rungate 0.5.0 → 0.7.0

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 (142) hide show
  1. package/lib/affected-tests.ts +398 -0
  2. package/lib/agent-audit.ts +2 -3
  3. package/lib/agent-worktree.ts +287 -0
  4. package/lib/agents-md-sections.ts +209 -0
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-diff.ts +139 -0
  7. package/lib/branch-protection.ts +790 -0
  8. package/lib/brief-ac-alignment.ts +104 -0
  9. package/lib/brief-references.ts +205 -0
  10. package/lib/bun-version.ts +347 -0
  11. package/lib/check-remedy.ts +140 -0
  12. package/lib/ci-checkout.ts +18 -1
  13. package/lib/ci-history-depth.ts +159 -0
  14. package/lib/ci-setup-step.ts +96 -0
  15. package/lib/claude-code-action.ts +85 -0
  16. package/lib/claude-tool-vocabulary.ts +188 -0
  17. package/lib/cli-commands.ts +15 -0
  18. package/lib/commit-sha.ts +42 -0
  19. package/lib/commit-subject.ts +90 -0
  20. package/lib/compliance-report.ts +377 -45
  21. package/lib/compliance.ts +196 -20
  22. package/lib/config-loader.ts +51 -1
  23. package/lib/config-trackable.ts +391 -0
  24. package/lib/conformity.ts +1272 -189
  25. package/lib/containment.ts +238 -0
  26. package/lib/content-hash.ts +24 -0
  27. package/lib/context-docs.ts +143 -28
  28. package/lib/create-brief.ts +2 -1
  29. package/lib/create-sc.ts +323 -4
  30. package/lib/dev-liveness.ts +180 -0
  31. package/lib/discovery-branch-points.ts +432 -0
  32. package/lib/discovery-stability.ts +481 -0
  33. package/lib/distribution-currency.ts +186 -0
  34. package/lib/doc-routing.ts +157 -0
  35. package/lib/doc-scan-targets.ts +9 -0
  36. package/lib/evidence-command-transport.ts +160 -0
  37. package/lib/evidence-prevalidator.ts +246 -2
  38. package/lib/evidence-satisfiability.ts +534 -12
  39. package/lib/failure-intake.ts +317 -0
  40. package/lib/fallow-availability.ts +286 -0
  41. package/lib/fs-write-capabilities.ts +232 -0
  42. package/lib/gate-refusal-currency.ts +112 -0
  43. package/lib/gate-run-split.ts +147 -0
  44. package/lib/gate-timeouts.ts +82 -0
  45. package/lib/generators/agent-briefs.ts +4 -1
  46. package/lib/generators/agents-md.ts +204 -48
  47. package/lib/generators/code-map.ts +2 -1
  48. package/lib/generators/types.ts +8 -0
  49. package/lib/git-dates.ts +55 -0
  50. package/lib/git-isolation.ts +140 -0
  51. package/lib/github.ts +15 -0
  52. package/lib/google-auth-action.ts +93 -0
  53. package/lib/harness-project.ts +48 -0
  54. package/lib/harness-provenance.ts +255 -0
  55. package/lib/hook-evidence.ts +235 -0
  56. package/lib/hook-scopes.ts +386 -0
  57. package/lib/hook-target-tree.ts +398 -0
  58. package/lib/hook-trees.ts +447 -0
  59. package/lib/js-top-level-code.ts +78 -10
  60. package/lib/junit-checks.ts +536 -0
  61. package/lib/launch-base.ts +253 -0
  62. package/lib/line-citation.ts +372 -0
  63. package/lib/local-calendar-day.ts +78 -0
  64. package/lib/orphan-reaper.ts +468 -0
  65. package/lib/parity-binding.ts +205 -0
  66. package/lib/per-test-timeouts.ts +219 -0
  67. package/lib/plan-coverage.ts +151 -0
  68. package/lib/prior-branch.ts +201 -8
  69. package/lib/process-table.ts +146 -0
  70. package/lib/project-state-derivation.ts +219 -0
  71. package/lib/project-state-root.ts +258 -0
  72. package/lib/project-state-shape.ts +59 -0
  73. package/lib/promote-outputs.ts +6 -2
  74. package/lib/published-artifact.ts +525 -0
  75. package/lib/readdir-sorted.ts +45 -0
  76. package/lib/report-provenance.ts +156 -0
  77. package/lib/review-execution-reading.ts +206 -0
  78. package/lib/review-tool-agreement.ts +433 -0
  79. package/lib/rule-promotion.ts +234 -0
  80. package/lib/rule-retirement.ts +525 -0
  81. package/lib/run-branch.ts +612 -0
  82. package/lib/rungate-schema.ts +19 -0
  83. package/lib/runner-home.ts +274 -0
  84. package/lib/sc-claim-forms.ts +75 -0
  85. package/lib/sc-id-cross-tree.ts +323 -0
  86. package/lib/sc-ids.ts +121 -13
  87. package/lib/sc-reservations.ts +289 -0
  88. package/lib/scaffold/ai-review-findings.ts +403 -0
  89. package/lib/scaffold/ai-review-step.ts +4777 -0
  90. package/lib/scaffold/managed-workflow.ts +587 -192
  91. package/lib/scaffold/owned-files.ts +186 -39
  92. package/lib/scaffold/pre-push-hook.ts +49 -5
  93. package/lib/scaffold/rehearsal.ts +205 -71
  94. package/lib/scaffold/steps.ts +1517 -293
  95. package/lib/scaffold/workflow-census.ts +217 -0
  96. package/lib/scaffold/workflow-drift.ts +217 -0
  97. package/lib/scaffold/write-steps.ts +10 -4
  98. package/lib/scan-budget.ts +247 -0
  99. package/lib/scanner.ts +80 -62
  100. package/lib/scratch-roots.ts +50 -5
  101. package/lib/screenshot-discovery.ts +121 -0
  102. package/lib/screenshot-upload.ts +41 -1
  103. package/lib/secret-patterns.ts +511 -8
  104. package/lib/ship-mode.ts +219 -0
  105. package/lib/source-slice.ts +294 -0
  106. package/lib/spec-listing.ts +148 -0
  107. package/lib/spec-requirements.ts +209 -0
  108. package/lib/stale-cleanup.ts +37 -3
  109. package/lib/suite-flake.ts +278 -0
  110. package/lib/suite-measurement.ts +23 -4
  111. package/lib/suite-run-reading.ts +411 -1
  112. package/lib/suite-timeout-margin.ts +193 -0
  113. package/lib/test-case-bodies.ts +883 -0
  114. package/lib/test-case-deletion.ts +653 -0
  115. package/lib/test-census.ts +97 -29
  116. package/lib/test-command-positions.ts +274 -0
  117. package/lib/test-command.ts +133 -0
  118. package/lib/test-suite-lock.ts +325 -26
  119. package/lib/tool-probe.ts +142 -0
  120. package/lib/top-level-cd.ts +393 -0
  121. package/lib/tracked-vs-ignored.ts +234 -0
  122. package/lib/tree-entries.ts +89 -0
  123. package/lib/ts-ast.ts +200 -0
  124. package/lib/validators/spec-validators.ts +3 -2
  125. package/lib/walk-test-files.ts +97 -0
  126. package/lib/workflow-actions.ts +263 -0
  127. package/lib/worktree-collect.ts +177 -5
  128. package/lib/worktree-repo.ts +36 -1
  129. package/package.json +2 -1
  130. package/scripts/ai-review-findings.ts +45 -0
  131. package/scripts/audit-specs.ts +247 -12
  132. package/scripts/audit-transcript.ts +2 -1
  133. package/scripts/convert-spec.ts +2 -1
  134. package/scripts/create-sc.ts +37 -7
  135. package/scripts/create-spec.ts +2 -1
  136. package/scripts/create-success.ts +2 -1
  137. package/scripts/extract-constraints.ts +197 -26
  138. package/scripts/generate-code-map.ts +62 -28
  139. package/scripts/scaffold-project.ts +12 -2
  140. package/scripts/split-spec.ts +2 -1
  141. package/scripts/sync-sc-status.ts +127 -14
  142. package/scripts/sync-spec-tests.ts +2 -1
