rungate 0.6.0 → 0.8.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 (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,232 @@
1
+ /**
2
+ * Can this module write to the filesystem? (#968, hardening #323 SC-6.)
3
+ *
4
+ * ## Why this exists
5
+ *
6
+ * `test/scratch-paths-unique.test.ts` excludes itself from its own scan,
7
+ * because its negative fixtures are source text and the detector reads its
8
+ * own test data as violations. An unchecked exclusion is how an exemption
9
+ * becomes a hole, so the exclusion is paired with a case asserting the file
10
+ * creates nothing. That case was:
11
+ *
12
+ * ```ts
13
+ * const fsImport = /import\s*\{([^}]*)\}\s*from\s*"fs";/.exec(self);
14
+ * ```
15
+ *
16
+ * `exec` returns the FIRST match. MEASURED by mutating the real file and
17
+ * running it: adding `import { mkdirSync } from "fs";` as a SECOND import
18
+ * leaves the suite at 8 pass / 0 fail, and so does
19
+ * `import { mkdirSync } from "node:fs";`. The file gains a write primitive
20
+ * and the case that exists to notice stays green.
21
+ *
22
+ * One claim in #968 did NOT reproduce and is recorded here so it is not
23
+ * re-fixed: the old check does not fail open. Replacing the braced import
24
+ * with `import * as fs from "fs"` makes `exec` return null, and the
25
+ * `.not.toBeNull()` line goes red — 1 fail, measured. The defect is the first
26
+ * match, not the missing match.
27
+ *
28
+ * ## Capability, not use
29
+ *
30
+ * This reports what the module CAN do, not what it does. An imported but
31
+ * uncalled `mkdirSync` is reported, deliberately: the exclusion it guards is
32
+ * about what the file could hide, and "imported but currently unused" is one
33
+ * edit away from used. That is also what the regex it replaces did, so the
34
+ * false-positive surface is unchanged on that axis.
35
+ *
36
+ * ## Why an AST
37
+ *
38
+ * The file being checked is full of `mkdtempSync(` and `rmSync(` as STRING
39
+ * DATA — its own negative fixtures. A source-text count reads them as calls;
40
+ * the old check sidestepped that by reading only the import list, which is
41
+ * what made it blind to the second import. In an AST a string is a `Literal`
42
+ * and a call is a `CallExpression`, so the detector can read both the imports
43
+ * and the calls without its fixtures lying to it.
44
+ *
45
+ * `null` means the source did not parse — a REFUSAL, distinct from `[]`.
46
+ *
47
+ * ## WHAT THIS DOES NOT COVER (stated, because an unstated boundary reads as
48
+ * coverage, and a clean report from an incomplete detector is worse than no
49
+ * detector — #968's own thesis)
50
+ *
51
+ * MEASURED against the current implementation, each of these returns `[]`:
52
+ *
53
+ * - **An indirection through a variable.** `const w = mkdirSync` after a
54
+ * read-only import, `const m = await import("fs"); m.mkdirSync(…)`, or a
55
+ * write primitive received as a function argument. Only bindings created
56
+ * by an import statement, `require` or `Bun.*` are read.
57
+ * - **A write primitive re-exported by a local module.** `import { write }
58
+ * from "./helpers"` is not an fs module and is not reported, by design —
59
+ * the alternative is following the import graph, which this is not.
60
+ * - **`process.binding`, `Deno.*`, raw syscalls, and native addons.**
61
+ * - **A write performed by code this module merely CALLS.** The reading is
62
+ * per-module, not transitive.
63
+ *
64
+ * What IS covered, and measured: named/namespace/default imports from `fs`,
65
+ * `node:fs`, `fs/promises`, `node:fs/promises`; `require()` and dynamic
66
+ * `import()` of those; `child_process` and `node:child_process`; and
67
+ * `Bun.write`, `Bun.$`, `Bun.spawn`, `Bun.spawnSync`.
68
+ *
69
+ * The consumer that matters — `test/scratch-paths-unique.test.ts` — holds
70
+ * none of the uncovered forms, and the covered set includes every form that
71
+ * file could plausibly acquire. The gap is bounded by the thing it guards
72
+ * rather than argued away.
73
+ */
74
+
75
+ import { type AstNode, calleeRoot, parseTsModule, walkNodes } from "./ts-ast";
76
+
77
+ /** Module specifiers that resolve to node's filesystem API. */
78
+ const FS_MODULES = new Set(["fs", "node:fs", "fs/promises", "node:fs/promises"]);
79
+
80
+ /**
81
+ * Named exports of `fs` that CANNOT modify the filesystem. Everything else
82
+ * an fs module exports is treated as a write capability.
83
+ *
84
+ * ## The ratchet direction, which is the whole point of this list
85
+ *
86
+ * This was an allowlist of write names, and an allowlist has its default
87
+ * pointing the wrong way: every export node adds in future arrives
88
+ * classified as safe, silently, and the detector reports clean on it. The
89
+ * list was already five short — MEASURED on the allowlist version, all of
90
+ * `link`, `chmod`, `utimes`, `writev` and `ftruncate` returned `[]`.
91
+ *
92
+ * Inverted, an unknown name is a write. A name on THIS list is a name
93
+ * somebody considered and classified, which is the property an exemption
94
+ * list has and an allowlist does not: naming what is exempt is evidence the
95
+ * entry was looked at, naming what is safe is not.
96
+ *
97
+ * The cost of the inversion is false positives on read-only exports not
98
+ * listed here, and it is measured rather than asserted — see the census in
99
+ * the PR and the over-report cases in
100
+ * `test/fs-write-capabilities.test.ts`. `readFileSync` and `readdirSync` are
101
+ * how the detector's own consumer does its job and must not be refused.
102
+ */
103
+ const FS_READ_ONLY_NAMES = new Set([
104
+ "access", "accessSync",
105
+ "createReadStream",
106
+ "exists", "existsSync",
107
+ "lstat", "lstatSync",
108
+ "opendir", "opendirSync",
109
+ "readFile", "readFileSync",
110
+ "readdir", "readdirSync",
111
+ "readlink", "readlinkSync",
112
+ "realpath", "realpathSync",
113
+ "stat", "statSync",
114
+ "statfs", "statfsSync",
115
+ "watch", "watchFile",
116
+ // Added after the inversion's census over 667 files flagged them. Both are
117
+ // genuinely read-only and were the ONLY false positives the inversion
118
+ // introduced: `glob` enumerates, `close` releases a descriptor. They are
119
+ // listed rather than quietly tolerated, which is exactly the property the
120
+ // inverted list is for — a name here is a name somebody classified.
121
+ "glob", "globSync",
122
+ "close", "closeSync",
123
+ "fstat", "fstatSync",
124
+ // Type-only and constant exports, which carry no capability at all.
125
+ "constants", "Dirent", "Dir", "Stats", "promises",
126
+ ]);
127
+
128
+ /**
129
+ * Modules whose exports can write without touching `fs` — a shell or a
130
+ * spawn is a write capability however it is spelled.
131
+ */
132
+ const PROCESS_MODULES = new Set([
133
+ "child_process",
134
+ "node:child_process",
135
+ "bun",
136
+ ]);
137
+
138
+ function literalString(node: unknown): string | null {
139
+ const n = node as AstNode | undefined;
140
+ if (n?.type === "Literal" && typeof n.value === "string") return n.value;
141
+ return null;
142
+ }
143
+
144
+ function isFsModule(spec: string | null): boolean {
145
+ return spec !== null && FS_MODULES.has(spec);
146
+ }
147
+
148
+ function isProcessModule(spec: string | null): boolean {
149
+ return spec !== null && PROCESS_MODULES.has(spec);
150
+ }
151
+
152
+ /**
153
+ * Every filesystem-write capability `source` holds, as human sentences, in
154
+ * document order. Empty means the module cannot write. `null` means the
155
+ * source did not parse.
156
+ */
157
+ export function fsWriteCapabilities(source: string): string[] | null {
158
+ const parsed = parseTsModule(source);
159
+ if (parsed === null) return null;
160
+
161
+ const out: string[] = [];
162
+ for (const node of walkNodes(parsed.tree)) {
163
+ if (node.type === "ImportDeclaration") {
164
+ const spec = literalString(node.source);
165
+ if (isProcessModule(spec)) {
166
+ out.push(`"${spec}" is imported, and a spawned process can write anything`);
167
+ continue;
168
+ }
169
+ if (!isFsModule(spec)) continue;
170
+ for (const s of (node.specifiers ?? []) as AstNode[]) {
171
+ // A namespace or default binding carries the WHOLE module, so every
172
+ // write primitive comes with it whether or not it is named here.
173
+ // Reported on the BINDING rather than on `fs.writeFileSync(…)` member
174
+ // access: the binding is the capability, and tracking member access
175
+ // would be a narrower reading that an indirection defeats.
176
+ if (s.type === "ImportNamespaceSpecifier" || s.type === "ImportDefaultSpecifier") {
177
+ out.push(`the whole of "${spec}" is bound as \`${(s.local as AstNode).name}\``);
178
+ continue;
179
+ }
180
+ const imported = (s.imported as AstNode | undefined)?.name;
181
+ // INVERTED (#968 review): anything not known to be read-only is a
182
+ // write. An unknown export defaults to reported, not to safe.
183
+ if (typeof imported === "string" && !FS_READ_ONLY_NAMES.has(imported)) {
184
+ out.push(`\`${imported}\` is imported from "${spec}" and is not a known read-only export`);
185
+ }
186
+ }
187
+ continue;
188
+ }
189
+
190
+ if (node.type === "ImportExpression") {
191
+ const spec = literalString(node.source);
192
+ if (isFsModule(spec)) out.push(`"${spec}" is imported dynamically`);
193
+ else if (isProcessModule(spec)) out.push(`"${spec}" is imported dynamically`);
194
+ continue;
195
+ }
196
+
197
+ // `Bun.$\`…\`` is a tagged template, not a call. Checked separately or it
198
+ // is the one shell spelling this detector cannot see — the exact shape of
199
+ // defect #968 is about.
200
+ if (node.type === "TaggedTemplateExpression") {
201
+ const tag = node.tag as AstNode | undefined;
202
+ if (tag && calleeRoot(tag) === "Bun") {
203
+ const text = parsed.js.slice(tag.start, tag.end);
204
+ if (/^Bun\s*\.\s*\$$/.test(text)) out.push(`\`${text}\` can write without importing fs`);
205
+ }
206
+ continue;
207
+ }
208
+
209
+ if (node.type !== "CallExpression") continue;
210
+ const args = (node.arguments ?? []) as AstNode[];
211
+
212
+ // `require("fs")` — the whole module, same as a namespace import.
213
+ if ((node.callee as AstNode)?.type === "Identifier" && (node.callee as AstNode).name === "require") {
214
+ const spec = literalString(args[0]);
215
+ if (isFsModule(spec) || isProcessModule(spec)) out.push(`"${spec}" is loaded with require()`);
216
+ continue;
217
+ }
218
+
219
+ // Bun's own writers and spawners, which import nothing and so are
220
+ // invisible to any import-list check. `Bun.$` is reported even though a
221
+ // read-only shell call writes nothing: a shell is a write capability,
222
+ // and the cost of over-reporting it is named in the caller.
223
+ const callee = node.callee as AstNode | undefined;
224
+ if (callee && calleeRoot(callee) === "Bun") {
225
+ const text = parsed.js.slice(callee.start, callee.end);
226
+ if (/^Bun\s*\.\s*(write|\$|spawn|spawnSync)$/.test(text)) {
227
+ out.push(`\`${text}\` can write without importing fs`);
228
+ }
229
+ }
230
+ }
231
+ return out;
232
+ }
@@ -5,7 +5,69 @@
5
5
  * scanning, and signal logging. The hook file is a thin trigger that
6
6
  * delegates all logic here.
7
7
  *
8
- * Issue: #544
8
+ * Issue: #544. Fail-open closed by #1155.
9
+ *
10
+ * ## A state that could not be read is not a state with no failures (#1155)
11
+ *
12
+ * This module decides whether an agent is walking away from a gate FAIL. It
13
+ * used to answer that question from a bare `catch` commented "skip malformed",
14
+ * so a `workflow-state.json` that would not parse read as **no gate failure** —
15
+ * the condition that should refuse most loudly producing the most permissive
16
+ * result. That is *Silent Default Substitution* (`.claude/rules/config-access.md`)
17
+ * and the same fail-open class `lib/gate-result-protection.ts` closed.
18
+ *
19
+ * Measured 2026-10-22, because "malformed" was covering more than one thing:
20
+ *
21
+ * - **Three** distinct throw sources reached that one catch — a `JSON.parse`
22
+ * SyntaxError, a TypeError from reading `.phase` off a parsed `null`, and
23
+ * an fs error when the path exists but cannot be read (EISDIR, EACCES, or
24
+ * a delete racing the `existsSync` above it).
25
+ * - **The catch was not the only fail-open.** A state parsing to `42`, `"x"`
26
+ * or `[]` throws nothing at all: `.phase` is `undefined`, `gates || {}` is
27
+ * empty, and the old code returned `null` down the *normal* path. So six
28
+ * inputs read as a clean run, not three. `gate-result-protection` already
29
+ * refuses the non-object parses by name; this module now agrees with it.
30
+ *
31
+ * Three states that the old `null` conflated are now distinct, and only the
32
+ * middle one refuses:
33
+ *
34
+ * | On disk | Reading |
35
+ * |---|---|
36
+ * | no work dir, or no state file — a first run | `MEASURED`, no failure |
37
+ * | present, parses, no blocking gate FAIL | `MEASURED`, no failure |
38
+ * | present and unreadable, unparseable, or not an object | `UNMEASURED` |
39
+ *
40
+ * ## Why the refusal is scoped to Skill calls, and is not a wider block
41
+ *
42
+ * A bare refusal here would be worse than the bug: `GateEnforcement` is a
43
+ * PreToolUse hook on `.*`, so refusing every tool call would make a single
44
+ * corrupt state file a denial of service on the session — and a guard nobody
45
+ * can get out from under gets switched off, after which it guards nothing.
46
+ * So the recovery path was measured before the failure mode was chosen:
47
+ *
48
+ * - `makeEnforcementDecision` already blocks **only** `Skill` calls. Bash,
49
+ * Read, Edit and Agent are nagged, never blocked — that is the existing
50
+ * design's own escape hatch and it predates this change.
51
+ * - `WorkflowStateGuard` refuses direct `Write`/`Edit` of the artifact and
52
+ * names the repair: `bun -e "… writeWorkflowState(…)"`.
53
+ * - `BashWriteGuard` inspects only `>`/`>>`, `tee`, `cp` and `mv` targets,
54
+ * so that `bun -e` command carries no write target it can see and is
55
+ * allowed through.
56
+ *
57
+ * The repair therefore runs over Bash, which this refusal leaves open. There
58
+ * is no deadlock, and `test/gate-enforcement.test.ts` holds that as a control
59
+ * rather than as a comment: if a later change starts blocking Bash here, the
60
+ * control goes red.
61
+ *
62
+ * The refusal is **immediate** rather than strike-counted. Strikes are keyed
63
+ * on `issue` + `gate` by `loadStrikeCount`, and an unreadable state supplies
64
+ * neither — there is nothing to count against. Same reasoning as an OUTCOME
65
+ * AC failure, which also blocks on sight.
66
+ *
67
+ * One more consequence of the old `catch` is worth naming, because it is not
68
+ * the one the issue was filed about: `runGateEnforcement` deletes
69
+ * `gate-pending.json` when it sees no failure, so a corrupt state file also
70
+ * **erased the strike counter**. An unmeasured reading now leaves it alone.
9
71
  */
10
72
 
11
73
  import {
@@ -18,6 +80,7 @@ import {
18
80
  writeFileSync,
19
81
  } from 'fs';
20
82
  import { checkDocHygiene } from './doc-hygiene';
83
+ import { BLOCKING_GATES } from './gate-names';
21
84
 
22
85
  export interface GateFailure {
23
86
  check: string;
@@ -62,13 +125,60 @@ export function formatFailures(failures: GateFailure[]): string {
62
125
  return failures.map(f => ` - ${f.check}: ${f.detail}`).join('\n');
63
126
  }
64
127
 
128
+ /**
129
+ * Whether every state file under the work directory could actually be read.
130
+ * `UNMEASURED` means at least one could not — which is not the same answer as
131
+ * "no gate failed", and must never be collapsed into it.
132
+ */
133
+ export type WorkflowReading = 'MEASURED' | 'UNMEASURED';
134
+
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
+ }
142
+
143
+ /** A plain JSON object — not an array, not null, not a scalar. */
144
+ function isPlainObject(v: unknown): v is Record<string, unknown> {
145
+ return typeof v === 'object' && v !== null && !Array.isArray(v);
146
+ }
147
+
148
+ /** What one state file yielded: a failure, or a reason it could not be read. */
149
+ interface FileReading {
150
+ failure: WorkflowGateFailure | null;
151
+ unmeasured: string | null;
152
+ }
153
+
154
+ const READABLE: FileReading = { failure: null, unmeasured: null };
155
+
65
156
  /**
66
157
  * Scan workflow-state.json files under workDir for active gate failures.
67
158
  * Returns the first failure found (scope > verify > ship priority).
68
159
  * Checks both direct children and nested subdirectories.
160
+ *
161
+ * An unreadable state does not abort the scan: a readable sibling can still
162
+ * carry a real FAIL, and discarding it would trade one fail-open for another.
163
+ * Both answers are carried — `failure` for the actionable one, `reading` for
164
+ * whether the sweep was complete.
69
165
  */
70
- export function findWorkflowGateFailure(workDir: string): WorkflowGateFailure | null {
71
- if (!existsSync(workDir)) return null;
166
+ export function findWorkflowGateFailure(workDir: string): WorkflowScan {
167
+ const reasons: string[] = [];
168
+ // An absent work directory is a first run, not a corrupt one. MEASURED.
169
+ if (!existsSync(workDir)) return { reading: 'MEASURED', failure: null, unmeasuredReasons: [] };
170
+
171
+ let failure: WorkflowGateFailure | null = null;
172
+
173
+ // First failure wins, as before — but the sweep RUNS TO COMPLETION rather
174
+ // than returning on it. Stopping early would make `reading` depend on
175
+ // readdir order: a corrupt state sorting after a failing one would go
176
+ // unreported, and the same two files would answer differently on a
177
+ // filesystem that enumerated them the other way round.
178
+ const take = (r: FileReading): void => {
179
+ if (r.unmeasured) reasons.push(r.unmeasured);
180
+ if (r.failure && !failure) failure = r.failure;
181
+ };
72
182
 
73
183
  try {
74
184
  const dirs = readdirSync(workDir, { withFileTypes: true })
@@ -76,39 +186,71 @@ export function findWorkflowGateFailure(workDir: string): WorkflowGateFailure |
76
186
 
77
187
  for (const d of dirs) {
78
188
  // Level 1: direct children
79
- const result = checkWorkflowFile(`${workDir}/${d.name}/workflow-state.json`, d.name);
80
- if (result) return result;
189
+ take(checkWorkflowFile(`${workDir}/${d.name}/workflow-state.json`, d.name));
81
190
 
82
191
  // Level 2: nested subdirectories
83
192
  try {
84
193
  const subDirs = readdirSync(`${workDir}/${d.name}`, { withFileTypes: true })
85
194
  .filter(sd => sd.isDirectory());
86
195
  for (const sd of subDirs) {
87
- const nestedResult = checkWorkflowFile(
196
+ take(checkWorkflowFile(
88
197
  `${workDir}/${d.name}/${sd.name}/workflow-state.json`,
89
198
  `${d.name}/${sd.name}`,
90
- );
91
- if (nestedResult) return nestedResult;
199
+ ));
92
200
  }
93
- } catch { /* skip */ }
201
+ } catch (err) {
202
+ reasons.push(`${workDir}/${d.name}: directory could not be listed (${err})`);
203
+ }
94
204
  }
95
- } catch { /* skip */ }
205
+ } catch (err) {
206
+ reasons.push(`${workDir}: work directory could not be listed (${err})`);
207
+ }
96
208
 
97
- return null;
209
+ return {
210
+ reading: reasons.length === 0 ? 'MEASURED' : 'UNMEASURED',
211
+ failure,
212
+ unmeasuredReasons: reasons,
213
+ };
98
214
  }
99
215
 
100
216
  /**
101
217
  * Check a single workflow-state.json file for gate failures.
218
+ *
219
+ * Returns a reason rather than `null` whenever the file is present but could
220
+ * not be read as a workflow state — see the module docstring for the six
221
+ * inputs that used to come back as a clean run.
102
222
  */
103
- function checkWorkflowFile(wfPath: string, slug: string): WorkflowGateFailure | null {
104
- if (!existsSync(wfPath)) return null;
223
+ function checkWorkflowFile(wfPath: string, slug: string): FileReading {
224
+ // Genuinely absent: this issue simply has no state yet.
225
+ if (!existsSync(wfPath)) return READABLE;
105
226
 
227
+ let wf: unknown;
106
228
  try {
107
- const wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
108
- if (wf.phase === 'DONE') return null;
229
+ wf = JSON.parse(readFileSync(wfPath, 'utf-8'));
230
+ } catch (err) {
231
+ return { failure: null, unmeasured: `${wfPath}: could not be read as JSON (${err})` };
232
+ }
233
+
234
+ // A workflow state is always an object. An array, a null or a scalar is a
235
+ // reading that could not be taken, and throws nothing on the way past.
236
+ if (!isPlainObject(wf)) {
237
+ return {
238
+ failure: null,
239
+ unmeasured: `${wfPath}: parsed to ${Array.isArray(wf) ? 'an array' : typeof wf}, not a workflow state object`,
240
+ };
241
+ }
109
242
 
110
- const gates = wf.gates || {};
111
- for (const gateName of ['scope', 'verify', 'ship']) {
243
+ try {
244
+ if (wf.phase === 'DONE') return READABLE;
245
+
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
+ }>;
250
+ // #1137: the registry, not a second copy of it. This list and
251
+ // GateResultProtection's agreed on every input anyone had, so nothing
252
+ // could go red when they diverged.
253
+ for (const gateName of BLOCKING_GATES) {
112
254
  const gate = gates[gateName];
113
255
  if (gate?.result === 'FAIL' && Array.isArray(gate.failures) && gate.failures.length > 0) {
114
256
  const acs = Array.isArray(wf.acs) ? wf.acs : [];
@@ -116,22 +258,27 @@ function checkWorkflowFile(wfPath: string, slug: string): WorkflowGateFailure |
116
258
  (ac: { type?: string; verdict?: string }) => ac.type === 'OUTCOME' && ac.verdict === 'FAIL',
117
259
  );
118
260
  return {
119
- gate: gateName,
120
- issue: wf.issue,
121
- slug: wf.slug || slug,
122
- failures: gate.failures.map(
123
- (f: { check?: string; id?: string; detail?: string; message?: string }) => ({
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 => ({
124
267
  check: f.check || f.id || 'unknown',
125
268
  detail: f.detail || f.message || JSON.stringify(f),
126
- }),
127
- ),
128
- hasOutcomeAcFailure,
269
+ })),
270
+ hasOutcomeAcFailure,
271
+ },
129
272
  };
130
273
  }
131
274
  }
132
- } catch { /* skip malformed */ }
275
+ } catch (err) {
276
+ // Nothing above should throw now that the shape is checked first — so if
277
+ // one does, that is an unread state, not a clean one. Refuse, don't skip.
278
+ return { failure: null, unmeasured: `${wfPath}: could not be interpreted (${err})` };
279
+ }
133
280
 
