code-guardian-ai 0.0.0-stage → 0.3.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 (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,121 @@
1
+ import { FOREIGN_SOURCE, buildIgnoreFilter, readGitignore, sourceLanguage } from '../ast/indexer.js';
2
+ import { loadPackages } from '../ast/packages.js';
3
+ import { TSCONFIG_NAME, diskReader, loadTsConfigs } from '../ast/tsconfig.js';
4
+ import { listTreeAtCommit, readBlob, readAtCommitSync } from '../git/git.js';
5
+ import { configFileName, parseConfigText } from '../../utils/config.js';
6
+ import { errorMessage } from '../../utils/errors.js';
7
+ import { compareText } from '../../utils/text.js';
8
+ const MAX_CONFIG_BYTES = 256 * 1024;
9
+ function stable(value) {
10
+ return JSON.stringify(value, (_key, v) => v && typeof v === 'object' && !Array.isArray(v)
11
+ ? Object.fromEntries(Object.entries(v).sort(([a], [b]) => compareText(a, b)))
12
+ : v);
13
+ }
14
+ // Configuration files are small and the loaders that parse them are synchronous, but reading them from git must not be: every
15
+ // synchronous `git show` blocks the event loop (no cancellation, no other request is served) and a repository can hold thousands
16
+ // of tsconfig and package files. They are read first, asynchronously and cancellably, and the loaders then read from memory.
17
+ // A file the loaders reach that was not read up front (an `extends` target with an unusual name) falls back to one synchronous
18
+ // read, within a fixed budget; past it the file counts as unreadable, which the validation reports as a partial baseline.
19
+ const PREFETCH_CONCURRENCY = 8;
20
+ const MAX_SYNC_FALLBACKS = 32;
21
+ async function prefetchConfigs(ctx, sha, files, signal) {
22
+ const found = new Map();
23
+ const queue = [...new Set(files)];
24
+ for (let i = 0; i < queue.length; i += PREFETCH_CONCURRENCY) {
25
+ signal?.throwIfAborted();
26
+ await Promise.all(queue.slice(i, i + PREFETCH_CONCURRENCY).map(async (rel) => {
27
+ const blob = await readBlob(ctx.root, sha, rel, MAX_CONFIG_BYTES, signal);
28
+ found.set(rel, blob.ok ? blob.data.toString('utf8') : null);
29
+ }));
30
+ }
31
+ signal?.throwIfAborted();
32
+ return found;
33
+ }
34
+ // Config files resolved through node_modules are not tracked by git, so those come from the working tree.
35
+ function readerAt(ctx, sha, prefetched, signal) {
36
+ const disk = diskReader(ctx.root);
37
+ let fallbacks = 0;
38
+ return (rel) => {
39
+ if (rel.split('/').includes('node_modules'))
40
+ return disk(rel);
41
+ const known = prefetched.get(rel);
42
+ if (known !== undefined)
43
+ return known;
44
+ signal?.throwIfAborted();
45
+ if (++fallbacks > MAX_SYNC_FALLBACKS)
46
+ return null;
47
+ return readAtCommitSync(ctx.root, sha, rel, MAX_CONFIG_BYTES)?.toString('utf8') ?? null;
48
+ };
49
+ }
50
+ // `signal` cancels the Git reads (the child processes are killed) and is checked again before any synchronous fallback read.
51
+ export async function reconstructBaseline(ctx, sha, project, signal) {
52
+ const tree = await listTreeAtCommit(ctx.root, sha, signal);
53
+ if (!tree)
54
+ return null;
55
+ const notes = [];
56
+ const changed = [];
57
+ const unreconstructable = [];
58
+ let historical = parseConfigText('{}');
59
+ if (tree.includes(configFileName)) {
60
+ const blob = await readBlob(ctx.root, sha, configFileName, MAX_CONFIG_BYTES, signal);
61
+ if (!blob.ok) {
62
+ unreconstructable.push(`${configFileName} exists at the base commit but could not be read (${blob.reason}); defaults were used for it`);
63
+ }
64
+ else {
65
+ try {
66
+ historical = parseConfigText(blob.data.toString('utf8'));
67
+ }
68
+ catch (err) {
69
+ unreconstructable.push(`${configFileName} at the base commit is invalid (${errorMessage(err).split('\n')[0]}); defaults were used for it`);
70
+ }
71
+ }
72
+ }
73
+ // Resource limits and LLM switches describe this run, not the project's rules.
74
+ const config = { ...historical, maxFiles: ctx.config.maxFiles, maxFileKb: ctx.config.maxFileKb, contextTokens: ctx.config.contextTokens, llm: ctx.config.llm };
75
+ let gitignoreThen = '';
76
+ if (tree.includes('.gitignore')) {
77
+ const blob = await readBlob(ctx.root, sha, '.gitignore', 256 * 1024, signal);
78
+ if (blob.ok)
79
+ gitignoreThen = blob.data.toString('utf8');
80
+ else
81
+ unreconstructable.push(`.gitignore exists at the base commit but could not be read (${blob.reason}); the files it ignored then are unknown`);
82
+ }
83
+ const filter = buildIgnoreFilter(gitignoreThen, config.ignore);
84
+ const paths = tree.filter((p) => sourceLanguage(p) && !filter.ignores(p)).sort(compareText);
85
+ const configFiles = tree.filter((p) => TSCONFIG_NAME.test(p.split('/').pop() ?? '') && !filter.ignores(p));
86
+ const packageFiles = tree.filter((p) => ['package.json', 'pyproject.toml'].includes(p.split('/').pop() ?? '') && !filter.ignores(p));
87
+ // Read every configuration file the loaders start from now, asynchronously, so a cancel stops the git processes and the event
88
+ // loop stays free; the loaders below then work on memory.
89
+ const prefetched = await prefetchConfigs(ctx, sha, [...configFiles, ...packageFiles], signal);
90
+ const reader = readerAt(ctx, sha, prefetched, signal);
91
+ const tsconfigs = loadTsConfigs(reader, configFiles);
92
+ const packages = loadPackages(reader, packageFiles);
93
+ signal?.throwIfAborted();
94
+ // A config file that loads today but not at the base (unreadable, invalid, or an `extends` that cannot be found)
95
+ // leaves the baseline without aliases, references or framework signals it really had.
96
+ const loadedNow = (files) => new Set(files.map((f) => f.file));
97
+ const missing = (wanted, got, now) => {
98
+ const have = loadedNow(got);
99
+ return wanted.filter((f) => !have.has(f) && now.has(f));
100
+ };
101
+ for (const file of missing(configFiles, tsconfigs, loadedNow(project.tsconfigs)))
102
+ unreconstructable.push(`${file} could not be read or parsed at the base commit`);
103
+ for (const file of missing(packageFiles, packages, loadedNow(project.packages)))
104
+ unreconstructable.push(`${file} could not be read or parsed at the base commit`);
105
+ const ruleSettings = (c) => stable({ ignore: c.ignore, pythonRoots: c.pythonRoots, profile: c.profile, entryPoints: c.entryPoints, rules: c.rules, exceptions: c.exceptions });
106
+ // Only what resolution and entry-point detection read from a manifest: names, entry fields, exports/imports and detected frameworks.
107
+ const manifestView = (list) => stable(list.map(({ file, name, main, module, types, bin, exports, imports, frameworks }) => ({ file, name, main, module, types, bin, exports, imports, frameworks })));
108
+ if (ruleSettings(config) !== ruleSettings(ctx.config))
109
+ changed.push(configFileName);
110
+ if (gitignoreThen !== readGitignore(ctx.root))
111
+ changed.push('.gitignore');
112
+ if (stable(tsconfigs) !== stable(project.tsconfigs))
113
+ changed.push('tsconfig/jsconfig');
114
+ if (manifestView(packages) !== manifestView(project.packages))
115
+ changed.push('package.json (frameworks, exports, workspaces)');
116
+ if (changed.length > 0) {
117
+ notes.push(`Project configuration differs from the base commit (${changed.join(', ')}). The baseline was rebuilt with the configuration that existed then.`);
118
+ }
119
+ const foreignExtensions = [...new Set(tree.filter((p) => !filter.ignores(p)).map((p) => (p.match(/\.[^./]+$/)?.[0] ?? '').toLowerCase()).filter((e) => FOREIGN_SOURCE.has(e)))].sort();
120
+ return { paths, tsconfigs, packages, foreignExtensions, config, changed, notes, unreconstructable };
121
+ }
@@ -0,0 +1,243 @@
1
+ import { analyze, analyzeProject } from '../ast/analysis.js';
2
+ import { languageOf } from '../ast/indexer.js';
3
+ import { loadLanguages, parseFile } from '../ast/parser.js';
4
+ import { createPacer } from '../../utils/pace.js';
5
+ import { collectChanges, detectRepo, readBlob } from '../git/git.js';
6
+ import { compareText } from '../../utils/text.js';
7
+ import { TSCONFIG_NAME } from '../ast/tsconfig.js';
8
+ import { configFileName, effectiveLimit } from '../../utils/config.js';
9
+ import { reconstructBaseline } from './baseline.js';
10
+ import { assessPolicy, excludedFiles, loweredSeverities } from './policy.js';
11
+ export const MAX_CHANGED_FILES = 400;
12
+ const FALLBACKS = {
13
+ 'git-not-found': 'git is not installed or not on PATH',
14
+ 'not-a-repository': 'this workspace is not a git repository',
15
+ };
16
+ function countMap(findings) {
17
+ return new Map(findings.map((f) => [f.key, f]));
18
+ }
19
+ // Identity is the finding key, so line shifts caused by edits do not make old findings look new.
20
+ export function diffFindings(before, after, changedFiles) {
21
+ const was = countMap(before);
22
+ const now = countMap(after);
23
+ const introduced = [];
24
+ const existing = [];
25
+ for (const finding of after) {
26
+ const previous = was.get(finding.key);
27
+ if (!previous) {
28
+ introduced.push({ ...finding, inChangedFile: changedFiles.has(finding.file) });
29
+ }
30
+ else if (finding.count > previous.count) {
31
+ const added = finding.count - previous.count;
32
+ introduced.push({ ...finding, count: added, message: `${added} new (${previous.count} before): ${finding.message}`, inChangedFile: changedFiles.has(finding.file) });
33
+ }
34
+ else {
35
+ existing.push(finding);
36
+ }
37
+ }
38
+ const fixed = before.filter((f) => {
39
+ const current = now.get(f.key);
40
+ return !current || current.count < f.count;
41
+ });
42
+ return { introduced, fixed, existing };
43
+ }
44
+ // Files that change how every other file is read: touching one invalidates the whole baseline, not just itself.
45
+ const isConfigFile = (p) => TSCONFIG_NAME.test(p.split('/').pop() ?? '') || p === configFileName || p === '.gitignore' || ['package.json', 'pyproject.toml'].includes(p.split('/').pop() ?? '');
46
+ const basePathOf = (change) => (change.status === 'renamed' && change.oldPath ? change.oldPath : change.path);
47
+ // Rebuilds the project as it was at `sha`: the files tracked then, parsed from their content then, resolved with
48
+ // the tsconfig, ignore rules and path aliases that existed then. A renamed file comes back at its ORIGINAL path, so
49
+ // every import that pointed at it in the base still resolves, and its findings are matched to the new path by identity.
50
+ async function buildBaseline(ctx, project, evaluated, overflow, sha, limit, signal) {
51
+ const pacer = createPacer({ signal });
52
+ const maxBytes = effectiveLimit(ctx.config, 'maxFileKb') * 1024;
53
+ const current = new Map(project.files.map((f) => [f.path, f]));
54
+ const files = new Map();
55
+ const skipped = overflow.map((c) => ({ path: c.path, reason: 'over-limit' }));
56
+ const notes = [];
57
+ const renames = new Map();
58
+ let reads = 0;
59
+ const rules = await reconstructBaseline(ctx, sha, project, signal);
60
+ if (rules)
61
+ notes.push(...rules.notes);
62
+ else
63
+ notes.push('The file list and configuration at the base commit could not be read; they were approximated from the working tree.');
64
+ const restore = async (rel) => {
65
+ const lang = languageOf(rel);
66
+ if (!lang)
67
+ return;
68
+ // Cancellation and the event loop: one file per tick, so a long baseline neither ignores a cancel nor blocks other requests.
69
+ await pacer.tick();
70
+ reads++;
71
+ const blob = await readBlob(ctx.root, sha, rel, maxBytes, signal);
72
+ if (!blob.ok) {
73
+ skipped.push({ path: rel, reason: blob.reason === 'too-large' ? 'baseline-too-large' : 'baseline-unreadable' });
74
+ return;
75
+ }
76
+ if (blob.data.length === 0)
77
+ return;
78
+ await loadLanguages([lang]);
79
+ const info = parseFile(rel, lang, blob.data.toString('utf8').replace(/^\uFEFF/, ''));
80
+ if (info)
81
+ files.set(rel, info);
82
+ else
83
+ skipped.push({ path: rel, reason: 'baseline-unparseable' });
84
+ };
85
+ const evaluatedByBase = new Map();
86
+ for (const change of evaluated) {
87
+ if (change.status === 'added')
88
+ continue;
89
+ evaluatedByBase.set(basePathOf(change), change);
90
+ if (change.status === 'renamed' && change.oldPath)
91
+ renames.set(change.oldPath, change.path);
92
+ }
93
+ const overflowByBase = new Set(overflow.filter((c) => c.status !== 'added').map(basePathOf));
94
+ if (rules) {
95
+ for (const rel of rules.paths) {
96
+ if (evaluatedByBase.has(rel)) {
97
+ await restore(rel);
98
+ continue;
99
+ }
100
+ const existing = current.get(rel);
101
+ if (existing) {
102
+ files.set(rel, existing);
103
+ }
104
+ else if (overflowByBase.has(rel) || reads >= limit) {
105
+ // Tracked at the base but absent from today's index, and no budget left to read it back.
106
+ if (!overflowByBase.has(rel))
107
+ skipped.push({ path: rel, reason: 'over-limit' });
108
+ }
109
+ else {
110
+ await restore(rel);
111
+ }
112
+ }
113
+ }
114
+ else {
115
+ for (const f of project.files)
116
+ files.set(f.path, f);
117
+ for (const change of evaluated) {
118
+ if (change.status === 'added')
119
+ files.delete(change.path);
120
+ else if (change.status === 'renamed' && change.oldPath) {
121
+ files.delete(change.path);
122
+ await restore(change.oldPath);
123
+ }
124
+ else {
125
+ files.delete(change.path);
126
+ await restore(change.path);
127
+ }
128
+ }
129
+ }
130
+ const known = rules
131
+ ? rules.paths
132
+ : [...new Set([...project.knownPaths.filter((p) => !evaluated.some((c) => c.status !== 'deleted' && c.path === p && (c.status === 'added' || c.status === 'renamed'))), ...evaluated.map(basePathOf).filter((p) => files.has(p))])].sort(compareText);
133
+ return {
134
+ files: [...files.values()].sort((a, b) => compareText(a.path, b.path)),
135
+ known,
136
+ skipped: skipped.sort((a, b) => compareText(a.path, b.path) || compareText(a.reason, b.reason)),
137
+ rules,
138
+ identify: (p) => renames.get(p) ?? p,
139
+ notes,
140
+ };
141
+ }
142
+ export async function validateChanges(ctx, project, current, options = {}) {
143
+ const limit = options.maxChangedFiles ?? MAX_CHANGED_FILES;
144
+ const indexReasons = () => {
145
+ if (project.complete)
146
+ return [];
147
+ const unavailable = project.configProblems.map((p) => `Configuration unavailable in the working tree: ${p}.`);
148
+ const reasons = [...unavailable];
149
+ if (project.stopped)
150
+ reasons.push('A resource limit stopped the scan, so the working tree was only partly indexed.');
151
+ if (project.parseIssues.length > 0)
152
+ reasons.push(`${project.parseIssues.length} file(s) in the working tree have syntax errors, so their extraction may be incomplete.`);
153
+ return reasons.length > 0 ? reasons : ['The working tree was only partly indexed (see the coverage notes).'];
154
+ };
155
+ const whole = (fallback) => ({
156
+ scope: 'workspace',
157
+ fallback,
158
+ changes: [],
159
+ introduced: current.findings.map((f) => ({ ...f, inChangedFile: false })),
160
+ fixed: [],
161
+ existing: [],
162
+ configDowngrades: [],
163
+ suppressedByPolicy: [],
164
+ partial: !project.complete,
165
+ partialReasons: indexReasons(),
166
+ baselineNotes: [],
167
+ });
168
+ const repo = await detectRepo(ctx.root, options.signal);
169
+ if (!repo.ok)
170
+ return whole(`${FALLBACKS[repo.reason]}, so existing findings cannot be told apart from new ones`);
171
+ const set = await collectChanges(ctx.root, repo, options.base, options.signal);
172
+ const relevant = set.changes.filter((c) => languageOf(c.path) || (c.oldPath && languageOf(c.oldPath)));
173
+ const evaluated = relevant.slice(0, limit);
174
+ const overflow = relevant.slice(limit);
175
+ const changedFiles = new Set(evaluated.flatMap((c) => (c.oldPath ? [c.path, c.oldPath] : [c.path])));
176
+ const coverage = (skipped) => ({
177
+ relevantChanges: relevant.length,
178
+ evaluated: evaluated.map((c) => c.path),
179
+ skipped,
180
+ limit,
181
+ });
182
+ const configTouched = set.changes.filter((c) => isConfigFile(c.path) || (c.oldPath !== undefined && isConfigFile(c.oldPath)));
183
+ if (evaluated.length === 0 && configTouched.length === 0) {
184
+ return { scope: 'changes', baseLabel: set.baseLabel, changes: [], introduced: [], fixed: [], existing: current.findings, configDowngrades: [], suppressedByPolicy: [], partial: !project.complete, partialReasons: indexReasons(), coverage: coverage([]), baselineNotes: [] };
185
+ }
186
+ const base = set.baseSha
187
+ ? await buildBaseline(ctx, project, evaluated, overflow, set.baseSha, limit, options.signal)
188
+ : { files: [], known: [], skipped: [], rules: null, identify: (p) => p, notes: [] };
189
+ const before = analyze(base.files, {
190
+ identify: base.identify,
191
+ tsconfigs: base.rules?.tsconfigs ?? project.tsconfigs,
192
+ packages: base.rules?.packages ?? project.packages,
193
+ foreignExtensions: base.rules?.foreignExtensions ?? project.foreignExtensions,
194
+ pythonRoots: base.rules?.config.pythonRoots ?? ctx.config.pythonRoots,
195
+ known: base.known,
196
+ complete: project.complete && base.skipped.length === 0 && (base.rules?.unreconstructable.length ?? 0) === 0,
197
+ config: base.rules?.config ?? ctx.config,
198
+ });
199
+ const diff = diffFindings(before.findings, current.findings, changedFiles);
200
+ const { introduced, existing } = diff;
201
+ // The base configuration is only known when it could be rebuilt; without it nothing can be said about a downgrade, and the
202
+ // result is already marked partial below.
203
+ const baseRules = base.rules;
204
+ const policy = baseRules
205
+ ? assessPolicy({
206
+ before: baseRules.config,
207
+ now: ctx.config,
208
+ // A stopped scan has not seen every path, so an unseen file would look excluded.
209
+ excluded: project.stopped ? undefined : excludedFiles(baseRules.paths, project.knownPaths, set.changes),
210
+ fixed: diff.fixed,
211
+ lowered: loweredSeverities(before.findings, current.findings),
212
+ })
213
+ : { downgrades: [], suppressed: [], fixed: diff.fixed };
214
+ const fixed = policy.fixed;
215
+ const reasons = indexReasons();
216
+ if (overflow.length > 0)
217
+ reasons.push(`${relevant.length} source files changed but only the first ${limit} were compared; the other ${overflow.length} were not restored from the base commit.`);
218
+ const unreadable = base.skipped.filter((s) => s.reason !== 'over-limit');
219
+ if (unreadable.length > 0)
220
+ reasons.push(`${unreadable.length} file(s) could not be read back from the base commit.`);
221
+ if (!base.rules && set.baseSha)
222
+ reasons.push('The base commit file list could not be read.');
223
+ for (const problem of base.rules?.unreconstructable ?? [])
224
+ reasons.push(`Base configuration not reconstructed: ${problem}.`);
225
+ return {
226
+ scope: 'changes',
227
+ baseLabel: set.baseLabel,
228
+ changes: evaluated,
229
+ introduced,
230
+ fixed,
231
+ existing,
232
+ configDowngrades: policy.downgrades,
233
+ suppressedByPolicy: policy.suppressed,
234
+ partial: reasons.length > 0,
235
+ partialReasons: reasons,
236
+ coverage: coverage(base.skipped),
237
+ baselineNotes: base.notes,
238
+ };
239
+ }
240
+ export async function validateProject(ctx, project, options = {}) {
241
+ const analysis = analyzeProject(project, ctx.config);
242
+ return { analysis, validation: await validateChanges(ctx, project, analysis, options) };
243
+ }
@@ -0,0 +1,123 @@
1
+ import ignore from 'ignore';
2
+ const RANK = { high: 0, medium: 1, low: 2 };
3
+ const MAX_LISTED = 5;
4
+ // A configured level replaces a finding's own severity. An unset rule counts as 'high' here, the strongest it can be,
5
+ // so setting it to medium or low is reported as a possible lowering (the default of some rules is already lower).
6
+ const levelRank = (level) => (level === 'high' || level === 'medium' || level === 'low' ? RANK[level] : 0);
7
+ // 'src/', './src' and 'src' are the same root, and '.' and '' are the project root.
8
+ const rootKey = (root) => root.replace(/\\/g, '/').replace(/^(\.\/)+/, '').replace(/\/+$/, '').replace(/^\.$/, '');
9
+ const PYTHON_FILE = /\.pyi?$/i;
10
+ const PYTHON_RESOLUTION_RULES = new Set(['unresolved-import', 'orphan-file', 'dead-export']);
11
+ const ENTRY_RULES = new Set(['orphan-file', 'dead-export']);
12
+ const sample = (items) => `${items.slice(0, MAX_LISTED).join(', ')}${items.length > MAX_LISTED ? `, and ${items.length - MAX_LISTED} more` : ''}`;
13
+ const exceptionKey = (e) => `${e.rule}\u0000${e.path}\u0000${e.symbol ?? ''}`;
14
+ const added = (now, before, key) => {
15
+ const had = new Set(before.map(key));
16
+ return now.filter((item) => !had.has(key(item)));
17
+ };
18
+ // Source files that were analysed at the base and still exist, but are no longer eligible: excluded by an ignore pattern,
19
+ // .gitignore or similar. A file that was deleted or renamed away is a code change, not an exclusion.
20
+ export function excludedFiles(basePaths, eligibleNow, changes) {
21
+ const now = new Set(eligibleNow);
22
+ const gone = new Set();
23
+ for (const c of changes) {
24
+ if (c.status === 'deleted')
25
+ gone.add(c.path);
26
+ if (c.status === 'renamed' && c.oldPath)
27
+ gone.add(c.oldPath);
28
+ }
29
+ return basePaths.filter((p) => !now.has(p) && !gone.has(p));
30
+ }
31
+ export function assessPolicy(input) {
32
+ const { before, now } = input;
33
+ const downgrades = [];
34
+ const disabled = Object.entries(now.rules).filter(([rule, level]) => level === 'off' && before.rules[rule] !== 'off').map(([rule]) => rule);
35
+ if (disabled.length > 0)
36
+ downgrades.push({ kind: 'rule-disabled', detail: `rule(s) turned off: ${disabled.sort().join(', ')}` });
37
+ const byRule = new Map();
38
+ for (const { finding } of input.lowered)
39
+ byRule.set(finding.rule, (byRule.get(finding.rule) ?? 0) + 1);
40
+ if (byRule.size > 0) {
41
+ const parts = [...byRule].sort(([a], [b]) => (a < b ? -1 : 1)).map(([rule, n]) => `${rule} (${n} finding(s))`);
42
+ downgrades.push({ kind: 'severity-lowered', detail: `severity lowered for existing findings of: ${parts.join(', ')}` });
43
+ }
44
+ // A rule whose configured severity went down, even if no current finding shows it yet: --fail-on and every later
45
+ // report read that level.
46
+ const reduced = Object.entries(now.rules)
47
+ .filter(([rule, level]) => level !== 'off' && before.rules[rule] !== 'off' && levelRank(level) > levelRank(before.rules[rule]))
48
+ .map(([rule]) => rule);
49
+ const reducedFromFindings = new Set(input.lowered.map(({ finding }) => finding.rule));
50
+ const reducedOnly = reduced.filter((rule) => !reducedFromFindings.has(rule));
51
+ if (reducedOnly.length > 0)
52
+ downgrades.push({ kind: 'severity-lowered', detail: `configured severity lowered for rule(s): ${reducedOnly.sort().join(', ')}` });
53
+ // profile decides which files count as entry points. Moving to 'none' only makes the check stricter; any other change can
54
+ // add entry points and hide unused-file and unused-export findings.
55
+ const profileWeakened = now.profile !== undefined && before.profile !== undefined && now.profile !== before.profile && now.profile !== 'none';
56
+ if (profileWeakened)
57
+ downgrades.push({ kind: 'profile-changed', detail: `profile changed from ${before.profile} to ${now.profile} (it can add entry points that hide unused-file and unused-export findings; review it)` });
58
+ // pythonRoots decide how Python imports resolve. A root that was not there before can make unresolved imports resolve and
59
+ // make files look referenced; removing a root can only do the opposite.
60
+ const hadRoots = new Set((before.pythonRoots ?? []).map(rootKey));
61
+ const newRoots = now.pythonRoots === undefined || before.pythonRoots === undefined ? [] : [...new Set(now.pythonRoots.map(rootKey))].filter((r) => !hadRoots.has(r));
62
+ if (newRoots.length > 0)
63
+ downgrades.push({ kind: 'python-roots-added', detail: `pythonRoots added: ${sample(newRoots.map((r) => r || '(project root)'))} (they change how Python imports resolve; review them)` });
64
+ // Protection for what leaves the machine: strict mode switched off, or masking rules and literals removed.
65
+ const outbound = [];
66
+ if (before.strictOutbound === true && now.strictOutbound === false)
67
+ outbound.push('strictOutbound turned off');
68
+ const patternsNow = new Set((now.maskPatterns ?? []).map((m) => `${m.name}\u0000${m.pattern}`));
69
+ const patternsLost = (before.maskPatterns ?? []).filter((m) => !patternsNow.has(`${m.name}\u0000${m.pattern}`));
70
+ if (now.maskPatterns !== undefined && patternsLost.length > 0)
71
+ outbound.push(`maskPatterns removed: ${sample(patternsLost.map((m) => m.name))}`);
72
+ const literalsNow = new Set(now.maskLiterals ?? []);
73
+ const literalsLost = (before.maskLiterals ?? []).filter((l) => !literalsNow.has(l));
74
+ if (now.maskLiterals !== undefined && literalsLost.length > 0)
75
+ outbound.push(`${literalsLost.length} maskLiterals entr${literalsLost.length === 1 ? 'y' : 'ies'} removed`);
76
+ if (outbound.length > 0)
77
+ downgrades.push({ kind: 'outbound-weakened', detail: `outbound protection weakened: ${outbound.join('; ')}` });
78
+ const newIgnores = added(now.ignore, before.ignore, (p) => p);
79
+ if (newIgnores.length > 0)
80
+ downgrades.push({ kind: 'ignore-added', detail: `ignore pattern(s) added: ${sample(newIgnores)}` });
81
+ const newExceptions = added(now.exceptions, before.exceptions, exceptionKey);
82
+ if (newExceptions.length > 0)
83
+ downgrades.push({ kind: 'exception-added', detail: `exception(s) added: ${sample(newExceptions.map((e) => `${e.rule} in ${e.path}${e.symbol ? ` for ${e.symbol}` : ''}`))}` });
84
+ const newEntries = added(now.entryPoints, before.entryPoints, (p) => p);
85
+ if (newEntries.length > 0)
86
+ downgrades.push({ kind: 'entry-point-added', detail: `entry point pattern(s) added (they hide unused-file and unused-export findings): ${sample(newEntries)}` });
87
+ const excluded = new Set(input.excluded ?? []);
88
+ if (excluded.size > 0)
89
+ downgrades.push({ kind: 'files-excluded', detail: `${excluded.size} source file(s) analysed at the base commit are no longer analysed: ${sample([...excluded].sort())}` });
90
+ // A vanished finding counts as suppressed when something above explains it; anything else stays a real fix.
91
+ const disabledRules = new Set(disabled);
92
+ const exceptionMatchers = newExceptions.map((e) => ({ e, matcher: ignore().add(e.path) }));
93
+ const entryMatcher = ignore().add(newEntries);
94
+ const explained = (f) => {
95
+ if (disabledRules.has(f.rule) || excluded.has(f.file))
96
+ return true;
97
+ if (ENTRY_RULES.has(f.rule) && newEntries.length > 0 && entryMatcher.ignores(f.file))
98
+ return true;
99
+ // Which files a changed profile or new Python root now covers is not recomputed here: every finding of the rules it
100
+ // can affect that vanished alongside it is kept out of "fixed", the safe side of an unavoidable guess.
101
+ if (profileWeakened && ENTRY_RULES.has(f.rule))
102
+ return true;
103
+ if (newRoots.length > 0 && PYTHON_RESOLUTION_RULES.has(f.rule) && PYTHON_FILE.test(f.file))
104
+ return true;
105
+ return exceptionMatchers.some(({ e, matcher }) => e.rule === f.rule && matcher.ignores(f.file) && (!e.symbol || f.message.includes(e.symbol) || f.key.includes(e.symbol)));
106
+ };
107
+ const suppressed = [];
108
+ const fixed = [];
109
+ for (const f of input.fixed)
110
+ (explained(f) ? suppressed : fixed).push(f);
111
+ return { downgrades, suppressed, fixed };
112
+ }
113
+ // Existing findings whose severity is lower than it was at the base commit.
114
+ export function loweredSeverities(before, after) {
115
+ const was = new Map(before.map((f) => [f.key, f]));
116
+ const lowered = [];
117
+ for (const finding of after) {
118
+ const previous = was.get(finding.key);
119
+ if (previous && RANK[finding.severity] > RANK[previous.severity])
120
+ lowered.push({ finding, was: previous.severity });
121
+ }
122
+ return lowered;
123
+ }