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,298 @@
1
+ import { hasParseError } from './health.js';
2
+ import { structuralHash, bodyHash, codeText, docstring, kids, lineOf, oneLine, rangeOf, summarizeNames, text, within } from './util.js';
3
+ const COMMENT_RULES = [
4
+ ['type: ignore', /#\s*type:\s*ignore/],
5
+ ['noqa', /#\s*noqa\b/i],
6
+ ['pylint: disable', /#\s*pylint:\s*disable/],
7
+ ['pyright: ignore', /#\s*pyright:\s*ignore/],
8
+ ['mypy: ignore-errors', /#\s*mypy:\s*ignore-errors/],
9
+ ];
10
+ const QUERY = `
11
+ (comment) @comment
12
+ (import_statement) @import
13
+ (import_from_statement) @from
14
+ `;
15
+ const CONSTANT = /^[A-Z][A-Z0-9_]*$/;
16
+ const INTENTIONAL_IMPORT = /#\s*(?:noqa|type:\s*ignore|pylint:\s*disable|pyright:\s*ignore)/i;
17
+ const WORD = /[A-Za-z_][A-Za-z0-9_]*/g;
18
+ const present = (nodes) => nodes.filter((n) => n !== null);
19
+ function signature(def, source) {
20
+ const body = def.childForFieldName('body');
21
+ return oneLine(codeText(def, source, body ? body.startIndex : def.endIndex)).replace(/:\s*(?:#.*)?$/, '');
22
+ }
23
+ const docField = (def) => {
24
+ const doc = docstring(def);
25
+ return doc ? { doc } : {};
26
+ };
27
+ function publicMethods(classNode) {
28
+ return kids(classNode.childForFieldName('body'))
29
+ .map((member) => (member.type === 'decorated_definition' ? member.childForFieldName('definition') : member))
30
+ .filter((member) => member?.type === 'function_definition')
31
+ .map((member) => member.childForFieldName('name')?.text ?? '')
32
+ .filter((name) => name && !name.startsWith('_'));
33
+ }
34
+ function insideFunction(node) {
35
+ for (let current = node.parent; current; current = current.parent) {
36
+ if (current.type === 'function_definition')
37
+ return true;
38
+ }
39
+ return false;
40
+ }
41
+ function insideTypeChecking(node) {
42
+ for (let current = node.parent; current; current = current.parent) {
43
+ if (current.type === 'if_statement' && /\bTYPE_CHECKING\b/.test(text(current.childForFieldName('condition'))))
44
+ return true;
45
+ }
46
+ return false;
47
+ }
48
+ // A string that names a type: inside an annotation, inside a subscript (Callable[["Response"], Any], Optional["Foo"]),
49
+ // or the first argument of cast("Foo", value). Only a bare dotted name counts, so ordinary strings are not mistaken for uses.
50
+ const TYPE_NAME = /^\s*[A-Za-z_][\w.]*(?:\[[\w.,\s|\[\]]*\])?\s*$/;
51
+ function insideAnnotation(node) {
52
+ let current = node.parent;
53
+ for (let depth = 0; current && depth < 6; depth++, current = current.parent) {
54
+ if (current.type === 'type')
55
+ return true;
56
+ }
57
+ const raw = node.text.replace(/^[rbuRBU]*['"]+|['"]+$/g, '');
58
+ if (!TYPE_NAME.test(raw))
59
+ return false;
60
+ for (let parent = node.parent, depth = 0; parent && depth < 4; depth++, parent = parent.parent) {
61
+ if (parent.type === 'subscript')
62
+ return true;
63
+ if (parent.type === 'call' && /^(?:typing\.)?cast$/.test(text(parent.childForFieldName('function'))))
64
+ return true;
65
+ if (parent.type === 'block' || parent.type === 'module')
66
+ break;
67
+ }
68
+ return false;
69
+ }
70
+ function importedItem(item) {
71
+ if (item.type !== 'aliased_import')
72
+ return { imported: item.text, local: item.text };
73
+ const imported = text(item.childForFieldName('name'));
74
+ return { imported, local: text(item.childForFieldName('alias')) || imported };
75
+ }
76
+ export function extractPython({ root, source, query, path: filePath }) {
77
+ const symbols = [];
78
+ const imports = [];
79
+ const reexports = [];
80
+ const suppressions = [];
81
+ const bindings = [];
82
+ const importRanges = [];
83
+ const isInit = /(^|\/)__init__\.py$/.test(filePath);
84
+ for (const node of kids(root)) {
85
+ const def = node.type === 'decorated_definition' ? node.childForFieldName('definition') : node;
86
+ if (!def)
87
+ continue;
88
+ const line = def.startPosition.row + 1;
89
+ const name = def.childForFieldName('name')?.text ?? '';
90
+ if (def.type === 'function_definition') {
91
+ symbols.push({
92
+ name,
93
+ kind: 'function',
94
+ line,
95
+ signature: signature(def, source),
96
+ ...docField(def),
97
+ ...(hasParseError(def) ? { partial: true } : {}),
98
+ exportName: name.startsWith('_') ? undefined : name,
99
+ bodyHash: bodyHash(def.childForFieldName('body')),
100
+ structHash: structuralHash([def.childForFieldName('parameters'), def.childForFieldName('body')], (n) => storeScope(n).store),
101
+ });
102
+ }
103
+ else if (def.type === 'class_definition') {
104
+ const methods = publicMethods(def);
105
+ const classHead = signature(def, source);
106
+ symbols.push({
107
+ name,
108
+ kind: 'class',
109
+ line,
110
+ signature: methods.length ? `${classHead} { ${summarizeNames(methods)} }` : classHead,
111
+ ...docField(def),
112
+ ...(hasParseError(def) ? { partial: true } : {}),
113
+ exportName: name.startsWith('_') ? undefined : name,
114
+ });
115
+ }
116
+ else if (def.type === 'expression_statement') {
117
+ const assignment = kids(def).find((c) => c.type === 'assignment');
118
+ const target = assignment?.childForFieldName('left');
119
+ if (target?.type === 'identifier' && CONSTANT.test(target.text)) {
120
+ const annotation = assignment?.childForFieldName('type');
121
+ symbols.push({
122
+ name: target.text,
123
+ kind: 'const',
124
+ line,
125
+ signature: annotation ? `${target.text}: ${annotation.text}` : target.text,
126
+ exportName: target.text.startsWith('_') ? undefined : target.text,
127
+ });
128
+ }
129
+ }
130
+ }
131
+ function readImport(node) {
132
+ importRanges.push(rangeOf(node));
133
+ const line = lineOf(node);
134
+ const kind = insideFunction(node) ? 'dynamic' : 'import';
135
+ const typeOnly = insideTypeChecking(node);
136
+ const endOfLine = source.indexOf('\n', node.endIndex);
137
+ const intentional = INTENTIONAL_IMPORT.test(source.slice(node.startIndex, endOfLine === -1 ? source.length : endOfLine));
138
+ if (node.type === 'import_statement') {
139
+ for (const item of present(node.childrenForFieldName('name'))) {
140
+ const aliased = item.type === 'aliased_import';
141
+ const dotted = aliased ? text(item.childForFieldName('name')) : item.text;
142
+ const alias = aliased ? text(item.childForFieldName('alias')) : '';
143
+ imports.push({ source: dotted, names: ['*'], line, kind, typeOnly });
144
+ bindings.push({ local: alias || dotted.split('.')[0], source: dotted, line, skip: rangeOf(node), intentional });
145
+ }
146
+ return;
147
+ }
148
+ const moduleName = text(node.childForFieldName('module_name'));
149
+ const wildcard = kids(node).some((c) => c.type === 'wildcard_import');
150
+ const items = present(node.childrenForFieldName('name')).map(importedItem);
151
+ imports.push({ source: moduleName, names: wildcard ? ['*'] : items.map((i) => i.imported), line, kind, typeOnly });
152
+ if (!wildcard && moduleName !== '__future__') {
153
+ for (const item of items)
154
+ bindings.push({ local: item.local, source: moduleName, line, skip: rangeOf(node), intentional });
155
+ }
156
+ if (isInit && kind === 'import' && !typeOnly) {
157
+ if (wildcard)
158
+ reexports.push({ source: moduleName, imported: '*', exported: '*' });
159
+ else
160
+ for (const item of items)
161
+ reexports.push({ source: moduleName, imported: item.imported, exported: item.local });
162
+ }
163
+ }
164
+ for (const capture of query(QUERY).captures(root)) {
165
+ if (capture.name === 'comment') {
166
+ const rule = COMMENT_RULES.find(([, pattern]) => pattern.test(capture.node.text));
167
+ if (rule)
168
+ suppressions.push({ kind: rule[0], line: lineOf(capture.node) });
169
+ }
170
+ else {
171
+ readImport(capture.node);
172
+ }
173
+ }
174
+ return { symbols, imports, reexports, unusedImports: isInit ? [] : findUnused(root, bindings, importRanges), suppressions, dynamicLoads: [], decorated: false, script: hasMainGuardOrCall(root) };
175
+ }
176
+ const PY_SCOPES = new Set(['function_definition', 'lambda', 'list_comprehension', 'set_comprehension', 'dictionary_comprehension', 'generator_expression', 'class_definition']);
177
+ const PATTERN_WRAPPERS = new Set(['tuple_pattern', 'list_pattern', 'pattern_list', 'list_splat_pattern', 'parenthesized_pattern', 'dictionary_splat_pattern']);
178
+ const PARAM_PARENTS = new Set(['parameters', 'lambda_parameters', 'default_parameter', 'typed_parameter', 'typed_default_parameter']);
179
+ // A top-level call or an `if __name__ == "__main__"` guard means the file is meant to be run, not only imported.
180
+ function hasMainGuardOrCall(root) {
181
+ return kids(root).some((n) => (n.type === 'if_statement' && /__name__/.test(text(n.childForFieldName('condition')))) ||
182
+ (n.type === 'expression_statement' && kids(n).some((c) => c.type === 'call' || c.type === 'await')));
183
+ }
184
+ const COMPREHENSIONS = new Set(['list_comprehension', 'set_comprehension', 'dictionary_comprehension', 'generator_expression']);
185
+ // A walrus inside a comprehension binds its target in the function (or module) around the comprehension, not in it.
186
+ function walrusScope(node) {
187
+ let scope = nearestPyScope(node);
188
+ while (scope && COMPREHENSIONS.has(scope.type))
189
+ scope = nearestPyScope(scope);
190
+ return scope;
191
+ }
192
+ function nearestPyScope(node) {
193
+ for (let current = node.parent; current; current = current.parent)
194
+ if (PY_SCOPES.has(current.type))
195
+ return current;
196
+ return null;
197
+ }
198
+ // A store introduces a name in its scope (assignment target, parameter, loop or with/except variable, def/class name).
199
+ // A keyword argument name is neither a store nor a use.
200
+ function storeScope(node) {
201
+ const parent = node.parent;
202
+ if (!parent)
203
+ return { store: false, scope: null };
204
+ if ((parent.type === 'function_definition' || parent.type === 'class_definition') && parent.childForFieldName('name')?.equals(node)) {
205
+ return { store: true, scope: nearestPyScope(parent) };
206
+ }
207
+ let current = node;
208
+ for (let p = current.parent; p; p = current.parent) {
209
+ if (PATTERN_WRAPPERS.has(p.type)) {
210
+ current = p;
211
+ continue;
212
+ }
213
+ if (p.type === 'assignment' || p.type === 'for_statement' || p.type === 'for_in_clause') {
214
+ return { store: p.childForFieldName('left')?.equals(current) === true, scope: nearestPyScope(p) };
215
+ }
216
+ if (p.type === 'as_pattern_target' || (p.type === 'as_pattern' && p.childForFieldName('alias')?.equals(current)))
217
+ return { store: true, scope: nearestPyScope(p) };
218
+ if (p.type === 'named_expression')
219
+ return { store: p.childForFieldName('name')?.equals(current) === true, scope: walrusScope(p) };
220
+ if (PARAM_PARENTS.has(p.type)) {
221
+ const bound = p.type === 'parameters' || p.type === 'lambda_parameters' || p.childForFieldName('name')?.equals(current) === true || p.firstNamedChild?.equals(current) === true;
222
+ return { store: bound, scope: nearestPyScope(p) };
223
+ }
224
+ return { store: false, scope: null };
225
+ }
226
+ return { store: false, scope: null };
227
+ }
228
+ function isKeywordName(node) {
229
+ return node.parent?.type === 'keyword_argument' && node.parent.childForFieldName('name')?.equals(node) === true;
230
+ }
231
+ function findUnused(root, bindings, importRanges) {
232
+ if (bindings.length === 0)
233
+ return [];
234
+ const wanted = new Set(bindings.map((b) => b.local));
235
+ const locals = new Map();
236
+ // Names bound in a class body, with where they are first bound: a read later in the same body sees the class
237
+ // attribute, a read inside a method skips the class scope and sees the module.
238
+ const classBound = new Map();
239
+ const loads = [];
240
+ for (const node of root.descendantsOfType('identifier')) {
241
+ if (!node || within(node.startIndex, importRanges))
242
+ continue;
243
+ const { store, scope } = storeScope(node);
244
+ if (store) {
245
+ if (scope && scope.type !== 'class_definition') {
246
+ const names = locals.get(scope.id) ?? new Set();
247
+ names.add(node.text);
248
+ locals.set(scope.id, names);
249
+ }
250
+ else if (scope) {
251
+ const bound = classBound.get(scope.id) ?? new Map();
252
+ if (!bound.has(node.text))
253
+ bound.set(node.text, node.startIndex);
254
+ classBound.set(scope.id, bound);
255
+ }
256
+ continue;
257
+ }
258
+ if (wanted.has(node.text) && !isKeywordName(node))
259
+ loads.push(node);
260
+ }
261
+ // `global x` / `nonlocal x` make the name refer to the outer binding again.
262
+ for (const statement of root.descendantsOfType(['global_statement', 'nonlocal_statement'])) {
263
+ if (!statement)
264
+ continue;
265
+ const scope = nearestPyScope(statement);
266
+ for (const id of kids(statement))
267
+ locals.get(scope?.id ?? -1)?.delete(id.text);
268
+ }
269
+ const used = new Set();
270
+ for (const node of loads) {
271
+ let shadowed = false;
272
+ const nearest = nearestPyScope(node);
273
+ if (nearest?.type === 'class_definition' && (classBound.get(nearest.id)?.get(node.text) ?? Infinity) < node.startIndex)
274
+ shadowed = true;
275
+ for (let scope = nearest; scope && !shadowed; scope = nearestPyScope(scope)) {
276
+ if (scope.type !== 'class_definition' && locals.get(scope.id)?.has(node.text)) {
277
+ shadowed = true;
278
+ break;
279
+ }
280
+ }
281
+ const isAttributeName = node.parent?.type === 'attribute' && node.parent.childForFieldName('attribute')?.equals(node);
282
+ if (!shadowed && !isAttributeName)
283
+ used.add(node.text);
284
+ }
285
+ // Quoted annotations ("Foo") and __all__ entries reference names without an identifier node.
286
+ for (const node of root.descendantsOfType('string')) {
287
+ if (!node)
288
+ continue;
289
+ const exportsList = node.parent?.parent?.type === 'assignment' && text(node.parent.parent.childForFieldName('left')) === '__all__';
290
+ if (!insideAnnotation(node) && !exportsList)
291
+ continue;
292
+ for (const word of node.text.match(WORD) ?? [])
293
+ used.add(word);
294
+ }
295
+ return bindings
296
+ .filter((b) => !b.intentional && !used.has(b.local))
297
+ .map((b) => ({ name: b.local, source: b.source, line: b.line }));
298
+ }
@@ -0,0 +1,92 @@
1
+ import { compareText } from '../../utils/text.js';
2
+ // Iterative Tarjan: dependency graphs can be deep enough to overflow a recursive implementation.
3
+ export function stronglyConnected(nodes, adjacency) {
4
+ const index = new Map();
5
+ const low = new Map();
6
+ const onStack = new Set();
7
+ const stack = [];
8
+ const components = [];
9
+ let counter = 0;
10
+ const visit = (node) => {
11
+ index.set(node, counter);
12
+ low.set(node, counter);
13
+ counter++;
14
+ stack.push(node);
15
+ onStack.add(node);
16
+ };
17
+ for (const start of nodes) {
18
+ if (index.has(start))
19
+ continue;
20
+ const frames = [{ node: start, next: 0 }];
21
+ visit(start);
22
+ while (frames.length > 0) {
23
+ const frame = frames[frames.length - 1];
24
+ const out = adjacency.get(frame.node) ?? [];
25
+ if (frame.next < out.length) {
26
+ const target = out[frame.next++];
27
+ if (!index.has(target)) {
28
+ visit(target);
29
+ frames.push({ node: target, next: 0 });
30
+ }
31
+ else if (onStack.has(target)) {
32
+ low.set(frame.node, Math.min(low.get(frame.node) ?? 0, index.get(target) ?? 0));
33
+ }
34
+ continue;
35
+ }
36
+ frames.pop();
37
+ if (low.get(frame.node) === index.get(frame.node)) {
38
+ const component = [];
39
+ let member;
40
+ do {
41
+ member = stack.pop();
42
+ if (member === undefined)
43
+ break;
44
+ onStack.delete(member);
45
+ component.push(member);
46
+ } while (member !== frame.node);
47
+ components.push(component.sort(compareText));
48
+ }
49
+ const parent = frames[frames.length - 1];
50
+ if (parent)
51
+ low.set(parent.node, Math.min(low.get(parent.node) ?? 0, low.get(frame.node) ?? 0));
52
+ }
53
+ }
54
+ return components;
55
+ }
56
+ function shortestCycle(start, members, adjacency) {
57
+ const previous = new Map();
58
+ const queue = [];
59
+ for (const next of adjacency.get(start) ?? []) {
60
+ if (members.has(next) && !previous.has(next)) {
61
+ previous.set(next, start);
62
+ queue.push(next);
63
+ }
64
+ }
65
+ for (let head = 0; head < queue.length; head++) {
66
+ const node = queue[head];
67
+ if (node === start)
68
+ break;
69
+ for (const next of adjacency.get(node) ?? []) {
70
+ if (members.has(next) && !previous.has(next)) {
71
+ previous.set(next, node);
72
+ queue.push(next);
73
+ }
74
+ }
75
+ }
76
+ const chain = [];
77
+ for (let node = previous.get(start); node !== undefined && node !== start; node = previous.get(node))
78
+ chain.unshift(node);
79
+ return [start, ...chain, start];
80
+ }
81
+ export function findCycles(nodes, edges) {
82
+ const sorted = [...nodes].sort(compareText);
83
+ const adjacency = new Map();
84
+ for (const [node, targets] of edges)
85
+ adjacency.set(node, [...new Set(targets)].sort(compareText));
86
+ // A strongly connected component of one file is a cycle only when that file imports itself.
87
+ const isCycle = (component) => component.length > 1 || (adjacency.get(component[0]) ?? []).includes(component[0]);
88
+ return stronglyConnected(sorted, adjacency)
89
+ .filter(isCycle)
90
+ .map((modules) => ({ modules, path: shortestCycle(modules[0], new Set(modules), adjacency) }))
91
+ .sort((a, b) => compareText(a.modules[0], b.modules[0]));
92
+ }