rungate 0.3.0 → 0.4.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 (49) hide show
  1. package/lib/ac-quality.ts +119 -0
  2. package/lib/brief-precedence.ts +114 -0
  3. package/lib/ci-checkout.ts +27 -1
  4. package/lib/compliance-backfill.ts +16 -4
  5. package/lib/compliance-report.ts +109 -8
  6. package/lib/config-loader.ts +129 -5
  7. package/lib/config-readers.ts +86 -0
  8. package/lib/conformity.ts +520 -27
  9. package/lib/context-docs.ts +182 -0
  10. package/lib/create-brief.ts +22 -17
  11. package/lib/create-sc.ts +55 -33
  12. package/lib/decomposition-waves.ts +197 -0
  13. package/lib/doc-scan-targets.ts +435 -0
  14. package/lib/gate-check-audit.ts +190 -0
  15. package/lib/generators/agents-md.ts +10 -5
  16. package/lib/issue-extraction.ts +368 -0
  17. package/lib/organize.ts +129 -40
  18. package/lib/package-closure.ts +111 -0
  19. package/lib/phase2-decomposition.ts +270 -0
  20. package/lib/prior-branch.ts +24 -1
  21. package/lib/project-aliases.ts +100 -0
  22. package/lib/prove-label-gate.ts +93 -0
  23. package/lib/release-preflight.ts +225 -15
  24. package/lib/rungate-schema.ts +36 -2
  25. package/lib/sc-cover.ts +92 -1
  26. package/lib/sc-ids.ts +151 -0
  27. package/lib/scaffold/pre-push-hook.ts +165 -0
  28. package/lib/scaffold/rehearsal.ts +330 -0
  29. package/lib/scaffold/steps.ts +175 -122
  30. package/lib/scaffold/write-steps.ts +167 -0
  31. package/lib/scope-denylist.ts +258 -0
  32. package/lib/scratch-cleanup.ts +198 -0
  33. package/lib/scratch-roots.ts +94 -0
  34. package/lib/task-completion-checks.ts +50 -3
  35. package/lib/typescript-project.ts +233 -0
  36. package/lib/validators/spec-validators.ts +23 -34
  37. package/lib/verified-push.ts +179 -2
  38. package/lib/workflow-security.ts +51 -7
  39. package/lib/worktree-cleanup.ts +318 -20
  40. package/lib/worktree-repo.ts +465 -0
  41. package/package.json +8 -2
  42. package/scripts/audit-specs.ts +134 -37
  43. package/scripts/audit-transcript.ts +259 -0
  44. package/scripts/create-sc.ts +15 -1
  45. package/scripts/detect-sc-drift.ts +200 -0
  46. package/scripts/extract-constraints.ts +16 -36
  47. package/scripts/scaffold-project.ts +26 -136
  48. package/scripts/split-spec.ts +315 -0
  49. package/scripts/sync-sc-status.ts +751 -0
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Package closure — does everything the tarball ships still resolve once it is
3
+ * the only thing on disk?
4
+ *
5
+ * `lib/` publishes whole. `scripts/` publishes by allowlist, one path at a
6
+ * time. An import that crosses from the first into the second is only sound
7
+ * while the allowlist happens to name its target, and nothing checked that.
8
+ * `lib/conformity.ts` imported `../scripts/split-spec` through two releases
9
+ * with the file left out, so every consumer of `rungate/lib/conformity` died
10
+ * on import while the repo stayed green — the suites resolve that path against
11
+ * the working tree, where it exists (#446).
12
+ *
13
+ * The check is static and offline: expand `files[]` into the set the tarball
14
+ * would carry, then walk the relative imports of every published source file
15
+ * and assert each target is in that set. One `catch` here would turn a
16
+ * malformed package.json into "no violations", so there is none.
17
+ */
18
+ import { existsSync, readdirSync, readFileSync, statSync } from "fs";
19
+ import { join, dirname, relative, resolve } from "path";
20
+
21
+ /** Extensions a bare specifier may acquire, in the order a resolver tries. */
22
+ const CANDIDATE_SUFFIXES = ["", ".ts", ".tsx", ".js", ".mjs", ".json", "/index.ts", "/index.js"];
23
+
24
+ const SOURCE_EXT = /\.(ts|tsx|mts|js|mjs)$/;
25
+
26
+ /** `files[]` entries are either a directory ("lib/") or one exact path. */
27
+ export function publishedFiles(root: string, patterns: string[]): Set<string> {
28
+ const out = new Set<string>();
29
+
30
+ function addDir(rel: string) {
31
+ const abs = join(root, rel);
32
+ if (!existsSync(abs)) return;
33
+ for (const entry of readdirSync(abs)) {
34
+ const childRel = `${rel}/${entry}`.replace(/\/+/g, "/");
35
+ if (statSync(join(root, childRel)).isDirectory()) addDir(childRel);
36
+ else out.add(childRel);
37
+ }
38
+ }
39
+
40
+ for (const pattern of patterns) {
41
+ const clean = pattern.replace(/^\.\//, "").replace(/\/$/, "");
42
+ const abs = join(root, clean);
43
+ if (!existsSync(abs)) continue;
44
+ if (statSync(abs).isDirectory()) addDir(clean);
45
+ else out.add(clean);
46
+ }
47
+
48
+ // npm always includes these regardless of files[].
49
+ for (const always of ["package.json", "README.md", "LICENSE"]) {
50
+ if (existsSync(join(root, always))) out.add(always);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /** Relative specifiers only — bare ones are the dependency resolver's problem. */
56
+ export function relativeImports(source: string): string[] {
57
+ const found: string[] = [];
58
+ const patterns = [
59
+ /\bfrom\s+["'](\.[^"']+)["']/g,
60
+ /\bimport\s+["'](\.[^"']+)["']/g,
61
+ /\bimport\s*\(\s*["'](\.[^"']+)["']\s*\)/g,
62
+ /\brequire\s*\(\s*["'](\.[^"']+)["']\s*\)/g,
63
+ ];
64
+ for (const pattern of patterns) {
65
+ let m: RegExpExecArray | null;
66
+ while ((m = pattern.exec(source)) !== null) found.push(m[1]);
67
+ }
68
+ return found;
69
+ }
70
+
71
+ /**
72
+ * The single binding. `test/package-closure.test.ts` builds a mutant of this
73
+ * module with the body short-circuited to `return []` and asserts the suite
74
+ * goes quiet over a package that is genuinely broken — which is the only thing
75
+ * separating this from a line in a report.
76
+ */
77
+ export function packageClosureViolations(root: string, published: Set<string>): string[] {
78
+ const violations: string[] = [];
79
+
80
+ for (const file of published) {
81
+ if (!SOURCE_EXT.test(file)) continue;
82
+ const source = readFileSync(join(root, file), "utf-8");
83
+
84
+ for (const specifier of relativeImports(source)) {
85
+ const target = resolve(dirname(join(root, file)), specifier);
86
+ const targetRel = relative(root, target);
87
+
88
+ // Resolvable against the working tree but absent from the tarball is
89
+ // the whole defect — a path that does not exist at all is a different
90
+ // bug, and typecheck already owns it.
91
+ const existsOnDisk = CANDIDATE_SUFFIXES.some(s => existsSync(target + s));
92
+ if (!existsOnDisk) continue;
93
+
94
+ const isPublished = CANDIDATE_SUFFIXES.some(s => published.has(`${targetRel}${s}`.replace(/\/+/g, "/")));
95
+ if (!isPublished) {
96
+ violations.push(`${file} imports "${specifier}" -> ${targetRel}, which files[] does not publish`);
97
+ }
98
+ }
99
+ }
100
+ return violations.sort();
101
+ }
102
+
103
+ export function readPackageFiles(root: string): string[] {
104
+ // Deliberately unguarded: a malformed package.json must throw, not read as
105
+ // a package with nothing in it.
106
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
107
+ if (!Array.isArray(pkg.files)) {
108
+ throw new Error("package.json has no files[] array — cannot determine what ships");
109
+ }
110
+ return pkg.files;
111
+ }
@@ -0,0 +1,270 @@
1
+ /**
2
+ * The Phase 2 issue has to carry the ACs it was given (#79).
3
+ *
4
+ * When discovery produces more than `MAX_ACS_PER_ISSUE` ACs, `workflows/
5
+ * ship.js` asks an agent to group them and open a sub-issue for each group
6
+ * after the first. The agent returns a STRUCTURED list — `{number, phase,
7
+ * acIds}` — and separately writes the issue BODY as free prose. Nothing
8
+ * compared the two.
9
+ *
10
+ * On #70 they disagreed completely. The structured list said:
11
+ *
12
+ * AC-7 a greenfield scaffold writes a roles.json with at least three
13
+ * agent role entries that survive a read-back
14
+ * AC-8 hook registrations stored in hooks.json drive consumer hook
15
+ * deployment under the directory layout
16
+ * AC-9 the existing scaffold and scanner test files still pass
17
+ *
18
+ * and the body of #75 described AC-7/8/9 as doc-path cleanup — a restatement
19
+ * of AC-5, which was already in Phase 1. Both halves are internally
20
+ * plausible: the ids line up, the spec cited is real, the line numbers are
21
+ * real. A human or an agent picking up #75 reads the prose, not the list, so
22
+ * the deferral would have re-fixed Phase 1's work, shipped it as complete,
23
+ * and closed the parent while `roles.json` and `hooks.json` went on being
24
+ * written empty for every greenfield consumer — the defect that opened #70.
25
+ *
26
+ * That is scope loss that LOOKS COMPLETE. The sub-issue exists, is linked to
27
+ * its parent, and has well-formed ACs. Nothing is visibly missing, which is
28
+ * why the fix has to be a comparison rather than a better prompt.
29
+ *
30
+ * WHAT THIS MODULE REFUSES, AND WHY EACH ONE IS SEPARATE
31
+ *
32
+ * `decompositionRefusal` reads the structure alone; `phase2BodyViolations`
33
+ * reads a body against the ACs it is supposed to carry. They are separate
34
+ * because they fail separately: a grouping can be sound and the body still
35
+ * describe something else (#70's case), and a body can quote its ACs
36
+ * perfectly while the grouping has silently dropped one.
37
+ *
38
+ * Every refusal here is a refusal rather than a repair. A decomposition the
39
+ * harness "fixes" is an acceptance criterion nobody reviewed, which is the
40
+ * #217 lesson one layer up.
41
+ */
42
+
43
+ /** An AC as discovery produced it. `statement` is the text that must survive. */
44
+ export interface DecomposedAc {
45
+ id: string;
46
+ statement: string;
47
+ specElement?: string;
48
+ }
49
+
50
+ /** One group the decompose agent proposed. `number` is set once it exists. */
51
+ export interface SubIssuePlan {
52
+ number?: number;
53
+ phase?: string;
54
+ acIds?: string[];
55
+ }
56
+
57
+ /**
58
+ * Everything wrong with a proposed decomposition, or an empty list.
59
+ *
60
+ * Returns a LIST, not a boolean or a first error: a decomposition that drops
61
+ * one AC and duplicates another has two problems, and reporting one of them
62
+ * invites a second round that discovers the other.
63
+ */
64
+ export function decompositionRefusal(
65
+ allAcs: readonly DecomposedAc[] | null | undefined,
66
+ phase1AcIds: readonly string[] | null | undefined,
67
+ subIssues: readonly SubIssuePlan[] | null | undefined,
68
+ ): string[] {
69
+ const acs = Array.isArray(allAcs) ? allAcs : [];
70
+ const phase1 = Array.isArray(phase1AcIds) ? phase1AcIds : [];
71
+ const groups = Array.isArray(subIssues) ? subIssues : [];
72
+ const out: string[] = [];
73
+
74
+ if (acs.length === 0) return ["decomposition was asked for with no ACs to decompose"];
75
+
76
+ const known = new Set<string>();
77
+ for (const ac of acs) {
78
+ if (ac?.id) known.add(ac.id);
79
+ if (ac?.specElement) for (const s of ac.specElement.split(",")) known.add(s.trim());
80
+ }
81
+
82
+ // Phase 1 holding nothing is not a decomposition, it is a deferral of the
83
+ // whole issue — and it reads as success because sub-issues were created.
84
+ if (phase1.length === 0) out.push("no AC was kept for Phase 1 — the whole issue was deferred");
85
+
86
+ for (const id of phase1) {
87
+ if (!known.has(id)) out.push(`Phase 1 keeps ${id}, which discovery never produced`);
88
+ }
89
+
90
+ /** Which groups claim each id — the shape both duplicate cases need. */
91
+ const claimedBy = new Map<string, string[]>();
92
+ for (const [i, g] of groups.entries()) {
93
+ const label = g?.number ? `#${g.number}` : (g?.phase || `group ${i + 1}`);
94
+ const ids = Array.isArray(g?.acIds) ? g.acIds : [];
95
+ if (ids.length === 0) out.push(`${label} was created carrying no ACs`);
96
+ for (const id of ids) {
97
+ if (!known.has(id)) out.push(`${label} claims ${id}, which discovery never produced`);
98
+ claimedBy.set(id, [...(claimedBy.get(id) ?? []), label]);
99
+ }
100
+ }
101
+
102
+ // AC-3. The #70 failure mode exactly: a deferred AC that restates one
103
+ // already being shipped. Flagged, never written.
104
+ const phase1Set = new Set(phase1);
105
+ for (const [id, labels] of claimedBy) {
106
+ if (phase1Set.has(id)) {
107
+ out.push(`${id} is in Phase 1 AND deferred to ${labels.join(" and ")} — a deferral that duplicates shipped work`);
108
+ }
109
+ if (labels.length > 1) {
110
+ out.push(`${id} is claimed by ${labels.join(" and ")} — two phases cannot both own one AC`);
111
+ }
112
+ }
113
+
114
+ // The silent half. An AC in neither Phase 1 nor any sub-issue has been
115
+ // dropped, and every count the run prints still adds up.
116
+ for (const ac of acs) {
117
+ const ids: string[] = [ac.id, ...(ac.specElement ? ac.specElement.split(",").map((s: string) => s.trim()) : [])].filter(Boolean);
118
+ const placed = ids.some(id => phase1Set.has(id) || claimedBy.has(id));
119
+ if (!placed) out.push(`${ac.id} was neither kept nor deferred — it is gone, and nothing else would say so`);
120
+ }
121
+
122
+ return out;
123
+ }
124
+
125
+ /**
126
+ * The ACs one group owns, in discovery's order.
127
+ *
128
+ * One function, so the body comparison and the issue that was created cannot
129
+ * disagree about which ACs belong to a group. Matches on `id` or on any
130
+ * comma-separated `specElement`, because the decompose agent returns either
131
+ * — the same tolerance `workflows/ship.js` already applies when it filters
132
+ * Phase 1, and splitting it in two is how the two would drift.
133
+ */
134
+ export function acsForGroup(
135
+ acs: readonly DecomposedAc[] | null | undefined,
136
+ group: SubIssuePlan | null | undefined,
137
+ ): DecomposedAc[] {
138
+ const ids = new Set<string>(Array.isArray(group?.acIds) ? group!.acIds : []);
139
+ if (ids.size === 0) return [];
140
+ // Annotated because `Array.isArray` narrows a `readonly T[]` to `any[]`,
141
+ // and an `any` here would silently turn every field access below into an
142
+ // unchecked one.
143
+ const list: readonly DecomposedAc[] = Array.isArray(acs) ? acs : [];
144
+ return list.filter(ac => {
145
+ if (ids.has(ac.id)) return true;
146
+ if (!ac.specElement) return false;
147
+ return ac.specElement.split(",").some((s: string) => ids.has(s.trim()));
148
+ });
149
+ }
150
+
151
+ /**
152
+ * Wrap a string so a POSIX shell passes it through untouched.
153
+ *
154
+ * AC statements routinely contain backticks, double quotes and `$`. A
155
+ * single-quoted shell word is literal for every character except `'`, which
156
+ * is closed, escaped and reopened. This is the only quoting in the data path
157
+ * and it exists because the reference copy of the statements must reach disk
158
+ * WITHOUT passing through the model — a model that reworded both the body
159
+ * and the thing the body is compared against would pass any comparison.
160
+ */
161
+ export function shellSingleQuote(value: string): string {
162
+ return `'${String(value).replace(/'/g, `'\\''`)}'`;
163
+ }
164
+
165
+ /**
166
+ * The AC list as it appears in the decompose prompt.
167
+ *
168
+ * The prompt used to list no ACs at all, so the agent wrote each sub-issue
169
+ * body by reconstructing the scope from memory — which is exactly how #75's
170
+ * body came to describe Phase 1's work. The statements are now in front of
171
+ * it, verbatim, in the form it is asked to copy.
172
+ */
173
+ export function acListBlock(acs: readonly DecomposedAc[]): string {
174
+ return acs.map(ac => `- [ ] ${ac.id}: ${ac.statement}`).join("\n");
175
+ }
176
+
177
+ /**
178
+ * The command that writes the comparison's reference copy of the ACs.
179
+ *
180
+ * Emitted into the prompt for the agent to run verbatim, the way every other
181
+ * `bun -e` in this workflow is. The payload is the harness's own validated
182
+ * discovery output, shell-quoted here rather than composed by the model.
183
+ */
184
+ export function phase2AcsCommand(harnessRoot: string, workDir: string, acs: readonly DecomposedAc[]): string {
185
+ const payload = JSON.stringify(acs.map(a => ({ id: a.id, statement: a.statement, specElement: a.specElement })));
186
+ return (
187
+ `cd ${harnessRoot} && bun -e 'require("fs").writeFileSync(process.argv[1], process.argv[2])' ` +
188
+ `${workDir}/phase2-acs.json ${shellSingleQuote(payload)}`
189
+ );
190
+ }
191
+
192
+ /** The heading the comparison reads under. Must match what the prompt asks for. */
193
+ export const SC_HEADING = "## Success Criteria";
194
+
195
+ /**
196
+ * Normalise for comparison WITHOUT making the comparison meaningless.
197
+ *
198
+ * Markdown wraps, so a statement written across two lines is the same
199
+ * statement; collapsing runs of whitespace is therefore required rather than
200
+ * lenient. Nothing else is touched — not case, not punctuation, not the
201
+ * backticks around an identifier. A looser comparison here is how a body
202
+ * that paraphrases its AC would start passing, which is the whole defect.
203
+ */
204
+ function normalise(text: string): string {
205
+ return text.replace(/\s+/g, " ").trim();
206
+ }
207
+
208
+ /**
209
+ * Everything wrong with a Phase 2 body, given the ACs it is supposed to carry.
210
+ *
211
+ * Covers #79 AC-1 (same ids) and AC-2 (statements verbatim, by string
212
+ * equality after whitespace collapsing). The id check alone would have passed
213
+ * #75 — its body listed AC-7, AC-8 and AC-9 — so the statement check is the
214
+ * load-bearing half and the id check is there for the case where a body
215
+ * silently carries one fewer.
216
+ */
217
+ export function phase2BodyViolations(
218
+ body: string | null | undefined,
219
+ acs: readonly DecomposedAc[] | null | undefined,
220
+ ): string[] {
221
+ const text = typeof body === "string" ? body : "";
222
+ const expected = Array.isArray(acs) ? acs : [];
223
+ const out: string[] = [];
224
+
225
+ if (expected.length === 0) return ["no ACs were supplied to compare the body against"];
226
+ if (normalise(text) === "") return ["the issue body is empty"];
227
+
228
+ const headingAt = text.indexOf(SC_HEADING);
229
+ if (headingAt < 0) {
230
+ return [`the body has no "${SC_HEADING}" section, so there is nothing to compare the AC list against`];
231
+ }
232
+ // Everything from the heading to the next H2, which is the section the
233
+ // prompt asks for. Reading the WHOLE body would let an AC id mentioned in
234
+ // passing somewhere else satisfy the check.
235
+ const rest = text.slice(headingAt + SC_HEADING.length);
236
+ const nextH2 = rest.search(/^## /m);
237
+ const section = nextH2 < 0 ? rest : rest.slice(0, nextH2);
238
+ const flat = normalise(section);
239
+
240
+ for (const ac of expected) {
241
+ if (!new RegExp(`(^|[^A-Za-z0-9-])${ac.id}([^A-Za-z0-9-]|$)`).test(flat)) {
242
+ out.push(`${ac.id} is in the deferred list and not in the body's ${SC_HEADING} section`);
243
+ continue;
244
+ }
245
+ const statement = normalise(ac.statement ?? "");
246
+ if (statement === "") {
247
+ out.push(`${ac.id} has no statement in discovery, so the body cannot be checked against it`);
248
+ continue;
249
+ }
250
+ if (!flat.includes(statement)) {
251
+ out.push(
252
+ `${ac.id}'s statement is not carried verbatim. discovery: "${statement}" — ` +
253
+ `the body describes something else, which is #70's defect: the ids lined up and the work did not`,
254
+ );
255
+ }
256
+ }
257
+
258
+ // The other direction. A body carrying an id that was never deferred to it
259
+ // is the #75 shape read from the body's side: plausible, well-formed, and
260
+ // about different work.
261
+ const expectedIds = new Set(expected.map(a => a.id));
262
+ for (const found of flat.matchAll(/(?:^|[^A-Za-z0-9-])(AC-\d+)(?![A-Za-z0-9-])/g)) {
263
+ const id = found[1]!;
264
+ if (!expectedIds.has(id)) {
265
+ out.push(`the body's ${SC_HEADING} section lists ${id}, which was not deferred to this issue`);
266
+ }
267
+ }
268
+
269
+ return out;
270
+ }
@@ -120,7 +120,30 @@ export function issueReference(issueNumber: number): (text: unknown) => boolean
120
120
  `issueReference needs a non-negative integer issue number, got ${JSON.stringify(issueNumber)}`,
121
121
  )
122
122
  }
