rungate 0.6.0 → 0.8.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 (164) hide show
  1. package/hooks/ActionVerificationGate.hook.ts +96 -0
  2. package/hooks/AgentBriefGuard.hook.ts +38 -0
  3. package/hooks/AgentVerdictCapture.hook.ts +87 -0
  4. package/hooks/AutoVerifyGate.hook.ts +79 -0
  5. package/hooks/BashToolGuard.hook.ts +65 -0
  6. package/hooks/BashWriteGuard.hook.ts +60 -0
  7. package/hooks/CommitEnforcement.hook.ts +130 -0
  8. package/hooks/DocHygiene.hook.ts +148 -0
  9. package/hooks/GateEnforcement.hook.ts +58 -0
  10. package/hooks/GateResultProtection.hook.ts +69 -0
  11. package/hooks/HarnessAFKGate.hook.ts +85 -0
  12. package/hooks/HookCurrency.hook.ts +99 -0
  13. package/hooks/IssueCloseGuard.hook.ts +149 -0
  14. package/hooks/MergeGuard.hook.ts +58 -0
  15. package/hooks/PostCompact.hook.ts +60 -0
  16. package/hooks/ProjectStateSync.hook.ts +103 -0
  17. package/hooks/SkillGuard.hook.ts +69 -0
  18. package/hooks/SpecConformityTrigger.hook.ts +43 -0
  19. package/hooks/SpecSCGuard.hook.ts +123 -0
  20. package/hooks/StaleTTLCleanup.hook.ts +141 -0
  21. package/hooks/TaskCompleted.hook.ts +51 -0
  22. package/hooks/TeamInit.hook.ts +85 -0
  23. package/hooks/TestSuiteGuard.hook.ts +70 -0
  24. package/hooks/TestSuiteRelease.hook.ts +85 -0
  25. package/hooks/TopLevelCdGuard.hook.ts +108 -0
  26. package/hooks/VerifyPhaseLock.hook.ts +84 -0
  27. package/hooks/WorkflowStateGuard.hook.ts +40 -0
  28. package/hooks/lib/agent-config.json +9 -0
  29. package/hooks/lib/agentDetection.ts +201 -0
  30. package/hooks/lib/comment-template.ts +86 -0
  31. package/hooks/lib/findWorkflow.ts +101 -0
  32. package/hooks/lib/parseStdin.ts +37 -0
  33. package/hooks/lib/paths.ts +111 -0
  34. package/hooks/lib/utils.ts +338 -0
  35. package/lib/affected-tests.ts +427 -0
  36. package/lib/agent-audit.ts +2 -3
  37. package/lib/agent-worktree.ts +287 -0
  38. package/lib/agents-md-sections.ts +81 -16
  39. package/lib/bash-write-guard.ts +373 -0
  40. package/lib/behavioral-cache.ts +150 -2
  41. package/lib/branch-cleanup.ts +279 -7
  42. package/lib/branch-protection.ts +790 -0
  43. package/lib/brief-ac-alignment.ts +104 -0
  44. package/lib/brief-references.ts +205 -0
  45. package/lib/bun-version.ts +93 -14
  46. package/lib/check-remedy.ts +140 -0
  47. package/lib/ci-checkout.ts +17 -0
  48. package/lib/ci-history-depth.ts +159 -0
  49. package/lib/ci-setup-step.ts +96 -0
  50. package/lib/claude-code-action.ts +85 -0
  51. package/lib/claude-tool-vocabulary.ts +188 -0
  52. package/lib/cli-commands.ts +15 -0
  53. package/lib/commit-sha.ts +42 -0
  54. package/lib/commit-subject.ts +90 -0
  55. package/lib/compliance-report.ts +377 -45
  56. package/lib/compliance.ts +191 -17
  57. package/lib/config-loader.ts +39 -1
  58. package/lib/config-trackable.ts +400 -0
  59. package/lib/conformity.ts +1087 -100
  60. package/lib/containment.ts +238 -0
  61. package/lib/content-hash.ts +24 -0
  62. package/lib/create-sc.ts +249 -16
  63. package/lib/dev-liveness.ts +180 -0
  64. package/lib/discovery-branch-points.ts +432 -0
  65. package/lib/discovery-stability.ts +481 -0
  66. package/lib/distribution-currency.ts +236 -0
  67. package/lib/doc-routing.ts +157 -0
  68. package/lib/evidence-prevalidator.ts +224 -2
  69. package/lib/evidence-satisfiability.ts +534 -12
  70. package/lib/failure-intake.ts +323 -0
  71. package/lib/fallow-availability.ts +157 -0
  72. package/lib/fs-write-capabilities.ts +232 -0
  73. package/lib/gate-enforcement.ts +222 -28
  74. package/lib/gate-names.ts +72 -0
  75. package/lib/gate-result-protection.ts +427 -0
  76. package/lib/gate-run-split.ts +147 -0
  77. package/lib/generators/agents-md.ts +140 -32
  78. package/lib/git-isolation.ts +140 -0
  79. package/lib/github.ts +15 -0
  80. package/lib/google-auth-action.ts +93 -0
  81. package/lib/harness-project.ts +48 -0
  82. package/lib/harness-provenance.ts +255 -0
  83. package/lib/hook-evidence.ts +235 -0
  84. package/lib/hook-scopes.ts +386 -0
  85. package/lib/hook-target-tree.ts +398 -0
  86. package/lib/hook-trees.ts +447 -0
  87. package/lib/intake-sources.ts +380 -0
  88. package/lib/js-top-level-code.ts +78 -10
  89. package/lib/junit-checks.ts +52 -0
  90. package/lib/late-env-spawn.ts +331 -0
  91. package/lib/launch-base.ts +376 -0
  92. package/lib/line-citation.ts +372 -0
  93. package/lib/orphan-reaper.ts +468 -0
  94. package/lib/parity-binding.ts +205 -0
  95. package/lib/paths.ts +96 -3
  96. package/lib/per-test-timeouts.ts +219 -0
  97. package/lib/phase2-decomposition.ts +1 -1
  98. package/lib/plan-coverage.ts +151 -0
  99. package/lib/prior-branch.ts +201 -8
  100. package/lib/process-table.ts +146 -0
  101. package/lib/project-state-derivation.ts +219 -0
  102. package/lib/project-state-root.ts +258 -0
  103. package/lib/published-artifact.ts +669 -0
  104. package/lib/readdir-sorted.ts +45 -0
  105. package/lib/review-execution-reading.ts +206 -0
  106. package/lib/review-tool-agreement.ts +433 -0
  107. package/lib/rule-promotion.ts +234 -0
  108. package/lib/rule-retirement.ts +525 -0
  109. package/lib/run-branch.ts +612 -0
  110. package/lib/rungate-schema.ts +19 -0
  111. package/lib/runner-home.ts +274 -0
  112. package/lib/sc-id-cross-tree.ts +103 -15
  113. package/lib/sc-ids.ts +121 -13
  114. package/lib/sc-reservations.ts +289 -0
  115. package/lib/scaffold/ai-review-findings.ts +409 -0
  116. package/lib/scaffold/ai-review-step.ts +5406 -64
  117. package/lib/scaffold/defaults.ts +82 -1
  118. package/lib/scaffold/managed-workflow.ts +587 -192
  119. package/lib/scaffold/owned-files.ts +152 -45
  120. package/lib/scaffold/pre-push-hook.ts +49 -5
  121. package/lib/scaffold/steps.ts +1836 -275
  122. package/lib/scaffold/workflow-census.ts +217 -0
  123. package/lib/scaffold/workflow-drift.ts +217 -0
  124. package/lib/scaffold/write-steps.ts +4 -0
  125. package/lib/scan-budget.ts +247 -0
  126. package/lib/scanner.ts +43 -51
  127. package/lib/scratch-roots.ts +50 -5
  128. package/lib/screenshot-discovery.ts +121 -0
  129. package/lib/screenshot-upload.ts +41 -1
  130. package/lib/secret-patterns.ts +511 -8
  131. package/lib/security-verdict.ts +1 -1
  132. package/lib/shell-path-interpolation.ts +594 -0
  133. package/lib/ship-mode.ts +219 -0
  134. package/lib/source-slice.ts +294 -0
  135. package/lib/stale-cleanup.ts +37 -3
  136. package/lib/suite-flake.ts +278 -0
  137. package/lib/suite-measurement.ts +23 -4
  138. package/lib/suite-run-reading.ts +241 -1
  139. package/lib/suite-timeout-margin.ts +193 -0
  140. package/lib/test-case-bodies.ts +883 -0
  141. package/lib/test-case-deletion.ts +653 -0
  142. package/lib/test-census.ts +97 -29
  143. package/lib/test-command-positions.ts +274 -0
  144. package/lib/test-suite-lock.ts +159 -16
  145. package/lib/text-dependents.ts +875 -0
  146. package/lib/tool-probe.ts +31 -9
  147. package/lib/top-level-cd.ts +393 -0
  148. package/lib/tree-entries.ts +89 -0
  149. package/lib/ts-ast.ts +200 -0
  150. package/lib/walk-test-files.ts +97 -0
  151. package/lib/workflow-actions.ts +263 -0
  152. package/lib/workflow-security.ts +29 -0
  153. package/lib/workflow-taint.ts +732 -0
  154. package/lib/worktree-cleanup.ts +65 -38
  155. package/lib/worktree-collect.ts +177 -5
  156. package/lib/worktree-repo.ts +68 -3
  157. package/package.json +4 -1
  158. package/scripts/ai-review-findings.ts +45 -0
  159. package/scripts/check-installed-hook-currency.ts +825 -0
  160. package/scripts/create-sc.ts +21 -1
  161. package/scripts/extract-constraints.ts +107 -7
  162. package/scripts/generate-code-map.ts +23 -30
  163. package/scripts/scaffold-project.ts +8 -1
  164. package/scripts/sync-sc-status.ts +77 -16
