rungate 0.2.1 → 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.
Files changed (129) hide show
  1. package/bin/rungate.ts +70 -0
  2. package/lib/aes-calculator.ts +66 -0
  3. package/lib/agent-audit.ts +139 -0
  4. package/lib/agent-brief-validation.ts +359 -0
  5. package/lib/agents-md-refs.ts +90 -0
  6. package/lib/bash-file-read.ts +197 -0
  7. package/lib/behavioral-cache.ts +78 -0
  8. package/lib/branch-cleanup.ts +234 -0
  9. package/lib/brief-context-parser.ts +35 -0
  10. package/lib/brief-precedence.ts +114 -0
  11. package/lib/canary.ts +117 -0
  12. package/lib/check-registry.ts +226 -0
  13. package/lib/ci-checkout.ts +426 -0
  14. package/lib/cli-commands.ts +137 -0
  15. package/lib/compliance-backfill.ts +232 -0
  16. package/lib/compliance-report.ts +605 -0
  17. package/lib/compliance.ts +361 -0
  18. package/lib/config-loader.ts +255 -0
  19. package/lib/config-readers.ts +86 -0
  20. package/lib/conformity.ts +2161 -137
  21. package/lib/container-provenance.ts +230 -0
  22. package/lib/create-brief.ts +150 -0
  23. package/lib/create-sc.ts +267 -0
  24. package/lib/decomposition-waves.ts +197 -0
  25. package/lib/deep-merge.ts +69 -0
  26. package/lib/dev-liveness.ts +214 -0
  27. package/lib/directive-extractor.ts +210 -0
  28. package/lib/distribution-standing.ts +113 -0
  29. package/lib/doc-hygiene.ts +238 -0
  30. package/lib/eval-criteria.ts +6 -0
  31. package/lib/evidence-portability.ts +123 -0
  32. package/lib/evidence-prevalidator.ts +390 -0
  33. package/lib/evidence-required.ts +150 -0
  34. package/lib/evidence-satisfiability.ts +288 -0
  35. package/lib/frontmatter.ts +163 -0
  36. package/lib/gap-scanner.ts +348 -0
  37. package/lib/gate-check-audit.ts +190 -0
  38. package/lib/gate-enforcement.ts +366 -0
  39. package/lib/generators/agent-briefs.ts +136 -0
  40. package/lib/generators/agents-md.ts +511 -0
  41. package/lib/generators/code-map.ts +60 -0
  42. package/lib/generators/types.ts +184 -0
  43. package/lib/git-ref-normalizer.ts +107 -0
  44. package/lib/github.ts +539 -0
  45. package/lib/harness-identity.ts +63 -0
  46. package/lib/hill-climb.ts +164 -0
  47. package/lib/instruction-effectiveness.ts +131 -0
  48. package/lib/issue-closure-audit.ts +225 -0
  49. package/lib/issue-create-override.ts +343 -0
  50. package/lib/issue-extraction.ts +368 -0
  51. package/lib/js-top-level-code.ts +250 -0
  52. package/lib/liveness-contradiction.ts +149 -0
  53. package/lib/organize.ts +505 -0
  54. package/lib/paths.ts +197 -6
  55. package/lib/phase2-decomposition.ts +270 -0
  56. package/lib/post-fix-verify.ts +157 -0
  57. package/lib/prior-branch.ts +512 -0
  58. package/lib/project-state-shape.ts +166 -0
  59. package/lib/promote-outputs.ts +156 -0
  60. package/lib/prove-label-gate.ts +128 -0
  61. package/lib/reachability.ts +302 -0
  62. package/lib/release-preflight.ts +288 -0
  63. package/lib/rule-health-pipeline.ts +264 -0
  64. package/lib/rule-health-trend.ts +161 -0
  65. package/lib/rule-provenance.ts +149 -0
  66. package/lib/rule-registry.ts +128 -0
  67. package/lib/rungate-schema.ts +127 -5
  68. package/lib/sc-claim-forms.ts +179 -0
  69. package/lib/sc-cover.ts +150 -0
  70. package/lib/sc-guard.ts +157 -0
  71. package/lib/sc-ids.ts +344 -0
  72. package/lib/scaffold/defaults.ts +165 -0
  73. package/lib/scaffold/managed-workflow.ts +370 -0
  74. package/lib/scaffold/owned-files.ts +265 -0
  75. package/lib/scaffold/pre-push-hook.ts +165 -0
  76. package/lib/scaffold/steps.ts +2621 -0
  77. package/lib/scanner.ts +701 -0
  78. package/lib/scope-denylist.ts +258 -0
  79. package/lib/screenshot-upload.ts +73 -0
  80. package/lib/secret-patterns.ts +112 -0
  81. package/lib/security-verdict.ts +616 -0
  82. package/lib/signal-phrases.ts +1 -0
  83. package/lib/spec-change-conformity.ts +80 -0
  84. package/lib/spec-files.ts +62 -0
  85. package/lib/spec-registry.ts +133 -0
  86. package/lib/spec-updater.ts +96 -0
  87. package/lib/stale-cleanup.ts +224 -0
  88. package/lib/stale-issue-scanner.ts +36 -0
  89. package/lib/strip-js-comments.ts +269 -0
  90. package/lib/suite-measurement.ts +228 -0
  91. package/lib/task-completion-checks.ts +224 -0
  92. package/lib/test-suite-lock.ts +1136 -0
  93. package/lib/transcript-checker.ts +1140 -0
  94. package/lib/typescript-project.ts +233 -0
  95. package/lib/validators/spec-validators.ts +171 -0
  96. package/lib/verdict-capture.ts +73 -0
  97. package/lib/verified-push.ts +535 -0
  98. package/lib/workflow-security.ts +174 -0
  99. package/lib/worktree-cleanup.ts +432 -0
  100. package/lib/worktree-collect.ts +283 -0
  101. package/lib/worktree-isolation.ts +82 -0
  102. package/lib/worktree-repo.ts +300 -0
  103. package/package.json +27 -3
  104. package/prompts/ac-adversary.md +14 -2
  105. package/prompts/aditi.md +5 -0
  106. package/prompts/blast-radius.md +5 -0
  107. package/prompts/container-verify.md +5 -0
  108. package/prompts/discovery.md +4 -0
  109. package/prompts/environment.md +5 -0
  110. package/prompts/evidence-hierarchy.md +5 -0
  111. package/prompts/evidence-validator.md +11 -0
  112. package/prompts/marcus.md +5 -0
  113. package/prompts/prevention.md +5 -0
  114. package/prompts/prove-reproducer.md +12 -0
  115. package/prompts/quinn-decision-tree.md +5 -0
  116. package/prompts/quinn-ui-brief.md +5 -0
  117. package/prompts/quinn.md +5 -0
  118. package/prompts/rca.md +5 -0
  119. package/prompts/read-before-write.md +4 -0
  120. package/prompts/regression.md +5 -0
  121. package/prompts/serena.md +5 -0
  122. package/scripts/audit-specs.ts +464 -0
  123. package/scripts/convert-spec.ts +293 -0
  124. package/scripts/create-sc.ts +92 -0
  125. package/scripts/create-spec.ts +166 -0
  126. package/scripts/extract-constraints.ts +4 -3
  127. package/scripts/generate-code-map.ts +1 -1
  128. package/scripts/scaffold-project.ts +138 -1426
  129. package/scripts/sync-spec-tests.ts +211 -126