123
- const pattern = new RegExp(`(^|[^\\d])${issueNumber}([^\\d]|$)`)
123
+ // The bound is on HEX digits and `_`, not on decimal digits alone (#433).
124
+ //
125
+ // `[^\d]` was right about the case it was written for — it stops `55`
126
+ // matching `550` — and wrong about the case this repo actually generates.
127
+ // Workflow fan-out branches are named `worktree-wf_<runid>-<n>` with a hex
128
+ // run id, and in `worktree-wf_55baa4aa-a00-9` the `55` is preceded by `_`
129
+ // and followed by `b`. Both are non-digits, so it matched, and
130
+ // `detectPriorBranch` reported a stranger's fan-out worktree as issue 55's
131
+ // prior work. There were 149 such branches here when this was found.
132
+ //
133
+ // The bound is `\b`, which is what "word-boundary matching" meant all
134
+ // along. A hand-rolled hex class was tried first and a mutation scored
135
+ // ZERO against widening it to all letters — the fixtures could not tell
136
+ // the two apart, because every real form separates the number with
137
+ // punctuation. The zero was the finding: the narrower class was buying
138
+ // nothing over the broader one, and `\b` IS the broader one, already
139
+ // treating `_` and every letter as a word character.
140
+ //
141
+ // `\b55\b` rejects `worktree-wf_55baa4aa-a00-9` (`_` and `b` are word
142
+ // characters, so neither side is a boundary) and `550-matcher-registry`
143
+ // (`0` likewise), and accepts `209-deep-modules`, `fix/55`, `Closes #209`
144
+ // and `fix(#209):`. All of them are asserted in
145
+ // test/prior-branch-reference.test.ts rather than trusted to this comment.
146
+ const pattern = new RegExp(`\\b${issueNumber}\\b`)
124
147
  return (text: unknown) => typeof text === 'string' && pattern.test(text)
