Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 1 addition & 1 deletion src/cache/graph-cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import { existsSync, mkdirSync, readFileSync, writeFileSync } from "node:fs";
import { resolve } from "node:path";
import type { DependencyGraphResult } from "../repo/types.js";

export const GRAPH_CACHE_SCHEMA_VERSION = "2";
export const GRAPH_CACHE_SCHEMA_VERSION = "3";

export interface GraphCacheKeyInputs {
commitSha: string;
Expand Down
53 changes: 28 additions & 25 deletions src/repo/graph.ts
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ interface ImportRef {
specifier: string;
kind: DependencyEdgeKind;
dynamic: boolean;
computed?: boolean;
}

const SOURCE_EXTENSIONS = new Set([
Expand Down Expand Up @@ -108,6 +109,11 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
const kind: DependencyEdgeKind = isTypeOnly ? "type-import" : "import";
refs.push({ specifier: specifier.text, kind, dynamic: false });
}
} else if (ts.isImportEqualsDeclaration(node) && ts.isExternalModuleReference(node.moduleReference)) {
const specifier = node.moduleReference.expression;
if (specifier && ts.isStringLiteral(specifier)) {
refs.push({ specifier: specifier.text, kind: node.isTypeOnly ? "type-import" : "require", dynamic: false });
}
} else if (ts.isExportDeclaration(node) && node.moduleSpecifier) {
const specifier = node.moduleSpecifier;
if (ts.isStringLiteral(specifier)) {
Expand All @@ -116,30 +122,15 @@ function extractImportRefs(sourceFile: ts.SourceFile): ImportRef[] {
}
} else if (ts.isCallExpression(node)) {
const firstArg = node.arguments[0];
if (node.expression.kind === ts.SyntaxKind.ImportKeyword && firstArg) {
if (ts.isStringLiteral(firstArg)) {
refs.push({
specifier: firstArg.text,
kind: "dynamic-import",
dynamic: true,
});
} else {
refs.push({
specifier: firstArg.getText(sourceFile).slice(0, 200),
kind: "dynamic-import",
dynamic: true,
});
}
} else if (
ts.isIdentifier(node.expression) &&
node.expression.text === "require" &&
firstArg &&
ts.isStringLiteral(firstArg)
) {
const isImport = node.expression.kind === ts.SyntaxKind.ImportKeyword;
const isRequire = ts.isIdentifier(node.expression) && node.expression.text === "require";
if ((isImport || isRequire) && firstArg) {
const literal = ts.isStringLiteral(firstArg) || ts.isNoSubstitutionTemplateLiteral(firstArg);
refs.push({
specifier: firstArg.text,
kind: "require",
dynamic: false,
specifier: literal ? firstArg.text : firstArg.getText(sourceFile).slice(0, 200),
kind: isImport ? "dynamic-import" : "require",
dynamic: isImport || !literal,
computed: !literal,
});
}
}
Expand Down Expand Up @@ -806,6 +797,13 @@ export async function buildDependencyGraph(
const refs = extractImportRefs(sf);
if (scope && sf.referencedFiles.length) adapterBlockers.push(`Triple-slash file references in the scoped suite require full validation: ${importerRel}`);
for (const ref of refs) {
// Expression text is not a module name. In particular, import(name) must
// not be classified as an external package called "name".
if (ref.computed) {
recordUnresolved(importerRel, ref, "computed module specifier requires full validation");
recordReference("unresolved", importerRel, ref);
continue;
}
if (!ref.specifier) {
recordUnresolved(importerRel, ref, "empty specifier");
recordReference("unresolved", importerRel, ref);
Expand Down Expand Up @@ -1258,14 +1256,16 @@ function computeConfidence(
* graph for EVERY delta, for as long as that one file's import stays unresolved, regardless of whether
* the delta being analyzed has anything to do with it.
*
* This narrows that: an unresolved import only makes THIS delta's confidence untrustworthy if the
* unresolved import's importer file is actually reachable from the delta's changed files (in either
* For static unresolved references, this narrows that: an unresolved import makes THIS delta's
* confidence untrustworthy if its importer is actually reachable from the changed files (in either
* direction - the changed file might depend on the incomplete file, or something reachable from the
* changed file might). If none of the graph's unresolved imports are anywhere near this delta, the
* graph's real incompleteness elsewhere cannot plausibly affect what can safely be determined about
* THIS specific change.
*
* Deliberately NOT narrowed - these remain hard, global blockers regardless of the delta:
* - Unresolved runtime imports/requires: a computed target has no known graph edge, so lack of
* reachability cannot establish that it does not load one of the changed files.
* - `sourceFileCount === 0` (an empty graph gives no reachability information to reason about at all).
* - `integrity.criticalCount > 0` (the graph's own internal structure is broken - a construction bug,
* not a property of any one file, so no delta-specific narrowing is meaningful).
Expand All @@ -1278,6 +1278,9 @@ function computeConfidence(
* sourceFileCount or integrity triggered it. */
export function refineConfidenceForDelta(result: DependencyGraphResult, changedFiles: string[]): GraphConfidence {
if (result.adapterBlockers?.length) return "UNSAFE";
// An unresolved runtime target can be any changed file. Its missing edge
// cannot prove the importer is unrelated to the delta.
if (result.unresolved.some(ref => ref.dynamic)) return "UNSAFE";
// Anything that was never UNSAFE in the first place passes through untouched - there is nothing to
// narrow, and re-deriving sourceFileCount/integrity from raw fields here (rather than trusting the
// already-computed confidence) would be both redundant and a real correctness risk: a caller's
Expand Down
11 changes: 11 additions & 0 deletions tests/cache/graph-cache.test.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
// SPDX-License-Identifier: AGPL-3.0-only
import { strict as assert } from "node:assert";
import { createHash } from "node:crypto";
import { describe, it, beforeEach, afterEach } from "node:test";
import { rmSync, mkdtempSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
Expand Down Expand Up @@ -84,6 +85,16 @@ describe("GraphCache", () => {
assert.equal(cache.load(key), undefined);
});

it("invalidates persisted schema-2 graphs even without an explicit engine version", () => {
const cache = new GraphCache({ cacheDir });
const oldKey = createHash("sha256").update(JSON.stringify({
schema: "2", commit: "abc", tsconfig: "", config: "", diffciVersion: "0.6.0-phase6",
})).digest("hex");
writeFileSync(`${cacheDir}/${oldKey}.json`, JSON.stringify({ ...minimalGraph, cacheSchemaVersion: "2" }));
assert.notEqual(buildGraphCacheKey({ commitSha: "abc" }), oldKey);
assert.equal(cache.load(oldKey), undefined, "pre-fix graphs must be rebuilt with the current analysis");
});

it("rejects corrupted serialized graph cache", () => {
const cache = new GraphCache({ cacheDir });
const key = buildGraphCacheKey({ commitSha: "abc" });
Expand Down
81 changes: 81 additions & 0 deletions tests/repo/graph.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { mkdirSync, mkdtempSync, rmSync, writeFileSync } from "node:fs";
import { tmpdir } from "node:os";
import { dirname, join } from "node:path";
import { describe, it } from "node:test";
import { ImpactAnalyzer } from "../../src/repo/impact.js";
import {
buildDependencyGraph,
graphToJson,
Expand Down Expand Up @@ -638,3 +639,83 @@ describe("tsconfig discovery is clamped to the repository (Phase 01 F5, 2026-08-
}
});
});

describe("runtime module references", () => {
for (const [name, source] of Object.entries({
"variable import": "const path = './changed'; export const load = () => import(path);",
"conditional import": "export const load = () => import(true ? './changed' : './other');",
"interpolated import": "export const load = (name: string) => import(`./${name}`);",
"variable require": "const path = './changed'; export const load = () => require(path);",
"interpolated require": "export const load = (name: string) => require(`./${name}`);",
})) {
it(`keeps full fallback for ${name} when the changed target has no static edge`, async () => {
const root = createTempRepo({
"src/changed.ts": "export const value = 1;",
"src/other.ts": "export const value = 2;",
"src/loader.ts": source,
"tests/loader.test.ts": "import { load } from '../src/loader'; export const value = load('changed');",
"tests/unrelated.test.ts": "export const unrelated = 1;",
});
try {
const result = await buildDependencyGraph({ repoPath: root });
assert.equal(result.confidence, "UNSAFE");
assert.ok(result.unresolved.some(ref => ref.importer === "src/loader.ts" && ref.dynamic));
assert.equal(refineConfidenceForDelta(result, ["src/changed.ts"]), "UNSAFE");
const impact = new ImpactAnalyzer().analyze({
baseSha: "base", headSha: "head", files: [{ path: "src/changed.ts", changeType: "modified" }], directories: [],
summary: { total: 1, added: 0, modified: 1, deleted: 0, renamed: 0, copied: 0, unmerged: 0, unknown: 0 },
analysis: { empty: false, configChanged: false, dependencyManifestChanged: false, lockfileChanged: false, workflowChanged: false, infrastructureChanged: false, databaseChanged: false },
}, result, result.profile);
assert.equal(impact.fallbackRequired, true);
assert.equal(impact.analysisStatus, "FALLBACK");
} finally {
rmSync(root, { recursive: true, force: true });
}
});
}

for (const [name, source] of Object.entries({
import: "export const load = () => import(`./changed`);",
require: "export const load = () => require(`./changed`);",
})) {
it(`resolves no-substitution template ${name} as a literal dependency`, async () => {
const root = createTempRepo({
"src/changed.ts": "export const value = 1;",
"src/loader.ts": source,
"tests/loader.test.ts": "import { load } from '../src/loader'; export const value = load();",
"tests/unrelated.test.ts": "export const unrelated = 1;",
});
try {
const result = await buildDependencyGraph({ repoPath: root });
assert.equal(result.confidence, "COMPLETE");
assert.deepEqual(result.graph.transitiveDependentsOf("src/changed.ts"), ["src/loader.ts", "tests/loader.test.ts"]);
} finally {
rmSync(root, { recursive: true, force: true });
}
});
}
});

describe("TypeScript import-equals dependencies", () => {
for (const typeOnly of [false, true]) {
it(`tracks ${typeOnly ? 'type-only' : 'runtime'} external-module import-equals declarations`, async () => {
const root = createTempRepo({
"tsconfig.json": JSON.stringify({ compilerOptions: { target: "ES2022", module: "CommonJS", moduleResolution: "Node10" }, include: ["**/*.ts"] }),
"src/changed.ts": "const value = 1; export = value;",
"src/loader.ts": `import ${typeOnly ? 'type ' : ''}changed = require('./changed'); export ${typeOnly ? 'type Value = typeof changed' : 'const value = changed'};`,
"tests/loader.test.ts": "import './loader-helper';",
"tests/loader-helper.ts": "import '../src/loader';",
"tests/unrelated.test.ts": "export const unrelated = 1;",
});
try {
const result = await buildDependencyGraph({ repoPath: root });
assert.equal(result.confidence, "COMPLETE");
assert.ok(result.graph.edges.some(edge => edge.from === "src/loader.ts" && edge.to === "src/changed.ts" && edge.kind === (typeOnly ? "type-import" : "require")));
assert.ok(result.graph.transitiveDependentsOf("src/changed.ts").includes("tests/loader.test.ts"));
assert.ok(!result.graph.transitiveDependentsOf("src/changed.ts").includes("tests/unrelated.test.ts"));
} finally {
rmSync(root, { recursive: true, force: true });
}
});
}
});