rungate 0.8.0 → 0.8.2

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 (73) hide show
  1. package/gates/.gate-salt +1 -0
  2. package/gates/SCHEMA-GUIDE.md +485 -0
  3. package/gates/ac-quality.test.ts +106 -0
  4. package/gates/adversarial.test.ts +283 -0
  5. package/gates/brief-assembler.test.ts +487 -0
  6. package/gates/brief-assembler.ts +448 -0
  7. package/gates/bunfig.toml +2 -0
  8. package/gates/chain.test.ts +91 -0
  9. package/gates/e2e-smoke.test.ts +234 -0
  10. package/gates/error-classifier.test.ts +250 -0
  11. package/gates/error-classifier.ts +99 -0
  12. package/gates/gate-executor.ts +3071 -0
  13. package/gates/orchestrator.test.ts +968 -0
  14. package/gates/orchestrator.ts +827 -0
  15. package/gates/preload.ts +89 -0
  16. package/gates/prompts/ac-adversary.md +20 -0
  17. package/gates/prompts/evidence-validator.md +22 -0
  18. package/gates/prompts/prove-reproducer.md +53 -0
  19. package/gates/prompts.sha256 +3 -0
  20. package/gates/prove.test.ts +164 -0
  21. package/gates/rook-state.test.ts +108 -0
  22. package/gates/run-attribution.ts +290 -0
  23. package/gates/run-gate.ts +163 -0
  24. package/gates/schema-parity.test.ts +378 -0
  25. package/gates/schema.ts +1209 -0
  26. package/gates/self-heal.test.ts +511 -0
  27. package/gates/self-heal.ts +125 -0
  28. package/gates/ship-orchestrator.test.ts +399 -0
  29. package/gates/ship-orchestrator.ts +384 -0
  30. package/gates/spec-compliance-probe.ts +159 -0
  31. package/gates/test-fixtures/broken-no-environments.json +110 -0
  32. package/gates/test-fixtures/consumer-directory-layout.json +90 -0
  33. package/gates/test-fixtures/valid-standard.json +91 -0
  34. package/gates/test-utils.ts +43 -0
  35. package/gates/typecheck-gate.ts +111 -0
  36. package/gates/witness.ts +349 -0
  37. package/gates/workflow.test.ts +2018 -0
  38. package/hooks/BashWriteGuard.hook.ts +19 -0
  39. package/hooks/GateResultProtection.hook.ts +27 -1
  40. package/hooks/VerifyPhaseLock.hook.ts +51 -11
  41. package/hooks/WorkflowStateGuard.hook.ts +24 -0
  42. package/lib/ai-review-rounds.ts +462 -0
  43. package/lib/bash-file-read.ts +17 -3
  44. package/lib/bash-write-guard.ts +1285 -50
  45. package/lib/distribution-standing.ts +75 -4
  46. package/lib/failure-intake.ts +12 -4
  47. package/lib/file-extensions.ts +81 -0
  48. package/lib/finding-arbiter.ts +1015 -0
  49. package/lib/finding-jury.ts +537 -0
  50. package/lib/gate-enforcement.ts +171 -43
  51. package/lib/gate-result-protection.ts +12 -2
  52. package/lib/generators/code-map.ts +55 -4
  53. package/lib/generators/types.ts +27 -1
  54. package/lib/github.ts +55 -0
  55. package/lib/interpreters.ts +64 -0
  56. package/lib/issue-create-override.ts +69 -8
  57. package/lib/issue-filing-gate.ts +605 -0
  58. package/lib/js-top-level-code.ts +20 -2
  59. package/lib/junit-checks.ts +239 -1
  60. package/lib/package-closure.ts +114 -0
  61. package/lib/publish-window.ts +287 -0
  62. package/lib/scaffold/ai-review-findings.ts +142 -3
  63. package/lib/scaffold/ai-review-step.ts +1012 -18
  64. package/lib/scaffold/managed-workflow.ts +163 -4
  65. package/lib/scaffold/steps.ts +498 -22
  66. package/lib/scanner.ts +13 -4
  67. package/lib/ticked-sc-symbols.ts +361 -0
  68. package/lib/transcript-checker.ts +6 -0
  69. package/lib/workflow-actions.ts +18 -0
  70. package/package.json +3 -1
  71. package/scripts/arbitrate-finding.ts +224 -0
  72. package/scripts/generate-code-map.ts +18 -10
  73. package/scripts/sync-sc-status.ts +82 -8
@@ -68,6 +68,39 @@
68
68
  * the one the issue was filed about: `runGateEnforcement` deletes
69
69
  * `gate-pending.json` when it sees no failure, so a corrupt state file also
70
70
  * **erased the strike counter**. An unmeasured reading now leaves it alone.
