rungate 0.4.1 → 0.5.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 (42) hide show
  1. package/config/behavioral-sc-map.json +170 -0
  2. package/config/brief-policies.json +28 -0
  3. package/config/ceremony-profiles.json +207 -0
  4. package/config/check-registry.json +114 -0
  5. package/config/matcher-registry.json +142 -0
  6. package/config/prove-evidence.schema.json +65 -0
  7. package/config/spec-policies.json +36 -0
  8. package/config/universal-rules.yaml +15 -0
  9. package/config/workflow-schema.json +279 -0
  10. package/lib/cli-commands.ts +7 -1
  11. package/lib/conformity.ts +965 -30
  12. package/lib/github.ts +195 -0
  13. package/lib/js-top-level-code.ts +27 -2
  14. package/lib/package-closure.ts +278 -2
  15. package/lib/release-preflight.ts +196 -0
  16. package/lib/scaffold/defaults.ts +40 -0
  17. package/lib/scaffold/managed-workflow.ts +125 -27
  18. package/lib/scaffold/owned-files.ts +6 -0
  19. package/lib/scaffold/profiles.ts +94 -0
  20. package/lib/scaffold/rehearsal.ts +27 -2
  21. package/lib/scaffold/steps.ts +654 -84
  22. package/lib/scaffold/write-steps.ts +50 -9
  23. package/lib/source-anchor.ts +144 -0
  24. package/lib/success-doc.ts +779 -0
  25. package/lib/suite-run-reading.ts +194 -0
  26. package/lib/test-census.ts +199 -0
  27. package/lib/trajectory.ts +377 -0
  28. package/lib/validators/spec-validators.ts +32 -4
  29. package/lib/workflow-security.ts +101 -0
  30. package/lib/workflow-test-harness.ts +349 -0
  31. package/package.json +6 -1
  32. package/scripts/create-success.ts +162 -0
  33. package/scripts/scaffold-project.ts +27 -3
  34. package/specs/SPEC-TEMPLATE.md +200 -0
  35. package/templates/SUCCESS-TEMPLATE.md +72 -0
  36. package/templates/agent-briefs/_shared.md +9 -0
  37. package/templates/agent-briefs/aditi.md +46 -0
  38. package/templates/agent-briefs/discovery.md +37 -0
  39. package/templates/agent-briefs/marcus.md +39 -0
  40. package/templates/agent-briefs/quinn.md +67 -0
  41. package/templates/agent-briefs/rook.md +40 -0
  42. package/templates/agent-briefs/serena.md +39 -0
package/lib/github.ts CHANGED
@@ -37,6 +37,16 @@ export interface GitHubClient {
37
37
  update: (params: { owner: string; repo: string; pull_number: number; [key: string]: any }) => Promise<{ data: any }>;
38
38
  list: (params: { owner: string; repo: string; [key: string]: any }) => Promise<{ data: any[] }>;
39
39
  };
40
+ checks: {
41
+ /**
42
+ * Check runs for one ref (#46).
43
+ *
44
+ * `ref` is passed a commit SHA and never a branch name. The endpoint
45
+ * accepts both, and the branch form is the whole defect this gate would
46
+ * otherwise introduce — see `readCi`.
47
+ */
48
+ listForRef: (params: { owner: string; repo: string; ref: string; per_page?: number }) => Promise<{ data: { total_count: number; check_runs: any[] } }>;
49
+ };
40
50
  };
