Skip to content

Graphs that teach > graphs that impress. Turn any code into an interactive knowledge graph you can explore, search, and ask questions about. Works with Claude Code, Codex, Cursor, Copilot, Gemini CLI, and more.

fix(import-map): abort incremental refresh failures

Lum1104884c559af992
diff --git a/tests/skill/understand/test_extract_import_map.test.mjs b/tests/skill/understand/test_extract_import_map.test.mjs
index 0cd0ed88..c6d49cc3 100644
--- a/tests/skill/understand/test_extract_import_map.test.mjs
+++ b/tests/skill/understand/test_extract_import_map.test.mjs
@@ -1583,6 +1583,9 @@ describe('extract-import-map.mjs — per-file failure resilience', () => {
expect(result.output.importMap['src/other.ts']).toEqual([]);
// Missing file is in importMap with []
expect(result.output.importMap['src/missing.ts']).toEqual([]);
+ expect(result.output.failures).toEqual([
+ expect.objectContaining({ path: 'src/missing.ts', stage: 'file-read' }),
+ ]);
// A warning was emitted on stderr for the missing file
expect(result.stderr).toMatch(/Warning: extract-import-map: import resolution failed for src\/missing\.ts/);
expect(result.stderr).toMatch(/importMap\[src\/missing\.ts\]=\[\]/);
@@ -1638,6 +1641,7 @@ describe('extract-import-map.mjs — output schema invariants', () => {
});
expect(result.status).toBe(0);
+ expect(result.output.failures).toEqual([]);
expect(Object.keys(result.output.importMap).sort()).toEqual([
'Dockerfile', 'README.md', 'a.ts', 'package.json',
]);
@@ -1933,6 +1937,9 @@ describe('extract-import-map.mjs — tsconfig parse resilience', () => {
expect(result.stderr).toMatch(/path aliases.*will not be applied/);
// Aliased import unresolved; relative import still resolves.
expect(result.output.importMap['src/index.ts']).toEqual(['src/sibling.ts']);
+ expect(result.output.failures).toEqual([
+ expect.objectContaining({ path: 'tsconfig.json', stage: 'resolver-config-parse' }),
+ ]);
});
it('falls back to raw-text parse when a paths value contains "//" that the stripper would damage', () => {
@@ -2083,6 +2090,9 @@ describe('extract-import-map.mjs — tree-sitter init graceful failure', () => {
expect(result.output.stats.filesScanned).toBe(2);
expect(result.output.stats.filesWithImports).toBe(0);
expect(result.output.stats.totalEdges).toBe(0);
+ expect(result.output.failures).toEqual([
+ expect.objectContaining({ path: null, stage: 'tree-sitter-init' }),
+ ]);
});
});
diff --git a/tests/skill/understand/test_prepare_incremental.test.mjs b/tests/skill/understand/test_prepare_incremental.test.mjs
index 4b63d3be..fb036e00 100644
--- a/tests/skill/understand/test_prepare_incremental.test.mjs
+++ b/tests/skill/understand/test_prepare_incremental.test.mjs
@@ -385,6 +385,40 @@ describe('prepare-incremental.mjs', { timeout: 30_000 }, () => {
expect(scan.importMap['src/index.ts']).toEqual(['alternate/foo.ts']);
});
+ it('aborts without advancing baselines when import extraction reports a config failure', () => {
+ const { root, baseCommit } = setupRepository({
+ 'tsconfig.json': JSON.stringify({
+ compilerOptions: { baseUrl: '.', paths: { '@/*': ['src/*'] } },
+ }),
+ 'src/index.ts': "import { value } from '@/foo';\nexport { value };\n",
+ 'src/foo.ts': 'export const value = 1;\n',
+ 'src/a.ts': 'export const a = 1;\n',
+ });
+ const graphPath = join(root, '.ua', 'knowledge-graph.json');
+ const fingerprintPath = join(root, '.ua', 'fingerprints.json');
+ const metaPath = join(root, '.ua', 'meta.json');
+ const scanPath = join(root, '.ua', 'intermediate', 'scan-result.json');
+ const graphBefore = readFileSync(graphPath, 'utf-8');
+ const fingerprintsBefore = readFileSync(fingerprintPath, 'utf-8');
+ const metaBefore = readFileSync(metaPath, 'utf-8');
+ const scanBefore = readFileSync(scanPath, 'utf-8');
+ writeProjectFile(root, 'tsconfig.json', '{"compilerOptions":{"paths":');
+ commit(root, 'break resolver config');
+
+ const result = spawnSync(process.execPath, [prepareScript, root, baseCommit], {
+ cwd: root,
+ encoding: 'utf-8',
+ });
+ expect(result.status).not.toBe(0);
+ expect(result.stderr).toContain(
+ 'Import extraction reported failures: tsconfig.json (resolver-config-parse)',
+ );
+ expect(readFileSync(graphPath, 'utf-8')).toBe(graphBefore);
+ expect(readFileSync(fingerprintPath, 'utf-8')).toBe(fingerprintsBefore);
+ expect(readFileSync(metaPath, 'utf-8')).toBe(metaBefore);
+ expect(readFileSync(scanPath, 'utf-8')).toBe(scanBefore);
+ });
+
it('refreshes supplemental require imports even when fingerprints classify the edit as cosmetic', () => {
const { root, baseCommit } = setupRepository({
'src/index.js': "const value = require('./a');\nmodule.exports = value;\n",
diff --git a/understand-anything-plugin/skills/understand/extract-import-map.mjs b/understand-anything-plugin/skills/understand/extract-import-map.mjs
index 27d02398..2c7aa9d2 100644
--- a/understand-anything-plugin/skills/understand/extract-import-map.mjs
+++ b/understand-anything-plugin/skills/understand/extract-import-map.mjs
@@ -263,6 +263,7 @@ function parseTsConfigText(raw) {
async function loadTsConfigs(projectRoot, files) {
const out = new Map();
const warnings = [];
+ const failures = [];
// Collect the candidate paths in the original file order before reading,
// so warning emit order matches the previous sequential implementation.
const candidates = [];
@@ -277,6 +278,7 @@ async function loadTsConfigs(projectRoot, files) {
const reads = await readFilesParallel(candidates);
for (const { key: p, raw, err } of reads) {
if (err) {
+ failures.push({ path: p, stage: 'resolver-config-read', message: err.message });
// absPath isn't carried through the helper return shape; reconstruct it.
warnings.push(
`Warning: extract-import-map: tsconfig.json at ${join(projectRoot, p)} failed ` +
@@ -287,6 +289,11 @@ async function loadTsConfigs(projectRoot, files) {
}
const parsed = parseTsConfigText(raw);
if (!parsed) {
+ failures.push({
+ path: p,
+ stage: 'resolver-config-parse',
+ message: 'invalid tsconfig.json',
+ });
warnings.push(
`Warning: extract-import-map: tsconfig.json at ${join(projectRoot, p)} failed ` +
`to parse — path aliases from this config will not be applied ` +
@@ -296,7 +303,7 @@ async function loadTsConfigs(projectRoot, files) {
}
out.set(dirOf(p), parsed);
}
- return { configs: out, warnings };
+ return { configs: out, warnings, failures };
}
/**
@@ -331,6 +338,7 @@ async function loadGoModules(projectRoot, files) {
// so the concurrent caller in buildResolutionContext can drain them
// uniformly in canonical order.
const warnings = [];
+ const failures = [];
const candidates = [];
for (const f of files) {
const p = toPosix(f.path);
@@ -342,7 +350,14 @@ async function loadGoModules(projectRoot, files) {
}
const reads = await readFilesParallel(candidates);
for (const { key: p, raw, err } of reads) {
- if (err) continue;
+ if (err) {
+ failures.push({ path: p, stage: 'resolver-config-read', message: err.message });
+ warnings.push(
+ `Warning: extract-import-map: go.mod at ${join(projectRoot, p)} failed ` +
+ `to read (${err.message}) — Go module imports may not resolve\n`,
+ );
+ continue;
+ }
let moduleName = '';
for (const line of raw.split(/\r?\n/)) {
const trimmed = line.replace(/\/\/.*$/, '').trim();
@@ -350,10 +365,21 @@ async function loadGoModules(projectRoot, files) {
moduleName = trimmed.slice('module '.length).trim();
break;
}
- if (!moduleName) continue;
+ if (!moduleName) {
+ failures.push({
+ path: p,
+ stage: 'resolver-config-parse',
+ message: 'module directive missing',
+ });
+ warnings.push(
+ `Warning: extract-import-map: go.mod at ${join(projectRoot, p)} has no ` +
+ `module directive — Go module imports may not resolve\n`,
+ );
+ continue;
+ }
out.set(dirOf(p), moduleName);
}
- return { modules: out, warnings };
+ return { modules: out, warnings, failures };
}
/**
@@ -425,6 +451,7 @@ function parseSwiftPackageTargets(raw) {
async function loadSwiftPackageTargets(projectRoot, files) {
const targets = new Map();
const warnings = [];
+ const failures = [];
const candidates = [];
for (const f of files) {
@@ -438,7 +465,14 @@ async function loadSwiftPackageTargets(projectRoot, files) {
const reads = await readFilesParallel(candidates);
for (const { key: p, raw, err } of reads) {
- if (err) continue;
+ if (err) {
+ failures.push({ path: p, stage: 'resolver-config-read', message: err.message });
+ warnings.push(
+ `Warning: extract-import-map: Package.swift at ${join(projectRoot, p)} failed ` +
+ `to read (${err.message}) — Swift module imports may not resolve\n`,
+ );
+ continue;
+ }
const packageDir = dirOf(p);
for (const target of parseSwiftPackageTargets(raw)) {
const targetPath = resolveRelative(packageDir, target.path.replace(/\\/g, '/'));
@@ -448,7 +482,7 @@ async function loadSwiftPackageTargets(projectRoot, files) {
}
}
- return { targets, warnings };
+ return { targets, warnings, failures };
}
/**
@@ -558,6 +592,12 @@ async function buildResolutionContext(projectRoot, files) {
scalaPackageIndex,
csIndex,
swiftModuleIndex,
+ failures: [
+ ...tsResult.failures,
+ ...goResult.failures,
+ ...phpResult.failures,
+ ...swiftResult.failures,
+ ],
phpAutoloads,
// Dedupe Sets for one-time-per-file warnings. Keyed by importer file
// path. Mutated by resolvers.
@@ -1490,6 +1530,7 @@ function parseComposerAutoloadText(raw) {
async function loadPhpAutoloads(projectRoot, files) {
const out = new Map();
const warnings = [];
+ const failures = [];
const candidates = [];
for (const f of files) {
const p = toPosix(f.path);
@@ -1502,6 +1543,7 @@ async function loadPhpAutoloads(projectRoot, files) {
const reads = await readFilesParallel(candidates);
for (const { key: p, raw, err } of reads) {
if (err) {
+ failures.push({ path: p, stage: 'resolver-config-read', message: err.message });
warnings.push(
`Warning: extract-import-map: composer.json at ${join(projectRoot, p)} failed ` +
`to read (${err.message}) — PSR-4 namespace mapping from this ` +
@@ -1512,6 +1554,11 @@ async function loadPhpAutoloads(projectRoot, files) {
}
const parsed = parseComposerAutoloadText(raw);
if (parsed === null) {
+ failures.push({
+ path: p,
+ stage: 'resolver-config-parse',
+ message: 'invalid composer.json',
+ });
warnings.push(
`Warning: extract-import-map: composer.json at ${join(projectRoot, p)} failed ` +
`to parse — PSR-4 namespace mapping unavailable — PHP imports ` +
@@ -1521,7 +1568,7 @@ async function loadPhpAutoloads(projectRoot, files) {
}
out.set(dirOf(p), parsed);
}
- return { autoloads: out, warnings };
+ return { autoloads: out, warnings, failures };
}
/**
@@ -1868,6 +1915,7 @@ async function main() {
const output = {
scriptCompleted: true,
stats: { filesScanned: 0, filesWithImports: 0, totalEdges: 0 },
+ failures: [],
importMap: {},
};
writeFileSync(outputPath, JSON.stringify(output, null, 2), 'utf-8');
@@ -1888,6 +1936,7 @@ async function main() {
// (file inventory, exports inferred from filenames, etc.) keeps working.
let registry = null;
let treeSitterReady = false;
+ const failures = [];
try {
const tsConfigs = builtinLanguageConfigs.filter(c => c.treeSitter);
const tsPlugin = new TreeSitterPlugin(tsConfigs);
@@ -1897,6 +1946,7 @@ async function main() {
registerAllParsers(registry);
treeSitterReady = true;
} catch (err) {
+ failures.push({ path: null, stage: 'tree-sitter-init', message: err.message });
process.stderr.write(
`Warning: extract-import-map: tree-sitter init failed ` +
`(${err.message}) — all importMap entries will be empty — ` +
@@ -1908,6 +1958,7 @@ async function main() {
// tsconfig/go.mod/composer.json files inside is parallelised — see
// `buildResolutionContext`.
const ctx = await buildResolutionContext(projectRoot, files);
+ failures.push(...ctx.failures);
const importMap = {};
let filesWithImports = 0;
@@ -1937,6 +1988,7 @@ async function main() {
try {
content = readFileSync(absolutePath, 'utf-8');
} catch (err) {
+ failures.push({ path, stage: 'file-read', message: err.message });
process.stderr.write(
`Warning: extract-import-map: import resolution failed for ${path} ` +
`(read error: ${err.message}) — importMap[${path}]=[]\n`,
@@ -1988,6 +2040,7 @@ async function main() {
: comparePaths(a, b),
);
} catch (err) {
+ failures.push({ path, stage: 'file-analyze', message: err.message });
process.stderr.write(
`Warning: extract-import-map: import resolution failed for ${path} ` +
`(analyze error: ${err.message}) — importMap[${path}]=[]\n`,
@@ -2010,6 +2063,7 @@ async function main() {
filesWithImports,
totalEdges,
},
+ failures,
importMap,
};
diff --git a/understand-anything-plugin/skills/understand/prepare-incremental.mjs b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
index 21c21722..c5b16322 100644
--- a/understand-anything-plugin/skills/understand/prepare-incremental.mjs
+++ b/understand-anything-plugin/skills/understand/prepare-incremental.mjs
@@ -381,7 +381,17 @@ function refreshImportMap({ projectRoot, intermediateDir, oldScan, currentScan,
analysisPaths,
});
run(process.execPath, [IMPORT_SCRIPT, inputPath, outputPath]);
- const selective = readJson(outputPath)?.importMap ?? {};
+ const extraction = readJson(outputPath);
+ const failures = Array.isArray(extraction?.failures) ? extraction.failures : [];
+ if (failures.length > 0) {
+ const preview = failures
+ .slice(0, 5)
+ .map(failure => `${failure.path ?? '<global>'} (${failure.stage})`)
+ .join(', ');
+ const suffix = failures.length > 5 ? ` (+${failures.length - 5} more)` : '';
+ throw new Error(`Import extraction reported failures: ${preview}${suffix}`);
+ }
+ const selective = extraction?.importMap ?? {};
const currentPaths = new Set(currentScan.files.map(file => file.path));
const importMap = {};
for (const file of currentScan.files) {