@diffci.com/diffci 0.3.61 → 0.3.63

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.
@@ -33,6 +33,7 @@
33
33
  */
34
34
  import { readFileSync, statSync } from "node:fs";
35
35
  import { join, posix } from "node:path";
36
+ import ts from "typescript";
36
37
  import { matchesGlob } from "./test-discovery.js";
37
38
  import { LOCKFILE_NAMES } from "./lockfiles.js";
38
39
 
@@ -357,7 +358,7 @@ function callArguments(content: string, start: number): CallArgument[] | undefin
357
358
  * everything under it, and a single literal between variables (`join(root, "ops", name)`) is left bare,
358
359
  * so a dynamic path keeps the conservative answer.
359
360
  */
360
- export function foldJoinedLiterals(content: string): string {
361
+ export function foldJoinedLiterals(content: string, bases?: ReadonlyMap<string, string>): string {
361
362
  if (!/\b(?:join|Join|resolve)\s*\(/.test(content)) return content;
362
363
  let folded = "";
363
364
  let last = 0;
@@ -366,7 +367,25 @@ export function foldJoinedLiterals(content: string): string {
366
367
  if (start < last) continue;
367
368
  const args = callArguments(content, start);
368
369
  if (!args) continue;
369
- for (let i = 0; i < args.length;) {
370
+ let from = 0;
371
+ // A known directory first, then literals: one repository path, anchored at the root (`$repo/...`),
372
+ // which names exactly that path instead of any directory of the same name (knownPathBases).
373
+ const base = args[0] && args[0].literal === undefined ? bases?.get(content.slice(args[0].start, args[0].end)) : undefined;
374
+ if (base !== undefined && args[1]?.literal !== undefined) {
375
+ let j = 1;
376
+ while (j + 1 < args.length && args[j + 1]!.literal !== undefined) j++;
377
+ const literals = args.slice(1, j + 1).map((arg) => arg.literal!);
378
+ // resolve() restarts at an absolute literal; the result is then not below the known directory.
379
+ if (!(/^resolve/.test(call[0]) && literals.some((literal) => literal.startsWith("/")))) {
380
+ const joined = posix.normalize(posix.join(base || ".", ...literals));
381
+ if (!joined.startsWith("..") && !posix.isAbsolute(joined)) {
382
+ folded += `${content.slice(last, args[0]!.start)}"$repo/${joined}"`;
383
+ last = args[j]!.end;
384
+ from = j + 1;
385
+ }
386
+ }
387
+ }
388
+ for (let i = from; i < args.length;) {
370
389
  if (args[i]!.literal === undefined) { i++; continue; }
371
390
  let j = i;
372
391
  while (j + 1 < args.length && args[j + 1]!.literal !== undefined) j++;
@@ -444,10 +463,146 @@ function namesDirectoryOf(content: string, readerPath: string, target: string):
444
463
  * a different file names that file, and a glob names only what it matches (2026-11-04). Bare names and
445
464
  * variables inside a path keep the conservative answer.
446
465
  */
466
+ const SCRIPT_FILE = /\.(?:[cm]?[jt]sx?)$/i;
467
+
468
+ /**
469
+ * JavaScript and TypeScript with every comment blanked out, length and line breaks kept (2026-11-23).
470
+ *
471
+ * WHY. A comment executes nothing, so a path named only in one is not read by the file. DentalPresence's
472
+ * route-cache-policy.ts and write-freeze.ts say "see ... in ops/cloudflare/src/index.js" in comments, and
473
+ * since much of the app imports them, every change to index.js selected about 190 tests: 3,030 test
474
+ * selections over 16 narrowed runs. Dockerfile and workflow comments were already ignored the same way.
475
+ *
476
+ * HOW. Comment ranges come from TypeScript's parser, so `//` inside a string, a template literal or a regular
477
+ * expression is never mistaken for a comment. Only trivia before or after a syntax node is blanked; a comment
478
+ * the walk does not reach stays, which can only keep a reader. Triple-slash directives (`/// <reference path>`)
479
+ * are loaded by the compiler and stay.
480
+ */
481
+ export function withoutCodeComments(content: string, path: string): string {
482
+ const kind = /\.tsx$/i.test(path) ? ts.ScriptKind.TSX : /\.jsx$/i.test(path) ? ts.ScriptKind.JSX : /\.[cm]?ts$/i.test(path) ? ts.ScriptKind.TS : ts.ScriptKind.JS;
483
+ const source = ts.createSourceFile(path, content, ts.ScriptTarget.Latest, false, kind);
484
+ const ranges = new Map<number, number>();
485
+ const collect = (list: ts.CommentRange[] | undefined) => {
486
+ for (const range of list ?? []) {
487
+ if (/^\/\/\/\s*<(?:reference|amd-)/.test(content.slice(range.pos, range.end))) continue;
488
+ ranges.set(range.pos, range.end);
489
+ }
490
+ };
491
+ const visit = (node: ts.Node) => {
492
+ collect(ts.getLeadingCommentRanges(content, node.getFullStart()));
493
+ collect(ts.getTrailingCommentRanges(content, node.getEnd()));
494
+ ts.forEachChild(node, visit);
495
+ };
496
+ visit(source);
497
+ if (ranges.size === 0) return content;
498
+ let out = "";
499
+ let from = 0;
500
+ for (const [pos, end] of [...ranges].sort((a, b) => a[0] - b[0])) {
501
+ if (pos < from) continue;
502
+ out += content.slice(from, pos) + content.slice(pos, end).replace(/[^\r\n]/g, " ");
503
+ from = end;
504
+ }
505
+ return out + content.slice(from);
506
+ }
507
+
508
+ /**
509
+ * Directories a script's path variables name, worked out from the script's own location (2026-11-23).
510
+ *
511
+ * WHY. `path.join(root, "src")` was read as a bare `"src"`, which names every directory called src: in
512
+ * DentalPresence, scripts/test-security.js walks the repository's src/, and because `npm test` runs it, every
513
+ * change under ops/cloudflare/src/ ran the full suite. Its `root` is `path.resolve(__dirname, "..")`, which
514
+ * says exactly which directory it is.
515
+ *
516
+ * WHAT. The values of `__dirname`, `import.meta.dirname`, and each top-level `const` whose initializer is built
517
+ * only from those, `fileURLToPath(new URL(literal, import.meta.url))`, `dirname(fileURLToPath(import.meta.url))`
518
+ * and `join`/`resolve`/`dirname` of a known directory with string literals: repository-relative, `""` for the
519
+ * root. A name counts only when it is the file's single binding of that name, so no parameter, inner variable
520
+ * or reassignment can shadow it. `process.cwd()`, environment variables and anything else stay unknown, and a
521
+ * join on an unknown base keeps the conservative reading.
522
+ */
523
+ export function knownPathBases(content: string, readerPath: string): Map<string, string> {
524
+ const readerDir = posix.dirname(readerPath) === "." ? "" : posix.dirname(readerPath);
525
+ const known = new Map<string, string>([["import.meta.dirname", readerDir]]);
526
+ if (!/\b(?:__dirname|import\.meta)\b/.test(content)) return known;
527
+ const source =ts.createSourceFile(readerPath, content, ts.ScriptTarget.Latest, false, /\.[cm]?tsx?$/i.test(readerPath) ? ts.ScriptKind.TS : ts.ScriptKind.JS);
528
+ const bindings = new Map<string, number>();
529
+ const bind = (name: ts.BindingName | ts.Identifier | undefined) => {
530
+ if (!name) return;
531
+ if (ts.isIdentifier(name)) bindings.set(name.text, (bindings.get(name.text) ?? 0) + 1);
532
+ else for (const element of name.elements) if (!ts.isOmittedExpression(element)) bind(element.name);
533
+ };
534
+ const visit = (node: ts.Node) => {
535
+ if (ts.isVariableDeclaration(node) || ts.isParameter(node) || ts.isBindingElement(node)) bind(node.name);
536
+ else if ((ts.isFunctionDeclaration(node) || ts.isFunctionExpression(node) || ts.isClassDeclaration(node)) && node.name) bind(node.name);
537
+ else if (ts.isImportClause(node) || ts.isImportSpecifier(node) || ts.isNamespaceImport(node) || ts.isImportEqualsDeclaration(node)) bind(node.name);
538
+ else if (ts.isBinaryExpression(node) && node.operatorToken.kind >= ts.SyntaxKind.FirstAssignment && node.operatorToken.kind <= ts.SyntaxKind.LastAssignment && ts.isIdentifier(node.left)) {
539
+ bindings.set(node.left.text, 2); // reassigned: never trusted
540
+ }
541
+ ts.forEachChild(node, visit);
542
+ };
543
+ visit(source);
544
+ // CommonJS's own __dirname, unless the file declares one (the ESM idiom), which is then judged like any const.
545
+ if (!bindings.has("__dirname")) known.set("__dirname", readerDir);
546
+
547
+ const literal =(node: ts.Expression) => ts.isStringLiteral(node) || ts.isNoSubstitutionTemplateLiteral(node) ? node.text : undefined;
548
+ const callee = (node: ts.CallExpression) => ts.isIdentifier(node.expression) ? node.expression.text : ts.isPropertyAccessExpression(node.expression) ? node.expression.name.text : undefined;
549
+ const importMetaUrl = (node: ts.Expression) => ts.isPropertyAccessExpression(node) && node.name.text === "url" && ts.isMetaProperty(node.expression);
550
+ const inside = (path: string) => {
551
+ const normal = posix.normalize(path || ".");
552
+ if (normal.startsWith("..") || posix.isAbsolute(normal)) return undefined;
553
+ const trimmed = normal.replace(TRAILING_SLASHES, "");
554
+ return trimmed === "." || trimmed === "" ? "" : trimmed;
555
+ };
556
+ const evaluate = (node: ts.Expression): string | undefined => {
557
+ if (ts.isParenthesizedExpression(node)) return evaluate(node.expression);
558
+ if (ts.isIdentifier(node)) return known.get(node.text);
559
+ if (ts.isPropertyAccessExpression(node) && node.name.text === "dirname" && ts.isMetaProperty(node.expression)) return readerDir;
560
+ if (!ts.isCallExpression(node)) return undefined;
561
+ const name = callee(node);
562
+ const [first, ...rest] = node.arguments;
563
+ if (!first) return undefined;
564
+ // fileURLToPath(new URL("..", import.meta.url)): resolved against this file's URL.
565
+ if (name === "fileURLToPath" && node.arguments.length === 1 && ts.isNewExpression(first) && ts.isIdentifier(first.expression) && first.expression.text === "URL"
566
+ && first.arguments?.length === 2 && importMetaUrl(first.arguments[1]!)) {
567
+ const relative = literal(first.arguments[0]!);
568
+ return relative === undefined || relative.startsWith("/") || /^[a-z]+:/i.test(relative) ? undefined : inside(posix.join(readerDir || ".", relative));
569
+ }
570
+ if (name === "dirname" && node.arguments.length === 1) {
571
+ // dirname(fileURLToPath(import.meta.url)) is this file's directory.
572
+ if (ts.isCallExpression(first) && callee(first) === "fileURLToPath" && first.arguments.length === 1 && importMetaUrl(first.arguments[0]!)) return readerDir;
573
+ const dir = evaluate(first);
574
+ return dir === undefined || dir === "" ? undefined : inside(posix.dirname(dir));
575
+ }
576
+ if (name === "join" || name === "resolve") {
577
+ const base = evaluate(first);
578
+ const parts = rest.map(literal);
579
+ if (base === undefined || parts.some((part) => part === undefined || part.startsWith("/"))) return undefined;
580
+ return inside(posix.join(base || ".", ...(parts as string[])));
581
+ }
582
+ return undefined;
583
+ };
584
+
585
+ for (const statement of source.statements) {
586
+ if (!ts.isVariableStatement(statement) || !(statement.declarationList.flags & ts.NodeFlags.Const)) continue;
587
+ for (const declaration of statement.declarationList.declarations) {
588
+ if (!ts.isIdentifier(declaration.name) || !declaration.initializer || bindings.get(declaration.name.text) !== 1) continue;
589
+ const value = evaluate(declaration.initializer);
590
+ if (value !== undefined) known.set(declaration.name.text, value);
591
+ }
592
+ }
593
+ return known;
594
+ }
595
+
447
596
  export function contentNamesPath(content: string, readerPath: string, target: string, pattern: RegExp, ancestors: boolean, readGlobs = true): boolean {
448
597
  if (!pattern.test(content)) return false;
598
+ // A script that names the path only in comments does not read it.
599
+ const script = SCRIPT_FILE.test(readerPath);
600
+ if (script) {
601
+ content = withoutCodeComments(content, readerPath);
602
+ if (!pattern.test(content)) return false;
603
+ }
449
604
  // Every path a join folds to was spelled out by its parts, so the raw test above stays a valid filter.
450
- content = foldJoinedLiterals(content);
605
+ content = foldJoinedLiterals(content, script ? knownPathBases(content, readerPath) : undefined);
451
606
  const dirs: string[] = [];
452
607
  for (let dir = posix.dirname(target); ancestors && dir !== "." && dir !== "/"; dir = posix.dirname(dir)) dirs.push(dir);
453
608
  const names = [target, ...dirs];
@@ -458,6 +613,19 @@ export function contentNamesPath(content: string, readerPath: string, target: st
458
613
  // in a workflow comment) does not count, as the reference pattern intends (2026-11-04).
459
614
  if (!pattern.test(content.slice(Math.max(0, match.index - 1), match.index + word.length + 1))) continue;
460
615
  if (inExclusionList(content, match.index)) continue;
616
+ // A join on a directory the script names exactly (knownPathBases): this repository path and no other.
617
+ const anchored = /^\$repo\/(.*)$/.exec(word);
618
+ if (anchored) {
619
+ const rest = anchored[1]!.replace(TRAILING_SLASHES, "");
620
+ if (rest === "" || rest === ".") return true;
621
+ if (/[*?{}[\]!$]/.test(rest)) {
622
+ if (!readGlobs) continue;
623
+ if (names.some((name) => matchesGlob(name, widenCharacterClasses(rest)))) return true;
624
+ continue;
625
+ }
626
+ if (names.includes(posix.normalize(rest))) return true;
627
+ continue;
628
+ }
461
629
  // A leading variable is a directory the content does not name (`$GITHUB_ACTION_PATH/../../scripts/x.sh`
462
630
  // names `scripts/x.sh` somewhere, not the repository's `scripts/`), so the rest is a path relative to
463
631
  // an unknown directory (2026-11-04: a LobeHub composite action blocked every changed file under scripts/).
@@ -65,6 +65,7 @@ function toolConfigurationSubject(filePath: string): string | undefined {
65
65
  const base = posix.basename(filePath);
66
66
  if (base === ".nvmrc" || base === ".node-version") return "Node version";
67
67
  if (base === ".npmrc") return "package manager settings";
68
+ if (/^\.yarn\/(?:releases|plugins)\//.test(filePath)) return "package manager";
68
69
  if (/^tsconfig\.[^/]+\.json$/.test(base) || /^jsconfig\.[^/]+\.json$/.test(base)) return "TypeScript configuration";
69
70
  if (base === ".mocharc" || base.startsWith(".mocharc.")) return "Mocha settings";
70
71
  if (base === ".tool-versions" || /^\.?mise(?:\.local)?\.toml$/.test(base)) return "tool versions";
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@diffci.com/diffci",
3
- "version": "0.3.61",
3
+ "version": "0.3.63",
4
4
  "description": "Verification for AI coding agents: runs the tests and checks a change affects, with full fallback and a receipt",
5
5
  "keywords": [
6
6
  "ci",
@@ -76,7 +76,7 @@
76
76
  "test": "node scripts/run-tests.mjs"
77
77
  },
78
78
  "dependencies": {
79
- "@diffci.com/core": "git+https://github.com/DiffCI/core.git#2304f706d00f49759517b94257caef67ef4c3fa3",
79
+ "@diffci.com/core": "git+https://github.com/DiffCI/core.git#e22323333adf89a959fe4e47297b8b3f365bbe95",
80
80
  "saxes": "6.0.0",
81
81
  "yaml": "^2.9.0"
82
82
  },
@@ -88,5 +88,5 @@
88
88
  "bundleDependencies": [
89
89
  "@diffci.com/core"
90
90
  ],
91
- "gitHead": "ec24f7c817ee3eac2574f15d35a987f5e7143828"
91
+ "gitHead": "ebeb4337fec92ee10fdb08800f9f80399bd0f836"
92
92
  }