rungate 0.8.1 → 0.8.2

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,287 @@
1
+ /**
2
+ * Where a tree is, relative to the registry, while a release is happening
3
+ * (#1237, #1226).
4
+ *
5
+ * ## One reading, two checks, two tolerances
6
+ *
7
+ * Two checks in this repository ask the same question — *does the registry
8
+ * serve the version this tree declares?* — and answered it with different
9
+ * tolerances, so a single release produced two opposite failures:
10
+ *
11
+ * - `distributionViolations` compares `SUCCESS.md`'s standing line to
12
+ * `package.json` and to the registry independently, which tolerates the
13
+ * pre-publish window (#1049) and reddens `main` for the post-publish one.
14
+ * Until this module, clearing that red meant a human editing a markdown
15
+ * file — and `SUCCESS.md` is DA-owned (#296), so the only agents who hit
16
+ * the failure were the only ones forbidden to fix it. Twice on 2026-10-22:
17
+ * `b7281397` and `803e1e66`, each a one-line hand edit over a red `main`.
18
+ * - the adjudicator pin in `.github/workflows/ai-review.yml` has no tolerance
19
+ * at all, so the pre-publish window turns a required check into a repo-wide
20
+ * merge block.
21
+ *
22
+ * This module is the one place that classifies the reading, so the two checks
23
+ * can disagree about what to DO with a state without disagreeing about which
24
+ * state it is.
25
+ *
26
+ * ## A tolerance is not an off switch
27
+ *
28
+ * The state that must stay red is **bumped and never published**: `main`
29
+ * declaring a version no consumer can obtain, with nothing in flight that
30
+ * will change that. It is observationally identical, at the instant you look,
31
+ * to a release that is publishing right now. Nothing but elapsed time
32
+ * separates them, so the separator has to be an event with a time on it.
33
+ *
34
+ * The release tag is that event. `release.yml` triggers on `push: tags: v*`,
35
+ * so a tree carrying a version with no `v<version>` tag was never released,
36
+ * and a tag older than the window is a release that was triggered and did not
37
+ * land. Both are NEVER_PUBLISHED. Only "tagged, and recently" is tolerated.
38
+ *
39
+ * ## The CDN edge is a third state, and it is decided without a clock
40
+ *
41
+ * `dist-tags.latest` is a pointer that propagates on its own schedule, and
42
+ * reading it to answer *did the publish take effect* reported three
43
+ * consecutive successful releases as failures (#445, #472) — 0.4.1 missed a
44
+ * 120-second budget by 48 seconds. So a version's EXISTENCE is read from the
45
+ * versions list, which is the same reading `release.yml`'s postflight trusts,
46
+ * and `latest` is consulted only to tell PUBLISHED from TAG_LAG. A
47
+ * propagation delay therefore cannot age into NEVER_PUBLISHED however long it
48
+ * lasts: no clock is involved in that branch.
49
+ */
50
+ import { execFileSync } from "child_process";
51
+
52
+ /**
53
+ * The registry's account of a package, as the two readings that answer
54
+ * different questions.
55
+ *
56
+ * `versions` answers *does this exist*. `latest` answers *is it what a
57
+ * consumer gets*. Keeping them apart is the whole of #445; collapsing them
58
+ * would make PUBLISHED and TAG_LAG the same row, which is the fourth shape in
59
+ * `.claude/rules/checks-must-be-able-to-fail.md` — two deciders that agree.
60
+ */
61
+ export interface Packument {
62
+ /** The `latest` dist-tag. `null` when the registry did not report one. */
63
+ latest: string | null;
64
+ /** Every version the registry serves. */
65
+ versions: string[];
66
+ /** Publish time per version, plus `created` and `modified`, which are not versions. */
67
+ time: Record<string, string>;
68
+ }
69
+
70
+ /**
71
+ * How long after its release tag a version may be absent from the registry
72
+ * before that stops being a release and starts being a defect.
73
+ *
74
+ * Derived, not chosen: the 0.8.1 release pushed `v0.8.1` at 18:48:45Z and the
75
+ * registry served it at 19:04:37Z — **sixteen minutes**, nearly all of it the
76
+ * full suite `release.yml` runs against the tag before publishing. Ninety
77
+ * minutes is five times that, which leaves room for a slow runner and a
78
+ * queued job without leaving room for a release that failed in the morning to
79
+ * still read as "publishing now" in the afternoon.
80
+ *
81
+ * Raising it trades detection latency for tolerance of a slower pipeline.
82
+ * Lowering it below the longest real release makes every release red again,
83
+ * which is the defect this module exists to remove.
84
+ */
85
+ export const PUBLISH_WINDOW_MS = 90 * 60 * 1000;
86
+
87
+ /**
88
+ * `PUBLISHED` — the registry serves this version and points `latest` at it.
89
+ * `TAG_LAG` — the registry HAS it; `latest` has not caught up. Not a defect.
90
+ * `PUBLISH_PENDING` — absent, and its release tag is inside the window.
91
+ * `NEVER_PUBLISHED` — absent, with no release in flight. A defect.
92
+ * `UNMEASURED` — the registry was not read. Never a pass.
93
+ */
94
+ export type PublishState =
95
+ | "PUBLISHED"
96
+ | "TAG_LAG"
97
+ | "PUBLISH_PENDING"
98
+ | "NEVER_PUBLISHED"
99
+ | "UNMEASURED";
100
+
101
+ export interface PublishWindowReading {
102
+ /** `package.json` `version`. */
103
+ treeVersion: string;
104
+ /** `null` when the registry could not be read. */
105
+ packument: Packument | null;
106
+ /** ISO time of the `v<treeVersion>` tag; `null` when there is no such tag. */
107
+ releaseTagAt: string | null;
108
+ now: Date;
109
+ }
110
+
111
+ /**
112
+ * The single classifier. One exported binding, so there is one thing to
113
+ * mutate and no second predicate over the same fields to hold a case up.
114
+ */
115
+ export function publishState(r: PublishWindowReading): PublishState {
116
+ const p = r.packument;
117
+ if (p === null || p.latest === null) return "UNMEASURED";
118
+ if (p.versions.includes(r.treeVersion)) {
119
+ return p.latest === r.treeVersion ? "PUBLISHED" : "TAG_LAG";
120
+ }
121
+ if (r.releaseTagAt === null) return "NEVER_PUBLISHED";
122
+ const tagged = Date.parse(r.releaseTagAt);
123
+ if (Number.isNaN(tagged)) return "NEVER_PUBLISHED";
124
+ const elapsed = r.now.getTime() - tagged;
125
+ // A negative elapsed time is clock skew, not a window that has not opened
126
+ // yet. Treating it as pending would hand an unbounded tolerance to any
127
+ // runner whose clock is behind the tagger's.
128
+ if (elapsed < 0 || elapsed > PUBLISH_WINDOW_MS) return "NEVER_PUBLISHED";
129
+ return "PUBLISH_PENDING";
130
+ }
131
+
132
+ /** `true` for the two states in which a consumer can obtain the tree's version. */
133
+ export function registryHasTreeVersion(s: PublishState): boolean {
134
+ return s === "PUBLISHED" || s === "TAG_LAG";
135
+ }
136
+
137
+ /**
138
+ * The release a consumer had immediately before the current `latest`.
139
+ *
140
+ * Ordered by PUBLISH TIME and not by version string, because the question is
141
+ * "what did a consumer get before now" and those genuinely disagree: a patch
142
+ * cut from a maintenance branch after a later minor shipped is newer in time
143
+ * and older in semver.
144
+ *
145
+ * `created` and `modified` sit in the same map and sort alongside real
146
+ * entries, so the keys are filtered against `versions` rather than taken from
147
+ * `time` directly. A reader that skipped that returns `created` on a
148
+ * single-release package and every comparison downstream holds vacuously.
149
+ */
150
+ export function previousPublished(p: Packument): string | null {
151
+ const dated = p.versions
152
+ .filter(v => typeof p.time[v] === "string")
153
+ .map(v => ({ v, t: Date.parse(p.time[v]!) }))
154
+ .filter(x => !Number.isNaN(x.t))
155
+ .sort((a, b) => b.t - a.t);
156
+ return dated.length >= 2 ? dated[1]!.v : null;
157
+ }
158
+
159
+ /**
160
+ * What the registry says, from its own JSON endpoint.
161
+ *
162
+ * Deliberately not `npm view`: no npm CLI on the path and no lockfile, so the
163
+ * reading is the same on a laptop and on CI. A failure THROWS rather than
164
+ * returning a fallback — an unreachable registry is an unmeasured check, and
165
+ * a check reporting "no problems found" when it could not look is the
166
+ * fail-open shape `.claude/rules/checks-must-be-able-to-fail.md` opens with.
167
+ */
168
+ export async function readPackument(
169
+ pkg: string,
170
+ fetchImpl: typeof fetch = fetch,
171
+ ): Promise<Packument> {
172
+ const res = await fetchImpl(`https://registry.npmjs.org/${pkg}`);
173
+ if (!res.ok) throw new Error(`registry returned ${res.status} for ${pkg}`);
174
+ const body = (await res.json()) as {
175
+ "dist-tags"?: { latest?: unknown };
176
+ versions?: unknown;
177
+ time?: unknown;
178
+ };
179
+ const versions = body.versions;
180
+ if (typeof versions !== "object" || versions === null) {
181
+ throw new Error(`registry returned no versions for ${pkg}`);
182
+ }
183
+ const latest = body["dist-tags"]?.latest;
184
+ const time = (typeof body.time === "object" && body.time !== null ? body.time : {}) as Record<
185
+ string,
186
+ string
187
+ >;
188
+ return {
189
+ latest: typeof latest === "string" ? latest : null,
190
+ versions: Object.keys(versions),
191
+ time,
192
+ };
193
+ }
194
+
195
+ /**
196
+ * A version, and nothing that is also a git option, a pathspec or a revision.
197
+ *
198
+ * Checked before any git runs, and `null` on a miss. A string that is not a
199
+ * version can never be a release tag, so refusing it costs nothing and closes
200
+ * the door on `--all`, `HEAD`, `""` and anything else that would be read as
201
+ * something other than a name.
202
+ */
203
+ const SEMVER = /^\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)*$/;
204
+
205
+ /**
206
+ * When `v<version>` was tagged **on the remote**, or `null`.
207
+ *
208
+ * ## Why the remote, and not this checkout
209
+ *
210
+ * This reading is the entire separator between *the registry does not have it
211
+ * YET* and *somebody bumped the version and never published*. Those states are
212
+ * observationally identical at the instant you look, so whatever tells them
213
+ * apart decides whether the tolerance is honest.
214
+ *
215
+ * As first shipped it was `git log -1 --format=%cI v<version>` against the
216
+ * local checkout, and that is **evidence produced by the party being
217
+ * measured**. `release.yml` fires on tag PUSH. An unpushed local tag proves
218
+ * nothing was ever triggered, and it bought a full `PUBLISH_WINDOW_MS` of
219
+ * tolerance for exactly the state that has to stay red — so the exemption was
220
+ * mintable by anyone who could run `git tag`.
221
+ *
222
+ * Three things changed, and they are separate defects:
223
+ *
224
+ * - `v${version}` was an unqualified **revision-or-pathspec**: a local BRANCH
225
+ * named `v1.2.3` resolved it as readily as a tag, and so could a path. It is
226
+ * now `refs/tags/v<version>` read through `for-each-ref`, which cannot match
227
+ * a branch or a path.
228
+ * - `%cI` is the **committer date of the commit the tag points at** — when the
229
+ * code was written, not when the release was cut. It is now
230
+ * `%(creatordate:iso-strict)` off the ref itself.
231
+ * - existence is confirmed with `ls-remote` against `origin`, so the evidence
232
+ * comes from the remote rather than from the working copy.
233
+ *
234
+ * The local date is pinned to the remote's object id. A local tag shadowing a
235
+ * pushed one with a fresher date would otherwise extend its own window.
236
+ *
237
+ * ## This is the weaker of the two available designs, deliberately
238
+ *
239
+ * The stronger one asks the Actions API whether a release run exists for the
240
+ * tag, so the separator is produced by a party other than the thing being
241
+ * gated. That is the right principle and it is filed rather than built: it
242
+ * puts a networked call to a rate-limited API on a path a unit test takes, and
243
+ * this repository already carries one open flake of exactly that shape. The
244
+ * remote ref is weaker evidence — a pushed tag is not proof a run started —
245
+ * but it is produced outside the checkout, which is the property that was
246
+ * missing.
247
+ *
248
+ * ## The bare catch falls CLOSED, and that is the point
249
+ *
250
+ * `.claude/rules/config-access.md` bans the fail-OPEN version of this pattern,
251
+ * where a catch turns a failed read into "no problems found". This one falls
252
+ * the other way: every failure path returns `null`, `null` means no release is
253
+ * in flight, and no release in flight means `NEVER_PUBLISHED` — the red state.
254
+ * An unreachable remote, a checkout with no tags fetched and a version nobody
255
+ * released all land on the refusal. Do not "fix" this into a throw or a
256
+ * fallback without reading which direction it falls in.
257
+ */
258
+ export function releaseTagTime(root: string, version: string): string | null {
259
+ if (!SEMVER.test(version)) return null;
260
+ const ref = `refs/tags/v${version}`;
261
+ const git = (...args: string[]) =>
262
+ execFileSync("git", ["-C", root, ...args], {
263
+ encoding: "utf-8",
264
+ stdio: ["ignore", "pipe", "ignore"],
265
+ });
266
+ try {
267
+ // Existence, from the remote. `--exit-code` makes "no such tag" a non-zero
268
+ // exit rather than empty output, so an absent ref and a failed command do
269
+ // not have to be told apart here — both are the refusal.
270
+ const remote = git("ls-remote", "--tags", "--exit-code", "origin", ref);
271
+ const line = remote.split("\n").find(l => l.endsWith(`\t${ref}`));
272
+ if (line === undefined) return null;
273
+ const remoteOid = line.split("\t")[0]!.trim();
274
+ if (remoteOid === "") return null;
275
+
276
+ // The date, from the ref itself rather than from the commit under it, and
277
+ // only if the local ref is the object the remote is serving.
278
+ const local = git("for-each-ref", "--format=%(objectname) %(creatordate:iso-strict)", ref).trim();
279
+ if (local === "") return null;
280
+ const [localOid, ...rest] = local.split(" ");
281
+ if (localOid !== remoteOid) return null;
282
+ const when = rest.join(" ").trim();
283
+ return when === "" ? null : when;
284
+ } catch {
285
+ return null;
286
+ }
287
+ }