134
- return null;
281
+ return READABLE;
135
282
  }
136
283
 
137
284
  /**
@@ -290,8 +437,55 @@ export function logEnforcementSignal(
290
437
  });
291
438
  }
292
439
 
440
+ /**
441
+ * What an agent is told when the gate state cannot be read. It names the
442
+ * artifact, the reason, and the one command that can repair it — a refusal
443
+ * with no way out is a denial of service, not a guard.
444
+ */
445
+ export function unmeasuredStateReason(reasons: string[]): string {
446
+ return [
447
+ 'UNMEASURED: the harness gate state could not be read, so whether a gate is ' +
448
+ 'currently FAILing is unknown — and an unknown is not a pass.',
449
+ ...reasons.map(r => ` - ${r}`),
450
+ '',
451
+ 'Repair the state, then retry. workflow-state.json is not directly writable ' +
452
+ '(WorkflowStateGuard); go through the validating writer:',
453
+ ' bun -e "import {writeWorkflowState} from \'./gates/orchestrator.ts\'; ' +
454
+ 'writeWorkflowState(\'WORK_DIR/workflow-state.json\', STATE);"',
455
+ '',
456
+ 'Bash, Read and Edit are not blocked — only Skill calls are, so the repair ' +
457
+ 'above is reachable right now.',
458
+ ].join('\n');
459
+ }
460
+
293
461
  export function runGateEnforcement(input: GateEnforcementInput): GateEnforcementResult {
294
- const wfFailure = findWorkflowGateFailure(input.workDir);
462
+ const scan = findWorkflowGateFailure(input.workDir);
463
+ const wfFailure = scan.failure;
464
+
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);
471
+ logSignal(input.signalsDir, input.signalsFile, {
472
+ ts: new Date().toISOString(),
473
+ type: 'gate_enforcement',
474
+ reading: 'UNMEASURED',
475
+ tool: input.toolName,
476
+ action: input.toolName === 'Skill' ? 'block' : 'nag',
477
+ reasons: scan.unmeasuredReasons,
478
+ });
479
+
480
+ if (input.toolName === 'Skill') {
481
+ return { stdout: JSON.stringify({ decision: 'block', reason }), action: 'block' };
482
+ }
483
+ return {
484
+ stdout: ['<system-reminder>', `⚠️ ${reason}`, '</system-reminder>'].join('\n'),
485
+ action: 'nag',
486
+ };
487
+ }
488
+
295
489
  if (!wfFailure) {
296
490
  if (existsSync(input.pendingFile)) {
297
491
  try {
@@ -0,0 +1,72 @@
1
+ /**
2
+ * Gate names, and the two different questions people ask about them (#1137).
3
+ *
4
+ * A LEAF module with no imports, so there is one thing to mutate and every
5
+ * tree can reach it — `hooks/` and `gates/` both import from `lib/`, and
6
+ * `lib/` is in `package.json` `files[]` while `gates/` is not, so this is the
7
+ * only directory a published hook may take a gate name from.
8
+ *
9
+ * ## Why there are two lists and not one
10
+ *
11
+ * The first draft of this file had one, `PROTECTED_GATES`, and used it as the
12
+ * guard's allowlist. A review round found that wrong twice over, and both
13
+ * corrections are worth keeping:
14
+ *
15
+ * 1. The list was INCOMPLETE. `gates/gate-executor.ts` calls
16
+ * `writeGateResult(sf, "merge", …)`, `(sf, "gaps", …)` and the dynamic
17
+ * `(sf, gate, …)` that `prove` reaches, so `gates.merge.result`,
18
+ * `gates.gaps.result` and `gates.prove.result` are all persisted and none
19
+ * of them was guarded. None is visible to a `gates\.[a-z]+` grep, because
20
+ * the name arrives as a function ARGUMENT and the write is
21
+ * `state.gates[gate] = …`.
22
+ * 2. An enumerated allowlist on a security boundary is correct exactly until
23
+ * someone adds a gate, and nothing makes the next person update it.
24
+ *
25
+ * So the guard no longer reads a list at all. `lib/gate-result-protection.ts`
26
+ * blocks a `result` under ANY key of `gates`, which cannot go stale — the
27
+ * question "is the list complete?" stops being askable. Neither list below is
28
+ * the guard's allowlist, and adding a name to either must never be required
29
+ * to make the guard see a new gate.
30
+ */
31
+
32
+ /**
33
+ * Gates whose FAIL blocks an agent, in the priority order
34
+ * `findWorkflowGateFailure` reports them: scope, then verify, then ship.
35
+ *
36
+ * NOT a security boundary and NOT the set of gates that record a result —
37
+ * `merge`, `prove` and `gaps` record results and are deliberately absent.
38
+ * `gaps` is WARN-only and is passed `fails = 0` unconditionally, so it can
39
+ * never be a blocking failure; `merge` and `prove` run after the ship gate
40
+ * has already decided. Widening this list would start nagging agents about
41
+ * gates that are not theirs to fix.
42
+ *
43
+ * Consumed by `lib/gate-enforcement.ts`.
44
+ */
45
+ export const BLOCKING_GATES = ['scope', 'verify', 'ship'] as const;
46
+
47
+ export type BlockingGate = (typeof BLOCKING_GATES)[number];
48
+
49
+ /**
50
+ * Every gate name `writeGateResult` is called with, so every key that can
51
+ * appear under `gates` carrying a `result`.
52
+ *
53
+ * **This is a TEST POPULATION, not an allowlist.** Nothing in the guard reads
54
+ * it. `test/gate-name-registry.test.ts` asserts the gate-agnostic guard
55
+ * refuses a forged result for every name here, so adding a name STRENGTHENS
56
+ * the evidence and forgetting to add one cannot weaken the guard. That
57
+ * direction is the whole point: a list that can only make the test weaker by
58
+ * omission is safe to leave slightly stale, and an allowlist is not.
59
+ *
60
+ * Derived 2026-10-22 from the `writeGateResult` call sites in
61
+ * `gates/gate-executor.ts` and the argument vocabulary in `gates/run-gate.ts`.
62
+ */
63
+ export const RESULT_BEARING_GATES = [
64
+ 'scope',
65
+ 'verify',
66
+ 'ship',
67
+ 'merge',
68
+ 'prove',
69
+ 'gaps',
70
+ ] as const;
71
+
72
+ export type ResultBearingGate = (typeof RESULT_BEARING_GATES)[number];