@@ -0,0 +1,426 @@
1
+ /**
2
+ * What CI's checkout actually looks like, read from CI's own workflow (#168).
3
+ *
4
+ * `scripts/test-clean-env.ts` claimed "a test that passes here passes in CI
5
+ * for the same reason". On 2026-10-07 it reported 2998 pass / 0 fail on a
6
+ * tree where CI reported 2 fail, and both failures were real. It models the
7
+ * developer's *environment* — `HOME`, `gh` credentials, git identity — and
8
+ * nothing about the developer's *checkout*. CI runs `actions/checkout@v4`,
9
+ * which by default fetches one commit onto a detached HEAD with no local
10
+ * branches. Any test whose behaviour depends on a ref or on history was
11
+ * therefore unmodelled, and `test/prior-branch.test.ts` was exactly that: it
12
+ * counts `main..<ref>`, which resolves on a developer's clone and does not
13
+ * resolve in CI.
14
+ *
15
+ * ## Why this reads the workflow instead of hardcoding CI's shape
16
+ *
17
+ * The obvious implementation is `git clone --depth 1`, detach, delete `main`.
18
+ * That is what the first draft of this did, and it was **already wrong** —
19
+ * #347 added a `git fetch --depth=200 origin main` step to the `test` job, so
20
+ * `origin/main` does exist by the time the suite runs. A hardcoded model
21
+ * reported two failures that CI does not have, which is the same defect as
22
+ * reporting zero that it does: a model nobody can trust in either direction.
23
+ *
24
+ * So the shape is parsed out of `.github/workflows/ci.yml`, and when the
25
+ * workflow changes the model follows. A parse that cannot find what it
26
+ * expects returns `null` with a reason, and the caller refuses — because a
27
+ * modelling step that silently falls back to "run it in the working tree" is
28
+ * the original defect with a flag on top.
29
+ */
30
+
31
+ /** One `git fetch` the workflow performs after checkout. */
32
+ export interface FetchStep {
33
+ /** The refspec as written, e.g. `+refs/heads/main:refs/remotes/origin/main`. */
34
+ refspec: string;
35
+ /** `--depth=N`, or null for an unbounded fetch. */
36
+ depth: number | null;
37
+ }
38
+
39
+ export interface CheckoutModel {
40
+ /** The job this was read from. */
41
+ jobName: string;
42
+ /** `fetch-depth`, defaulting to 1 the way `actions/checkout` does. null = full. */
43
+ depth: number | null;
44
+ /** Fetches the job runs after the checkout, in order. */
45
+ fetches: FetchStep[];
46
+ }
47
+
48
+ export interface CheckoutModelResult {
49
+ model: CheckoutModel | null;
50
+ /** Why there is no model, when there is none. Empty when there is one. */
51
+ why: string;
52
+ }
53
+
54
+ /**
55
+ * What this models, and — the part that matters — what it does not.
56
+ *
57
+ * #168's SC-582 asks for this list in writing, because the claim it replaces
58
+ * was absolute and wrong. Everything here is a way a local run can still
59
+ * disagree with CI, and naming them is the difference between a model and a
60
+ * promise.
61
+ */
62
+ export const UNMODELLED: readonly string[] = [
63
+ "the runner OS — CI is ubuntu-latest and this runs on the developer's machine, so anything platform-dependent (BSD vs GNU flags, path casing, file watchers) is still invisible here",
64
+ "a fresh `bun install` — node_modules is linked from the working tree rather than installed, so a missing or mis-ranged dependency still passes locally",
65
+ "the bun version — CI pins `bun-version: latest` at the moment the job runs; this uses whichever bun is on PATH",
66
+ "the PR merge commit — `actions/checkout@v4` on a pull_request checks out a merge of the head into the base, while this checks out the head alone, so a conflict-free-but-broken merge is not modelled",
67
+ "network and API availability — CI has neither the developer's `gh` credentials (stripped) nor their network conditions",
68
+ "files git ignores — a `.env` or a stray build artefact present locally and absent in CI is carried over only if git can see it",
69
+ ];
70
+
71
+ /**
72
+ * Is this refspec safe to hand to `git fetch` as an argument?
73
+ *
74
+ * Found by a security review of the first commit. The refspec is read out of
75
+ * a workflow file and pushed into an argv, and `git fetch` takes options
76
+ * anywhere on its command line — so a refspec beginning with `-` is a flag,
77
+ * and `--upload-pack=<command>` makes git **execute that command**. An argv
78
+ * array stops shell metacharacters; it does nothing about a value that is
79
+ * itself an option.
80
+ *
81
+ * This matters more here than the file it reads might suggest. rungate
82
+ * scaffolds other projects, so this parses workflow files it does not own —
83
+ * a repo whose CI contains `git fetch origin --upload-pack=...` would be
84
+ * cloning arbitrary execution into whoever ran the harness against it.
85
+ *
86
+ * An allowlist, not a denylist of leading dashes: the set of characters a
87
+ * real refspec needs is small and closed, and enumerating what is forbidden
88
+ * is how the next option syntax gets through.
89
+ */
90
+ export function isSafeRefspec(refspec: string): boolean {
91
+ return /^\+?[A-Za-z0-9_][A-Za-z0-9_.\/*-]*(:[A-Za-z0-9_][A-Za-z0-9_.\/*-]*)?$/.test(refspec);
92
+ }
93
+
94
+ /**
95
+ * Read the checkout shape out of a workflow file.
96
+ *
97
+ * Hand-parsed rather than YAML-parsed, because adding a YAML dependency to
98
+ * ship a modelling script is a worse trade than a narrow parser that says so
99
+ * when it is lost. The narrowness is the risk — a detector narrower than what
100
+ * it detects is this repo's second-most-common defect — so every branch that
101
+ * cannot find what it expects returns a reason rather than a default.
102
+ */
103
+ export function parseCheckoutModel(workflowYaml: string, jobName: string): CheckoutModelResult {
104
+ const lines = workflowYaml.split("\n");
105
+
106
+ const jobIdx = lines.findIndex(l => new RegExp(`^\\s{2}${jobName}:\\s*$`).test(l));
107
+ if (jobIdx === -1) {
108
+ return { model: null, why: `no job named "${jobName}" at two-space indentation` };
109
+ }
110
+ const jobIndent = (/^(\s*)/.exec(lines[jobIdx]) || ["", ""])[1].length;
111
+
112
+ // The job runs until the next key at the same indentation.
113
+ let end = lines.length;
114
+ for (let i = jobIdx + 1; i < lines.length; i++) {
115
+ const l = lines[i];
116
+ if (l.trim() === "" || /^\s*#/.test(l)) continue;
117
+ const indent = (/^(\s*)/.exec(l) || ["", ""])[1].length;
118
+ if (indent <= jobIndent) { end = i; break; }
119
+ }
120
+ const body = lines.slice(jobIdx, end);
121
+ const joined = body.join("\n");
122
+
123
+ const checkoutIdx = body.findIndex(l => /uses:\s*actions\/checkout@/.test(l));
124
+ if (checkoutIdx === -1) {
125
+ return { model: null, why: `job "${jobName}" has no actions/checkout step` };
126
+ }
127
+
128
+ // `fetch-depth` belongs to this step, so only look between it and the next
129
+ // step marker. Reading the whole job would pick up a second checkout's
130
+ // depth and model a checkout that never happens.
131
+ let stepEnd = body.length;
132
+ for (let i = checkoutIdx + 1; i < body.length; i++) {
133
+ if (/^\s*-\s/.test(body[i])) { stepEnd = i; break; }
134
+ }
135
+ const stepBody = body.slice(checkoutIdx, stepEnd).join("\n");
136
+ const depthMatch = /fetch-depth:\s*["']?(\d+)["']?/.exec(stepBody);
137
+ // No `fetch-depth` is not "unknown" — actions/checkout documents the
138
+ // default as 1, and that default is the whole reason this issue exists.
139
+ const rawDepth = depthMatch ? parseInt(depthMatch[1], 10) : 1;
140
+ const depth = rawDepth === 0 ? null : rawDepth;
141
+
142
+ const fetches: FetchStep[] = [];
143
+ for (const m of joined.matchAll(/git fetch\s+([^\n|]*)/g)) {
144
+ const args = m[1];
145
+ const refspecMatch = /['"]([^'"]*refs\/[^'"]*)['"]|(\+?refs\/\S+)/.exec(args);
146
+ if (!refspecMatch) continue;
147
+ const refspec = refspecMatch[1] ?? refspecMatch[2];
148
+ if (!isSafeRefspec(refspec)) {
149
+ return {
150
+ model: null,
151
+ why: `the "${jobName}" job fetches a refspec this will not pass to git: ${JSON.stringify(refspec)}`,
152
+ };
153
+ }
154
+ const fetchDepth = /--depth[= ](\d+)/.exec(args);
155
+ fetches.push({
156
+ refspec,
157
+ depth: fetchDepth ? parseInt(fetchDepth[1], 10) : null,
158
+ });
159
+ }
160
+
161
+ return { model: { jobName, depth, fetches }, why: "" };
162
+ }
163
+
164
+ /** A command the preparer wants run. Returned rather than executed so the plan is testable. */
165
+ export interface CheckoutCommand {
166
+ /**
167
+ * `exec` runs `argv`. `delete-local-refs` has no fixed argv — the refs a
168
+ * clone invents are only knowable once it exists — so the executor
169
+ * enumerates and deletes them. Named as its own kind rather than hidden
170
+ * behind a placeholder string, because a step a reader cannot see is a step
171
+ * nobody checks.
172
+ */
173
+ kind: "exec" | "delete-local-refs";
174
+ argv: string[];
175
+ /** Run in the clone rather than the parent directory. */
176
+ inClone: boolean;
177
+ /** Failing this command is not fatal — matches the workflow's own `|| echo WARN`. */
178
+ tolerateFailure?: boolean;
179
+ }
180
+
181
+ /** The refs a fresh clone invents and a CI runner does not have. */
182
+ export const CLONE_INVENTED_REF_PREFIXES = ["refs/heads/", "refs/remotes/"] as const;
183
+
184
+ /**
185
+ * The exact commands that turn a source repo into a CI-shaped checkout.
186
+ *
187
+ * A list rather than a sequence of `execSync` calls, because the interesting
188
+ * property — "the local branches are gone and the workflow's fetches are
189
+ * replayed" — is then something a test can read instead of infer from a
190
+ * directory it has to build.
191
+ */
192
+ export function ciCheckoutPlan(opts: {
193
+ source: string;
194
+ dest: string;
195
+ model: CheckoutModel;
196
+ /**
197
+ * The source repo's own `origin`, restored after the fetches (#183).
198
+ *
199
+ * `actions/checkout@v4` leaves `origin` pointing at the GitHub repository.
200
+ * This plan repoints it at `file://source` so the replayed fetches resolve
201
+ * offline, and before #183 it left it there — so a test asking "what
202
+ * repository is this checkout of" got a filesystem path under the model and
203
+ * `github.com/owner/name` in CI. `test/worktree-repo.test.ts`'s SC-1444
204
+ * positive control failed here for that reason and passed in CI, which is
205
+ * the inversion this whole module exists to prevent.
206
+ *
207
+ * Omit it and `origin` keeps the `file://` URL — a source with no origin
208
+ * has nothing to restore.
209
+ */
210
+ originUrl?: string | null;
211
+ }): CheckoutCommand[] {
212
+ const { source, dest, model } = opts;
213
+ const cmds: CheckoutCommand[] = [];
214
+
215
+ const clone = ["git", "clone", "--quiet", "--no-hardlinks"];
216
+ if (model.depth !== null) clone.push(`--depth=${model.depth}`);
217
+ clone.push(`file://${source}`, dest);
218
+ cmds.push({ kind: "exec", argv: clone, inClone: false });
219
+
220
+ // Detach first: a branch cannot be deleted while it is checked out, and a
221
+ // detached HEAD is what the runner has.
222
+ cmds.push({ kind: "exec", argv: ["git", "checkout", "--detach", "--quiet", "HEAD"], inClone: true });
223
+ // Every local branch and every remote-tracking ref the clone invented. The
224
+ // runner has neither until the workflow asks for them, and leaving them is
225
+ // precisely the blindness being fixed.
226
+ cmds.push({ kind: "delete-local-refs", argv: [], inClone: true });
227
+
228
+ // Point origin back at the source so the replayed fetches resolve offline.
229
+ cmds.push({ kind: "exec", argv: ["git", "remote", "set-url", "origin", `file://${source}`], inClone: true });
230
+
231
+ for (const f of model.fetches) {
232
+ // Checked at the parse boundary and again here. The plan is exported and
233
+ // a caller can build a model by hand, so the one place that turns a
234
+ // refspec into an argument is also a place that refuses to.
235
+ if (!isSafeRefspec(f.refspec)) continue;
236
+ const argv = ["git", "fetch", "--no-tags"];
237
+ if (f.depth !== null) argv.push(`--depth=${f.depth}`);
238
+ argv.push("origin", f.refspec);
239
+ // The workflow tolerates its own fetch failing (it prints a WARN and
240
+ // carries on), so the model must too — a model stricter than CI starts
241
+ // failing runs CI would pass, which costs trust the same way.
242
+ cmds.push({ kind: "exec", argv, inClone: true, tolerateFailure: true });
243
+ }
244
+
245
+ // Last, and it has to be last: every fetch above needs `file://` to resolve
246
+ // without a network.
247
+ if (opts.originUrl) {
248
+ cmds.push({ kind: "exec", argv: ["git", "remote", "set-url", "origin", opts.originUrl], inClone: true });
249
+ }
250
+
251
+ return cmds;
252
+ }
253
+
254
+ /** One refusal reason, or null when the checkout was built. */
255
+ export type PrepareResult = { ok: true; refs: string[] } | { ok: false; why: string };
256
+
257
+ /**
258
+ * The single exit code every refusal in `scripts/test-clean-env.ts` routes
259
+ * through, per `.claude/rules/checks-must-be-able-to-fail.md`.
260
+ *
261
+ * Declared here rather than in the script so a test can import it instead of
262
+ * restating `2` — an assertion that hardcodes the number it is checking
263
+ * stays green when the script stops using it.
264
+ */
265
+ export const CLEAN_ENV_REFUSE_EXIT = 2;
266
+
267
+ export interface Runner {
268
+ (argv: string[], cwd: string): { status: number; stdout: string; stderr: string };
269
+ }
270
+
271
+ /**
272
+ * Execute a plan. Separate from building it so the plan can be read in a test
273
+ * without a filesystem, and the execution checked against a real clone.
274
+ *
275
+ * Every refusal is a refusal. A preparer that gives up halfway and lets the
276
+ * caller run the suite anyway would report green for a checkout it never
277
+ * built — the exact fail-open shape `.claude/rules/checks-must-be-able-to-fail.md`
278
+ * is about, reintroduced by the tool written to close it.
279
+ */
280
+ export function executeCheckoutPlan(
281
+ plan: CheckoutCommand[],
282
+ dest: string,
283
+ parentDir: string,
284
+ run: Runner,
285
+ ): PrepareResult {
286
+ for (const cmd of plan) {
287
+ const cwd = cmd.inClone ? dest : parentDir;
288
+
289
+ if (cmd.kind === "delete-local-refs") {
290
+ const listed = run(
291
+ ["git", "for-each-ref", "--format=%(refname)", ...CLONE_INVENTED_REF_PREFIXES],
292
+ cwd,
293
+ );
294
+ if (listed.status !== 0) {
295
+ return { ok: false, why: `could not list the clone's refs: ${listed.stderr.trim()}` };
296
+ }
297
+ for (const ref of listed.stdout.split("\n").map(s => s.trim()).filter(Boolean)) {
298
+ const del = run(["git", "update-ref", "-d", ref], cwd);
299
+ if (del.status !== 0) {
300
+ return { ok: false, why: `could not delete ${ref}: ${del.stderr.trim()}` };
301
+ }
302
+ }
303
+ continue;
304
+ }
305
+
306
+ const r = run(cmd.argv, cwd);
307
+ if (r.status !== 0 && !cmd.tolerateFailure) {
308
+ return { ok: false, why: `${cmd.argv.join(" ")} exited ${r.status}: ${r.stderr.trim()}` };
309
+ }
310
+ }
311
+
312
+ const after = run(["git", "for-each-ref", "--format=%(refname)", "refs/heads/", "refs/remotes/"], dest);
313
+ if (after.status !== 0) {
314
+ return { ok: false, why: `could not read the prepared checkout's refs: ${after.stderr.trim()}` };
315
+ }
316
+ const refs = after.stdout.split("\n").map(s => s.trim()).filter(Boolean);
317
+
318
+ // The one property the whole exercise is for. A plan that ran clean and
319
+ // left `refs/heads/main` standing has modelled nothing, and would be
320
+ // indistinguishable from a working-tree run.
321
+ const localBranches = refs.filter(r => r.startsWith("refs/heads/"));
322
+ if (localBranches.length > 0) {
323
+ return {
324
+ ok: false,
325
+ why: `the prepared checkout still has local branches (${localBranches.join(", ")}) — ` +
326
+ `CI has none, so this would model the developer's tree and report its answers as CI's`,
327
+ };
328
+ }
329
+
330
+ return { ok: true, refs };
331
+ }
332
+
333
+ export interface PrepareOptions {
334
+ /** The repository to model — normally the developer's working tree. */
335
+ source: string;
336
+ /** Where to read CI's shape from. */
337
+ workflowPath: string;
338
+ /** Which job in it. */
339
+ jobName: string;
340
+ /** Empty directory the clone goes inside. */
341
+ tmpRoot: string;
342
+ readFile: (path: string) => string;
343
+ run: Runner;
344
+ /** Copy a path from the working tree into the clone, or remove it if gone. */
345
+ carryOver: (relPath: string, from: string, to: string) => void;
346
+ /** Make node_modules available in the clone. */
347
+ link: (from: string, to: string) => void;
348
+ exists: (path: string) => boolean;
349
+ log: (line: string) => void;
350
+ }
351
+
352
+ export type PrepareOutcome =
353
+ | { ok: true; dir: string; model: CheckoutModel; refs: string[]; carried: string[] }
354
+ | { ok: false; why: string; hint: string };
355
+
356
+ /**
357
+ * Build a CI-shaped checkout of `source`, or say why not.
358
+ *
359
+ * In the library rather than inline in `scripts/test-clean-env.ts` for one
360
+ * reason, and it was measured: with the decision inline, replacing its
361
+ * refusal with "warn and run in the working tree anyway" scored **0 red**.
362
+ * That is the worst fail-open this issue could produce — a caller who asked
363
+ * for the strict check, was told it could not be built, and got the
364
+ * unmodelled run the whole issue is about, reported as the strict one. The
365
+ * script now does nothing with this but translate `ok: false` into an exit.
366
+ *
367
+ * Every refusal is a refusal. There is deliberately no fall-back parameter:
368
+ * a caller who wants the working tree asks for it up front, where the choice
369
+ * is visible, not as a silent consequence of something having gone wrong.
370
+ */
371
+ export function prepareCiCheckout(opts: PrepareOptions): PrepareOutcome {
372
+ const hint = "the CI checkout is read from the workflow, not assumed. Use --no-ci-checkout to run in the working tree instead.";
373
+
374
+ let yaml: string;
375
+ try {
376
+ yaml = opts.readFile(opts.workflowPath);
377
+ } catch (e) {
378
+ return { ok: false, why: `cannot read ${opts.workflowPath} — ${(e as Error).message}`, hint };
379
+ }
380
+
381
+ const { model, why } = parseCheckoutModel(yaml, opts.jobName);
382
+ if (!model) {
383
+ return { ok: false, why: `could not read the "${opts.jobName}" job's checkout — ${why}`, hint };
384
+ }
385
+
386
+ const dest = `${opts.tmpRoot}/repo`;
387
+ // What the runner's `origin` points at (#183). A source with no origin —
388
+ // a bare init, a consumer's unpushed scaffold — restores nothing, which is
389
+ // also what CI would have.
390
+ const srcOrigin = opts.run(["git", "remote", "get-url", "origin"], opts.source);
391
+ const originUrl = srcOrigin.status === 0 ? srcOrigin.stdout.trim() || null : null;
392
+ const result = executeCheckoutPlan(
393
+ ciCheckoutPlan({ source: opts.source, dest, model, originUrl }),
394
+ dest,
395
+ opts.tmpRoot,
396
+ opts.run,
397
+ );
398
+ if (!result.ok) {
399
+ return { ok: false, why: `could not build the CI checkout — ${result.why}`, hint };
400
+ }
401
+
402
+ // Uncommitted work. CI tests a pushed commit, but a developer running this
403
+ // is asking "will CI pass on what I have", and answering with the contents
404
+ // of their last commit is a different question confidently answered.
405
+ const status = opts.run(["git", "status", "--porcelain", "-z"], opts.source);
406
+ if (status.status !== 0) {
407
+ return { ok: false, why: `could not read the working tree's status: ${status.stderr.trim()}`, hint };
408
+ }
409
+ const carried = status.stdout.split("\0").map(s => s.slice(3)).filter(Boolean);
410
+ for (const rel of carried) opts.carryOver(rel, opts.source, dest);
411
+
412
+ // Linked, not installed — see UNMODELLED. A `bun install` here would add a
413
+ // minute and a network dependency to every run.
414
+ const mods = `${opts.source}/node_modules`;
415
+ if (opts.exists(mods)) opts.link(mods, `${dest}/node_modules`);
416
+
417
+ const depthLabel = model.depth === null ? "full history" : `depth ${model.depth}`;
418
+ opts.log(
419
+ `CI checkout: ${depthLabel}, detached, ${result.refs.length} ref(s) after ` +
420
+ `${model.fetches.length} replayed fetch(es)` +
421
+ (carried.length ? `, ${carried.length} uncommitted path(s) carried over` : ""),
422
+ );
423
+ opts.log(`still NOT modelled: ${UNMODELLED.length} things — see UNMODELLED in lib/ci-checkout.ts`);
424
+
425
+ return { ok: true, dir: dest, model, refs: result.refs, carried };
426
+ }
@@ -0,0 +1,137 @@
1
+ /**
2
+ * What `rungate <command>` dispatches to (#363).
3
+ *
4
+ * Data, not a switch in the bin, because three separate things have to agree
5
+ * and only one of them is code:
6
+ *
7
+ * 1. `bin/rungate.ts` can run the command
8
+ * 2. `package.json`'s `files` ships the script it runs
9
+ * 3. the AGENTS.md generator publishes the command to every consumer
10
+ *
11
+ * Before this existed they did not agree, and the disagreement was invisible
12
+ * from every direction. `AGENTS.md` published `bunx rungate create-spec`;
13
+ * `package.json` declared no `bin`, so the command could not run at all; and
14
+ * `scripts/create-spec.ts` was not in `files`, so even a correct `bin` would
15
+ * have shipped a dispatcher pointing at a script the consumer never received.
16
+ * Three defects, each hiding behind the next.
17
+ *
18
+ * An agent reading `AGENTS.md` ran the command and it failed. An agent
19
+ * reading `package.json` saw no `bin`, concluded rungate had no CLI and was
20
+ * not distributable, and recommended hand-scaffolding a project. Both
21
+ * readings of the repo were wrong, which is the state a single source fixes.
22
+ *
23
+ * ## The scripts execute on import
24
+ *
25
+ * None of them guards on `import.meta.main`; each reads `process.argv` at the
26
+ * top level. That is why the dispatcher uses a dynamic `import()` and rewrites
27
+ * `process.argv` first — the import IS the invocation. Adding an
28
+ * `import.meta.main` guard to any of them would silently turn its subcommand
29
+ * into a no-op, so `test/cli-contract.test.ts` runs every command for real.
30
+ */
31
+
32
+ export interface CliCommand {
33
+ /** The script this runs, relative to the package root. Must be in `files`. */
34
+ script: string;
35
+ /** One line for `rungate --help`. */
36
+ summary: string;
37
+ /** Shown under the summary; the form a consumer types. */
38
+ usage: string;
39
+ /**
40
+ * The script defaults its project root to its OWN location, so the
41
+ * dispatcher must pass `--project-root <cwd>` or the command writes into
42
+ * the installed package.
43
+ *
44
+ * `scripts/create-spec.ts` ends with
45
+ * `const root = projectRoot ?? join(import.meta.dir, "..")`, which is
46
+ * correct for `bun scripts/create-spec.ts` inside this repo and wrong for
47
+ * every consumer: `bunx rungate create-spec "Title"` would write
48
+ * `node_modules/rungate/specs/TITLE-SPEC.md` and print `Created
49
+ * specs/TITLE-SPEC.md`, so the command reports success and the consumer's
50
+ * project is untouched. That is the #363 defect one layer in — the
51
+ * documented interface existing and doing the wrong thing.
52
+ *
53
+ * Flagged per-command rather than passed to everything, because a script
54
+ * that does not accept the flag would take it as a positional argument.
55
+ */
56
+ projectRootFlag?: true;
57
+ }
58
+
59
+ export const CLI_COMMANDS: Record<string, CliCommand> = {
60
+ scaffold: {
61
+ script: "scripts/scaffold-project.ts",
62
+ summary: "Generate or refresh a project's agent files, rules and conformity suite",
63
+ usage: "rungate scaffold <path> [--type code|workflow] [--fix] [--force] [--commit]",
64
+ },
65
+ "create-spec": {
66
+ script: "scripts/create-spec.ts",
67
+ summary: "Create a spec file with the required frontmatter",
68
+ usage: 'rungate create-spec "Title" ["what it governs"] [--sc "statement"]',
69
+ projectRootFlag: true,
70
+ },
71
+ "create-sc": {
72
+ script: "scripts/create-sc.ts",
73
+ summary: "Generate a matchable success-criterion line from a registered pattern",
74
+ usage: "rungate create-sc --pattern <name> --params '<json>' [--spec <file>]",
75
+ },
76
+ "convert-spec": {
77
+ script: "scripts/convert-spec.ts",
78
+ summary: "Convert an existing document into a testable spec",
79
+ usage: 'rungate convert-spec <file> [--dry-run] [--title "..."] [--governs "..."]',
80
+ projectRootFlag: true,
81
+ },
82
+ "audit-specs": {
83
+ script: "scripts/audit-specs.ts",
84
+ summary: "Report which success criteria are matched, unmatched or uncovered",
85
+ usage: "rungate audit-specs",
86
+ },
87
+ "sync-spec-tests": {
88
+ script: "scripts/sync-spec-tests.ts",
89
+ summary: "Regenerate the conformity suite from the specs",
90
+ usage: "rungate sync-spec-tests",
91
+ },
92
+ "generate-code-map": {
93
+ script: "scripts/generate-code-map.ts",
94
+ summary: "Regenerate CODE-MAP.md from the source tree",
95
+ usage: "rungate generate-code-map",
96
+ },
97
+ "extract-constraints": {
98
+ script: "scripts/extract-constraints.ts",
99
+ summary: "Extract constraints from a project's docs into agent rules",
100
+ usage: "rungate extract-constraints",
101
+ },
102
+ };
103
+
104
+ /** The commands the AGENTS.md generator may publish to a consumer. */
105
+ export function publishedCommands(): string[] {
106
+ return Object.keys(CLI_COMMANDS);
107
+ }
108
+
109
+ export function helpText(): string {
110
+ const rows = Object.entries(CLI_COMMANDS).map(
111
+ ([name, c]) => ` ${name.padEnd(20)}${c.summary}\n ${" ".repeat(20)}${c.usage}`,
112
+ );
113
+ return [
114
+ "rungate — ship harness: conformity tests, scaffold, and agent briefs",
115
+ "",
116
+ "Usage: rungate <command> [options]",
117
+ "",
118
+ "Commands:",
119
+ ...rows,
120
+ "",
121
+ "Run a command with no arguments for its own usage where it has one.",
122
+ ].join("\n");
123
+ }
124
+
125
+ /**
126
+ * Every `bunx <pkg> <cmd>` invocation in a markdown command table.
127
+ *
128
+ * Used in both directions by `test/cli-contract.test.ts`: a published command
129
+ * must dispatch, and a dispatching command's script must be shipped. Written
130
+ * to find the invocation ANYWHERE in the text rather than only in a table
131
+ * row, because a documented-but-broken command is just as broken in a prose
132
+ * sentence as in a table.
133
+ */
134
+ export function bunxInvocations(markdown: string, pkg: string): string[] {
135
+ const pattern = new RegExp(String.raw`\bbunx\s+${pkg}\s+([a-z][a-z0-9-]*)`, "g");
136
+ return [...new Set([...markdown.matchAll(pattern)].map(m => m[1]))];
137
+ }