71
+ *
72
+ * ## The catch was one route to the wrong answer, not the only one
73
+ *
74
+ * A review of the first fix found three more, and measuring them found a
75
+ * fourth. None of them throws: each walks past a malformed value and arrives
76
+ * at the same "no gate failure" the catch produced. All now refuse.
77
+ *
78
+ * | Shape | Why it is not cosmetic |
79
+ * |---|---|
80
+ * | `gates` present and not an object | reads as a state with no gates |
81
+ * | a record under a gate name not an object | reads as that gate not failing |
82
+ * | `result: "FAIL"` with non-array `failures` | drops an explicit FAIL |
83
+ * | `acs` present and not an array | `hasOutcomeAcFailure` false, so an immediate block degrades to a 3-strike nag |
84
+ * | `issue` absent or not a number | `loadStrikeCount` compares with `===`, so strikes read 0 forever and max_strikes is never reached — escalation silently off |
85
+ *
86
+ * `failures` ABSENT stays legal, because the schema has it optional; only a
87
+ * present-but-wrong-typed one refuses.
88
+ *
89
+ * ## Why refusing is safe here, which the issue asked to be shown and not assumed
90
+ *
91
+ * The issue's open question was transient corruption — a half-written state
92
+ * during a concurrent gate run turning into a block. It cannot happen:
93
+ * `writeState` in `gates/orchestrator.ts` writes a `.tmp`, RE-PARSES it to
94
+ * prove it is valid JSON, and only then `renameSync`s over the real path.
95
+ * rename(2) is atomic, so a concurrent reader sees the whole old file or the
96
+ * whole new one, never a prefix of either. An unparseable state on disk is
97
+ * therefore durable corruption from something other than the writer — which
98
+ * is exactly the case that must refuse.
99
+ *
100
+ * Measured against the live work store on 2026-10-22 as a control on
101
+ * over-refusal: 164 state files, `issue` a number in 164, `acs` an array in
102
+ * 164, `slug` a string in 164, and `failures` a non-empty array in all 95
103
+ * FAIL gates. This module reads that store as MEASURED with zero reasons.
71
104
  */
72
105
 
