rungate 0.8.13 → 0.8.16

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 (88) hide show
  1. package/README.md +182 -0
  2. package/gates/.gate-salt +1 -1
  3. package/hooks/HarnessAFKGate.hook.ts +5 -1
  4. package/hooks/HookCurrency.hook.ts +11 -8
  5. package/hooks/MergeGuard.hook.ts +7 -1
  6. package/hooks/StaleTTLCleanup.hook.ts +4 -4
  7. package/hooks/VerifyPhaseLock.hook.ts +3 -3
  8. package/hooks/lib/findWorkflow.ts +3 -2
  9. package/hooks/lib/paths.ts +14 -2
  10. package/hooks/lib/utils.ts +23 -3
  11. package/lib/active-milestone.ts +50 -0
  12. package/lib/ai-review-rounds.ts +99 -0
  13. package/lib/ai-review-suppression.ts +200 -21
  14. package/lib/bash-write-guard.ts +397 -23
  15. package/lib/board-flow.ts +280 -0
  16. package/lib/board-lane-health.ts +578 -0
  17. package/lib/board-mirror.ts +136 -39
  18. package/lib/board-ready-fanout.ts +297 -14
  19. package/lib/board-ready-rule.ts +1211 -0
  20. package/lib/board-throughput.ts +136 -0
  21. package/lib/board-walkthrough.ts +240 -0
  22. package/lib/body-evidence.ts +203 -0
  23. package/lib/branch-protection.ts +399 -9
  24. package/lib/bun-version.ts +36 -0
  25. package/lib/cli-commands.ts +75 -4
  26. package/lib/closing-reference-audit.ts +307 -6
  27. package/lib/config-loader.ts +254 -25
  28. package/lib/config-readers.ts +170 -10
  29. package/lib/config-trackable.ts +96 -57
  30. package/lib/conformity.ts +121 -7
  31. package/lib/create-sc.ts +25 -2
  32. package/lib/derived-spec.ts +21 -9
  33. package/lib/filing-compliance.ts +367 -0
  34. package/lib/filing-plan.ts +47 -21
  35. package/lib/finding-arbiter.ts +79 -5
  36. package/lib/finding-jury.ts +43 -4
  37. package/lib/finding-promotion.ts +1123 -0
  38. package/lib/generators/agents-md.ts +149 -0
  39. package/lib/git-isolation.ts +137 -1
  40. package/lib/github-api-base.ts +66 -0
  41. package/lib/github.ts +194 -9
  42. package/lib/graphql-cursor.ts +80 -0
  43. package/lib/hook-scopes.ts +78 -0
  44. package/lib/issue-create-override.ts +415 -3
  45. package/lib/issue-decomposition.ts +124 -7
  46. package/lib/issue-extraction.ts +9 -7
  47. package/lib/issue-file-overlap.ts +373 -0
  48. package/lib/issue-filing-gate.ts +1109 -52
  49. package/lib/issue-repair.ts +90 -9
  50. package/lib/issue-shape.ts +199 -0
  51. package/lib/live-issues.ts +31 -2
  52. package/lib/local-work.ts +423 -0
  53. package/lib/markdown-fence.ts +134 -0
  54. package/lib/milestone-title.ts +46 -0
  55. package/lib/scaffold/ai-review-findings.ts +148 -3
  56. package/lib/scaffold/ai-review-step.ts +65 -5
  57. package/lib/scaffold/ai-review-unmeasured-workflow.ts +3 -0
  58. package/lib/scaffold/steps.ts +115 -9
  59. package/lib/source-census.ts +108 -0
  60. package/lib/spec-deps.ts +55 -11
  61. package/lib/spec-placement.ts +203 -13
  62. package/lib/spec-registry.ts +75 -16
  63. package/lib/spec-source.ts +609 -0
  64. package/lib/spec-write-sweep.ts +4 -0
  65. package/lib/stage-ladder.ts +896 -3
  66. package/lib/state-claim-readings.ts +252 -0
  67. package/lib/success-doc.ts +7 -6
  68. package/lib/test-command-positions.ts +135 -1
  69. package/lib/work-status.ts +551 -0
  70. package/lib/worktree-repo.ts +14 -2
  71. package/package.json +7 -1
  72. package/scripts/ai-review-findings.ts +8 -13
  73. package/scripts/ai-review-threads.ts +16 -17
  74. package/scripts/audit-closing-references.ts +330 -0
  75. package/scripts/audit-specs.ts +59 -103
  76. package/scripts/board-conformance.ts +747 -40
  77. package/scripts/board-mirror.ts +594 -13
  78. package/scripts/board-ready.ts +979 -0
  79. package/scripts/board-snapshot.ts +464 -12
  80. package/scripts/claim-files.ts +578 -0
  81. package/scripts/criterion-inventory.ts +526 -50
  82. package/scripts/finding-promotion.ts +547 -0
  83. package/scripts/generate-code-map.ts +1 -1
  84. package/scripts/plan-issues.ts +279 -40
  85. package/scripts/plan-spec.ts +105 -3
  86. package/scripts/sync-sc-status.ts +147 -7
  87. package/scripts/worktree-census.ts +958 -0
  88. package/scripts/worktree-sweep.ts +269 -0
