code-guardian-ai 0.0.0-stage → 0.3.0

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 (70) hide show
  1. package/.env.example +24 -0
  2. package/LICENSE +21 -0
  3. package/README.md +774 -2
  4. package/bin/cli.js +2 -0
  5. package/dist/build-manifest.json +136 -0
  6. package/dist/cli/commands/check.js +56 -0
  7. package/dist/cli/commands/doctor.js +55 -0
  8. package/dist/cli/commands/find.js +31 -0
  9. package/dist/cli/commands/init-files.js +13 -0
  10. package/dist/cli/commands/init.js +50 -0
  11. package/dist/cli/commands/optimize.js +53 -0
  12. package/dist/cli/commands/scan.js +47 -0
  13. package/dist/cli/index.js +62 -0
  14. package/dist/cli/output.js +4 -0
  15. package/dist/context.js +11 -0
  16. package/dist/core/ast/analysis.js +455 -0
  17. package/dist/core/ast/cached-info.js +46 -0
  18. package/dist/core/ast/discovery.js +485 -0
  19. package/dist/core/ast/extract-js.js +531 -0
  20. package/dist/core/ast/extract-py.js +298 -0
  21. package/dist/core/ast/graph.js +92 -0
  22. package/dist/core/ast/health.js +338 -0
  23. package/dist/core/ast/indexer.js +286 -0
  24. package/dist/core/ast/packages.js +343 -0
  25. package/dist/core/ast/parser.js +91 -0
  26. package/dist/core/ast/report.js +154 -0
  27. package/dist/core/ast/resolver.js +392 -0
  28. package/dist/core/ast/rules.js +37 -0
  29. package/dist/core/ast/scope-js.js +191 -0
  30. package/dist/core/ast/shared-index.js +131 -0
  31. package/dist/core/ast/tsconfig.js +301 -0
  32. package/dist/core/ast/types.js +1 -0
  33. package/dist/core/ast/util.js +156 -0
  34. package/dist/core/git/git.js +430 -0
  35. package/dist/core/llm/policy.js +35 -0
  36. package/dist/core/llm/provider.js +199 -0
  37. package/dist/core/prompt/compressor.js +118 -0
  38. package/dist/core/prompt/criteria.js +36 -0
  39. package/dist/core/prompt/find.js +47 -0
  40. package/dist/core/prompt/guidelines.js +22 -0
  41. package/dist/core/prompt/model-output.js +178 -0
  42. package/dist/core/prompt/refiner.js +194 -0
  43. package/dist/core/prompt/relevance.js +265 -0
  44. package/dist/core/prompt/untrusted.js +57 -0
  45. package/dist/core/security/masker.js +330 -0
  46. package/dist/core/security/outbound.js +40 -0
  47. package/dist/core/security/safe-file.js +396 -0
  48. package/dist/core/security/sandbox.js +181 -0
  49. package/dist/core/validation/baseline.js +121 -0
  50. package/dist/core/validation/delta.js +243 -0
  51. package/dist/core/validation/policy.js +123 -0
  52. package/dist/db/cache-key.js +221 -0
  53. package/dist/db/client.js +563 -0
  54. package/dist/db/schema-check.js +149 -0
  55. package/dist/db/schema.js +36 -0
  56. package/dist/db/windows-acl.js +150 -0
  57. package/dist/index.js +55 -0
  58. package/dist/mcp/server.js +20 -0
  59. package/dist/mcp/tools/find-reusable.js +22 -0
  60. package/dist/mcp/tools/get-context.js +39 -0
  61. package/dist/mcp/tools/optimize-prompt.js +31 -0
  62. package/dist/mcp/tools/result.js +31 -0
  63. package/dist/mcp/tools/validate-rules.js +28 -0
  64. package/dist/utils/config.js +117 -0
  65. package/dist/utils/errors.js +9 -0
  66. package/dist/utils/logger.js +19 -0
  67. package/dist/utils/pace.js +19 -0
  68. package/dist/utils/text.js +22 -0
  69. package/dist/utils/tokens.js +14 -0
  70. package/package.json +69 -4
