rungate 0.7.0 → 0.8.1

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 (108) 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/ActionVerificationGate.hook.ts +96 -0
  39. package/hooks/AgentBriefGuard.hook.ts +38 -0
  40. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  41. package/hooks/AutoVerifyGate.hook.ts +79 -0
  42. package/hooks/BashToolGuard.hook.ts +65 -0
  43. package/hooks/BashWriteGuard.hook.ts +60 -0
  44. package/hooks/CommitEnforcement.hook.ts +130 -0
  45. package/hooks/DocHygiene.hook.ts +148 -0
  46. package/hooks/GateEnforcement.hook.ts +58 -0
  47. package/hooks/GateResultProtection.hook.ts +95 -0
  48. package/hooks/HarnessAFKGate.hook.ts +85 -0
  49. package/hooks/HookCurrency.hook.ts +99 -0
  50. package/hooks/IssueCloseGuard.hook.ts +149 -0
  51. package/hooks/MergeGuard.hook.ts +58 -0
  52. package/hooks/PostCompact.hook.ts +60 -0
  53. package/hooks/ProjectStateSync.hook.ts +103 -0
  54. package/hooks/SkillGuard.hook.ts +69 -0
  55. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  56. package/hooks/SpecSCGuard.hook.ts +123 -0
  57. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  58. package/hooks/TaskCompleted.hook.ts +51 -0
  59. package/hooks/TeamInit.hook.ts +85 -0
  60. package/hooks/TestSuiteGuard.hook.ts +70 -0
  61. package/hooks/TestSuiteRelease.hook.ts +85 -0
  62. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  63. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  64. package/hooks/WorkflowStateGuard.hook.ts +64 -0
  65. package/hooks/lib/agent-config.json +9 -0
  66. package/hooks/lib/agentDetection.ts +201 -0
  67. package/hooks/lib/comment-template.ts +86 -0
  68. package/hooks/lib/findWorkflow.ts +101 -0
  69. package/hooks/lib/parseStdin.ts +37 -0
  70. package/hooks/lib/paths.ts +111 -0
  71. package/hooks/lib/utils.ts +338 -0
  72. package/lib/affected-tests.ts +29 -0
  73. package/lib/bash-write-guard.ts +627 -0
  74. package/lib/branch-cleanup.ts +279 -7
  75. package/lib/config-trackable.ts +9 -0
  76. package/lib/distribution-currency.ts +55 -5
  77. package/lib/failure-intake.ts +7 -1
  78. package/lib/gate-enforcement.ts +360 -38
  79. package/lib/gate-names.ts +72 -0
  80. package/lib/gate-result-protection.ts +437 -0
  81. package/lib/generators/code-map.ts +55 -4
  82. package/lib/generators/types.ts +27 -1
  83. package/lib/intake-sources.ts +380 -0
  84. package/lib/js-top-level-code.ts +20 -2
  85. package/lib/junit-checks.ts +239 -1
  86. package/lib/late-env-spawn.ts +331 -0
  87. package/lib/launch-base.ts +128 -5
  88. package/lib/package-closure.ts +114 -0
  89. package/lib/paths.ts +96 -3
  90. package/lib/phase2-decomposition.ts +1 -1
  91. package/lib/published-artifact.ts +162 -18
  92. package/lib/sc-id-cross-tree.ts +84 -8
  93. package/lib/scaffold/ai-review-findings.ts +149 -4
  94. package/lib/scaffold/ai-review-step.ts +1006 -132
  95. package/lib/scaffold/defaults.ts +82 -1
  96. package/lib/scaffold/steps.ts +642 -54
  97. package/lib/scanner.ts +4 -2
  98. package/lib/security-verdict.ts +1 -1
  99. package/lib/shell-path-interpolation.ts +594 -0
  100. package/lib/text-dependents.ts +875 -0
  101. package/lib/transcript-checker.ts +6 -0
  102. package/lib/workflow-security.ts +29 -0
  103. package/lib/workflow-taint.ts +732 -0
  104. package/lib/worktree-cleanup.ts +65 -38
  105. package/lib/worktree-repo.ts +32 -2
  106. package/package.json +4 -1
  107. package/scripts/check-installed-hook-currency.ts +825 -0
  108. package/scripts/generate-code-map.ts +13 -8
