rungate 0.3.0 → 0.4.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.
@@ -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
+ }
@@ -184,3 +184,105 @@ export function postflightRefusal(treeVersion: string, latestAfter: string | nul
184
184
  }
185
185
  return null;
186
186
  }
187
+
188
+ /** What a postflight poll saw, and how hard it had to look (#407). */
189
+ export interface PostflightReading {
190
+ /** The `latest` dist-tag on the final read. */
191
+ latest: string | null;
192
+ /** Reads performed. 1 means the registry had it immediately. */
193
+ attempts: number;
194
+ /** Time spent sleeping between reads, in ms. */
195
+ waitedMs: number;
196
+ /** The refusal, or `null` to allow. */
197
+ refusal: string | null;
198
+ }
199
+
200
+ /** Defaults sized for npm's observed read-after-write lag: up to ~30s. */
201
+ export const POSTFLIGHT_ATTEMPTS = 10;
202
+ export const POSTFLIGHT_DELAY_MS = 3_000;
203
+
204
+ /**
205
+ * Poll the registry until it serves `treeVersion`, or give up and refuse (#407).
206
+ *
207
+ * `v0.3.0` published cleanly and the release job still went red: the
208
+ * postflight read `registry.npmjs.org/rungate` about a second after `npm
209
+ * publish` returned, and that document is CDN-fronted and eventually
210
+ * consistent, so it was still serving `0.2.1`. The publish was fine. The check
211
+ * was wrong.
212
+ *
213
+ * `.claude/rules/checks-must-be-able-to-fail.md` is about checks that cannot
214
+ * fail. This is the inverse and it costs the same thing, because the message
215
+ * is wrong either way — and a red job over a green release is how a gate
216
+ * teaches people to stop reading it.
217
+ *
218
+ * ## The bound is the point
219
+ *
220
+ * Retrying until it goes green would turn this into the defect in the other
221
+ * direction. The loop is bounded, a publish that never lands still refuses,
222
+ * and the refusal says how long it waited — otherwise "it refused" and "it
223
+ * did not wait long enough" are indistinguishable to whoever reads the log.
224
+ *
225
+ * ## Why an intermediate throw retries and the last one does not
226
+ *
227
+ * A transient network error is exactly what polling is for, so a read that
228
+ * throws with attempts remaining is retried. The FINAL one rethrows, because
229
+ * `registryState` throws rather than returning an empty state precisely so
230
+ * that "could not measure" cannot read as "nothing wrong" — and swallowing
231
+ * the last throw here would put that fail-open back.
232
+ *
233
+ * `sleep` is injectable so the exhaustion case can be driven in a test without
234
+ * spending 30 seconds of wall clock on it.
235
+ */
236
+ export async function awaitRegistryServes(
237
+ pkg: string,
238
+ treeVersion: string,
239
+ opts: {
240
+ fetchImpl?: typeof fetch;
241
+ base?: string;
242
+ attempts?: number;
243
+ delayMs?: number;
244
+ sleep?: (ms: number) => Promise<void>;
245
+ } = {},
246
+ ): Promise<PostflightReading> {
247
+ const attempts = opts.attempts ?? POSTFLIGHT_ATTEMPTS;
248
+ const delayMs = opts.delayMs ?? POSTFLIGHT_DELAY_MS;
249
+ // A zero-attempt poll reads nothing and would fall out of the loop with no
250
+ // refusal — a check that never runs, reported as a check that passed.
251
+ if (!Number.isInteger(attempts) || attempts < 1) {
252
+ throw new Error(`postflight needs at least one attempt, got ${opts.attempts}`);
253
+ }
254
+ const sleep = opts.sleep ?? ((ms: number) => new Promise(r => setTimeout(r, ms)));
255
+
256
+ let waitedMs = 0;
257
+ let latest: string | null = null;
258
+ let refusal: string | null = null;
259
+
260
+ for (let attempt = 1; attempt <= attempts; attempt++) {
261
+ const last = attempt === attempts;
262
+ try {
263
+ const state = await registryState(pkg, opts.fetchImpl ?? fetch, opts.base);
264
+ latest = state.latest;
265
+ refusal = postflightRefusal(treeVersion, latest);
266
+ } catch (e) {
267
+ if (last) throw e;
268
+ refusal = `could not read the registry: ${(e as Error).message}`;
269
+ }
270
+
271
+ if (refusal === null) return { latest, attempts: attempt, waitedMs, refusal: null };
272
+ if (last) {
273
+ return {
274
+ latest,
275
+ attempts: attempt,
276
+ waitedMs,
277
+ refusal:
278
+ `${refusal} — read ${attempt} times over ${Math.round(waitedMs / 1000)}s, ` +
279
+ `which is long enough that this is not the registry catching up`,
280
+ };
281
+ }
282
+ await sleep(delayMs);
283
+ waitedMs += delayMs;
284
+ }
285
+
286
+ /* c8 ignore next */
287
+ throw new Error("unreachable: the loop returns on its last attempt");
288
+ }
@@ -6,7 +6,19 @@ export const DevSchema = z.object({
6
6
  uiBase: z.string().url(),
7
7
  preStart: z.string().optional(),
8
8
  testCmd: z.string().optional(),
9
- typeCheck: z.string().optional(),
9
+ /**
10
+ * The project's type check, or `null` when it has nothing to type-check.
11
+ *
12
+ * **Nullable as well as optional (#87)**, for `healthPath`'s reason below.
13
+ * The scaffold used to write `bunx tsc --noEmit` here unconditionally, and
14
+ * `gates/gate-executor.ts` RUNS what it finds; without a tsconfig that
15
+ * command prints its help text and exits 1, so the verify gate reported
16
+ * `Type check FAIL` at every consumer the rest of the scaffold had already
17
+ * decided was not a TypeScript project. Absent and null are different facts
18
+ * — "nobody configured this" versus "the scaffold looked and there is
19
+ * nothing to run" — and the gate skips on either.
20
+ */
21
+ typeCheck: z.string().nullable().optional(),
10
22
  note: z.string().optional(),
11
23
  /**
12
24
  * The path the dev-server liveness probe requests, relative to `apiBase`.
@@ -0,0 +1,165 @@
1
+ /**
2
+ * The generated `.git/hooks/pre-push`, as one binding (#397).
3
+ *
4
+ * It lived as a template literal inside `createGitHooks`, where nothing could
5
+ * run it. The hook is a shell script with an exit code, so
6
+ * `.claude/rules/checks-must-be-able-to-fail.md`'s worked pattern applies
7
+ * directly: route every refusal through one exit-code constant and drive the
8
+ * script against planted fixture repositories. That is what
9
+ * `test/pre-push-hook.test.ts` does, and it is why this is a module rather
10
+ * than a string in the middle of a 2,400-line generator.
11
+ *
12
+ * ## What was wrong
13
+ *
14
+ * The hook could not PASS in any consumer whose `bun.lock` is gitignored, and
15
+ * it failed closed with "Conformity tests failed against the commits being
16
+ * pushed" — which is not what happened. Found on agentgrit on 2026-10-14
17
+ * with conformity at 43 pass, 0 fail in the working tree and the push
18
+ * rejected.
19
+ *
20
+ * The lockfile comparison read `$tmp/bun.lock`, which comes from the git
21
+ * checkout. A gitignored lockfile is never in the checkout, so the `cmp`
22
+ * branch could not be taken and every push fell through to
23
+ * `bun install --frozen-lockfile` with no lockfile to freeze against. For a
24
+ * consumer with a `file:` or `link:` dependency on a sibling directory it
25
+ * then failed a second, independent way: a relative path does not resolve
26
+ * from `/tmp`.
27
+ *
28
+ * `.claude/rules/checks-must-be-able-to-fail.md` is about guards that cannot
29
+ * fail. This is the inverse and the damage is the same shape, because the
30
+ * message is wrong either way — a developer reading "conformity failed" goes
31
+ * and looks at conformity, which is green.
32
+ *
33
+ * ## The three outcomes, and why UNMEASURED blocks
34
+ *
35
+ * | what happened | exit | message |
36
+ * |---|---|---|
37
+ * | conformity ran and failed | refuse | the conformity message |
38
+ * | the suite could not be run at all | refuse | UNMEASURED, naming the cause |
39
+ * | conformity ran and passed | 0 | — |
40
+ *
41
+ * UNMEASURED blocks, and that is a decision rather than an accident of
42
+ * control flow. A pre-push gate that waves a commit through when it could not
43
+ * check is the fail-open this repo keeps finding; `SKIP` is indistinguishable
44
+ * from success and `UNMEASURED` is not
45
+ * (`.claude/rules/config-access.md`). What makes it tolerable is that it says
46
+ * which of the two happened and names `--no-verify` itself, so the developer
47
+ * is not hunting a green suite for a failure that never occurred.
48
+ */
49
+
50
+ /** The ONE exit code every refusal routes through. Asserted to appear once. */
51
+ export const PRE_PUSH_REFUSE_EXIT = 1;
52
+
53
+ export const PRE_PUSH_MANAGED_MARKER = "# Managed by rungate — conformity check before push";
54
+
55
+ /**
56
+ * The conformity suite the hook runs. One literal, so the test that plants a
57
+ * passing and a failing fixture writes the same path the hook reads.
58
+ */
59
+ export const PRE_PUSH_SUITE = "test/scaffold-conformity.test.ts";
60
+
61
+ export function prePushHookScript(): string {
62
+ return `#!/bin/sh
63
+ ${PRE_PUSH_MANAGED_MARKER}
64
+ #
65
+ # Three outcomes, not two: conformity FAILED, conformity could not be RUN,
66
+ # and conformity passed. The first two used to share a message and a status
67
+ # variable, so an install that could not happen was reported as a test that
68
+ # did not pass (#397).
69
+ REFUSE=${PRE_PUSH_REFUSE_EXIT}
70
+ ZERO=0000000000000000000000000000000000000000
71
+ TOPLEVEL=$(git rev-parse --show-toplevel) || exit $REFUSE
72
+ conformity=0
73
+ unmeasured=0
74
+ why=""
75
+
76
+ while read -r _lref lsha _rref _rsha; do
77
+ # Branch deletion: there is no commit to check out.
78
+ [ "$lsha" = "$ZERO" ] && continue
79
+
80
+ tmp=$(mktemp -d) || exit $REFUSE
81
+ if ! git worktree add --detach --quiet "$tmp" "$lsha"; then
82
+ unmeasured=1
83
+ why="the pushed commit $lsha could not be checked out"
84
+ rm -rf "$tmp"
85
+ break
86
+ fi
87
+
88
+ # Which node_modules the pushed commit expects.
89
+ #
90
+ # The old test was \`[ -f "$tmp/bun.lock" ] && cmp -s ...\`, which treats "the
91
+ # checkout has no lockfile" as "the dependencies differ" and installs. But a
92
+ # lockfile absent from the checkout is a lockfile git does not track — it is
93
+ # gitignored, or the project has none — and then there is nothing in this
94
+ # push that can change the dependency graph. The working tree's modules are
95
+ # the right ones by definition, and installing is both slower and less
96
+ # accurate.
97
+ if [ ! -f "$tmp/bun.lock" ]; then
98
+ ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
99
+ elif [ -f "$TOPLEVEL/bun.lock" ] && cmp -s "$TOPLEVEL/bun.lock" "$tmp/bun.lock"; then
100
+ ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
101
+ else
102
+ echo "pre-push: dependencies differ from the working tree — installing from the pushed lockfile" >&2
103
+ if ! ( cd "$tmp" && bun install --frozen-lockfile ) >&2; then
104
+ # NOT a conformity result. A relative \`file:\`/\`link:\` dependency does
105
+ # not resolve from a temp directory, and a lockfile that cannot be
106
+ # frozen is an environment fault in this hook's own sandbox.
107
+ unmeasured=1
108
+ why="dependencies could not be installed in the temporary checkout"
109
+ fi
110
+ fi
111
+
112
+ if [ "$unmeasured" -eq 0 ]; then
113
+ out=$( cd "$tmp" && bun test ${PRE_PUSH_SUITE} 2>&1 )
114
+ rc=$?
115
+ echo "$out" >&2
116
+
117
+ # A suite that FAILED and a suite that never RAN both exit non-zero: a
118
+ # missing file, an unresolvable import, and a red assertion are one exit
119
+ # code. Two things in bun's summary tell them apart, and both are needed.
120
+ #
121
+ # Counted tests. The summary prints \`N pass\` / \`N fail\`; a file that is
122
+ # not there prints neither. Zero counted tests is UNMEASURED even when the
123
+ # exit code is 0, because a suite passing vacuously is exactly what
124
+ # .claude/rules/checks-must-be-able-to-fail.md exists to catch.
125
+ #
126
+ # Counted ERRORS. A module that will not resolve is reported as \`1 fail\`
127
+ # AND \`1 error\` — measured on bun 1.3.14 — so the counted-tests test
128
+ # alone calls it a conformity failure, which is the wrong half of the
129
+ # distinction this hook exists to draw. A red assertion prints no error
130
+ # line at all. An unhandled error between tests means the suite did not
131
+ # run as written, whatever the fail count says.
132
+ if echo "$out" | grep -qE '^[[:space:]]*[1-9][0-9]* error'; then
133
+ unmeasured=1
134
+ why="the conformity suite did not load (an unhandled error, usually an import that will not resolve)"
135
+ elif echo "$out" | grep -qE '^[[:space:]]*[1-9][0-9]* (pass|fail)'; then
136
+ [ "$rc" -ne 0 ] && conformity=1
137
+ else
138
+ unmeasured=1
139
+ why="the conformity suite ran no tests (the file is not in the pushed commit, or it declares none)"
140
+ fi
141
+ fi
142
+
143
+ # Always clean up. An early exit here would leak a worktree on every failed
144
+ # push, which is how #68 reached 39 stale worktrees and 243 MB.
145
+ git worktree remove --force "$tmp" 2>/dev/null
146
+ rm -rf "$tmp"
147
+
148
+ [ "$conformity" -ne 0 ] && break
149
+ [ "$unmeasured" -ne 0 ] && break
150
+ done
151
+
152
+ if [ "$unmeasured" -ne 0 ]; then
153
+ echo "ERROR: pre-push did NOT run the conformity suite — $why." >&2
154
+ echo " This is UNMEASURED, not a test failure: your conformity tests may be green." >&2
155
+ echo " Fix the cause, or push with --no-verify once you have run" >&2
156
+ echo " \\\`bun test ${PRE_PUSH_SUITE}\\\` in the real tree yourself." >&2
157
+ exit $REFUSE
158
+ fi
159
+ if [ "$conformity" -ne 0 ]; then
160
+ echo "ERROR: Conformity tests failed against the commits being pushed — fix before pushing" >&2
161
+ exit $REFUSE
162
+ fi
163
+ exit 0
164
+ `;
165
+ }
@@ -17,12 +17,14 @@ import { generateCodeMap as buildCodeMapContent } from "../generators/code-map";
17
17
  import { buildAgentMeta, DEFAULT_AGENT_META } from "../create-brief";
18
18
  import { buildDefaultRoles, buildDefaultHooks } from "./defaults";
19
19
  import { mergeManagedWorkflow } from "./managed-workflow";
20
+ import { PRE_PUSH_MANAGED_MARKER, prePushHookScript } from "./pre-push-hook";
20
21
  import { tryLoadRungateConfig } from "../config-loader";
21
22
  import type { ProjectScan, ProjectType, SpecEntry, TestFile, RefFile, DocRoute, Category } from "../generators/types";
22
23
  import { tier1Ere } from "../secret-patterns";
23
24
  import { healthPathIn } from "../liveness-contradiction";
24
25
  import { decideRuleWrite } from "../rule-provenance";
25
26
  import { referencedPaths } from "../agents-md-refs";
27
+ import { TS_SOURCE_DIRS, typeScriptSourceDirs, typecheckDecision } from "../typescript-project";
26
28
  import {
27
29
  OWNED_FILES,
28
30
  SCAFFOLD_REFUSE,
@@ -707,7 +709,7 @@ export function generateConformityTest(root?: string): string {
707
709
  const from = root && isHarnessItself(root) ? "../lib/conformity" : "rungate/lib/conformity";
708
710
  return `import { resolve } from "path";
709
711
  import { afterAll } from "bun:test";
710
- import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, writeFindingsReport } from "${from}";
712
+ import { runScaffoldConformity, runSpecDiscovery, runSpecDrift, runDocHygiene, runFallowCheck, runAgentFileValidation, runDirectoryValidation, runPackageValidation, runTsconfigValidation, runConfigAccessValidation, runPromptConfigAccessValidation, writeFindingsReport } from "${from}";
711
713
 
712
714
  const ROOT = resolve(import.meta.dir, "..");
713
715
 
@@ -720,6 +722,8 @@ runAgentFileValidation(ROOT);
720
722
  runDirectoryValidation(ROOT);
721
723
  runPackageValidation(ROOT);
722
724
  runTsconfigValidation(ROOT);
725
+ runConfigAccessValidation(ROOT);
726
+ runPromptConfigAccessValidation(ROOT);
723
727
 
724
728
  afterAll(() => writeFindingsReport(ROOT));
725
729
  `;
@@ -905,12 +909,17 @@ export function generateOrAuditProjectHarness(root: string, actions: string[]):
905
909
  // Scan test commands
906
910
  const pkgPath = join(root, "package.json");
907
911
  let testCmd = "bun test";
908
- let typeCheckCmd = "bunx tsc --noEmit";
909
912
  if (existsSync(pkgPath)) {
910
913
  const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
911
914
  if (pkg.scripts?.test) testCmd = pkg.scripts.test;
912
- if (pkg.scripts?.typecheck) typeCheckCmd = pkg.scripts.typecheck;
913
915
  }
916
+ // #87 — this defaulted to `bunx tsc --noEmit` for every project, including
917
+ // one with no tsconfig, and `gates/gate-executor.ts` RUNS what lands here.
918
+ // Without a tsconfig that command prints 147 lines of help and exits 1, so
919
+ // the verify gate reported "Type check FAIL" at every consumer that the
920
+ // three other sites had already agreed should not be type-checked at all.
921
+ // `null` is the honest value and the gate already skips on a falsy one.
922
+ const typeCheckCmd = typecheckDecision(root).command;
914
923
 
915
924
  // Scan port from Makefile, docker-compose.yml, or .env.example
916
925
  const makefile = join(root, "Makefile");
@@ -1462,43 +1471,10 @@ export function copySpecTemplateIfEmpty(specsDir: string, actions: string[]): vo
1462
1471
 
1463
1472
  // ── tsconfig.json ──────────────────────────────────────────────
1464
1473
 
1465
- /**
1466
- * Trees a generated tsconfig type-checks. Same list as the scanner's source
1467
- * directories, plus `scripts/` — a consumer keeps real TypeScript there and
1468
- * nothing else would check it.
1469
- *
1470
- * `test/` is deliberately absent. The conformity test rungate generates into
1471
- * every consumer imports `bun:test` and `rungate/lib/conformity`, and neither
1472
- * resolves for tsc without `@types/bun` and an installed `rungate` — so
1473
- * including the test tree would hand a freshly scaffolded project a type check
1474
- * that reports 4 errors it did not cause and cannot fix. That is the #65/#76
1475
- * defect again in the other direction: a documented command whose result says
1476
- * nothing about the project's code.
1477
- */
1478
- const TS_SOURCE_DIRS = ["src", "lib", "scripts", "gates", "hooks", "workflows"] as const;
1479
-
1480
- /** True when `dir` holds at least one hand-written .ts/.tsx file. */
1481
- function containsTypeScript(dir: string): boolean {
1482
- let stack = [dir];
1483
- while (stack.length > 0) {
1484
- const current = stack.pop()!;
1485
- let entries;
1486
- try {
1487
- entries = readdirSync(current, { withFileTypes: true });
1488
- } catch {
1489
- continue;
1490
- }
1491
- for (const entry of entries) {
1492
- if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
1493
- if (entry.isDirectory()) {
1494
- stack.push(join(current, entry.name));
1495
- } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
1496
- return true;
1497
- }
1498
- }
1499
- }
1500
- return false;
1501
- }
1474
+ // `TS_SOURCE_DIRS`, `containsTypeScript` and the directory filter all moved to
1475
+ // lib/typescript-project.ts in #87. Five sites decided "is this a TypeScript
1476
+ // project" and they disagreed; two copies of a predicate survive any mutation
1477
+ // of either, which is what SC-842 and SC-843 already say about this file.
1502
1478
 
1503
1479
  /**
1504
1480
  * Write a tsconfig.json for a TypeScript consumer that has none (#72, #65/#76).
@@ -1524,13 +1500,14 @@ export function createTsconfig(root: string, actions: string[]): void {
1524
1500
  return;
1525
1501
  }
1526
1502
 
1527
- // The include list and the "is this a TypeScript project" test are the same
1528
- // question, answered once. Deriving them separately is how you get a
1503
+ // The include list, the "is this a TypeScript project" test and TSC-1's
1504
+ // applicability are the same question, answered once in
1505
+ // lib/typescript-project.ts. Deriving them separately is how you get a
1529
1506
  // tsconfig whose include matches no files — tsc error TS18003, which reads
1530
- // as a broken type check rather than as "nothing to check".
1531
- const include = TS_SOURCE_DIRS
1532
- .filter(dir => containsTypeScript(join(root, dir)))
1533
- .map(dir => `${dir}/**/*.ts`);
1507
+ // as a broken type check rather than as "nothing to check" — and how TSC-1
1508
+ // came to hard-fail over a file this function had deliberately not written
1509
+ // (#87).
1510
+ const include = typeScriptSourceDirs(root).map(dir => `${dir}/**/*.ts`);
1534
1511
 
1535
1512
  if (include.length === 0) {
1536
1513
  actions.push(`SKIP: tsconfig.json (no TypeScript source in ${TS_SOURCE_DIRS.join("/, ")}/)`);
@@ -2096,16 +2073,15 @@ export function createCiWorkflows(root: string, actions: string[], opts: { force
2096
2073
  // Rungate itself was shielded from noticing because `bun test` failed first
2097
2074
  // and the step never ran.
2098
2075
  //
2099
- // Emit it only when the project actually has a tsconfig, and prefer the
2100
- // project's own ratchet script when it has one — consumers do not get
2101
- // rungate's scripts/, so they must fall back to plain tsc.
2102
- const hasTsconfig = existsSync(join(root, "tsconfig.json"));
2103
- const hasRatchet = existsSync(join(root, "scripts", "typecheck.ts"));
2104
- const typecheckStep = !hasTsconfig
2105
- ? ""
2106
- : hasRatchet
2107
- ? `\n - run: bun scripts/typecheck.ts`
2108
- : `\n - run: bunx tsc --noEmit`;
2076
+ // Which command, and whether there is one at all, is `typecheckDecision`'s
2077
+ // to answer — the same binding AGENTS.md's row and the scanned
2078
+ // `dev.typeCheck` read (#87). This site used to check for
2079
+ // `scripts/typecheck.ts` on disk, a branch `files:` makes unreachable for
2080
+ // every consumer, and never looked at a project's own `typecheck` script.
2081
+ const typecheck = typecheckDecision(root);
2082
+ const typecheckStep = typecheck.command
2083
+ ? `\n - run: ${typecheck.command}`
2084
+ : `\n # No type check: ${typecheck.reason}.`;
2109
2085
 
2110
2086
  const ciYml = `# Managed by rungate — do not edit. Customize the ci section of .claude/rungate/config.json.
2111
2087
  name: CI
@@ -2367,7 +2343,7 @@ exit 0
2367
2343
  }
2368
2344
 
2369
2345
  const prePush = join(hooksDir, "pre-push");
2370
- const MANAGED_MARKER = "# Managed by rungate — conformity check before push";
2346
+ const MANAGED_MARKER = PRE_PUSH_MANAGED_MARKER;
2371
2347
 
2372
2348
  // `2>/dev/null` threw away the only output that said WHY conformity failed,
2373
2349
  // leaving the developer a bare "fix before pushing" and no diagnosis. And the
@@ -2399,50 +2375,15 @@ exit 0
2399
2375
  // actually differ — the common push changes no dependencies and keeps the
2400
2376
  // fast path, and the push that does change them cannot quietly test against
2401
2377
  // the wrong ones.
2402
- writeFileSync(prePush, `#!/bin/sh
2403
- ${MANAGED_MARKER}
2404
- ZERO=0000000000000000000000000000000000000000
2405
- TOPLEVEL=$(git rev-parse --show-toplevel) || exit 1
2406
- status=0
2407
-
2408
- while read -r _lref lsha _rref _rsha; do
2409
- # Branch deletion: there is no commit to check out.
2410
- [ "$lsha" = "$ZERO" ] && continue
2411
-
2412
- tmp=$(mktemp -d) || exit 1
2413
- if ! git worktree add --detach --quiet "$tmp" "$lsha"; then
2414
- echo "ERROR: could not check out $lsha to verify the push" >&2
2415
- rm -rf "$tmp"
2416
- exit 1
2417
- fi
2418
-
2419
- # Reuse the installed modules only when the pushed commit expects the same
2420
- # ones; otherwise install from the pushed lockfile.
2421
- if [ -f "$TOPLEVEL/bun.lock" ] && [ -f "$tmp/bun.lock" ] && cmp -s "$TOPLEVEL/bun.lock" "$tmp/bun.lock"; then
2422
- ln -s "$TOPLEVEL/node_modules" "$tmp/node_modules" 2>/dev/null
2423
- else
2424
- echo "pre-push: dependencies differ from the working tree — installing from the pushed lockfile" >&2
2425
- ( cd "$tmp" && bun install --frozen-lockfile ) >&2 || status=1
2426
- fi
2427
-
2428
- if [ "$status" -eq 0 ]; then
2429
- ( cd "$tmp" && bun test test/scaffold-conformity.test.ts ) || status=1
2430
- fi
2431
-
2432
- # Always clean up. An early exit here would leak a worktree on every failed
2433
- # push, which is how #68 reached 39 stale worktrees and 243 MB.
2434
- git worktree remove --force "$tmp" 2>/dev/null
2435
- rm -rf "$tmp"
2436
-
2437
- [ "$status" -ne 0 ] && break
2438
- done
2439
-
2440
- if [ "$status" -ne 0 ]; then
2441
- echo "ERROR: Conformity tests failed against the commits being pushed — fix before pushing" >&2
2442
- exit 1
2443
- fi
2444
- exit 0
2445
- `);
2378
+ //
2379
+ // The script itself lives in lib/scaffold/pre-push-hook.ts (#397). As a
2380
+ // template literal here it was unrunnable, and the thing nothing runs is
2381
+ // the thing nothing checks: the lockfile comparison read the CHECKOUT's
2382
+ // `bun.lock`, so a consumer that gitignores its lockfile could never take
2383
+ // the fast path and could never pass. Over there it is one binding with one
2384
+ // exit-code constant, and test/pre-push-hook.test.ts drives it against
2385
+ // planted repositories.
2386
+ writeFileSync(prePush, prePushHookScript());
2446
2387
  chmodSync(prePush, 0o755);
2447
2388
  actions.push(existing === null
2448
2389
  ? "CREATED: .git/hooks/pre-push (conformity check)"