rungate 0.6.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 (113) 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 +81 -16
  5. package/lib/behavioral-cache.ts +150 -2
  6. package/lib/branch-protection.ts +790 -0
  7. package/lib/brief-ac-alignment.ts +104 -0
  8. package/lib/brief-references.ts +205 -0
  9. package/lib/bun-version.ts +93 -14
  10. package/lib/check-remedy.ts +140 -0
  11. package/lib/ci-checkout.ts +17 -0
  12. package/lib/ci-history-depth.ts +159 -0
  13. package/lib/ci-setup-step.ts +96 -0
  14. package/lib/claude-code-action.ts +85 -0
  15. package/lib/claude-tool-vocabulary.ts +188 -0
  16. package/lib/cli-commands.ts +15 -0
  17. package/lib/commit-sha.ts +42 -0
  18. package/lib/commit-subject.ts +90 -0
  19. package/lib/compliance-report.ts +377 -45
  20. package/lib/compliance.ts +191 -17
  21. package/lib/config-loader.ts +39 -1
  22. package/lib/config-trackable.ts +391 -0
  23. package/lib/conformity.ts +1087 -100
  24. package/lib/containment.ts +238 -0
  25. package/lib/content-hash.ts +24 -0
  26. package/lib/create-sc.ts +249 -16
  27. package/lib/dev-liveness.ts +180 -0
  28. package/lib/discovery-branch-points.ts +432 -0
  29. package/lib/discovery-stability.ts +481 -0
  30. package/lib/distribution-currency.ts +186 -0
  31. package/lib/doc-routing.ts +157 -0
  32. package/lib/evidence-prevalidator.ts +224 -2
  33. package/lib/evidence-satisfiability.ts +534 -12
  34. package/lib/failure-intake.ts +317 -0
  35. package/lib/fallow-availability.ts +157 -0
  36. package/lib/fs-write-capabilities.ts +232 -0
  37. package/lib/gate-run-split.ts +147 -0
  38. package/lib/generators/agents-md.ts +140 -32
  39. package/lib/git-isolation.ts +140 -0
  40. package/lib/github.ts +15 -0
  41. package/lib/google-auth-action.ts +93 -0
  42. package/lib/harness-project.ts +48 -0
  43. package/lib/harness-provenance.ts +255 -0
  44. package/lib/hook-evidence.ts +235 -0
  45. package/lib/hook-scopes.ts +386 -0
  46. package/lib/hook-target-tree.ts +398 -0
  47. package/lib/hook-trees.ts +447 -0
  48. package/lib/js-top-level-code.ts +78 -10
  49. package/lib/junit-checks.ts +52 -0
  50. package/lib/launch-base.ts +253 -0
  51. package/lib/line-citation.ts +372 -0
  52. package/lib/orphan-reaper.ts +468 -0
  53. package/lib/parity-binding.ts +205 -0
  54. package/lib/per-test-timeouts.ts +219 -0
  55. package/lib/plan-coverage.ts +151 -0
  56. package/lib/prior-branch.ts +201 -8
  57. package/lib/process-table.ts +146 -0
  58. package/lib/project-state-derivation.ts +219 -0
  59. package/lib/project-state-root.ts +258 -0
  60. package/lib/published-artifact.ts +525 -0
  61. package/lib/readdir-sorted.ts +45 -0
  62. package/lib/review-execution-reading.ts +206 -0
  63. package/lib/review-tool-agreement.ts +433 -0
  64. package/lib/rule-promotion.ts +234 -0
  65. package/lib/rule-retirement.ts +525 -0
  66. package/lib/run-branch.ts +612 -0
  67. package/lib/rungate-schema.ts +19 -0
  68. package/lib/runner-home.ts +274 -0
  69. package/lib/sc-id-cross-tree.ts +19 -7
  70. package/lib/sc-ids.ts +121 -13
  71. package/lib/sc-reservations.ts +289 -0
  72. package/lib/scaffold/ai-review-findings.ts +403 -0
  73. package/lib/scaffold/ai-review-step.ts +4661 -64
  74. package/lib/scaffold/managed-workflow.ts +587 -192
  75. package/lib/scaffold/owned-files.ts +152 -45
  76. package/lib/scaffold/pre-push-hook.ts +49 -5
  77. package/lib/scaffold/steps.ts +1413 -244
  78. package/lib/scaffold/workflow-census.ts +217 -0
  79. package/lib/scaffold/workflow-drift.ts +217 -0
  80. package/lib/scaffold/write-steps.ts +4 -0
  81. package/lib/scan-budget.ts +247 -0
  82. package/lib/scanner.ts +43 -51
  83. package/lib/scratch-roots.ts +50 -5
  84. package/lib/screenshot-discovery.ts +121 -0
  85. package/lib/screenshot-upload.ts +41 -1
  86. package/lib/secret-patterns.ts +511 -8
  87. package/lib/ship-mode.ts +219 -0
  88. package/lib/source-slice.ts +294 -0
  89. package/lib/stale-cleanup.ts +37 -3
  90. package/lib/suite-flake.ts +278 -0
  91. package/lib/suite-measurement.ts +23 -4
  92. package/lib/suite-run-reading.ts +241 -1
  93. package/lib/suite-timeout-margin.ts +193 -0
  94. package/lib/test-case-bodies.ts +883 -0
  95. package/lib/test-case-deletion.ts +653 -0
  96. package/lib/test-census.ts +97 -29
  97. package/lib/test-command-positions.ts +274 -0
  98. package/lib/test-suite-lock.ts +159 -16
  99. package/lib/tool-probe.ts +31 -9
  100. package/lib/top-level-cd.ts +393 -0
  101. package/lib/tree-entries.ts +89 -0
  102. package/lib/ts-ast.ts +200 -0
  103. package/lib/walk-test-files.ts +97 -0
  104. package/lib/workflow-actions.ts +263 -0
  105. package/lib/worktree-collect.ts +177 -5
  106. package/lib/worktree-repo.ts +36 -1
  107. package/package.json +2 -1
  108. package/scripts/ai-review-findings.ts +45 -0
  109. package/scripts/create-sc.ts +21 -1
  110. package/scripts/extract-constraints.ts +107 -7
  111. package/scripts/generate-code-map.ts +23 -30
  112. package/scripts/scaffold-project.ts +8 -1
  113. package/scripts/sync-sc-status.ts +77 -16