@@ -0,0 +1,338 @@
1
+ import { readdirSync, readFileSync, existsSync, statSync } from 'fs';
2
+ import { join } from 'path';
3
+
4
+ export const WORK_DIR = join(process.env.RUNGATE_WORK_DIR || process.env.HOME!, '.rungate');
5
+ export const HARNESS_ROOT = process.env.HARNESS_ROOT || join(process.env.HOME!, 'Projects', 'rungate');
6
+
7
+ export interface HookInput {
8
+ tool_name?: string;
9
+ tool_input?: { command?: string; name?: string; subagent_type?: string; prompt?: string; [k: string]: unknown };
10
+ tool_response?: { output?: string; content?: string; [k: string]: unknown } | string;
11
+ session_id?: string;
12
+ /**
13
+ * The working directory the tool call was made from.
14
+ *
15
+ * Typed because #239 depends on it: sub-agent Bash calls reach the hooks
16
+ * carrying the PARENT session's id, so `session_id` cannot tell two sibling
17
+ * agents apart. Each runs in its own worktree, so the cwd can.
18
+ */
19
+ cwd?: string;
20
+ [k: string]: unknown;
21
+ }
22
+
23
+ export async function parseHookInput(timeoutMs = 2000): Promise<HookInput | null> {
24
+ try {
25
+ const raw = await Promise.race([
26
+ Bun.stdin.text(),
27
+ new Promise<string>((_, reject) => setTimeout(() => reject(new Error('timeout')), timeoutMs)),
28
+ ]);
29
+ if (!raw?.trim()) return null;
30
+ return JSON.parse(raw) as HookInput;
31
+ } catch { return null; }
32
+ }
33
+
34
+ const AGENT_CONFIG: Record<string, { match: string[]; exclude: string[] }> = {
35
+ marcus: { match: ['marcus', 'engineer', 'marcus webb'], exclude: ['council'] },
36
+ quinn: { match: ['quinn', 'qatester', 'quinn torres'], exclude: [] },
37
+ rook: { match: ['rook', 'pentester', 'rook blackburn'], exclude: [] },
38
+ };
39
+
40
+ export function detectAgent(toolInput: { name?: string; subagent_type?: string; prompt?: string }): { key: string; name: string } | null {
41
+ const name = (toolInput.name || '').toLowerCase();
42
+ const type = (toolInput.subagent_type || '').toLowerCase();
43
+ const prompt = (toolInput.prompt || '').toLowerCase();
44
+ for (const [key, cfg] of Object.entries(AGENT_CONFIG)) {
45
+ if (cfg.exclude.some(ex => prompt.includes(ex))) continue;
46
+ if (cfg.match.some(p => name.includes(p) || type === p || prompt.includes(p)))
47
+ return { key, name: toolInput.name || key };
48
+ }
49
+ return null;
50
+ }
51
+
52
+ export interface WorkflowResult { path: string; data: any; slug: string }
53
+
54
+ export function findWorkflowState(issueNum?: string, phases?: string[]): WorkflowResult | null {
55
+ if (!existsSync(WORK_DIR)) return null;
56
+ const validPhases = phases || ['BUILD', 'VERIFY', 'SCOPE', 'SHIP', 'DONE'];
57
+ const candidates: (WorkflowResult & { mtime: number })[] = [];
58
+
59
+ const collect = (wfPath: string, slug: string) => {
60
+ if (!existsSync(wfPath)) return;
61
+ try {
62
+ const data = JSON.parse(readFileSync(wfPath, 'utf-8'));
63
+ if (!validPhases.includes(data.phase)) return;
64
+ candidates.push({ path: wfPath, data, slug, mtime: statSync(wfPath).mtimeMs });
65
+ } catch {}
66
+ };
67
+
68
+ try {
69
+ for (const d of readdirSync(WORK_DIR, { withFileTypes: true }).filter(d => d.isDirectory())) {
70
+ collect(join(WORK_DIR, d.name, 'workflow-state.json'), d.name);
71
+ try {
72
+ for (const sd of readdirSync(join(WORK_DIR, d.name), { withFileTypes: true }).filter(sd => sd.isDirectory()))
73
+ collect(join(WORK_DIR, d.name, sd.name, 'workflow-state.json'), `${d.name}/${sd.name}`);
74
+ } catch {}
75
+ }
76
+ } catch {}
77
+
78
+ if (!candidates.length) return null;
79
+ if (issueNum) {
80
+ const match = candidates.find(c => String(c.data.issue) === issueNum);
81
+ return match ? { path: match.path, data: match.data, slug: match.slug } : null;
82
+ }
83
+ candidates.sort((a, b) => b.mtime - a.mtime);
84
+ return { path: candidates[0].path, data: candidates[0].data, slug: candidates[0].slug };
85
+ }
86
+
87
+ export function extractIssueNumber(text: string): string | undefined {
88
+ return text.match(/#(\d+)/)?.[1];
89
+ }
90
+
91
+ /**
92
+ * The `owner/name` a `gh` command targets, or undefined if it names none.
93
+ *
94
+ * Split out of IssueCloseGuard (#140) so it can be tested without driving the
95
+ * hook, and because HOOK-ARCHITECTURE-SPEC wants the logic in lib rather than
96
+ * in the trigger.
97
+ *
98
+ * The previous pattern was `--repo\s+(\S+)`, which ran to the next space and
99
+ * so captured whatever punctuation followed — `owner/name"}}'` when the close
100
+ * appeared inside a nested shell string. The lookup then 404'd on the mangled
101
+ * slug. That was harmless while the guard swallowed errors; now that an
102
+ * unreadable label set blocks the close, a sloppy parse refuses legitimate
103
+ * work. Match the slug's shape and stop.
104
+ *
105
+ * This parses a command string to infer what `gh` will do, which is a
106
+ * differential by construction: anywhere the two disagree, the guard checks
107
+ * one repository's labels and `gh` closes an issue in another. Three
108
+ * disagreements were found by checking against the real binary rather than
109
+ * assuming, and all three are closed here:
110
+ *
111
+ * gh issue view 23 --repo a/pai-config --repo b/pai-harness -> LAST wins
112
+ * gh issue view 23 -R b/pai-harness -> `-R` is a real alias
113
+ * GH_REPO=b/pai-harness gh issue view 23 -> env is honoured
114
+ *
115
+ * The first was a guard bypass: taking the first occurrence let
116
+ * `--repo unprotected/x --repo protected/y` be vetted against `unprotected/x`
117
+ * and closed in `protected/y`.
118
+ */
119
+ export type CloseTarget =
120
+ | { kind: "none" }
121
+ | { kind: "ambiguous"; reason: string }
122
+ | { kind: "one"; issue: string; repo?: string };
123
+
124
+ /**
125
+ * What a command closes, or a refusal to guess.
126
+ *
127
+ * Inferring a `gh` invocation by regex over an arbitrary shell string is a
128
+ * parser differential by construction: wherever this disagrees with the shell
129
+ * and with `gh`, the guard vets one issue's labels while another issue gets
130
+ * closed. Three rounds of security review found three such disagreements in
131
+ * three successive versions of this parser, which is the signal to stop
132
+ * tightening the pattern and change what the pattern is FOR.
133
+ *
134
+ * So the parse no longer decides *what to check*. It decides *whether the
135
+ * command is simple enough to check at all*. Anything with more than one
136
+ * close, a command separator, a substitution, or a flag value this cannot
137
+ * read literally is reported ambiguous, and the caller blocks. Detection
138
+ * stays deliberately over-broad because its failure mode is now a refusal
139
+ * rather than a wave-through.
140
+ *
141
+ * The bypass that forced this: `closeMatch` took the FIRST issue number while
142
+ * the repo scan took the LAST slug, so
143
+ *
144
+ * gh issue close 1 --repo unprotected/x; gh issue close 99 --repo protected/y
145
+ *
146
+ * vetted issue 1 against protected/y and closed 99 in it. No amount of
147
+ * regex care fixes that class; refusing to answer does.
148
+ */
149
+ /** A `gh issue close` anywhere in a segment, with nothing required after it. */
150
+ const GH_CLOSE = /\bgh\b.*?\bissue\b.*?\bclose\b/;
151
+
152
+ /**
153
+ * The harness's own close path, added by #137.
154
+ *
155
+ * Moving workflow steps onto `scripts/github-op.ts` would otherwise have
156
+ * walked every automated close straight around this guard — the detector
157
+ * above looks for `gh`, and the new path is `bun scripts/github-op.ts
158
+ * issue-update --issue N --state closed`. A control that stops applying to
159
+ * the caller it was written for is worse than no control, because the report
160
+ * still says it ran.
161
+ */
162
+ const OP_CLOSE = /github-op\.ts\s+issue-update\b[^\n]*--state[\s=]+['"]?closed\b/;
163
+
164
+ const CLOSE_INVOCATION = new RegExp(`${GH_CLOSE.source}|${OP_CLOSE.source}`);
165
+
166
+ /** `https://github.com/owner/name/issues/123`, which `gh` accepts in place of a number. */
167
+ // Host-anchored. `[^\\s"'`]*?github\\.com` matched the literal anywhere in
168
+ // the URL, so https://evil.example/github.com/a/b/issues/1 yielded a/b — a
169
+ // repository gh would never have touched. Userinfo and the www. prefix are
170
+ // the only things allowed before the host.
171
+ const ISSUE_URL = /https?:\/\/(?:[^/@\s]*@)?(?:www\.)?github\.com\/([A-Za-z0-9._-]+)\/([A-Za-z0-9._-]+)\/issues\/(\d+)/;
172
+
173
+ export function parseCloseTarget(command: string, env: NodeJS.ProcessEnv = process.env): CloseTarget {
174
+ // Detection is deliberately loose and requires NOTHING after `close`. The
175
+ // previous version demanded `close\s+(\d+)`, so `gh issue close --repo a/b 23`
176
+ // — flag first, number last, which gh accepts — matched nothing, returned
177
+ // "no close here", and the guard stepped aside entirely. A detector that
178
+ // can under-match is a bypass; a detector that over-matches is at worst an
179
+ // inconvenient refusal.
180
+ if (!CLOSE_INVOCATION.test(command)) return { kind: "none" };
181
+
182
+ const ambiguous = (reason: string): CloseTarget => ({ kind: "ambiguous", reason });
183
+
184
+ // Indirection that cannot be resolved from the source text. `gh` acts on
185
+ // the expanded command; we only ever see what was typed.
186
+ if (/\$\(|`|\$\{/.test(command)) return ambiguous("a command substitution makes the target unreadable — run the close on its own");
187
+ if (/\beval\b/.test(command)) return ambiguous("an eval makes the target unreadable — run the close on its own");
188
+
189
+ // Split on separators rather than rejecting them outright, so an ordinary
190
+ // `cd somewhere && gh issue close 23 --repo a/b` still gets vetted. Exactly
191
+ // one segment may be closing an issue: two let the issue number from one be
192
+ // paired with the repository from the other, which is the bypass that
193
+ // prompted all of this.
194
+ const closing = command.split(/[;|&\n]+/).filter(s => CLOSE_INVOCATION.test(s));
195
+ if (closing.length !== 1) {
196
+ return ambiguous(`${closing.length} issue closes in one command — run them separately so each can be checked`);
197
+ }
198
+ const segment = closing[0];
199
+
200
+ // The github-op form is parsed on its own terms rather than squeezed
201
+ // through the gh rules below. Its grammar is strictly `--flag value`, with
202
+ // no positional issue number and no URL form, so none of the ambiguity the
203
+ // gh path has to reason about exists here — and reusing those rules would
204
+ // have been a fourth parser differential waiting to happen.
205
+ if (OP_CLOSE.test(segment)) {
206
+ // No GH_REPO fallback: scripts/github-op.ts requires --repo and does not
207
+ // read the environment, so inheriting one here would vet a repository the
208
+ // command is not going to touch.
209
+ const repo = parseRepoSlug(segment, {} as NodeJS.ProcessEnv);
210
+ if (!repo) {
211
+ return ambiguous("github-op needs a literal --repo owner/name so the close can be checked");
212
+ }
213
+ // Last wins, matching the script's own flag parsing, where a repeated
214
+ // flag overwrites the earlier value.
215
+ const issues = [...segment.matchAll(/--issue[\s=]+['"]?([^\s'"]+)/g)];
216
+ const last = issues.length ? issues[issues.length - 1][1] : undefined;
217
+ if (!last || !/^\d+$/.test(last)) {
218
+ return ambiguous("the --issue value is not a literal number — pass it literally so it can be checked");
219
+ }
220
+ return { kind: "one", issue: last, repo };
221
+ }
222
+
223
+ // An inline or exported GH_REPO is honoured by gh and invisible to the
224
+ // regex below, which matches only --repo/-R. Measured: with the session's
225
+ // GH_REPO set to this repo, `GH_REPO=unprotected/x gh issue close 23`
226
+ // resolved to this repo while gh would have closed it in unprotected/x.
227
+ // Reading the assignment properly means tracking shell variable scope, so
228
+ // refuse instead — the operator can pass --repo.
229
+ //
230
+ // Tested against the WHOLE command, not the closing segment. The first
231
+ // version checked the segment and so caught the inline-prefix form while
232
+ // missing the natural one: `export GH_REPO=unprotected/x && gh issue close
233
+ // 23` splits on `&&`, and the closing segment contains no assignment at
234
+ // all. A control that only covers the awkward spelling is not a control.
235
+ //
236
+ // Only when the close names no repository of its own. An explicit
237
+ // --repo/-R beats GH_REPO in gh too, so there is no differential left to
238
+ // refuse, and refusing anyway would block an ordinary command that happens
239
+ // to set the variable for an earlier step. Deliberately NOT parseRepoSlug's
240
+ // env-aware form — the environment is exactly what is in question here.
241
+ if (/\bGH_REPO=/.test(command) && !parseRepoSlug(segment, {} as NodeJS.ProcessEnv)) {
242
+ return ambiguous("GH_REPO is being set inside the command, which the guard cannot follow — pass --repo owner/name instead");
243
+ }
244
+
245
+ // A URL carries its own owner/name, which overrides --repo. If both are
246
+ // present and disagree, we cannot tell which gh will use.
247
+ //
248
+ // It counts only when it IS the thing being closed. Matching it anywhere in
249
+ // the segment meant a URL in a `--comment` body took over the whole target:
250
+ //
251
+ // gh issue close 99 --comment "see https://github.com/unprotected/x/issues/1"
252
+ // => { issue: '1', repo: 'unprotected/x' }
253
+ //
254
+ // The guard then read #1's labels in a repository nobody named while gh
255
+ // closed #99 here, and an unlabelled decoy was enough to permit the close
256
+ // of a protected issue. It needed no attacker: an ordinary dedup close
257
+ // links the duplicate. The `direct` branch below already says the
258
+ // positional number "is unambiguous even when other digits appear in a
259
+ // comment body" — the intent was written down and the match order defeated
260
+ // it.
261
+ //
262
+ // A stray URL is refused rather than ignored. Ignoring handles the comment
263
+ // case but not `gh issue close --repo a/b https://github.com/c/d/issues/5`,
264
+ // where the URL is the real target, is not positional because a flag comes
265
+ // first, and the number heuristic would then pair issue 5 with repo a/b.
266
+ const flagRepo = parseRepoSlug(segment, env);
267
+ const positional = segment.match(/\bclose\b\s+['"]?([^\s'"]+)/)?.[1];
268
+ const positionalUrl = positional ? positional.match(ISSUE_URL) : null;
269
+ if (positionalUrl) {
270
+ const urlRepo = `${positionalUrl[1]}/${positionalUrl[2]}`;
271
+ if (flagRepo && flagRepo !== urlRepo) {
272
+ return ambiguous("the issue URL and --repo name different repositories — pass one of them");
273
+ }
274
+ return { kind: "one", issue: positionalUrl[3], repo: urlRepo };
275
+ }
276
+ if (ISSUE_URL.test(segment)) {
277
+ return ambiguous("an issue URL appears but is not the issue being closed — pass the issue number right after `close`, or the URL as the only argument");
278
+ }
279
+
280
+ // A flag is present but its value is not a literal slug (`--repo "$REPO"`).
281
+ // Defaulting here would vet an entirely different repository.
282
+ if (/(?:--repo|-R)[\s=]/.test(segment) && !flagRepo) {
283
+ return ambiguous("the --repo value is not a literal owner/name — pass it literally so it can be checked");
284
+ }
285
+
286
+ // Prefer the number immediately after `close`, which is the ordinary form
287
+ // and is unambiguous even when other digits appear in a comment body.
288
+ const direct = segment.match(/\bclose\b\s+['"]?#?(\d+)\b/);
289
+ if (direct) return { kind: "one", issue: direct[1], repo: flagRepo };
290
+
291
+ // Otherwise gh is taking the number from somewhere later in the line. Only
292
+ // act when exactly one candidate exists; guessing between several is how
293
+ // the wrong issue gets vetted.
294
+ const after = segment.slice(segment.search(/\bclose\b/));
295
+ const numbers = [...new Set((after.match(/(?<![\w/.-])#?(\d+)\b/g) || []).map(n => n.replace("#", "")))];
296
+ if (numbers.length === 1) return { kind: "one", issue: numbers[0], repo: flagRepo };
297
+ return ambiguous(
298
+ numbers.length === 0
299
+ ? "no issue number could be read from the command — pass it directly after `close`"
300
+ : `several numbers could be the issue (${numbers.join(", ")}) — put the issue number directly after \`close\``,
301
+ );
302
+ }
303
+
304
+ export function parseRepoSlug(command: string, env: NodeJS.ProcessEnv = process.env): string | undefined {
305
+ // Global, and keep the last — `gh` lets a later flag override an earlier one.
306
+ const matches = [...command.matchAll(/(?:--repo|-R)[\s=]+['"]?([A-Za-z0-9._-]+\/[A-Za-z0-9._-]+)/g)];
307
+ const explicit = matches.length ? matches[matches.length - 1][1] : undefined;
308
+ // `gh` falls back to GH_REPO when no flag is given.
309
+ const slug = explicit ?? env.GH_REPO?.trim();
310
+ if (!slug) return undefined;
311
+
312
+ // `[A-Za-z0-9._-]+` admits `.` and `..`, so `--repo ../..` parsed as a slug
313
+ // and reached Octokit, which built `/repos/../../issues/N` and issued it —
314
+ // the request normalises to a different endpoint entirely. Observed: the
315
+ // guard answering "Not Found - https://docs.github.com/rest" for a crafted
316
+ // `--repo`. A GET with the operator's own token is a small prize, but a
317
+ // relative segment is never part of a real `owner/name`, so refuse it.
318
+ const parts = slug.split("/");
319
+ if (parts.length !== 2) return undefined;
320
+ if (parts.some(seg => !seg || seg === "." || seg === ".." || !/^[A-Za-z0-9._-]+$/.test(seg))) {
321
+ return undefined;
322
+ }
323
+ return slug;
324
+ }
325
+
326
+ /**
327
+ * Strip credential-shaped substrings from text that is about to be printed.
328
+ *
329
+ * Hook output lands in transcripts and, downstream, in issue comments. An API
330
+ * error can carry the request URL, and a base URL given as
331
+ * `https://user:token@host` would put a secret somewhere durable. Cheap
332
+ * insurance at the one place that prints an upstream error verbatim (#140).
333
+ */
334
+ export function redactSecrets(text: string): string {
335
+ return String(text)
336
+ .replace(/\b(gh[pousr]_|github_pat_)[A-Za-z0-9_]+/g, "$1[REDACTED]")
337
+ .replace(/\/\/[^/@\s]+:[^/@\s]+@/g, "//[REDACTED]@");
338
+ }
@@ -44,6 +44,35 @@ export const SELECTABLE_SOURCE = /\.(ts|tsx|js|jsx|mts|cts)$/;
44
44
  /** A test file, by the convention this repo uses everywhere. */
45
45
  export const TEST_FILE = /\.test\.(ts|tsx)$/;
46
46
 
47
+ /**
48
+ * The shape a path is allowed to have before it may be PRINTED as part of a
49
+ * `bun test …` selection.
50
+ *
51
+ * Every selector here writes its answer to stdout and a caller interpolates
52
+ * it into a shell command unquoted, because word-splitting is how a list
53
+ * becomes arguments. Rather than trust that a tree walk produced inert
54
+ * paths, anything outside this alphabet refuses the whole selection. The
55
+ * injection surface is removed by construction rather than by assuming the
56
+ * walk is well-behaved.
57
+ *
58
+ * **It lives here, next to `TEST_FILE`, because there is now more than one
59
+ * producer.** It was a `const` inside `scripts/select-affected-tests.ts`
60
+ * until `scripts/text-dependents.ts` (#1054) began emitting into the same
61
+ * composition without it — a guard that one of two producers applies is a
62
+ * guard with a hole, and the hole is invisible from either file. Copying
63
+ * the pattern into the second producer would have made it two deciders that
64
+ * agree, which `.claude/rules/checks-must-be-able-to-fail.md` names as a
65
+ * shape where mutating either leaves the other holding the case up. One
66
+ * binding, both importers, and `test/selection-path-safety.test.ts` fails
67
+ * if a third producer declares its own.
68
+ *
69
+ * The shape of the defect is worth naming, because it is the shape of the
70
+ * issue that introduced it: #1054 is about a dependency expressed in a
71
+ * syntax the checker did not know, and this was the same thing one level
72
+ * up — a validation expressed in one of two producers.
73
+ */
74
+ export const SAFE_TEST_PATH = /^[A-Za-z0-9._/-]+\.test\.tsx?$/;
75
+
47
76
  /**
48
77
  * Directories walked when building the graph.
49
78
  *