jev-codeguard 0.0.0-stage → 1.1.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.
- package/LICENSE +21 -0
- package/README.md +364 -2
- package/THIRD_PARTY_NOTICES.md +25 -0
- package/dist/src/cli/hook-runner.d.ts +27 -0
- package/dist/src/cli/hook-runner.js +196 -0
- package/dist/src/cli/hook-runner.js.map +1 -0
- package/dist/src/cli/index.d.ts +2 -0
- package/dist/src/cli/index.js +173 -0
- package/dist/src/cli/index.js.map +1 -0
- package/dist/src/cli/setup.d.ts +14 -0
- package/dist/src/cli/setup.js +122 -0
- package/dist/src/cli/setup.js.map +1 -0
- package/dist/src/core/cache.d.ts +16 -0
- package/dist/src/core/cache.js +64 -0
- package/dist/src/core/cache.js.map +1 -0
- package/dist/src/core/command-shape.d.ts +17 -0
- package/dist/src/core/command-shape.js +138 -0
- package/dist/src/core/command-shape.js.map +1 -0
- package/dist/src/core/context-enricher.d.ts +149 -0
- package/dist/src/core/context-enricher.js +1397 -0
- package/dist/src/core/context-enricher.js.map +1 -0
- package/dist/src/core/event-log.d.ts +35 -0
- package/dist/src/core/event-log.js +241 -0
- package/dist/src/core/event-log.js.map +1 -0
- package/dist/src/core/git-collector.d.ts +18 -0
- package/dist/src/core/git-collector.js +227 -0
- package/dist/src/core/git-collector.js.map +1 -0
- package/dist/src/core/hybrid-ast-engine.d.ts +46 -0
- package/dist/src/core/hybrid-ast-engine.js +641 -0
- package/dist/src/core/hybrid-ast-engine.js.map +1 -0
- package/dist/src/core/jev-client.d.ts +50 -0
- package/dist/src/core/jev-client.js +262 -0
- package/dist/src/core/jev-client.js.map +1 -0
- package/dist/src/core/policy-config.d.ts +96 -0
- package/dist/src/core/policy-config.js +60 -0
- package/dist/src/core/policy-config.js.map +1 -0
- package/dist/src/core/policy-engine.d.ts +65 -0
- package/dist/src/core/policy-engine.js +344 -0
- package/dist/src/core/policy-engine.js.map +1 -0
- package/dist/src/core/presets.d.ts +18 -0
- package/dist/src/core/presets.js +180 -0
- package/dist/src/core/presets.js.map +1 -0
- package/dist/src/core/skill-auditor.d.ts +56 -0
- package/dist/src/core/skill-auditor.js +435 -0
- package/dist/src/core/skill-auditor.js.map +1 -0
- package/dist/src/core/telemetry.d.ts +30 -0
- package/dist/src/core/telemetry.js +55 -0
- package/dist/src/core/telemetry.js.map +1 -0
- package/dist/src/core/types.d.ts +89 -0
- package/dist/src/core/types.js +2 -0
- package/dist/src/core/types.js.map +1 -0
- package/dist/src/dashboard/server.d.ts +9 -0
- package/dist/src/dashboard/server.js +2425 -0
- package/dist/src/dashboard/server.js.map +1 -0
- package/dist/src/mcp/server.d.ts +137 -0
- package/dist/src/mcp/server.js +875 -0
- package/dist/src/mcp/server.js.map +1 -0
- package/package.json +75 -4
- package/skills/jev-system-one/SKILL.md +54 -0
- package/skills/vendor/codebase-design/DEEPENING.md +37 -0
- package/skills/vendor/codebase-design/DESIGN-IT-TWICE.md +44 -0
- package/skills/vendor/codebase-design/LICENSE +21 -0
- package/skills/vendor/codebase-design/SKILL.md +114 -0
- package/skills/vendor/gsap-performance/LICENSE +21 -0
- package/skills/vendor/gsap-performance/SKILL.md +79 -0
- package/skills/vendor/manifest.json +122 -0
- package/skills/vendor/security-best-practices/LICENSE.txt +201 -0
- package/skills/vendor/security-best-practices/SKILL.md +86 -0
- package/skills/vendor/security-best-practices/references/golang-general-backend-security.md +826 -0
- package/skills/vendor/security-best-practices/references/javascript-express-web-server-security.md +1158 -0
- package/skills/vendor/security-best-practices/references/javascript-general-web-frontend-security.md +747 -0
- package/skills/vendor/security-best-practices/references/javascript-jquery-web-frontend-security.md +678 -0
- package/skills/vendor/security-best-practices/references/javascript-typescript-nextjs-web-server-security.md +1144 -0
- package/skills/vendor/security-best-practices/references/javascript-typescript-react-web-frontend-security.md +990 -0
- package/skills/vendor/security-best-practices/references/javascript-typescript-vue-web-frontend-security.md +791 -0
- package/skills/vendor/security-best-practices/references/python-django-web-server-security.md +882 -0
- package/skills/vendor/security-best-practices/references/python-fastapi-web-server-security.md +1036 -0
- package/skills/vendor/security-best-practices/references/python-flask-web-server-security.md +705 -0
|
@@ -0,0 +1,641 @@
|
|
|
1
|
+
import { execFileSync, spawn } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import path from "node:path";
|
|
4
|
+
import { fileURLToPath } from "node:url";
|
|
5
|
+
import { Project, SyntaxKind } from "ts-morph";
|
|
6
|
+
import { z } from "zod";
|
|
7
|
+
import { isSensitiveFilePath, isWithinWorkspaceBoundary, resolvePythonExecutable } from "./context-enricher.js";
|
|
8
|
+
const MAX_AST_FILE_BYTES = 512 * 1024;
|
|
9
|
+
const MAX_ANALYZED_FILES = 64;
|
|
10
|
+
const SafeFileListSchema = z.array(z.string().min(1).max(512)).max(MAX_ANALYZED_FILES);
|
|
11
|
+
const tsMorphProject = new Project({
|
|
12
|
+
skipAddingFilesFromTsConfig: true,
|
|
13
|
+
skipFileDependencyResolution: true,
|
|
14
|
+
compilerOptions: {
|
|
15
|
+
allowJs: true,
|
|
16
|
+
checkJs: false,
|
|
17
|
+
noEmit: true,
|
|
18
|
+
target: 99 // ESNext
|
|
19
|
+
}
|
|
20
|
+
});
|
|
21
|
+
const autoInitTriggeredWorkspaces = new Set();
|
|
22
|
+
function parseChangedLinesByFile(rawDiff) {
|
|
23
|
+
const map = new Map();
|
|
24
|
+
if (!rawDiff || !rawDiff.trim())
|
|
25
|
+
return map;
|
|
26
|
+
const chunks = rawDiff
|
|
27
|
+
.split(/(?=^diff --git )/m)
|
|
28
|
+
.map((c) => c.trim())
|
|
29
|
+
.filter(Boolean);
|
|
30
|
+
for (const chunk of chunks) {
|
|
31
|
+
const fileMatch = chunk.match(/^diff --git a\/.+? b\/([^\r\n\t]+)$/m) ??
|
|
32
|
+
chunk.match(/^\+\+\+ b\/([^\r\n\t]+)$/m);
|
|
33
|
+
const file = fileMatch ? fileMatch[1].trim() : "";
|
|
34
|
+
if (!file)
|
|
35
|
+
continue;
|
|
36
|
+
const lines = [];
|
|
37
|
+
for (const m of chunk.matchAll(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s*@@/gm)) {
|
|
38
|
+
const start = parseInt(m[1], 10);
|
|
39
|
+
const count = m[2] !== undefined ? parseInt(m[2], 10) : 1;
|
|
40
|
+
lines.push(start, start + Math.max(0, Math.floor(count / 2)));
|
|
41
|
+
}
|
|
42
|
+
if (lines.length > 0) {
|
|
43
|
+
map.set(file.replace(/\\/g, "/"), lines);
|
|
44
|
+
}
|
|
45
|
+
}
|
|
46
|
+
return map;
|
|
47
|
+
}
|
|
48
|
+
/**
|
|
49
|
+
* Uses `ts-morph` (TypeScript Compiler AST) for `.ts/.tsx/.js/.jsx` and Python's native `ast` module
|
|
50
|
+
* for `.py` to extract 100% accurate AST symbol signatures, return types, decorators, and enclosing AST nodes.
|
|
51
|
+
*/
|
|
52
|
+
export function extractHybridAstSkeletons(cwd, changedFiles, rawDiff = "", maxFiles = 8) {
|
|
53
|
+
const resolvedCwd = path.resolve(z.string().min(1).max(1024).parse(cwd));
|
|
54
|
+
const boundedFiles = SafeFileListSchema.parse(changedFiles.slice(0, MAX_ANALYZED_FILES));
|
|
55
|
+
const boundedMaxFiles = Math.max(1, Math.min(maxFiles, 16));
|
|
56
|
+
const changedLinesMap = parseChangedLinesByFile(rawDiff.slice(0, 120_000));
|
|
57
|
+
const skeletons = [];
|
|
58
|
+
const tsJsFiles = [];
|
|
59
|
+
const pyFiles = [];
|
|
60
|
+
for (const rel of boundedFiles) {
|
|
61
|
+
if (tsJsFiles.length + pyFiles.length >= boundedMaxFiles)
|
|
62
|
+
break;
|
|
63
|
+
const norm = rel.replace(/\\/g, "/");
|
|
64
|
+
const full = path.isAbsolute(rel) ? rel : path.join(resolvedCwd, rel);
|
|
65
|
+
if (isSensitiveFilePath(full) || !isWithinWorkspaceBoundary(resolvedCwd, full))
|
|
66
|
+
continue;
|
|
67
|
+
if (!fs.existsSync(full))
|
|
68
|
+
continue;
|
|
69
|
+
const stat = fs.statSync(full);
|
|
70
|
+
if (!stat.isFile() || stat.size > MAX_AST_FILE_BYTES)
|
|
71
|
+
continue;
|
|
72
|
+
if (/\.(ts|tsx|js|jsx|mjs)$/i.test(norm)) {
|
|
73
|
+
tsJsFiles.push(norm);
|
|
74
|
+
}
|
|
75
|
+
else if (/\.py$/i.test(norm)) {
|
|
76
|
+
pyFiles.push(norm);
|
|
77
|
+
}
|
|
78
|
+
}
|
|
79
|
+
// 1. Parse TypeScript / JavaScript files via ts-morph AST
|
|
80
|
+
for (const relFile of tsJsFiles) {
|
|
81
|
+
const fullPath = path.isAbsolute(relFile) ? relFile : path.join(resolvedCwd, relFile);
|
|
82
|
+
try {
|
|
83
|
+
const content = fs.readFileSync(fullPath, "utf8");
|
|
84
|
+
const sourceFile = tsMorphProject.createSourceFile(fullPath, content, { overwrite: true });
|
|
85
|
+
const imports = sourceFile
|
|
86
|
+
.getImportDeclarations()
|
|
87
|
+
.slice(0, 12)
|
|
88
|
+
.map((imp) => {
|
|
89
|
+
const spec = imp.getModuleSpecifierValue();
|
|
90
|
+
const named = imp
|
|
91
|
+
.getNamedImports()
|
|
92
|
+
.map((n) => n.getName())
|
|
93
|
+
.slice(0, 6)
|
|
94
|
+
.join(", ");
|
|
95
|
+
const def = imp.getDefaultImport()?.getText();
|
|
96
|
+
return `${def ? `${def} ` : ""}${named ? `{ ${named} } ` : ""}from "${spec}"`.trim();
|
|
97
|
+
});
|
|
98
|
+
const exportedSignatures = [];
|
|
99
|
+
for (const fn of sourceFile.getFunctions()) {
|
|
100
|
+
if (fn.isExported() || exportedSignatures.length < 10) {
|
|
101
|
+
const name = fn.getName() ?? "anonymous";
|
|
102
|
+
const params = fn
|
|
103
|
+
.getParameters()
|
|
104
|
+
.map((p) => p.getText())
|
|
105
|
+
.join(", ");
|
|
106
|
+
const ret = fn.getReturnTypeNode()?.getText() ?? "";
|
|
107
|
+
const asyncPrefix = fn.isAsync() ? "async " : "";
|
|
108
|
+
exportedSignatures.push(`L${fn.getStartLineNumber()}: ${fn.isExported() ? "export " : ""}${asyncPrefix}function ${name}(${params})${ret ? `: ${ret}` : ""}`);
|
|
109
|
+
}
|
|
110
|
+
}
|
|
111
|
+
for (const cls of sourceFile.getClasses()) {
|
|
112
|
+
const name = cls.getName() ?? "AnonymousClass";
|
|
113
|
+
const methods = cls
|
|
114
|
+
.getMethods()
|
|
115
|
+
.slice(0, 8)
|
|
116
|
+
.map((m) => `${m.getName()}(${m.getParameters().map((p) => p.getName()).join(", ")})`)
|
|
117
|
+
.join("; ");
|
|
118
|
+
exportedSignatures.push(`L${cls.getStartLineNumber()}: class ${name} { ${methods} }`);
|
|
119
|
+
}
|
|
120
|
+
for (const iface of sourceFile.getInterfaces()) {
|
|
121
|
+
const name = iface.getName();
|
|
122
|
+
const props = iface
|
|
123
|
+
.getProperties()
|
|
124
|
+
.slice(0, 10)
|
|
125
|
+
.map((p) => `${p.getName()}${p.hasQuestionToken() ? "?" : ""}: ${p.getTypeNode()?.getText() ?? "any"}`)
|
|
126
|
+
.join("; ");
|
|
127
|
+
exportedSignatures.push(`L${iface.getStartLineNumber()}: interface ${name} { ${props} }`);
|
|
128
|
+
}
|
|
129
|
+
for (const typeAlias of sourceFile.getTypeAliases()) {
|
|
130
|
+
const name = typeAlias.getName();
|
|
131
|
+
const typeText = (typeAlias.getTypeNode()?.getText() ?? "").replace(/\s+/g, " ").slice(0, 120);
|
|
132
|
+
exportedSignatures.push(`L${typeAlias.getStartLineNumber()}: type ${name} = ${typeText}`);
|
|
133
|
+
}
|
|
134
|
+
// Locate exact AST enclosing nodes for modified lines in git diff
|
|
135
|
+
const targetLines = changedLinesMap.get(relFile) ?? [];
|
|
136
|
+
const enclosingModifiedNodes = [];
|
|
137
|
+
const callableNodes = [
|
|
138
|
+
...sourceFile.getDescendantsOfKind(SyntaxKind.FunctionDeclaration),
|
|
139
|
+
...sourceFile.getDescendantsOfKind(SyntaxKind.MethodDeclaration),
|
|
140
|
+
...sourceFile.getDescendantsOfKind(SyntaxKind.ClassDeclaration)
|
|
141
|
+
];
|
|
142
|
+
for (const lineNum of targetLines) {
|
|
143
|
+
for (const node of callableNodes) {
|
|
144
|
+
const startL = node.getStartLineNumber();
|
|
145
|
+
const endL = node.getEndLineNumber();
|
|
146
|
+
if (lineNum >= startL && lineNum <= endL) {
|
|
147
|
+
const headerLine = node.getText().split(/\r?\n/)[0]?.trim().slice(0, 140) ?? "";
|
|
148
|
+
const label = `L${startL}-L${endL}: ${headerLine}`;
|
|
149
|
+
if (headerLine && !enclosingModifiedNodes.includes(label)) {
|
|
150
|
+
enclosingModifiedNodes.push(label);
|
|
151
|
+
}
|
|
152
|
+
}
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
skeletons.push({
|
|
156
|
+
file: relFile,
|
|
157
|
+
language: /\.tsx?$/i.test(relFile) ? "typescript" : "javascript",
|
|
158
|
+
imports: imports.slice(0, 10),
|
|
159
|
+
exportedSignatures: exportedSignatures.slice(0, 16),
|
|
160
|
+
enclosingModifiedNodes: enclosingModifiedNodes.slice(0, 6)
|
|
161
|
+
});
|
|
162
|
+
tsMorphProject.removeSourceFile(sourceFile);
|
|
163
|
+
}
|
|
164
|
+
catch {
|
|
165
|
+
// ignore AST parse failure on partial file
|
|
166
|
+
}
|
|
167
|
+
}
|
|
168
|
+
// 2. Parse Python files via Python's built-in `ast` module
|
|
169
|
+
if (pyFiles.length > 0) {
|
|
170
|
+
const pyScript = `
|
|
171
|
+
import ast, json, sys
|
|
172
|
+
out = []
|
|
173
|
+
for rel, full, lines in json.loads(sys.argv[1]):
|
|
174
|
+
try:
|
|
175
|
+
src = open(full, 'r', encoding='utf-8').read()
|
|
176
|
+
tree = ast.parse(src, filename=rel)
|
|
177
|
+
imports, sigs, enclosing = [], [], []
|
|
178
|
+
for node in ast.walk(tree):
|
|
179
|
+
if isinstance(node, ast.ImportFrom) and node.module:
|
|
180
|
+
names = ", ".join(a.name for a in node.names[:5])
|
|
181
|
+
imports.append(f"from {node.module} import {names}")
|
|
182
|
+
elif isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
|
|
183
|
+
decs = [f"@{ast.unparse(d)}" for d in node.decorator_list[:2]] if hasattr(ast, 'unparse') else []
|
|
184
|
+
args = ", ".join(a.arg for a in node.args.args[:6])
|
|
185
|
+
ret = f" -> {ast.unparse(node.returns)}" if getattr(node, 'returns', None) and hasattr(ast, 'unparse') else ""
|
|
186
|
+
prefix = "async def" if isinstance(node, ast.AsyncFunctionDef) else "def"
|
|
187
|
+
sig = f"L{node.lineno}: {' '.join(decs)} {prefix} {node.name}({args}){ret}".strip()
|
|
188
|
+
sigs.append(sig)
|
|
189
|
+
end_l = getattr(node, 'end_lineno', node.lineno + 15)
|
|
190
|
+
for ln in lines:
|
|
191
|
+
if node.lineno <= ln <= end_l:
|
|
192
|
+
enclosing.append(f"L{node.lineno}-L{end_l}: {sig}")
|
|
193
|
+
elif isinstance(node, ast.ClassDef):
|
|
194
|
+
bases = ", ".join(ast.unparse(b) for b in node.bases) if hasattr(ast, 'unparse') else ""
|
|
195
|
+
sigs.append(f"L{node.lineno}: class {node.name}({bases})")
|
|
196
|
+
out.append({"file": rel, "imports": imports[:10], "sigs": sigs[:16], "enclosing": list(dict.fromkeys(enclosing))[:6]})
|
|
197
|
+
except Exception:
|
|
198
|
+
pass
|
|
199
|
+
print(json.dumps(out))
|
|
200
|
+
`.trim();
|
|
201
|
+
const pyTargets = pyFiles.map((rel) => [
|
|
202
|
+
rel,
|
|
203
|
+
path.isAbsolute(rel) ? rel : path.join(resolvedCwd, rel),
|
|
204
|
+
changedLinesMap.get(rel) ?? []
|
|
205
|
+
]);
|
|
206
|
+
try {
|
|
207
|
+
const stdout = execFileSync(resolvePythonExecutable(), ["-c", pyScript, JSON.stringify(pyTargets)], {
|
|
208
|
+
cwd: resolvedCwd,
|
|
209
|
+
encoding: "utf8",
|
|
210
|
+
timeout: 1200,
|
|
211
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
212
|
+
}).trim();
|
|
213
|
+
const parsed = JSON.parse(stdout);
|
|
214
|
+
for (const item of parsed) {
|
|
215
|
+
skeletons.push({
|
|
216
|
+
file: item.file,
|
|
217
|
+
language: "python",
|
|
218
|
+
imports: item.imports,
|
|
219
|
+
exportedSignatures: item.sigs,
|
|
220
|
+
enclosingModifiedNodes: item.enclosing
|
|
221
|
+
});
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
catch {
|
|
225
|
+
// ignore if python unavailable
|
|
226
|
+
}
|
|
227
|
+
}
|
|
228
|
+
return skeletons;
|
|
229
|
+
}
|
|
230
|
+
function resolveLocalOxlintRunner() {
|
|
231
|
+
const selfDir = path.dirname(fileURLToPath(import.meta.url));
|
|
232
|
+
const scriptCandidates = [
|
|
233
|
+
path.resolve(process.cwd(), "node_modules", "oxlint", "bin", "oxlint"),
|
|
234
|
+
path.resolve(selfDir, "..", "..", "..", "node_modules", "oxlint", "bin", "oxlint"),
|
|
235
|
+
path.resolve(selfDir, "..", "..", "node_modules", "oxlint", "bin", "oxlint")
|
|
236
|
+
];
|
|
237
|
+
for (const scriptPath of scriptCandidates) {
|
|
238
|
+
if (fs.existsSync(scriptPath)) {
|
|
239
|
+
return { cmd: process.execPath, prefixArgs: [scriptPath] };
|
|
240
|
+
}
|
|
241
|
+
}
|
|
242
|
+
if (process.platform !== "win32") {
|
|
243
|
+
const posixBin = path.resolve(process.cwd(), "node_modules", ".bin", "oxlint");
|
|
244
|
+
if (fs.existsSync(posixBin)) {
|
|
245
|
+
return { cmd: posixBin, prefixArgs: [] };
|
|
246
|
+
}
|
|
247
|
+
}
|
|
248
|
+
return undefined;
|
|
249
|
+
}
|
|
250
|
+
let cachedCodeGraphRunner;
|
|
251
|
+
/**
|
|
252
|
+
* Resolves `codegraph` to a direct executable or Node entrypoint so child processes
|
|
253
|
+
* NEVER require `shell: true` (eliminating cmd.exe / shell metacharacter injection).
|
|
254
|
+
*/
|
|
255
|
+
function resolveCodeGraphRunner() {
|
|
256
|
+
if (cachedCodeGraphRunner !== undefined) {
|
|
257
|
+
return cachedCodeGraphRunner;
|
|
258
|
+
}
|
|
259
|
+
if (process.platform !== "win32") {
|
|
260
|
+
try {
|
|
261
|
+
const whichOut = execFileSync("which", ["codegraph"], {
|
|
262
|
+
encoding: "utf8",
|
|
263
|
+
timeout: 600,
|
|
264
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
265
|
+
}).trim();
|
|
266
|
+
if (whichOut && fs.existsSync(whichOut)) {
|
|
267
|
+
cachedCodeGraphRunner = { cmd: whichOut, prefixArgs: [] };
|
|
268
|
+
return cachedCodeGraphRunner;
|
|
269
|
+
}
|
|
270
|
+
}
|
|
271
|
+
catch {
|
|
272
|
+
// codegraph not installed on POSIX host
|
|
273
|
+
}
|
|
274
|
+
cachedCodeGraphRunner = null;
|
|
275
|
+
return null;
|
|
276
|
+
}
|
|
277
|
+
const jsCandidates = [
|
|
278
|
+
path.resolve(process.cwd(), "node_modules", "@colbymchenry", "codegraph", "dist", "bin", "codegraph.js")
|
|
279
|
+
];
|
|
280
|
+
if (process.env.APPDATA) {
|
|
281
|
+
jsCandidates.push(path.join(process.env.APPDATA, "npm", "node_modules", "@colbymchenry", "codegraph", "dist", "bin", "codegraph.js"));
|
|
282
|
+
}
|
|
283
|
+
for (const jsPath of jsCandidates) {
|
|
284
|
+
if (fs.existsSync(jsPath)) {
|
|
285
|
+
cachedCodeGraphRunner = { cmd: process.execPath, prefixArgs: [jsPath] };
|
|
286
|
+
return cachedCodeGraphRunner;
|
|
287
|
+
}
|
|
288
|
+
}
|
|
289
|
+
try {
|
|
290
|
+
const whereOut = execFileSync("where.exe", ["codegraph"], {
|
|
291
|
+
encoding: "utf8",
|
|
292
|
+
timeout: 800,
|
|
293
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
294
|
+
});
|
|
295
|
+
const matches = whereOut
|
|
296
|
+
.split(/\r?\n/)
|
|
297
|
+
.map((s) => s.trim())
|
|
298
|
+
.filter(Boolean);
|
|
299
|
+
const exeMatch = matches.find((m) => /\.exe$/i.test(m) && fs.existsSync(m));
|
|
300
|
+
if (exeMatch) {
|
|
301
|
+
cachedCodeGraphRunner = { cmd: exeMatch, prefixArgs: [] };
|
|
302
|
+
return cachedCodeGraphRunner;
|
|
303
|
+
}
|
|
304
|
+
const cmdMatch = matches.find((m) => /\.cmd$/i.test(m) && fs.existsSync(m));
|
|
305
|
+
if (cmdMatch) {
|
|
306
|
+
const shimText = fs.readFileSync(cmdMatch, "utf8");
|
|
307
|
+
const relMatch = shimText.match(/%dp0%\\(node_modules\\[^"\r\n]+\.js)/i);
|
|
308
|
+
if (relMatch) {
|
|
309
|
+
const resolvedJs = path.join(path.dirname(cmdMatch), relMatch[1]);
|
|
310
|
+
if (fs.existsSync(resolvedJs)) {
|
|
311
|
+
cachedCodeGraphRunner = { cmd: process.execPath, prefixArgs: [resolvedJs] };
|
|
312
|
+
return cachedCodeGraphRunner;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
}
|
|
316
|
+
}
|
|
317
|
+
catch {
|
|
318
|
+
// codegraph not installed
|
|
319
|
+
}
|
|
320
|
+
cachedCodeGraphRunner = null;
|
|
321
|
+
return null;
|
|
322
|
+
}
|
|
323
|
+
/**
|
|
324
|
+
* Runs ultra-fast Rust static analyzers (`oxlint` >14k ⭐ for JS/TS/React and `ruff` >36k ⭐ for Python + Bandit Security `S` rules)
|
|
325
|
+
* plus `ts-morph` AST syntax diagnostics on modified files in < 1.2s.
|
|
326
|
+
*/
|
|
327
|
+
export function runHybridStaticAnalysis(cwd, changedFiles) {
|
|
328
|
+
const resolvedCwd = path.resolve(z.string().min(1).max(1024).parse(cwd));
|
|
329
|
+
const boundedFiles = SafeFileListSchema.parse(changedFiles.slice(0, MAX_ANALYZED_FILES));
|
|
330
|
+
const checkedFiles = [];
|
|
331
|
+
const enginesUsed = new Set();
|
|
332
|
+
const diagnostics = [];
|
|
333
|
+
const jsTsTargets = [];
|
|
334
|
+
const pyTargets = [];
|
|
335
|
+
for (const rel of boundedFiles.slice(0, 10)) {
|
|
336
|
+
const fullPath = path.isAbsolute(rel) ? rel : path.join(resolvedCwd, rel);
|
|
337
|
+
if (isSensitiveFilePath(fullPath) || !isWithinWorkspaceBoundary(resolvedCwd, fullPath)) {
|
|
338
|
+
continue;
|
|
339
|
+
}
|
|
340
|
+
if (!fs.existsSync(fullPath))
|
|
341
|
+
continue;
|
|
342
|
+
const stat = fs.statSync(fullPath);
|
|
343
|
+
if (!stat.isFile() || stat.size > MAX_AST_FILE_BYTES)
|
|
344
|
+
continue;
|
|
345
|
+
if (rel.endsWith(".json")) {
|
|
346
|
+
checkedFiles.push(rel);
|
|
347
|
+
enginesUsed.add("json-parser");
|
|
348
|
+
try {
|
|
349
|
+
JSON.parse(fs.readFileSync(fullPath, "utf8"));
|
|
350
|
+
}
|
|
351
|
+
catch (err) {
|
|
352
|
+
diagnostics.push({
|
|
353
|
+
engine: "json",
|
|
354
|
+
file: rel,
|
|
355
|
+
severity: "error",
|
|
356
|
+
code: "JSON_SYNTAX",
|
|
357
|
+
message: err instanceof Error ? err.message : "Invalid JSON syntax"
|
|
358
|
+
});
|
|
359
|
+
}
|
|
360
|
+
}
|
|
361
|
+
else if (/\.(ts|tsx|js|jsx|mjs)$/i.test(rel)) {
|
|
362
|
+
checkedFiles.push(rel);
|
|
363
|
+
jsTsTargets.push(fullPath);
|
|
364
|
+
// Fast in-memory ts-morph syntax parse check
|
|
365
|
+
try {
|
|
366
|
+
const content = fs.readFileSync(fullPath, "utf8");
|
|
367
|
+
const sf = tsMorphProject.createSourceFile(fullPath, content, { overwrite: true });
|
|
368
|
+
enginesUsed.add("ts-morph-ast");
|
|
369
|
+
const syntaxDiags = sf.getPreEmitDiagnostics().filter((d) => d.getCategory() === 1 && d.getCode() < 2000);
|
|
370
|
+
for (const d of syntaxDiags.slice(0, 4)) {
|
|
371
|
+
const msg = d.getMessageText();
|
|
372
|
+
diagnostics.push({
|
|
373
|
+
engine: "ts-morph",
|
|
374
|
+
file: rel,
|
|
375
|
+
line: d.getLineNumber(),
|
|
376
|
+
severity: "error",
|
|
377
|
+
code: `TS${d.getCode()}`,
|
|
378
|
+
message: typeof msg === "string" ? msg : msg.getMessageText()
|
|
379
|
+
});
|
|
380
|
+
}
|
|
381
|
+
tsMorphProject.removeSourceFile(sf);
|
|
382
|
+
}
|
|
383
|
+
catch {
|
|
384
|
+
// ignore
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
else if (/\.py$/i.test(rel)) {
|
|
388
|
+
checkedFiles.push(rel);
|
|
389
|
+
pyTargets.push(fullPath);
|
|
390
|
+
}
|
|
391
|
+
}
|
|
392
|
+
// Run Oxlint (Rust JS/TS Linter) on modified JS/TS files with shell: false
|
|
393
|
+
if (jsTsTargets.length > 0) {
|
|
394
|
+
const oxlintRunner = resolveLocalOxlintRunner();
|
|
395
|
+
if (oxlintRunner) {
|
|
396
|
+
try {
|
|
397
|
+
const rawOut = execFileSync(oxlintRunner.cmd, [...oxlintRunner.prefixArgs, "--format", "json", ...jsTsTargets], {
|
|
398
|
+
cwd: resolvedCwd,
|
|
399
|
+
encoding: "utf8",
|
|
400
|
+
timeout: 1500,
|
|
401
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
402
|
+
}).trim();
|
|
403
|
+
enginesUsed.add("oxlint-rust");
|
|
404
|
+
parseOxlintJson(rawOut, resolvedCwd, diagnostics);
|
|
405
|
+
}
|
|
406
|
+
catch (err) {
|
|
407
|
+
enginesUsed.add("oxlint-rust");
|
|
408
|
+
if (err && typeof err === "object" && "stdout" in err && err.stdout) {
|
|
409
|
+
parseOxlintJson(String(err.stdout), resolvedCwd, diagnostics);
|
|
410
|
+
}
|
|
411
|
+
}
|
|
412
|
+
}
|
|
413
|
+
}
|
|
414
|
+
// Run Ruff (Astral Rust Python Linter respecting project config + ignoring S101 pytest assert false positives)
|
|
415
|
+
if (pyTargets.length > 0) {
|
|
416
|
+
try {
|
|
417
|
+
const rawOut = execFileSync(resolvePythonExecutable(), ["-m", "ruff", "check", "--ignore", "S101,E501", "--output-format", "json", ...pyTargets], {
|
|
418
|
+
cwd: resolvedCwd,
|
|
419
|
+
encoding: "utf8",
|
|
420
|
+
timeout: 1500,
|
|
421
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
422
|
+
}).trim();
|
|
423
|
+
enginesUsed.add("ruff-rust");
|
|
424
|
+
parseRuffJson(rawOut, resolvedCwd, diagnostics);
|
|
425
|
+
}
|
|
426
|
+
catch (err) {
|
|
427
|
+
if (err && typeof err === "object" && "stdout" in err && err.stdout) {
|
|
428
|
+
enginesUsed.add("ruff-rust");
|
|
429
|
+
parseRuffJson(String(err.stdout), resolvedCwd, diagnostics);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
if (checkedFiles.length === 0) {
|
|
434
|
+
return {
|
|
435
|
+
enginesUsed: [],
|
|
436
|
+
status: "SKIPPED",
|
|
437
|
+
checkedFiles: [],
|
|
438
|
+
errorCount: 0,
|
|
439
|
+
warningCount: 0,
|
|
440
|
+
diagnostics: []
|
|
441
|
+
};
|
|
442
|
+
}
|
|
443
|
+
const errorCount = diagnostics.filter((d) => d.severity === "error").length;
|
|
444
|
+
const warningCount = diagnostics.filter((d) => d.severity === "warning").length;
|
|
445
|
+
return {
|
|
446
|
+
enginesUsed: Array.from(enginesUsed),
|
|
447
|
+
status: errorCount > 0 ? "ERRORS_DETECTED" : warningCount > 0 ? "WARNINGS" : "CLEAN",
|
|
448
|
+
checkedFiles,
|
|
449
|
+
errorCount,
|
|
450
|
+
warningCount,
|
|
451
|
+
diagnostics: diagnostics.slice(0, 15)
|
|
452
|
+
};
|
|
453
|
+
}
|
|
454
|
+
function parseOxlintJson(rawJson, resolvedCwd, diagnostics) {
|
|
455
|
+
try {
|
|
456
|
+
const parsed = JSON.parse(rawJson);
|
|
457
|
+
const list = Array.isArray(parsed.diagnostics) ? parsed.diagnostics : [];
|
|
458
|
+
for (const item of list.slice(0, 10)) {
|
|
459
|
+
const rel = item.filename
|
|
460
|
+
? path.relative(resolvedCwd, item.filename).replace(/\\/g, "/")
|
|
461
|
+
: "unknown";
|
|
462
|
+
diagnostics.push({
|
|
463
|
+
engine: "oxlint",
|
|
464
|
+
file: rel,
|
|
465
|
+
line: item.labels?.[0]?.span?.line,
|
|
466
|
+
severity: item.severity === "error" ? "error" : "warning",
|
|
467
|
+
code: item.code ?? "oxlint",
|
|
468
|
+
message: (item.message ?? "").slice(0, 200)
|
|
469
|
+
});
|
|
470
|
+
}
|
|
471
|
+
}
|
|
472
|
+
catch {
|
|
473
|
+
// ignore malformed json
|
|
474
|
+
}
|
|
475
|
+
}
|
|
476
|
+
function parseRuffJson(rawJson, resolvedCwd, diagnostics) {
|
|
477
|
+
try {
|
|
478
|
+
const list = JSON.parse(rawJson);
|
|
479
|
+
if (!Array.isArray(list))
|
|
480
|
+
return;
|
|
481
|
+
for (const item of list.slice(0, 10)) {
|
|
482
|
+
const rel = item.filename
|
|
483
|
+
? path.relative(resolvedCwd, item.filename).replace(/\\/g, "/")
|
|
484
|
+
: "unknown";
|
|
485
|
+
const code = item.code ?? "RUFF";
|
|
486
|
+
const isError = code.startsWith("F") || code.startsWith("E9") || code.startsWith("S");
|
|
487
|
+
diagnostics.push({
|
|
488
|
+
engine: "ruff",
|
|
489
|
+
file: rel,
|
|
490
|
+
line: item.location?.row,
|
|
491
|
+
severity: isError ? "error" : "warning",
|
|
492
|
+
code,
|
|
493
|
+
message: (item.message ?? "").slice(0, 200)
|
|
494
|
+
});
|
|
495
|
+
}
|
|
496
|
+
}
|
|
497
|
+
catch {
|
|
498
|
+
// ignore malformed json
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
/**
|
|
502
|
+
* Integrates `codegraph` v0.8.0 (Tree-sitter Knowledge Graph):
|
|
503
|
+
* - Automatically initializes `.codegraph` in the background if missing on a Git repo.
|
|
504
|
+
* - Runs `codegraph sync`, `codegraph context`, and `codegraph affected --json` to retrieve
|
|
505
|
+
* graph-ranked context and affected test files across the dependency graph.
|
|
506
|
+
*/
|
|
507
|
+
export function queryCodeGraphIntelligence(cwd, taskOrSpec, changedFiles = []) {
|
|
508
|
+
const resolvedCwd = path.resolve(z.string().min(1).max(1024).parse(cwd));
|
|
509
|
+
const boundedTask = z.string().max(16000).parse(taskOrSpec.slice(0, 16000));
|
|
510
|
+
changedFiles = SafeFileListSchema.parse(changedFiles.slice(0, MAX_ANALYZED_FILES));
|
|
511
|
+
const cgDir = path.join(resolvedCwd, ".codegraph");
|
|
512
|
+
const cgRunner = resolveCodeGraphRunner();
|
|
513
|
+
if (!cgRunner) {
|
|
514
|
+
return {
|
|
515
|
+
indexed: false,
|
|
516
|
+
graphAffectedTests: [],
|
|
517
|
+
symbolRelations: []
|
|
518
|
+
};
|
|
519
|
+
}
|
|
520
|
+
if (!fs.existsSync(cgDir)) {
|
|
521
|
+
// Auto-initialize CodeGraph asynchronously in the background if this is a Git repo
|
|
522
|
+
if (fs.existsSync(path.join(resolvedCwd, ".git")) &&
|
|
523
|
+
!autoInitTriggeredWorkspaces.has(resolvedCwd)) {
|
|
524
|
+
autoInitTriggeredWorkspaces.add(resolvedCwd);
|
|
525
|
+
try {
|
|
526
|
+
const child = spawn(cgRunner.cmd, [...cgRunner.prefixArgs, "init", "-i", resolvedCwd], {
|
|
527
|
+
cwd: resolvedCwd,
|
|
528
|
+
detached: true,
|
|
529
|
+
stdio: "ignore"
|
|
530
|
+
});
|
|
531
|
+
child.on("error", () => { });
|
|
532
|
+
child.unref();
|
|
533
|
+
}
|
|
534
|
+
catch {
|
|
535
|
+
// non-fatal
|
|
536
|
+
}
|
|
537
|
+
}
|
|
538
|
+
return {
|
|
539
|
+
indexed: false,
|
|
540
|
+
graphAffectedTests: [],
|
|
541
|
+
symbolRelations: []
|
|
542
|
+
};
|
|
543
|
+
}
|
|
544
|
+
// Sync incremental changes since last index
|
|
545
|
+
try {
|
|
546
|
+
execFileSync(cgRunner.cmd, [...cgRunner.prefixArgs, "sync", resolvedCwd], {
|
|
547
|
+
cwd: resolvedCwd,
|
|
548
|
+
encoding: "utf8",
|
|
549
|
+
timeout: 1200,
|
|
550
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
551
|
+
});
|
|
552
|
+
}
|
|
553
|
+
catch {
|
|
554
|
+
// non-fatal if locked
|
|
555
|
+
}
|
|
556
|
+
const stripAnsi = (s) => s.replace(/\x1b\[[0-9;]*m/g, "").trim();
|
|
557
|
+
let taskGraphContext;
|
|
558
|
+
if (boundedTask && boundedTask.trim().length > 0) {
|
|
559
|
+
try {
|
|
560
|
+
const cleanQuery = boundedTask
|
|
561
|
+
.replace(/[^\w./:\s-]/g, " ")
|
|
562
|
+
.replace(/\s+/g, " ")
|
|
563
|
+
.trim()
|
|
564
|
+
.slice(0, 160);
|
|
565
|
+
if (cleanQuery.length > 0) {
|
|
566
|
+
const ctxOut = execFileSync(cgRunner.cmd, [...cgRunner.prefixArgs, "context", "-p", resolvedCwd, "-n", "12", "--no-code", cleanQuery], {
|
|
567
|
+
cwd: resolvedCwd,
|
|
568
|
+
encoding: "utf8",
|
|
569
|
+
timeout: 1400,
|
|
570
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
571
|
+
}).trim();
|
|
572
|
+
if (ctxOut) {
|
|
573
|
+
taskGraphContext = stripAnsi(ctxOut).slice(0, 1800);
|
|
574
|
+
}
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
catch {
|
|
578
|
+
// ignore timeout
|
|
579
|
+
}
|
|
580
|
+
}
|
|
581
|
+
const graphAffectedTests = [];
|
|
582
|
+
if (changedFiles.length > 0) {
|
|
583
|
+
try {
|
|
584
|
+
const safeChangedFiles = changedFiles
|
|
585
|
+
.slice(0, 8)
|
|
586
|
+
.filter((f) => !f.startsWith("-"));
|
|
587
|
+
if (safeChangedFiles.length > 0) {
|
|
588
|
+
const affOut = execFileSync(cgRunner.cmd, [...cgRunner.prefixArgs, "affected", "-p", resolvedCwd, "-q", ...safeChangedFiles], {
|
|
589
|
+
cwd: resolvedCwd,
|
|
590
|
+
encoding: "utf8",
|
|
591
|
+
timeout: 1200,
|
|
592
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
593
|
+
}).trim();
|
|
594
|
+
if (affOut) {
|
|
595
|
+
for (const line of affOut.split(/\r?\n/)) {
|
|
596
|
+
const clean = stripAnsi(line);
|
|
597
|
+
if (clean && !graphAffectedTests.includes(clean)) {
|
|
598
|
+
graphAffectedTests.push(clean);
|
|
599
|
+
}
|
|
600
|
+
}
|
|
601
|
+
}
|
|
602
|
+
}
|
|
603
|
+
}
|
|
604
|
+
catch {
|
|
605
|
+
// ignore
|
|
606
|
+
}
|
|
607
|
+
}
|
|
608
|
+
const symbolRelations = [];
|
|
609
|
+
if (changedFiles.length > 0) {
|
|
610
|
+
try {
|
|
611
|
+
const stem = path
|
|
612
|
+
.basename(changedFiles[0], path.extname(changedFiles[0]))
|
|
613
|
+
.replace(/[^\w.-]/g, "");
|
|
614
|
+
if (stem && stem.length >= 3 && !stem.startsWith("-")) {
|
|
615
|
+
const qOut = execFileSync(cgRunner.cmd, [...cgRunner.prefixArgs, "query", stem], {
|
|
616
|
+
cwd: resolvedCwd,
|
|
617
|
+
encoding: "utf8",
|
|
618
|
+
timeout: 1100,
|
|
619
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
620
|
+
}).trim();
|
|
621
|
+
if (qOut) {
|
|
622
|
+
symbolRelations.push(...qOut
|
|
623
|
+
.split(/\r?\n/)
|
|
624
|
+
.map(stripAnsi)
|
|
625
|
+
.filter(Boolean)
|
|
626
|
+
.slice(0, 10));
|
|
627
|
+
}
|
|
628
|
+
}
|
|
629
|
+
}
|
|
630
|
+
catch {
|
|
631
|
+
// ignore
|
|
632
|
+
}
|
|
633
|
+
}
|
|
634
|
+
return {
|
|
635
|
+
indexed: true,
|
|
636
|
+
taskGraphContext,
|
|
637
|
+
graphAffectedTests: graphAffectedTests.slice(0, 10),
|
|
638
|
+
symbolRelations
|
|
639
|
+
};
|
|
640
|
+
}
|
|
641
|
+
//# sourceMappingURL=hybrid-ast-engine.js.map
|