rungate 0.4.0 → 0.4.1

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.
package/lib/organize.ts CHANGED
@@ -21,6 +21,7 @@ import {
21
21
  } from "fs";
22
22
  import { join, relative, dirname, basename } from "path";
23
23
  import { loadComplianceConfig, type OrganizeExternalSource } from "./config-loader.js";
24
+ import { matchesAnyAlias, projectAliases } from "./project-aliases.js";
24
25
 
25
26
  // ── Types ────────────────────────────────────────────────────────
26
27
 
@@ -64,6 +65,27 @@ export interface OrganizeOptions {
64
65
  harnessRoot?: string;
65
66
  }
66
67
 
68
+ /**
69
+ * What a scan covered, and what it could not (#442).
70
+ *
71
+ * `scanExternalSources` had three fail-opens in one loop: a declared path
72
+ * that is not on disk was `continue`d, an unreadable file was `catch {}`ed
73
+ * into a non-match, and the whole directory walk sat inside another bare
74
+ * `catch`. A user who declares where their documents live and is told
75
+ * nothing when that place is not there has been given `0`, `{}` and `SKIP`
76
+ * — which `.claude/rules/config-access.md` names as indistinguishable from
77
+ * success. `UNMEASURED` is not.
78
+ */
79
+ export interface OrganizeReport {
80
+ proposals: OrganizeProposal[];
81
+ /** Declared external paths that are not on disk. Named, not skipped. */
82
+ unmeasured: string[];
83
+ /** Paths that exist and could not be read. A non-match is not the answer. */
84
+ unreadable: string[];
85
+ /** The names matching was actually done against, so a miss is diagnosable. */
86
+ aliases: string[];
87
+ }
88
+
67
89
  // ── Well-known root files to skip ────────────────────────────────
68
90
 