@@ -0,0 +1,669 @@
1
+ /**
2
+ * What a consumer actually installs, compared against this tree — by CONTENT,
3
+ * not by version string (#875).
4
+ *
5
+ * ## The defect this exists for
6
+ *
7
+ * `lib/distribution-standing.ts` compares three spellings of a NUMBER:
8
+ * `package.json`'s version, `SUCCESS.md`'s standing line, and the registry's
9
+ * `latest`. All three agreeing proves the repository and the registry agree
10
+ * about a NAME. It proves nothing about what is behind the name.
11
+ *
12
+ * Measured 2026-10-21, with all three agreeing on `0.6.0` and the check
13
+ * reporting standing fine:
14
+ *
15
+ * | Reading | Value |
16
+ * |---|---|
17
+ * | files `npm pack --dry-run` would publish | 235 |
18
+ * | files in the published `rungate@0.6.0` tarball | 192 |
19
+ * | published files whose bytes differ from the tree | 42 |
20
+ * | files the published artifact does not have at all | 43 |
21
+ *
22
+ * Same label, different software. That is the defect class
23
+ * `.claude/rules/checks-must-be-able-to-fail.md` calls *a detector narrower
24
+ * than what it detects*: the version string is the cheapest proxy for "the
25
+ * registry and the tree agree", and a proxy is a thing that can be satisfied
26
+ * directly without fixing anything. Here it is satisfied permanently, because
27
+ * the numbers keep agreeing for as long as nobody bumps.
28
+ *
29
+ * ## Why a content mismatch is not automatically a failure
30
+ *
31
+ * A repository that is AHEAD of its last release is the normal state between
32
+ * releases, so a check that reddened on "the tree differs from npm" would be
33
+ * red every day and would teach everyone to stop reading it. The distinction
34
+ * this module is built around is which of two things the difference means:
35
+ *
36
+ * | Versions | Content | Reading | Violation |
37
+ * |---|---|---|---|
38
+ * | tree > published | — | `AHEAD` | no — unreleased work is what a repo is for |
39
+ * | tree < published | — | `BEHIND` | no — a stale checkout, not a distribution defect |
40
+ * | equal | identical | `MATCHED` | no |
41
+ * | **equal** | **differs** | **`DIVERGED`** | **yes — the label lies** |
42
+ * | could not be taken | — | `UNMEASURED` | yes |
43
+ *
44
+ * `DIVERGED` is the only content state that is a defect, and it is a defect
45
+ * because of what the version string claims, not because of the bytes. A
46
+ * consumer running `bun add -d rungate@0.6.0` and a maintainer reading `0.6.0`
47
+ * in `package.json` are talking about different trees and nothing says so.
48
+ *
49
+ * ## UNMEASURED is a violation, deliberately
50
+ *
51
+ * `0`, `{}`, `null` and `SKIP` are indistinguishable from success
52
+ * (`.claude/rules/config-access.md`). A guard with no failing input in the
53
+ * configuration it actually runs in is worse than no guard, because the green
54
+ * is read as evidence — so an unreachable registry, an absent `npm`, a tarball
55
+ * this module cannot parse and a pack that named no files all produce
56
+ * `UNMEASURED`, and `artifactViolations` refuses it with the same force it
57
+ * refuses `DIVERGED`.
58
+ *
59
+ * ## One binding per question
60
+ *
61
+ * `artifactStanding` is the only thing that decides a reading and
62
+ * `artifactViolations` is a projection of it, so they cannot disagree — two
63
+ * deciders that agree are behaviourally one guard and no behavioural test can
64
+ * tell them apart.
65
+ *
66
+ * ## The question this does NOT answer
67
+ *
68
+ * `artifactViolations` refuses a lying LABEL, so the cheapest way to clear it
69
+ * is to bump `package.json` — `DIVERGED` becomes `AHEAD`, the refusal goes
70
+ * away, and the published tree is exactly as stale as it was.
71
+ * `lib/distribution-currency.ts` asks the consumer's question instead — is the
72
+ * published artifact the content this tree would publish — which takes no
73
+ * version string as an input and so does not move under that bump. Run it with
74
+ * `bun scripts/check-distribution-currency.ts`; it exits non-zero when a
75
+ * consumer cannot obtain this tree.
76
+ */
77
+ import { createHash } from "crypto";
78
+ import { readFileSync } from "fs";
79
+ import { join } from "path";
80
+ import { gunzipSync } from "zlib";
81
+ import { NPM_REGISTRY } from "./release-preflight";
82
+
83
+ /** One file in a publishable artifact, hashed by content. */
84
+ export interface ArtifactFile {
85
+ /** Path relative to the package root — `lib/conformity.ts`, never `package/lib/…`. */
86
+ path: string;
87
+ /** sha256 of the file's bytes, hex. */
88
+ sha256: string;
89
+ /** Bytes, so a reader can see the size of a difference without re-reading. */
90
+ size: number;
91
+ }
92
+
93
+ /** Every npm tarball entry is prefixed with this directory. */
94
+ export const TARBALL_ROOT = "package/";
95
+
96
+ /** Raised by anything in this module that could not take its reading. */
97
+ export class ArtifactUnmeasured extends Error {}
98
+
99
+ function sha256(bytes: Uint8Array): string {
100
+ return createHash("sha256").update(bytes).digest("hex");
101
+ }
102
+
103
+ /**
104
+ * Parse an uncompressed npm tarball into per-entry content hashes.
105
+ *
106
+ * Hand-rolled rather than extracted to disk: nothing from the registry is ever
107
+ * written to the filesystem, so there is no untrusted archive to unpack and no
108
+ * `tar` binary whose flags differ between macOS and CI.
109
+ *
110
+ * **Every way of failing to read throws.** A typeflag this does not understand
111
+ * — a pax extended header, a GNU long name, a symlink — is an entry whose name
112
+ * or content comes from somewhere this parser is not looking, and skipping it
113
+ * would silently shrink the published set, which makes the comparison agree for
114
+ * a reason that has nothing to do with the bytes. The header checksum is
115
+ * verified for the same reason: a misaligned read produces plausible garbage,
116
+ * and plausible garbage compares unequal, which reads as a finding.
117
+ */
118
+ export function parseNpmTarball(tar: Uint8Array): ArtifactFile[] {
119
+ const b = Buffer.from(tar.buffer, tar.byteOffset, tar.byteLength);
120
+ const out: ArtifactFile[] = [];
121
+ let off = 0;
122
+
123
+ /** A list with nothing in it compares equal to anything. Refuse instead. */
124
+ const done = (): ArtifactFile[] => {
125
+ if (out.length === 0) throw new ArtifactUnmeasured("the tarball holds no files at all");
126
+ return out.sort((x, y) => (x.path < y.path ? -1 : 1));
127
+ };
128
+
129
+ while (off + 512 <= b.length) {
130
+ const header = b.subarray(off, off + 512);
131
+ if (header.every(x => x === 0)) return done();
132
+
133
+ // The checksum is the sum of every header byte with the checksum field
134
+ // itself read as spaces. If this does not agree we are not on a header.
135
+ const declared = parseInt(header.subarray(148, 156).toString("utf8").replace(/\0.*$/, "").trim(), 8);
136
+ let sum = 0;
137
+ for (let i = 0; i < 512; i++) sum += i >= 148 && i < 156 ? 0x20 : header[i];
138
+ if (!Number.isFinite(declared) || declared !== sum) {
139
+ throw new ArtifactUnmeasured(
140
+ `tarball header at byte ${off} has checksum ${declared} but its bytes sum to ${sum} — ` +
141
+ `the parser is not aligned on a header and anything it reported would be noise`,
142
+ );
143
+ }
144
+
145
+ const name = header.subarray(0, 100).toString("utf8").replace(/\0.*$/, "");
146
+ const prefix = header.subarray(345, 500).toString("utf8").replace(/\0.*$/, "");
147
+ const type = String.fromCharCode(header[156]);
148
+ const sizeField = header.subarray(124, 136).toString("utf8").replace(/\0.*$/, "").trim();
149
+ const size = parseInt(sizeField, 8);
150
+ if (!Number.isFinite(size) || size < 0) {
151
+ throw new ArtifactUnmeasured(`tarball entry ${name} declares an unreadable size ${JSON.stringify(sizeField)}`);
152
+ }
153
+
154
+ const dataStart = off + 512;
155
+ const dataEnd = dataStart + size;
156
+ if (dataEnd > b.length) {
157
+ throw new ArtifactUnmeasured(
158
+ `tarball entry ${name} declares ${size} bytes but the archive ends ${dataEnd - b.length} bytes short — truncated`,
159
+ );
160
+ }
161
+
162
+ if (type !== "0" && type !== "\0" && type !== "5") {
163
+ throw new ArtifactUnmeasured(
164
+ `tarball entry ${name} has typeflag ${JSON.stringify(type)}, which this parser does not read. ` +
165
+ `Skipping it would shrink the published file set and the comparison would agree for the wrong reason`,
166
+ );
167
+ }
168
+
169
+ if (type !== "5") {
170
+ const full = prefix ? `${prefix}/${name}` : name;
171
+ if (!full.startsWith(TARBALL_ROOT)) {
172
+ throw new ArtifactUnmeasured(`tarball entry ${full} is not under ${TARBALL_ROOT}`);
173
+ }
174
+ out.push({
175
+ path: full.slice(TARBALL_ROOT.length),
176
+ sha256: sha256(b.subarray(dataStart, dataEnd)),
177
+ size,
178
+ });
179
+ }
180
+
181
+ off = dataStart + Math.ceil(size / 512) * 512;
182
+ }
183
+
184
+ // Falling out of the loop means the terminating zero blocks were never
185
+ // reached. Every tar npm writes ends with two of them, so their absence is a
186
+ // truncated download — and a truncated download yields a SHORT FILE LIST,
187
+ // which reads as "the published artifact has fewer files than the tree",
188
+ // i.e. as a finding rather than as the absence of a reading.
189
+ throw new ArtifactUnmeasured(
190
+ `the tarball ended after ${out.length} entries without its terminating zero blocks, ` +
191
+ `${b.length - off} bytes short of a header — the download is truncated`,
192
+ );
193
+ }
194
+
195
+ /**
196
+ * Download and hash what the registry actually serves for `pkg@version`.
197
+ *
198
+ * Reads only. Nothing here publishes, tags, or writes to the registry.
199
+ */
200
+ export async function publishedArtifact(
201
+ pkg: string,
202
+ version: string,
203
+ opts: { fetchImpl?: typeof fetch; base?: string } = {},
204
+ ): Promise<ArtifactFile[]> {
205
+ const base = opts.base ?? NPM_REGISTRY;
206
+ const f = opts.fetchImpl ?? fetch;
207
+ const bare = pkg.replace(/^@[^/]+\//, "");
208
+ const url = `${base}/${pkg}/-/${bare}-${version}.tgz`;
209
+ let res: Response;
210
+ try {
211
+ res = await f(url);
212
+ } catch (e) {
213
+ throw new ArtifactUnmeasured(`could not reach ${url}: ${(e as Error).message}`);
214
+ }
215
+ if (!res.ok) throw new ArtifactUnmeasured(`registry returned ${res.status} for ${url}`);
216
+ const gz = new Uint8Array(await res.arrayBuffer());
217
+ if (gz.length === 0) throw new ArtifactUnmeasured(`registry returned an empty body for ${url}`);
218
+ let plain: Buffer;
219
+ try {
220
+ plain = gunzipSync(gz);
221
+ } catch (e) {
222
+ throw new ArtifactUnmeasured(`${url} is not gzip: ${(e as Error).message}`);
223
+ }
224
+ return parseNpmTarball(plain);
225
+ }
226
+
227
+ /** The shape `npm pack --dry-run --json` reports, narrowed to what is read here. */
228
+ export interface PackReading {
229
+ name: string;
230
+ version: string;
231
+ files: ArtifactFile[];
232
+ }
233
+
234
+ /** How a command is run, so a test can drive the reading without a real npm. */
235
+ export type RunCommand = (
236
+ cmd: string[],
237
+ cwd: string,
238
+ ) => { status: number | null; stdout: string; stderr: string };
239
+
240
+ /**
241
+ * What `npm pack` would publish from `root`, hashed from disk.
242
+ *
243
+ * **The file list comes from npm, not from `package.json`'s `files[]`.**
244
+ * `files[]` is the declaration being checked — #484 is this repository's own
245
+ * instance of a published module reading a path `files[]` omitted — so a
246
+ * comparison built from it would be a comparison of the list with itself.
247
+ * `npm pack --dry-run` is the emitting side: it applies `files[]`, `.npmignore`,
248
+ * npm's always-included and always-excluded sets, and reports the result.
249
+ */
250
+ export function localArtifact(root: string, run: RunCommand): PackReading {
251
+ const r = run(["npm", "pack", "--dry-run", "--json"], root);
252
+ if (r.status !== 0) {
253
+ throw new ArtifactUnmeasured(
254
+ `\`npm pack --dry-run --json\` exited ${r.status} in ${root}: ${r.stderr.trim() || "(no stderr)"}`,
255
+ );
256
+ }
257
+ let parsed: unknown;
258
+ try {
259
+ parsed = JSON.parse(r.stdout);
260
+ } catch {
261
+ throw new ArtifactUnmeasured(`\`npm pack --dry-run --json\` did not print JSON: ${r.stdout.slice(0, 200)}`);
262
+ }
263
+ const first = Array.isArray(parsed) ? (parsed[0] as Record<string, unknown> | undefined) : undefined;
264
+ if (!first || typeof first.name !== "string" || typeof first.version !== "string") {
265
+ throw new ArtifactUnmeasured("`npm pack --dry-run --json` reported no package name and version");
266
+ }
267
+ const entries = Array.isArray(first.files) ? (first.files as { path?: unknown }[]) : [];
268
+ if (entries.length === 0) {
269
+ // Zero files is not agreement with an empty artifact. It is a pack that
270
+ // read nothing, and an empty set compares equal to anything.
271
+ throw new ArtifactUnmeasured(`\`npm pack --dry-run\` named no files in ${root}`);
272
+ }
273
+ const files: ArtifactFile[] = entries.map(e => {
274
+ if (typeof e.path !== "string") throw new ArtifactUnmeasured("`npm pack` reported a file with no path");
275
+ const bytes = readFileSync(join(root, e.path));
276
+ return { path: e.path, sha256: sha256(bytes), size: bytes.length };
277
+ });
278
+ return { name: first.name, version: first.version, files: files.sort((a, b) => (a.path < b.path ? -1 : 1)) };
279
+ }
280
+
281
+ /** Which paths are on one side only, and which are on both and differ. */
282
+ export interface ContentDifference {
283
+ onlyLocal: string[];
284
+ onlyPublished: string[];
285
+ differing: string[];
286
+ localCount: number;
287
+ publishedCount: number;
288
+ }
289
+
290
+ /** `true` when nothing is on one side only and nothing shared differs. */
291
+ export function contentAgrees(d: ContentDifference): boolean {
292
+ return d.onlyLocal.length === 0 && d.onlyPublished.length === 0 && d.differing.length === 0;
293
+ }
294
+
295
+ /**
296
+ * The single place that compares two artifacts.
297
+ *
298
+ * A comparison over two empty sets agrees trivially, which is the vacuous
299
+ * shape this repository has shipped before, so an empty side REFUSES rather
300
+ * than returning a clean difference.
301
+ */
302
+ export function contentDifference(local: ArtifactFile[], published: ArtifactFile[]): ContentDifference {
303
+ if (local.length === 0 || published.length === 0) {
304
+ throw new ArtifactUnmeasured(
305
+ `a content comparison needs both sides: local has ${local.length} files and published has ` +
306
+ `${published.length}. Two empty sets agree, and that agreement is not a reading`,
307
+ );
308
+ }
309
+ const l = new Map(local.map(f => [f.path, f.sha256]));
310
+ const p = new Map(published.map(f => [f.path, f.sha256]));
311
+ const onlyLocal: string[] = [];
312
+ const differing: string[] = [];
313
+ for (const [path, hash] of l) {
314
+ const other = p.get(path);
315
+ if (other === undefined) onlyLocal.push(path);
316
+ else if (other !== hash) differing.push(path);
317
+ }
318
+ const onlyPublished = [...p.keys()].filter(path => !l.has(path));
319
+ return {
320
+ onlyLocal: onlyLocal.sort(),
321
+ onlyPublished: onlyPublished.sort(),
322
+ differing: differing.sort(),
323
+ localCount: l.size,
324
+ publishedCount: p.size,
325
+ };
326
+ }
327
+
328
+ export type ArtifactReading = "MATCHED" | "DIVERGED" | "AHEAD" | "BEHIND" | "UNMEASURED";
329
+
330
+ /**
331
+ * WHICH condition produced a red (#1117). Never a verdict.
332
+ *
333
+ * #875 refuses two conditions that arrive looking alike — a registry nobody
334
+ * could reach, and a registry serving different software under this tree's
335
+ * version string. On 2026-10-21 they arrived together, were collapsed into
336
+ * one, and the first reading on four PRs was "my change broke something".
337
+ * They are not the same fact and they do not have the same remedy: a re-run
338
+ * clears the first and will never clear the second.
339
+ *
340
+ * Nothing here is consulted by `artifactViolations` or by `currencyRefusal`.
341
+ * A cause changes no verdict; it says whose red it is.
342
+ */
343
+ export type StandingCause =
344
+ /** The registry could not be read. External to this branch; a re-run may clear it. */
345
+ | "REGISTRY"
346
+ /** This checkout could not be packed — `npm`, the working tree, the runner. */
347
+ | "TOOLCHAIN"
348
+ /** The two version strings exist and cannot be ordered against each other. */
349
+ | "VERSIONS"
350
+ /** The comparison WAS taken and the two differ. Only a release clears it. */
351
+ | "CONTENT"
352
+ /** A reason arrived with no cause attached. Never attributed to a cause that did not claim it. */
353
+ | "UNCLASSIFIED";
354
+
355
+ /** A reason and the condition that produced it. */
356
+ export interface UnmeasuredReason {
357
+ cause: StandingCause;
358
+ text: string;
359
+ }
360
+
361
+ export interface ArtifactStanding {
362
+ reading: ArtifactReading;
363
+ /** `package.json`'s version in the tree that was packed. */
364
+ treeVersion: string | null;
365
+ /** The registry's `latest`. */
366
+ publishedVersion: string | null;
367
+ /** `null` only when the comparison could not be performed. */
368
+ difference: ContentDifference | null;
369
+ /** Commits between the published tag and HEAD. `null` is a reading nobody took. */
370
+ commitsAhead: number | null;
371
+ /** Why `commitsAhead` is null, when it is. Reported; never gated on. */
372
+ distanceNote: string | null;
373
+ /** Non-empty exactly when `reading` is `UNMEASURED`. */
374
+ unmeasured: UnmeasuredReason[];
375
+ /**
376
+ * The same list, rendered. A projection of `unmeasured` computed in
377
+ * `artifactStanding` and nowhere else, so the two cannot disagree about
378
+ * what was wrong — a second list built beside it would always agree with
379
+ * this one and would survive any mutation of it.
380
+ */
381
+ unmeasuredReasons: string[];
382
+ }
383
+
384
+ /**
385
+ * One sentence per condition, declared once.
386
+ *
387
+ * A total `Record`, so a new `StandingCause` is a build error rather than a
388
+ * red with no sentence beside it — `.claude/rules/config-access.md`.
389
+ */
390
+ export const STANDING_CAUSE_HEADLINE: Record<StandingCause, string> = {
391
+ REGISTRY:
392
+ "REGISTRY — the npm registry could not be read from this runner. This is not your branch: " +
393
+ "nothing in the diff can cause it or clear it, and a re-run may.",
394
+ TOOLCHAIN:
395
+ "TOOLCHAIN — this checkout could not be packed, so there was nothing to compare the registry " +
396
+ "against. Your branch only if it changed packaging.",
397
+ VERSIONS:
398
+ "VERSIONS — the tree's version and the registry's cannot be ordered against each other. " +
399
+ "This tree; a re-run will not clear it.",
400
+ CONTENT:
401
+ "CONTENT — the registry and this tree are DIFFERENT SOFTWARE under one version string. " +
402
+ "This repository, standing, and not your branch: only a release clears it, and a re-run never will.",
403
+ UNCLASSIFIED:
404
+ "UNCLASSIFIED — a reason arrived with no condition attached, so nobody can say whose red this " +
405
+ "is. Treat it as unmeasured and tag the reason at the point that produces it.",
406
+ };
407
+
408
+ /**
409
+ * The single binding that says which condition produced a standing's red.
410
+ *
411
+ * One binding, so there is one thing to mutate. It reads the causes the
412
+ * producers attached; it does not re-derive them from the rendered text,
413
+ * which would be a second decider that agrees with the first on every input
414
+ * anyone has — and a detector narrower than what it detects besides.
415
+ *
416
+ * Empty for a standing that does not refuse. Order is the order the reasons
417
+ * arrived in, de-duplicated, so a standing with two registry reasons names
418
+ * the registry once.
419
+ */
420
+ export function standingCauses(s: ArtifactStanding): StandingCause[] {
421
+ if (s.reading === "UNMEASURED") {
422
+ const seen: StandingCause[] = [];
423
+ for (const r of s.unmeasured) if (!seen.includes(r.cause)) seen.push(r.cause);
424
+ return seen;
425
+ }
426
+ if (s.reading === "DIVERGED") return ["CONTENT"];
427
+ return [];
428
+ }
429
+
430
+ /** Every condition behind a red, as sentences. `""` when nothing refuses. */
431
+ export function standingHeadline(s: ArtifactStanding): string {
432
+ return standingCauses(s)
433
+ .map(c => STANDING_CAUSE_HEADLINE[c])
434
+ .join(" ");
435
+ }
436
+
437
+ /** `0.6.0` → `[0,6,0]`; anything else → `null`. Prerelease suffixes are ignored. */
438
+ function parts(v: string): [number, number, number] | null {
439
+ const m = /^(\d+)\.(\d+)\.(\d+)/.exec(v);
440
+ return m ? [Number(m[1]), Number(m[2]), Number(m[3])] : null;
441
+ }
442
+
443
+ /** `-1`, `0`, `1`, or `null` when either side is not a version this can order. */
444
+ export function compareVersions(a: string, b: string): -1 | 0 | 1 | null {
445
+ const x = parts(a);
446
+ const y = parts(b);
447
+ if (!x || !y) return null;
448
+ for (let i = 0; i < 3; i++) {
449
+ if (x[i] !== y[i]) return x[i] > y[i] ? 1 : -1;
450
+ }
451
+ return 0;
452
+ }
453
+
454
+ /**
455
+ * The only place the two reason views are built, so they cannot disagree.
456
+ *
457
+ * `unmeasuredReasons` is the repo-wide shape every other `UNMEASURED` reading
458
+ * in this tree carries, and callers of it are unchanged; `unmeasured` is the
459
+ * same list with the condition still attached. Deriving one from the other
460
+ * here is the difference between two projections and two deciders.
461
+ */
462
+ function project(reasons: UnmeasuredReason[]): {
463
+ unmeasured: UnmeasuredReason[];
464
+ unmeasuredReasons: string[];
465
+ } {
466
+ return { unmeasured: reasons, unmeasuredReasons: reasons.map(r => r.text) };
467
+ }
468
+
469
+ /**
470
+ * The single place that turns the readings into a verdict.
471
+ *
472
+ * Pure: every input is passed in, so a case can construct any state including
473
+ * ones that cannot be produced on this machine today.
474
+ */
475
+ export function artifactStanding(input: {
476
+ treeVersion: string | null;
477
+ publishedVersion: string | null;
478
+ difference: ContentDifference | null;
479
+ commitsAhead?: number | null;
480
+ distanceNote?: string | null;
481
+ /** Reasons carrying the condition that produced them. Preferred (#1117). */
482
+ unmeasured?: UnmeasuredReason[];
483
+ /**
484
+ * Reasons with no condition attached. Accepted, and classified
485
+ * `UNCLASSIFIED` rather than folded into whichever cause looks likeliest —
486
+ * a reason attributed to a condition that did not claim it is worse than
487
+ * one that says nobody tagged it.
488
+ */
489
+ unmeasuredReasons?: string[];
490
+ }): ArtifactStanding {
491
+ const base = {
492
+ treeVersion: input.treeVersion,
493
+ publishedVersion: input.publishedVersion,
494
+ difference: input.difference,
495
+ commitsAhead: input.commitsAhead ?? null,
496
+ distanceNote: input.distanceNote ?? null,
497
+ };
498
+ /** One list. `unmeasured` and `unmeasuredReasons` are both read off it. */
499
+ const reasons: UnmeasuredReason[] = [
500
+ ...(input.unmeasured ?? []),
501
+ ...(input.unmeasuredReasons ?? []).map(text => ({ cause: "UNCLASSIFIED" as const, text })),
502
+ ];
503
+ // The three below are CONSEQUENCES of a reading that failed, so each is
504
+ // attributed to the input that failed and never to `CONTENT`. `CONTENT` is
505
+ // reachable only from `DIVERGED` — a comparison that was taken. That is
506
+ // what stops an unreachable registry reporting a divergence it never
507
+ // measured, which is #1117's whole complaint.
508
+ if (input.treeVersion === null) {
509
+ reasons.push({ cause: "TOOLCHAIN", text: "the tree's version could not be read" });
510
+ }
511
+ if (input.publishedVersion === null) {
512
+ reasons.push({ cause: "REGISTRY", text: "the registry's published version could not be read" });
513
+ }
514
+ if (input.difference === null) {
515
+ reasons.push({
516
+ cause: input.treeVersion === null ? "TOOLCHAIN" : "REGISTRY",
517
+ text: "the content comparison was not performed",
518
+ });
519
+ }
520
+ if (reasons.length > 0) {
521
+ return { ...base, reading: "UNMEASURED", ...project(reasons) };
522
+ }
523
+
524
+ const order = compareVersions(input.treeVersion!, input.publishedVersion!);
525
+ if (order === null) {
526
+ return {
527
+ ...base,
528
+ reading: "UNMEASURED",
529
+ ...project([
530
+ {
531
+ cause: "VERSIONS",
532
+ text: `cannot order ${JSON.stringify(input.treeVersion)} against ${JSON.stringify(input.publishedVersion)}`,
533
+ },
534
+ ]),
535
+ };
536
+ }
537
+ if (order > 0) return { ...base, reading: "AHEAD", ...project([]) };
538
+ if (order < 0) return { ...base, reading: "BEHIND", ...project([]) };
539
+ return {
540
+ ...base,
541
+ reading: contentAgrees(input.difference!) ? "MATCHED" : "DIVERGED",
542
+ ...project([]),
543
+ };
544
+ }
545
+
546
+ /**
547
+ * The single refusal. One binding, so there is one thing to mutate.
548
+ *
549
+ * A projection of `reading` and nothing else — a second predicate over the
550
+ * same facts would always agree with this one and would survive any mutation
551
+ * of it.
552
+ *
553
+ * `standingHeadline` leads each message (#1117) and is not consulted by the
554
+ * branch above it: the set of states this refuses is exactly what it was.
555
+ * A cause makes a red legible; it never makes one go away.
556
+ */
557
+ export function artifactViolations(s: ArtifactStanding): string[] {
558
+ if (s.reading === "UNMEASURED") {
559
+ return [
560
+ `${standingHeadline(s)} ` +
561
+ `UNMEASURED: the published artifact was not compared against this tree — ` +
562
+ s.unmeasuredReasons.join("; ") +
563
+ `. A comparison that could not be taken is not one that passed.`,
564
+ ];
565
+ }
566
+ if (s.reading === "DIVERGED") {
567
+ const d = s.difference!;
568
+ return [
569
+ `${standingHeadline(s)} ` +
570
+ `rungate@${s.publishedVersion} on the registry and the ${s.treeVersion} tree are ` +
571
+ `DIFFERENT SOFTWARE under the SAME version string: ${d.differing.length} of the published ` +
572
+ `artifact's ${d.publishedCount} files differ in content, ${d.onlyLocal.length} files the ` +
573
+ `tree would publish are absent from it, and ${d.onlyPublished.length} of its files are gone ` +
574
+ `from the tree` +
575
+ (s.commitsAhead === null ? "" : ` (${s.commitsAhead} commits since the published tag)`) +
576
+ `. Bump package.json so the two names stop claiming to be one thing, or cut the release.`,
577
+ ];
578
+ }
579
+ return [];
580
+ }
581
+
582
+ /**
583
+ * Commits between `v<version>` and `HEAD`. `null` is a reading nobody took.
584
+ *
585
+ * Never gated on: a shallow CI checkout has no tags, so a refusal here would
586
+ * fire on the ordinary case. It is reported so staleness is a number someone
587
+ * can read, which is the half of #875 that is informational rather than a gate.
588
+ */
589
+ export function publishedTagDistance(
590
+ root: string,
591
+ version: string,
592
+ run: RunCommand,
593
+ ): { commits: number | null; note: string | null } {
594
+ const tag = `v${version}`;
595
+ const probe = run(["git", "rev-parse", "--verify", `${tag}^{commit}`], root);
596
+ if (probe.status !== 0) {
597
+ return { commits: null, note: `tag ${tag} is not in this checkout (a shallow clone has none)` };
598
+ }
599
+ const r = run(["git", "rev-list", "--count", `${tag}..HEAD`], root);
600
+ if (r.status !== 0) return { commits: null, note: `git rev-list failed: ${r.stderr.trim()}` };
601
+ const n = Number(r.stdout.trim());
602
+ return Number.isInteger(n) ? { commits: n, note: null } : { commits: null, note: `unreadable count ${r.stdout.trim()}` };
603
+ }
604
+
605
+ /**
606
+ * Take every reading and produce one standing. Any throw becomes `UNMEASURED`.
607
+ *
608
+ * The catch is what makes an unreachable registry reportable instead of a
609
+ * crash — and `artifactViolations` refuses `UNMEASURED`, so it is not a
610
+ * fail-open. The distinction matters: this converts an exception into a
611
+ * REFUSAL, not into a pass.
612
+ */
613
+ export async function measureArtifactStanding(opts: {
614
+ pkg: string;
615
+ root: string;
616
+ run: RunCommand;
617
+ latestVersion: (pkg: string) => Promise<string>;
618
+ fetchImpl?: typeof fetch;
619
+ base?: string;
620
+ }): Promise<ArtifactStanding> {
621
+ let treeVersion: string | null = null;
622
+ let publishedVersion: string | null = null;
623
+ let difference: ContentDifference | null = null;
624
+ // Each catch tags its own reason, because the catch is the only position
625
+ // that knows which reading failed. A classifier downstream would have to
626
+ // guess from the text, which is a detector narrower than what it detects.
627
+ const reasons: UnmeasuredReason[] = [];
628
+
629
+ let local: ArtifactFile[] = [];
630
+ try {
631
+ const pack = localArtifact(opts.root, opts.run);
632
+ treeVersion = pack.version;
633
+ local = pack.files;
634
+ } catch (e) {
635
+ reasons.push({ cause: "TOOLCHAIN", text: (e as Error).message });
636
+ }
637
+
638
+ try {
639
+ publishedVersion = await opts.latestVersion(opts.pkg);
640
+ } catch (e) {
641
+ reasons.push({ cause: "REGISTRY", text: `registry: ${(e as Error).message}` });
642
+ }
643
+
644
+ if (publishedVersion !== null && local.length > 0) {
645
+ try {
646
+ const remote = await publishedArtifact(opts.pkg, publishedVersion, {
647
+ fetchImpl: opts.fetchImpl,
648
+ base: opts.base,
649
+ });
650
+ difference = contentDifference(local, remote);
651
+ } catch (e) {
652
+ reasons.push({ cause: "REGISTRY", text: (e as Error).message });
653
+ }
654
+ }
655
+
656
+ const distance =
657
+ publishedVersion === null
658
+ ? { commits: null, note: "no published version to measure from" }
659
+ : publishedTagDistance(opts.root, publishedVersion, opts.run);
660
+
661
+ return artifactStanding({
662
+ treeVersion,
663
+ publishedVersion,
664
+ difference,
665
+ commitsAhead: distance.commits,
666
+ distanceNote: distance.note,
667
+ unmeasured: reasons,
668
+ });
669
+ }