@angular-modernizer/adapter-mcp 2.0.0 → 2.1.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.
Files changed (46) hide show
  1. package/CHANGELOG.md +45 -0
  2. package/README.md +3 -1
  3. package/dist/cli.js +6 -1
  4. package/dist/index.d.ts +3 -0
  5. package/dist/index.js +1 -0
  6. package/dist/server/build-staleness.d.ts +92 -0
  7. package/dist/server/build-staleness.js +159 -0
  8. package/dist/server/limited-stdio-transport.js +28 -1
  9. package/dist/server/sdk-server.d.ts +6 -0
  10. package/dist/server/sdk-server.js +21 -2
  11. package/dist/server/tool-registry.d.ts +2 -1
  12. package/dist/server/tool-registry.js +8 -2
  13. package/dist/tools/analyze-project.d.ts +26 -1
  14. package/dist/tools/analyze-project.js +8 -3
  15. package/dist/tools/compare-health.d.ts +40 -4
  16. package/dist/tools/compare-health.js +22 -5
  17. package/dist/tools/helpers/analysis-output.js +3 -0
  18. package/dist/tools/helpers/health-delta.d.ts +6 -0
  19. package/dist/tools/helpers/health-delta.js +4 -1
  20. package/dist/tools/helpers/library-import-warning.d.ts +33 -0
  21. package/dist/tools/helpers/library-import-warning.js +38 -0
  22. package/dist/tools/helpers/library-imports.d.ts +38 -14
  23. package/dist/tools/helpers/library-imports.js +128 -23
  24. package/dist/tools/helpers/output-contract.d.ts +24 -2
  25. package/dist/tools/helpers/output-contract.js +15 -2
  26. package/dist/tools/helpers/refresh-apply.js +1 -1
  27. package/dist/tools/helpers/refresh-inventory.d.ts +1 -1
  28. package/dist/tools/helpers/refresh-inventory.js +24 -3
  29. package/dist/tools/helpers/scan-cache.d.ts +45 -2
  30. package/dist/tools/helpers/scan-cache.js +47 -2
  31. package/dist/tools/helpers/scan-engine.d.ts +13 -0
  32. package/dist/tools/helpers/scan-engine.js +10 -0
  33. package/dist/tools/learn-patterns.js +6 -6
  34. package/dist/tools/list-imports.d.ts +1 -1
  35. package/dist/tools/refresh-state.js +1 -1
  36. package/dist/tools/scan-all.d.ts +7 -1
  37. package/dist/tools/scan-all.js +8 -13
  38. package/dist/tools/scan-angular.d.ts +7 -1
  39. package/dist/tools/scan-angular.js +7 -2
  40. package/dist/tools/scan-architecture.d.ts +8 -0
  41. package/dist/tools/scan-architecture.js +25 -14
  42. package/dist/tools/scan-solid.d.ts +7 -1
  43. package/dist/tools/scan-solid.js +7 -2
  44. package/dist/tools/server-status.d.ts +6 -24
  45. package/dist/tools/server-status.js +9 -57
  46. package/package.json +11 -11
@@ -18,7 +18,7 @@ export declare const DEFAULT_KEEP_NEWEST = 5;
18
18
  /** Store of the platform state an item belongs to. */
19
19
  export type RefreshStore = 'scan-cache' | 'legacy-cache' | 'health-snapshot' | 'pattern-knowledge' | 'backups' | 'snapshot-refs' | 'feedback' | 'ngm-cache';
20
20
  /** Why an item is listed. */
21
- export type RefreshReason = 'orphan' | 'expired' | 'unreadable' | 'legacy-layout' | 'legacy-store' | 'retention' | 'missing-metadata' | 'ref-without-backup' | 'duplicate-records' | 'outdated-records' | 'stale-date';
21
+ export type RefreshReason = 'orphan' | 'outdated-layout' | 'expired' | 'unreadable' | 'legacy-layout' | 'legacy-store' | 'retention' | 'missing-metadata' | 'ref-without-backup' | 'duplicate-records' | 'outdated-records' | 'stale-date';
22
22
  /** What a later apply would do with the item. */
23
23
  export type RefreshAction = 'remove' | 'mark' | 'regenerate';
24
24
  /** One stale, orphaned or duplicated piece of platform state. */
@@ -5,9 +5,10 @@
5
5
  */
6
6
  import { execFileSync } from 'node:child_process';
7
7
  import { closeSync, existsSync, lstatSync, openSync, readFileSync, readSync, readdirSync, realpathSync, } from 'node:fs';
8
- import { isAbsolute, join, relative, resolve, sep } from 'node:path';
8
+ import { basename, isAbsolute, join, relative, resolve, sep } from 'node:path';
9
9
  import { gunzipSync } from 'node:zlib';
10
10
  import { readSidecar, sameMarks, scanFeedbackSessions } from './feedback-sidecar.js';
11
+ import { SCAN_CACHE_LAYOUTS } from './scan-cache.js';
11
12
  /** Platform cache folder in the project root. */
12
13
  export const CACHE_DIR = '.angular-modernizer-cache';
13
14
  /** Transform backup folder in the project root. */
@@ -178,6 +179,8 @@ function scanCaches(ctx) {
178
179
  .filter((p) => stat(p)?.isDirectory() === true),
179
180
  ];