@@ -0,0 +1,609 @@
1
+ /**
2
+ * Where a reading's spec came from — the shipped ref, or the tree you are
3
+ * standing in.
4
+ *
5
+ * Stage D's D3: *"it fetches and reads origin/main, never a working tree — a
6
+ * stale tree and a missing feature look identical"*. `scripts/board-snapshot.ts`
7
+ * read the spec with a bare `readFileSync`, so every reading it produced was
8
+ * scoped by whatever branch the caller happened to be on, and the output said
9
+ * nothing about which. A branch halfway through editing a Phase placement
10
+ * table and a branch four days behind `main` produce different numbers against
11
+ * the SAME live board, and both print as an ordinary reading.
12
+ *
13
+ * ## The three answers, and why `untracked` is not a failure
14
+ *
15
+ * | reading | when | what the caller does |
16
+ * |---|---|---|
17
+ * | `ref` | the path is tracked and `origin/<branch>` has it | measure it — this is the shipped spec |
18
+ * | `untracked` | git does not know the path at all | read it from disk, and SAY so |
19
+ * | `unmeasured` | git knows the path and the ref read failed | refuse; do NOT fall back to disk |
20
+ *
21
+ * A file git has never heard of has no `origin/main` version to read, and that
22
+ * is a fact about the file rather than a failure of the reader — a planted
23
+ * fixture in an `mkdtemp` is the ordinary case. **An untracked path is
24
+ * reported by name**, so a reading taken against one cannot be mistaken for a
25
+ * reading taken against the shipped spec.
26
+ *
27
+ * The third row is the one that matters. `catch { return readFileSync(...) }`
28
+ * is the whole defect wearing a repair: it turns "the fetch failed" into
29
+ * "here is the working tree", silently, in exactly the case where the two
30
+ * disagree most. That is *Silent Default Substitution* from
31
+ * `.claude/rules/config-access.md`, and this module refuses instead.
32
+ *
33
+ * ## Fetch immediately before reading, never once at startup
34
+ *
35
+ * `origin/main` is a local ref and it is as old as the last fetch. The fetch
36
+ * and the `git show` are adjacent here on purpose: anything between them is a
37
+ * window in which the remote moves and the reading cites a ref nobody can
38
+ * reproduce.
39
+ *
40
+ * A fetch that fails is NOT fatal on its own — an offline machine still has a
41
+ * usable `origin/main` from its last fetch, and refusing there would make the
42
+ * command unrunnable on a plane for no reading-level reason. It is reported in
43
+ * `staleness`, so the caller can say the ref may be behind.
44
+ */
45
+
46
+ import { realpathSync } from "fs";
47
+ import { basename, dirname, join, relative, resolve, sep } from "path";
48
+
49
+ /** What a single git invocation came back with. */
50
+ export interface GitRun {
51
+ ok: boolean;
52
+ stdout: string;
53
+ stderr: string;
54
+ /**
55
+ * The process's exit status, or `null` when it never ran.
56
+ *
57
+ * **Carried because `ok: false` spans two opposite facts.** `git ls-files
58
+ * --error-unmatch` exits **1** for "this path is not tracked", which is an
59
+ * answer, and **128** for "this is not a repository / the object store is
60
+ * broken", which is the reader failing. Collapsing them is the
61
+ * working-tree fallback reached through a side door: a `root` pointed at
62
+ * the wrong place reports every path untracked, reads disk, and prints a
63
+ * reading. Found by security review of PR #1896, round 1 — in the module
64
+ * whose docblock says it refuses exactly this.
65
+ *
66
+ * `null` is a spawn that never happened — no `git` on PATH. That is never
67
+ * an answer about a file.
68
+ */
69
+ code: number | null;
70
+ }
71
+
72
+ /**
73
+ * Strip anything credential-shaped out of text bound for a log line.
74
+ *
75
+ * `git fetch` failures quote the remote URL, and a CI checkout's remote is
76
+ * routinely `https://x-access-token:<TOKEN>@github.com/owner/repo`. This
77
+ * module interpolates that stderr into `staleness`, and
78
+ * `scripts/board-conformance.ts` prints it — so a failed fetch on a runner
79
+ * put a live token in the build log. Actions masks secrets it was given;
80
+ * it cannot mask one that reached the URL by another route.
81
+ *
82
+ * Applied at the point of interpolation rather than trusted to the caller:
83
+ * the caller is a log line, and a sanitiser the emitter has to remember is
84
+ * one that gets forgotten. Found by security review of PR #1896, round 1.
85
+ *
86
+ * **EVERY interpolation, not every stderr.** Round 3 found the one arm that
87
+ * quotes a git *stdout* — `--git-dir`'s path — and it was unwrapped because
88
+ * the rule in this docblock said "stderr" and a path looked exempt. A path
89
+ * is `GIT_DIR` when `GIT_DIR` is set, and `GIT_DIR` is a string somebody
90
+ * else chose. The narrower rule is the defect: a sanitiser with a carve-out
91
+ * is one each new arm has to re-decide, so there is no carve-out.
92
+ */
93
+ export function redactCredentials(text: string): string {
94
+ return text
95
+ // `scheme://user:secret@host` — the userinfo is the whole payload.
96
+ .replace(/:\/\/[^/@\s]+@/g, "://***@")
97
+ // GitHub's own token shapes, in case one is quoted outside a URL.
98
+ .replace(/\bgh[pousr]_[A-Za-z0-9]{16,}/g, "***")
99
+ .replace(/\bgithub_pat_[A-Za-z0-9_]{16,}/g, "***");
100
+ }
101
+
102
+ /** `git -C <root> <args>` — injected so a test never reaches a real repository. */
103
+ export type GitRunner = (args: readonly string[]) => GitRun;
104
+
105
+ export type SpecSource =
106
+ | {
107
+ kind: "ref";
108
+ /** `origin/main`, as given. */
109
+ ref: string;
110
+ /** The commit `ref` resolved to, read in the same breath as the content. */
111
+ sha: string;
112
+ /** The path as git spells it — repository-relative, forward slashes. */
113
+ path: string;
114
+ content: string;
115
+ /**
116
+ * Why the ref may be behind the remote, or null when the fetch succeeded.
117
+ *
118
+ * Never a refusal. A stale `origin/main` is still `origin/main`, and the
119
+ * caller's provenance line is the right place to say it might be old.
120
+ */
121
+ staleness: string | null;
122
+ /**
123
+ * True when the working tree's copy differs from `ref`'s, **and `null`
124
+ * when the comparison itself failed.**
125
+ *
126
+ * D4's half of this lives elsewhere; what this flag buys D3 is that the
127
+ * provenance line can say "I read the shipped spec, and yours differs"
128
+ * rather than leaving the reader to wonder which they got.
129
+ *
130
+ * The third state is not decoration. `git diff --quiet` exits 0 for
131
+ * same and 1 for differs, and anything else is the comparison not
132
+ * happening — which `!ok` printed as a confident "DIFFERS". A reader
133
+ * cannot act on a difference nobody measured.
134
+ */
135
+ worktreeDiffers: boolean | null;
136
+ /** Why the comparison failed, when `worktreeDiffers` is `null`. */
137
+ worktreeCompareFailed: string | null;
138
+ }
139
+ | { kind: "untracked"; path: string; why: string }
140
+ | { kind: "unmeasured"; why: string };
141
+
142
+ /**
143
+ * The ref a reading should be taken against, unless a caller names another.
144
+ *
145
+ * `origin/main` rather than `main`: a local `main` is a working tree too, and
146
+ * it is behind the remote for exactly as long as nobody pulls.
147
+ */
148
+ export const DEFAULT_SPEC_REF = "origin/main";
149
+
150
+ /**
151
+ * `origin/main` -> `{ remote: "origin", branch: "main" }`, or null when the
152
+ * ref does not name both.
153
+ *
154
+ * **One decider.** Round 4 read the remote back out of the fetch argv as
155
+ * `fetchArgs[1]`, which is `--quiet`, and asked `git remote get-url
156
+ * --quiet` — so every unresolvable ref fell through to a working-tree read,
157
+ * which is the fail-open that arm exists to prevent. The fake could not see
158
+ * it: it keys answers on the subcommand and never looked at the operand.
159
+ */
160
+ export function splitRef(ref: string): { remote: string; branch: string } | null {
161
+ const at = ref.indexOf("/");
162
+ if (at <= 0 || at === ref.length - 1) return null;
163
+ return { remote: ref.slice(0, at), branch: ref.slice(at + 1) };
164
+ }
165
+
166
+ /**
167
+ * `origin/main` -> `origin +main:refs/remotes/origin/main`, for the fetch
168
+ * that refreshes it.
169
+ *
170
+ * **The destination is explicit, and that is the whole point.** `git fetch
171
+ * origin main` updates `refs/remotes/origin/main` only as an *opportunistic*
172
+ * side effect of the remote's already-configured `remote.<name>.fetch`
173
+ * refspec happening to match — and `actions/checkout` configures a narrow
174
+ * one naming just the PR's branch. Measured on git 2.50.1 against a bare
175
+ * upstream, with the ordinary clone as the control:
176
+ *
177
+ * wildcard `+refs/heads/*:refs/remotes/origin/*` origin/main RESOLVES
178
+ * narrow `+refs/heads/some-pr:refs/remotes/…` UNKNOWN REVISION
179
+ * narrow, with this explicit destination origin/main RESOLVES
180
+ *
181
+ * In the middle row `fetch` exits 0 and `FETCH_HEAD` resolves — the data is
182
+ * there — so the next `rev-parse origin/main` fails and the whole reading
183
+ * refuses as unmeasured on a remote the spec is genuinely fetchable from.
184
+ * That is this module's one prohibited outcome: an ordinary, recoverable
185
+ * situation wearing a broken reader's face.
186
+ *
187
+ * Forced (`+`) to match what a clone writes. A remote-tracking ref follows
188
+ * the remote wherever it goes, and refusing a non-fast-forward here would
189
+ * reintroduce the same refusal after any force-push to the base branch.
190
+ * Review of #1896 round 9.
191
+ */
192
+ function fetchArgsFor(ref: string): string[] | null {
193
+ const parts = splitRef(ref);
194
+ if (parts === null) return null;
195
+ const dest = `+${parts.branch}:refs/remotes/${parts.remote}/${parts.branch}`;
196
+ return ["fetch", "--quiet", parts.remote, dest];
197
+ }
198
+
199
+ /**
200
+ * Resolve the spec's content from `ref`, or say precisely why not.
201
+ *
202
+ * `absPath` is where the caller believes the spec is; `root` is the repository
203
+ * it should be read relative to. Both are taken rather than derived, because
204
+ * `board-snapshot` accepts an absolute spec path and deriving a root from it
205
+ * would silently measure a different checkout.
206
+ */
207
+ /**
208
+ * Canonicalise a directory, or `null` when it cannot be resolved.
209
+ *
210
+ * Injected for the same reason {@link GitRunner} is: a case that touches the
211
+ * real filesystem measures whatever this machine happens to look like. The
212
+ * live one returns `null` on ENOENT rather than throwing, because an
213
+ * unresolvable path is a reading this module must refuse, not a crash.
214
+ */
215
+ export type RealPath = (p: string) => string | null;
216
+
217
+ export const LIVE_REALPATH: RealPath = p => {
218
+ try {
219
+ return realpathSync(p);
220
+ } catch {
221
+ return null;
222
+ }
223
+ };
224
+
225
+ export function resolveSpecSource(opts: {
226
+ root: string;
227
+ absPath: string;
228
+ ref?: string;
229
+ git: GitRunner;
230
+ realpath?: RealPath;
231
+ }): SpecSource {
232
+ const ref = opts.ref ?? DEFAULT_SPEC_REF;
233
+ const realpath = opts.realpath ?? LIVE_REALPATH;
234
+
235
+ // IS THERE A REPOSITORY AT ALL, FIRST — and is `git` even runnable.
236
+ //
237
+ // Three outcomes, and they are NOT one: a spawn that never happened is
238
+ // the reader broken (UNMEASURED); a directory that is not a repository
239
+ // genuinely has no `origin/main`, so disk is the only copy there is and
240
+ // saying so is the honest reading; and a repository proceeds.
241
+ // `--show-toplevel`, which answers BOTH questions in one call: whether
242
+ // there is a work tree, and where it ends. The second half matters as
243
+ // much as the first — see the containment check below.
244
+ const inRepo = opts.git(["rev-parse", "--show-toplevel"]);
245
+ if (inRepo.code === null) {
246
+ return {
247
+ kind: "unmeasured",
248
+ why:
249
+ `\`git\` could not be run in ${opts.root}: ${redactCredentials(inRepo.stderr.trim()) || "it never started"}. ` +
250
+ `A reader that cannot run has not found an untracked file — reading the working tree here would print a ` +
251
+ `reading scoped by whatever branch this is.`,
252
+ };
253
+ }
254
+ const top = inRepo.stdout.trim();
255
+ // **AN `ok` ANSWER OF NOTHING IS UNMEASURED, NEVER UNTRACKED.** git
256
+ // succeeded and said something this function cannot interpret, and
257
+ // "I do not understand the answer" is not "there is no repository".
258
+ // Round 2 of #1896's security review; this arm used to return untracked
259
+ // and a case in the battery asserted that wrong answer.
260
+ if (inRepo.ok && top === "") {
261
+ return {
262
+ kind: "unmeasured",
263
+ why:
264
+ `\`git rev-parse --show-toplevel\` exited 0 in ${opts.root} and printed nothing. That is an answer this ` +
265
+ `reader cannot interpret, not a directory without a repository — and the difference decides whether the ` +
266
+ `working tree gets read.`,
267
+ };
268
+ }
269
+ if (!inRepo.ok) {
270
+ // **A SECOND PROBE, BECAUSE 128 SPANS TWO FACTS.** `--show-toplevel`
271
+ // exits 128 for "no repository anywhere above here" and for "there is
272
+ // a repository and its work tree is unusable" — a bare repo, an
273
+ // unreadable `.git`. The first is an ordinary planted fixture and disk
274
+ // is genuinely the only copy; the second is a reader that failed, and
275
+ // falling back there is the defect this module exists to prevent.
276
+ //
277
+ // Not two deciders over one question: `--git-dir` answers *is there a
278
+ // repository*, `--show-toplevel` answers *does it have a work tree I
279
+ // can see*. Measured — in a plain temp directory both exit 128, which
280
+ // is what makes "both failed" the signal for no repository at all.
281
+ const gitDir = opts.git(["rev-parse", "--git-dir"]);
282
+ if (gitDir.ok) {
283
+ return {
284
+ kind: "unmeasured",
285
+ why:
286
+ `${opts.root} IS a git repository (\`--git-dir\` resolved to ` +
287
+ `${redactCredentials(gitDir.stdout.trim()) || "an unnamed path"}) ` +
288
+ `and \`--show-toplevel\` still failed with exit ${inRepo.code}: ` +
289
+ `${redactCredentials(inRepo.stderr.trim()) || "no reason given"}. A work tree that cannot be located is a ` +
290
+ `reader that failed, not a file that is untracked.`,
291
+ };
292
+ }
293
+ return {
294
+ kind: "untracked",
295
+ path: opts.absPath,
296
+ // THE EXIT AND BOTH REASONS, quoted. No text matcher decides which
297
+ // kind of 128 this was — the two probes do, and the line says what
298
+ // each of them said so a reader can judge for themselves.
299
+ why:
300
+ `${opts.root} is not inside a git work tree and is not a repository (\`--show-toplevel\` exit ` +
301
+ `${inRepo.code}: ${redactCredentials(inRepo.stderr.trim()) || "no reason given"}; \`--git-dir\` exit ` +
302
+ `${gitDir.code}), so there is no ${ref} to read and the file on disk is the only copy that exists. ` +
303
+ `The reading below was taken against it.`,
304
+ };
305
+ }
306
+
307
+ // **A PATH OUTSIDE THE REPOSITORY IS UNTRACKED, AND IT IS DECIDED HERE
308
+ // RATHER THAN BY GIT'S EXIT CODE.** `ls-files --error-unmatch` exits 128
309
+ // for a path outside the work tree AND for a broken object store, so the
310
+ // arm below cannot separate them — asking the question before git does
311
+ // is what lets 128 mean exactly one thing when it arrives. The
312
+ // alternative is matching on `is outside repository` in stderr, which is
313
+ // a detector a locale or a git release can silently narrow.
314
+ //
315
+ // This is also the ordinary case rather than an edge: every fixture in
316
+ // `test/board-snapshot.test.ts` plants a spec in an `mkdtemp` while the
317
+ // project root is this checkout.
318
+ // **CANONICALISED BOTH SIDES, because a lexical compare has a parser
319
+ // differential against the filesystem.** On darwin `/tmp` IS
320
+ // `/private/tmp` and the volume is case-insensitive, so a path genuinely
321
+ // inside the work tree can read as outside — and the error falls toward
322
+ // reading the working tree, which is the direction that matters. Round 2
323
+ // of #1896's security review.
324
+ //
325
+ // `realpath` is resolved on the DIRECTORY and the basename re-attached,
326
+ // so a spec that does not exist yet still canonicalises; a directory that
327
+ // cannot be resolved at all is UNMEASURED rather than untracked, for the
328
+ // same reason every other failure here is.
329
+ const canonTop = realpath(resolve(top));
330
+ const canonAbs = realpath(resolve(dirname(opts.absPath)));
331
+ if (canonTop === null || canonAbs === null) {
332
+ return {
333
+ kind: "unmeasured",
334
+ why:
335
+ `the work tree at ${top} or the directory holding ${opts.absPath} could not be resolved to a real path, ` +
336
+ `so whether the spec is inside the repository is unknown. Guessing it is outside would read the working ` +
337
+ `tree; guessing it is inside would read a ref for a file somewhere else.`,
338
+ };
339
+ }
340
+ const real = join(canonAbs, basename(opts.absPath));
341
+ const within = real === canonTop || real.startsWith(canonTop + sep);
342
+ if (!within) {
343
+ return {
344
+ kind: "untracked",
345
+ path: opts.absPath,
346
+ why:
347
+ `${opts.absPath} is outside the work tree at ${top}, so ${ref} has no version of it. ` +
348
+ `The reading below was taken against the file on disk.`,
349
+ };
350
+ }
351
+
352
+ // **THE REPOSITORY-RELATIVE PATH IS DERIVED, NOT ASKED OF `ls-files`.**
353
+ // Both operands are already canonical and containment is already decided,
354
+ // so `relative` is the whole computation and it needs no subprocess. What
355
+ // it replaces is `ls-files --full-name`, which returned this string as a
356
+ // side effect of answering a question about the LOCAL index — see below.
357
+ const path = relative(canonTop, real).split(sep).join("/");
358
+ if (path === "" || path.startsWith("..")) {
359
+ return {
360
+ kind: "unmeasured",
361
+ why:
362
+ `${opts.absPath} resolved to ${real}, which is the work tree at ${canonTop} itself rather than a file ` +
363
+ `inside it. A spec is a file; there is no reading to take here.`,
364
+ };
365
+ }
366
+
367
+ const fetchArgs = fetchArgsFor(ref);
368
+ let staleness: string | null = null;
369
+ if (fetchArgs === null) {
370
+ staleness = `${ref} does not name a remote and a branch, so nothing was fetched and it is as old as the last one`;
371
+ } else {
372
+ const fetched = opts.git(fetchArgs);
373
+ if (!fetched.ok) {
374
+ staleness =
375
+ `\`git ${fetchArgs.join(" ")}\` failed, so ${ref} is as old as the last successful fetch: ` +
376
+ `${redactCredentials(fetched.stderr.trim()) || "no reason given"}`;
377
+ }
378
+ }
379
+
380
+ // THE SHA AND THE CONTENT, adjacent. Resolved after the fetch so the two
381
+ // describe the same ref, and reported together so a reading can be
382
+ // re-taken by somebody who was not here.
383
+ const resolved = opts.git(["rev-parse", ref]);
384
+ const sha = resolved.stdout.trim();
385
+ if (!resolved.ok || sha === "") {
386
+ // **AN UNRESOLVABLE REF FAILS CLOSED, AND THE ONE WIDENING IS A
387
+ // MISSING REMOTE.** Round 3 widened it with the LOCAL INDEX instead —
388
+ // untracked here plus an unresolvable ref read disk — and that is the
389
+ // hole this module had just closed, re-opened one arm along: a stale
390
+ // checkout missing a newly-shipped spec is untracked locally, and a
391
+ // transient resolution failure then hands it a working-tree read. The
392
+ // local index cannot be the evidence that permits a disk read; it is
393
+ // the thing being doubted.
394
+ //
395
+ // A remote that does not exist is different in kind. `origin/main`
396
+ // cannot ever resolve there and no fetch will change it, so there is
397
+ // no shipped version to be wrong about. `git remote get-url` is the
398
+ // probe, and only its exit 0 counts as an answer — anything else is a
399
+ // reading nobody took.
400
+ const remote = splitRef(ref)?.remote ?? null;
401
+ if (remote !== null) {
402
+ // **EXIT 2 AND NOTHING ELSE.** Measured: `git remote get-url` exits
403
+ // 2 for a remote that is not configured and 0 for one that is. Any
404
+ // other code is git failing to answer — a malformed `.git/config` is
405
+ // 128 — and round 5 accepted every non-null non-zero here, so a
406
+ // broken config read as "no remote" and fell through to a
407
+ // working-tree read. Round 6.
408
+ const url = opts.git(["remote", "get-url", remote]);
409
+ if (!url.ok && url.code !== 2 && url.code !== 0) {
410
+ return {
411
+ kind: "unmeasured",
412
+ why:
413
+ `\`git remote get-url ${remote}\` failed in ${opts.root} with exit ${url.code}: ` +
414
+ `${redactCredentials(url.stderr.trim()) || "no reason given"}. That is git unable to say whether the ` +
415
+ `remote exists, which is not the same as it not existing.`,
416
+ };
417
+ }
418
+ if (!url.ok) {
419
+ return {
420
+ kind: "untracked",
421
+ path: opts.absPath,
422
+ why:
423
+ `${opts.root} has no remote named \`${remote}\`, so ${ref} can never resolve and there is no shipped ` +
424
+ `version of ${opts.absPath} to read. The reading below was taken against the file on disk.`,
425
+ };
426
+ }
427
+ }
428
+ return {
429
+ kind: "unmeasured",
430
+ why:
431
+ `${ref} does not resolve in ${opts.root}: ${redactCredentials(resolved.stderr.trim()) || "no reason given"}. ` +
432
+ `Falling back to the working tree would report a reading scoped by whatever branch this is.`,
433
+ };
434
+ }
435
+
436
+ // **DOES THE REF HAVE IT — ASKED OF THE REF.**
437
+ //
438
+ // This used to be `git ls-files --error-unmatch`, and that is a question
439
+ // about the LOCAL index. The two answers diverge in exactly the direction
440
+ // this module exists to prevent: a spec added on `origin/main` after this
441
+ // checkout was cut is absent locally and present at the ref, so the local
442
+ // question said "untracked" and the caller read disk — or, in
443
+ // `board-snapshot`, refused with "no such spec" while the shipped copy
444
+ // sat in the ref it was asked to read. Found by review of #1896 round 3,
445
+ // and no case could see it: every fixture keyed `ls-files` to the same
446
+ // branch state as `show`, so the suite varied one axis and the defect
447
+ // sat on the other.
448
+ //
449
+ // The cost is that an untracked path inside the work tree now costs a
450
+ // fetch, because trackedness is no longer known before the ref is
451
+ // resolved. That is the right trade: the saved fetch was buying a wrong
452
+ // answer.
453
+ // **`ls-tree`, NOT `cat-file -e` — because `cat-file -e` has no exit code
454
+ // for "the ref has not got it".** Measured against real git at
455
+ // b40a62a0: an absent path exits **128**, and so does a bad object name,
456
+ // and so does a corrupt store. Round 3 of this review shipped
457
+ // `atRef.code !== 1` over it, which sent every absent path to UNMEASURED
458
+ // and left the untracked arm unreachable — and the suite stayed green
459
+ // because the fake answered `1`, a code real git never returns here. A
460
+ // fixture that encodes semantics git does not have is a suite measuring
461
+ // nothing; `test/spec-source.test.ts` now pins these codes against the
462
+ // real binary so the fake cannot drift from it again.
463
+ //
464
+ // `ls-tree` separates the three answers without an exit code doing the
465
+ // work: it exits 0 whether or not the path is there, prints the object's
466
+ // TYPE when it is, and prints nothing when it is not. Anything non-zero
467
+ // is the reader failing. `%(objecttype)` also answers the second half —
468
+ // a directory is a `tree`, and `git show <sha>:<dir>` is a listing, not
469
+ // a spec.
470
+ //
471
+ // **`--full-tree`, because a pathspec is resolved against the PROCESS's
472
+ // cwd and that is `root`, not the work tree top.** When `root` is a
473
+ // subdirectory of the toplevel — which the containment logic above
474
+ // exists to support — a root-relative `path` matches nothing from
475
+ // there, and `ls-tree` says so by exiting **0 with empty output**: the
476
+ // same bytes as "the ref has not got it". Measured from `lib/` against
477
+ // `README.md`: empty without the flag, `blob` with it. Round 5 of this
478
+ // review, in the arm round 4 had just added.
479
+ const atRef = opts.git(["ls-tree", "-z", "--full-tree", "--format=%(objecttype)", sha, "--", `:(literal)${path}`]);
480
+ if (!atRef.ok) {
481
+ return {
482
+ kind: "unmeasured",
483
+ why:
484
+ `\`git ls-tree\` failed in ${opts.root} with exit ${atRef.code}: ` +
485
+ `${redactCredentials(atRef.stderr.trim()) || "no reason given"}. That is a broken reader, not a spec the ` +
486
+ `ref has not got, and the difference is the whole of this module.`,
487
+ };
488
+ }
489
+ const objectType = atRef.stdout.replace(/\0/g, "").trim();
490
+ if (objectType !== "" && objectType !== "blob") {
491
+ return {
492
+ kind: "unmeasured",
493
+ why:
494
+ `${path} is a \`${objectType}\` in ${ref} (${sha}), not a file. A spec is a file; \`git show\` would hand ` +
495
+ `back a directory listing and this would print it as the spec's text.`,
496
+ };
497
+ }
498
+ if (objectType === "") {
499
+ // NOT AT THE REF — and now the LOCAL index is the right thing to ask,
500
+ // because the two cases it separates are both about this checkout: a
501
+ // spec added on this branch and not yet shipped, versus a file git has
502
+ // never heard of. Only the second may be read from disk.
503
+ const rel = opts.git(["ls-files", "--error-unmatch", "--", opts.absPath]);
504
+ if (!rel.ok && rel.code !== 1) {
505
+ return {
506
+ kind: "unmeasured",
507
+ why:
508
+ `\`git ls-files\` failed in ${opts.root} with exit ${rel.code}: ` +
509
+ `${redactCredentials(rel.stderr.trim()) || "no reason given"}. That is a broken reader, not an untracked ` +
510
+ `file, and the difference is the whole of this module.`,
511
+ };
512
+ }
513
+ if (rel.ok) {
514
+ return {
515
+ kind: "unmeasured",
516
+ why:
517
+ `${path} is tracked here but ${ref} (${sha}) has no version of it. That is a spec added on this branch ` +
518
+ `and not yet shipped, which is a different fact from a spec whose criteria are unplaced — reading the ` +
519
+ `working tree here would print the second while the first is true.`,
520
+ };
521
+ }
522
+ return {
523
+ kind: "untracked",
524
+ path: opts.absPath,
525
+ why:
526
+ `neither ${ref} (${sha}) nor git in ${opts.root} has any version of ${opts.absPath}, so the file on disk ` +
527
+ `is the only copy that exists. The reading below was taken against it.`,
528
+ };
529
+ }
530
+
531
+ const shown = opts.git(["show", `${sha}:${path}`]);
532
+ if (!shown.ok) {
533
+ return {
534
+ kind: "unmeasured",
535
+ why:
536
+ `${ref} (${sha}) has ${path} and \`git show\` could not produce it: ` +
537
+ `${redactCredentials(shown.stderr.trim()) || "no reason given"}. Two calls disagreeing about one object is a ` +
538
+ `broken reader, and reading the working tree here would print a reading scoped by whatever branch this is.`,
539
+ };
540
+ }
541
+
542
+ // The working-tree comparison is a `diff` against the index-and-disk copy,
543
+ // not a re-read of the file: `git diff` already knows about CRLF
544
+ // normalisation and filters, and a byte compare here would call a checkout
545
+ // difference a content difference on a tree configured for either.
546
+ //
547
+ // **AND IT IS READ AS THREE OUTCOMES, not as `!ok`.** `--quiet` exits 0
548
+ // for same and 1 for differs; anything else is the comparison failing,
549
+ // and `!ok` printed that as "your working tree's copy DIFFERS from it" —
550
+ // a measured fact nobody measured. Review of #1896 round 3. This is the
551
+ // last of the four sites where one boolean stood over a tri-state; the
552
+ // type change that stops a fifth site arriving is filed separately.
553
+ //
554
+ // **`:(top,literal)` — the same blob the `show` above read, addressed
555
+ // the same way.** This is the one call that cannot use `<rev>:<path>`
556
+ // syntax, so it is the one whose pathspec the process's cwd can move,
557
+ // and a pathspec matching nothing does not error: `--quiet` exits 0, so
558
+ // the failure would be "your copy matches" about a comparison that
559
+ // never ran. `:(top)` is `git diff`'s `--full-tree`.
560
+ //
561
+ // Round 7 reported the previous spelling — an absolute `absPath` — as
562
+ // that failure. **It does not reproduce:** measured from a nested cwd,
563
+ // the absolute pathspec, the `/private` realpath of it, and
564
+ // `:(top,literal)` all return exit 1 against an edited tree. This change
565
+ // ships as hardening, not as a fix, and carries no battery row claiming
566
+ // it binds. What it does buy is one path expression across all three
567
+ // calls instead of two.
568
+ const differs = opts.git(["diff", "--quiet", sha, "--", `:(top,literal)${path}`]);
569
+ const worktreeDiffers =
570
+ differs.code === 0 ? false : differs.code === 1 ? true : null;
571
+
572
+ return {
573
+ kind: "ref",
574
+ ref,
575
+ sha,
576
+ path,
577
+ content: shown.stdout,
578
+ staleness,
579
+ worktreeDiffers,
580
+ worktreeCompareFailed:
581
+ worktreeDiffers === null
582
+ ? `\`git diff --quiet\` exited ${differs.code}: ${redactCredentials(differs.stderr.trim()) || "no reason given"}`
583
+ : null,
584
+ };
585
+ }
586
+
587
+ /**
588
+ * One line naming where the content came from, for stderr.
589
+ *
590
+ * Always emitted, never only on the interesting arm. A provenance line that
591
+ * appears when something is odd and vanishes when it is not teaches the reader
592
+ * that silence means `origin/main`, and silence is also what a build printing
593
+ * nothing looks like.
594
+ */
595
+ export function describeSpecSource(source: SpecSource): string {
596
+ if (source.kind === "untracked") return `spec read from the working tree — ${source.why}`;
597
+ if (source.kind === "unmeasured") return `spec UNMEASURED — ${source.why}`;
598
+ const notes = [
599
+ source.worktreeDiffers === true ? "your working tree's copy DIFFERS from it" : null,
600
+ source.worktreeDiffers === null
601
+ ? `whether your working tree's copy differs is UNMEASURED — ${source.worktreeCompareFailed}`
602
+ : null,
603
+ source.staleness,
604
+ ].filter((s): s is string => s !== null);
605
+ return (
606
+ `spec read from ${source.ref} at ${source.sha.slice(0, 8)} (${source.path})` +
607
+ (notes.length > 0 ? ` — ${notes.join("; ")}` : "")
608
+ );
609
+ }
@@ -206,6 +206,10 @@ export const REASSIGNABLE_TARGETS: Record<string, string> = {
206
206
  "the artefact path given by --out, written only when that flag was passed",
207
207
  "gates/run-gate.ts::SF":
208
208
  "the gate state file this script exists to maintain",
209
+ "scripts/board-conformance.ts::flags.emitReadings":
210
+ "the board-readings JSON given by --emit-readings, written only when that flag was passed; never a spec (#1889)",
211
+ "scripts/board-conformance.ts::probeAt":
212
+ "the same --emit-readings path, written as a zero-byte probe and removed in the next statement — it proves the path is writable before the board is produced rather than at the last line; never a spec (#1889)",
209
213
  };
210
214
 
211
215
  /**