package/lib/tool-probe.ts CHANGED
@@ -65,6 +65,31 @@ export interface ToolProbeOptions {
65
65
  timeoutMs?: number;
66
66
  }
67
67
 
68
+ /**
69
+ * The one place that decides `available` from `outcome`.
70
+ *
71
+ * Every return below goes through it, and so does every caller that needs to
72
+ * state a reading it did not spawn — a test forcing a tool absent, a consumer
73
+ * replaying a recorded probe. Without it `available` is a field anyone can set,
74
+ * and a probe reporting `{ outcome: "absent", available: true }` would be a
75
+ * contradiction nothing could refuse. It is a projection of the reading, and
76
+ * the projection has an owner.
77
+ */
78
+ export function toolProbe(fields: {
79
+ outcome: ToolProbeOutcome;
80
+ tool: string;
81
+ exitCode?: number | null;
82
+ reason: string;
83
+ }): ToolProbe {
84
+ return {
85
+ outcome: fields.outcome,
86
+ available: fields.outcome === "available",
87
+ tool: fields.tool,
88
+ exitCode: fields.exitCode ?? null,
89
+ reason: fields.reason,
90
+ };
91
+ }
92
+
68
93
  /** The probe's own budget. A tool that cannot answer in five seconds is not ready to be used in a gate. */
69
94
  export const TOOL_PROBE_TIMEOUT_MS = 5_000;
70
95
 
@@ -88,33 +113,30 @@ export function probeExternalTool(command: string, args: string[] = [], opts?: T
88
113
  // tool is not here, and it is why this branch is not merged with a
89
114
  // non-zero exit below.
90
115
  const message = e instanceof Error ? e.message : String(e);
91
- return {
116
+ return toolProbe({
92
117
  outcome: "absent",
93
- available: false,
94
118
  tool,
95
119
  exitCode: null,
96
120
  reason: `${command} is not on PATH: ${message.split("\n")[0]}`,
97
- };
121
+ });
98
122
  }