73
106
  import {
@@ -132,13 +165,38 @@ export function formatFailures(failures: GateFailure[]): string {
132
165
  */
133
166
  export type WorkflowReading = 'MEASURED' | 'UNMEASURED';
134
167
 
135
- export interface WorkflowScan {
136
- reading: WorkflowReading;
137
- /** The first blocking gate FAIL found, in scope > verify > ship priority. */
138
- failure: WorkflowGateFailure | null;
139
- /** One line per unreadable path. Non-empty exactly when UNMEASURED. */
140
- unmeasuredReasons: string[];
141
- }
168
+ /**
169
+ * A union rather than a record, so **`failure` exists only on the measured
170
+ * variant** — the shape `lib/intake-sources.ts` uses for the same hazard over
171
+ * these same files, and for the same stated reason: "a warning beside a
172
+ * number is read after the number, if at all."
173
+ *
174
+ * The hazard is not hypothetical here, it was live in this module's first
175
+ * draft: `runGateEnforcement` read `scan.failure` and consulted `reading`
176
+ * only when that was null, so a sweep that failed to parse one state and
177
+ * found a failure in another reported a COMPLETE result. `intake-sources`
178
+ * declines to convert `FailureIntakeReading` to a union on the grounds that
179
+ * its hazard is latent and the type is shipped; both halves of that argument
180
+ * point the other way for this type, which is new in #1155 and whose first
181
+ * consumer had already fallen into the trap.
182
+ *
183
+ * The partial result stays reachable — withholding it would make a partial
184
+ * scan and a clean one look alike — but under a name nobody reaches for by
185
+ * accident, because acting on it is a decision.
186
+ */
187
+ export type WorkflowScan =
188
+ | {
189
+ reading: 'MEASURED';
190
+ unmeasuredReasons: string[];
191
+ /** The first blocking gate FAIL, in scope > verify > ship priority. */
192
+ failure: WorkflowGateFailure | null;
193
+ }
194
+ | {
195
+ reading: 'UNMEASURED';
196
+ unmeasuredReasons: string[];
197
+ /** What the states that COULD be read yielded. Deliberately not `failure`. */
198
+ failureFromPartialScan: WorkflowGateFailure | null;
199
+ };
142
200
 
143
201
  /** A plain JSON object — not an array, not null, not a scalar. */
144
202
  function isPlainObject(v: unknown): v is Record<string, unknown> {
@@ -206,11 +264,11 @@ export function findWorkflowGateFailure(workDir: string): WorkflowScan {
206
264
  reasons.push(`${workDir}: work directory could not be listed (${err})`);
207
265
  }
208
266
 
209
- return {
210
- reading: reasons.length === 0 ? 'MEASURED' : 'UNMEASURED',
211
- failure,
212
- unmeasuredReasons: reasons,
213
- };
267
+ // Same derivation as `lib/intake-sources.ts`: the reading is a function of
268
+ // whether anything went unread, and NOT of whether a failure turned up.
269
+ return reasons.length === 0
270
+ ? { reading: 'MEASURED', failure, unmeasuredReasons: reasons }
271
+ : { reading: 'UNMEASURED', failureFromPartialScan: failure, unmeasuredReasons: reasons };
214
272
  }
215
273
 
216
274
  /**
@@ -240,37 +298,85 @@ function checkWorkflowFile(wfPath: string, slug: string): FileReading {
240
298
  };
241
299
  }
242
300
 
301
+ const refuse = (what: string) => ({
302
+ failure: null,
303
+ unmeasured: `${wfPath}: ${what} — the state is malformed, so whether a gate FAILed is unknown`,
304
+ });
305
+
243
306
  try {
244
307
  if (wf.phase === 'DONE') return READABLE;
245
308
 
246
- const gates = (isPlainObject(wf.gates) ? wf.gates : {}) as Record<string, {
247
- result?: string;
248
- failures?: { check?: string; id?: string; detail?: string; message?: string }[];
249
- }>;
309
+ // Every shape check below mirrors `WorkflowStateSchema` in gates/schema.ts,
310
+ // which `writeWorkflowState` enforces on the way in. A value that violates
311
+ // it did not come from the sanctioned writer, and walking past it reaches
312
+ // the same wrong answer as the catch this issue was filed about.
313
+ //
314
+ // Mirrored by hand rather than imported: `package.json` `files[]` ships
315
+ // `lib/` and `hooks/` and NOT `gates/`, so importing the schema here
316
+ // would make the published package reference a file it does not ship.
317
+ // `lib/` imports nothing from `gates/` today and this is not the change
318
+ // that should be the first. The duplication is bounded to four field
319
+ // types, and over-refusal is controlled by measurement, not by hope:
320
+ // across the 164 state files in the live work store this reports
321
+ // MEASURED with zero reasons.
322
+ if (wf.gates !== undefined && !isPlainObject(wf.gates)) {
323
+ return refuse(`gates is ${Array.isArray(wf.gates) ? 'an array' : typeof wf.gates}, not an object`);
324
+ }
325
+ // `acs` feeds hasOutcomeAcFailure, which is the difference between an
326
+ // immediate block and a three-strike nag — so a malformed one downgrades
327
+ // enforcement rather than merely losing detail.
328
+ if (wf.acs !== undefined && !Array.isArray(wf.acs)) {
329
+ return refuse(`acs is ${typeof wf.acs}, not an array`);
330
+ }
331
+ // `issue` keys the strike counter, and `loadStrikeCount` compares it with
332
+ // `===`. A string issue reads 0 strikes on every call, so the agent never
333
+ // reaches max_strikes and is never blocked — escalation silently off.
334
+ if (typeof wf.issue !== 'number') {
335
+ return refuse(wf.issue === undefined ? 'issue is absent' : `issue is ${wf.issue === null ? 'null' : typeof wf.issue}, not a number`);
336
+ }
337
+ if (wf.slug !== undefined && typeof wf.slug !== 'string') {
338
+ return refuse(`slug is ${typeof wf.slug}, not a string`);
339
+ }
340
+
341
+ const gates = (wf.gates ?? {}) as Record<string, unknown>;
250
342
  // #1137: the registry, not a second copy of it. This list and
251
343
  // GateResultProtection's agreed on every input anyone had, so nothing
252
344
  // could go red when they diverged.
253
345
  for (const gateName of BLOCKING_GATES) {
254
- const gate = gates[gateName];
255
- if (gate?.result === 'FAIL' && Array.isArray(gate.failures) && gate.failures.length > 0) {
256
- const acs = Array.isArray(wf.acs) ? wf.acs : [];
257
- const hasOutcomeAcFailure = acs.some(
258
- (ac: { type?: string; verdict?: string }) => ac.type === 'OUTCOME' && ac.verdict === 'FAIL',
259
- );
260
- return {
261
- unmeasured: null,
262
- failure: {
263
- gate: gateName,
264
- issue: wf.issue as number,
265
- slug: (wf.slug as string) || slug,
266
- failures: gate.failures.map(f => ({
267
- check: f.check || f.id || 'unknown',
268
- detail: f.detail || f.message || JSON.stringify(f),
269
- })),
270
- hasOutcomeAcFailure,
271
- },
272
- };
346
+ const raw = gates[gateName];
347
+ if (raw === undefined || raw === null) continue;
348
+ if (!isPlainObject(raw)) {
349
+ return refuse(`gates.${gateName} is ${Array.isArray(raw) ? 'an array' : typeof raw}, not an object`);
350
+ }
351
+ const gate = raw as {
352
+ result?: unknown;
353
+ failures?: { check?: string; id?: string; detail?: string; message?: string }[];
354
+ };
355
+ if (gate.result !== 'FAIL') continue;
356
+
357
+ // `failures` is optional in the schema, so ABSENT is legal and reads as
358
+ // a FAIL with nothing to report (0 of 95 live FAIL gates omit it).
359
+ // Present-but-not-an-array is not legal, and dropping a FAIL because
360
+ // its detail is the wrong type is the fail-open in miniature.
361
+ if (gate.failures !== undefined && !Array.isArray(gate.failures)) {
362
+ return refuse(`gates.${gateName}.result is FAIL but failures is ${typeof gate.failures}, not an array`);
273
363
  }
364
+ if (!Array.isArray(gate.failures) || gate.failures.length === 0) continue;
365
+
366
+ const acs = (wf.acs ?? []) as { type?: string; verdict?: string }[];
367
+ return {
368
+ unmeasured: null,
369
+ failure: {
370
+ gate: gateName,
371
+ issue: wf.issue,
372
+ slug: (wf.slug as string | undefined) || slug,
373
+ failures: gate.failures.map(f => ({
374
+ check: f.check || f.id || 'unknown',
375
+ detail: f.detail || f.message || JSON.stringify(f),
376
+ })),
377
+ hasOutcomeAcFailure: acs.some(ac => ac?.type === 'OUTCOME' && ac?.verdict === 'FAIL'),
378
+ },
379
+ };
274
380
  }
275
381
  } catch (err) {
276
382
  // Nothing above should throw now that the shape is checked first — so if
@@ -442,11 +548,22 @@ export function logEnforcementSignal(
442
548
  * artifact, the reason, and the one command that can repair it — a refusal
443
549
  * with no way out is a denial of service, not a guard.
444
550
  */
445
- export function unmeasuredStateReason(reasons: string[]): string {
551
+ export function unmeasuredStateReason(
552
+ reasons: string[],
553
+ alsoFound: WorkflowGateFailure | null = null,
554
+ ): string {
446
555
  return [
447
556
  'UNMEASURED: the harness gate state could not be read, so whether a gate is ' +
448
557
  'currently FAILing is unknown — and an unknown is not a pass.',
449
558
  ...reasons.map(r => ` - ${r}`),
559
+ ...(alsoFound
560
+ ? [
561
+ '',
562
+ `The states that COULD be read also carry a ${alsoFound.gate} gate FAIL on ` +
563
+ `issue #${alsoFound.issue}:`,
564
+ formatFailures(alsoFound.failures),
565
+ ]
566
+ : []),
450
567
  '',
451
568
  'Repair the state, then retry. workflow-state.json is not directly writable ' +
452
569
  '(WorkflowStateGuard); go through the validating writer:',
@@ -460,14 +577,20 @@ export function unmeasuredStateReason(reasons: string[]): string {
460
577
 
461
578
  export function runGateEnforcement(input: GateEnforcementInput): GateEnforcementResult {
462
579
  const scan = findWorkflowGateFailure(input.workDir);
463
- const wfFailure = scan.failure;
464
580
 
465
- // #1155: no readable failure, but the sweep was incomplete. Refuse rather
466
- // than report the clean run we did not actually observe. Skill-scoped, and
467
- // the strike counter is left alone — an unmeasured reading is not evidence
468
- // that the gate it was counting against has been fixed.
469
- if (!wfFailure && scan.reading === 'UNMEASURED') {
470
- const reason = unmeasuredStateReason(scan.unmeasuredReasons);
581
+ // #1155: the sweep was incomplete. Refuse rather than report a clean run we
582
+ // did not observe — and refuse WHETHER OR NOT a failure was also readable.
583
+ // Gating this on "found nothing" was the first draft's own instance of the
584
+ // bug: a scan that missed a state and found a failure elsewhere reported a
585
+ // complete result, and the unread state may hold the OUTCOME AC failure
586
+ // that would have blocked on sight rather than nagged for three strikes.
587
+ //
588
+ // Skill-scoped, so the repair path stays open; and the strike counter is
589
+ // left alone, because an unmeasured reading is not evidence that the gate
590
+ // it was counting against has been fixed.
591
+ if (scan.reading === 'UNMEASURED') {
592
+ const alsoFound = scan.failureFromPartialScan;
593
+ const reason = unmeasuredStateReason(scan.unmeasuredReasons, alsoFound);
471
594
  logSignal(input.signalsDir, input.signalsFile, {
472
595
  ts: new Date().toISOString(),
473
596
  type: 'gate_enforcement',
@@ -475,6 +598,7 @@ export function runGateEnforcement(input: GateEnforcementInput): GateEnforcement
475
598
  tool: input.toolName,
476
599
  action: input.toolName === 'Skill' ? 'block' : 'nag',
477
600
  reasons: scan.unmeasuredReasons,
601
+ ...(alsoFound ? { partial_gate: alsoFound.gate, partial_issue: alsoFound.issue } : {}),
478
602
  });
479
603
 
480
604
  if (input.toolName === 'Skill') {
@@ -486,6 +610,10 @@ export function runGateEnforcement(input: GateEnforcementInput): GateEnforcement
486
610
  };
487
611
  }
488
612
 
613
+ // Narrowed to the MEASURED variant by the return above, so `failure` is
614
+ // reachable here and only here.
615
+ const wfFailure = scan.failure;
616
+
489
617
  if (!wfFailure) {
490
618
  if (existsSync(input.pendingFile)) {
491
619
  try {
@@ -160,9 +160,19 @@ const EDIT_CORRUPTS_REASON =
160
160
  'for every write after it.' +
161
161
  REPAIR_HINT;
162
162
 
163
- /** The artifact this module guards. */
163
+ /**
164
+ * The artifact this module guards.
165
+ *
166
+ * #1184: the comparison is case-FOLDED. Measured on this machine,
167
+ * `WORKFLOW-STATE.JSON` and `workflow-state.json` resolve to the same inode,
168
+ * because the default macOS filesystem is case-insensitive — so an uppercase
169
+ * spelling reached the same file with the guard switched off. On a
170
+ * case-sensitive filesystem they are genuinely different files and folding
171
+ * costs only a refusal of a name that cannot coexist with the real one on
172
+ * the platform where the bypass exists.
173
+ */
164
174
  export function isWorkflowState(filePath: string): boolean {
165
- return filePath.endsWith('workflow-state.json');
175
+ return filePath.toLowerCase().endsWith('workflow-state.json');
166
176
  }
167
177
 
168
178
  /** Whitespace-tolerant, because JSON is. */
@@ -4,9 +4,60 @@
4
4
  * Extracted from scaffold-project.ts per SCAFFOLD-DECOMPOSITION-SPEC (D-2).
5
5
  * Takes scan data in, produces file content out. No file I/O.
6
6
  */
7
- import type { ProjectScan } from "./types";
7
+ import type { DirEntry, ProjectScan } from "./types";
8
8
  import { localCalendarDay } from "../local-calendar-day";
9
9
 
10
+ /**
11
+ * What CODE-MAP.md guarantees, and what it does not — stated IN the file.
12
+ *
13
+ * #1163's acceptance, and the reason it is a constant rather than a sentence
14
+ * written twice: both renderers in this repo emit the same file
15
+ * (`scripts/generate-code-map.ts` for a real tree, this module for the
16
+ * scaffold's inline fallback), and a disclaimer that is true in one of them
17
+ * and missing from the other is worse than no disclaimer, because a reader
18
+ * who has seen it once stops looking for it.
19
+ *
20
+ * The claim it makes is narrow on purpose. The directory list is stable —
21
+ * MEASURED, 0 of the last 50 commit transitions moved it — and the
22
+ * per-directory file census was removed because 22 of those same 50 moved
23
+ * one. What remains unfixable is the FRONTMATTER: `scanned-at-sha` is
24
+ * `git rev-parse HEAD` at generation time, so it is a branch tip and can
25
+ * never be the squash commit that lands the file. There is no drift gate
26
+ * that survives that, and #1163's scope note forbids pretending otherwise.
27
+ */
28
+ export const FRESHNESS_NOTICE =
29
+ "**What this guarantees:** the sections below describe the tree at `scanned-at-sha`.\n" +
30
+ "**What it does not:** that `scanned-at-sha` is the commit you are reading this on. The scan\n" +
31
+ "runs on a branch tip and the squash merge lands it on a `main` that has already moved, so this\n" +
32
+ "file is at best one merge behind and no drift gate can close that (#1163). Per-directory file\n" +
33
+ "counts were removed for the same reason — 22 of 50 consecutive commits moved one. Treat every\n" +
34
+ "row as orientation, not as a fact about your working tree.";
35
+
36
+ /**
37
+ * The `## Directory Structure` table — header and body, ordered by name.
38
+ *
39
+ * ONE renderer for the two code paths that write CODE-MAP.md
40
+ * (`scripts/generate-code-map.ts` for a real tree, `generateCodeMap` below
41
+ * for the scaffold's inline fallback), and ONE place the row order is
42
+ * decided.
43
+ *
44
+ * That second property is the point. Before #1163 the order came from each
45
+ * of the THREE scanners that build `dirs`, every one of them sorting
46
+ * `b.fileCount - a.fileCount` — so the order was the census with an
47
+ * indirection in front of it, and removing the printed count would have left
48
+ * it behind. Three sites agreeing is the fourth shape in
49
+ * `.claude/rules/checks-must-be-able-to-fail.md`: a mutation of any one of
50
+ * them leaves the other two holding the answer up. The scanners no longer
51
+ * sort at all; this function does, by name, which is a key a reader can
52
+ * reproduce from what the file prints.
53
+ */
54
+ export function directoryTable(dirs: DirEntry[]): string {
55
+ const rows = [...dirs]
56
+ .sort((a, b) => a.name.localeCompare(b.name))
57
+ .map(d => `| ${d.name}/ | ${d.types.join(", ")} |`);
58
+ return ["| Directory | Types |", "|-----------|-------|", ...rows].join("\n");
59
+ }
60
+
10
61
  /**
11
62
  * Generate CODE-MAP.md content from project scan data.
12
63
  *
@@ -27,6 +78,8 @@ generator: scaffold-project.ts
27
78
 
28
79
  Auto-generated architecture snapshot.
29
80
 
81
+ ${FRESHNESS_NOTICE}
82
+
30
83
  ## Summary
31
84
 
32
85
  | Metric | Count |
@@ -37,9 +90,7 @@ Auto-generated architecture snapshot.
37
90
 
38
91
  ## Directory Structure
39
92
 
40
- | Directory | Files | Types |
41
- |-----------|-------|-------|
42
- ${dirs.map(d => `| ${d.name}/ | ${d.fileCount} | ${d.types.join(", ")} |`).join("\n")}
93
+ ${directoryTable(dirs)}
43
94
  `;
44
95
 
45
96
  if (routes.length > 0) {
@@ -49,9 +49,35 @@ export interface Category {
49
49
  notes: string;
50
50
  }
51
51
 
52
+ /**
53
+ * One top-level directory, as CODE-MAP.md lists it.
54
+ *
55
+ * **No file count, deliberately (#1163).** This interface carried a
56
+ * `fileCount` that every CODE-MAP renderer printed, and it was the one field
57
+ * in the file that could not be kept true. MEASURED over the 50 commit
58
+ * transitions ending at `b7281397`:
59
+ *
60
+ * | what moved | transitions out of 50 |
61
+ * |---|---|
62
+ * | a per-directory file count | **22** |
63
+ * | the row ORDER (it was sorted by that count) | 1 |
64
+ * | the directory list itself | **0** |
65
+ * | the `types` column | **0** |
66
+ *
67
+ * So the list is stable and the census is not — it is wrong roughly every
68
+ * second merge, and #1163 measured why no gate can hold it: `scanned-at-sha`
69
+ * is `git rev-parse HEAD` at generation time, which can never equal the sha
70
+ * of the squash commit that ships the file, so a regenerate-and-diff job
71
+ * fails 50 of the last 50 commits on the frontmatter alone.
72
+ *
73
+ * The count is therefore not rendered, not stored, and not scanned for. It
74
+ * is deleted rather than left computed-but-hidden, because a field nothing
75
+ * prints is a field nobody notices going stale — and because the row order
76
+ * was derived from it, the renderers sort by NAME now rather than by a
77
+ * number that is no longer there.
78
+ */
52
79
  export interface DirEntry {
53
80
  name: string;
54
- fileCount: number;
55
81
  types: string[];
56
82
  }
57
83
 
package/lib/github.ts CHANGED
@@ -30,6 +30,12 @@ export interface GitHubClient {
30
30
  createComment: (params: { owner: string; repo: string; issue_number: number; body: string }) => Promise<{ data: any }>;
31
31
  addLabels: (params: { owner: string; repo: string; issue_number: number; labels: string[] }) => Promise<{ data: any }>;
32
32
  update: (params: { owner: string; repo: string; issue_number: number; state?: string; [key: string]: any }) => Promise<{ data: any }>;
33
+ /**
34
+ * The repository's issues. **Returns pull requests too** — the REST API
35
+ * treats a PR as an issue, and every row carrying a `pull_request` key
36
+ * is one. `listOpenIssues` drops them; see why there.
37
+ */
38
+ listForRepo: (params: { owner: string; repo: string; state?: string; per_page?: number; [key: string]: any }) => Promise<{ data: any[] }>;
33
39
  };
34
40
  pulls: {
35
41
  create: (params: { owner: string; repo: string; title: string; head: string; base: string; body?: string; draft?: boolean }) => Promise<{ data: any }>;
@@ -306,6 +312,55 @@ export async function getIssueLabels(
306
312
  .filter((n: unknown): n is string => typeof n === "string" && n.length > 0);
307
313
  }
308
314
 
315
+ /** One open issue, as little of one as a symptom comparison needs. */
316
+ export interface OpenIssue {
317
+ number: number;
318
+ title: string;
319
+ body: string;
320
+ }
321
+
322
+ /**
323
+ * Open issues, newest first, **pull requests excluded** (#1261).
324
+ *
325
+ * Written for `lib/issue-filing-gate.ts`, which compares a filing about to be
326
+ * made against what is already on the tracker. Through Octokit rather than
327
+ * the GitHub CLI for the reason in `getIssueLabels` above and in
328
+ * GITHUB-API-MIGRATION-SPEC.md: a hook runs in whatever environment the
329
+ * session has, and a subprocess needs the CLI installed and authenticated
330
+ * there.
331
+ *
332
+ * **The PR filter is the part that is easy to leave out and expensive to
333
+ * omit.** `GET /repos/{o}/{r}/issues` returns pull requests as issues, and
334
+ * every PR row carries a `pull_request` key that an issue row does not. Left
335
+ * in, every open PR becomes a finding the dedupe can match against — and a
336
+ * PR body in this repository quotes the symptom of the issue it fixes, so the
337
+ * filing most likely to collide with an open PR is the one reporting the
338
+ * defect that PR has not yet merged. That is the exact filing this gate must
339
+ * not silence.
340
+ */
341
+ export async function listOpenIssues(
342
+ client: GitHubClient,
343
+ repoSlug: string,
344
+ limit = 100,
345
+ ): Promise<OpenIssue[]> {
346
+ const { owner, repo } = parseOwnerRepo(repoSlug);
347
+ const response = await client.rest.issues.listForRepo({
348
+ owner,
349
+ repo,
350
+ state: "open",
351
+ per_page: Math.min(Math.max(limit, 1), 100),
352
+ });
353
+ const rows = Array.isArray(response?.data) ? response.data : [];
354
+ return rows
355
+ .filter(row => row !== null && typeof row === "object" && row.pull_request === undefined)
356
+ .filter(row => typeof row.number === "number" && typeof row.title === "string")
357
+ .map(row => ({
358
+ number: row.number as number,
359
+ title: row.title as string,
360
+ body: typeof row.body === "string" ? row.body : "",
361
+ }));
362
+ }
363
+
309
364
  /**
310
365
  * Add a comment to an issue.
311
366
  */
@@ -0,0 +1,64 @@
1
+ /**
2
+ * One binding for "is this word an interpreter" (#1240).
3
+ *
4
+ * Two modules were asking the same question with two different answers.
5
+ * `lib/bash-write-guard.ts` asked it of a command word, to decide whether a
6
+ * `-c`/`-e` argument is a program; `lib/bash-file-read.ts` asked it of the
7
+ * text before a `<<`, to decide whether a heredoc body is a program or a
8
+ * document. The second list was shells only, so a `python3` heredoc read as
9
+ * a document there — and the write guard, which never asked the heredoc
10
+ * question at all, could not see a `python3 <<'PY'` program either.
11
+ *
12
+ * The write guard's list is the one kept, because `python3 <<'PY'` is as
13
+ * much a program as `bash <<'EOF'`.
14
+ *
15
+ * ## The third binding is NOT this question, and stays where it is
16
+ *
17
+ * `lib/hook-trees.ts` has an `INTERPRETERS` set of
18
+ * `bun/bunx/node/npx/npm/pnpm/yarn/deno/ts-node/tsx` — package runners, no
19
+ * shells. It answers "which leading token do I skip to find the hook file",
20
+ * which is a different population reached for a different reason, and its
21
+ * own docblock already carries a written reason not to share its parser
22
+ * ("the cheap generalisation 'reuse this parser everywhere' still has a
23
+ * written reason not to"). Folding it in here would widen it to `sh`, `php`
24
+ * and `osascript`, none of which register a hook. Two bindings collapse into
25
+ * one; the third is left with the reason restated rather than implied.
26
+ */
27
+
28
+ /**
29
+ * Programs that take source on the command line or on stdin and run it.
30
+ *
31
+ * Spelled as names rather than a regex so membership is one lookup and the
32
+ * list reads as a list. `python` without a suffix is included: `python <<PY`
33
+ * is still a program on a machine where `python` resolves to 3.
34
+ */
35
+ export const INTERPRETER_NAMES: ReadonlySet<string> = new Set([
36
+ 'sh', 'bash', 'zsh', 'dash', 'ksh',
37
+ 'python', 'python2', 'python3',
38
+ 'perl', 'ruby', 'php', 'osascript',
39
+ 'node', 'bun', 'deno',
40
+ ]);
41
+
42
+ /** Interpreters whose inline argument and heredoc body are SHELL. */
43
+ export const SHELL_NAMES: ReadonlySet<string> = new Set(['sh', 'bash', 'zsh', 'dash', 'ksh']);
44
+
45
+ /**
46
+ * The bare name of a token: leading directories and a leading `\` removed.
47
+ *
48
+ * `/bin/bash`, `\bash` and `bash` are one program to the shell, and the
49
+ * reason this exists rather than a `basename()` call is that a leading
50
+ * backslash is quoting, not a path component.
51
+ */
52
+ export function interpreterName(token: string): string {
53
+ return token.replace(/^\\/, '').replace(/^.*\//, '');
54
+ }
55
+
56
+ /** Is this token an interpreter — `/usr/bin/python3` as readily as `sh`? */
57
+ export function isInterpreterWord(token: string): boolean {
58
+ return INTERPRETER_NAMES.has(interpreterName(token));
59
+ }
60
+
61
+ /** Is this token a shell, whose program text this module can parse as shell? */
62
+ export function isShellWord(token: string): boolean {
63
+ return SHELL_NAMES.has(interpreterName(token));
64
+ }
@@ -284,11 +284,63 @@ const BOOLEAN_FLAGS = new Set(["-w", "--web", "-h", "--help", "--recover-only"])
284
284
  * MISSED — and a missed label is a refusal, the direction this guard is
285
285
  * allowed to be wrong in.
286
286
  */
287
- export function labelValues(tokens: string[]): string[] {
287
+ export interface FlagQuery {
288
+ /** The long form, with its dashes: `--label`. */
289
+ long: string;
290
+ /** The short form, with its dash: `-l`. Omit when there is none to read. */
291
+ short?: string;
292
+ /** `gh` reads `--label a,b` as two labels. A title is one value. */
293
+ commaSeparated?: boolean;
294
+ }
295
+
296
+ /** `--label` / `-l`, the one query this file's own decision needs. */
297
+ export const LABEL_FLAG: FlagQuery = { long: "--label", short: "-l", commaSeparated: true };
298
+
299
+ /**
300
+ * Short flags of `gh issue create` whose value may be ATTACHED: `-lfollow-up`.
301
+ *
302
+ * `-a` assignee, `-b` body, `-F` body-file, `-l` label, `-m` milestone,
303
+ * `-p` project, `-t` title, `-T` template, `-R` repo. `-w` and `-h` are
304
+ * boolean and live in `BOOLEAN_FLAGS`.
305
+ *
306
+ * **One table, consulted by every query, because where a token ends is a
307
+ * property of the COMMAND and not of the question being asked.** The first
308
+ * cut of this made it a per-query letter, so a walk looking for `--title`
309
+ * recognised `-tFoo` as attached while a walk looking for `--label` read the
310
+ * same token as an unknown flag and blindly consumed the one after it. Two
311
+ * readings of one command line, disagreeing about token boundaries — found
312
+ * by the AI review on #1282, which is right that the consequence is a
313
+ * silently dropped argument: `gh issue create -tFoo --body "…"` lost the
314
+ * body, so the finding arrived with no symptom and escaped the dedupe.
315
+ *
316
+ * It is a real change to `labelValues`, and in the direction of accuracy.
317
+ * `gh issue create -aalice --label follow-up` applies the override label and
318
+ * was REFUSED before this, because `-aalice` ate the `--label`. That was the
319
+ * accepted error direction — a missed label is a refusal — but it was still
320
+ * a wrong answer about a command somebody can type, and nothing about the
321
+ * widening lets a label be read where none was written: the token after an
322
+ * attached short is now parsed on its own merits rather than swallowed, and
323
+ * it still has to BE a `--label` argument to count. An unknown short flag is
324
+ * absent from this table and keeps the old conservative default.
325
+ */
326
+ const VALUE_SHORT_FLAGS = new Set(["a", "b", "F", "l", "m", "p", "t", "T", "R"]);
327
+
328
+ /** `-lfollow-up` — a short flag with its value glued on. */
329
+ const ATTACHED_SHORT = /^-([A-Za-z])[^-=]/;
330
+
331
+ /**
332
+ * The values passed to one flag of a `gh issue create` clause.
333
+ *
334
+ * One arity walk, parameterised, so a second reader of the same clause — see
335
+ * `lib/issue-filing-gate.ts`, which needs `--title` and `--body` — agrees with
336
+ * this one about where a flag's value is. Two walks would disagree the first
337
+ * time either learned a flag the other did not have.
338
+ */
339
+ export function flagValues(tokens: string[], q: FlagQuery): string[] {
288
340
  const out: string[] = [];
289
341
  const add = (v: string) => {
290
- for (const part of v.split(",")) {
291
- const t = part.trim();
342
+ for (const part of q.commaSeparated === true ? v.split(",") : [v]) {
343
+ const t = q.commaSeparated === true ? part.trim() : part;
292
344
  if (t) out.push(t);
293
345
  }
294
346
  };
@@ -299,16 +351,21 @@ export function labelValues(tokens: string[]): string[] {
299
351
  const eq = t.indexOf("=");
300
352
  if (eq !== -1) {
301
353
  const name = t.slice(0, eq);
302
- if (name === "--label" || name === "-l") add(t.slice(eq + 1));
354
+ if (name === q.long || name === q.short) add(t.slice(eq + 1));
303
355
  continue; // `--flag=value` carries its own value; it consumes nothing
304
356
  }
305
- if (t === "--label" || t === "-l") {
357
+ if (t === q.long || t === q.short) {
306
358
  if (i + 1 < tokens.length) add(tokens[++i]);
307
359
  continue;
308
360
  }
309
- // `-lfollow-up` — pflag lets a short flag carry its value attached.
310
- if (/^-l[^-=]/.test(t)) {
311
- add(t.slice(2));
361
+ // `-lfollow-up` — pflag lets a short flag carry its value attached. Its
362
+ // value is IN the token, so it consumes nothing whether or not it is the
363
+ // flag this query is collecting. That second half is the fix: a query
364
+ // that skipped it here would also skip the `continue` and eat the next
365
+ // token, which is the desync `VALUE_SHORT_FLAGS` exists to prevent.
366
+ const attached = ATTACHED_SHORT.exec(t);
367
+ if (attached !== null && VALUE_SHORT_FLAGS.has(attached[1])) {
368
+ if (q.short === `-${attached[1]}`) add(t.slice(2));
312
369
  continue;
313
370
  }
314
371
  if (!BOOLEAN_FLAGS.has(t)) i++; // this flag eats the next token
@@ -316,6 +373,10 @@ export function labelValues(tokens: string[]): string[] {
316
373
  return out;
317
374
  }
318
375
 
376
+ export function labelValues(tokens: string[]): string[] {
377
+ return flagValues(tokens, LABEL_FLAG);
378
+ }
379
+
319
380
  /**
320
381
  * The single place that decides. `null` means allow.
321
382
  *