41
51
  /**
42
52
  * The GraphQL endpoint, for the handful of operations REST does not expose.
@@ -537,3 +547,188 @@ export async function listPRs(client: GitHubClient, repoSlug: string, opts?: Lis
537
547
  });
538
548
  return response.data;
539
549
  }
550
+
551
+ // ── CI verification (#46) ────────────────────────────────────
552
+
553
+ /**
554
+ * One check run, reduced to the four fields a verdict depends on.
555
+ *
556
+ * `headSha` is carried even though the query is already keyed on a SHA. It is
557
+ * the field `readCi` re-checks, and re-checking it is the point: see below.
558
+ */
559
+ export interface CheckRunSummary {
560
+ name: string;
561
+ /** `queued` | `in_progress` | `completed`, per the checks API. */
562
+ status: string;
563
+ /** `null` until the run completes. Never treat null as success. */
564
+ conclusion: string | null;
565
+ headSha: string;
566
+ url?: string;
567
+ }
568
+
569
+ export interface CiReading {
570
+ verdict: "PASS" | "FAIL" | "UNMEASURED";
571
+ /** The commit the verdict is ABOUT. A reading without this is not a reading. */
572
+ sha: string;
573
+ /** A sentence naming why, in every branch including PASS. */
574
+ reason: string;
575
+ checks: CheckRunSummary[];
576
+ failed: string[];
577
+ pending: string[];
578
+ /** Checks that completed without concluding either way — skipped, neutral. */
579
+ inconclusive: string[];
580
+ }
581
+
582
+ /**
583
+ * Conclusions that mean the check ran and said no.
584
+ *
585
+ * `cancelled` is in here deliberately. A cancelled run measured nothing, so
586
+ * the tempting reading is UNMEASURED — but on this repo's CI a cancellation is
587
+ * almost always `concurrency: cancel-in-progress` superseding the run, and
588
+ * calling that "unmeasured" lets a superseded commit's gate pass on a reading
589
+ * about a commit nobody is shipping. FAIL is the direction that costs a re-run
590
+ * rather than a bad merge.
591
+ */
592
+ const CI_FAILURE_CONCLUSIONS = new Set([
593
+ "failure",
594
+ "timed_out",
595
+ "cancelled",
596
+ "action_required",
597
+ "startup_failure",
598
+ "stale",
599
+ ]);
600
+
601
+ /**
602
+ * Conclusions that completed without answering the question.
603
+ *
604
+ * `skipped` is the one that matters. A skipped check is the single most
605
+ * convincing-looking way for this gate to certify nothing: the run exists, it
606
+ * completed, it did not fail, and a verdict computed as "no failures" calls it
607
+ * PASS. It measured nothing, so the reading is UNMEASURED.
608
+ */
609
+ const CI_INCONCLUSIVE_CONCLUSIONS = new Set(["skipped", "neutral"]);
610
+
611
+ /**
612
+ * The verdict for one commit, from the checks recorded against it.
613
+ *
614
+ * Pure, and separate from the fetching, because every interesting decision
615
+ * here is a classification rather than a network call — and the classification
616
+ * is the part that has to be wrong-proof.
617
+ *
618
+ * **There is no branch that arrives at PASS by not finding a failure.** PASS
619
+ * requires at least one check, every check belonging to this exact commit,
620
+ * every check `completed`, and every conclusion `success`. Absence, pending,
621
+ * skipped and null all land elsewhere. That is the whole design: the natural
622
+ * implementation of "did CI pass" is `!checks.some(failed)`, which returns
623
+ * true for a commit CI has never heard of.
624
+ *
625
+ * **A check whose `headSha` differs is discarded, not counted.** The checks
626
+ * API accepts a branch name as `ref` and will happily answer about whatever
627
+ * commit that branch pointed at when CI last ran — so a gate keyed on the
628
+ * branch certifies the previous push. Filtering here means that even a caller
629
+ * who passes a branch name gets UNMEASURED rather than a stale PASS.
630
+ */
631
+ export function readCi(sha: string, checks: CheckRunSummary[]): CiReading {
632
+ const base = { sha, checks, failed: [] as string[], pending: [] as string[], inconclusive: [] as string[] };
633
+
634
+ if (!sha || !/^[0-9a-f]{7,40}$/i.test(sha)) {
635
+ return { ...base, verdict: "UNMEASURED", reason: `"${sha}" is not a commit SHA, so there is nothing to ask CI about — a ref that is not a SHA would be answered about whatever commit it last pointed at` };
636
+ }
637
+
638
+ const mine = checks.filter(c => c.headSha === sha);
639
+ const foreign = checks.filter(c => c.headSha !== sha);
640
+ if (mine.length === 0) {
641
+ return {
642
+ ...base,
643
+ verdict: "UNMEASURED",
644
+ reason: foreign.length > 0
645
+ ? `every check found belongs to a different commit (${[...new Set(foreign.map(c => c.headSha))].join(", ")}), not ${sha} — this is the stale reading, not a pass`
646
+ : `no check has been recorded for ${sha} — CI has not reported on this commit, which is not the same as reporting success`,
647
+ };
648
+ }
649
+
650
+ const failed = mine.filter(c => c.conclusion !== null && CI_FAILURE_CONCLUSIONS.has(c.conclusion)).map(c => c.name);
651
+ const pending = mine.filter(c => c.status !== "completed").map(c => c.name);
652
+ const inconclusive = mine
653
+ .filter(c => c.status === "completed" && (c.conclusion === null || CI_INCONCLUSIVE_CONCLUSIONS.has(c.conclusion)))
654
+ .map(c => c.name);
655
+ const full = { ...base, checks: mine, failed, pending, inconclusive };
656
+
657
+ // A failure first, even with others still running. More waiting cannot
658
+ // un-fail a check, and reporting UNMEASURED here would turn a known red into
659
+ // "we did not find out".
660
+ if (failed.length > 0) {
661
+ return { ...full, verdict: "FAIL", reason: `CI failed on ${sha}: ${failed.join(", ")}` };
662
+ }
663
+ if (pending.length > 0) {
664
+ return { ...full, verdict: "UNMEASURED", reason: `CI has not finished on ${sha} — still running: ${pending.join(", ")}` };
665
+ }
666
+ if (inconclusive.length > 0) {
667
+ return { ...full, verdict: "UNMEASURED", reason: `CI completed on ${sha} without measuring: ${inconclusive.join(", ")} neither passed nor failed` };
668
+ }
669
+ return { ...full, verdict: "PASS", reason: `all ${mine.length} check${mine.length === 1 ? "" : "s"} passed on ${sha}: ${mine.map(c => c.name).join(", ")}` };
670
+ }
671
+
672
+ /** The check runs GitHub has recorded against one commit. */
673
+ export async function listCheckRuns(client: GitHubClient, repoSlug: string, sha: string): Promise<CheckRunSummary[]> {
674
+ const { owner, repo } = parseOwnerRepo(repoSlug);
675
+ const response = await client.rest.checks.listForRef({ owner, repo, ref: sha, per_page: 100 });
676
+ return (response.data?.check_runs ?? []).map((c: any) => ({
677
+ name: String(c.name ?? "<unnamed>"),
678
+ status: String(c.status ?? "unknown"),
679
+ conclusion: c.conclusion === undefined ? null : c.conclusion,
680
+ headSha: String(c.head_sha ?? ""),
681
+ url: typeof c.html_url === "string" ? c.html_url : undefined,
682
+ }));
683
+ }
684
+
685
+ export interface WaitForCiOptions {
686
+ timeoutMs: number;
687
+ intervalMs: number;
688
+ /** Injected so a test can run the loop without waiting for it. */
689
+ sleep?: (ms: number) => Promise<void>;
690
+ now?: () => number;
691
+ }
692
+
693
+ /**
694
+ * Poll until CI has an answer for this commit, or until the wait runs out.
695
+ *
696
+ * Polling, and not a webhook, because a local harness has no inbound endpoint
697
+ * for a webhook to arrive at — the choice is not whether to poll but who does
698
+ * and whether the wait is bounded. `gh run watch` polls too, and blocks
699
+ * without a bound.
700
+ *
701
+ * **A timeout returns the last reading, which is UNMEASURED.** It never
702
+ * upgrades to PASS, and it never degrades to FAIL either: running out of
703
+ * patience is not evidence about the code. The returned reason names what was
704
+ * still pending, so the operator can see what it was waiting for.
705
+ */
706
+ export async function waitForCi(
707
+ client: GitHubClient,
708
+ repoSlug: string,
709
+ sha: string,
710
+ opts: WaitForCiOptions,
711
+ ): Promise<CiReading> {
712
+ const sleep = opts.sleep ?? ((ms: number) => new Promise<void>(r => setTimeout(r, ms)));
713
+ const now = opts.now ?? (() => Date.now());
714
+ const deadline = now() + Math.max(0, opts.timeoutMs);
715
+ let reading = readCi(sha, await listCheckRuns(client, repoSlug, sha));
716
+
717
+ // Only a pending or absent reading is worth waiting on. A FAIL will not
718
+ // improve, a PASS will not get better, and an inconclusive check has already
719
+ // finished — polling those is time spent to reach the same answer.
720
+ const worthWaiting = (r: CiReading) => r.verdict === "UNMEASURED" && (r.pending.length > 0 || r.checks.length === 0);
721
+
722
+ while (worthWaiting(reading) && now() < deadline) {
723
+ await sleep(Math.min(opts.intervalMs, Math.max(0, deadline - now())));
724
+ reading = readCi(sha, await listCheckRuns(client, repoSlug, sha));
725
+ }
726
+ if (worthWaiting(reading)) {
727
+ const waited = Math.round(opts.timeoutMs / 1000);
728
+ return {
729
+ ...reading,
730
+ reason: `${reading.reason} — gave up after ${waited}s, which is a statement about the wait and not about the code`,
731
+ };
732
+ }
733
+ return reading;
734
+ }
@@ -35,7 +35,26 @@ function regexCanFollow(prev: string): boolean {
35
35
  return !/[A-Za-z0-9_$)\]]/.test(prev);
