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.
@@ -0,0 +1,258 @@
1
+ /**
2
+ * Files a goal put out of bounds, and the plans that claimed them anyway (#306).
3
+ *
4
+ * ## What happened
5
+ *
6
+ * #274 attempt 4 (`wf_b3714a40-bb7`). The goal said, under a heading in
7
+ * capitals, "ALSO DO NOT FIX, ALREADY FILED: #295 … leave it there". The
8
+ * `to-issues` decomposer then emitted a sub-issue whose `filesToModify` was
9
+ * `gates/schema.ts`, `lib/evidence-prevalidator.ts`,
10
+ * `gates/SCHEMA-GUIDE.md` — the three files you would touch to fix #295, and
11
+ * nothing to do with #274. The agent did what its file list permitted, and
12
+ * the run refused on its own contradiction: one sub-issue both documented the
13
+ * defect and removed it.
14
+ *
15
+ * The attribution is the decomposer's, not the agent's. The collection guard
16
+ * (#178, SC-413) refuses any file no sub-issue claimed, and it did not refuse
17
+ * these — so they were in the plan. An agent handed `gates/schema.ts` and a
18
+ * defect description has been told, by the strongest signal in the system,
19
+ * that the file is in scope.
20
+ *
21
+ * ## One thing #306 got wrong, corrected here
22
+ *
23
+ * The issue proposes "the goal already names them; the decomposer could be
24
+ * given an explicit deny-list". **The goal did not name them.** Re-read the
25
+ * quoted prohibition: it names an ISSUE (`#295`) and three code symbols
26
+ * (`prevalidationViolations`, `reading.broken`, `acs[].status`). Not one file
27
+ * path. The paths came from `discovery.filesToModify`, which
28
+ * `workflows/ship.js:1952` hands to the decomposer verbatim as "Files to
29
+ * modify".
30
+ *
31
+ * That changes the fix in a way worth stating, because a deny-list built on
32
+ * the issue's premise would have returned `[]` for the very run that
33
+ * motivated it and passed — the decorative check
34
+ * `.claude/rules/checks-must-be-able-to-fail.md` is about, shipped as its own
35
+ * remedy. So this module has two outputs, not one:
36
+ *
37
+ * - `deniedFiles` — paths the prohibition actually named, which can be
38
+ * enforced.
39
+ * - `unresolvedProhibitions` — prohibitions that named an issue and no file,
40
+ * which CANNOT be enforced and are reported rather than counted as clean.
41
+ * #274's own goal is this case. An empty deny-list and an unenforceable one
42
+ * look identical from the outside, and conflating them is the whole bug.
43
+ */
44
+
45
+ /** A marked region of goal text and what could be extracted from it. */
46
+ export interface Prohibition {
47
+ /** The text of the marked paragraph. */
48
+ text: string;
49
+ /** Repo-relative paths named inside it. */
50
+ files: string[];
51
+ /** Issue numbers named inside it, as `#295`. */
52
+ issues: string[];
53
+ }
54
+
55
+ /**
56
+ * Line markers that put the rest of a paragraph out of bounds.
57
+ *
58
+ * Deliberately short and literal. A wider list reads ordinary prose as a
59
+ * prohibition and starts denying files the run needs, which fails a correct
60
+ * plan — and a guard that fires on correct work is removed within a week.
61
+ */
62
+ const MARKERS = [
63
+ /\bdo\s+not\s+fix\b/i,
64
+ /\bdo\s+not\s+touch\b/i,
65
+ /\bdo\s+not\s+modify\b/i,
66
+ /\bout\s+of\s+scope\b/i,
67
+ /\bnot\s+in\s+scope\b/i,
68
+ /\balready\s+filed\b/i,
69
+ ];
70
+
71
+ /**
72
+ * A source path: an optional directory prefix and a KNOWN EXTENSION.
73
+ *
74
+ * The extension is what does the discriminating, and that is worth stating
75
+ * because the first draft of this file claimed the `/` did. It does not.
76
+ * `reading.broken` and `acs[].status` — both in #274's prohibition, both code
77
+ * expressions — are excluded because `.broken` and `.status` are not
78
+ * extensions, not because they lack a separator. Mutating the `/` from
79
+ * required to optional scored **zero red** against the cases written to
80
+ * defend it, which is how the claim was caught.
81
+ *
82
+ * The separator is optional on purpose, once it stopped being load-bearing:
83
+ * requiring it silently misses every root-level file a goal might name —
84
+ * `package.json`, `AGENTS.md`, `CODE-MAP.md` — which is a false negative in
85
+ * exactly the common case. How a bare name matches a plan entry is
86
+ * `matchesDenied` below, and it is not the same rule as for a full path.
87
+ */
88
+ const PATH = /\b([A-Za-z0-9_.-]+(?:\/[A-Za-z0-9_.-]+)*\.(?:ts|tsx|js|jsx|md|json|ya?ml|sh))\b/g;
89
+
90
+ const ISSUE_REF = /#(\d+)\b/g;
91
+
92
+ /** Paths named in a span of text, deduplicated, in first-seen order. */
93
+ export function pathsNamedIn(text: string): string[] {
94
+ return [...new Set([...text.matchAll(PATH)].map(m => m[1]))];
95
+ }
96
+
97
+ /**
98
+ * Split goal text into the paragraphs a marker puts out of bounds.
99
+ *
100
+ * A paragraph, not a line: #274's prohibition is one bolded lead-in followed
101
+ * by two sentences, and a line-scoped reader would see the marker and stop
102
+ * before the content. A paragraph, not the rest of the document: a marker
103
+ * near the top would otherwise deny the entire goal.
104
+ */
105
+ export function prohibitions(goalText: string): Prohibition[] {
106
+ const out: Prohibition[] = [];
107
+ for (const para of String(goalText ?? "").split(/\n\s*\n/)) {
108
+ if (!MARKERS.some(m => m.test(para))) continue;
109
+ out.push({
110
+ text: para.trim(),
111
+ files: pathsNamedIn(para),
112
+ issues: [...new Set([...para.matchAll(ISSUE_REF)].map(m => `#${m[1]}`))],
113
+ });
114
+ }
115
+ return out;
116
+ }
117
+
118
+ /**
119
+ * Every file the goal put out of bounds.
120
+ *
121
+ * `scopeOut` entries count in full — that field exists to say what is out of
122
+ * scope, so it needs no marker. Until now nothing read it at all: it was
123
+ * required by the discovery schema, appended to in one place, and consulted
124
+ * by nothing, which is its own small version of this bug.
125
+ */
126
+ export function deniedFiles(goalText: string, scopeOut: readonly string[] = []): string[] {
127
+ const fromGoal = prohibitions(goalText).flatMap(p => p.files);
128
+ const fromScopeOut = scopeOut.flatMap(s => pathsNamedIn(String(s ?? "")));
129
+ return [...new Set([...fromGoal, ...fromScopeOut])];
130
+ }
131
+
132
+ /**
133
+ * Prohibitions that name an issue and no file (#306).
134
+ *
135
+ * These are the ones the deny-list cannot act on, and reporting them is the
136
+ * point. "Nothing was denied because the goal named nothing" and "nothing was
137
+ * denied because the goal named no files" are the same empty list, and only
138
+ * the first is a clean run.
139
+ */
140
+ export function unresolvedProhibitions(goalText: string): Prohibition[] {
141
+ return prohibitions(goalText).filter(p => p.files.length === 0 && p.issues.length > 0);
142
+ }
143
+
144
+ /** A plan item that claims files. Shaped to match a sub-issue or discovery. */
145
+ export interface FileClaimant {
146
+ title?: string;
147
+ filesToModify?: readonly string[];
148
+ }
149
+
150
+ /**
151
+ * One spelling per path, so a guard cannot be stepped around by rewriting it.
152
+ *
153
+ * A string comparison is only as good as its normalisation, and `./a/b.ts`,
154
+ * `a//b.ts`, `a/./b.ts` and `a/c/../b.ts` are four spellings of one file that
155
+ * an `===` reads as four different ones. The whole value of this module is a
156
+ * comparison, so an un-normalised one is a guard with a documented bypass —
157
+ * "a detector narrower than what it detects", third shape in
158
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
159
+ *
160
+ * A leading `..` is kept rather than resolved away: it escapes the repo root
161
+ * and there is nothing above it to collapse into, so dropping it would make
162
+ * `../secrets.ts` normalise to `secrets.ts` and match a deny entry that never
163
+ * meant it. Raised by the commit security review on this change.
164
+ */
165
+ export function normalisePath(p: string): string {
166
+ const raw = String(p ?? "").trim().replace(/\\/g, "/");
167
+ const out: string[] = [];
168
+ for (const seg of raw.split("/")) {
169
+ if (seg === "" || seg === ".") continue;
170
+ if (seg === ".." && out.length > 0 && out.at(-1) !== "..") out.pop();
171
+ else out.push(seg);
172
+ }
173
+ return out.join("/");
174
+ }
175
+
176
+ /**
177
+ * Does a plan's file entry fall under a denied entry?
178
+ *
179
+ * Two rules, because a goal names files two ways:
180
+ *
181
+ * - **A denied entry WITH a separator matches exactly**, after normalisation.
182
+ * A suffix match would read `test/gates/schema.ts` as `gates/schema.ts` and
183
+ * deny a file the prohibition never mentioned.
184
+ * - **A denied entry with NO separator matches by basename.** "Do not touch
185
+ * package.json" has to reach `package.json`, and "do not touch
186
+ * HARNESS-STANDARD.md" has to reach `specs/HARNESS-STANDARD.md` — a goal
187
+ * author naming a bare file means the file, wherever it lives. Requiring
188
+ * the path instead would make the common phrasing silently do nothing,
189
+ * which is this issue's own defect one level down.
190
+ *
191
+ * The basename arm compares the last segment rather than testing `endsWith`,
192
+ * because `endsWith("/package.json")` is satisfied by nothing a normalised
193
+ * path can spell differently but the segment comparison says what it means.
194
+ */
195
+ export function matchesDenied(planFile: string, deniedEntry: string): boolean {
196
+ const plan = normalisePath(planFile);
197
+ const denied = normalisePath(deniedEntry);
198
+ if (denied === "" || plan === "") return false;
199
+ if (denied.includes("/")) return plan === denied;
200
+ return plan === denied || plan.split("/").at(-1) === denied;
201
+ }
202
+
203
+ /** Violations, one line each. Empty allows. */
204
+ export function denylistViolations(
205
+ claimants: readonly FileClaimant[],
206
+ denied: readonly string[],
207
+ ): string[] {
208
+ const out: string[] = [];
209
+ for (const [i, c] of claimants.entries()) {
210
+ for (const f of c.filesToModify ?? []) {
211
+ if (!denied.some(d => matchesDenied(f, d))) continue;
212
+ out.push(
213
+ `${c.title ? `"${c.title}"` : `plan item ${i + 1}`} claims ${f}, which the goal ` +
214
+ `put out of scope. An agent handed a file is an agent told the file is in ` +
215
+ `scope (#306).`,
216
+ );
217
+ }
218
+ }
219
+ return out;
220
+ }
221
+
222
+ /**
223
+ * Did the deny-list eat the entire plan? (commit security review, #306)
224
+ *
225
+ * Two findings on this change were about the same hazard from opposite
226
+ * sides. The goal text is attacker-influenceable — issue bodies are — and
227
+ * nothing here validates it. What limits the damage is direction: a
228
+ * deny-list only ever NARROWS what an agent may write, so a hostile goal can
229
+ * deny progress but cannot grant access. That is the safe direction, and it
230
+ * is why this is a report rather than a refusal.
231
+ *
232
+ * The one outcome that is NOT safe is silence. If every file the run was
233
+ * going to touch is denied, stripping leaves an empty plan, and an empty
234
+ * plan is indistinguishable from a run with nothing to do — work refused,
235
+ * reported as work completed. That is the fail-open, and it is the shape the
236
+ * rest of this issue is about, so it gets a message rather than an empty
237
+ * array.
238
+ */
239
+ export function scopeContradiction(
240
+ files: readonly string[],
241
+ denied: readonly string[],
242
+ ): string | null {
243
+ if (files.length === 0 || denied.length === 0) return null;
244
+ if (withoutDenied(files, denied).length > 0) return null;
245
+ return (
246
+ `every file the run planned to touch is out of scope (${files.join(", ")} vs ` +
247
+ `denied ${denied.join(", ")}). An empty plan looks exactly like a run with ` +
248
+ `nothing to do, so this is reported rather than stripped in silence (#306).`
249
+ );
250
+ }
251
+
252
+ /** The denied files stripped out, order preserved. Same rule as above. */
253
+ export function withoutDenied(
254
+ files: readonly string[],
255
+ denied: readonly string[],
256
+ ): string[] {
257
+ return files.filter(f => !denied.some(d => matchesDenied(f, d)));
258
+ }
@@ -11,6 +11,8 @@ import { spawnSync } from 'child_process';
11
11
  import { existsSync, readFileSync } from 'fs';
