diff --git a/src/cache/graph-cache.ts b/src/cache/graph-cache.ts index 5081e2fa..7849c670 100644 --- a/src/cache/graph-cache.ts +++ b/src/cache/graph-cache.ts @@ -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; diff --git a/src/repo/graph.ts b/src/repo/graph.ts index 6412afb3..44655911 100644 --- a/src/repo/graph.ts +++ b/src/repo/graph.ts @@ -25,6 +25,7 @@ interface ImportRef { specifier: string; kind: DependencyEdgeKind; dynamic: boolean; + computed?: boolean; } const SOURCE_EXTENSIONS = new Set([ @@ -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)) { @@ -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, }); } } @@ -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); @@ -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). @@ -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 diff --git a/tests/cache/graph-cache.test.ts b/tests/cache/graph-cache.test.ts index a2424c5f..d0583b19 100644 --- a/tests/cache/graph-cache.test.ts +++ b/tests/cache/graph-cache.test.ts @@ -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"; @@ -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" }); diff --git a/tests/repo/graph.test.ts b/tests/repo/graph.test.ts index 2f517d8e..7835fdbf 100644 --- a/tests/repo/graph.test.ts +++ b/tests/repo/graph.test.ts @@ -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, @@ -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 }); + } + }); + } +});