@@ -94,12 +94,32 @@ export interface DetectExistingPROptions {
94
94
  * Does this text reference issue N? One binding, used by both detectors
95
95
  * and by anything that reads a PR body (#223).
96
96
  *
97
- * The bound is on DIGITS, not on a `#`: the three places this has to match
98
- * spell the reference three ways — `Closes #209` in a PR body, `fix(#209):`
99
- * in the subject ship.js writes, and `209-deep-modules` in a branch name.
100
- * The digit bound is what stops `515` matching `5150`, and it is the whole
101
- * of the correctness condition; the `#` is decoration that two of the three
102
- * forms do not have.
97
+ * ## This is the IDENTIFIER form. Prose has its own binding below.
98
+ *
99
+ * The bound is on DIGITS and not on a `#`, which is right for the thing this
100
+ * now reads and ONLY that thing: a branch name. `209-deep-modules` carries no
101
+ * `#` and never will, because a ref is a structured identifier whose whole
102
+ * content is chosen to name the work. The digit bound is what stops `515`
103
+ * matching `5150`.
104
+ *
105
+ * It used to read PR titles and bodies too, and that was wrong in a way no
106
+ * amount of tightening the digit bound could reach (#687). A body is FREE
107
+ * TEXT. Ship run `wf_4b5a4d83-fa4` for issue #631 refused with
108
+ * `PRIOR_WORK_OPEN_PR — Issue #631 already has open PR #686`; PR #686 is
109
+ * #644's work, and what matched was line 42 of its body:
110
+ *
111
+ * and projectRoot is on rungate/run-631 ...
112
+ *
113
+ * a sample refusal message quoted as evidence. So a PR that merely MENTIONS
114
+ * another issue's branch name became that issue's prior work, and that issue
115
+ * could not be shipped until the PR closed. Not rare prose — this repository
116
+ * writes cross-session handoff notes, quoted refusals and "adjacent to #631"
117
+ * paragraphs into PR bodies deliberately.
118
+ *
119
+ * `detectExistingPR`'s own comment names the hazard two lines above the call:
120
+ * matching `pr.number` "is a false positive on the one path where a false
121
+ * positive stops a correct run from ever starting". That is exactly what a
122
+ * bare-number body reading is, and it sat beneath that sentence.
103
123
  *
104
124
  * Total over non-strings. It runs over `pr.body`, which GitHub returns as
105
125
  * `null` for a PR opened with an empty body, and a throw on that path is a
@@ -147,6 +167,147 @@ export function issueReference(issueNumber: number): (text: unknown) => boolean
147
167
  return (text: unknown) => typeof text === 'string' && pattern.test(text)
148
168
  }
149
169
 
170
+ /**
171
+ * Does this PROSE reference issue N? The second binding, and the narrow one.
172
+ *
173
+ * A PR title, a PR body and a commit subject are sentences people write. A
174
+ * bare number in one of them is a number, not a claim — it is a line count, a
175
+ * SHA prefix, a quoted branch name, a port. What makes it a REFERENCE is the
176
+ * `#`, and every form this repository actually produces in prose has one:
177
+ * `Closes #209` and `Fixes #209`, which ship.js writes into every body it
178
+ * opens, and `fix(#209):`, which it writes into every subject it commits.
179
+ *
180
+ * So the `#` is not decoration here. It is the entire difference between the
181
+ * two populations, and requiring it loses nothing: a PR with no `#` reference
182
+ * anywhere in its prose is still found through its HEAD REF by
183
+ * `issueReference` above, which is the identifier reading and keeps its bare
184
+ * number. Two readings, two bounds, named separately — because the fields
185
+ * have different grammars and one pattern over all three cannot be right for
186
+ * all three.
187
+ *
188
+ * `#209\b` rejects `rungate/run-631` for 631 (no `#`), rejects `#2091` (`1`
189
+ * is a word character, so there is no boundary) and rejects `#1209` (the
190
+ * character before `209` is `1`, not `#`). All asserted in
191
+ * `test/prior-branch-reference.test.ts` rather than trusted to this comment.
192
+ *
193
+ * Total over non-strings, for the same reason as above: GitHub returns `null`
194
+ * for the body of a PR opened without one.
195
+ */
196
+ export function issueProseReference(issueNumber: number): (text: unknown) => boolean {
197
+ if (!Number.isSafeInteger(issueNumber) || issueNumber < 0) {
198
+ throw new TypeError(
199
+ `issueProseReference needs a non-negative integer issue number, got ${JSON.stringify(issueNumber)}`,
200
+ )
201
+ }
202
+ const pattern = new RegExp(`#${issueNumber}\\b`)
203
+ return (text: unknown) => typeof text === 'string' && pattern.test(text)
204
+ }
205
+
206
+ /**
207
+ * Does this PR BODY declare that it closes issue N? The third binding, and
208
+ * the narrowest (#887).
209
+ *
210
+ * `issueProseReference` above requires a `#`, which is the right bound for a
211
+ * COMMIT SUBJECT and far too wide for a PR body. Citing another issue in a
212
+ * body is not an edge case in these repositories, it is the house style:
213
+ * measured over this repository's 120 most recent PRs, 103 of them cite
214
+ * issues they do not close, 417 citations in all. Treating any of those as
215
+ * prior work stops a correct run from ever starting, and it fires late --
216
+ * A consumer run for issue #1624 refused after 9 agents, 716k tokens and
217
+ * naming a PR with zero file overlap.
218
+ *
219
+ * The signal that separates the populations already exists and the harness
220
+ * already writes it: `Fixes #${ISSUE}`, which ship.js puts in every body it
221
+ * opens, and which is also what GitHub itself reads to link a PR to an issue.
222
+ *
223
+ * Two deliberate choices, both of which cost something if taken the other
224
+ * way:
225
+ *
226
+ * - **Every GitHub variant, case-insensitively.** `close`/`closes`/`closed`,
227
+ * `fix`/`fixes`/`fixed`, `resolve`/`resolves`/`resolved`. Matching only
228
+ * ship.js's own spelling would stop detecting hand-written PRs, and the
229
+ * issue would go back to being shipped twice -- #209, the defect this
230
+ * module exists to prevent.
231
+ * - **A backtick does not disarm it.** GitHub closes `#N` from a quoted
232
+ * `` `Fixes #N` `` in a body, so a detector that skipped code spans would
233
+ * disagree with GitHub about which PR closes what. Match the same text
234
+ * GitHub does, including the false positive GitHub itself has.
235
+ *
236
+ * There is deliberately NO fallback to the bare reading when no closing
237
+ * keyword is found. A fallback would reintroduce #887 exactly; "no closing
238
+ * keyword in any open body" reads as no prior work, which is the true answer
239
+ * for #1624 today. A PR whose body says nothing is still found through its
240
+ * head ref and its subject.
241
+ *
242
+ * Total over non-strings: GitHub returns `null` for a body opened without one.
243
+ */
244
+ export function issueClosingReference(issueNumber: number): (text: unknown) => boolean {
245
+ if (!Number.isSafeInteger(issueNumber) || issueNumber < 0) {
246
+ throw new TypeError(
247
+ `issueClosingReference needs a non-negative integer issue number, got ${JSON.stringify(issueNumber)}`,
248
+ )
249
+ }
250
+ // The forms GitHub itself honours, not just the one ship.js writes. A
251
+ // detector NARROWER than GitHub's grammar fails in the dangerous
252
+ // direction: a PR saying `Fixes: #209` or `Closes GH-209` really does
253
+ // close the issue, this would not see it, and the issue gets shipped
254
+ // twice -- #209, which is the defect the module exists to prevent. Found
255
+ // by security review of the first draft, which required a bare `#`.
256
+ //
257
+ // keyword, optional colon, whitespace, then one of:
258
+ // #209 GH-209 https://github.com/<owner>/<repo>/issues/209
259
+ const ref = `(?:#|GH-|https?://github\\.com/[^/\\s]+/[^/\\s]+/issues/)${issueNumber}`
260
+ const pattern = new RegExp(
261
+ `\\b(?:close[sd]?|fix(?:e[sd])?|resolve[sd]?)\\s*:?\\s+${ref}\\b`,
262
+ 'i',
263
+ )
264
+ return (text: unknown) => typeof text === 'string' && pattern.test(text)
265
+ }
266
+
267
+ /**
268
+ * Does this PR TITLE name issue N as its SUBJECT? The fourth binding (#887).
269
+ *
270
+ * A title is one sentence, so the body's problem is smaller here but it is
271
+ * the same problem: measured over this repository's 120 most recent PRs, 107
272
+ * titles carry a `#N` and 6 carry more than one -- `docs(#837): record the
273
+ * #836 battery` is #837's PR, and under a whole-title reading it was also
274
+ * #836's.
275
+ *
276
+ * What separates them is POSITION, not spelling. The conventional-commit
277
+ * subject -- everything before the first colon -- is where this repository
278
+ * writes the issue a change is FOR, every time: `fix(#209):`, `#795:`,
279
+ * `#640 + #644:`. A number after the colon is prose.
280
+ *
281
+ * A title with no colon in its first 40 characters declares no subject issue
282
+ * and matches nothing. That is deliberately not a fallback to the whole
283
+ * string: a fallback is how the body reading got as wide as it did, and the
284
+ * honest answer for a title that does not name an issue in its subject is
285
+ * that it does not say. The PR is still found by head ref or by body.
286
+ */
287
+ export function issueSubjectReference(issueNumber: number): (text: unknown) => boolean {
288
+ if (!Number.isSafeInteger(issueNumber) || issueNumber < 0) {
289
+ throw new TypeError(
290
+ `issueSubjectReference needs a non-negative integer issue number, got ${JSON.stringify(issueNumber)}`,
291
+ )
292
+ }
293
+ const pattern = new RegExp(`#${issueNumber}\\b`)
294
+ return (text: unknown) => {
295
+ if (typeof text !== 'string') return false
296
+ const colon = text.indexOf(':')
297
+ if (colon < 0 || colon > SUBJECT_PREFIX_LIMIT) return false
298
+ return pattern.test(text.slice(0, colon))
299
+ }
300
+ }
301
+
302
+ /**
303
+ * How far into a title the conventional-commit colon may sit (#887).
304
+ *
305
+ * Long enough for `docs(#837)` and `#640 + #644`, short enough that a colon
306
+ * in an ordinary sentence -- "the reading says: nothing" -- does not turn the
307
+ * first half of a prose title into a subject.
308
+ */
309
+ const SUBJECT_PREFIX_LIMIT = 40
310
+
150
311
  function git(args: string[], cwd: string, timeout = 15_000) {
151
312
  return spawnSync('git', args, { cwd, encoding: 'utf-8', timeout })
152
313
  }
@@ -332,9 +493,13 @@ export async function detectPriorBranch(opts: DetectOptions): Promise<PriorBranc
332
493
  // becomes findable. Scratch refs are still excluded upstream by
333
494
  // `isHarnessScratchRef`: a subject match widens which REAL branches are
334
495
  // found, it does not readmit the ones #185 ruled out.
496
+ // Two readings, because a ref and a subject have different grammars. The
497
+ // ref is an identifier and carries the bare number; the subject is a
498
+ // sentence and must carry `#` (#687).
335
499
  const refs = issueReference(issueNumber)
500
+ const prose = issueProseReference(issueNumber)
336
501
  const matches = listCandidateRefs(projectRoot)
337
- .filter(c => refs(c.branch) || refs(c.subject))
502
+ .filter(c => refs(c.branch) || prose(c.subject))
338
503
  if (matches.length === 0) return null
339
504
 
340
505
  // Most recent wins; a local head breaks a tie with its origin twin.
@@ -400,6 +565,23 @@ const PR_PAGE_SIZE = 100
400
565
  * says which issue the PR is for. A head-ref-only reading could not match the
401
566
  * PRs this workflow opens.
402
567
  *
568
+ * Three fields, three grammars, three readings — see `issueReference`,
569
+ * `issueSubjectReference` and `issueClosingReference`. One pattern over all
570
+ * three has now been wrong twice:
571
+ *
572
+ * - **#687**: a bare-number reading matched `rungate/run-631` quoted as
573
+ * evidence in a body, and issue 631's run refused. Fixed by requiring `#`.
574
+ * - **#887**: `#N` is still what a CITATION looks like. A consumer run for
575
+ * issue #1624 refused after 9 agents, 716k tokens and 26 minutes, naming a PR
576
+ * with zero file overlap that mentioned it in two sentences of prose —
577
+ * and three other open PRs cited it too, so removing one would have handed
578
+ * the refusal to the next. The body must now DECLARE that it closes the
579
+ * issue, and the title is read at its subject rather than whole.
580
+ *
581
+ * Both narrowings cost nothing in recall because the three readings are a
582
+ * disjunction over fields that rarely all stay silent: measured over this
583
+ * repository's 120 most recent PRs, the new rule loses no true pair.
584
+ *
403
585
  * Returns `null` for "no open PR", a PR for "this one", and `{unreadable}`
404
586
  * for "could not look". Never conflate the first and the last.
405
587
  */
@@ -423,10 +605,21 @@ export async function detectExistingPR(opts: DetectExistingPROptions | DetectExi
423
605
  // matching it made PR #209 the prior work for issue #209 whatever it was
424
606
  // about, which is a false positive on the one path where a false positive
425
607
  // stops a correct run from ever starting.
608
+ // THREE readings, because the three fields have three grammars and one
609
+ // pattern over all of them has now been wrong twice (#687, #887).
426
610
  const refs = issueReference(issueNumber)
611
+ const subject = issueSubjectReference(issueNumber)
612
+ const closes = issueClosingReference(issueNumber)
427
613
  const match = prs.find((pr: any) => {
428
614
  const headRef = pr?.head?.ref || pr?.headRefName || ''
429
- return refs(headRef) || refs(pr?.title) || refs(pr?.body)
615
+ // - the HEAD REF is an identifier: bare number, unchanged.
616
+ // - the TITLE is read at its conventional-commit SUBJECT, before the
617
+ // first colon, which is where this repository names the issue a change
618
+ // is FOR. `docs(#837): record the #836 battery` is 837's, not 836's.
619
+ // - the BODY must DECLARE that it closes the issue. A bare `#N` in a
620
+ // body is a citation, and 103 of this repository's 120 most recent PRs
621
+ // carry 417 of them.
622
+ return refs(headRef) || subject(pr?.title) || closes(pr?.body)
430
623
  })
431
624
 
432
625
  if (!match) return null
@@ -0,0 +1,146 @@
1
+ /**
2
+ * One reading of the process table, for every caller that needs one (#690, #707).
3
+ *
4
+ * Two subsystems ask about running processes and they used to ask differently:
5
+ * `lib/test-suite-lock.ts` ran `ps -axo command` and pattern-matched the text,
6
+ * and `~/.pai/hooks/OrphanProcessCleanup.hook.ts` ran `pgrep -f "bun test"` and
7
+ * then `pkill -f "bun test"`. Neither could answer the only question that
8
+ * matters when processes belong to other people — **whose process is this** —
9
+ * because neither read a pid, a parent, or an age.
10
+ *
11
+ * ## A pattern is not a reading, and `pkill` is not a decision
12
+ *
13
+ * `pkill -f <pattern>` has no observation step at all: it matches and signals
14
+ * in one syscall sequence, against whatever the table holds at signal time,
15
+ * including processes that started after whoever ran it decided to run it.
16
+ * There is no pid to record, no list to report, and no way to exclude the
17
+ * shell that launched the thing being killed — `-f` matches the full command
18
+ * line, so the measuring wrapper dies with the measured suite and the exit
19
+ * code is never written. That is #690: two full suites died mid-run on
20
+ * 2026-10-19 leaving logs that end at 323 lines with no summary, which is
21
+ * byte-indistinguishable from a hang.
22
+ *
23
+ * So this module reads ROWS — pid, ppid, elapsed seconds, command — and every
24
+ * decision downstream is taken about a row and signalled to a pid. Nothing in
25
+ * this repository may signal by pattern; `test/orphan-reaper.test.ts` holds
26
+ * that population at zero over `lib`, `hooks`, `scripts`, `workflows`,
27
+ * `gates` and `bin`, with no exemption list.
28
+ *
29
+ * ## An unreadable table is UNMEASURED, and it has a control string
30
+ *
31
+ * `ps` exiting non-zero, printing nothing, or printing something this parser
32
+ * cannot read must NOT come back as "no processes are running" — `0`, `[]`
33
+ * and silence are indistinguishable from success
34
+ * (`.claude/rules/config-access.md`). The control is the cheapest one
35
+ * available and it cannot be absent from a real reading: **the reading must
36
+ * contain the pid of the process taking it.** A table that cannot see its own
37
+ * reader is an instrument failure, and `readProcessTable` throws rather than
38
+ * returning a short list that every caller would read as an idle machine.
39
+ */
40
+
41
+ import { execFileSync } from "child_process";
42
+
43
+ /** One row of the process table. */
44
+ export interface ProcessRow {
45
+ pid: number;
46
+ ppid: number;
47
+ /** Wall-clock seconds since the process started, from `ps` `etime`. */
48
+ elapsedSeconds: number;
49
+ /** The full command line, `argv` joined by spaces, as `ps` reports it. */
50
+ command: string;
51
+ }
52
+
53
+ /**
54
+ * The process table could not be read, or the reading failed its own control.
55
+ *
56
+ * A distinct type so a caller can report UNMEASURED by name instead of
57
+ * folding the failure into an empty list.
58
+ */
59
+ export class ProcessTableUnreadable extends Error {
60
+ constructor(reason: string) {
61
+ super(`the process table is UNMEASURED: ${reason}`);
62
+ this.name = "ProcessTableUnreadable";
63
+ }
64
+ }
65
+
66
+ /** The `ps` invocation, in one place so there is one thing to mutate. */
67
+ export const PS_ARGS = ["-axo", "pid=,ppid=,etime=,command="];
68
+
69
+ /**
70
+ * `etime` in seconds, from BSD `ps`'s four shapes: `SS`, `MM:SS`, `HH:MM:SS`
71
+ * and `DD-HH:MM:SS`.
72
+ *
73
+ * Returns `null` rather than 0 on anything it cannot read. Zero is a real age
74
+ * — a process that started this second — so returning it for a parse failure
75
+ * would make an unreadable row look like the youngest possible process, which
76
+ * is the one state an age floor treats as "definitely leave this alone". That
77
+ * is the safe direction for the floor and the wrong direction for honesty, so
78
+ * the caller is made to decide.
79
+ */
80
+ export function parseEtime(raw: string): number | null {
81
+ const text = raw.trim();
82
+ if (!/^(\d+-)?(\d+:)?(\d+:)?\d+$/.test(text)) return null;
83
+ const [days, clock] = text.includes("-")
84
+ ? [Number(text.slice(0, text.indexOf("-"))), text.slice(text.indexOf("-") + 1)]
85
+ : [0, text];
86
+ const parts = clock.split(":").map(Number);
87
+ if (parts.some((n) => !Number.isFinite(n))) return null;
88
+ let seconds = 0;
89
+ for (const part of parts) seconds = seconds * 60 + part;
90
+ return days * 86_400 + seconds;
91
+ }
92
+
93
+ /**
94
+ * Parse `ps -axo pid=,ppid=,etime=,command=` output into rows.
95
+ *
96
+ * Lines this cannot read are DROPPED and counted by the caller's control
97
+ * rather than guessed at — a row with an unparseable age is a row nobody can
98
+ * apply an age floor to.
99
+ */
100
+ export function parseProcessTable(raw: string): ProcessRow[] {
101
+ const rows: ProcessRow[] = [];
102
+ for (const line of raw.split("\n")) {
103
+ const m = /^\s*(\d+)\s+(\d+)\s+(\S+)\s+(.*)$/.exec(line);
104
+ if (!m) continue;
105
+ const elapsedSeconds = parseEtime(m[3]);
106
+ if (elapsedSeconds === null) continue;
107
+ const command = m[4].trim();
108
+ if (!command) continue;
109
+ rows.push({ pid: Number(m[1]), ppid: Number(m[2]), elapsedSeconds, command });
110
+ }
111
+ return rows;
112
+ }
113
+
114
+ /** How the table is fetched. Injected so no test has to run `ps`. */
115
+ export type ProcessTableReader = () => string;
116
+
117
+ const defaultReader: ProcessTableReader = () =>
118
+ execFileSync("ps", PS_ARGS, { encoding: "utf-8", maxBuffer: 8 * 1024 * 1024 });
119
+
120
+ /**
121
+ * Read the process table, or throw `ProcessTableUnreadable`.
122
+ *
123
+ * The control is applied here and not left to callers: a reading that does
124
+ * not contain `selfPid` is refused. Every caller then gets rows it can trust
125
+ * or an exception it has to name, and neither can be mistaken for an idle
126
+ * machine.
127
+ */
128
+ export function readProcessTable(
129
+ options: { read?: ProcessTableReader; selfPid?: number } = {},
130
+ ): ProcessRow[] {
131
+ const selfPid = options.selfPid ?? process.pid;
132
+ let raw: string;
133
+ try {
134
+ raw = (options.read ?? defaultReader)();
135
+ } catch (e) {
136
+ throw new ProcessTableUnreadable(`ps could not be run (${(e as Error).message})`);
137
+ }
138
+ const rows = parseProcessTable(raw);
139
+ if (!rows.some((r) => r.pid === selfPid)) {
140
+ throw new ProcessTableUnreadable(
141
+ `the reading does not contain the reader's own pid ${selfPid}, ` +
142
+ `so ${rows.length} rows is not a count of what is running`,
143
+ );
144
+ }
145
+ return rows;
146
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Does THIS project generate `PROJECT-STATE.md` from `project-state.json`?
3
+ * (#781)
4
+ *
5
+ * `.claude/rules/key-files.md` is generated, and one of its rows was a
6
+ * hardcoded literal in two places — `lib/scanner.ts` and
7
+ * `lib/scaffold/steps.ts` — reading *"Live status + handoff (generated from
8
+ * project-state.json — don't edit directly)"*. Every consumer got that
9
+ * sentence, whether or not it was true of them.
10
+ *
11
+ * Measured on one consumer at `e58ab6bb` (named on #781): **no generator exists there.**
12
+ * Nothing in `src/`, `scripts/`, `dashboard/src/` or the `Makefile` reads
13
+ * `project-state.json`, and the two files carry unrelated content — the JSON
14
+ * has priorities and sessions, the Markdown has 27 KB of page inventory, API
15
+ * groups and architecture. An agent that reads the rule, believes it, and
16
+ * regenerates destroys the only authoritative snapshot that repo has, and
17
+ * **the loss presents as a success**: exit 0, `git status` showing `M`, not
18
+ * `D`.
19
+ *
20
+ * ## The generator was asserting a relationship it had no way to check
21
+ *
22
+ * That is the part worth fixing rather than wording around. *"Generated from
23
+ * X"* is a claim about the CONSUMER's build. The sentence that authorises the
24
+ * destructive action was emitted unconditionally by a generator that had
25
+ * never looked.
26
+ *
27
+ * So the row is now a reading. A project with something that reads
28
+ * `project-state.json` is told the file is derived; a project with nothing
29
+ * that reads it is told it is maintained directly; and a scan that could not
30
+ * look at anything says so instead of defaulting to either
31
+ * (`.claude/rules/config-access.md`, *Silent Default Substitution* — `0`,
32
+ * `{}` and silence are indistinguishable from success).
33
+ *
34
+ * ## The cheapest wrong fix, named before the repair
35
+ *
36
+ * **Soften the literal.** Replace both copies with *"Live status + handoff.
37
+ * DA-owned."* and stop. It is one find-and-replace, it removes the
38
+ * authorisation, and #781 lists it as option 1.
39
+ *
40
+ * It is wrong because it is wrong in the other direction for everybody else:
41
+ * this repository DOES generate `PROJECT-STATE.md`, from
42
+ * `scripts/update-project-state.ts`, and a consumer told to edit it directly
43
+ * will have its edits overwritten on the next run. The derivation claim is
44
+ * not false — it is *conditional*, and a fix that deletes it trades one
45
+ * untrue sentence for another.
46
+ *
47
+ * The case that does not survive it is the GENERATOR_FOUND one: a fixture
48
+ * that does read `project-state.json` must still be told the file is
49
+ * derived. A battery with only the no-generator shape in it would have
50
+ * certified the softening.
51
+ *
52
+ * ## Why the scan reports its own coverage
53
+ *
54
+ * #492: a scan that reports a verdict should report how much it read. An
55
+ * empty tree and a tree with no generator produce the same `found: false`,
56
+ * and only one of them is a measurement. `filesScanned` and `bytesScanned`
57
+ * are both carried, and both must be non-zero — a byte count alone is
58
+ * walked past by a single newline, which is measured in that issue.
59
+ */
60
+
61
+ import { existsSync, readFileSync, readdirSync, statSync } from "fs";
62
+ import { join } from "path";
63
+
64
+ /** The one spelling of the ownership fact, so no site states it twice. */
65
+ export const PROJECT_STATE_OWNERSHIP = "DA-owned (#296)";
66
+
67
+ export const PROJECT_STATE_DERIVED =
68
+ "Live status + handoff (generated from project-state.json — don't edit directly)";
69
+
70
+ export const PROJECT_STATE_UNDERIVED =
71
+ `Live status + handoff. ${PROJECT_STATE_OWNERSHIP} — nothing in this project reads ` +
72
+ "project-state.json, so this file is maintained directly and regenerating it would " +
73
+ "destroy its contents";
74
+
75
+ export const PROJECT_STATE_UNMEASURED =
76
+ `Live status + handoff. ${PROJECT_STATE_OWNERSHIP} — whether anything in this project ` +
77
+ "generates it could not be determined, so do not regenerate it";
78
+
79
+ export type DerivationVerdict = "GENERATOR_FOUND" | "NO_GENERATOR" | "UNMEASURED";
80
+
81
+ export interface DerivationReading {
82
+ verdict: DerivationVerdict;
83
+ /** Project-relative paths that read `project-state.json`. */
84
+ evidence: string[];
85
+ /** How many files the walk actually opened, so a PASS can report its coverage. */
86
+ filesScanned: number;
87
+ /** And how much of them it read — one empty file is not a scan. */
88
+ bytesScanned: number;
89
+ /** Present only on UNMEASURED, and never empty when it is. */
90
+ unmeasuredReason: string | null;
91
+ }
92
+
93
+ /**
94
+ * Where a generator could live. Deliberately wider than the source
95
+ * directories `scanner.ts` detects: `scripts/` and `bin/` are where this
96
+ * repository's own updater lives, and a walk that missed them would report
97
+ * NO_GENERATOR for the tree it is running in.
98
+ */
99
+ const SEARCH_DIRS = ["src", "lib", "gates", "workflows", "hooks", "scripts", "bin", "dashboard/src"];
100
+ const SEARCH_FILES = ["Makefile", "package.json", "justfile", "Taskfile.yml"];
101
+
102
+ /** `.claude/` is excluded on purpose: the rule file naming the claim is not evidence for it. */
103
+ const SKIP_DIRS = new Set([".git", ".claude", "node_modules", "dist", "build", "coverage"]);
104
+
105
+ /**
106
+ * This module is excluded from its own walk.
107
+ *
108
+ * #646's trap, in the form that is easiest to ship by accident: the file that
109
+ * DECIDES whether a generator exists quotes both of the strings it looks for,
110
+ * so without this it is evidence for itself and every project carrying a copy
111
+ * of rungate's source reads GENERATOR_FOUND. The store quoting the subject
112
+ * back is not a witness.
113
+ */
114
+ const SELF = "project-state-derivation.ts";
115
+ const TEXTLIKE = /\.(ts|tsx|js|jsx|mjs|cjs|py|rb|go|rs|sh|bash|zsh|json|ya?ml|toml|mk)$/;
116
+
117
+ function walk(dir: string, root: string, acc: { files: string[] }, depth = 0): void {
118
+ if (depth > 8) return;
119
+ let entries;
120
+ try {
121
+ entries = readdirSync(dir, { withFileTypes: true });
122
+ } catch {
123
+ return;
124
+ }
125
+ for (const e of entries) {
126
+ if (SKIP_DIRS.has(e.name)) continue;
127
+ const p = join(dir, e.name);
128
+ if (e.isDirectory()) walk(p, root, acc, depth + 1);
129
+ else if (TEXTLIKE.test(e.name) && e.name !== SELF) acc.files.push(p);
130
+ }
131
+ }
132
+
133
+ /**
134
+ * Read the project and say whether anything in it consumes
135
+ * `project-state.json`.
136
+ *
137
+ * One binding, so there is one thing to mutate and one answer. A second
138
+ * notion of "does this project generate it" would agree on every tree anyone
139
+ * has and diverge on the one that matters
140
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, the fourth shape).
141
+ */
142
+ export function projectStateDerivation(root: string): DerivationReading {
143
+ const acc = { files: [] as string[] };
144
+ for (const d of SEARCH_DIRS) {
145
+ const full = join(root, d);
146
+ if (existsSync(full)) walk(full, root, acc);
147
+ }
148
+ for (const f of SEARCH_FILES) {
149
+ const full = join(root, f);
150
+ try {
151
+ if (existsSync(full) && statSync(full).isFile()) acc.files.push(full);
152
+ } catch {
153
+ /* unreadable is not present */
154
+ }
155
+ }
156
+
157
+ const evidence: string[] = [];
158
+ let filesScanned = 0;
159
+ let bytesScanned = 0;
160
+ for (const f of acc.files) {
161
+ let text: string;
162
+ try {
163
+ text = readFileSync(f, "utf-8");
164
+ } catch {
165
+ continue;
166
+ }
167
+ filesScanned++;
168
+ bytesScanned += text.length;
169
+ // BOTH names, not either. A generator reads the JSON and writes the
170
+ // Markdown, and that is the claim being made; a file that merely mentions
171
+ // `project-state.json` — a doc lint, a gitignore check, a path constant —
172
+ // is not one. The direction of a loose predicate matters here: a false
173
+ // GENERATOR_FOUND is the reading that re-authorises destroying the file.
174
+ if (text.includes("project-state.json") && text.includes("PROJECT-STATE.md")) {
175
+ evidence.push(f.startsWith(root) ? f.slice(root.length).replace(/^[/\\]/, "") : f);
176
+ }
177
+ }
178
+
179
+ if (filesScanned === 0 || bytesScanned === 0) {
180
+ return {
181
+ verdict: "UNMEASURED",
182
+ evidence: [],
183
+ filesScanned,
184
+ bytesScanned,
185
+ unmeasuredReason:
186
+ filesScanned === 0
187
+ ? "no source file in this project could be read, so nothing was searched for a " +
188
+ "generator — which is not the same fact as there being none (#781)"
189
+ : `${filesScanned} file(s) were walked and none had any content, so the search ` +
190
+ "read nothing (#781)",
191
+ };
192
+ }
193
+
194
+ return {
195
+ verdict: evidence.length > 0 ? "GENERATOR_FOUND" : "NO_GENERATOR",
196
+ evidence: evidence.sort(),
197
+ filesScanned,
198
+ bytesScanned,
199
+ unmeasuredReason: null,
200
+ };
201
+ }
202
+
203
+ /**
204
+ * The `what` column of `key-files.md`'s PROJECT-STATE.md row.
205
+ *
206
+ * One binding for the three sentences, so the two generators cannot drift —
207
+ * #781's SC-2 is exactly that: a fix applied to one hardcoded copy leaves the
208
+ * other.
209
+ */
210
+ export function projectStateKeyFileNote(reading: DerivationReading): string {
211
+ switch (reading.verdict) {
212
+ case "GENERATOR_FOUND":
213
+ return PROJECT_STATE_DERIVED;
214
+ case "NO_GENERATOR":
215
+ return PROJECT_STATE_UNDERIVED;
216
+ default:
217
+ return PROJECT_STATE_UNMEASURED;
218
+ }
219
+ }