99
123
 
100
124
  if (exitCode === 0 || stdout.trim().length > 0) {
101
- return {
125
+ return toolProbe({
102
126
  outcome: "available",
103
- available: true,
104
127
  tool,
105
128
  exitCode,
106
129
  reason: `${tool} ran and answered (exit ${exitCode})`,
107
- };
130
+ });
108
131
  }
109
132
 
110
- return {
133
+ return toolProbe({
111
134
  outcome: "errored",
112
- available: false,
113
135
  tool,
114
136
  exitCode,
115
137
  reason:
116
138
  `${tool} ran and did not succeed (exit ${exitCode})` +
117
139
  (stderr.trim() ? `: ${stderr.trim().split("\n")[0].slice(0, 200)}` : "") +
118
140
  ` — the tool was reachable, so this is not the same as it being absent`,
119
- };
141
+ });
120
142
  }
@@ -0,0 +1,393 @@
1
+ /**
2
+ * top-level-cd.ts — the decision behind TopLevelCdGuard (#992)
3
+ *
4
+ * One question: does this Bash command move the SESSION's working directory?
5
+ *
6
+ * `topLevelCdRefusal` is the only exported binding and the only decider, so
7
+ * there is one thing to mutate and one thing for a later caller to reuse —
8
+ * the grader, a conformity check, a transcript audit. A second copy of this
9
+ * parse anywhere would survive any mutation of this one and both would read
10
+ * as covered (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
11
+ *
12
+ * ## Why the question is "top level" and not "anywhere"
13
+ *
14
+ * A Bash tool call runs in a shell whose cwd PERSISTS between calls, and the
15
+ * agent runtime resolves `isolation: 'worktree'` against that directory. So a
16
+ * `cd` at the top level of one call can kill a peer agent's worktree creation
17
+ * hours later, and the failure names the session's directory rather than the
18
+ * command that moved it. A `cd` inside a subshell, a command substitution or
19
+ * a child interpreter cannot do that: the child exits and the parent's cwd is
20
+ * untouched.
21
+ *
22
+ * ## The direction this is allowed to be wrong in
23
+ *
24
+ * Toward REFUSAL. A false refusal costs one retyped command and teaches the
25
+ * habit; a false allow costs another agent half a day. Three forms are
26
+ * refused that bash would in fact fork — a pipeline element, a backgrounded
27
+ * command, and `exec cd` — because distinguishing them needs the shell's own
28
+ * semantics and the saving is one retype.
29
+ *
30
+ * An input this cannot READ is refused for the same reason and said out loud:
31
+ * a command that is absent, or not a string, has not been examined and found
32
+ * clean. See `unreadableMessage`, and the `|| ''` it replaced.
33
+ *
34
+ * ## KNOWN FALSE REFUSALS — the direction this is allowed to be wrong in
35
+ *
36
+ * A `#` comment is not parsed. `ls # cd /tmp` is allowed because `ls` is the
37
+ * segment's first token, but a comment carrying a separator —
38
+ * `make # fails; cd /x is not the fix` — splits and the tail reads as a
39
+ * top-level `cd`. Both forms are asserted in `test/top-level-cd.test.ts`.
40
+ *
41
+ * Stripping comments would fix it and was deliberately not done: a `#` inside
42
+ * `$(…)` on one line comments out the closing paren, so a stripper unbalances
43
+ * the depth counter and a later top-level `cd` falls INSIDE the unclosed
44
+ * subshell and is allowed. That trades a rare false refusal for a new
45
+ * false-allow path, which is the wrong direction.
46
+ *
47
+ * ## WHAT THIS DOES NOT COVER
48
+ *
49
+ * Every form below moves the session and is NOT refused. They are asserted as
50
+ * cases in `test/top-level-cd.test.ts` under AC-10, not merely listed here, so
51
+ * a later widening that closes one goes red rather than silently changing the
52
+ * behaviour of every session on the machine.
53
+ *
54
+ * - `eval "cd /x"` — the command is a string until the shell expands it.
55
+ * - `CMD=cd; $CMD /x` — a command built from a variable. The hook has no
56
+ * access to shell state and cannot know what `$CMD` holds.
57
+ * - A heredoc body sourced into the current shell (`source /dev/stdin <<EOF`).
58
+ * Heredoc bodies are stripped before the scan because they are data in
59
+ * every other case, and `cat <<EOF` carrying the word `cd` was a real false
60
+ * positive in the sibling guard (`lib/bash-file-read.ts`).
61
+ * - A function defined and called in one command: `goto() { cd "$1"; }; goto /x`.
62
+ * - A zsh function or alias from the user's rc — the token is not `cd` and
63
+ * nothing in the command says what it expands to.
64
+ * - A sourced script that cds: `. ./setup.sh`, `source ./setup.sh`.
65
+ * - A `trap 'cd /x' EXIT` body, which is quoted now and run later.
66
+ *
67
+ * Closing any of these needs a real shell parser plus the shell's runtime
68
+ * state. This is a habit-former, not a sandbox.
69
+ *
70
+ * Issue: #992
71
+ */
72
+
73
+ export interface CdRefusal {
74
+ /** The top-level segment that moves the shell, trimmed. */
75
+ segment: string;
76
+ /** What the caller is told, naming the alternatives. */
77
+ message: string;
78
+ }
79
+
80
+ /**
81
+ * THE refusal exit, declared once.
82
+ *
83
+ * `hooks/TopLevelCdGuard.hook.ts` emits this as its `decision` and has no
84
+ * literal of its own, so there is exactly one site to mutate and a case that
85
+ * observes a refusal can be proved to have observed THIS one
86
+ * (`.claude/rules/checks-must-be-able-to-fail.md`, *For a script whose job is
87
+ * to exit non-zero*). A second inlined `'block'` anywhere in the hook would
88
+ * survive the mutation and the case would go green having witnessed nothing —
89
+ * `test/top-level-cd.test.ts` asserts the literal appears exactly once.
90
+ */
91
+ export const CD_GUARD_DECISION = 'block';
92
+
93
+ /** Builtins that move the shell's own working directory. */
94
+ const SHELL_MOVERS = new Set(['cd', 'pushd', 'popd']);
95
+
96
+ /**
97
+ * Wrappers that delegate to the real command. `command cd /x` and
98
+ * `builtin cd /x` both run the builtin. `exec`, `time` and `nohup` are here
99
+ * for the refusal direction: they would not in fact move the parent, and
100
+ * refusing them costs one retype.
101
+ */
102
+ const PREFIXES = new Set(['command', 'builtin', 'exec', 'time', 'nohup']);
103
+
104
+ /**
105
+ * Shell keywords that can be immediately followed by a command which runs in
106
+ * the CURRENT shell. `{ … }` is a group, not a subshell — it is in this list
107
+ * deliberately, and `(` is deliberately not.
108
+ */
109
+ const LEADING_KEYWORDS = new Set([
110
+ 'if', 'then', 'elif', 'else', 'fi',
111
+ 'while', 'until', 'do', 'done',
112
+ '{', '}', '!',
113
+ ]);
114
+
115
+ /** An inline `VAR=value` assignment preceding the command. */
116
+ const ASSIGNMENT = /^[A-Za-z_][A-Za-z0-9_]*=/;
117
+
118
+ /**
119
+ * Remove heredoc bodies before scanning. A heredoc body is data, and the hook
120
+ * sees the raw command string, so `cat <<EOF > f … cd /x … EOF` would
121
+ * otherwise read as a top-level `cd` on its own line.
122
+ *
123
+ * Unlike `lib/bash-file-read.ts` this drops the body even when the feeding
124
+ * command is a shell interpreter, because `bash <<EOF` runs the body in a
125
+ * CHILD and cannot move the session. The one form that can — `source
126
+ * /dev/stdin <<EOF` — is a declared gap above.
127
+ */
128
+ function stripHeredocBodies(command: string): string {
129
+ if (!command.includes('<<')) return command;
130
+
131
+ const out: string[] = [];
132
+ let delim: string | null = null;
133
+ let allowIndent = false;
134
+
135
+ for (const line of command.split('\n')) {
136
+ if (delim !== null) {
137
+ if ((allowIndent ? line.trimStart() : line) === delim) delim = null;
138
+ continue; // drop body and terminator
139
+ }
140
+
141
+ const m = line.match(/<<(-?)\s*(['"]?)([A-Za-z_][A-Za-z0-9_]*)\2/);
142
+ if (m) {
143
+ allowIndent = m[1] === '-';
144
+ delim = m[3];
145
+ out.push(line.slice(0, m.index) + line.slice(m.index! + m[0].length));
146
+ continue;
147
+ }
148
+
149
+ out.push(line);
150
+ }
151
+
152
+ return out.join('\n');
153
+ }
154
+
155
+ /**
156
+ * Split a command into the segments that run in the CURRENT shell.
157
+ *
158
+ * Quote-, paren- and backtick-aware by necessity. A naive split tears quoted
159
+ * strings apart (`git commit -m "cd into /x"` would yield a bogus `cd into
160
+ * /x"` segment) and, worse, cannot tell `(cd /x && make)` from `cd /x &&
161
+ * make` — which is the whole distinction this module exists for.
162
+ *
163
+ * Text inside `(` … `)`, `$(` … `)` and backticks is a child process, so no
164
+ * split happens there and the enclosing segment keeps its own first token:
165
+ * `(cd /x && make)` is one segment beginning `(cd`, which is not `cd`.
166
+ *
167
+ * This is deliberately NOT `splitSegments` from `lib/bash-file-read.ts`.
168
+ * That one answers a question where depth is irrelevant — a `cat` reading a
169
+ * file reads it in a subshell too — so it tracks quotes and nothing else.
170
+ */
171
+ function topLevelSegments(command: string): string[] {
172
+ const segments: string[] = [];
173
+ let current = '';
174
+ let quote: "'" | '"' | null = null;
175
+ let depth = 0;
176
+ let backtick = false;
177
+
178
+ for (let i = 0; i < command.length; i++) {
179
+ const ch = command[i];
180
+
181
+ if (quote) {
182
+ current += ch;
183
+ if (ch === '\\' && quote === '"' && i + 1 < command.length) current += command[++i];
184
+ else if (ch === quote) quote = null;
185
+ continue;
186
+ }
187
+
188
+ if (ch === "'" || ch === '"') {
189
+ quote = ch;
190
+ current += ch;
191
+ continue;
192
+ }
193
+
194
+ if (ch === '\\' && i + 1 < command.length) {
195
+ current += ch + command[++i];
196
+ continue;
197
+ }
198
+
199
+ if (ch === '`') {
200
+ backtick = !backtick;
201
+ current += ch;
202
+ continue;
203
+ }
204
+
205
+ if (ch === '(') depth++;
206
+ else if (ch === ')') depth = Math.max(0, depth - 1);
207
+
208
+ if (depth === 0 && !backtick && (ch === '|' || ch === '&' || ch === ';' || ch === '\n')) {
209
+ if ((ch === '|' || ch === '&') && command[i + 1] === ch) i++; // consume || and &&
210
+ segments.push(current);
211
+ current = '';
212
+ continue;
213
+ }
214
+
215
+ current += ch;
216
+ }
217
+
218
+ segments.push(current);
219
+ return segments;
220
+ }
221
+
222
+ /**
223
+ * Resolve a token to the command name it invokes: quotes off, escapes off,
224
+ * directory off. `'cd'`, `\cd` and `/usr/bin/cd` all resolve to `cd`.
225
+ */
226
+ function commandName(token: string): string {
227
+ let t = token;
228
+ if (t.length > 1 && (t[0] === "'" || t[0] === '"') && t[t.length - 1] === t[0]) {
229
+ t = t.slice(1, -1);
230
+ }
231
+ t = t.replace(/\\/g, '');
232
+ return t.split('/').pop() || t;
233
+ }
234
+
235
+ /** Drop leading keywords, wrapper prefixes and inline assignments. */
236
+ function firstCommandName(segment: string): string | null {
237
+ const tokens = segment.trim().split(/\s+/).filter(Boolean);
238
+ for (const raw of tokens) {
239
+ if (ASSIGNMENT.test(raw)) continue;
240
+ const name = commandName(raw);
241
+ if (LEADING_KEYWORDS.has(name) || PREFIXES.has(name)) continue;
242
+ return name;
243
+ }
244
+ return null;
245
+ }
246
+
247
+ /**
248
+ * The refusal text. It names `git -C <path>` and the subshell form, because a
249
+ * refusal that does not say what to do instead gets worked around rather than
250
+ * obeyed — which is how this started as prose and ended as a hook.
251
+ */
252
+ function refusalMessage(segment: string): string {
253
+ return [
254
+ '#992: refusing a top-level `cd`.',
255
+ '',
256
+ `Offending segment: ${segment}`,
257
+ '',
258
+ 'A top-level `cd` moves the SESSION\'s working directory, not just this',
259
+ 'command\'s. Worktree isolation resolves against that directory, so a peer',
260
+ 'agent\'s worktree creation dies hours later with no error naming the cause.',
261
+ '',
262
+ 'Use one of these instead:',
263
+ ' git -C <path> <subcommand> — for anything git, always',
264
+ ' (cd <path> && <command>) — a subshell; the session does not move',
265
+ ' bun --cwd <path> <args> — bun',
266
+ ' make -C <path> / npm --prefix <path>',
267
+ '',
268
+ 'If the session really must move, that is a deliberate decision — say so',
269
+ 'out loud rather than reaching for `cd` by reflex.',
270
+ ].join('\n');
271
+ }
272
+
273
+ /**
274
+ * What the caller is told when the command could not be read at all.
275
+ *
276
+ * A Bash tool call always carries a command string. If one arrives without
277
+ * one, the guard has not examined a command and found it clean — it has
278
+ * examined nothing, and `0`, `{}`, `null` and silence are indistinguishable
279
+ * from success (`.claude/rules/config-access.md`). The previous shape here
280
+ * was `payload.tool_input?.command || ''`, which is that defect exactly: an
281
+ * absent command became an empty one and the guard passed over it.
282
+ */
283
+ function unreadableMessage(command: unknown): string {
284
+ return [
285
+ '#992: refusing a Bash command this guard could not read.',
286
+ '',
287
+ `Received: ${typeof command} ${JSON.stringify(command) ?? String(command)}`,
288
+ '',
289
+ 'This is UNMEASURED, not clean. The guard refuses a top-level `cd`, and it',
290
+ 'cannot tell whether this command carries one, so it refuses rather than',
291
+ 'reporting a pass it did not earn.',
292
+ '',
293
+ 'Re-send the call with a command string. If a Bash call legitimately has',
294
+ 'no command, that is a bug in the caller, not in this guard.',
295
+ ].join('\n');
296
+ }
297
+
298
+ /**
299
+ * Does this command move the session's working directory at the top level?
300
+ *
301
+ * Returns the refusal, or null when the command is clean. THE one decider:
302
+ * every caller — the hook, any future grader — asks this and nothing else.
303
+ *
304
+ * Takes `unknown` deliberately. The hook's input is JSON off a pipe, so the
305
+ * command's type is an assumption until it is checked, and the check belongs
306
+ * with the decision rather than at the call site where a `|| ''` is one
307
+ * keystroke away.
308
+ */
309
+ export function topLevelCdRefusal(command: unknown): CdRefusal | null {
310
+ if (typeof command !== 'string' || command.trim() === '') {
311
+ return { segment: '<unreadable>', message: unreadableMessage(command) };
312
+ }
313
+
314
+ for (const segment of topLevelSegments(stripHeredocBodies(command))) {
315
+ const name = firstCommandName(segment);
316
+ if (name === null) continue;
317
+ if (!SHELL_MOVERS.has(name)) continue;
318
+ const trimmed = segment.trim();
319
+ return { segment: trimmed, message: refusalMessage(trimmed) };
320
+ }
321
+ return null;
322
+ }
323
+
324
+ /**
325
+ * How loudly the guard speaks: the WARN→data→FAIL ladder
326
+ * `specs/harness-automation-matrix.md` prescribes (#992).
327
+ *
328
+ * ## Why a mode exists at all, with the number that decided it
329
+ *
330
+ * The parser is sound: **32.7% of 31,577 unique Bash commands** from this
331
+ * machine's transcript store since 2026-10-14 would be refused, with **zero
332
+ * false positives** — all three deliberate over-refusal classes clean, a
333
+ * 20-command spread hand-read and all 20 genuine, and the 245 `cd`-carrying
334
+ * commands it allows are subshells and heredoc bodies.
335
+ *
336
+ * The issue's original cost model was *"a false refusal costs one retyped
337
+ * command"*. At that rate it costs **10,332 retyped commands**, and a hook
338
+ * refusing a third of all Bash calls is the gets-disabled failure the issue
339
+ * itself warns about two paragraphs below its own recommendation. The
340
+ * premise was corrected on the issue; this is the code catching up to the
341
+ * correction.
342
+ *
343
+ * So `cd` is not an occasional lapse, it is the dominant navigation idiom,
344
+ * and most instances are harmless — a top-level `cd` costs something only in
345
+ * a session with concurrent agents holding worktrees.
346
+ *
347
+ * ## The default is `block`, and that is a decision, not a reading
348
+ *
349
+ * The paragraphs above are the argument for `warn` and they are left intact
350
+ * because they are the honest case against what this now does. **Jason took
351
+ * `block`** (#992), with the 32.7% in hand: the scoping to harnessed
352
+ * projects is the answer to "mis-scoped rather than mis-tuned", and a rung
353
+ * that costs a retype is preferred to one that costs a peer's half-day. The
354
+ * first rung of the ladder exists and was skipped deliberately.
355
+ *
356
+ * `RUNGATE_CD_GUARD=warn` and `=off` are both still reachable, so reversing
357
+ * this needs no code change — which is the property #1040 built the mode for.
358
+ *
359
+ * ## An unrecognised value is not silently a default
360
+ *
361
+ * It resolves to the default rung and the caller is TOLD which value it did
362
+ * not understand. `0`, `{}` and silence being indistinguishable from success
363
+ * is `.claude/rules/config-access.md`, and a typo'd
364
+ * `RUNGATE_CD_GUARD=blcok` degrading quietly is that shape exactly. Note the
365
+ * direction moved with the default: an unreadable value now refuses rather
366
+ * than warns, which is the same "err toward refusal" this module takes
367
+ * everywhere else.
368
+ */
369
+ export type CdGuardMode = "warn" | "block" | "off";
370
+
371
+ /** The env var selecting the rung. Absent means `block` — see above. */
372
+ export const CD_GUARD_MODE_VAR = "RUNGATE_CD_GUARD";
373
+
374
+ /**
375
+ * The rung taken when nothing selects one. Declared once so the decision is
376
+ * a single site a mutation can move, and so `cdGuardMode`'s two default
377
+ * paths — absent value and unrecognised value — cannot drift apart.
378
+ */
379
+ export const CD_GUARD_DEFAULT_MODE: CdGuardMode = "block";
380
+
381
+ export interface CdGuardModeReading {
382
+ mode: CdGuardMode;
383
+ /** Set when the configured value was not recognised, naming it. */
384
+ unrecognised?: string;
385
+ }
386
+
387
+ export function cdGuardMode(env: NodeJS.ProcessEnv = process.env): CdGuardModeReading {
388
+ const raw = env[CD_GUARD_MODE_VAR];
389
+ if (raw === undefined || raw === "") return { mode: CD_GUARD_DEFAULT_MODE };
390
+ const v = raw.trim().toLowerCase();
391
+ if (v === "warn" || v === "block" || v === "off") return { mode: v };
392
+ return { mode: CD_GUARD_DEFAULT_MODE, unrecognised: raw };
393
+ }
@@ -0,0 +1,89 @@
1
+ /**
2
+ * What a commit holds at every path, as `<mode> <type> <oid>`.
3
+ *
4
+ * Extracted from `scripts/verify-merge-content.ts` (#516) when `#640` needed
5
+ * the same reading to decide whether a run branch is safe to delete. It is
6
+ * here rather than there because `gates/` and `lib/` may not import from
7
+ * `scripts/` — that is a layering inversion — and because a second copy of
8
+ * this parse would be two deciders that agree: a mutation of either would
9
+ * leave the other answering correctly, and no behavioural test could tell
10
+ * them apart (`.claude/rules/checks-must-be-able-to-fail.md`, fourth shape).
11
+ *
12
+ * Nothing about the reading changed in the move. The two defects its
13
+ * docblock records were both measured on the first cut of the merge
14
+ * verifier and both still govern this file.
15
+ */
16
+ import { spawnSync } from "child_process";
17
+
18
+ /**
19
+ * A path a commit does not hold.
20
+ *
21
+ * `ABSENT` is a value rather than a throw because "the branch deleted this
22
+ * file" and "the comparison dropped it" are different answers and both have
23
+ * to be comparable. Swallowing the error into a `null` that also means
24
+ * "something went wrong" is how `0`, `{}` and `SKIP` become
25
+ * indistinguishable from success.
26
+ */
27
+ export const ABSENT = "ABSENT" as const;
28
+
29
+ /**
30
+ * Run git and keep BOTH streams.
31
+ *
32
+ * stderr is returned rather than discarded because git warns on stderr and
33
+ * exits 0: `multiple merge bases, using <sha>` is the one that matters to
34
+ * callers here, and it means a scope was computed against an arbitrary
35
+ * choice of base. A warning thrown away by the process that provoked it is
36
+ * the fail-open shape one layer out from the code.
37
+ */
38
+ export function gitRead(projectRoot: string, args: string[]): { out: string; err: string } {
39
+ const r = spawnSync("git", ["-C", projectRoot, ...args], {
40
+ encoding: "utf-8",
41
+ timeout: 30_000,
42
+ maxBuffer: 64 * 1024 * 1024,
43
+ });
44
+ if (r.error) throw r.error;
45
+ if (r.status !== 0) {
46
+ throw new Error(`git ${args[0]} exited ${r.status}: ${(r.stderr || "").trim().split("\n")[0]}`);
47
+ }
48
+ return { out: r.stdout ?? "", err: r.stderr ?? "" };
49
+ }
50
+
51
+ /**
52
+ * Every path a commit holds, mapped to `<mode> <type> <oid>`.
53
+ *
54
+ * **Why the whole tree, and why not `rev-parse <commit>:<path>`.** Two
55
+ * defects, both measured on the first cut of the merge verifier (#516
56
+ * review):
57
+ *
58
+ * 1. `git diff --name-only` C-quotes any path with a non-ASCII byte, a
59
+ * quote, a tab or a newline — `"caf\303\251.ts"`, quotes included. Fed
60
+ * back to `rev-parse` that string resolves on NEITHER commit, both sides
61
+ * came back ABSENT, and ABSENT equals ABSENT: a merge that dropped two
62
+ * whole files printed `2 file(s) landed as reviewed` and exited 0. The
63
+ * fix is `-z` everywhere, and then no path is ever re-parsed at all —
64
+ * these keys are raw bytes out of git, compared in JS.
65
+ * 2. `rev-parse` answers with a blob, so it cannot see a MODE. A merge that
66
+ * drops a `chmod +x` lands the identical OID at 100644, and in this repo
67
+ * a hook that loses its exec bit is silently inert. A symlink replaced
68
+ * by a regular file with the same bytes is the same hole, sharper.
69
+ *
70
+ * The value is the ls-tree triple, so a mode or type change is a divergence
71
+ * by construction rather than by a second comparison somebody has to
72
+ * remember to write.
73
+ */
74
+ export function treeEntries(projectRoot: string, commit: string): Map<string, string> {
75
+ const { out } = gitRead(projectRoot, ["ls-tree", "-r", "-z", commit]);
76
+ const entries = new Map<string, string>();
77
+ for (const record of out.split("\0")) {
78
+ if (!record) continue;
79
+ const tab = record.indexOf("\t");
80
+ if (tab === -1) continue;
81
+ entries.set(record.slice(tab + 1), record.slice(0, tab).replace(/\s+/g, " ").trim());
82
+ }
83
+ return entries;
84
+ }
85
+
86
+ /** What a tree holds at a path, or `ABSENT`. One lookup, no second decider. */
87
+ export function entryOf(tree: Map<string, string>, path: string): string {
88
+ return tree.get(path) ?? ABSENT;
89
+ }