125
148
  }
126
149
 
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The names a cross-project document actually calls a project by (#442).
3
+ *
4
+ * `scanExternalSources` matched on `basename(projectRoot)` and nothing else,
5
+ * in both of its match modes. Measured by the reporting session against a
6
+ * real document in a sibling project:
7
+ *
8
+ * grep -ic "dailybriefdashboard" -> 0
9
+ * grep -ic "ddb" -> 2
10
+ *
11
+ * That generalises. A document written in one project that refers to another
12
+ * calls it by nickname, abbreviation, product name or repo slug — almost
13
+ * never by the literal name of the directory it happens to be checked out
14
+ * into. An exact substring match on the folder name is the wrong matcher for
15
+ * the only situation the feature exists to serve, and the feature has never
16
+ * fired for any project.
17
+ */
18
+
19
+ import { existsSync, readFileSync } from "fs";
20
+ import { basename, join } from "path";
21
+
22
+ /**
23
+ * Below this length an alias matches so much that it is noise.
24
+ *
25
+ * Two characters inside word boundaries is already thin; one is a letter,
26
+ * and a one-letter alias proposes adopting most of a directory. The same
27
+ * shape bit #437, where a one-character prefix made `isScratchEntry`
28
+ * accept `.claude`.
29
+ */
30
+ export const MIN_ALIAS_LENGTH = 2;
31
+
32
+ function escapeRegex(s: string): string {
33
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34
+ }
35
+
36
+ /** `owner/name` from a git remote URL, in either of the two forms git writes. */
37
+ export function remoteSlug(remoteUrl: string): string | null {
38
+ const m = /(?:github\.com[:/])([^/\s]+)\/([^/\s]+?)(?:\.git)?\s*$/.exec(remoteUrl.trim());
39
+ if (!m) return null;
40
+ return `${m[1]}/${m[2]}`;
41
+ }
42
+
43
+ /**
44
+ * Every name this project answers to, lowercased and de-duplicated.
45
+ *
46
+ * The repo name and the GitHub slug are DERIVED rather than typed, which is
47
+ * the point of SC-1: a project should not have to write down facts the tree
48
+ * already states. `configured` is for the ones only a human knows — the
49
+ * abbreviation, the product name, the thing the team says out loud.
50
+ */
51
+ export function projectAliases(projectRoot: string, configured: string[] = []): string[] {
52
+ const out: string[] = [basename(projectRoot)];
53
+
54
+ // `.git/config` rather than spawning git: this runs inside scaffold, and a
55
+ // subprocess per scaffolded project is a cost with no payoff when the file
56
+ // is right there. An unreadable or absent one simply contributes nothing —
57
+ // not a fail-open, because the directory name is always present and the
58
+ // caller is told which aliases were used.
59
+ const gitConfig = join(projectRoot, ".git", "config");
60
+ if (existsSync(gitConfig)) {
61
+ let text = "";
62
+ try {
63
+ text = readFileSync(gitConfig, "utf-8");
64
+ } catch {
65
+ text = "";
66
+ }
67
+ for (const m of text.matchAll(/^\s*url\s*=\s*(.+)$/gm)) {
68
+ const slug = remoteSlug(m[1]!);
69
+ if (!slug) continue;
70
+ out.push(slug);
71
+ out.push(slug.split("/")[1]!);
72
+ }
73
+ }
74
+
75
+ out.push(...configured);
76
+
77
+ const seen = new Set<string>();
78
+ return out
79
+ .map(a => a.trim().toLowerCase())
80
+ .filter(a => a.length >= MIN_ALIAS_LENGTH && !seen.has(a) && (seen.add(a), true));
81
+ }
82
+
83
+ /**
84
+ * Whether any alias appears in `text` as a WORD.
85
+ *
86
+ * ONE decider, used by both match modes. They were two separate expressions
87
+ * — `entry.toLowerCase().includes(projectName)` and
88
+ * `content.toLowerCase().includes(projectName)` — which meant two places to
89
+ * fix and two places for them to drift apart.
90
+ *
91
+ * Word boundaries rather than substring, because the aliases that make this
92
+ * feature work are short: `ddb` as a substring matches `oddball`, and a
93
+ * three-letter abbreviation proposing adoption of every document that
94
+ * happens to contain those letters is worse than the matcher that never
95
+ * fired. A slug like `owner/name` is bounded by `/`, which `\b` handles.
96
+ */
97
+ export function matchesAnyAlias(text: string, aliases: string[]): boolean {
98
+ const haystack = text.toLowerCase();
99
+ return aliases.some(a => new RegExp(`\\b${escapeRegex(a)}\\b`).test(haystack));
100
+ }
@@ -33,3 +33,96 @@ export function proveLabelViolation(labels: readonly string[]): string | null {
33
33
  "Run /prove to demonstrate the fix against a reproducer before closing (#1390)."
34
34
  );
35
35
  }