@@ -0,0 +1,455 @@
1
+ import path from 'node:path';
2
+ import ignore from 'ignore';
3
+ import { compareText } from '../../utils/text.js';
4
+ import { findCycles } from './graph.js';
5
+ import { describeHealth } from './health.js';
6
+ import { createResolver } from './resolver.js';
7
+ import { PROFILE_ENTRIES, REMEDIATION } from './rules.js';
8
+ const TEST_FILE = /(^|\/)(__tests__|tests?|e2e)\/|\.(?:test|spec|stories)\.[cm]?[jt]sx?$|(^|\/)test_[^/]*\.py$|_test\.py$|(^|\/)conftest\.py$/;
9
+ const ENTRY_FILE = /(^|\/)(?:index|main|cli|app|server|manage|setup|wsgi|asgi|__init__|__main__)\.[a-z]+$|\.config\.[cm]?[jt]s$|(^|\/)(?:bin|scripts|migrations)\//;
10
+ const FRAMEWORK_FILE = /(^|\/)(?:page|layout|route|loading|error|not-found|template|middleware|instrumentation|_app|_document)\.[cm]?[jt]sx?$/;
11
+ const GENERIC_NAMES = new Set([
12
+ 'default', 'main', 'handler', 'init', 'setup', 'run', 'index', 'app', 'config', 'loader', 'action', 'meta',
13
+ 'links', 'middleware', 'GET', 'POST', 'PUT', 'PATCH', 'DELETE', 'HEAD', 'OPTIONS',
14
+ ]);
15
+ export const isTest = (p) => TEST_FILE.test(p);
16
+ // Files written by a generator: reporting style problems in them is noise the developer cannot act on.
17
+ const GENERATED_FILE = /\.(?:gen|generated)\.[cm]?[jt]sx?$|(^|\/)__generated__\//;
18
+ const conventionalEntry = (p) => ENTRY_FILE.test(p) || FRAMEWORK_FILE.test(p);
19
+ // Directories whose contents frameworks and plugin systems load by convention rather than by import.
20
+ const RUNTIME_DIR = /(^|\/)(?:plugins?|adapters?|handlers?|commands?|jobs?|workers?|listeners?|subscribers?|providers?|migrations?|seeds?|strategies|drivers?|loaders?|extensions?|middlewares?|controllers?|resolvers?|modules?)\//i;
21
+ function suppressionSeverity(kind) {
22
+ if (kind === '@ts-nocheck')
23
+ return 'high';
24
+ return kind === 'any' ? 'low' : 'medium';
25
+ }
26
+ const push = (map, key, value) => {
27
+ const list = map.get(key);
28
+ if (list)
29
+ list.push(value);
30
+ else
31
+ map.set(key, [value]);
32
+ };
33
+ export function analyze(files, options = {}) {
34
+ // A file Tree-sitter had to repair may have lost imports or declarations, so "nothing imports this" cannot be proven
35
+ // while one exists, and a use of a name inside its damaged region may be missed.
36
+ const damaged = new Set(files.filter((f) => f.parse).map((f) => f.path));
37
+ const degraded = files.filter((f) => f.parse?.status === 'degraded');
38
+ const complete = (options.complete ?? true) && damaged.size === 0;
39
+ const id = options.identify ?? ((p) => p);
40
+ const resolve = createResolver({
41
+ files: files.map((f) => f.path),
42
+ known: options.known,
43
+ tsconfigs: options.tsconfigs ?? [],
44
+ packages: options.packages ?? [],
45
+ pythonRoots: options.pythonRoots ?? ['', 'src'],
46
+ });
47
+ const settings = options.config ?? {};
48
+ const frameworks = new Set((options.packages ?? []).flatMap((p) => p.frameworks));
49
+ const profile = settings.profile ?? 'auto';
50
+ const profilePatterns = profile === 'none' ? [] : profile === 'auto' ? [...frameworks].flatMap((f) => PROFILE_ENTRIES[f] ?? []) : PROFILE_ENTRIES[profile];
51
+ const entryMatcher = ignore().add([...profilePatterns, ...(settings.entryPoints ?? [])]);
52
+ const publicEntries = new Set(resolve.publicEntries());
53
+ const isEntry = (p) => (profile !== 'none' && conventionalEntry(p)) || entryMatcher.ignores(p) || publicEntries.has(p);
54
+ const profileLabel = profile === 'auto' ? (frameworks.size > 0 ? `auto: ${[...frameworks].join(', ')}` : 'auto') : profile;
55
+ const edges = new Map();
56
+ const importedBy = new Map();
57
+ const used = new Map();
58
+ const forwards = new Map();
59
+ const unresolved = [];
60
+ const seenUnresolved = new Set();
61
+ const addUse = (file, name) => {
62
+ const names = used.get(file) ?? new Set();
63
+ names.add(name);
64
+ used.set(file, names);
65
+ };
66
+ // A name used through a barrel is a use of the module that really defines it. Iterative: a chain of re-exports can be as long as
67
+ // the project has files, and `seen` bounds the work to one visit per (file, name) pair.
68
+ const markUsed = (file, name, seen) => {
69
+ const pending = [{ file, name }];
70
+ for (let item = pending.pop(); item; item = pending.pop()) {
71
+ const key = `${item.file}\0${item.name}`;
72
+ if (seen.has(key))
73
+ continue;
74
+ seen.add(key);
75
+ addUse(item.file, item.name);
76
+ for (const forward of forwards.get(item.file) ?? []) {
77
+ if (item.name === '*')
78
+ pending.push({ file: forward.target, name: forward.imported });
79
+ else if (forward.exported === item.name)
80
+ pending.push({ file: forward.target, name: forward.imported });
81
+ else if (forward.exported === '*' && item.name !== 'default')
82
+ pending.push({ file: forward.target, name: item.name });
83
+ }
84
+ }
85
+ };
86
+ const consumed = [];
87
+ const selfImports = new Set();
88
+ for (const file of files) {
89
+ for (const imp of file.imports) {
90
+ const resolution = resolve(file, imp);
91
+ if (resolution.unresolved) {
92
+ const key = `${file.path}\0${imp.source}`;
93
+ if (!seenUnresolved.has(key)) {
94
+ seenUnresolved.add(key);
95
+ unresolved.push({ ...resolution.unresolved, file: file.path, line: imp.line });
96
+ }
97
+ }
98
+ for (const hit of resolution.targets) {
99
+ const runtime = imp.kind !== 'dynamic' && !imp.typeOnly;
100
+ if (hit.file === file.path) {
101
+ // A self-import is never a use by another file, but it is a one-file cycle when it runs at load time.
102
+ // `from . import x` inside a package's __init__.py loads submodules, it does not import the file itself.
103
+ const bareRelativePython = file.lang === 'python' && /^\.*$/.test(imp.source);
104
+ if (runtime && !bareRelativePython)
105
+ selfImports.add(file.path);
106
+ continue;
107
+ }
108
+ const edgeKey = `${file.path}\0${hit.file}`;
109
+ const edge = edges.get(edgeKey);
110
+ if (edge)
111
+ edge.runtime = edge.runtime || runtime;
112
+ else
113
+ edges.set(edgeKey, { runtime });
114
+ const importers = importedBy.get(hit.file) ?? new Set();
115
+ importers.add(file.path);
116
+ importedBy.set(hit.file, importers);
117
+ if (imp.kind !== 'reexport')
118
+ for (const name of hit.names)
119
+ consumed.push({ file: hit.file, name });
120
+ // `const User = require('./user'); User.all()` records the members read (all), but what was required is the value the
121
+ // module assigned to module.exports: its default export. Using any member of it uses the export itself.
122
+ if (imp.kind === 'require' && file.lang !== 'python' && hit.names.length > 0 && !hit.names.includes('default'))
123
+ consumed.push({ file: hit.file, name: 'default' });
124
+ }
125
+ }
126
+ for (const reexport of file.reexports) {
127
+ const resolution = resolve(file, { source: reexport.source, names: [reexport.imported], line: 0, kind: 'reexport', typeOnly: false });
128
+ for (const hit of resolution.targets) {
129
+ if (hit.file !== file.path)
130
+ push(forwards, file.path, { target: hit.file, imported: reexport.imported, exported: reexport.exported });
131
+ }
132
+ }
133
+ }
134
+ for (const { file, name } of consumed)
135
+ markUsed(file, name, new Set());
136
+ // A real entry point (nothing imports it) exposes everything it re-exports. An imported barrel is tracked name by name.
137
+ for (const file of files)
138
+ if (isEntry(file.path) && !importedBy.has(file.path))
139
+ markUsed(file.path, '*', new Set());
140
+ const links = [...edges]
141
+ .map(([key, edge]) => {
142
+ const [source, target] = key.split('\0');
143
+ return { source, target, runtime: edge.runtime };
144
+ })
145
+ .sort((a, b) => compareText(a.source, b.source) || compareText(a.target, b.target));
146
+ const runtimeAdjacency = new Map();
147
+ for (const link of links)
148
+ if (link.runtime)
149
+ push(runtimeAdjacency, link.source, link.target);
150
+ for (const file of selfImports)
151
+ push(runtimeAdjacency, file, file);
152
+ const cycles = findCycles(files.map((f) => f.path), runtimeAdjacency);
153
+ const inCycle = new Set(cycles.flatMap((c) => c.modules));
154
+ const orphans = new Set(files.filter((f) => !importedBy.has(f.path) && !isTest(f.path) && !isEntry(f.path)).map((f) => f.path));
155
+ const graph = {
156
+ nodes: files.map((f) => ({
157
+ id: f.path,
158
+ lang: f.lang,
159
+ lines: f.lines,
160
+ exports: f.symbols.filter((s) => s.exportName).length,
161
+ importedBy: importedBy.get(f.path)?.size ?? 0,
162
+ orphan: orphans.has(f.path),
163
+ inCycle: inCycle.has(f.path),
164
+ })),
165
+ links,
166
+ };
167
+ const findings = [];
168
+ const add = (draft) => {
169
+ findings.push({ count: 1, remediation: REMEDIATION[draft.rule], ...draft });
170
+ };
171
+ // ---- is this file reachable some way other than an import?
172
+ const loaders = files.filter((f) => f.dynamicLoads.length > 0);
173
+ const reachedByDynamicLoad = (file) => {
174
+ for (const loader of loaders) {
175
+ const dir = path.posix.dirname(loader.path) === '.' ? '' : path.posix.dirname(loader.path);
176
+ for (const load of loader.dynamicLoads) {
177
+ if (load.prefix) {
178
+ if (!load.prefix.startsWith('.'))
179
+ continue;
180
+ const base = path.posix.normalize(path.posix.join(dir || '.', load.prefix));
181
+ if (file.startsWith(base))
182
+ return `${loader.path}:${load.line} loads modules from ${load.prefix} at run time`;
183
+ }
184
+ else if (dir ? file.startsWith(`${dir}/`) : !file.includes('/')) {
185
+ return `${loader.path}:${load.line} loads a computed ${load.kind} path, which could reach this file`;
186
+ }
187
+ }
188
+ }
189
+ return undefined;
190
+ };
191
+ const unsupportedAliases = unresolved
192
+ .filter((u) => u.reason === 'unsupported')
193
+ .map((u) => ({ spec: u.spec, tail: u.spec.replace(/^[@~$#]+\/?/, '').replace(/\.[cm]?[jt]sx?$/, '').replace(/\/index$/, '') }))
194
+ .filter((u) => u.tail.length > 0);
195
+ const viaUnsupportedAlias = (file) => {
196
+ const stem = file.replace(/\.[^.]+$/, '').replace(/\/index$/, '');
197
+ return unsupportedAliases.find((u) => stem === u.tail || stem.endsWith(`/${u.tail}`))?.spec;
198
+ };
199
+ const foreign = options.foreignExtensions ?? [];
200
+ const signalsFor = (f, forFile) => {
201
+ const signals = [];
202
+ const dynamic = reachedByDynamicLoad(f.path);
203
+ if (dynamic)
204
+ signals.push(dynamic);
205
+ const alias = viaUnsupportedAlias(f.path);
206
+ if (alias)
207
+ signals.push(`'${alias}' is imported through an alias this tool cannot resolve`);
208
+ if (foreign.length > 0)
209
+ signals.push(`the workspace has ${foreign.join(', ')} files, which are not analysed and may import it`);
210
+ if (RUNTIME_DIR.test(f.path))
211
+ signals.push('is in a directory that frameworks and plugin systems load by convention');
212
+ if (f.decorated)
213
+ signals.push('declares a decorated class, which frameworks often register without an import');
214
+ if (forFile && f.script)
215
+ signals.push('runs code when loaded, so it may be launched directly');
216
+ else if (forFile && !f.symbols.some((s) => s.exportName))
217
+ signals.push('exports nothing, so it may exist only for its side effects');
218
+ return signals;
219
+ };
220
+ const classify = (signals) => (!complete ? 'unreferenced' : signals.length > 0 ? 'potentially-unused' : 'confidently-unused');
221
+ const orphanConfidence = { 'confidently-unused': 'high', 'potentially-unused': 'medium', unreferenced: 'low' };
222
+ const exportConfidence = { 'confidently-unused': 'medium', 'potentially-unused': 'low', unreferenced: 'low' };
223
+ // Which files are damaged and how, in path order, so the reason for a lowered confidence is in the evidence and not only the
224
+ // fact that it was lowered. At most three are spelled out; the rest are counted.
225
+ const damagedFiles = files.filter((f) => f.parse).sort((a, b) => compareText(a.path, b.path));
226
+ const listed = new Set(damagedFiles.slice(0, 3).map((f) => f.path));
227
+ const syntaxNotes = [...damagedFiles.slice(0, 3).map((f) => `${f.path}: ${describeHealth(f.parse)}`), ...(damagedFiles.length > 3 ? [`and ${damagedFiles.length - 3} more file(s) with syntax errors`] : [])];
228
+ const caveat = [
229
+ ...(damaged.size > 0
230
+ ? [
231
+ `${damaged.size} file(s) have syntax errors or were not analysed${degraded.length > 0 ? ` (${degraded.length} at the top level or inside an import/export)` : ''}, so an importer may have been missed and a missing importer proves nothing`,
232
+ ]
233
+ : []),
234
+ ...(options.complete === false
235
+ ? ['the scan did not see every file, so a missing importer cannot be ruled out']
236
+ : []),
237
+ ...syntaxNotes,
238
+ ];
239
+ const byPath = new Map(files.map((f) => [f.path, f]));
240
+ for (const file of [...orphans].sort(compareText)) {
241
+ const info = byPath.get(file);
242
+ const signals = signalsFor(info, true);
243
+ const classification = classify(signals);
244
+ add({
245
+ rule: 'orphan-file',
246
+ severity: classification === 'confidently-unused' ? 'medium' : 'low',
247
+ file,
248
+ message: `${classification === 'confidently-unused' ? 'Confidently unused' : classification === 'potentially-unused' ? 'Potentially unused' : 'Unreferenced'}: no file imports this module`,
249
+ key: `orphan-file|${id(file)}`,
250
+ confidence: orphanConfidence[classification],
251
+ method: 'import-graph',
252
+ classification,
253
+ evidence: [`no import of it among ${files.length} indexed files`, `not an entry point (profile: ${profileLabel})`, ...caveat, ...signals],
254
+ remediation: classification === 'confidently-unused' ? REMEDIATION['orphan-file'] : `Check whether it is loaded some other way. ${REMEDIATION['orphan-file']}`,
255
+ });
256
+ }
257
+ for (const f of files) {
258
+ const names = used.get(f.path);
259
+ if (orphans.has(f.path) || isTest(f.path) || isEntry(f.path) || names?.has('*'))
260
+ continue;
261
+ const signals = signalsFor(f, false);
262
+ // Any public name of an importable Python package module can be reached as package.module.name without being imported by
263
+ // name (requests.cookies.CookieConflictError, click.testing.Result), which an import graph cannot see.
264
+ if (f.lang === 'python' && byPath.has(`${f.path.includes('/') ? f.path.slice(0, f.path.lastIndexOf('/') + 1) : ''}__init__.py`)) {
265
+ signals.push('is a module of an importable Python package: callers can use the name as package.module.name without importing it by name');
266
+ }
267
+ const classification = classify(signals);
268
+ for (const s of f.symbols) {
269
+ if (s.exportName && !names?.has(s.exportName)) {
270
+ add({
271
+ rule: 'dead-export',
272
+ severity: 'low',
273
+ file: f.path,
274
+ line: s.line,
275
+ message: `${classification === 'potentially-unused' ? 'Possibly unused' : 'Unused'} export: ${s.exportName} is exported but never imported`,
276
+ key: `dead-export|${id(f.path)}|${s.exportName}`,
277
+ confidence: s.partial || f.parse ? 'low' : exportConfidence[classification],
278
+ method: 'import-graph',
279
+ classification,
280
+ evidence: [`no indexed file imports ${s.exportName} from ${f.path}`, 'not re-exported by an entry point or public package export', 'code outside this workspace (other packages, consumers) is not visible', ...caveat, ...signals, ...(f.parse ? [`${f.path} has syntax errors${s.partial ? ' inside this declaration' : ''}, so this symbol may be incompletely extracted${listed.has(f.path) ? '' : ` (${describeHealth(f.parse)})`}`] : [])],
281
+ });
282
+ }
283
+ }
284
+ }
285
+ const byHash = new Map();
286
+ const byStruct = new Map();
287
+ const byName = new Map();
288
+ for (const f of files.filter((x) => !isTest(x.path))) {
289
+ for (const s of f.symbols) {
290
+ const where = { file: f.path, line: s.line, name: s.name, exported: Boolean(s.exportName), body: s.bodyHash };
291
+ if (s.bodyHash)
292
+ push(byHash, s.bodyHash, where);
293
+ if (s.structHash)
294
+ push(byStruct, s.structHash, where);
295
+ if ((s.kind === 'function' || s.kind === 'class') && !GENERIC_NAMES.has(s.name) && !s.name.startsWith('_'))
296
+ push(byName, s.name, where);
297
+ }
298
+ }
299
+ const place = (w) => `${w.name} (${w.file}:${w.line})`;
300
+ const exact = new Set();
301
+ const memberKey = (w) => `${id(w.file)}:${w.name}`;
302
+ for (const group of byHash.values()) {
303
+ if (group.length < 2)
304
+ continue;
305
+ group.forEach((w) => exact.add(`${w.file}:${w.name}`));
306
+ add({
307
+ rule: 'duplicate-body',
308
+ severity: 'high',
309
+ file: group[0].file,
310
+ line: group[0].line,
311
+ message: `Textually identical implementation (whitespace-normalized text match, not a semantic comparison): ${group.slice(0, 4).map(place).join(', ')}`,
312
+ key: `duplicate-body|${group.map(memberKey).sort(compareText).join(',')}`,
313
+ confidence: 'high',
314
+ method: 'exact-text-match',
315
+ evidence: [`${group.length} functions have the same body once whitespace is ignored`, ...group.slice(0, 6).map(place)],
316
+ });
317
+ }
318
+ const MAX_SIMILAR_GROUP = 8;
319
+ for (const group of byStruct.values()) {
320
+ if (group.length < 2 || group.length > MAX_SIMILAR_GROUP)
321
+ continue;
322
+ if (group.every((w) => exact.has(`${w.file}:${w.name}`)))
323
+ continue;
324
+ add({
325
+ rule: 'similar-structure',
326
+ severity: 'medium',
327
+ file: group[0].file,
328
+ line: group[0].line,
329
+ message: `Structurally similar implementation (same syntax tree after renaming local variables and normalizing literals; not a semantic comparison): ${group.slice(0, 4).map(place).join(', ')}`,
330
+ key: `similar-structure|${group.map(memberKey).sort(compareText).join(',')}`,
331
+ confidence: 'medium',
332
+ method: 'normalized-structure-match',
333
+ evidence: [`${group.length} functions have the same syntax tree shape (at least 40 tokens)`, 'local names, literal values and type annotations were ignored; called functions and property names were not', ...group.slice(0, 6).map(place)],
334
+ });
335
+ }
336
+ for (const [name, group] of byName) {
337
+ const distinctFiles = new Set(group.map((w) => w.file));
338
+ const alreadyCovered = group.every((w) => exact.has(`${w.file}:${w.name}`));
339
+ if (distinctFiles.size < 2 || !group.some((w) => w.exported) || alreadyCovered)
340
+ continue;
341
+ add({
342
+ rule: 'duplicate-symbol',
343
+ severity: 'low',
344
+ file: group[0].file,
345
+ line: group[0].line,
346
+ message: `${name} is defined in ${distinctFiles.size} files: ${group.slice(0, 4).map((w) => `${w.file}:${w.line}`).join(', ')} (same name only; the bodies were not found to match)`,
347
+ key: `duplicate-symbol|${name}|${[...distinctFiles].map(id).sort(compareText).join(',')}`,
348
+ confidence: 'low',
349
+ method: 'name-match',
350
+ evidence: [`the name ${name} is declared in ${distinctFiles.size} files`, 'a shared name says nothing about shared behaviour'],
351
+ });
352
+ }
353
+ for (const f of files) {
354
+ const byKind = new Map();
355
+ for (const s of f.suppressions)
356
+ push(byKind, s.kind, s.line);
357
+ for (const [kind, lines] of byKind) {
358
+ add({
359
+ rule: 'suppression',
360
+ severity: suppressionSeverity(kind),
361
+ file: f.path,
362
+ line: lines[0],
363
+ message: `${lines.length}x ${kind} (line${lines.length > 1 ? 's' : ''} ${lines.slice(0, 5).join(', ')}${lines.length > 5 ? ', …' : ''})`,
364
+ key: `suppression|${id(f.path)}|${kind}`,
365
+ count: lines.length,
366
+ confidence: 'high',
367
+ method: 'comment-scan',
368
+ evidence: [`${lines.length} occurrence(s) of ${kind} found in the source`],
369
+ });
370
+ }
371
+ for (const item of f.unusedImports) {
372
+ // A Python module's imports are attributes of the module: another file importing the name from here is a re-export (compat shims).
373
+ if (f.lang === 'python' && used.get(f.path)?.has(item.name))
374
+ continue;
375
+ // Generated code (route trees, API clients) imports for module augmentation and is rewritten on every build.
376
+ if (GENERATED_FILE.test(f.path))
377
+ continue;
378
+ add({
379
+ rule: 'unused-import',
380
+ severity: 'low',
381
+ file: f.path,
382
+ line: item.line,
383
+ message: `${item.name} is imported from '${item.source}' but never used`,
384
+ key: `unused-import|${id(f.path)}|${item.source}|${item.name}`,
385
+ confidence: f.parse ? 'low' : f.lang === 'python' ? 'medium' : 'high',
386
+ method: 'scope-analysis',
387
+ evidence: [`'${item.name}' is bound by the import on line ${item.line}`, 'no reference in the file resolves to that binding (shadowed names and declarations were not counted)', ...(f.lang === 'python' ? ['Python can use a name through getattr, globals() or a re-export that static analysis does not see'] : []), ...(f.parse ? [`the file has syntax errors near line ${f.parse.lines.join(', ')}, so a use of '${item.name}' inside the damaged region may have been missed (${describeHealth(f.parse)})`] : [])],
388
+ });
389
+ }
390
+ }
391
+ for (const cycle of cycles) {
392
+ const extra = cycle.modules.length > cycle.path.length - 1 ? ` (${cycle.modules.length} modules take part)` : '';
393
+ add({
394
+ rule: 'circular-dependency',
395
+ severity: 'medium',
396
+ file: cycle.path[0],
397
+ message: `Circular dependency: ${cycle.path.join(' → ')}${extra}`,
398
+ key: `circular-dependency|${cycle.modules.map(id).sort(compareText).join(',')}`,
399
+ confidence: 'high',
400
+ method: 'import-graph',
401
+ evidence: [`${cycle.path.join(' → ')}`, 'every edge is a load-time import between resolved files (type-only and lazy imports are not counted)'],
402
+ });
403
+ }
404
+ for (const item of unresolved) {
405
+ if (item.reason === 'not-indexed' || item.reason === 'unsupported')
406
+ continue;
407
+ const detail = item.reason === 'ambiguous' ? `is ambiguous (${item.candidates.slice(0, 3).join(', ')}), not guessing` : 'could not be resolved to a file in this workspace';
408
+ add({
409
+ rule: 'unresolved-import',
410
+ severity: 'low',
411
+ file: item.file,
412
+ line: item.line,
413
+ message: `'${item.spec}' ${detail}`,
414
+ key: `unresolved-import|${id(item.file)}|${item.spec}`,
415
+ // "No such file" is an absence claim, like "nothing imports this": on a scan that did not see the whole workspace the file may
416
+ // simply be somewhere the scan did not look.
417
+ confidence: options.complete === false ? 'low' : item.reason === 'not-found' && item.spec.startsWith('.') ? 'high' : 'medium',
418
+ method: 'import-resolution',
419
+ evidence: [
420
+ `'${item.spec}' was looked up as ${item.spec.startsWith('.') ? 'a relative path' : 'a configured alias or local module'}`,
421
+ item.reason === 'ambiguous' ? `it matches several files: ${item.candidates.slice(0, 3).join(', ')}` : 'no matching file exists in the index',
422
+ ...(options.complete === false ? ['the scan did not see every file, so the target may exist where it did not look'] : []),
423
+ ],
424
+ });
425
+ }
426
+ // Project configuration: per-rule severity (or off) and path exceptions.
427
+ const ruleSettings = settings.rules ?? {};
428
+ const exceptions = (settings.exceptions ?? []).map((e) => ({ rule: e.rule, symbol: e.symbol, matcher: ignore().add(e.path) }));
429
+ const kept = findings.filter((f) => {
430
+ if (ruleSettings[f.rule] === 'off')
431
+ return false;
432
+ return !exceptions.some((e) => e.rule === f.rule && e.matcher.ignores(f.file) && (!e.symbol || f.message.includes(e.symbol) || f.key.includes(e.symbol)));
433
+ });
434
+ for (const f of kept) {
435
+ const level = ruleSettings[f.rule];
436
+ if (level && level !== 'off')
437
+ f.severity = level;
438
+ }
439
+ findings.length = 0;
440
+ findings.push(...kept);
441
+ const weight = { high: 0, medium: 1, low: 2 };
442
+ findings.sort((a, b) => weight[a.severity] - weight[b.severity] || compareText(a.rule, b.rule) || compareText(a.file, b.file) || (a.line ?? 0) - (b.line ?? 0) || compareText(a.key, b.key));
443
+ return { graph, findings, cycles, unresolved: unresolved.filter((u) => u.reason !== 'unsupported'), unsupported: unresolved.filter((u) => u.reason === 'unsupported') };
444
+ }
445
+ export function analyzeProject(project, config) {
446
+ return analyze(project.files, {
447
+ tsconfigs: project.tsconfigs,
448
+ packages: project.packages,
449
+ foreignExtensions: project.foreignExtensions,
450
+ pythonRoots: config.pythonRoots,
451
+ known: project.knownPaths,
452
+ complete: project.complete,
453
+ config,
454
+ });
455
+ }
@@ -0,0 +1,46 @@
1
+ import { CACHE_LIMITS } from '../../db/schema.js';
2
+ // Structural check of a cached file result, nested records included. The signature on a cached row is what shows it was
3
+ // produced by this installation; this check is the second layer, so that a row from an older shape, a bug or a damaged
4
+ // database cannot put a wrongly typed value into the analysis. It accepts any extra fields and checks every field the
5
+ // analysis reads. It does not decide whether a result is genuine.
6
+ // The same bound the cache applies before it verifies a stored result (see CACHE_LIMITS), so a value too large to be stored is too large to be parsed.
7
+ const MAX_RAW = CACHE_LIMITS.maxInfoBytes;
8
+ const LANGS = new Set(['typescript', 'tsx', 'javascript', 'python']);
9
+ const SYMBOL_KINDS = new Set(['function', 'class', 'const', 'type', 'interface', 'enum', 'default', 'reexport']);
10
+ const IMPORT_KINDS = new Set(['import', 'reexport', 'require', 'dynamic']);
11
+ const DYNAMIC_KINDS = new Set(['import', 'require', 'glob']);
12
+ const HEALTH_STATUS = new Set(['recovered', 'degraded']);
13
+ const HEALTH_LIMITS = new Set(['depth', 'nodes']);
14
+ const isRec = (v) => typeof v === 'object' && v !== null && !Array.isArray(v);
15
+ const isStr = (v) => typeof v === 'string';
16
+ const isNum = (v) => typeof v === 'number' && Number.isFinite(v) && v >= 0;
17
+ const optStr = (v) => v === undefined || isStr(v);
18
+ const list = (v, each) => Array.isArray(v) && v.every(each);
19
+ const sym = (v) => isRec(v) && isStr(v.name) && isStr(v.kind) && SYMBOL_KINDS.has(v.kind) && isNum(v.line) && isStr(v.signature) &&
20
+ optStr(v.doc) && optStr(v.exportName) && optStr(v.bodyHash) && optStr(v.structHash) && (v.partial === undefined || v.partial === true);
21
+ const importRef = (v) => isRec(v) && isStr(v.source) && list(v.names, isStr) && isNum(v.line) && isStr(v.kind) && IMPORT_KINDS.has(v.kind) && typeof v.typeOnly === 'boolean';
22
+ const reexport = (v) => isRec(v) && isStr(v.source) && isStr(v.imported) && isStr(v.exported);
23
+ const unusedImport = (v) => isRec(v) && isStr(v.name) && isStr(v.source) && isNum(v.line);
24
+ const suppression = (v) => isRec(v) && isStr(v.kind) && isNum(v.line);
25
+ const dynamicLoad = (v) => isRec(v) && isNum(v.line) && isStr(v.kind) && DYNAMIC_KINDS.has(v.kind) && optStr(v.prefix);
26
+ const health = (v) => v === undefined || (isRec(v) && isStr(v.status) && HEALTH_STATUS.has(v.status) && isNum(v.errors) && isNum(v.missing) && list(v.lines, (n) => isNum(n)) && (v.limit === undefined || (isStr(v.limit) && HEALTH_LIMITS.has(v.limit))));
27
+ // `expectedPath`, when given, must be the path the result claims to describe.
28
+ export function parseCachedInfo(raw, expectedPath) {
29
+ if (typeof raw !== 'string' || raw.length > MAX_RAW || Buffer.byteLength(raw) > MAX_RAW)
30
+ return null;
31
+ let value;
32
+ try {
33
+ value = JSON.parse(raw);
34
+ }
35
+ catch {
36
+ return null;
37
+ }
38
+ if (!isRec(value))
39
+ return null;
40
+ const ok = isStr(value.path) && (expectedPath === undefined || value.path === expectedPath) &&
41
+ isStr(value.lang) && LANGS.has(value.lang) && isNum(value.bytes) && isNum(value.lines) &&
42
+ list(value.symbols, sym) && list(value.imports, importRef) && list(value.reexports, reexport) &&
43
+ list(value.unusedImports, unusedImport) && list(value.suppressions, suppression) && list(value.dynamicLoads, dynamicLoad) &&
44
+ typeof value.decorated === 'boolean' && typeof value.script === 'boolean' && health(value.parse);
45
+ return ok ? value : null;
46
+ }