rungate 0.8.13 → 0.8.16

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.
Files changed (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,423 @@
1
+ /**
2
+ * Work that exists on this machine and on no pushed ref.
3
+ *
4
+ * #1944. Every GitHub reading this repository takes — the board, the lane
5
+ * health, the stale sweep, `work-status` — answers "is somebody working on
6
+ * this" from things GitHub can see. A commit sitting in a worktree answers
7
+ * it too, and no query can reach one. The live instance, 2026-11-09:
8
+ * #1931's only work was commit `3bd05a14`, committed in `rg-wt-1931` and
9
+ * never pushed. Every reading reported the issue as claimed and idle. The
10
+ * work existed and nothing could see it.
11
+ *
12
+ * This module is the local half. It feeds `localCommits` to `workVerdict`
13
+ * in `lib/board-lane-health.ts`, which is the one place that decides the
14
+ * question — see #1972. `work-status` is the first caller able to read all
15
+ * three of its evidence fields, which is what makes its `PARKED` verdict
16
+ * reachable at all.
17
+ *
18
+ * ## A reading that could not be taken is `null`, never `false`
19
+ *
20
+ * The whole module is built around one asymmetry. "I looked and there are
21
+ * no local commits" releases somebody's claim. "I could not look" must
22
+ * not. A `git` that is absent, a directory that is not a repository, a
23
+ * command that failed — every one of those produces `unmeasured`, and
24
+ * `localCommitsFor` then returns `null` for every issue rather than
25
+ * `false` for all of them. Silent Default Substitution, in the direction
26
+ * that unassigns live work.
27
+ */
28
+
29
+ import { execFileSync } from "child_process";
30
+
31
+ /** One commit reachable from a local branch and from no remote-tracking ref. */
32
+ export interface UnpushedCommit {
33
+ readonly sha: string;
34
+ readonly branch: string;
35
+ }
36
+
37
+ export interface LocalWork {
38
+ /** Issue number → commits on a local branch and on no pushed ref. */
39
+ readonly byIssue: ReadonlyMap<number, number>;
40
+ /** The same tally before the branch names were resolved to issues. */
41
+ readonly byBranch: ReadonlyMap<string, number>;
42
+ /**
43
+ * Branches whose leading number is not an issue that exists.
44
+ *
45
+ * ai-review round 2 of #1974. `issueFromBranch` is a reading of a NAME,
46
+ * and a name is not a fact about the tracker: `release/2026-11-10-x`
47
+ * reads as 2026 and `2-factor-auth` as 2. This checkout already carries
48
+ * `rg/2620-tick`, and the highest issue in the repository is #1973.
49
+ *
50
+ * Reported rather than silently dropped. A commit on one of these is
51
+ * real local work that nothing will now attribute, and that is a thing
52
+ * somebody should see rather than a tidy empty result.
53
+ *
54
+ * Empty when the caller passed no issue list — see `tallyLocalWork`.
55
+ */
56
+ readonly unattributed: ReadonlyMap<string, number>;
57
+ /**
58
+ * Why the reading could not be taken, or `null` when it was taken.
59
+ *
60
+ * An empty `byIssue` with `unmeasured === null` means "looked, found
61
+ * nothing". An empty `byIssue` with a reason means "did not look". Those
62
+ * are different facts and only the first may release a claim.
63
+ */
64
+ readonly unmeasured: string | null;
65
+ }
66
+
67
+ /**
68
+ * The issue a branch is for, or `null` when the name does not say.
69
+ *
70
+ * Takes the FIRST number in the branch name after any prefix. This repo
71
+ * writes `rg/1944-local-work`, `fix/1087-adjudicated-notice` and
72
+ * `rungate/run-1931`, and it also writes `fix/640-644-run-branch-base`
73
+ * for a branch covering two issues — the first is the one the branch is
74
+ * named for, and attributing such a branch to both would let one commit
75
+ * count as work on an issue nobody has touched.
76
+ *
77
+ * A name with no number returns `null` rather than guessing. `main` and a
78
+ * personal scratch branch are not work on an issue.
79
+ *
80
+ * ## The number must OPEN the final segment, or follow `run-`
81
+ *
82
+ * The first cut took any digits preceded by `-` or `/`, and ai-review
83
+ * round 1 of #1974 found the shape that breaks: GitHub's web editor makes
84
+ * `username-patch-1`, which would have been attributed to issue #1.
85
+ *
86
+ * Checking the live refs turned that from a hypothetical into a count.
87
+ * This repository already carries `rg/adr-011-plan`, `rg/adr011-measure`
88
+ * and a dozen `rg/b2-*` branches — `adr-011-plan` would have been read as
89
+ * **issue #11**. A commit on somebody's ADR branch would have reported an
90
+ * unrelated issue as WORKING, which hides genuine neglect: exactly the
91
+ * direction this module is supposed to protect.
92
+ *
93
+ * So the rule is positional rather than a blocklist. Either the number
94
+ * opens the last `/`-separated segment (`rg/1944-x`, `fix/640-644-x`,
95
+ * `rg/1931`), or the segment is `run-<n>` (`rungate/run-1931`). Nothing
96
+ * else counts, and a shape nobody anticipated costs an unattributed
97
+ * commit rather than a wrong attribution — the direction a wrong answer
98
+ * is cheapest in.
99
+ */
100
+ export function issueFromBranch(branch: string): number | null {
101
+ const segment = branch.slice(branch.lastIndexOf("/") + 1);
102
+ const m = segment.match(/^(?:run-)?(\d{1,6})(?:-|$)/);
103
+ if (m === null) return null;
104
+ const n = Number(m[1]);
105
+ return Number.isInteger(n) && n > 0 ? n : null;
106
+ }
107
+
108
+ /**
109
+ * Parse `git log --branches --not --remotes --source --format=%H\t%S`.
110
+ *
111
+ * `--source` is what makes this one command rather than one per branch:
112
+ * `%S` prints the ref the commit was reached from, so attribution comes
113
+ * out of the same walk. There are 258 local branches in this checkout and
114
+ * a per-branch `rev-list` was the first cut.
115
+ *
116
+ * A malformed line is skipped rather than throwing. The caller's refusal
117
+ * is for a command that FAILED; a single unparseable row in a successful
118
+ * run is not evidence that the reading is untrustworthy, and throwing here
119
+ * would convert it into one.
120
+ */
121
+ export function parseUnpushed(stdout: string): UnpushedCommit[] {
122
+ const out: UnpushedCommit[] = [];
123
+ for (const line of stdout.split("\n")) {
124
+ const tab = line.indexOf("\t");
125
+ if (tab <= 0) continue;
126
+ const sha = line.slice(0, tab).trim();
127
+ const branch = line.slice(tab + 1).trim();
128
+ if (sha === "" || branch === "") continue;
129
+ out.push({ sha, branch });
130
+ }
131
+ return out;
132
+ }
133
+
134
+ /**
135
+ * Tally parsed commits by branch and by issue. Pure.
136
+ *
137
+ * `knownIssues` is the tracker's own answer to "is this a real issue", and
138
+ * when it is supplied a branch whose number is not in it lands in
139
+ * `unattributed` instead of `byIssue`. `issueFromBranch` can only read a
140
+ * NAME; whether that name corresponds to anything is a fact the caller
141
+ * holds and this module does not. ai-review round 2 of #1974, after
142
+ * `rg/2620-tick` was found live against a tracker whose highest issue is
143
+ * #1973.
144
+ *
145
+ * `null` keeps the name-only behaviour, for a caller with no issue list.
146
+ * That is looser and it is the caller's declaration that it has nothing
147
+ * better — not a default this module picks.
148
+ */
149
+ export function tallyLocalWork(
150
+ commits: readonly UnpushedCommit[],
151
+ unmeasured: string | null = null,
152
+ knownIssues: ReadonlySet<number> | null = null,
153
+ ): LocalWork {
154
+ const byBranch = new Map<string, number>();
155
+ const byIssue = new Map<number, number>();
156
+ const unattributed = new Map<string, number>();
157
+ for (const c of commits) {
158
+ byBranch.set(c.branch, (byBranch.get(c.branch) ?? 0) + 1);
159
+ const issue = issueFromBranch(c.branch);
160
+ if (issue === null) continue;
161
+ if (knownIssues !== null && !knownIssues.has(issue)) {
162
+ unattributed.set(c.branch, (unattributed.get(c.branch) ?? 0) + 1);
163
+ continue;
164
+ }
165
+ byIssue.set(issue, (byIssue.get(issue) ?? 0) + 1);
166
+ }
167
+ return { byBranch, byIssue, unattributed, unmeasured };
168
+ }
169
+
170
+ /**
171
+ * Does this issue have work on this machine that no pushed ref carries?
172
+ *
173
+ * `null` when the reading was not taken — see the module docblock. This is
174
+ * the function `scripts/work-status.ts` hands to `workVerdict`, and
175
+ * returning `false` from an unmeasured reading is the one defect this
176
+ * whole module exists to make impossible.
177
+ */
178
+ export function localCommitsFor(work: LocalWork, issue: number): boolean | null {
179
+ if (work.unmeasured !== null) return null;
180
+ return (work.byIssue.get(issue) ?? 0) > 0;
181
+ }
182
+
183
+ /**
184
+ * Issues with a branch pushed to `origin`.
185
+ *
186
+ * The second of `workVerdict`'s three fields, and the cheap one: a single
187
+ * `for-each-ref` over `refs/remotes/origin` (755 refs in this checkout,
188
+ * one command). A pushed branch is work somebody can see even with no
189
+ * pull request open, so it is WORKING rather than INVISIBLE.
190
+ */
191
+ export function issuesWithPushedBranch(
192
+ refs: readonly string[],
193
+ knownIssues: ReadonlySet<number> | null = null,
194
+ ): Set<number> {
195
+ const out = new Set<number>();
196
+ for (const ref of refs) {
197
+ // `origin/rg/1944-x` → strip the remote, then read the issue.
198
+ const branch = ref.startsWith("origin/") ? ref.slice("origin/".length) : ref;
199
+ if (branch === "HEAD") continue;
200
+ const issue = issueFromBranch(branch);
201
+ if (issue === null) continue;
202
+ // ai-review round 3 of #1974. Round 2 put this guard on
203
+ // `tallyLocalWork` and I did not sweep for the siblings — this
204
+ // function and `issuesWithUncommittedWork` kept crediting a number
205
+ // read from a name. `origin/2-factor-auth` made issue #2 read
206
+ // WORKING, which is the direction that hides neglect.
207
+ if (knownIssues !== null && !knownIssues.has(issue)) continue;
208
+ out.add(issue);
209
+ }
210
+ return out;
211
+ }
212
+
213
+ /**
214
+ * Worktrees holding changes nobody has committed.
215
+ *
216
+ * The title of #1944 says "unmerged **and uncommitted**", and this is the
217
+ * second half. An uncommitted change is even less visible than an unpushed
218
+ * commit: it is not in any ref, so a `git log` walk cannot reach it and
219
+ * losing the directory loses the work. `.claude/rules/parallel-sessions.md`
220
+ * records two sessions that lost in-flight work this way on 2026-10-16.
221
+ *
222
+ * Takes the per-worktree readings rather than running them, so the
223
+ * attribution is testable without a filesystem. A worktree whose status
224
+ * could not be read is carried as `dirty: null` and must not be reported
225
+ * as clean.
226
+ */
227
+ export interface WorktreeState {
228
+ readonly path: string;
229
+ readonly branch: string | null;
230
+ /** `null` is NOT READ, exactly as everywhere else in this module. */
231
+ readonly dirty: boolean | null;
232
+ }
233
+
234
+ export function issuesWithUncommittedWork(
235
+ states: readonly WorktreeState[],
236
+ knownIssues: ReadonlySet<number> | null = null,
237
+ ): {
238
+ readonly dirty: Map<number, string>;
239
+ readonly unread: string[];
240
+ } {
241
+ const dirty = new Map<number, string>();
242
+ const unread: string[] = [];
243
+ for (const s of states) {
244
+ if (s.dirty === null) {
245
+ unread.push(s.path);
246
+ continue;
247
+ }
248
+ if (!s.dirty || s.branch === null) continue;
249
+ const issue = issueFromBranch(s.branch);
250
+ if (issue === null) continue;
251
+ // The third attribution site, and the second one round 2 missed.
252
+ if (knownIssues !== null && !knownIssues.has(issue)) continue;
253
+ if (!dirty.has(issue)) dirty.set(issue, s.path);
254
+ }
255
+ return { dirty, unread };
256
+ }
257
+
258
+ /**
259
+ * Does an open pull request DECLARE it closes this issue?
260
+ *
261
+ * The third evidence field, and the only one read from GitHub rather than
262
+ * from the local disk — so it is the one that was shipped breaking this
263
+ * module's own rule. ai-review round 1 of #1974: the caller passed
264
+ * `declared.has(n)`, a plain boolean, even when a pull request's
265
+ * `closingIssuesReferences` page had been truncated.
266
+ *
267
+ * The asymmetry is the whole function:
268
+ *
269
+ * - **`true` survives truncation.** A pull request that did declare it
270
+ * closes this is a fact no cut-off page takes back.
271
+ * - **Absence does not.** An issue beyond the cut never reached the set,
272
+ * and `false` would feed `workVerdict` a reading nobody took — the
273
+ * issue could come back PARKED with a live pull request open on it.
274
+ *
275
+ * It lives here rather than inline in the script so there is one place to
276
+ * mutate and a behavioural case can observe it. A ternary in a top-level
277
+ * script that performs network calls on import is reachable only by
278
+ * reading the source.
279
+ */
280
+ /**
281
+ * The issues a pull request declares it closes **in one repository**.
282
+ *
283
+ * ai-review round 5 of #1974. `closingIssuesReferences` resolves GitHub's
284
+ * closing keywords, and those match across repositories: `Fixes
285
+ * other-org/other-repo#1944` produces a node numbered 1944 that has
286
+ * nothing to do with this tracker. Taking `.number` alone made a pull
287
+ * request here mark the local #1944 WORKING on the strength of somebody
288
+ * else's issue.
289
+ *
290
+ * Checked against the live tracker before fixing: of the open pull
291
+ * requests today exactly one declares a closing reference and it is
292
+ * same-repo, so this is a real mechanism that is not currently firing —
293
+ * worth saying, because "found a bug" and "found a bug that is happening"
294
+ * are different claims.
295
+ *
296
+ * Same shape as the `knownIssues` guard above, one level out: a number is
297
+ * not an identity until something says which tracker it belongs to.
298
+ */
299
+ export function declaredClosingIn(
300
+ nodes: readonly { readonly number: number; readonly repository?: { readonly nameWithOwner?: string } }[],
301
+ repoNameWithOwner: string,
302
+ ): number[] {
303
+ return nodes
304
+ .filter(n => n.repository?.nameWithOwner === repoNameWithOwner)
305
+ .map(n => n.number);
306
+ }
307
+
308
+ export function openPullRequestReading(
309
+ declared: ReadonlySet<number>,
310
+ truncatedPRs: readonly number[],
311
+ issue: number,
312
+ ): boolean | null {
313
+ if (declared.has(issue)) return true;
314
+ return truncatedPRs.length > 0 ? null : false;
315
+ }
316
+
317
+ /** Exposed so a test can drive the parse without spawning git. */
318
+ export const UNPUSHED_ARGS: readonly string[] = [
319
+ "log",
320
+ "--branches",
321
+ "--not",
322
+ "--remotes",
323
+ "--source",
324
+ "--format=%H%x09%S",
325
+ ];
326
+
327
+ /**
328
+ * Run the reading against a checkout.
329
+ *
330
+ * Every failure path lands in `unmeasured` with the reason, and none of
331
+ * them produces an empty-but-measured result. `execFileSync` throws on a
332
+ * non-zero exit, on a missing binary, and on a directory that is not a
333
+ * repository, and all three mean the same thing here: nobody looked.
334
+ */
335
+ export function readLocalWork(
336
+ repoRoot: string,
337
+ knownIssues: ReadonlySet<number> | null = null,
338
+ ): LocalWork {
339
+ let stdout: string;
340
+ try {
341
+ stdout = execFileSync("git", ["-C", repoRoot, ...UNPUSHED_ARGS], {
342
+ encoding: "utf-8",
343
+ maxBuffer: 32 * 1024 * 1024,
344
+ });
345
+ } catch (err) {
346
+ const why = err instanceof Error ? err.message.split("\n")[0] : String(err);
347
+ return tallyLocalWork(
348
+ [],
349
+ `UNMEASURED — the local commit walk did not run in ${repoRoot}: ${why}. ` +
350
+ `No issue can be reported as having no local work on the strength of this`,
351
+ );
352
+ }
353
+ return tallyLocalWork(parseUnpushed(stdout), null, knownIssues);
354
+ }
355
+
356
+ /** One `for-each-ref`. Returns `null` when it could not be run. */
357
+ export function readPushedBranches(
358
+ repoRoot: string,
359
+ knownIssues: ReadonlySet<number> | null = null,
360
+ ): Set<number> | null {
361
+ try {
362
+ const out = execFileSync(
363
+ "git",
364
+ ["-C", repoRoot, "for-each-ref", "--format=%(refname:short)", "refs/remotes/origin"],
365
+ { encoding: "utf-8", maxBuffer: 32 * 1024 * 1024 },
366
+ );
367
+ return issuesWithPushedBranch(
368
+ out.split("\n").filter(l => l.trim() !== ""),
369
+ knownIssues,
370
+ );
371
+ } catch {
372
+ return null;
373
+ }
374
+ }
375
+
376
+ /**
377
+ * `git worktree list --porcelain`, then one `status --porcelain` each.
378
+ *
379
+ * 28 worktrees in this checkout, so this is 29 local commands rather than
380
+ * the 258 a per-branch walk would cost. A status that throws is carried as
381
+ * `dirty: null` — the worktree directory may have been deleted out from
382
+ * under its registration, and "I could not look" is not "it is clean".
383
+ */
384
+ export function readWorktreeStates(repoRoot: string): WorktreeState[] | null {
385
+ let listing: string;
386
+ try {
387
+ listing = execFileSync("git", ["-C", repoRoot, "worktree", "list", "--porcelain"], {
388
+ encoding: "utf-8",
389
+ maxBuffer: 32 * 1024 * 1024,
390
+ });
391
+ } catch {
392
+ return null;
393
+ }
394
+ const states: WorktreeState[] = [];
395
+ let path: string | null = null;
396
+ let branch: string | null = null;
397
+ const flush = () => {
398
+ if (path === null) return;
399
+ let dirty: boolean | null;
400
+ try {
401
+ const st = execFileSync("git", ["-C", path, "status", "--porcelain"], {
402
+ encoding: "utf-8",
403
+ maxBuffer: 32 * 1024 * 1024,
404
+ });
405
+ dirty = st.trim() !== "";
406
+ } catch {
407
+ dirty = null;
408
+ }
409
+ states.push({ path, branch, dirty });
410
+ path = null;
411
+ branch = null;
412
+ };
413
+ for (const line of listing.split("\n")) {
414
+ if (line.startsWith("worktree ")) {
415
+ flush();
416
+ path = line.slice("worktree ".length).trim();
417
+ } else if (line.startsWith("branch ")) {
418
+ branch = line.slice("branch ".length).trim().replace(/^refs\/heads\//, "");
419
+ }
420
+ }
421
+ flush();
422
+ return states;
423
+ }
@@ -0,0 +1,134 @@
1
+ /**
2
+ * Is this line inside a fenced code block? The one answer for lib/. #2130.
3
+ *
4
+ * ## Why one module
5
+ *
6
+ * Seven readers in lib/ answered this four different ways. One closed a ```
7
+ * block on a `~~~` line. One let a ```` block close on its first ``` content
8
+ * line. One missed a longer close, so its block ran on. The cost each time
9
+ * was the same: a `# heading`, a path or a `Fixes #N` written inside an
10
+ * example was read as real. Found in review round 2 of #2127, where
11
+ * `finding-promotion` read a fenced heading and misplaced a criterion.
12
+ *
13
+ * Seven deciders of one grammar is the "two deciders that agree" shape in
14
+ * `.claude/rules/checks-must-be-able-to-fail.md`, and a behavioural suite
15
+ * only catches the last one to regress. So `test/markdown-fence.test.ts`
16
+ * holds a census that fails on any other lib/ file spelling a fence regex.
17
+ *
18
+ * ## The grammar, CommonMark's
19
+ *
20
+ * - A fence opens on a run of three or more backticks, or three or more
21
+ * tildes. What follows the run is the info string.
22
+ * - It closes only on a run of the SAME character, at least as long, with
23
+ * nothing after it but whitespace. A ``` line inside a `~~~` block is
24
+ * content; so is ```` ```js ```` inside a ```` ```md ```` block.
25
+ * - An unclosed fence runs to the end of the text, which is how a renderer
26
+ * shows it, and `readFences` says where it opened so a caller can refuse
27
+ * rather than silently treat the rest as code.
28
+ *
29
+ * ## Two deliberate departures, both inherited from every reader before this
30
+ *
31
+ * - **Any indentation opens.** CommonMark allows three spaces, but a fence
32
+ * inside a list item is indented by the item's content offset, and a line
33
+ * reader cannot see list containers. Every site but one read any
34
+ * indentation already. `lib/filing-plan.ts` applies the three-space limit
35
+ * itself, because it also handles indented code blocks.
36
+ * - **A backtick info string may contain backticks.** CommonMark would not
37
+ * open on ```` ```a`b ````. Every reader here did, and `lib/filing-plan.ts`
38
+ * relies on it to resolve an ambiguous line toward NOT authorising.
39
+ */
40
+
41
+ export type FenceChar = "`" | "~";
42
+
43
+ /** A line that opens a fence: its marker, the info string after it, and its indentation. */
44
+ export interface FenceOpening {
45
+ readonly char: FenceChar;
46
+ readonly length: number;
47
+ /** Everything after the marker run, untrimmed. */
48
+ readonly info: string;
49
+ /** Spaces and tabs before the marker run. */
50
+ readonly indent: number;
51
+ }
52
+
53
+ /** The one spelling of a fence marker line in lib/. */
54
+ const MARKER_LINE = /^([ \t]*)(`{3,}|~{3,})(.*)$/;
55
+
56
+ /** The fence `line` would open, or `null` when it is not a fence line. */
57
+ export function fenceOpening(line: string): FenceOpening | null {
58
+ const m = MARKER_LINE.exec(line);
59
+ if (m === null) return null;
60
+ return { char: m[2]![0] as FenceChar, length: m[2]!.length, info: m[3]!, indent: m[1]!.length };
61
+ }
62
+
63
+ /** Whether `line` closes the fence `open` opened: same character, at least as long, nothing after. */
64
+ export function closesFence(line: string, open: FenceOpening): boolean {
65
+ const m = fenceOpening(line);
66
+ return m !== null && m.char === open.char && m.length >= open.length && m.info.trim() === "";
67
+ }
68
+
69
+ /** `fence` is an opening or closing marker line; `code` is a line between them. */
70
+ export type LineRole = "prose" | "fence" | "code";
71
+
72
+ export interface FenceReading {
73
+ /** One role per input line. */
74
+ readonly roles: readonly LineRole[];
75
+ /** The index of the line that opened a fence nothing closed, or `null`. */
76
+ readonly unclosedAt: number | null;
77
+ }
78
+
79
+ /** Every line's role. An unclosed fence marks the rest `code` and is reported by `unclosedAt`. */
80
+ export function readFences(lines: readonly string[]): FenceReading {
81
+ const roles: LineRole[] = [];
82
+ let open: FenceOpening | null = null;
83
+ let openedAt: number | null = null;
84
+ for (let i = 0; i < lines.length; i++) {
85
+ const line = lines[i]!;
86
+ if (open === null) {
87
+ open = fenceOpening(line);
88
+ if (open === null) {
89
+ roles.push("prose");
90
+ continue;
91
+ }
92
+ openedAt = i;
93
+ roles.push("fence");
94
+ continue;
95
+ }
96
+ if (closesFence(line, open)) {
97
+ open = null;
98
+ openedAt = null;
99
+ roles.push("fence");
100
+ continue;
101
+ }
102
+ roles.push("code");
103
+ }
104
+ return { roles, unclosedAt: openedAt };
105
+ }
106
+
107
+ /**
108
+ * Each fenced block's character range in `text`, from the start of its
109
+ * opening line to the end of its closing line — or to the end of the text,
110
+ * for an unclosed one. For a caller that masks by offset rather than by line.
111
+ */
112
+ export function fencedBlocks(text: string): { start: number; end: number }[] {
113
+ const lines = text.split("\n");
114
+ const { roles } = readFences(lines);
115
+ const out: { start: number; end: number }[] = [];
116
+ let offset = 0;
117
+ let current: { start: number; end: number } | null = null;
118
+ for (let i = 0; i < lines.length; i++) {
119
+ const end = offset + lines[i]!.length;
120
+ const opening = roles[i] === "fence" && (i === 0 || roles[i - 1] === "prose" || current === null);
121
+ if (roles[i] === "prose") {
122
+ current = null;
123
+ } else if (opening) {
124
+ current = { start: offset, end };
125
+ out.push(current);
126
+ } else {
127
+ current!.end = end;
128
+ // A closing marker ends the block, so the next marker line opens another.
129
+ if (roles[i] === "fence") current = null;
130
+ }
131
+ offset = end + 1;
132
+ }
133
+ return out;
134
+ }
@@ -0,0 +1,46 @@
1
+ /**
2
+ * #2057: the one reader of a milestone title's family and phase.
3
+ *
4
+ * `Pipeline Phase 6 — the board's state is a reading` is family `Pipeline`,
5
+ * phase 6. A bare `Phase 2 — x` is family `""`. Anything else is not a phase
6
+ * milestone, and is `null`, never a guess.
7
+ *
8
+ * Four regexes used to read this grammar: `phaseOf` (lib/board-mirror.ts),
9
+ * `phaseInFamily` and `familyOf` (lib/spec-placement.ts), and one in
10
+ * `scripts/status-view.ts`. They disagreed at least four times, each patched
11
+ * one title shape at a time: a double space (round 2 of #1705), a
12
+ * parenthetical `Release (Phase 3)`, a mid-title prefix, and a title saying
13
+ * "Phase" twice (review of #2055). They now all read through this file, and
14
+ * `test/milestone-title.test.ts` holds the census that keeps the phase token
15
+ * spelled here alone.
16
+ */
17
+
18
+ /**
19
+ * `Phase <number>`, captured: the token every phase grammar in this
20
+ * repository is built from — a milestone title here, a placement-table cell
21
+ * and a spec heading in `lib/spec-placement.ts`. Spelled once, so the
22
+ * grammars cannot disagree about what a phase number is.
23
+ */
24
+ export const PHASE_TOKEN = String.raw`Phase (\d+)`;
25
+
26
+ /**
27
+ * The family is everything before the FIRST `Phase N`, lazily, so a title
28
+ * that says "Phase" again later (`… starts after Phase 5 ships`) keeps the
29
+ * family it opened with. Whitespace must separate them — any run of it, and
30
+ * the family is trimmed, so `Pipeline Phase 6` is family `Pipeline` rather
31
+ * than `Pipeline ` (AI review of #2121: the trailing space made phaseOf and
32
+ * inMilestoneFamily disagree). A word ending in `Phase` (`TestPhase 3`) and a
33
+ * parenthetical (`Release (Phase 3)`) are not phase milestones.
34
+ */
35
+ const MILESTONE_TITLE = new RegExp(String.raw`^(?:(.*?)\s+)?${PHASE_TOKEN}\b`);
36
+
37
+ export interface MilestoneTitle {
38
+ /** `Pipeline`, or `""` for a bare `Phase N` title. */
39
+ readonly family: string;
40
+ readonly phase: number;
41
+ }
42
+
43
+ export function readMilestoneTitle(title: string | null | undefined): MilestoneTitle | null {
44
+ const m = MILESTONE_TITLE.exec(title ?? "");
45
+ return m ? { family: (m[1] ?? "").trim(), phase: Number(m[2]) } : null;
46
+ }