12
12
  import { join } from 'path';
13
13
 
14
+ import { tryLoadRungateConfig } from './config-loader';
15
+
14
16
  export interface CompletionCheckResult {
15
17
  passed: boolean;
16
18
  blockers: string[];
@@ -105,15 +107,60 @@ export function checkUncommittedChanges(projectRoot: string): CompletionCheckRes
105
107
  }
106
108
 
107
109
  /**
108
- * Run conformity checks if rungate.json exists.
110
+ * Run conformity checks if the project is scaffolded.
109
111
  * Returns blocker if conformity fails.
110
112
  */
111
113
  export function checkConformity(projectRoot: string): CompletionCheckResult {
112
114
  const blockers: string[] = [];
113
115
  const warnings: string[] = [];
114
116
 
115
- const rungateConfig = join(projectRoot, '.claude', 'rungate.json');
116
- if (!existsSync(rungateConfig)) {
117
+ // Either layout counts as scaffolded. The old existence check named the
118
+ // monolith only, so every consumer that followed the documented migration
119
+ // to `.claude/rungate/` stopped having its conformity suite run here —
120
+ // silently, reporting passed.
121
+ //
122
+ // The throw is CAUGHT and converted to a blocker, which is the one place in
123
+ // this migration that is not simply "let the loader throw". This function is
124
+ // reached from `hooks/TaskCompleted.hook.ts`, which has no catch of its own,
125
+ // and a hook that exits 1 is neither allow (0) nor block (2) — so an
126
+ // escaping throw would disable the entire completion gate, not just this
127
+ // check, on one unparseable byte. Blocking keeps ADR-001 D2's distinction
128
+ // (a corrupt config is never a missing config) and keeps the gate closed.
129
+ let configured: boolean;
130
+ try {
131
+ configured = tryLoadRungateConfig(projectRoot) !== null;
132
+ } catch (err: unknown) {
133
+ // The CLASS, not the message. `JSON.parse` quotes a token from the file it
134
+ // failed on — "Unexpected identifier \"ghp_…\"" — and a config can hold
135
+ // credentials, so the parser's text is a channel out of the file and into
136
+ // this blocker, which is printed to stderr and captured in transcripts.
137
+ // The reproduction command is the replacement for the detail: it gives the
138
+ // operator the full message on their own terminal, where the config
139
+ // already is.
140
+ const kind = err instanceof Error && err.name ? err.name : "error";
141
+ // No runnable command in the text, and the path is JSON-quoted.
142
+ //
143
+ // The first draft printed `bun -e '…${projectRoot}…'` for the operator to
144
+ // paste, which the push review called command injection and is: this is a
145
+ // library function, the root reaches it from the caller, and a path
146
+ // carrying `'; rm -rf ~; '` would have been printed as a command a human
147
+ // is being told to run. A refusal that hands someone a line to paste is
148
+ // an execution path with a person in the middle of it.
149
+ //
150
+ // `JSON.stringify` on the path escapes quotes and newlines, so a crafted
151
+ // root cannot end the sentence and forge a second one either.
152
+ return {
153
+ passed: false,
154
+ blockers: [
155
+ `rungate config under ${JSON.stringify(join(projectRoot, '.claude'))} could not be read ` +
156
+ `(${kind}), so conformity did not run — a config that exists and cannot be parsed is ` +
157
+ `not an unconfigured project. Load that root with loadRungateConfig from ` +
158
+ `lib/config-loader.ts to see the parser's own message.`,
159
+ ],
160
+ warnings: [],
161
+ };
162
+ }
163
+ if (!configured) {
117
164
  // No rungate config — skip conformity check
118
165
  return { passed: true, blockers: [], warnings: [] };
119
166
  }
@@ -0,0 +1,233 @@
1
+ /**
2
+ * One fact, one decider: "is this a TypeScript project, and what type-checks it?" (#87)
3
+ *
4
+ * Four places answered the first question and three answered the second, and
5
+ * they disagreed — which is the whole of #87:
6
+ *
7
+ * | Site | Asked | Answered |
8
+ * |---|---|---|
9
+ * | `createTsconfig` | is there TypeScript source? | skip the tsconfig if not |
10
+ * | `createCiWorkflows` | is there a tsconfig? | skip the CI step if not |
11
+ * | `generateAgentsMd` | is there a tsconfig? | skip the doc row if not |
12
+ * | `scanProject` → `dev.typeCheck` | nothing | `bunx tsc --noEmit`, always |
13
+ * | `runTsconfigValidation` (TSC-1) | nothing | the tsconfig MUST exist |
14
+ *
15
+ * So a consumer with no TypeScript source got no tsconfig from the generator
16
+ * that decided it did not need one, no CI step and no doc row from the two
17
+ * that agreed — and then a conformity suite that hard-failed TSC-1 over the
18
+ * absent file, plus a `dev.typeCheck` of `bunx tsc --noEmit` written into its
19
+ * config, which `gates/gate-executor.ts` runs. Without a tsconfig tsc prints
20
+ * 147 lines of help text and exits 1, so that is #65/#76 reintroduced in the
21
+ * one place #65/#76 never looked.
22
+ *
23
+ * THE DECISION #87 ASKED FOR
24
+ *
25
+ * > Either consumers are allowed to be non-TypeScript projects (then TSC-1
26
+ * > must become conditional or a warning), or they are not (then the scaffold
27
+ * > should generate a tsconfig and TSC-1 is right). Pick one; today both are
28
+ * > asserted.
29
+ *
30
+ * Consumers ARE allowed to be non-TypeScript projects. Two generators had
31
+ * already voted that way and shipped, and writing a tsconfig into a project
32
+ * with no TypeScript in it produces `include: []` — tsc error TS18003, a type
33
+ * check that reads as broken rather than as "nothing to check". So TSC-1
34
+ * becomes conditional on the predicate `createTsconfig` already used, and the
35
+ * conditional arm RECORDS why it did not measure instead of passing quietly:
36
+ * `.claude/rules/config-access.md` calls the silent form out by name, and a
37
+ * check that cannot fail is indistinguishable from a check that is satisfied.
38
+ *
39
+ * WHY THE COMMAND LIVES HERE TOO
40
+ *
41
+ * `typecheckDecision` exists because the three command sites were a worse
42
+ * version of the same problem: they agreed on the question and still produced
43
+ * different answers, and one of their branches was unreachable. `files:` in
44
+ * package.json ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so no
45
+ * consumer could ever land on the ratchet branch — it was dead code that read
46
+ * as a supported configuration. A consumer's own `package.json` `scripts.
47
+ * typecheck` is checked first, which is the escape hatch that was missing: the
48
+ * ratchet is reachable by any project that writes one, and a project with a
49
+ * tsconfig full of pre-existing errors is no longer handed a CI step that can
50
+ * only be red over a generated file it is told not to edit.
51
+ */
52
+
53
+ import { existsSync, readdirSync, readFileSync } from "fs";
54
+ import { join } from "path";
55
+
56
+ /**
57
+ * Where a consumer keeps hand-written TypeScript.
58
+ *
59
+ * The scanner's source directories plus `scripts/` — a consumer keeps real
60
+ * TypeScript there and nothing else would check it.
61
+ *
62
+ * `test/` is deliberately absent. The conformity test rungate generates into
63
+ * every consumer imports `bun:test` and `rungate/lib/conformity`, and neither
64
+ * resolves for tsc without `@types/bun` and an installed `rungate` — so
65
+ * including the test tree would hand a freshly scaffolded project a type check
66
+ * that reports 4 errors it did not cause and cannot fix. That is the #65/#76
67
+ * defect again in the other direction: a documented command whose result says
68
+ * nothing about the project's code.
69
+ */
70
+ export const TS_SOURCE_DIRS = ["src", "lib", "scripts", "gates", "hooks", "workflows"] as const;
71
+
72
+ /** True when `dir` holds at least one hand-written .ts/.tsx file. */
73
+ export function containsTypeScript(dir: string): boolean {
74
+ let stack = [dir];
75
+ while (stack.length > 0) {
76
+ const current = stack.pop()!;
77
+ let entries;
78
+ try {
79
+ entries = readdirSync(current, { withFileTypes: true });
80
+ } catch {
81
+ continue;
82
+ }
83
+ for (const entry of entries) {
84
+ if (entry.name === "node_modules" || entry.name.startsWith(".")) continue;
85
+ if (entry.isDirectory()) {
86
+ stack.push(join(current, entry.name));
87
+ } else if (/\.tsx?$/.test(entry.name) && !entry.name.endsWith(".d.ts")) {
88
+ return true;
89
+ }
90
+ }
91
+ }
92
+ return false;
93
+ }
94
+
95
+ /**
96
+ * The source directories that actually hold TypeScript, in TS_SOURCE_DIRS order.
97
+ *
98
+ * The include list and the "is this a TypeScript project" test are the same
99
+ * question, answered once. Deriving them separately is how you get a tsconfig
100
+ * whose include matches no files — tsc error TS18003, which reads as a broken
101
+ * type check rather than as "nothing to check".
102
+ */
103
+ export function typeScriptSourceDirs(root: string): string[] {
104
+ return TS_SOURCE_DIRS.filter(dir => containsTypeScript(join(root, dir)));
105
+ }
106
+
107
+ /** True when the project has hand-written TypeScript anywhere a type check would look. */
108
+ export function isTypeScriptProject(root: string): boolean {
109
+ return typeScriptSourceDirs(root).length > 0;
110
+ }
111
+
112
+ export interface TsconfigVerdict {
113
+ /** Does this project need a tsconfig.json at all? */
114
+ applicable: boolean;
115
+ /** Is one there? */
116
+ present: boolean;
117
+ /** The source directories that made it applicable — empty when it is not. */
118
+ dirs: string[];
119
+ /** Why, in the words the finding and the failure message both use. */
120
+ reason: string;
121
+ }
122
+
123
+ /**
124
+ * Whether TSC-1 has anything to assert, and why.
125
+ *
126
+ * Never returns a bare boolean: a check that skips has to be able to say what
127
+ * it skipped over, or its silence is indistinguishable from a pass.
128
+ */
129
+ export function tsconfigVerdict(root: string): TsconfigVerdict {
130
+ const dirs = typeScriptSourceDirs(root);
131
+ const present = existsSync(join(root, "tsconfig.json"));
132
+ const applicable = dirs.length > 0;
133
+
134
+ if (!applicable) {
135
+ return {
136
+ applicable,
137
+ present,
138
+ dirs,
139
+ reason:
140
+ `NOT APPLICABLE: no hand-written TypeScript in ${TS_SOURCE_DIRS.join("/, ")}/, ` +
141
+ `so no tsconfig.json is required and the scaffold did not write one (#87)`,
142
+ };
143
+ }
144
+ if (!present) {
145
+ return {
146
+ applicable,
147
+ present,
148
+ dirs,
149
+ reason:
150
+ `TypeScript source in ${dirs.join("/, ")}/ and no tsconfig.json — ` +
151
+ `\`bunx tsc --noEmit\` would print its help text and exit 1 (#65/#76). ` +
152
+ `Run \`bunx rungate scaffold .\` to create one`,
153
+ };
154
+ }
155
+ return {
156
+ applicable,
157
+ present,
158
+ dirs,
159
+ reason: `tsconfig.json is present and ${dirs.length} source director${dirs.length === 1 ? "y" : "ies"} need it`,
160
+ };
161
+ }
162
+
163
+ /** Where the type-check command came from. `none` means there is nothing to run. */
164
+ export type TypecheckSource = "package-script" | "ratchet" | "tsc" | "none";
165
+
166
+ export interface TypecheckDecision {
167
+ /** The shell command, or null when the project has nothing to type-check. */
168
+ command: string | null;
169
+ source: TypecheckSource;
170
+ /** Why this command and not another. Carried into the generated comment. */
171
+ reason: string;
172
+ }
173
+
174
+ /**
175
+ * The one type-check command for a project — CI step, AGENTS.md row and
176
+ * `dev.typeCheck` all read this.
177
+ *
178
+ * Order matters and each step earns its place:
179
+ *
180
+ * 1. **No tsconfig → no command.** Not a default, an absence. `bunx tsc
181
+ * --noEmit` without one prints help and exits 1, and three of the four
182
+ * former call sites had already learned that separately.
183
+ * 2. **The project's own `scripts.typecheck`.** A project that has thought
184
+ * about its type check has said so in package.json; overriding that with a
185
+ * guess is the thing `scanProject` was doing wrong in the other direction.
186
+ * This is also what makes the ratchet form reachable at all — `files:`
187
+ * ships neither `scripts/typecheck.ts` nor `tsconfig.json`, so a consumer
188
+ * gets a ratchet only by writing one, and then only this branch sees it.
189
+ * 3. **`scripts/typecheck.ts` on disk.** How the harness itself and anyone who
190
+ * copied its ratchet is served when package.json does not mention it.
191
+ * 4. **Plain `bunx tsc --noEmit`.** Honest for a project with a clean tree.
192
+ */
193
+ export function typecheckDecision(root: string): TypecheckDecision {
194
+ if (!existsSync(join(root, "tsconfig.json"))) {
195
+ return {
196
+ command: null,
197
+ source: "none",
198
+ reason: "no tsconfig.json — tsc would print its help text and check nothing (#65/#76)",
199
+ };
200
+ }
201
+
202
+ const pkgPath = join(root, "package.json");
203
+ if (existsSync(pkgPath)) {
204
+ try {
205
+ const pkg = JSON.parse(readFileSync(pkgPath, "utf-8"));
206
+ if (typeof pkg?.scripts?.typecheck === "string" && pkg.scripts.typecheck.trim() !== "") {
207
+ return {
208
+ command: "bun run typecheck",
209
+ source: "package-script",
210
+ reason: "the project declares its own `typecheck` script, which beats anything inferred",
211
+ };
212
+ }
213
+ } catch {
214
+ // An unreadable package.json is not a reason to lose the type check. The
215
+ // two branches below need no package.json at all, and `createTsconfig`'s
216
+ // neighbours already shrug at this rather than killing the scaffold (#380).
217
+ }
218
+ }
219
+
220
+ if (existsSync(join(root, "scripts", "typecheck.ts"))) {
221
+ return {
222
+ command: "bun scripts/typecheck.ts",
223
+ source: "ratchet",
224
+ reason: "the project has a ratchet script, which fails in both directions",
225
+ };
226
+ }
227
+
228
+ return {
229
+ command: "bunx tsc --noEmit",
230
+ source: "tsc",
231
+ reason: "a tsconfig.json exists and the project declares no type-check script of its own",
232
+ };
233
+ }