69
91
  const WELL_KNOWN_ROOT_FILES = new Set([
@@ -288,7 +310,14 @@ export function classifyDocument(
288
310
 
289
311
  // ── Main organize function ───────────────────────────────────────
290
312
 
291
- export function organizeProject(root: string, options: OrganizeOptions = {}): OrganizeProposal[] {
313
+ /**
314
+ * The full result: what was proposed, and what could not be looked at.
315
+ *
316
+ * `organizeProject` below is a view onto this, not a second implementation —
317
+ * eight call sites want only the proposals and changing them all would have
318
+ * bought nothing. One decider, one convenience accessor.
319
+ */
320
+ export function organizeProjectReport(root: string, options: OrganizeOptions = {}): OrganizeReport {
292
321
  const complianceConfig = options.harnessRoot
293
322
  ? loadComplianceConfig(options.harnessRoot)
294
323
  : null;
@@ -316,71 +345,131 @@ export function organizeProject(root: string, options: OrganizeOptions = {}): Or
316
345
  });
317
346
  }
318
347
 
348
+ const aliases = projectAliases(root, organizeConfig?.aliases ?? []);
349
+ const report: OrganizeReport = { proposals, unmeasured: [], unreadable: [], aliases };
350
+
319
351
  // Scan external sources from config
320
352
  if (organizeConfig?.externalSources) {
321
- const externalProposals = scanExternalSources(root, organizeConfig.externalSources);
322
- proposals.push(...externalProposals);
353
+ proposals.push(...scanExternalSources(root, organizeConfig.externalSources, aliases, report));
323
354
  }
324
355
 
325
356
  if (options.apply && !options.dryRun) {
326
357
  executeProposals(root, proposals);
327
358
  }
328
359
 
329
- return proposals;
360
+ return report;
361
+ }
362
+
363
+ export function organizeProject(root: string, options: OrganizeOptions = {}): OrganizeProposal[] {
364
+ return organizeProjectReport(root, options).proposals;
330
365
  }
331
366
 
332
367
  // ── External source scanning ────────────────────────────────────
333
368
 
334
- function scanExternalSources(projectRoot: string, sources: OrganizeExternalSource[]): OrganizeProposal[] {
369
+ function scanExternalSources(
370
+ projectRoot: string,
371
+ sources: OrganizeExternalSource[],
372
+ aliases: string[],
373
+ report: { unmeasured: string[]; unreadable: string[] },
374
+ ): OrganizeProposal[] {
335
375
  const proposals: OrganizeProposal[] = [];
336
- const projectName = basename(projectRoot).toLowerCase();
337
376
 
338
377
  for (const source of sources) {
339
- const expandedPath = source.path.replace("~", process.env.HOME || "");
340
- if (!existsSync(expandedPath)) continue;
378
+ const expandedPath = expandHome(source.path);
379
+ if (!existsSync(expandedPath)) {
380
+ // UNMEASURED, not skipped. The user said their documents live here.
381
+ report.unmeasured.push(source.path);
382
+ continue;
383
+ }
341
384
  if (source.target === null) continue;
342
385
 
343
- if (lstatSync(expandedPath).isDirectory()) {
344
- try {
345
- for (const entry of readdirSync(expandedPath)) {
346
- const entryPath = join(expandedPath, entry);
347
- if (!lstatSync(entryPath).isDirectory() && !entry.endsWith(".md")) continue;
348
-
349
- let matches = false;
350
- if (source.matchBy === "project-name") {
351
- matches = entry.toLowerCase().includes(projectName) ||
352
- (lstatSync(entryPath).isDirectory() && readdirSync(entryPath).some(f =>
353
- f.toLowerCase().includes(projectName)));
354
- } else if (source.matchBy === "content-reference") {
355
- if (entry.endsWith(".md")) {
356
- try {
357
- const content = readFileSync(entryPath, "utf-8");
358
- matches = content.toLowerCase().includes(projectName);
359
- } catch {}
360
- }
361
- }
386
+ let stat;
387
+ try {
388
+ stat = lstatSync(expandedPath);
389
+ } catch {
390
+ report.unreadable.push(source.path);
391
+ continue;
392
+ }
393
+ if (!stat.isDirectory()) continue;
394
+
395
+ let entries: string[];
396
+ try {
397
+ entries = readdirSync(expandedPath);
398
+ } catch {
399
+ // Was a bare `catch {}` around the whole walk. A declared source the
400
+ // process cannot list is the single most important thing to say.
401
+ report.unreadable.push(source.path);
402
+ continue;
403
+ }
362
404
 
363
- if (matches) {
364
- const targetPath = join(source.target, entry);
365
- const targetFull = join(projectRoot, targetPath);
366
- if (existsSync(targetFull)) continue;
367
-
368
- proposals.push({
369
- source: entryPath,
370
- target: targetPath,
371
- classification: source.type,
372
- reasoning: `external ${source.type} matched by ${source.matchBy} in ${source.path}`,
373
- confidence: 0.7,
374
- });
405
+ for (const entry of entries) {
406
+ const entryPath = join(expandedPath, entry);
407
+ let isDir: boolean;
408
+ try {
409
+ isDir = lstatSync(entryPath).isDirectory();
410
+ } catch {
411
+ report.unreadable.push(entryPath);
412
+ continue;
413
+ }
414
+ if (!isDir && !entry.endsWith(".md")) continue;
415
+
416
+ let matches = false;
417
+ if (source.matchBy === "project-name") {
418
+ matches = matchesAnyAlias(entry, aliases);
419
+ if (!matches && isDir) {
420
+ try {
421
+ matches = readdirSync(entryPath).some(f => matchesAnyAlias(f, aliases));
422
+ } catch {
423
+ report.unreadable.push(entryPath);
424
+ continue;
375
425
  }
376
426
  }
377
- } catch {}
427
+ } else if (source.matchBy === "content-reference") {
428
+ if (!entry.endsWith(".md")) continue;
429
+ let content: string;
430
+ try {
431
+ content = readFileSync(entryPath, "utf-8");
432
+ } catch {
433
+ // Was `catch {}`, which made unreadable and not-a-match the same
434
+ // answer. They are opposite answers: one is "no", the other is
435
+ // "I could not look".
436
+ report.unreadable.push(entryPath);
437
+ continue;
438
+ }
439
+ matches = matchesAnyAlias(content, aliases);
440
+ }
441
+
442
+ if (!matches) continue;
443
+
444
+ const targetPath = join(source.target, entry);
445
+ if (existsSync(join(projectRoot, targetPath))) continue;
446
+
447
+ proposals.push({
448
+ source: entryPath,
449
+ target: targetPath,
450
+ classification: source.type,
451
+ reasoning: `external ${source.type} matched by ${source.matchBy} in ${source.path}`,
452
+ confidence: 0.7,
453
+ });
378
454
  }
379
455
  }
380
456
 
381
457
  return proposals;
382
458
  }
383
459
 
460
+ /**
461
+ * `~` expansion, anchored.
462
+ *
463
+ * `source.path.replace("~", HOME)` replaces the FIRST `~` anywhere in the
464
+ * string, so `/srv/backup~old/docs` became `/srv/backup<HOME>old/docs`. Only
465
+ * a leading `~` is a home reference.
466
+ */
467
+ export function expandHome(path: string): string {
468
+ if (path !== "~" && !path.startsWith("~/")) return path;
469
+ const home = process.env.HOME || "";
470
+ return home ? home + path.slice(1) : path;
471
+ }
472
+
384
473
  // ── Execute proposals (move files) ───────────────────────────────
385
474
 
386
475
  function executeProposals(root: string, proposals: OrganizeProposal[]): void {
@@ -0,0 +1,111 @@
1
+ /**
2
+ * Package closure — does everything the tarball ships still resolve once it is
3
+ * the only thing on disk?
4
+ *
5
+ * `lib/` publishes whole. `scripts/` publishes by allowlist, one path at a
6
+ * time. An import that crosses from the first into the second is only sound
7
+ * while the allowlist happens to name its target, and nothing checked that.
8
+ * `lib/conformity.ts` imported `../scripts/split-spec` through two releases
9
+ * with the file left out, so every consumer of `rungate/lib/conformity` died
10
+ * on import while the repo stayed green — the suites resolve that path against
11
+ * the working tree, where it exists (#446).
12
+ *
13
+ * The check is static and offline: expand `files[]` into the set the tarball
14
+ * would carry, then walk the relative imports of every published source file
15
+ * and assert each target is in that set. One `catch` here would turn a
16
+ * malformed package.json into "no violations", so there is none.
17
+ */
18
+ import { existsSync, readdirSync, readFileSync, statSync } from "fs";
19
+ import { join, dirname, relative, resolve } from "path";
20
+
21
+ /** Extensions a bare specifier may acquire, in the order a resolver tries. */
22
+ const CANDIDATE_SUFFIXES = ["", ".ts", ".tsx", ".js", ".mjs", ".json", "/index.ts", "/index.js"];
23
+
24
+ const SOURCE_EXT = /\.(ts|tsx|mts|js|mjs)$/;
25
+
26
+ /** `files[]` entries are either a directory ("lib/") or one exact path. */
27
+ export function publishedFiles(root: string, patterns: string[]): Set<string> {
28
+ const out = new Set<string>();
29
+
30
+ function addDir(rel: string) {
31
+ const abs = join(root, rel);
32
+ if (!existsSync(abs)) return;
33
+ for (const entry of readdirSync(abs)) {
34
+ const childRel = `${rel}/${entry}`.replace(/\/+/g, "/");
35
+ if (statSync(join(root, childRel)).isDirectory()) addDir(childRel);
36
+ else out.add(childRel);
37
+ }
38
+ }
39
+
40
+ for (const pattern of patterns) {
41
+ const clean = pattern.replace(/^\.\//, "").replace(/\/$/, "");
42
+ const abs = join(root, clean);
43
+ if (!existsSync(abs)) continue;
44
+ if (statSync(abs).isDirectory()) addDir(clean);
45
+ else out.add(clean);
46
+ }
47
+
48
+ // npm always includes these regardless of files[].
49
+ for (const always of ["package.json", "README.md", "LICENSE"]) {
50
+ if (existsSync(join(root, always))) out.add(always);
51
+ }
52
+ return out;
53
+ }
54
+
55
+ /** Relative specifiers only — bare ones are the dependency resolver's problem. */
56
+ export function relativeImports(source: string): string[] {
57
+ const found: string[] = [];
58
+ const patterns = [
59
+ /\bfrom\s+["'](\.[^"']+)["']/g,
60
+ /\bimport\s+["'](\.[^"']+)["']/g,
61
+ /\bimport\s*\(\s*["'](\.[^"']+)["']\s*\)/g,
62
+ /\brequire\s*\(\s*["'](\.[^"']+)["']\s*\)/g,
63
+ ];
64
+ for (const pattern of patterns) {
65
+ let m: RegExpExecArray | null;
66
+ while ((m = pattern.exec(source)) !== null) found.push(m[1]);
67
+ }
68
+ return found;
69
+ }
70
+
71
+ /**
72
+ * The single binding. `test/package-closure.test.ts` builds a mutant of this
73
+ * module with the body short-circuited to `return []` and asserts the suite
74
+ * goes quiet over a package that is genuinely broken — which is the only thing
75
+ * separating this from a line in a report.
76
+ */
77
+ export function packageClosureViolations(root: string, published: Set<string>): string[] {
78
+ const violations: string[] = [];
79
+
80
+ for (const file of published) {
81
+ if (!SOURCE_EXT.test(file)) continue;
82
+ const source = readFileSync(join(root, file), "utf-8");
83
+
84
+ for (const specifier of relativeImports(source)) {
85
+ const target = resolve(dirname(join(root, file)), specifier);
86
+ const targetRel = relative(root, target);
87
+
88
+ // Resolvable against the working tree but absent from the tarball is
89
+ // the whole defect — a path that does not exist at all is a different
90
+ // bug, and typecheck already owns it.
91
+ const existsOnDisk = CANDIDATE_SUFFIXES.some(s => existsSync(target + s));
92
+ if (!existsOnDisk) continue;
93
+
94
+ const isPublished = CANDIDATE_SUFFIXES.some(s => published.has(`${targetRel}${s}`.replace(/\/+/g, "/")));
95
+ if (!isPublished) {
96
+ violations.push(`${file} imports "${specifier}" -> ${targetRel}, which files[] does not publish`);
97
+ }
98
+ }
99
+ }
100
+ return violations.sort();
101
+ }
102
+
103
+ export function readPackageFiles(root: string): string[] {
104
+ // Deliberately unguarded: a malformed package.json must throw, not read as
105
+ // a package with nothing in it.
106
+ const pkg = JSON.parse(readFileSync(join(root, "package.json"), "utf-8"));
107
+ if (!Array.isArray(pkg.files)) {
108
+ throw new Error("package.json has no files[] array — cannot determine what ships");
109
+ }
110
+ return pkg.files;
111
+ }
@@ -0,0 +1,100 @@
1
+ /**
2
+ * The names a cross-project document actually calls a project by (#442).
3
+ *
4
+ * `scanExternalSources` matched on `basename(projectRoot)` and nothing else,
5
+ * in both of its match modes. Measured by the reporting session against a
6
+ * real document in a sibling project:
7
+ *
8
+ * grep -ic "dailybriefdashboard" -> 0
9
+ * grep -ic "ddb" -> 2
10
+ *
11
+ * That generalises. A document written in one project that refers to another
12
+ * calls it by nickname, abbreviation, product name or repo slug — almost
13
+ * never by the literal name of the directory it happens to be checked out
14
+ * into. An exact substring match on the folder name is the wrong matcher for
15
+ * the only situation the feature exists to serve, and the feature has never
16
+ * fired for any project.
17
+ */
18
+
19
+ import { existsSync, readFileSync } from "fs";
20
+ import { basename, join } from "path";
21
+
22
+ /**
23
+ * Below this length an alias matches so much that it is noise.
24
+ *
25
+ * Two characters inside word boundaries is already thin; one is a letter,
26
+ * and a one-letter alias proposes adopting most of a directory. The same
27
+ * shape bit #437, where a one-character prefix made `isScratchEntry`
28
+ * accept `.claude`.
29
+ */
30
+ export const MIN_ALIAS_LENGTH = 2;
31
+
32
+ function escapeRegex(s: string): string {
33
+ return s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
34
+ }
35
+
36
+ /** `owner/name` from a git remote URL, in either of the two forms git writes. */
37
+ export function remoteSlug(remoteUrl: string): string | null {
38
+ const m = /(?:github\.com[:/])([^/\s]+)\/([^/\s]+?)(?:\.git)?\s*$/.exec(remoteUrl.trim());
39
+ if (!m) return null;
40
+ return `${m[1]}/${m[2]}`;
41
+ }
42
+
43
+ /**
44
+ * Every name this project answers to, lowercased and de-duplicated.
45
+ *
46
+ * The repo name and the GitHub slug are DERIVED rather than typed, which is
47
+ * the point of SC-1: a project should not have to write down facts the tree
48
+ * already states. `configured` is for the ones only a human knows — the
49
+ * abbreviation, the product name, the thing the team says out loud.
50
+ */
51
+ export function projectAliases(projectRoot: string, configured: string[] = []): string[] {
52
+ const out: string[] = [basename(projectRoot)];
53
+
54
+ // `.git/config` rather than spawning git: this runs inside scaffold, and a
55
+ // subprocess per scaffolded project is a cost with no payoff when the file
56
+ // is right there. An unreadable or absent one simply contributes nothing —
57
+ // not a fail-open, because the directory name is always present and the
58
+ // caller is told which aliases were used.
59
+ const gitConfig = join(projectRoot, ".git", "config");
60
+ if (existsSync(gitConfig)) {
61
+ let text = "";
62
+ try {
63
+ text = readFileSync(gitConfig, "utf-8");
64
+ } catch {
65
+ text = "";
66
+ }
67
+ for (const m of text.matchAll(/^\s*url\s*=\s*(.+)$/gm)) {
68
+ const slug = remoteSlug(m[1]!);
69
+ if (!slug) continue;
70
+ out.push(slug);
71
+ out.push(slug.split("/")[1]!);
72
+ }
73
+ }
74
+
75
+ out.push(...configured);
76
+
77
+ const seen = new Set<string>();
78
+ return out
79
+ .map(a => a.trim().toLowerCase())
80
+ .filter(a => a.length >= MIN_ALIAS_LENGTH && !seen.has(a) && (seen.add(a), true));
81
+ }
82
+
83
+ /**
84
+ * Whether any alias appears in `text` as a WORD.
85
+ *
86
+ * ONE decider, used by both match modes. They were two separate expressions
87
+ * — `entry.toLowerCase().includes(projectName)` and
88
+ * `content.toLowerCase().includes(projectName)` — which meant two places to
89
+ * fix and two places for them to drift apart.
90
+ *
91
+ * Word boundaries rather than substring, because the aliases that make this
92
+ * feature work are short: `ddb` as a substring matches `oddball`, and a
93
+ * three-letter abbreviation proposing adoption of every document that
94
+ * happens to contain those letters is worse than the matcher that never
95
+ * fired. A slug like `owner/name` is bounded by `/`, which `\b` handles.
96
+ */
97
+ export function matchesAnyAlias(text: string, aliases: string[]): boolean {
98
+ const haystack = text.toLowerCase();
99
+ return aliases.some(a => new RegExp(`\\b${escapeRegex(a)}\\b`).test(haystack));
100
+ }