36
36
  }
37
37
 
38
- export function stripStringsAndComments(src: string): string {
38
+ /**
39
+ * `keepStringContents` leaves quoted string bodies intact while still blanking
40
+ * comments, regex literals and template text.
41
+ *
42
+ * Added for #484, which needs the opposite half of what every other caller
43
+ * wants: the path segments in `join(__dirname, "..", "config", "x.json")` are
44
+ * the payload, and the reason it needs this tokenizer at all is that the same
45
+ * expression written in a DOC COMMENT must not be read as a call. The first
46
+ * draft of that check scanned raw source and reported its own module docstring
47
+ * as a violation — #454 is the same mistake in CONFIG-1, two weeks earlier.
48
+ *
49
+ * It is an option on this function rather than a second stripper in that
50
+ * module on purpose. Two functions that each decide what a comment is are two
51
+ * deciders, and the one that is wrong is invisible — see
52
+ * `.claude/rules/checks-must-be-able-to-fail.md`.
53
+ */
54
+ export function stripStringsAndComments(
55
+ src: string,
56
+ { keepStringContents = false }: { keepStringContents?: boolean } = {},
57
+ ): string {
39
58
  let out = "";
40
59
  let i = 0;
41
60
  // Stack of brace depths, one entry per template literal currently open. An
@@ -100,13 +119,19 @@ export function stripStringsAndComments(src: string): string {
100
119
  i++;
101
120
  while (i < src.length) {
102
121
  if (src[i] === "\\") {
122
+ // Carry the escape through verbatim under `keepStringContents`.
123
+ // Dropping both characters turned `"a\"b"` into `ab`, which is not
124
+ // a shorter version of the segment — it is a DIFFERENT path, and a
125
+ // caller resolving it would report a file the code never reads.
126
+ // Silently wrong beats loudly wrong only in the wrong direction.
127
+ if (keepStringContents) out += src.slice(i, i + 2);
103
128
  i += 2;
104
129
  continue;
105
130
  }
106
131
  if (src[i] === quote) break;
107
132
  // Unterminated strings must not swallow the rest of the file.
108
133
  if (src[i] === "\n") break;
109
- out += src[i] === "\n" ? "\n" : "";
134
+ out += keepStringContents ? src[i] : "";
110
135
  i++;
111
136
  }
112
137
  if (src[i] === quote) {
@@ -14,9 +14,41 @@
14
14
  * would carry, then walk the relative imports of every published source file
15
15
  * and assert each target is in that set. One `catch` here would turn a
16
16
  * malformed package.json into "no violations", so there is none.
17
+ *
18
+ * ## Imports were half of it (#484)
19
+ *
20
+ * The version of this module that shipped with #446 asked one question —
21
+ * *does every relative IMPORT resolve to a published file?* — and `0.4.1` went
22
+ * out with `SUCCESS.md` recording that the distribution had been verified. It
23
+ * had been verified for imports.
24
+ *
25
+ * `lib/conformity.ts:495` does not import its matcher registry. It builds a
26
+ * path and reads it:
27
+ *
28
+ * join(dirname(fileURLToPath(import.meta.url)), "..", "config", "matcher-registry.json")
29
+ *
30
+ * `config/` was not in `files[]`, so `resolveMatcher()` threw ENOENT for every
31
+ * consumer, and `bunx rungate create-sc --list` — a command the README
32
+ * documents — died the same way. Same defect as #446, different syntax, and
33
+ * the guard written for #446 was structurally incapable of seeing it: a
34
+ * detector narrower than what it detects, which is the shape
35
+ * `.claude/rules/checks-must-be-able-to-fail.md` names third.
36
+ *
37
+ * What made it latent rather than loud is worth recording. An external
38
+ * consumer does not reach `resolveMatcher` until one of its success criteria
39
+ * MATCHES a registry pattern. Measured on `pov-plugin`: 21 pass, 0 fail, over
40
+ * a library that could not load its own registry, purely because all 40 of its
41
+ * SCs were unmatched. The reward for making its spec more testable would have
42
+ * been an ENOENT crash, and nothing connected those two events.
43
+ *
44
+ * So both syntaxes are asked the same question here, and `runtimeReads` is
45
+ * deliberately NOT a second copy of the import walker — the two find different
46
+ * things and both feed the one `packageClosureViolations` binding, so there is
47
+ * still exactly one decider to mutate.
17
48
  */
18
- import { existsSync, readdirSync, readFileSync, statSync } from "fs";
49
+ import { existsSync, lstatSync, readdirSync, readFileSync, statSync } from "fs";
19
50
  import { join, dirname, relative, resolve } from "path";
51
+ import { stripStringsAndComments } from "./js-top-level-code";
20
52
 
21
53
  /** Extensions a bare specifier may acquire, in the order a resolver tries. */
22
54
  const CANDIDATE_SUFFIXES = ["", ".ts", ".tsx", ".js", ".mjs", ".json", "/index.ts", "/index.js"];
@@ -32,15 +64,57 @@ export function publishedFiles(root: string, patterns: string[]): Set<string> {
32
64
  if (!existsSync(abs)) return;
33
65
  for (const entry of readdirSync(abs)) {
34
66
  const childRel = `${rel}/${entry}`.replace(/\/+/g, "/");
35
- if (statSync(join(root, childRel)).isDirectory()) addDir(childRel);
67
+ const childAbs = join(root, childRel);
68
+ // `lstat`, not `stat`. A symlink inside a published directory points
69
+ // wherever it likes, and `relative()` cannot see that because the path
70
+ // STRING is still under the root — a `linked/` symlink enumerated
71
+ // `secret.txt` from a directory outside the package entirely. npm would
72
+ // follow it into the tarball too, so this is a packaging hazard either
73
+ // way and the honest answer is to refuse rather than to model it.
74
+ const st = lstatSync(childAbs);
75
+ if (st.isSymbolicLink()) {
76
+ throw new Error(`package.json files[] reaches a symlink at "${childRel}" — refusing to resolve it`);
77
+ }
78
+ if (st.isDirectory()) addDir(childRel);
36
79
  else out.add(childRel);
37
80
  }
38
81
  }
39
82
 
83
+ /** npm expands these; this checker does not, and must not pretend to. */
84
+ const GLOB_META = /[*?[\]{}!]/;
85
+
40
86
  for (const pattern of patterns) {
87
+ // A glob is not a path, and treating it as one resolves to NOTHING:
88
+ // `files: ["scripts/*.ts"]` produced a published set containing only
89
+ // package.json, so the closure loop had almost nothing to walk and
90
+ // reported zero violations over a package it had not looked at. That is
91
+ // the same vacuous-scan failure CONFIG-1 refuses, reached through the
92
+ // manifest instead of through the file walk.
93
+ if (GLOB_META.test(pattern)) {
94
+ throw new Error(
95
+ `package.json files[] entry "${pattern}" is a glob, which this checker does not expand — ` +
96
+ `it would report a clean closure over files it never resolved`,
97
+ );
98
+ }
41
99
  const clean = pattern.replace(/^\.\//, "").replace(/\/$/, "");
42
100
  const abs = join(root, clean);
101
+ // A files[] entry that climbs out of the package is never legitimate, and
102
+ // this function walks directories recursively — so an unchecked `../..`
103
+ // would enumerate the filesystem above the project. Refuse rather than
104
+ // normalise: npm would not publish it either, and silently reading it as
105
+ // the directory it resolves to would hide a malformed manifest.
106
+ if (relative(root, abs).startsWith("..")) {
107
+ throw new Error(`package.json files[] entry "${pattern}" escapes the package root`);
108
+ }
43
109
  if (!existsSync(abs)) continue;
110
+ // The same lstat the recursion does. A first draft checked only inside
111
+ // addDir, so `files: ["linked/"]` — the symlink named as the entry itself
112
+ // — walked straight past it and enumerated a directory outside the
113
+ // package. The guard has to sit on every path that becomes a published
114
+ // name, not only on the ones reached by recursion.
115
+ if (lstatSync(abs).isSymbolicLink()) {
116
+ throw new Error(`package.json files[] entry "${pattern}" is a symlink — refusing to resolve it`);
117
+ }
44
118
  if (statSync(abs).isDirectory()) addDir(clean);
45
119
  else out.add(clean);
46
120
  }
@@ -68,6 +142,142 @@ export function relativeImports(source: string): string[] {
68
142
  return found;
69
143
  }
70
144
 
145
+ /**
146
+ * A path a module builds from its OWN location and then reads at runtime.
147
+ *
148
+ * `up` is how many directories above the source file the path starts, and
149
+ * `segments` is what is appended. The two anchors below both mean "the
150
+ * directory this module is in", so they are 0; every `dirname()` wrapped
151
+ * around one, and every `".."` among the segments, adds a level.
152
+ */
153
+ export interface RuntimeRead {
154
+ /** The expression as written, for the violation message. */
155
+ expression: string;
156
+ /** Directories above the source file's own directory. */
157
+ up: number;
158
+ /** Literal path segments below that, `..` already folded into `up`. */
159
+ segments: string[];
160
+ }
161
+
162
+ /** Spellings of "the directory this module lives in". */
163
+ const MODULE_DIR_ANCHORS = [
164
+ /\bdirname\s*\(\s*fileURLToPath\s*\(\s*import\.meta\.url\s*\)\s*\)/,
165
+ /\bimport\.meta\.dir\b/,
166
+ /\b__dirname\b/,
167
+ ];
168
+
169
+ /** Split a `join(...)` argument list on top-level commas. */
170
+ function splitArgs(argText: string): string[] {
171
+ const args: string[] = [];
172
+ let depth = 0;
173
+ let quote: string | null = null;
174
+ let current = "";
175
+ for (let i = 0; i < argText.length; i++) {
176
+ const c = argText[i];
177
+ if (quote) {
178
+ if (c === quote && argText[i - 1] !== "\\") quote = null;
179
+ current += c;
180
+ continue;
181
+ }
182
+ if (c === '"' || c === "'" || c === "`") { quote = c; current += c; continue; }
183
+ if (c === "(" || c === "[" || c === "{") depth++;
184
+ if (c === ")" || c === "]" || c === "}") depth--;
185
+ if (c === "," && depth === 0) { args.push(current.trim()); current = ""; continue; }
186
+ current += c;
187
+ }
188
+ if (current.trim()) args.push(current.trim());
189
+ return args;
190
+ }
191
+
192
+ /**
193
+ * A segment the scanner is willing to resolve.
194
+ *
195
+ * No backslash: an escaped character means the written text and the runtime
196
+ * string differ, and resolving the text would name a path the code does not
197
+ * read. Such a segment falls through to `unresolved`, where it is reported,
198
+ * rather than being turned into a plausible wrong answer.
199
+ */
200
+ const STRING_LITERAL = /^["'`]([^"'`\\]*)["'`]$/;
201
+
202
+ /**
203
+ * Every `join(<this module's directory>, ...literals)` in a source file.
204
+ *
205
+ * Only fully-literal segment lists are returned. A `join` whose segments come
206
+ * from a variable cannot be resolved statically and is NOT silently dropped —
207
+ * `unresolvedModuleRelativeJoins` counts those separately so a new one is
208
+ * visible rather than absorbed, which is the fail-open this whole module
209
+ * exists to avoid.
210
+ */
211
+ export function runtimeReads(source: string): RuntimeRead[] {
212
+ return scanModuleRelativeJoins(source).resolved;
213
+ }
214
+
215
+ /** Module-relative `join(...)` calls whose segments are not all literals. */
216
+ export function unresolvedModuleRelativeJoins(source: string): string[] {
217
+ return scanModuleRelativeJoins(source).unresolved;
218
+ }
219
+
220
+ function scanModuleRelativeJoins(raw: string): { resolved: RuntimeRead[]; unresolved: string[] } {
221
+ const resolved: RuntimeRead[] = [];
222
+ const unresolved: string[] = [];
223
+
224
+ // Comments out, string contents kept. The first draft of this scanner read
225
+ // raw source and reported THIS MODULE's own docstring — which quotes the
226
+ // `join(dirname(fileURLToPath(...)), "..", "config", ...)` expression to
227
+ // explain the bug — as a live violation. A detector that cannot tell a call
228
+ // from a sentence about a call is #454 again.
229
+ const source = stripStringsAndComments(raw, { keepStringContents: true });
230
+
231
+ for (let i = source.indexOf("join"); i !== -1; i = source.indexOf("join", i + 1)) {
232
+ // `join` must be the whole identifier, and an open paren must follow.
233
+ if (i > 0 && /[A-Za-z0-9_$.]/.test(source[i - 1])) continue;
234
+ let j = i + 4;
235
+ while (j < source.length && /\s/.test(source[j])) j++;
236
+ if (source[j] !== "(") continue;
237
+
238
+ // Walk to the matching close paren.
239
+ let depth = 0;
240
+ let k = j;
241
+ for (; k < source.length; k++) {
242
+ if (source[k] === "(") depth++;
243
+ else if (source[k] === ")") { depth--; if (depth === 0) break; }
244
+ }
245
+ if (depth !== 0) continue;
246
+
247
+ const argText = source.slice(j + 1, k);
248
+ const args = splitArgs(argText);
249
+ if (args.length < 2) continue;
250
+
251
+ const anchor = args[0];
252
+ if (!MODULE_DIR_ANCHORS.some(a => a.test(anchor))) continue;
253
+
254
+ // `dirname(fileURLToPath(import.meta.url))` IS the anchor, so remove it
255
+ // before counting the dirname() calls that genuinely climb.
256
+ const climbing = anchor.replace(MODULE_DIR_ANCHORS[0], "");
257
+ let up = (climbing.match(/\bdirname\s*\(/g) || []).length;
258
+
259
+ const expression = `join(${args.join(", ")})`;
260
+ const segments: string[] = [];
261
+ let literal = true;
262
+ for (const arg of args.slice(1)) {
263
+ const m = STRING_LITERAL.exec(arg);
264
+ if (!m) { literal = false; break; }
265
+ for (const part of m[1].split("/").filter(Boolean)) {
266
+ if (part === "..") { if (segments.length) segments.pop(); else up++; }
267
+ else if (part !== ".") segments.push(part);
268
+ }
269
+ }
270
+
271
+ // `join(import.meta.dir, "..")` with nothing below it is the "find the
272
+ // package root" idiom, not a read of a particular file. Eleven published
273
+ // modules use it and none of them is a closure question.
274
+ if (literal && segments.length > 0) resolved.push({ expression, up, segments });
275
+ else if (!literal) unresolved.push(expression);
276
+ }
277
+
278
+ return { resolved, unresolved };
279
+ }
280
+
71
281
  /**
72
282
  * The single binding. `test/package-closure.test.ts` builds a mutant of this
73
283
  * module with the body short-circuited to `return []` and asserts the suite
@@ -76,11 +286,64 @@ export function relativeImports(source: string): string[] {
76
286
  */
77
287
  export function packageClosureViolations(root: string, published: Set<string>): string[] {
78
288
  const violations: string[] = [];
289
+ let scanned = 0;
79
290
 
80
291
  for (const file of published) {
81
292
  if (!SOURCE_EXT.test(file)) continue;
293
+ scanned++;
82
294
  const source = readFileSync(join(root, file), "utf-8");
83
295
 
296
+ // A module-relative path the scanner could not resolve statically is
297
+ // UNMEASURED, and unmeasured is not clean. The first draft of this module
298
+ // exported `unresolvedModuleRelativeJoins`, tested it in isolation, and
299
+ // never called it from here — so its own docstring claimed these were
300
+ // "NOT silently dropped" while the only path that produces violations
301
+ // dropped them. Found by the push security review, in the same commit
302
+ // that adds a section about exactly this to
303
+ // `.claude/rules/checks-must-be-able-to-fail.md`.
304
+ //
305
+ // Enforced strictly because the live tree has zero: there is no migration
306
+ // window to ratchet through, so a new one fails immediately.
307
+ for (const expression of unresolvedModuleRelativeJoins(source)) {
308
+ violations.push(
309
+ `${file} builds ${expression} from its own directory and the segments are not all literal — ` +
310
+ `the scanner cannot say what it reads, so whether it ships is UNMEASURED`,
311
+ );
312
+ }
313
+
314
+ // `join` resolved by identifier. An aliased import would be invisible, so
315
+ // it is refused rather than missed — the blind spot is small, and the
316
+ // point is that entering it cannot be silent.
317
+ if (/\bimport\s*\{[^}]*\bjoin\s+as\s+\w/.test(source)) {
318
+ violations.push(
319
+ `${file} imports join under an alias, which this scanner resolves by name and would not see`,
320
+ );
321
+ }
322
+
323
+ // #484. A path built from the module's own location and read at runtime
324
+ // asks the same question an import does, so it is answered here and not
325
+ // in a second checker that could drift from this one.
326
+ for (const read of runtimeReads(source)) {
327
+ let dir = dirname(join(root, file));
328
+ for (let n = 0; n < read.up; n++) dir = dirname(dir);
329
+ const target = join(dir, ...read.segments);
330
+ const targetRel = relative(root, target);
331
+
332
+ // Outside the package entirely is not this check's business.
333
+ if (targetRel.startsWith("..")) continue;
334
+ if (!existsSync(target)) continue;
335
+
336
+ const isPublished = statSync(target).isDirectory()
337
+ ? [...published].some(p => p === targetRel || p.startsWith(`${targetRel}/`))
338
+ : published.has(targetRel);
339
+
340
+ if (!isPublished) {
341
+ violations.push(
342
+ `${file} reads ${read.expression} at runtime -> ${targetRel}, which files[] does not publish`,
343
+ );
344
+ }
345
+ }
346
+
84
347
  for (const specifier of relativeImports(source)) {
85
348
  const target = resolve(dirname(join(root, file)), specifier);
86
349
  const targetRel = relative(root, target);
@@ -97,6 +360,19 @@ export function packageClosureViolations(root: string, published: Set<string>):
97
360
  }
98
361
  }
99
362
  }
363
+
364
+ // A closure check that walked no source reports a closed package and cannot
365
+ // be told from one. Every way of producing an empty set found so far — a
366
+ // glob entry, a files[] naming only non-source, a wrong root — throws or
367
+ // refuses somewhere above; this is the backstop for the next one, because
368
+ // the list of ways is not knowable in advance. ADR-002 D4, same argument.
369
+ if (scanned === 0) {
370
+ return [
371
+ "package closure: NO published source files were scanned. A check that reads nothing " +
372
+ "reports nothing and cannot be told from a closed package — refusing rather than " +
373
+ "reporting clean.",
374
+ ];
375
+ }
100
376
  return violations.sort();
101
377
  }
102
378