180
181
  for (const toolDir of toolDirs) {
182
+ // Scan cache folders have a layout version; kernel caches (the base folder) do not
183
+ const layout = toolDir === base ? undefined : SCAN_CACHE_LAYOUTS[basename(toolDir)];
181
184
  // Former layout <cacheDir>/YYYY/MM/DD/(ast|analysis)/ (replaced 2026-10, bfd5f91c): looked up by the current
182
185
  // date only, so nothing reads these folders any more
183
186
  for (const name of list(toolDir)) {
@@ -219,7 +222,7 @@ function scanCaches(ctx) {
219
222
  }
220
223
  entries++;
221
224
  bytes += s.size;
222
- const item = cacheEntryItem(ctx, path, s);
225
+ const item = cacheEntryItem(ctx, path, s, type === 'analysis' ? layout : undefined);
223
226
  ages.push(item.age);
224
227
  if (item.listed !== undefined) {
225
228
  cacheItems.push(item.listed);
@@ -256,7 +259,12 @@ function scanCaches(ctx) {
256
259
  legacy: { report: legacy, items: legacyItems },
257
260
  };
258
261
  }
259
- function cacheEntryItem(ctx, path, s) {
262
+ /**
263
+ * @param layout - Current layout version of the scan cache folder the entry
264
+ * is in; an entry of another layout is never read again (`outdated-layout`).
265
+ * Unset for kernel caches.
266
+ */
267
+ function cacheEntryItem(ctx, path, s, layout) {
260
268
  const metadata = readCacheMetadata(path);
261
269
  const cachedAt = typeof metadata?.cachedAt === 'number' ? metadata.cachedAt : s.mtimeMs;
262
270
  const age = ageDays(ctx, cachedAt);
@@ -291,6 +299,19 @@ function cacheEntryItem(ctx, path, s) {
291
299
  },
292
300
  };
293
301
  }
302
+ // The version is `<layout>+<hash>`; the hash part (config, rules, scope,
303
+ // unresolved packages) belongs to the scan call and is not checked here
304
+ const entryLayout = typeof metadata.version === 'string' ? metadata.version.split('+')[0] : undefined;
305
+ if (layout !== undefined && entryLayout !== layout) {
306
+ return {
307
+ age,
308
+ listed: {
309
+ ...base,
310
+ reason: 'outdated-layout',
311
+ detail: `${shown}; written with cache layout ${entryLayout ?? 'unknown'}, the scan reads ${layout}`,
312
+ },
313
+ };
314
+ }
294
315
  if (ctx.now - cachedAt > CACHE_MAX_AGE_MS) {
295
316
  return {
296
317
  age,
@@ -12,9 +12,42 @@ import { type CacheManager } from '@angular-modernizer/core';
12
12
  * layout were filed under each finding's file (the template's `.html` for
13
13
  * template rules, never read back) and missing for files without findings;
14
14
  * `scan-3` also drops entries whose cross-file findings saw only their batch,
15
- * `scan-4` entries that hold project rule findings of another file.
15
+ * `scan-4` entries that hold project rule findings of another file, `scan-5`
16
+ * entries written before the unresolved library packages were part of the
17
+ * version (a scan without node_modules would be served once it is complete)
18
+ * and entries filtered before a suppression marker in a comment block or
19
+ * inside a decorator counted.
16
20
  */
17
- export declare const SCAN_TOOL_CACHE_VERSION = "scan-4";
21
+ export declare const SCAN_TOOL_CACHE_VERSION = "scan-5";
22
+ /**
23
+ * Version of the cache entries scan-all writes. Entries from before the
24
+ * per-analyzed-file layout (findings filed under their template, files without
25
+ * findings missing) would read as complete; `scan-all-3` also drops entries
26
+ * whose cross-file findings saw only their own batch, `scan-all-4` entries
27
+ * that hold project rule findings of another file, `scan-all-5` entries whose
28
+ * solid:circular-dependency findings have no `cycleId` and carry the path of a
29
+ * long cycle on every file, `scan-all-6` entries written before the unresolved
30
+ * library packages were part of the version or filtered before a suppression
31
+ * marker in a comment block or inside a decorator counted.
32
+ */
33
+ export declare const SCAN_ALL_CACHE_VERSION = "scan-all-6";
34
+ /**
35
+ * Version of the cache entries of scan-architecture's imperative path: one
36
+ * entry per analyzed file with the findings of the file-scope rules. Entries
37
+ * of the earlier layout were filed under each finding's file and held
38
+ * project-wide findings; `scan-architecture-3` drops solid:circular-dependency
39
+ * findings without `cycleId` that carry the path of a long cycle on every
40
+ * file, `scan-architecture-4` entries written before the unresolved library
41
+ * packages were part of the version or filtered before a suppression marker
42
+ * in a comment block or inside a decorator counted.
43
+ */
44
+ export declare const ARCHITECTURE_CACHE_VERSION = "scan-architecture-4";
45
+ /**
46
+ * Current layout version per scan cache folder under
47
+ * `.angular-modernizer-cache/`; refresh-state lists entries of another
48
+ * layout (`outdated-layout`), which no scan reads any more.
49
+ */
50
+ export declare const SCAN_CACHE_LAYOUTS: Readonly<Record<string, string>>;
18
51
  /**
19
52
  * Cache version for a scan of `rootPath`: the layout version plus a hash of
20
53
  * the configuration the rules read. Rule options, `parser`, `layers` and the
@@ -29,6 +62,9 @@ export declare const SCAN_TOOL_CACHE_VERSION = "scan-4";
29
62
  * the default patterns keeps the version without a scope. Entries are kept
30
63
  * per file, so a scan with another version replaces the entries of the files
31
64
  * it analyzed, and the next scan with the first version analyzes them again.
65
+ * The packages whose imports do not resolve (`unresolvedPackages`) count too:
66
+ * entries written without a complete node_modules are not served once it is
67
+ * complete, and the other way round.
32
68
  *
33
69
  * @throws the loader's error for an invalid `.angular-modernizer.json`
34
70
  */
@@ -42,6 +78,13 @@ export interface ScanCacheScope {
42
78
  readonly includePatterns?: readonly string[];
43
79
  /** Exclude patterns of the scan, unset for the default. */
44
80
  readonly excludePatterns?: readonly string[];
81
+ /**
82
+ * Packages whose imports do not resolve in the scope (missing or
83
+ * incomplete node_modules); unset or empty when all resolve. Rules that
84
+ * need library types report differently without them, so entries of one
85
+ * state are not served in the other.
86
+ */
87
+ readonly unresolvedPackages?: readonly string[];
45
88
  }
46
89
  /**
47
90
  * How a scan uses its cache: `use` serves unchanged files from it, `refresh`
@@ -15,9 +15,47 @@ import { loadConfig } from '@angular-modernizer/core';
15
15
  * layout were filed under each finding's file (the template's `.html` for
16
16
  * template rules, never read back) and missing for files without findings;
17
17
  * `scan-3` also drops entries whose cross-file findings saw only their batch,
18
- * `scan-4` entries that hold project rule findings of another file.
18
+ * `scan-4` entries that hold project rule findings of another file, `scan-5`
19
+ * entries written before the unresolved library packages were part of the
20
+ * version (a scan without node_modules would be served once it is complete)
21
+ * and entries filtered before a suppression marker in a comment block or
22
+ * inside a decorator counted.
19
23
  */
20
- export const SCAN_TOOL_CACHE_VERSION = 'scan-4';
24
+ export const SCAN_TOOL_CACHE_VERSION = 'scan-5';
25
+ /**
26
+ * Version of the cache entries scan-all writes. Entries from before the
27
+ * per-analyzed-file layout (findings filed under their template, files without
28
+ * findings missing) would read as complete; `scan-all-3` also drops entries
29
+ * whose cross-file findings saw only their own batch, `scan-all-4` entries
30
+ * that hold project rule findings of another file, `scan-all-5` entries whose
31
+ * solid:circular-dependency findings have no `cycleId` and carry the path of a
32
+ * long cycle on every file, `scan-all-6` entries written before the unresolved
33
+ * library packages were part of the version or filtered before a suppression
34
+ * marker in a comment block or inside a decorator counted.
35
+ */
36
+ export const SCAN_ALL_CACHE_VERSION = 'scan-all-6';
37
+ /**
38
+ * Version of the cache entries of scan-architecture's imperative path: one
39
+ * entry per analyzed file with the findings of the file-scope rules. Entries
40
+ * of the earlier layout were filed under each finding's file and held
41
+ * project-wide findings; `scan-architecture-3` drops solid:circular-dependency
42
+ * findings without `cycleId` that carry the path of a long cycle on every
43
+ * file, `scan-architecture-4` entries written before the unresolved library
44
+ * packages were part of the version or filtered before a suppression marker
45
+ * in a comment block or inside a decorator counted.
46
+ */
47
+ export const ARCHITECTURE_CACHE_VERSION = 'scan-architecture-4';
48
+ /**
49
+ * Current layout version per scan cache folder under
50
+ * `.angular-modernizer-cache/`; refresh-state lists entries of another
51
+ * layout (`outdated-layout`), which no scan reads any more.
52
+ */
53
+ export const SCAN_CACHE_LAYOUTS = {
54
+ all: SCAN_ALL_CACHE_VERSION,
55
+ solid: SCAN_TOOL_CACHE_VERSION,
56
+ angular: SCAN_TOOL_CACHE_VERSION,
57
+ architecture: ARCHITECTURE_CACHE_VERSION,
58
+ };
21
59
  /**
22
60
  * Cache version for a scan of `rootPath`: the layout version plus a hash of
23
61
  * the configuration the rules read. Rule options, `parser`, `layers` and the
@@ -32,6 +70,9 @@ export const SCAN_TOOL_CACHE_VERSION = 'scan-4';
32
70
  * the default patterns keeps the version without a scope. Entries are kept
33
71
  * per file, so a scan with another version replaces the entries of the files
34
72
  * it analyzed, and the next scan with the first version analyzes them again.
73
+ * The packages whose imports do not resolve (`unresolvedPackages`) count too:
74
+ * entries written without a complete node_modules are not served once it is
75
+ * complete, and the other way round.
35
76
  *
36
77
  * @throws the loader's error for an invalid `.angular-modernizer.json`
37
78
  */
@@ -49,6 +90,10 @@ export function scanCacheVersion(layout, rootPath, ruleIds, scope = {}) {
49
90
  hash.update(`${name}:${stableJson([...new Set(patterns)].sort())}`);
50
91
  }
51
92
  }
93
+ // Empty when all resolve, so a complete node_modules keeps the version
94
+ if (scope.unresolvedPackages !== undefined && scope.unresolvedPackages.length > 0) {
95
+ hash.update(`unresolved:${[...new Set(scope.unresolvedPackages)].sort().join(',')}`);
96
+ }
52
97
  const layersSourcePath = layersSourceFile(ruleConfig['layersSource'], rootPath);
53
98
  if (layersSourcePath !== undefined) {
54
99
  hash.update(readOrEmpty(layersSourcePath));
@@ -12,6 +12,7 @@
12
12
  * worker killed in the middle leaves nothing half written.
13
13
  */
14
14
  import { type ConfigWarning, type UnreadableSourceFile } from '@angular-modernizer/core';
15
+ import { type UnresolvedLibraryImports } from './library-import-warning.js';
15
16
  import { type RuleRunResult, type RuleRunnerViolation } from './rule-runner.js';
16
17
  /** Plugins a scan runs. */
17
18
  export type ScanPluginSet = 'all' | 'solid' | 'angular' | 'architecture' | 'analyzer';
@@ -64,6 +65,12 @@ export interface ScanSpec {
64
65
  maxDurationMs?: number;
65
66
  /** `runner`: start of the budget (epoch ms). */
66
67
  startTime?: number;
68
+ /**
69
+ * Check the library imports of `files` and `contextFiles` for imports that
70
+ * do not resolve (missing or incomplete node_modules); the result carries
71
+ * {@link ScanEngineResult.unresolvedLibraryImports}.
72
+ */
73
+ libraryImports?: boolean;
67
74
  }
68
75
  /** A finding as the scans collect it. */
69
76
  export interface ScanFinding {
@@ -118,6 +125,12 @@ export interface ScanEngineResult {
118
125
  * plugins report into the caller's scope directly.
119
126
  */
120
127
  configWarnings?: ConfigWarning[];
128
+ /**
129
+ * Library imports of the scope that do not resolve, only with
130
+ * {@link ScanSpec.libraryImports}; checked before the rules run, so a
131
+ * cancelled in-thread run carries it too, a cancelled worker run not.
132
+ */
133
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
121
134
  }
122
135
  /** Cancellation of an in-thread run; a worker is terminated instead. */
123
136
  export interface ScanControl {
@@ -60,6 +60,16 @@ export async function runScanEngine(spec, sink, control = {}) {
60
60
  projectOptions: { skipAddingFilesFromTsConfig: spec.mode !== 'sequential' },
61
61
  });
62
62
  await kernel.initialize();
63
+ // Loaded on demand like the plugins: unit tests of the scan tools mock
64
+ // node:fs, under which ts-morph cannot load
65
+ const unresolvedLibraryImports = spec.libraryImports === true
66
+ ? (await import('./library-imports.js')).findUnresolvedLibraryImportsInFiles(kernel.getProject(), spec.tsConfigPath, new Set([...spec.files, ...(spec.contextFiles ?? [])]))
67
+ : undefined;
68
+ const result = await runRules(kernel, spec, sink, control);
69
+ return unresolvedLibraryImports === undefined ? result : { ...result, unresolvedLibraryImports };
70
+ }
71
+ /** Selects the rules of the scan and runs them in the mode of `spec`. */
72
+ async function runRules(kernel, spec, sink, control) {
63
73
  // The kernel's plugin instances carry the ruleConfigs of .angular-modernizer.json
64
74
  const allRules = kernel
65
75
  .getAllPlugins()
@@ -5,18 +5,18 @@ import { resolve, dirname, join } from 'node:path';
5
5
  import { countList } from './helpers/analysis-output.js';
6
6
  import { anonymizeCode, anonymizeFilePath, anonymizeMetadata, } from './helpers/pattern-anonymizer.js';
7
7
  import { COUNT_OBJECT } from './helpers/investigation-schemas.js';
8
- import { PatternKnowledgeBase, StyleConventionDetector, ContextAwareScorer, ContextAwareRuleGenerator, RealFileSystemAdapter, loadConfig, } from '@angular-modernizer/core';
8
+ import { PatternKnowledgeBase, learnedPatternId, StyleConventionDetector, ContextAwareScorer, ContextAwareRuleGenerator, RealFileSystemAdapter, loadConfig, } from '@angular-modernizer/core';
9
9
  /**
10
- * Stable id of a pattern: the same category and type give the same id in
11
- * every run, so the knowledge base recognises a pattern it stored before.
12
- * Patterns are grouped by category and type, so the id is unique per run.
10
+ * Stable id of a pattern ({@link learnedPatternId} of core, shared with the
11
+ * knowledge base's migration of pre-2.0 ids). Patterns are grouped by category
12
+ * and type, so the id is unique per run.
13
13
  */
14
14
  function patternId(category, type) {
15
- return `learned-${category}-${type}`;
15
+ return learnedPatternId(category, type);
16
16
  }
17
17
  /** Pattern type from an id built by {@link patternId}. */
18
18
  function patternTypeOf(pattern) {
19
- const prefix = `learned-${pattern.category}-`;
19
+ const prefix = learnedPatternId(pattern.category, '');
20
20
  return pattern.id.startsWith(prefix) ? pattern.id.slice(prefix.length) : pattern.id;
21
21
  }
22
22
  /** Own inputs above which a component is a too-many-inputs pattern, unless the config sets `maxInputs`. */
@@ -219,7 +219,7 @@ export declare class ListImportsTool implements MCPTool {
219
219
  type: string;
220
220
  };
221
221
  };
222
- required: ("total" | "external" | "unresolved" | "aliased" | "relative" | "reExports" | "typeOnly")[];
222
+ required: ("total" | "unresolved" | "external" | "aliased" | "relative" | "reExports" | "typeOnly")[];
223
223
  };
224
224
  summary: {
225
225
  type: string;
@@ -179,7 +179,7 @@ export class RefreshStateTool {
179
179
  items: { type: 'string', enum: [...REFRESH_PARTS] },
180
180
  minItems: 1,
181
181
  uniqueItems: true,
182
- description: "Parts to act on (mode 'apply' only). caches: scan cache entries listed as orphan, expired or unreadable, and the legacy cache folders; backups: backup groups listed by retention (exactly the files the report saw) and backup files without metadata; refs: snapshot refs listed by retention or without a backup group (deleted only while they still point at the commit of the report); feedback: session files listed with duplicate or outdated records, marked in .claude-feedback/index/consolidated.json while the file is unchanged (the session files stay as written)",
182
+ description: "Parts to act on (mode 'apply' only). caches: scan cache entries listed as orphan, outdated-layout, expired or unreadable, and the legacy cache folders; backups: backup groups listed by retention (exactly the files the report saw) and backup files without metadata; refs: snapshot refs listed by retention or without a backup group (deleted only while they still point at the commit of the report); feedback: session files listed with duplicate or outdated records, marked in .claude-feedback/index/consolidated.json while the file is unchanged (the session files stay as written)",
183
183
  },
184
184
  retentionDays: {
185
185
  type: 'integer',
@@ -2,6 +2,7 @@ import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
2
2
  import { type CancelledExecution } from './helpers/tool-context.js';
3
3
  import { type ScanCounts } from './helpers/analysis-output.js';
4
4
  import { type ScanCacheMode } from './helpers/scan-cache.js';
5
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
5
6
  /** Result of the scan-all tool. */
6
7
  export interface ScanAllResult {
7
8
  /** The requested page of violations (`maxResults`, `resultOffset`). */
@@ -93,8 +94,13 @@ export interface ScanAllResult {
93
94
  };
94
95
  };
95
96
  };
96
- /** Deprecation notices of the call (`orchestration` has no effect). */
97
+ /**
98
+ * Deprecation notices of the call (`orchestration` has no effect) and the
99
+ * warning about library imports that do not resolve.
100
+ */
97
101
  warnings?: string[];
102
+ /** Library imports of the scope that do not resolve; absent when all resolve. */
103
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
98
104
  /**
99
105
  * @deprecated No longer set: the block claimed a parallel run that never
100
106
  * happened. The scan always runs in the scan worker.
@@ -6,17 +6,8 @@ import { FindingWindow } from './helpers/finding-window.js';
6
6
  import { cancelledExecution, fileProgressMessage, finalFileProgress, } from './helpers/tool-context.js';
7
7
  import { runScan } from '../scan-host/scan-host.js';
8
8
  import { describeScan, DEPRECATED_SCAN_ORCHESTRATION_SCHEMA, SCAN_EXECUTION_SCHEMA, SCAN_ORCHESTRATION_NOTICE, scanOutputSchema, } from './helpers/analysis-output.js';
9
- import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, scanCacheVersion, } from './helpers/scan-cache.js';
10
- /**
11
- * Version of the cache entries scan-all writes. Entries from before the
12
- * per-analyzed-file layout (findings filed under their template, files without
13
- * findings missing) would read as complete; `scan-all-3` also drops entries
14
- * whose cross-file findings saw only their own batch, `scan-all-4` entries
15
- * that hold project rule findings of another file, `scan-all-5` entries whose
16
- * solid:circular-dependency findings have no `cycleId` and carry the path of a
17
- * long cycle on every file.
18
- */
19
- const SCAN_ALL_CACHE_VERSION = 'scan-all-5';
9
+ import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, scanCacheVersion, SCAN_ALL_CACHE_VERSION, } from './helpers/scan-cache.js';
10
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
20
11
  /**
21
12
  * MCP tool `scan-all`: one scan with the rules of all analysis plugins.
22
13
  *
@@ -162,11 +153,15 @@ export class ScanAllTool {
162
153
  // returned no hits and invalidated (deleted) their entries.
163
154
  // ============================================================================
164
155
  const fileSystem = new RealFileSystemAdapter();
156
+ // Library resolution state before the cache read: it is part of the
157
+ // cache version, so entries of another node_modules state are not served
158
+ const libraryCheck = await (await import('./helpers/library-imports.js')).checkScanScope(tsConfigPath, filesToAnalyze);
165
159
  const multiCacheManager = new MultiCacheFallbackManager(fileSystem, ['all'], {
166
160
  ...createMultiCacheConfig(mergedParams.rootPath),
167
161
  version: scanCacheVersion(SCAN_ALL_CACHE_VERSION, mergedParams.rootPath, ruleSelection, {
168
162
  includePatterns: mergedParams.includePatterns,
169
163
  excludePatterns: mergedParams.excludePatterns,
164
+ unresolvedPackages: libraryCheck.packages,
170
165
  }),
171
166
  });
172
167
  await multiCacheManager.initialize();
@@ -336,7 +331,7 @@ export class ScanAllTool {
336
331
  const allRuleIds = engine.ruleIds;
337
332
  // Get final cache statistics (Phase 3)
338
333
  const finalStats = multiCacheManager.getStats();
339
- return {
334
+ return withLibraryImportWarning({
340
335
  violations: paginatedViolations,
341
336
  counts,
342
337
  metadata: {
@@ -367,7 +362,7 @@ export class ScanAllTool {
367
362
  pagination,
368
363
  ...(execution === undefined ? {} : { execution }),
369
364
  summary: describeScan(counts, paginatedViolations, pagination, [...notices, ...(execution === undefined ? [] : [execution.note])]),
370
- };
365
+ }, libraryCheck.unresolved);
371
366
  }
372
367
  /**
373
368
  * Load scan-all tool configuration from .angular-modernizer.json file.
@@ -1,6 +1,7 @@
1
1
  import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
2
2
  import { type ScanCounts } from './helpers/analysis-output.js';
3
3
  import { type CancelledExecution } from './helpers/tool-context.js';
4
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
4
5
  /** Result of the scan-angular tool. */
5
6
  export interface ScanAngularResult {
6
7
  /** The requested page of violations (`maxResults`, `resultOffset`). */
@@ -41,8 +42,13 @@ export interface ScanAngularResult {
41
42
  /** Root path of the scanned project. */
42
43
  projectRoot: string;
43
44
  };
44
- /** Deprecation notices of the call (`orchestration` has no effect). */
45
+ /**
46
+ * Deprecation notices of the call (`orchestration` has no effect) and the
47
+ * warning about library imports that do not resolve.
48
+ */
45
49
  warnings?: string[];
50
+ /** Library imports of the scope that do not resolve; absent when all resolve. */
51
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
46
52
  /**
47
53
  * @deprecated No longer set: the block claimed a parallel run that never
48
54
  * happened. The scan always runs in the scan worker.
@@ -7,6 +7,7 @@ import { cancelledExecution, fileProgressMessage, finalFileProgress, } from './h
7
7
  import { runScan } from '../scan-host/scan-host.js';
8
8
  import { openToolCache } from './helpers/tool-cache.js';
9
9
  import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, SCAN_TOOL_CACHE_VERSION, scanCacheVersion, } from './helpers/scan-cache.js';
10
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
10
11
  /**
11
12
  * MCP tool `scan-angular`: scans for Angular-specific best practice
12
13
  * violations. Runs only the rules of the AngularPlugin (OnPush, TrackBy,
@@ -134,9 +135,13 @@ export class ScanAngularTool {
134
135
  const uniqueFiles = Array.from(new Set(allFiles)).sort();
135
136
  const filesToAnalyze = uniqueFiles; // Analyze ALL files found (batch processing prevents memory issues)
136
137
  const maxFiles = mergedParams.maxFiles ?? 100; // Batch size (default 100)
138
+ // Library resolution state before the cache read: it is part of the
139
+ // cache version, so entries of another node_modules state are not served
140
+ const libraryCheck = await (await import('./helpers/library-imports.js')).checkScanScope(tsConfigPath, filesToAnalyze);
137
141
  const cache = await openToolCache(mergedParams.rootPath, 'angular', scanCacheVersion(SCAN_TOOL_CACHE_VERSION, mergedParams.rootPath, ruleSelection, {
138
142
  includePatterns: mergedParams.includePatterns,
139
143
  excludePatterns: mergedParams.excludePatterns,
144
+ unresolvedPackages: libraryCheck.packages,
140
145
  }));
141
146
  // ============================================================================
142
147
  // CACHE READ SYSTEM
@@ -292,7 +297,7 @@ export class ScanAngularTool {
292
297
  };
293
298
  const duration = Date.now() - startTime;
294
299
  const ruleIds = engine.ruleIds;
295
- return {
300
+ return withLibraryImportWarning({
296
301
  violations: paginatedViolations,
297
302
  counts,
298
303
  metadata: {
@@ -304,7 +309,7 @@ export class ScanAngularTool {
304
309
  pagination,
305
310
  ...(execution === undefined ? {} : { execution }),
306
311
  summary: describeScan(counts, paginatedViolations, pagination, [...notices, ...(execution === undefined ? [] : [execution.note])]),
307
- };
312
+ }, libraryCheck.unresolved);
308
313
  }
309
314
  /**
310
315
  * The `tools['scan-angular']` section of `.angular-modernizer.json`; arguments of
@@ -1,4 +1,5 @@
1
1
  import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
2
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
2
3
  import { type ScanCounts } from './helpers/analysis-output.js';
3
4
  import { type RuleTiming } from './helpers/rule-runner.js';
4
5
  /**
@@ -70,6 +71,13 @@ export interface ScanArchitectureResult {
70
71
  * Operation ID for streaming mode (when streaming=true).
71
72
  */
72
73
  operationId?: string;
74
+ /** The warning about library imports that do not resolve. */
75
+ warnings?: string[];
76
+ /**
77
+ * Library imports of the scope that do not resolve (sequential and fluent
78
+ * path); absent when all resolve.
79
+ */
80
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
73
81
  /**
74
82
  * All violations found.
75
83
  */
@@ -2,7 +2,8 @@ import { findTsConfig } from './helpers/find-ts-config.js';
2
2
  import { cancelledExecution, fileProgressMessage, finalFileProgress, yieldIfCancellable, } from './helpers/tool-context.js';
3
3
  import { runScan } from '../scan-host/scan-host.js';
4
4
  import { openToolCache } from './helpers/tool-cache.js';
5
- import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, scanCacheVersion, templateDependencies, } from './helpers/scan-cache.js';
5
+ import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, scanCacheVersion, ARCHITECTURE_CACHE_VERSION, templateDependencies, } from './helpers/scan-cache.js';
6
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
6
7
  import { loadSourceFiles } from './helpers/load-source-files.js';
7
8
  import { filterFilesByScopePaths } from './helpers/scope-paths.js';
8
9
  import { toParallelOptions } from '../types.js';
@@ -42,10 +43,10 @@ function paginateViolations(violations, params) {
42
43
  */
43
44
  function withScanSummary(result) {
44
45
  const notes = result.execution?.note === undefined ? [] : [result.execution.note];
45
- return {
46
+ return withLibraryImportWarning({
46
47
  ...result,
47
48
  summary: describeScan(result.counts, result.violations, result.pagination, notes),
48
- };
49
+ }, result.unresolvedLibraryImports);
49
50
  }
50
51
  /**
51
52
  * MCP tool `scan-architecture`: scans for architectural issues. Runs only the
@@ -364,6 +365,7 @@ export class ScanArchitectureTool {
364
365
  // own analysis workers); the sequential path runs in a scan worker.
365
366
  let parallelKernel;
366
367
  let rulesExecuted = [];
368
+ let unresolvedLibraryImports;
367
369
  let lastProgress;
368
370
  if (orchestration.parallel || orchestration.incremental) {
369
371
  // Initialize kernel with ArchitecturePlugin only + caching
@@ -592,7 +594,14 @@ export class ScanArchitectureTool {
592
594
  // once more at another file (70 -> 74 -> 78 findings on a large app).
593
595
  // The cache version carries the rule configuration (scanCacheVersion).
594
596
  // ============================================================================
595
- const cache = await openToolCache(mergedParams.rootPath, 'architecture', scanCacheVersion(ARCHITECTURE_CACHE_VERSION, mergedParams.rootPath));
597
+ // Library resolution state before the cache read: it is part of the
598
+ // cache version, so entries of another node_modules state are not served
599
+ const libraryCheck = await (await import('./helpers/library-imports.js')).checkScanScope(tsConfigPath, filesToAnalyze);
600
+ unresolvedLibraryImports =
601
+ libraryCheck.unresolved.imports > 0 ? libraryCheck.unresolved : undefined;
602
+ const cache = await openToolCache(mergedParams.rootPath, 'architecture', scanCacheVersion(ARCHITECTURE_CACHE_VERSION, mergedParams.rootPath, undefined, {
603
+ unresolvedPackages: libraryCheck.packages,
604
+ }));
596
605
  // A run limited by rules holds only those rules' findings per file:
597
606
  // it neither reads the cache nor writes entries a full run would
598
607
  // take for complete
@@ -702,6 +711,7 @@ export class ScanArchitectureTool {
702
711
  ...summary,
703
712
  analyzedFiles: filesAnalyzed,
704
713
  },
714
+ ...(unresolvedLibraryImports === undefined ? {} : { unresolvedLibraryImports }),
705
715
  metadata: {
706
716
  rulesExecuted,
707
717
  duration,
@@ -752,7 +762,14 @@ export class ScanArchitectureTool {
752
762
  ruleTimings: [],
753
763
  durationMs: Date.now() - (spec.startTime ?? Date.now()),
754
764
  };
755
- return { run, ruleIds: engine.ruleIds };
765
+ return {
766
+ run,
767
+ ruleIds: engine.ruleIds,
768
+ // Only when some do not resolve, like the other scans
769
+ ...((engine.unresolvedLibraryImports?.imports ?? 0) > 0
770
+ ? { unresolvedLibraryImports: engine.unresolvedLibraryImports }
771
+ : {}),
772
+ };
756
773
  }
757
774
  /**
758
775
  * Execute analysis using fluent API.
@@ -806,13 +823,14 @@ export class ScanArchitectureTool {
806
823
  // rules such as layer-boundary-violation returned 0 violations, Bug 1/3),
807
824
  // in a scan worker when enabled.
808
825
  const violations = [];
809
- const { run, ruleIds } = await this.runRules({
826
+ const { run, ruleIds, unresolvedLibraryImports } = await this.runRules({
810
827
  tool: this.name,
811
828
  plugins: 'architecture',
812
829
  tsConfigPath,
813
830
  rootPath: params.rootPath,
814
831
  files: filesToAnalyze,
815
832
  mode: 'runner',
833
+ libraryImports: true,
816
834
  ...(params.rules === undefined ? {} : { ruleIds: params.rules }),
817
835
  maxDurationMs: parseMaxDurationMs(params.maxDurationMs),
818
836
  startTime,
@@ -828,6 +846,7 @@ export class ScanArchitectureTool {
828
846
  ...summary,
829
847
  analyzedFiles: filesAnalyzed,
830
848
  },
849
+ ...(unresolvedLibraryImports === undefined ? {} : { unresolvedLibraryImports }),
831
850
  metadata: {
832
851
  rulesExecuted: ruleIds,
833
852
  duration,
@@ -1358,14 +1377,6 @@ function withFileCap(execution, scopeFiles, selectedFiles, maxFiles) {
1358
1377
  function relativeToRoot(violations, rootPath) {
1359
1378
  return violations.map((v) => ({ ...v, filePath: relative(rootPath, v.filePath) }));
1360
1379
  }
1361
- /**
1362
- * Version of the imperative path's cache entries: one entry per analyzed file
1363
- * with the findings of the file-scope rules. Entries of the earlier layout
1364
- * were filed under each finding's file and held project-wide findings;
1365
- * `scan-architecture-3` drops solid:circular-dependency findings without
1366
- * `cycleId` that carry the path of a long cycle on every file.
1367
- */
1368
- const ARCHITECTURE_CACHE_VERSION = 'scan-architecture-3';
1369
1380
  /** Files a cache entry depends on besides the analyzed file itself. */
1370
1381
  function cacheDependencies(filePath, findings) {
1371
1382
  let text = '';
@@ -1,6 +1,7 @@
1
1
  import type { MCPTool, ToolAnnotations, ToolContext } from '../types.js';
2
2
  import { type ScanCounts } from './helpers/analysis-output.js';
3
3
  import { type CancelledExecution } from './helpers/tool-context.js';
4
+ import { type UnresolvedLibraryImports } from './helpers/library-import-warning.js';
4
5
  /** Result of the scan-solid tool. */
5
6
  export interface ScanSolidResult {
6
7
  /** The requested page of violations (`maxResults`, `resultOffset`). */
@@ -41,8 +42,13 @@ export interface ScanSolidResult {
41
42
  /** Root path of the scanned project. */
42
43
  projectRoot: string;
43
44
  };
44
- /** Deprecation notices of the call (`orchestration` has no effect). */
45
+ /**
46
+ * Deprecation notices of the call (`orchestration` has no effect) and the
47
+ * warning about library imports that do not resolve.
48
+ */
45
49
  warnings?: string[];
50
+ /** Library imports of the scope that do not resolve; absent when all resolve. */
51
+ unresolvedLibraryImports?: UnresolvedLibraryImports;
46
52
  /**
47
53
  * @deprecated No longer set: the block claimed a parallel run that never
48
54
  * happened. The scan always runs in the scan worker.
@@ -7,6 +7,7 @@ import { cancelledExecution, fileProgressMessage, finalFileProgress, } from './h
7
7
  import { runScan } from '../scan-host/scan-host.js';
8
8
  import { openToolCache } from './helpers/tool-cache.js';
9
9
  import { findingsInFileOrder, readCachedFindings, SCAN_CACHE_MODE_SCHEMA, scanCacheMode, SCAN_TOOL_CACHE_VERSION, scanCacheVersion, } from './helpers/scan-cache.js';
10
+ import { withLibraryImportWarning, } from './helpers/library-import-warning.js';
10
11
  /**
11
12
  * MCP tool `scan-solid`: scans for SOLID principle violations. Runs only the
12
13
  * rules of the SolidPlugin (DIP, SRP, LSP, OCP, ISP).
@@ -133,9 +134,13 @@ export class ScanSolidTool {
133
134
  const uniqueFiles = Array.from(new Set(allFiles)).sort();
134
135
  const filesToAnalyze = uniqueFiles; // Analyze ALL files found (batch processing prevents memory issues)
135
136
  const maxFiles = mergedParams.maxFiles ?? 100; // Batch size (default 100)
137
+ // Library resolution state before the cache read: it is part of the
138
+ // cache version, so entries of another node_modules state are not served
139
+ const libraryCheck = await (await import('./helpers/library-imports.js')).checkScanScope(tsConfigPath, filesToAnalyze);
136
140
  const cache = await openToolCache(mergedParams.rootPath, 'solid', scanCacheVersion(SCAN_TOOL_CACHE_VERSION, mergedParams.rootPath, ruleSelection, {
137
141
  includePatterns: mergedParams.includePatterns,
138
142
  excludePatterns: mergedParams.excludePatterns,
143
+ unresolvedPackages: libraryCheck.packages,
139
144
  }));
140
145
  // ============================================================================
141
146
  // CACHE READ SYSTEM
@@ -322,7 +327,7 @@ export class ScanSolidTool {
322
327
  };
323
328
  const duration = Date.now() - startTime;
324
329
  const ruleIds = engine.ruleIds;
325
- return {
330
+ return withLibraryImportWarning({
326
331
  violations: paginatedViolations,
327
332
  counts,
328
333
  metadata: {
@@ -334,7 +339,7 @@ export class ScanSolidTool {
334
339
  pagination,
335
340
  ...(execution === undefined ? {} : { execution }),
336
341
  summary: describeScan(counts, paginatedViolations, pagination, [...notices, ...(execution === undefined ? [] : [execution.note])]),
337
- };
342
+ }, libraryCheck.unresolved);
338
343
  }
339
344
  /**
340
345
  * The `tools['scan-solid']` section of `.angular-modernizer.json`; arguments of