36
+
37
+ /**
38
+ * What the gate does when the label read itself fails (#405).
39
+ *
40
+ * The read used to be wrapped in `catch { return }`, so a missing token, a
41
+ * rate limit, a network blip and a typo'd repo slug all landed in the same
42
+ * place and the gate reported clean. "No blocking label" and "could not find
43
+ * out" were the same outcome, which is shape one in
44
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
45
+ *
46
+ * ## The token-less decision, and why
47
+ *
48
+ * #405 left this open: "whether a token-less local run should refuse or skip.
49
+ * A gate that refuses every local invocation is a gate people will comment
50
+ * out." Three outcomes rather than two, decided on what the environment can
51
+ * actually answer:
52
+ *
53
+ * | token | read | verdict |
54
+ * |---|---|---|
55
+ * | — | n/a | `UNMEASURED` — the environment was never able to answer |
56
+ * | present | threw | `REFUSE` — something that should have worked did not |
57
+ * | present | ok | `ALLOW` or `REFUSE` by `proveLabelViolation` |
58
+ *
59
+ * A token-less run does NOT refuse, because every local `bun test gates/`
60
+ * would block and the gate would be deleted within a week. It does not
61
+ * silently pass either: the verdict is `UNMEASURED` and carries its reason,
62
+ * which is the distinction `.claude/rules/config-access.md` names — `SKIP` is
63
+ * indistinguishable from success and `UNMEASURED` is not.
64
+ *
65
+ * That is safe where it matters because of where the gate actually runs, which
66
+ * was checked rather than assumed:
67
+ *
68
+ * - It is guarded by `isShipPlus()` — `gates/workflow.test.ts:229`, true only
69
+ * when workflow state says `SHIP` or `DONE`. It is reached from
70
+ * `gates/gate-executor.ts`, which spawns `bun test gates/` in the ship
71
+ * pipeline's own process environment, where a token is present.
72
+ * - CI runs `gates/workflow.test.ts` too (`ci.yml` runs a bare `bun test`) and
73
+ * has NO token. It never reaches this code: there is no workflow state in a
74
+ * CI checkout, so `isShipPlus()` is false and the test returns first. The
75
+ * `gates` job does not run this file at all — only the conformity suite and
76
+ * the secret scan.
77
+ *
78
+ * So the authenticated-and-still-failing case is the one real invocations hit,
79
+ * and it is the one that now blocks.
80
+ *
81
+ * `tokenPresent` comes from `resolveGitHubToken` at the call site rather than
82
+ * from a second `process.env` read here — two deciders of one fact survive
83
+ * any mutation of either.
84
+ */
85
+ export type ProveLabelVerdict = "ALLOW" | "REFUSE" | "UNMEASURED";
86
+
87
+ export interface LabelRead {
88
+ /** Set when the read succeeded. */
89
+ labels?: readonly string[];
90
+ /** Set when it threw. */
91
+ error?: unknown;
92
+ /** Whether the environment had a token at all. */
93
+ tokenPresent: boolean;
94
+ }
95
+
96
+ export interface ProveLabelOutcome {
97
+ verdict: ProveLabelVerdict;
98
+ /** Why, in the words the gate prints. `null` only when allowed. */
99
+ message: string | null;
100
+ }
101
+
102
+ export function proveLabelGateVerdict(read: LabelRead): ProveLabelOutcome {
103
+ if (read.labels !== undefined) {
104
+ const refusal = proveLabelViolation(read.labels);
105
+ return refusal ? { verdict: "REFUSE", message: refusal } : { verdict: "ALLOW", message: null };
106
+ }
107
+
108
+ const detail = read.error instanceof Error ? read.error.message : String(read.error ?? "no error reported");
109
+
110
+ if (!read.tokenPresent) {
111
+ return {
112
+ verdict: "UNMEASURED",
113
+ message:
114
+ "prove-label was NOT checked: no GITHUB_TOKEN or GH_TOKEN in this environment, so the " +
115
+ `issue's labels could not be read (${detail}). This is UNMEASURED, not clean — an issue ` +
116
+ "carrying `needs-prove` would look the same from here.",
117
+ };
118
+ }
119
+
120
+ return {
121
+ verdict: "REFUSE",
122
+ message:
123
+ "Close gate blocked: a token was present and the issue's labels still could not be read " +
124
+ `(${detail}). "No blocking label" and "could not find out" are different facts, and this ` +
125
+ "is the second one — re-run once GitHub is reachable rather than closing on a read that " +
126
+ "never happened (#405).",
127
+ };
128
+ }