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,1397 @@
|
|
|
1
|
+
import { execFileSync } from "node:child_process";
|
|
2
|
+
import fs from "node:fs";
|
|
3
|
+
import os from "node:os";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { readSessionEvents } from "./event-log.js";
|
|
6
|
+
const dnaCache = new Map();
|
|
7
|
+
const DNA_CACHE_TTL_MS = 30_000;
|
|
8
|
+
const HOST_BINARY_DIR_NAMES = new Set([
|
|
9
|
+
"antigravity",
|
|
10
|
+
"programs",
|
|
11
|
+
"system32",
|
|
12
|
+
"windows",
|
|
13
|
+
"appdata",
|
|
14
|
+
"local"
|
|
15
|
+
]);
|
|
16
|
+
export function isGenericHostDirectory(dirPath) {
|
|
17
|
+
const normalized = path.resolve(dirPath).toLowerCase();
|
|
18
|
+
const base = path.basename(normalized);
|
|
19
|
+
if (HOST_BINARY_DIR_NAMES.has(base))
|
|
20
|
+
return true;
|
|
21
|
+
if (normalized.includes("\\appdata\\local\\programs\\"))
|
|
22
|
+
return true;
|
|
23
|
+
return false;
|
|
24
|
+
}
|
|
25
|
+
function hasProjectRootMarker(dirPath) {
|
|
26
|
+
try {
|
|
27
|
+
return (fs.existsSync(path.join(dirPath, ".git")) ||
|
|
28
|
+
fs.existsSync(path.join(dirPath, "AGENTS.md")) ||
|
|
29
|
+
fs.existsSync(path.join(dirPath, "GEMINI.md")) ||
|
|
30
|
+
fs.existsSync(path.join(dirPath, "package.json")) ||
|
|
31
|
+
fs.existsSync(path.join(dirPath, "pyproject.toml")) ||
|
|
32
|
+
fs.existsSync(path.join(dirPath, "Cargo.toml")) ||
|
|
33
|
+
fs.existsSync(path.join(dirPath, "go.mod")));
|
|
34
|
+
}
|
|
35
|
+
catch {
|
|
36
|
+
return false;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
function findNearestProjectRoot(startPath) {
|
|
40
|
+
try {
|
|
41
|
+
let curr = path.resolve(startPath);
|
|
42
|
+
if (fs.existsSync(curr) && fs.statSync(curr).isFile()) {
|
|
43
|
+
curr = path.dirname(curr);
|
|
44
|
+
}
|
|
45
|
+
for (let depth = 0; depth < 7; depth++) {
|
|
46
|
+
if (fs.existsSync(path.join(curr, ".git")) ||
|
|
47
|
+
fs.existsSync(path.join(curr, "AGENTS.md")) ||
|
|
48
|
+
fs.existsSync(path.join(curr, "package.json")) ||
|
|
49
|
+
fs.existsSync(path.join(curr, "pyproject.toml"))) {
|
|
50
|
+
if (!isGenericHostDirectory(curr)) {
|
|
51
|
+
return curr;
|
|
52
|
+
}
|
|
53
|
+
}
|
|
54
|
+
const parent = path.dirname(curr);
|
|
55
|
+
if (parent === curr)
|
|
56
|
+
break;
|
|
57
|
+
curr = parent;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
catch {
|
|
61
|
+
// ignore filesystem errors
|
|
62
|
+
}
|
|
63
|
+
return undefined;
|
|
64
|
+
}
|
|
65
|
+
function extractRelativePathCandidates(texts) {
|
|
66
|
+
const results = new Set();
|
|
67
|
+
const relRegex = /(?:^|[\s"'`(\[:])((?:docs|src|apps|packages|backend|frontend|scripts|tests|ops|services|lib|components|pages|app|server|client|config)\/[A-Za-z0-9_./-]+\.[A-Za-z0-9]+|[A-Za-z0-9_.-]+\.(?:md|ts|tsx|js|jsx|py|go|json|yaml|yml|toml|sh|ps1|css|sql))(?:$|[\s"'`)\]:,;])/gm;
|
|
68
|
+
for (const text of texts) {
|
|
69
|
+
if (!text)
|
|
70
|
+
continue;
|
|
71
|
+
for (const match of text.matchAll(relRegex)) {
|
|
72
|
+
const candidate = match[1]?.trim().replace(/^[./\\]+/, "");
|
|
73
|
+
if (candidate && candidate.length > 2 && !candidate.startsWith("http")) {
|
|
74
|
+
results.add(candidate);
|
|
75
|
+
}
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
return Array.from(results);
|
|
79
|
+
}
|
|
80
|
+
/**
|
|
81
|
+
* Blocks secret/credential files from ever being auto-read and uploaded to an external API.
|
|
82
|
+
*/
|
|
83
|
+
export function isSensitiveFilePath(filePath) {
|
|
84
|
+
const normalized = filePath.replace(/\\/g, "/").toLowerCase();
|
|
85
|
+
const base = path.posix.basename(normalized);
|
|
86
|
+
if (base === ".env.example" ||
|
|
87
|
+
base === ".env.sample" ||
|
|
88
|
+
base === ".env.template" ||
|
|
89
|
+
base === ".env.dist") {
|
|
90
|
+
return false;
|
|
91
|
+
}
|
|
92
|
+
if (base === ".env" ||
|
|
93
|
+
base.startsWith(".env.") ||
|
|
94
|
+
base === ".npmrc" ||
|
|
95
|
+
base === ".netrc" ||
|
|
96
|
+
base === ".pypirc" ||
|
|
97
|
+
base === "id_rsa" ||
|
|
98
|
+
base === "id_ed25519" ||
|
|
99
|
+
base === "id_ecdsa" ||
|
|
100
|
+
base === "credentials.json" ||
|
|
101
|
+
normalized.includes("/.mcp-jev/config.json") ||
|
|
102
|
+
normalized.includes("/.ssh/") ||
|
|
103
|
+
normalized.includes("/.aws/") ||
|
|
104
|
+
/\.(pem|key|p12|pfx|keystore|jks)$/i.test(base)) {
|
|
105
|
+
return true;
|
|
106
|
+
}
|
|
107
|
+
return false;
|
|
108
|
+
}
|
|
109
|
+
/**
|
|
110
|
+
* Ensures `targetPath` resolves strictly inside `workspaceRoot` (preventing `../` traversal or symlink escape).
|
|
111
|
+
*/
|
|
112
|
+
export function isWithinWorkspaceBoundary(workspaceRoot, targetPath) {
|
|
113
|
+
try {
|
|
114
|
+
const resolvedRoot = fs.existsSync(workspaceRoot)
|
|
115
|
+
? fs.realpathSync(workspaceRoot)
|
|
116
|
+
: path.resolve(workspaceRoot);
|
|
117
|
+
const resolvedTarget = fs.existsSync(targetPath)
|
|
118
|
+
? fs.realpathSync(targetPath)
|
|
119
|
+
: path.resolve(targetPath);
|
|
120
|
+
const rel = path.relative(resolvedRoot, resolvedTarget);
|
|
121
|
+
if (rel === "")
|
|
122
|
+
return true;
|
|
123
|
+
if (rel.startsWith("..") || path.isAbsolute(rel))
|
|
124
|
+
return false;
|
|
125
|
+
if (process.platform === "win32") {
|
|
126
|
+
return resolvedTarget.toLowerCase().startsWith(`${resolvedRoot.toLowerCase()}${path.sep}`);
|
|
127
|
+
}
|
|
128
|
+
return true;
|
|
129
|
+
}
|
|
130
|
+
catch {
|
|
131
|
+
return false;
|
|
132
|
+
}
|
|
133
|
+
}
|
|
134
|
+
let cachedPythonBin = null;
|
|
135
|
+
/**
|
|
136
|
+
* Cross-platform Python binary resolver (`python3` preferred on POSIX, `python` on Windows).
|
|
137
|
+
*/
|
|
138
|
+
export function resolvePythonExecutable() {
|
|
139
|
+
if (cachedPythonBin)
|
|
140
|
+
return cachedPythonBin;
|
|
141
|
+
const candidates = process.platform === "win32" ? ["python", "python3"] : ["python3", "python"];
|
|
142
|
+
for (const bin of candidates) {
|
|
143
|
+
try {
|
|
144
|
+
execFileSync(bin, ["--version"], {
|
|
145
|
+
timeout: 600,
|
|
146
|
+
stdio: ["ignore", "ignore", "ignore"]
|
|
147
|
+
});
|
|
148
|
+
cachedPythonBin = bin;
|
|
149
|
+
return bin;
|
|
150
|
+
}
|
|
151
|
+
catch {
|
|
152
|
+
// try next candidate
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
cachedPythonBin = process.platform === "win32" ? "python" : "python3";
|
|
156
|
+
return cachedPythonBin;
|
|
157
|
+
}
|
|
158
|
+
/**
|
|
159
|
+
* Resolves the true target project workspace even when the calling agent omits `working_directory`
|
|
160
|
+
* or when `process.cwd()` points to a generic IDE host directory (e.g. `.../Programs/Antigravity`).
|
|
161
|
+
*/
|
|
162
|
+
export function resolveTargetWorkspace(explicitCwd, hints = []) {
|
|
163
|
+
// 1. If explicitCwd is provided and is a real project directory (not IDE host dir), prefer it
|
|
164
|
+
if (explicitCwd && explicitCwd.trim().length > 0 && !isGenericHostDirectory(explicitCwd)) {
|
|
165
|
+
const resolved = path.resolve(explicitCwd);
|
|
166
|
+
const root = findNearestProjectRoot(resolved);
|
|
167
|
+
if (root)
|
|
168
|
+
return root;
|
|
169
|
+
if (fs.existsSync(resolved))
|
|
170
|
+
return resolved;
|
|
171
|
+
}
|
|
172
|
+
// 2. Scan hints for any absolute Windows or POSIX workspace paths on disk
|
|
173
|
+
const absPathRegexes = [
|
|
174
|
+
/\b([A-Za-z]:[\\/][^\s"'`<>|?*]+)\b/g,
|
|
175
|
+
/(?:^|[\s"'`(\[])(\/(?:Users|home|workspace|workspaces|projects|srv|opt|var\/www)\/[^\s"'`<>|?*]+)/g
|
|
176
|
+
];
|
|
177
|
+
for (const hint of hints) {
|
|
178
|
+
if (!hint)
|
|
179
|
+
continue;
|
|
180
|
+
for (const rx of absPathRegexes) {
|
|
181
|
+
for (const match of hint.matchAll(rx)) {
|
|
182
|
+
const rawPath = match[1].replace(/[,:;.)\]'"]+$/, "");
|
|
183
|
+
const root = findNearestProjectRoot(rawPath);
|
|
184
|
+
if (root)
|
|
185
|
+
return root;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
}
|
|
189
|
+
// Gather known active workspaces from recent session events + configured/sibling parent roots
|
|
190
|
+
const recentEvents = readSessionEvents(60);
|
|
191
|
+
const candidateWorkspaces = [];
|
|
192
|
+
for (const ev of recentEvents) {
|
|
193
|
+
if (ev.workspacePath &&
|
|
194
|
+
!isGenericHostDirectory(ev.workspacePath) &&
|
|
195
|
+
!candidateWorkspaces.includes(ev.workspacePath) &&
|
|
196
|
+
fs.existsSync(ev.workspacePath) &&
|
|
197
|
+
hasProjectRootMarker(ev.workspacePath)) {
|
|
198
|
+
candidateWorkspaces.push(ev.workspacePath);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
const configuredRoots = (process.env.JEV_WORKSPACE_ROOTS ?? "")
|
|
202
|
+
.split(path.delimiter)
|
|
203
|
+
.map((s) => s.trim())
|
|
204
|
+
.filter(Boolean);
|
|
205
|
+
const procCwd = process.cwd();
|
|
206
|
+
if (!isGenericHostDirectory(procCwd)) {
|
|
207
|
+
const parentDir = path.dirname(path.resolve(procCwd));
|
|
208
|
+
if (parentDir && parentDir !== path.parse(parentDir).root && !isGenericHostDirectory(parentDir)) {
|
|
209
|
+
configuredRoots.push(parentDir);
|
|
210
|
+
}
|
|
211
|
+
}
|
|
212
|
+
for (const rootDir of configuredRoots) {
|
|
213
|
+
try {
|
|
214
|
+
if (!fs.existsSync(rootDir))
|
|
215
|
+
continue;
|
|
216
|
+
for (const entry of fs.readdirSync(rootDir, { withFileTypes: true }).slice(0, 60)) {
|
|
217
|
+
if (entry.isDirectory()) {
|
|
218
|
+
const full = path.join(rootDir, entry.name);
|
|
219
|
+
if (!candidateWorkspaces.includes(full) && hasProjectRootMarker(full)) {
|
|
220
|
+
candidateWorkspaces.push(full);
|
|
221
|
+
}
|
|
222
|
+
}
|
|
223
|
+
}
|
|
224
|
+
}
|
|
225
|
+
catch {
|
|
226
|
+
// ignore
|
|
227
|
+
}
|
|
228
|
+
}
|
|
229
|
+
// 3. Check if relative file paths mentioned in hints exist inside one of the candidate workspaces
|
|
230
|
+
const relCandidates = extractRelativePathCandidates(hints);
|
|
231
|
+
if (relCandidates.length > 0) {
|
|
232
|
+
let bestWorkspace;
|
|
233
|
+
let bestScore = 0;
|
|
234
|
+
for (const wsPath of candidateWorkspaces) {
|
|
235
|
+
let score = 0;
|
|
236
|
+
for (const rel of relCandidates.slice(0, 16)) {
|
|
237
|
+
if (fs.existsSync(path.join(wsPath, rel))) {
|
|
238
|
+
score += 1;
|
|
239
|
+
}
|
|
240
|
+
}
|
|
241
|
+
if (score > bestScore) {
|
|
242
|
+
bestScore = score;
|
|
243
|
+
bestWorkspace = wsPath;
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
if (bestWorkspace && bestScore > 0) {
|
|
247
|
+
return bestWorkspace;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
// 4. Check if any hint explicitly names a known workspace folder
|
|
251
|
+
const primaryHintsLower = hints
|
|
252
|
+
.filter(Boolean)
|
|
253
|
+
.map((h) => h.slice(0, 1200))
|
|
254
|
+
.join("\n")
|
|
255
|
+
.toLowerCase();
|
|
256
|
+
for (const wsPath of candidateWorkspaces) {
|
|
257
|
+
const wsName = path.basename(wsPath).toLowerCase();
|
|
258
|
+
if (wsName.length < 4)
|
|
259
|
+
continue;
|
|
260
|
+
const escaped = wsName.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
|
|
261
|
+
const boundaryRegex = new RegExp(`(?:^|[\\s"'\\(\\[/\\\\])${escaped}(?:$|[\\s"'\\)\\]/\\\\.,:;])`, "i");
|
|
262
|
+
if (boundaryRegex.test(primaryHintsLower)) {
|
|
263
|
+
return wsPath;
|
|
264
|
+
}
|
|
265
|
+
}
|
|
266
|
+
// 5. If process.cwd() is a valid non-host workspace, use it; otherwise fallback to most recent valid workspace
|
|
267
|
+
if (!isGenericHostDirectory(procCwd)) {
|
|
268
|
+
return path.resolve(procCwd);
|
|
269
|
+
}
|
|
270
|
+
return candidateWorkspaces[0] ?? path.resolve(procCwd);
|
|
271
|
+
}
|
|
272
|
+
function safeReadText(filePath, maxChars = 1500) {
|
|
273
|
+
try {
|
|
274
|
+
if (!fs.existsSync(filePath))
|
|
275
|
+
return undefined;
|
|
276
|
+
const stat = fs.statSync(filePath);
|
|
277
|
+
if (!stat.isFile())
|
|
278
|
+
return undefined;
|
|
279
|
+
const raw = fs.readFileSync(filePath, "utf8").trim();
|
|
280
|
+
if (!raw)
|
|
281
|
+
return undefined;
|
|
282
|
+
return raw.length <= maxChars ? raw : `${raw.slice(0, maxChars)}\n...[TRUNCATED]`;
|
|
283
|
+
}
|
|
284
|
+
catch {
|
|
285
|
+
return undefined;
|
|
286
|
+
}
|
|
287
|
+
}
|
|
288
|
+
/**
|
|
289
|
+
* Distills markdown documentation by keeping headings, critical directives (MUST/NEVER/BẮT BUỘC),
|
|
290
|
+
* and structural bullet points so multiple doc files fit into a compact high-signal envelope.
|
|
291
|
+
*/
|
|
292
|
+
function distillMarkdownDoc(filePath, maxChars = 1200) {
|
|
293
|
+
try {
|
|
294
|
+
if (!fs.existsSync(filePath) || !fs.statSync(filePath).isFile())
|
|
295
|
+
return undefined;
|
|
296
|
+
const raw = fs.readFileSync(filePath, "utf8").trim();
|
|
297
|
+
if (!raw)
|
|
298
|
+
return undefined;
|
|
299
|
+
if (raw.length <= maxChars)
|
|
300
|
+
return raw;
|
|
301
|
+
const lines = raw.split(/\r?\n/);
|
|
302
|
+
const prioritized = [];
|
|
303
|
+
let currentLen = 0;
|
|
304
|
+
for (const line of lines) {
|
|
305
|
+
const trimmed = line.trim();
|
|
306
|
+
if (!trimmed)
|
|
307
|
+
continue;
|
|
308
|
+
const isHighSignal = /^#{1,4}\s+/.test(trimmed) ||
|
|
309
|
+
/\b(MUST|NEVER|ALWAYS|IMPORTANT|CRITICAL|BẮT BUỘC|KHÔNG ĐƯỢC|ƯU TIÊN|INVARIANT|GATE|SECURITY|ARCHITECTURE|STACK)\b/i.test(trimmed) ||
|
|
310
|
+
/^[-*]\s+\*\*[^*]+\*\*/.test(trimmed);
|
|
311
|
+
if (isHighSignal || currentLen < maxChars * 0.45) {
|
|
312
|
+
if (currentLen + trimmed.length + 1 > maxChars)
|
|
313
|
+
break;
|
|
314
|
+
prioritized.push(trimmed);
|
|
315
|
+
currentLen += trimmed.length + 1;
|
|
316
|
+
}
|
|
317
|
+
}
|
|
318
|
+
return prioritized.length > 0
|
|
319
|
+
? prioritized.join("\n")
|
|
320
|
+
: `${raw.slice(0, maxChars)}\n...[TRUNCATED]`;
|
|
321
|
+
}
|
|
322
|
+
catch {
|
|
323
|
+
return undefined;
|
|
324
|
+
}
|
|
325
|
+
}
|
|
326
|
+
function summarizePackageJson(pkgPath, rootCwd) {
|
|
327
|
+
try {
|
|
328
|
+
if (!fs.existsSync(pkgPath))
|
|
329
|
+
return undefined;
|
|
330
|
+
const raw = JSON.parse(fs.readFileSync(pkgPath, "utf8"));
|
|
331
|
+
const deps = [
|
|
332
|
+
...Object.keys(raw.dependencies ?? {}),
|
|
333
|
+
...Object.keys(raw.devDependencies ?? {})
|
|
334
|
+
].slice(0, 22);
|
|
335
|
+
const scripts = Object.keys(raw.scripts ?? {}).slice(0, 8);
|
|
336
|
+
const relDir = path.relative(rootCwd, path.dirname(pkgPath)) || ".";
|
|
337
|
+
return `${raw.name ?? relDir} (${relDir}): deps=[${deps.join(", ")}]${scripts.length > 0 ? ` scripts=[${scripts.join(", ")}]` : ""}`;
|
|
338
|
+
}
|
|
339
|
+
catch {
|
|
340
|
+
return undefined;
|
|
341
|
+
}
|
|
342
|
+
}
|
|
343
|
+
function discoverSubdirPackages(baseDir) {
|
|
344
|
+
try {
|
|
345
|
+
if (!fs.existsSync(baseDir))
|
|
346
|
+
return [];
|
|
347
|
+
return fs
|
|
348
|
+
.readdirSync(baseDir, { withFileTypes: true })
|
|
349
|
+
.filter((d) => d.isDirectory())
|
|
350
|
+
.map((d) => path.join(baseDir, d.name, "package.json"))
|
|
351
|
+
.filter((p) => fs.existsSync(p));
|
|
352
|
+
}
|
|
353
|
+
catch {
|
|
354
|
+
return [];
|
|
355
|
+
}
|
|
356
|
+
}
|
|
357
|
+
function buildStackSummary(cwd) {
|
|
358
|
+
const parts = [];
|
|
359
|
+
const candidatePkgPaths = [
|
|
360
|
+
path.join(cwd, "package.json"),
|
|
361
|
+
path.join(cwd, "frontend", "package.json"),
|
|
362
|
+
...discoverSubdirPackages(path.join(cwd, "apps")),
|
|
363
|
+
...discoverSubdirPackages(path.join(cwd, "packages"))
|
|
364
|
+
];
|
|
365
|
+
const seen = new Set();
|
|
366
|
+
for (const pkgPath of candidatePkgPaths) {
|
|
367
|
+
if (seen.has(pkgPath))
|
|
368
|
+
continue;
|
|
369
|
+
seen.add(pkgPath);
|
|
370
|
+
const summary = summarizePackageJson(pkgPath, cwd);
|
|
371
|
+
if (summary)
|
|
372
|
+
parts.push(summary);
|
|
373
|
+
}
|
|
374
|
+
const pyProjectCandidates = [
|
|
375
|
+
path.join(cwd, "pyproject.toml"),
|
|
376
|
+
path.join(cwd, "backend", "pyproject.toml"),
|
|
377
|
+
path.join(cwd, "requirements.txt"),
|
|
378
|
+
path.join(cwd, "backend", "requirements.txt")
|
|
379
|
+
];
|
|
380
|
+
for (const pyPath of pyProjectCandidates) {
|
|
381
|
+
const excerpt = safeReadText(pyPath, 500);
|
|
382
|
+
if (excerpt) {
|
|
383
|
+
parts.push(`${path.relative(cwd, pyPath) || path.basename(pyPath)}: ${excerpt.replace(/\s+/g, " ")}`);
|
|
384
|
+
break;
|
|
385
|
+
}
|
|
386
|
+
}
|
|
387
|
+
return parts.length > 0 ? parts.join(" | ").slice(0, 1800) : "generic workspace";
|
|
388
|
+
}
|
|
389
|
+
function buildRepoTopology(cwd) {
|
|
390
|
+
const ignored = new Set([
|
|
391
|
+
".git",
|
|
392
|
+
"node_modules",
|
|
393
|
+
"dist",
|
|
394
|
+
"build",
|
|
395
|
+
".next",
|
|
396
|
+
".turbo",
|
|
397
|
+
"__pycache__",
|
|
398
|
+
".venv",
|
|
399
|
+
"venv",
|
|
400
|
+
".pytest_cache",
|
|
401
|
+
"coverage",
|
|
402
|
+
".codegraph"
|
|
403
|
+
]);
|
|
404
|
+
try {
|
|
405
|
+
const entries = fs.readdirSync(cwd, { withFileTypes: true });
|
|
406
|
+
const topItems = [];
|
|
407
|
+
for (const entry of entries) {
|
|
408
|
+
if (ignored.has(entry.name) || entry.name.startsWith("."))
|
|
409
|
+
continue;
|
|
410
|
+
if (entry.isDirectory()) {
|
|
411
|
+
try {
|
|
412
|
+
const children = fs
|
|
413
|
+
.readdirSync(path.join(cwd, entry.name), { withFileTypes: true })
|
|
414
|
+
.filter((c) => !ignored.has(c.name) && !c.name.startsWith("."))
|
|
415
|
+
.slice(0, 8)
|
|
416
|
+
.map((c) => (c.isDirectory() ? `${c.name}/` : c.name));
|
|
417
|
+
topItems.push(children.length > 0 ? `${entry.name}/[${children.join(", ")}]` : `${entry.name}/`);
|
|
418
|
+
}
|
|
419
|
+
catch {
|
|
420
|
+
topItems.push(`${entry.name}/`);
|
|
421
|
+
}
|
|
422
|
+
}
|
|
423
|
+
else {
|
|
424
|
+
topItems.push(entry.name);
|
|
425
|
+
}
|
|
426
|
+
}
|
|
427
|
+
return topItems.slice(0, 24).join(", ");
|
|
428
|
+
}
|
|
429
|
+
catch {
|
|
430
|
+
return "";
|
|
431
|
+
}
|
|
432
|
+
}
|
|
433
|
+
export function buildProjectContextEnvelope(cwd = process.cwd(), hints = []) {
|
|
434
|
+
const resolvedCwd = resolveTargetWorkspace(cwd, hints);
|
|
435
|
+
const workspaceName = path.basename(resolvedCwd) || "workspace";
|
|
436
|
+
const now = Date.now();
|
|
437
|
+
let baseDna = dnaCache.get(resolvedCwd)?.dna;
|
|
438
|
+
if (!baseDna || (dnaCache.get(resolvedCwd)?.expiresAt ?? 0) < now) {
|
|
439
|
+
// Combine ALL present rule & architecture documents instead of stopping after the first file
|
|
440
|
+
const ruleCandidates = [
|
|
441
|
+
{ file: "AGENTS.md", budget: 1400 },
|
|
442
|
+
{ file: "CLAUDE.md", budget: 900 },
|
|
443
|
+
{ file: "GEMINI.md", budget: 900 },
|
|
444
|
+
{ file: "CONTEXT.md", budget: 1100 },
|
|
445
|
+
{ file: "PRODUCT.md", budget: 1000 },
|
|
446
|
+
{ file: "ARCHITECTURE.md", budget: 1000 },
|
|
447
|
+
{ file: "README.md", budget: 800 }
|
|
448
|
+
];
|
|
449
|
+
const ruleSections = [];
|
|
450
|
+
let totalRuleChars = 0;
|
|
451
|
+
for (const { file, budget } of ruleCandidates) {
|
|
452
|
+
if (totalRuleChars >= 3400)
|
|
453
|
+
break;
|
|
454
|
+
const text = distillMarkdownDoc(path.join(resolvedCwd, file), budget);
|
|
455
|
+
if (text) {
|
|
456
|
+
ruleSections.push(`[${file}]\n${text}`);
|
|
457
|
+
totalRuleChars += text.length;
|
|
458
|
+
}
|
|
459
|
+
}
|
|
460
|
+
const projectRulesExcerpt = ruleSections.length > 0 ? ruleSections.join("\n\n").slice(0, 3600) : undefined;
|
|
461
|
+
// Combine BOTH CURRENT.md and WORKBOARD.md when present
|
|
462
|
+
const memoryCandidates = [
|
|
463
|
+
{ rel: path.join("docs", "memory", "CURRENT.md"), budget: 1100 },
|
|
464
|
+
{ rel: path.join("docs", "memory", "WORKBOARD.md"), budget: 900 }
|
|
465
|
+
];
|
|
466
|
+
const memorySections = [];
|
|
467
|
+
for (const { rel, budget } of memoryCandidates) {
|
|
468
|
+
const text = distillMarkdownDoc(path.join(resolvedCwd, rel), budget);
|
|
469
|
+
if (text) {
|
|
470
|
+
memorySections.push(`[${rel.replace(/\\/g, "/")}]\n${text}`);
|
|
471
|
+
}
|
|
472
|
+
}
|
|
473
|
+
const activeMemoryExcerpt = memorySections.length > 0 ? memorySections.join("\n\n").slice(0, 2000) : undefined;
|
|
474
|
+
baseDna = {
|
|
475
|
+
workspaceName,
|
|
476
|
+
workspacePath: resolvedCwd,
|
|
477
|
+
stackSummary: buildStackSummary(resolvedCwd),
|
|
478
|
+
repoTopology: buildRepoTopology(resolvedCwd),
|
|
479
|
+
domainAndAuthFingerprint: extractDomainAndRuntimeFingerprint(resolvedCwd),
|
|
480
|
+
projectRulesExcerpt,
|
|
481
|
+
activeMemoryExcerpt
|
|
482
|
+
};
|
|
483
|
+
dnaCache.set(resolvedCwd, {
|
|
484
|
+
expiresAt: now + DNA_CACHE_TTL_MS,
|
|
485
|
+
dna: baseDna
|
|
486
|
+
});
|
|
487
|
+
syncProjectBrainProfile({
|
|
488
|
+
...baseDna,
|
|
489
|
+
recentWorkspaceDecisions: []
|
|
490
|
+
});
|
|
491
|
+
}
|
|
492
|
+
const recentEvents = readSessionEvents(40)
|
|
493
|
+
.filter((e) => e.workspace.toLowerCase() === workspaceName.toLowerCase())
|
|
494
|
+
.slice(0, 5)
|
|
495
|
+
.map((e) => ({
|
|
496
|
+
timestamp: e.timestamp,
|
|
497
|
+
agent: e.agent,
|
|
498
|
+
tool: e.tool,
|
|
499
|
+
questionOrTitle: e.questionOrTitle.slice(0, 220),
|
|
500
|
+
verdict: e.verdict,
|
|
501
|
+
directive: e.directive.slice(0, 220)
|
|
502
|
+
}));
|
|
503
|
+
return {
|
|
504
|
+
...baseDna,
|
|
505
|
+
learnedHumanOverrides: readLearnedHumanOverrides(workspaceName),
|
|
506
|
+
recentWorkspaceDecisions: recentEvents
|
|
507
|
+
};
|
|
508
|
+
}
|
|
509
|
+
/**
|
|
510
|
+
* Automatically detects and reads any files (handoffs, review docs, specs, scripts, components)
|
|
511
|
+
* explicitly referenced inside the prompt/spec/question/context so Jev never evaluates blindly.
|
|
512
|
+
*/
|
|
513
|
+
export function extractReferencedDocsAndFiles(cwd, texts, maxFiles = 5, maxCharsPerFile = 2400) {
|
|
514
|
+
const resolvedCwd = path.resolve(cwd);
|
|
515
|
+
const candidates = extractRelativePathCandidates(texts);
|
|
516
|
+
const combinedPrompt = texts.filter(Boolean).join("\n");
|
|
517
|
+
// Extract specific section/ticket tokens mentioned in the prompt (e.g. CR1-01, R1, Phase 2)
|
|
518
|
+
const focusTokens = Array.from(new Set(Array.from(combinedPrompt.matchAll(/\b([A-Z]{2,5}\d*-\d+|section\s+\d+|pha(?:se)?\s+\d+)\b/gi), (m) => m[1].toLowerCase())));
|
|
519
|
+
const result = {};
|
|
520
|
+
for (const rel of candidates) {
|
|
521
|
+
if (Object.keys(result).length >= maxFiles)
|
|
522
|
+
break;
|
|
523
|
+
const fullPath = path.isAbsolute(rel) ? rel : path.join(resolvedCwd, rel);
|
|
524
|
+
if (isSensitiveFilePath(fullPath) || !isWithinWorkspaceBoundary(resolvedCwd, fullPath)) {
|
|
525
|
+
continue;
|
|
526
|
+
}
|
|
527
|
+
try {
|
|
528
|
+
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile())
|
|
529
|
+
continue;
|
|
530
|
+
const raw = fs.readFileSync(fullPath, "utf8").trim();
|
|
531
|
+
if (!raw)
|
|
532
|
+
continue;
|
|
533
|
+
if (raw.length <= maxCharsPerFile) {
|
|
534
|
+
result[rel] = raw;
|
|
535
|
+
continue;
|
|
536
|
+
}
|
|
537
|
+
// If prompt mentions specific IDs/sections (like CR1-01..CR1-03), pull header + matching sections
|
|
538
|
+
const lines = raw.split(/\r?\n/);
|
|
539
|
+
const head = lines.slice(0, 35).join("\n");
|
|
540
|
+
const matchedSnippets = [];
|
|
541
|
+
if (focusTokens.length > 0) {
|
|
542
|
+
for (let i = 35; i < lines.length; i++) {
|
|
543
|
+
const lower = lines[i].toLowerCase();
|
|
544
|
+
if (focusTokens.some((tok) => lower.includes(tok))) {
|
|
545
|
+
const block = lines.slice(Math.max(35, i - 2), Math.min(lines.length, i + 18)).join("\n");
|
|
546
|
+
matchedSnippets.push(block);
|
|
547
|
+
i += 15;
|
|
548
|
+
if (matchedSnippets.join("\n").length > maxCharsPerFile * 0.6)
|
|
549
|
+
break;
|
|
550
|
+
}
|
|
551
|
+
}
|
|
552
|
+
}
|
|
553
|
+
if (matchedSnippets.length > 0) {
|
|
554
|
+
result[rel] = `${head}\n...\n${matchedSnippets.join("\n---\n")}`.slice(0, maxCharsPerFile);
|
|
555
|
+
}
|
|
556
|
+
else {
|
|
557
|
+
result[rel] = `${raw.slice(0, maxCharsPerFile)}\n...[TRUNCATED]`;
|
|
558
|
+
}
|
|
559
|
+
}
|
|
560
|
+
catch {
|
|
561
|
+
// ignore unreadable files
|
|
562
|
+
}
|
|
563
|
+
}
|
|
564
|
+
return result;
|
|
565
|
+
}
|
|
566
|
+
/**
|
|
567
|
+
* Parses the full raw git diff BEFORE character truncation to produce a complete
|
|
568
|
+
* per-file structural map (line counts, hunk headers, and added/modified symbols,
|
|
569
|
+
* functions, components, tests, routes, and CSS selectors).
|
|
570
|
+
*/
|
|
571
|
+
export function extractStructuralDiffMap(rawDiff) {
|
|
572
|
+
if (!rawDiff || !rawDiff.trim())
|
|
573
|
+
return [];
|
|
574
|
+
const chunks = rawDiff
|
|
575
|
+
.split(/(?=^diff --git )/m)
|
|
576
|
+
.map((c) => c.trim())
|
|
577
|
+
.filter(Boolean);
|
|
578
|
+
const results = [];
|
|
579
|
+
const symbolRegex = /^\+\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function|class|interface|type|const|let|def|describe|it|test)\s+([A-Za-z0-9_$]+)|^\+\s*([.#][a-zA-Z0-9_-]+)\s*\{|^\+\s*@(?:app|router)\.(?:get|post|put|delete|patch)\(\s*["']([^"']+)["']/;
|
|
580
|
+
for (const chunk of chunks.slice(0, 45)) {
|
|
581
|
+
const fileMatch = chunk.match(/^diff --git a\/.+? b\/([^\r\n\t]+)$/m) ??
|
|
582
|
+
chunk.match(/^\+\+\+ b\/([^\r\n\t]+)$/m);
|
|
583
|
+
const file = fileMatch ? fileMatch[1].trim() : "unknown";
|
|
584
|
+
let addedLines = 0;
|
|
585
|
+
let removedLines = 0;
|
|
586
|
+
const hunkHeaders = [];
|
|
587
|
+
const touchedSymbols = [];
|
|
588
|
+
const lines = chunk.split(/\r?\n/);
|
|
589
|
+
for (const line of lines) {
|
|
590
|
+
if (line.startsWith("@@")) {
|
|
591
|
+
const hunkCtx = line.replace(/^@@[^@]+@@\s*/, "").trim();
|
|
592
|
+
if (hunkCtx && hunkHeaders.length < 10 && !hunkHeaders.includes(hunkCtx)) {
|
|
593
|
+
hunkHeaders.push(hunkCtx.slice(0, 100));
|
|
594
|
+
}
|
|
595
|
+
continue;
|
|
596
|
+
}
|
|
597
|
+
if (line.startsWith("+") && !line.startsWith("+++")) {
|
|
598
|
+
addedLines += 1;
|
|
599
|
+
if (touchedSymbols.length < 18) {
|
|
600
|
+
const symMatch = line.match(symbolRegex);
|
|
601
|
+
const sym = symMatch?.[1] ?? symMatch?.[2] ?? symMatch?.[3];
|
|
602
|
+
if (sym && !touchedSymbols.includes(sym)) {
|
|
603
|
+
touchedSymbols.push(sym);
|
|
604
|
+
}
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
else if (line.startsWith("-") && !line.startsWith("---")) {
|
|
608
|
+
removedLines += 1;
|
|
609
|
+
}
|
|
610
|
+
}
|
|
611
|
+
results.push({
|
|
612
|
+
file,
|
|
613
|
+
addedLines,
|
|
614
|
+
removedLines,
|
|
615
|
+
hunkHeaders,
|
|
616
|
+
touchedSymbols
|
|
617
|
+
});
|
|
618
|
+
}
|
|
619
|
+
return results;
|
|
620
|
+
}
|
|
621
|
+
/**
|
|
622
|
+
* Reads the actual post-edit files on disk around the modified hunk line numbers (`@@ ... +start,count @@`)
|
|
623
|
+
* and locates the nearest enclosing function/class/route decorator header above each hunk.
|
|
624
|
+
* This gives Jev the true post-edit code structure and surrounding guards/transactions/auth decorators.
|
|
625
|
+
*/
|
|
626
|
+
export function extractPostEditHunkScopes(cwd, rawDiff, maxFiles = 6, maxTotalChars = 7500) {
|
|
627
|
+
if (!rawDiff || !rawDiff.trim())
|
|
628
|
+
return {};
|
|
629
|
+
const resolvedCwd = path.resolve(cwd);
|
|
630
|
+
const chunks = rawDiff
|
|
631
|
+
.split(/(?=^diff --git )/m)
|
|
632
|
+
.map((c) => c.trim())
|
|
633
|
+
.filter(Boolean);
|
|
634
|
+
const scopes = {};
|
|
635
|
+
let usedChars = 0;
|
|
636
|
+
const sigRegex = /^\s*(?:export\s+)?(?:default\s+)?(?:async\s+)?(?:function\s+[A-Za-z0-9_$]+|class\s+[A-Za-z0-9_$]+|const\s+[A-Za-z0-9_$]+\s*=\s*(?:async\s*)?\(|def\s+[A-Za-z0-9_]+|async\s+def\s+[A-Za-z0-9_]+|@(?:app|router)\.(?:get|post|put|delete|patch))/;
|
|
637
|
+
for (const chunk of chunks) {
|
|
638
|
+
if (Object.keys(scopes).length >= maxFiles || usedChars >= maxTotalChars)
|
|
639
|
+
break;
|
|
640
|
+
const fileMatch = chunk.match(/^diff --git a\/.+? b\/([^\r\n\t]+)$/m) ??
|
|
641
|
+
chunk.match(/^\+\+\+ b\/([^\r\n\t]+)$/m);
|
|
642
|
+
const relFile = fileMatch ? fileMatch[1].trim() : "";
|
|
643
|
+
if (!relFile || !/\.(ts|tsx|js|jsx|mjs|py|go|css)$/i.test(relFile))
|
|
644
|
+
continue;
|
|
645
|
+
const fullPath = path.join(resolvedCwd, relFile);
|
|
646
|
+
if (!fs.existsSync(fullPath))
|
|
647
|
+
continue;
|
|
648
|
+
try {
|
|
649
|
+
const fileLines = fs.readFileSync(fullPath, "utf8").split(/\r?\n/);
|
|
650
|
+
const hunkMatches = Array.from(chunk.matchAll(/^@@\s*-\d+(?:,\d+)?\s+\+(\d+)(?:,(\d+))?\s*@@/gm));
|
|
651
|
+
if (hunkMatches.length === 0)
|
|
652
|
+
continue;
|
|
653
|
+
const windows = [];
|
|
654
|
+
for (const m of hunkMatches.slice(0, 3)) {
|
|
655
|
+
const startLine = Math.max(1, parseInt(m[1], 10));
|
|
656
|
+
const count = m[2] !== undefined ? parseInt(m[2], 10) : 1;
|
|
657
|
+
const winStart = Math.max(1, startLine - 10);
|
|
658
|
+
const winEnd = Math.min(fileLines.length, startLine + Math.max(1, count) + 10);
|
|
659
|
+
// Search upward from winStart for the enclosing function/class/decorator header
|
|
660
|
+
let enclosingHeader;
|
|
661
|
+
for (let lineIdx = winStart - 2; lineIdx >= Math.max(0, winStart - 60); lineIdx--) {
|
|
662
|
+
if (sigRegex.test(fileLines[lineIdx])) {
|
|
663
|
+
enclosingHeader = `L${lineIdx + 1}: ${fileLines[lineIdx].trim()}`;
|
|
664
|
+
break;
|
|
665
|
+
}
|
|
666
|
+
}
|
|
667
|
+
windows.push({ start: winStart, end: winEnd, enclosingHeader });
|
|
668
|
+
}
|
|
669
|
+
const formattedBlocks = windows.map((w) => {
|
|
670
|
+
const numbered = fileLines
|
|
671
|
+
.slice(w.start - 1, w.end)
|
|
672
|
+
.map((l, idx) => `L${w.start + idx}: ${l}`)
|
|
673
|
+
.join("\n");
|
|
674
|
+
return w.enclosingHeader
|
|
675
|
+
? `[Enclosing Scope -> ${w.enclosingHeader}]\n${numbered}`
|
|
676
|
+
: numbered;
|
|
677
|
+
});
|
|
678
|
+
const combined = formattedBlocks.join("\n...\n").slice(0, 1600);
|
|
679
|
+
if (combined) {
|
|
680
|
+
scopes[relFile] = combined;
|
|
681
|
+
usedChars += combined.length;
|
|
682
|
+
}
|
|
683
|
+
}
|
|
684
|
+
catch {
|
|
685
|
+
// ignore read errors
|
|
686
|
+
}
|
|
687
|
+
}
|
|
688
|
+
return scopes;
|
|
689
|
+
}
|
|
690
|
+
function resolveRelativeImportPath(fromFileFull, importSpec, rootCwd) {
|
|
691
|
+
const baseDir = path.dirname(fromFileFull);
|
|
692
|
+
const candidates = [];
|
|
693
|
+
if (importSpec.startsWith(".")) {
|
|
694
|
+
const rawTarget = path.resolve(baseDir, importSpec.replace(/\.(js|mjs)$/, ""));
|
|
695
|
+
candidates.push(rawTarget, `${rawTarget}.ts`, `${rawTarget}.tsx`, `${rawTarget}.js`, `${rawTarget}.py`, path.join(rawTarget, "index.ts"), path.join(rawTarget, "index.tsx"));
|
|
696
|
+
}
|
|
697
|
+
else if (importSpec.startsWith("@/")) {
|
|
698
|
+
const stripped = importSpec.slice(2).replace(/\.(js|mjs)$/, "");
|
|
699
|
+
for (const prefix of ["src", "frontend/src", "apps/web/src", "apps/api/src"]) {
|
|
700
|
+
const target = path.join(rootCwd, prefix, stripped);
|
|
701
|
+
candidates.push(target, `${target}.ts`, `${target}.tsx`, path.join(target, "index.ts"));
|
|
702
|
+
}
|
|
703
|
+
}
|
|
704
|
+
else if (/^(?:app|backend\.app)\./.test(importSpec)) {
|
|
705
|
+
const relPy = importSpec.replace(/^backend\./, "").replace(/\./g, "/");
|
|
706
|
+
candidates.push(path.join(rootCwd, `${relPy}.py`), path.join(rootCwd, "backend", `${relPy}.py`), path.join(rootCwd, relPy, "__init__.py"), path.join(rootCwd, "backend", relPy, "__init__.py"));
|
|
707
|
+
}
|
|
708
|
+
for (const c of candidates) {
|
|
709
|
+
if (fs.existsSync(c) && fs.statSync(c).isFile()) {
|
|
710
|
+
return c;
|
|
711
|
+
}
|
|
712
|
+
}
|
|
713
|
+
return undefined;
|
|
714
|
+
}
|
|
715
|
+
/**
|
|
716
|
+
* Resolves local cross-file imports (`./...`, `../...`, `@/...`, `from app... import ...`)
|
|
717
|
+
* from modified files and extracts exported TypeScript interfaces/types/schemas and Python Pydantic/function signatures.
|
|
718
|
+
* Also queries `.codegraph` if initialized in the workspace.
|
|
719
|
+
*/
|
|
720
|
+
export function extractCrossFileContracts(cwd, changedFiles, maxContracts = 6, maxTotalChars = 4800) {
|
|
721
|
+
const resolvedCwd = path.resolve(cwd);
|
|
722
|
+
const contracts = {};
|
|
723
|
+
let totalChars = 0;
|
|
724
|
+
const tsImportRegex = /from\s+["'](\.[^"']+|@\/[^"']+)["']/g;
|
|
725
|
+
const pyImportRegex = /^\s*from\s+((?:app|backend\.app)\.[A-Za-z0-9_.]+)\s+import\s+/gm;
|
|
726
|
+
const exportLineRegex = /^\s*(?:export\s+(?:interface|type|enum|class|function|async\s+function|const)\s+[A-Za-z0-9_$]+.*|class\s+[A-Za-z0-9_]+\([^)]*\):|(?:async\s+)?def\s+[A-Za-z0-9_]+\([^)]*\).*?:)/;
|
|
727
|
+
const visitedTargets = new Set();
|
|
728
|
+
for (const relFile of changedFiles.slice(0, 8)) {
|
|
729
|
+
if (Object.keys(contracts).length >= maxContracts || totalChars >= maxTotalChars)
|
|
730
|
+
break;
|
|
731
|
+
const fullFrom = path.isAbsolute(relFile) ? relFile : path.join(resolvedCwd, relFile);
|
|
732
|
+
if (!fs.existsSync(fullFrom) || !fs.statSync(fullFrom).isFile())
|
|
733
|
+
continue;
|
|
734
|
+
try {
|
|
735
|
+
const source = fs.readFileSync(fullFrom, "utf8").slice(0, 8000);
|
|
736
|
+
const importSpecs = [];
|
|
737
|
+
for (const m of source.matchAll(tsImportRegex)) {
|
|
738
|
+
if (m[1])
|
|
739
|
+
importSpecs.push(m[1]);
|
|
740
|
+
}
|
|
741
|
+
for (const m of source.matchAll(pyImportRegex)) {
|
|
742
|
+
if (m[1])
|
|
743
|
+
importSpecs.push(m[1]);
|
|
744
|
+
}
|
|
745
|
+
for (const spec of importSpecs) {
|
|
746
|
+
if (Object.keys(contracts).length >= maxContracts || totalChars >= maxTotalChars)
|
|
747
|
+
break;
|
|
748
|
+
const resolvedTarget = resolveRelativeImportPath(fullFrom, spec, resolvedCwd);
|
|
749
|
+
if (!resolvedTarget || visitedTargets.has(resolvedTarget))
|
|
750
|
+
continue;
|
|
751
|
+
visitedTargets.add(resolvedTarget);
|
|
752
|
+
const targetLines = fs.readFileSync(resolvedTarget, "utf8").split(/\r?\n/);
|
|
753
|
+
const extracted = [];
|
|
754
|
+
for (let i = 0; i < targetLines.length && extracted.join("\n").length < 900; i++) {
|
|
755
|
+
if (exportLineRegex.test(targetLines[i])) {
|
|
756
|
+
const block = targetLines.slice(i, Math.min(targetLines.length, i + 8)).join("\n");
|
|
757
|
+
extracted.push(block);
|
|
758
|
+
i += 6;
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
if (extracted.length > 0) {
|
|
762
|
+
const relTarget = path.relative(resolvedCwd, resolvedTarget).replace(/\\/g, "/");
|
|
763
|
+
const snippet = extracted.join("\n").slice(0, 950);
|
|
764
|
+
contracts[relTarget] = snippet;
|
|
765
|
+
totalChars += snippet.length;
|
|
766
|
+
}
|
|
767
|
+
}
|
|
768
|
+
}
|
|
769
|
+
catch {
|
|
770
|
+
// ignore
|
|
771
|
+
}
|
|
772
|
+
}
|
|
773
|
+
// Optional CodeGraph CLI enrichment when `.codegraph` exists in the workspace
|
|
774
|
+
if (fs.existsSync(path.join(resolvedCwd, ".codegraph")) && changedFiles.length > 0) {
|
|
775
|
+
try {
|
|
776
|
+
const queryTerm = path.basename(changedFiles[0], path.extname(changedFiles[0]));
|
|
777
|
+
const cgOut = execFileSync("codegraph", ["query", queryTerm], {
|
|
778
|
+
cwd: resolvedCwd,
|
|
779
|
+
encoding: "utf8",
|
|
780
|
+
timeout: 1200,
|
|
781
|
+
stdio: ["ignore", "pipe", "ignore"]
|
|
782
|
+
}).trim();
|
|
783
|
+
if (cgOut) {
|
|
784
|
+
contracts["[codegraph_symbol_relations]"] = cgOut.slice(0, 900);
|
|
785
|
+
}
|
|
786
|
+
}
|
|
787
|
+
catch {
|
|
788
|
+
// non-fatal if codegraph binary is not in PATH or times out
|
|
789
|
+
}
|
|
790
|
+
}
|
|
791
|
+
return contracts;
|
|
792
|
+
}
|
|
793
|
+
/**
|
|
794
|
+
* Splits multi-point specifications (e.g., `(1) ... (2) ...` or `1. ... 2. ...` or bulleted lists)
|
|
795
|
+
* into discrete requirement items and pre-maps each requirement against changed files and touched symbols.
|
|
796
|
+
*/
|
|
797
|
+
export function buildSpecRequirementMatrix(spec, structuralMap, rawDiff) {
|
|
798
|
+
if (!spec || !spec.trim())
|
|
799
|
+
return [];
|
|
800
|
+
// Split by numbered items `(1)`, `1.`, `1)` or markdown bullets or semicolons when multi-clause
|
|
801
|
+
const rawSegments = spec
|
|
802
|
+
.split(/(?:\r?\n)+\s*(?:[-*•]|\(?\d+[.)])\s+|\s+\(\d+\)\s+/g)
|
|
803
|
+
.map((s) => s.trim())
|
|
804
|
+
.filter((s) => s.length >= 8);
|
|
805
|
+
const segments = rawSegments.length > 1
|
|
806
|
+
? rawSegments
|
|
807
|
+
: spec
|
|
808
|
+
.split(/\s*;\s+/g)
|
|
809
|
+
.map((s) => s.trim())
|
|
810
|
+
.filter((s) => s.length >= 12);
|
|
811
|
+
const stopWords = new Set([
|
|
812
|
+
"the",
|
|
813
|
+
"and",
|
|
814
|
+
"for",
|
|
815
|
+
"with",
|
|
816
|
+
"from",
|
|
817
|
+
"that",
|
|
818
|
+
"this",
|
|
819
|
+
"into",
|
|
820
|
+
"when",
|
|
821
|
+
"only",
|
|
822
|
+
"must",
|
|
823
|
+
"should",
|
|
824
|
+
"keep",
|
|
825
|
+
"make",
|
|
826
|
+
"update",
|
|
827
|
+
"add",
|
|
828
|
+
"fix",
|
|
829
|
+
"trong",
|
|
830
|
+
"các",
|
|
831
|
+
"của",
|
|
832
|
+
"cho",
|
|
833
|
+
"không",
|
|
834
|
+
"được",
|
|
835
|
+
"với",
|
|
836
|
+
"khi",
|
|
837
|
+
"nhưng",
|
|
838
|
+
"phải",
|
|
839
|
+
"thêm",
|
|
840
|
+
"sửa"
|
|
841
|
+
]);
|
|
842
|
+
const addedLinesLower = rawDiff
|
|
843
|
+
.split(/\r?\n/)
|
|
844
|
+
.filter((l) => l.startsWith("+") && !l.startsWith("+++"))
|
|
845
|
+
.join("\n")
|
|
846
|
+
.toLowerCase();
|
|
847
|
+
return segments.slice(0, 12).map((reqText, idx) => {
|
|
848
|
+
const tokens = Array.from(new Set(reqText
|
|
849
|
+
.split(/[^A-Za-z0-9_./-]+/)
|
|
850
|
+
.map((t) => t.trim())
|
|
851
|
+
.filter((t) => t.length >= 3 && !stopWords.has(t.toLowerCase()))));
|
|
852
|
+
const matchedFiles = [];
|
|
853
|
+
const matchedEvidence = [];
|
|
854
|
+
for (const fileEntry of structuralMap) {
|
|
855
|
+
const fileLower = fileEntry.file.toLowerCase();
|
|
856
|
+
const symbolsLower = fileEntry.touchedSymbols.map((s) => s.toLowerCase());
|
|
857
|
+
const hunksLower = fileEntry.hunkHeaders.join(" ").toLowerCase();
|
|
858
|
+
for (const tok of tokens) {
|
|
859
|
+
const tokLower = tok.toLowerCase();
|
|
860
|
+
if (fileLower.includes(tokLower)) {
|
|
861
|
+
if (!matchedFiles.includes(fileEntry.file))
|
|
862
|
+
matchedFiles.push(fileEntry.file);
|
|
863
|
+
}
|
|
864
|
+
for (let sIdx = 0; sIdx < symbolsLower.length; sIdx++) {
|
|
865
|
+
if (symbolsLower[sIdx].includes(tokLower) || tokLower.includes(symbolsLower[sIdx])) {
|
|
866
|
+
if (!matchedFiles.includes(fileEntry.file))
|
|
867
|
+
matchedFiles.push(fileEntry.file);
|
|
868
|
+
const ev = `${fileEntry.file}#${fileEntry.touchedSymbols[sIdx]}`;
|
|
869
|
+
if (!matchedEvidence.includes(ev))
|
|
870
|
+
matchedEvidence.push(ev);
|
|
871
|
+
}
|
|
872
|
+
}
|
|
873
|
+
if (hunksLower.includes(tokLower) && !matchedFiles.includes(fileEntry.file)) {
|
|
874
|
+
matchedFiles.push(fileEntry.file);
|
|
875
|
+
}
|
|
876
|
+
}
|
|
877
|
+
}
|
|
878
|
+
if (matchedEvidence.length === 0) {
|
|
879
|
+
for (const tok of tokens) {
|
|
880
|
+
if (tok.length >= 4 && addedLinesLower.includes(tok.toLowerCase())) {
|
|
881
|
+
matchedEvidence.push(`diff:+${tok}`);
|
|
882
|
+
if (matchedEvidence.length >= 5)
|
|
883
|
+
break;
|
|
884
|
+
}
|
|
885
|
+
}
|
|
886
|
+
}
|
|
887
|
+
return {
|
|
888
|
+
id: `REQ_${idx + 1}`,
|
|
889
|
+
requirement: reqText.slice(0, 240),
|
|
890
|
+
matchedFiles: matchedFiles.slice(0, 6),
|
|
891
|
+
matchedEvidence: matchedEvidence.slice(0, 6)
|
|
892
|
+
};
|
|
893
|
+
});
|
|
894
|
+
}
|
|
895
|
+
/**
|
|
896
|
+
* Extracts the top imports, auth middleware, and validation schema headers of modified files
|
|
897
|
+
* so `jev_audit_code` does not false-flag partial diffs whose imports/validators sit at the top of the file.
|
|
898
|
+
*/
|
|
899
|
+
export function extractFileHeaderContext(cwd, filePath, changedFiles = []) {
|
|
900
|
+
const resolvedCwd = path.resolve(cwd);
|
|
901
|
+
const targets = [];
|
|
902
|
+
if (filePath && filePath !== "local git diff" && filePath !== "unknown") {
|
|
903
|
+
targets.push(filePath);
|
|
904
|
+
}
|
|
905
|
+
for (const f of changedFiles) {
|
|
906
|
+
if (targets.length >= 5)
|
|
907
|
+
break;
|
|
908
|
+
if (!targets.includes(f) && /\.(ts|tsx|js|jsx|mjs|py|go)$/i.test(f)) {
|
|
909
|
+
targets.push(f);
|
|
910
|
+
}
|
|
911
|
+
}
|
|
912
|
+
const headers = {};
|
|
913
|
+
for (const relOrAbs of targets) {
|
|
914
|
+
const fullPath = path.isAbsolute(relOrAbs)
|
|
915
|
+
? relOrAbs
|
|
916
|
+
: path.join(resolvedCwd, relOrAbs);
|
|
917
|
+
try {
|
|
918
|
+
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile())
|
|
919
|
+
continue;
|
|
920
|
+
const lines = fs
|
|
921
|
+
.readFileSync(fullPath, "utf8")
|
|
922
|
+
.split(/\r?\n/)
|
|
923
|
+
.slice(0, 55)
|
|
924
|
+
.join("\n")
|
|
925
|
+
.trim();
|
|
926
|
+
if (lines) {
|
|
927
|
+
headers[relOrAbs] = lines.slice(0, 1800);
|
|
928
|
+
}
|
|
929
|
+
}
|
|
930
|
+
catch {
|
|
931
|
+
// ignore unreadable files
|
|
932
|
+
}
|
|
933
|
+
}
|
|
934
|
+
return headers;
|
|
935
|
+
}
|
|
936
|
+
const repoFilesCache = new Map();
|
|
937
|
+
function listWorkspaceSourceFiles(cwd, maxFiles = 380) {
|
|
938
|
+
const resolved = path.resolve(cwd);
|
|
939
|
+
const now = Date.now();
|
|
940
|
+
const cached = repoFilesCache.get(resolved);
|
|
941
|
+
if (cached && cached.expiresAt > now) {
|
|
942
|
+
return cached.files;
|
|
943
|
+
}
|
|
944
|
+
const ignored = new Set([
|
|
945
|
+
".git",
|
|
946
|
+
"node_modules",
|
|
947
|
+
"dist",
|
|
948
|
+
"build",
|
|
949
|
+
".next",
|
|
950
|
+
".turbo",
|
|
951
|
+
"__pycache__",
|
|
952
|
+
".venv",
|
|
953
|
+
"venv",
|
|
954
|
+
".pytest_cache",
|
|
955
|
+
"coverage",
|
|
956
|
+
".codegraph"
|
|
957
|
+
]);
|
|
958
|
+
const collected = [];
|
|
959
|
+
function walk(dir, depth) {
|
|
960
|
+
if (depth > 5 || collected.length >= maxFiles)
|
|
961
|
+
return;
|
|
962
|
+
let entries = [];
|
|
963
|
+
try {
|
|
964
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
965
|
+
}
|
|
966
|
+
catch {
|
|
967
|
+
return;
|
|
968
|
+
}
|
|
969
|
+
for (const entry of entries) {
|
|
970
|
+
if (collected.length >= maxFiles)
|
|
971
|
+
break;
|
|
972
|
+
if (ignored.has(entry.name) || entry.name.startsWith("."))
|
|
973
|
+
continue;
|
|
974
|
+
const full = path.join(dir, entry.name);
|
|
975
|
+
if (entry.isDirectory()) {
|
|
976
|
+
walk(full, depth + 1);
|
|
977
|
+
}
|
|
978
|
+
else if (/\.(ts|tsx|js|jsx|mjs|py|go|prisma|sql)$/i.test(entry.name)) {
|
|
979
|
+
collected.push(path.relative(resolved, full).replace(/\\/g, "/"));
|
|
980
|
+
}
|
|
981
|
+
}
|
|
982
|
+
}
|
|
983
|
+
walk(resolved, 0);
|
|
984
|
+
repoFilesCache.set(resolved, { expiresAt: now + 30_000, files: collected });
|
|
985
|
+
return collected;
|
|
986
|
+
}
|
|
987
|
+
/**
|
|
988
|
+
* Upward Blast-Radius / Caller Graph:
|
|
989
|
+
* Scans workspace source files to identify which files import the modified files or reference
|
|
990
|
+
* their touched symbols, distinguishing callers that were updated in the diff (`modifiedDependents`)
|
|
991
|
+
* from untouched callers (`unmodifiedDependents` — potential breaking change candidates).
|
|
992
|
+
*/
|
|
993
|
+
export function extractReverseDependents(cwd, changedFiles, structuralMap = []) {
|
|
994
|
+
const resolvedCwd = path.resolve(cwd);
|
|
995
|
+
const changedNorm = new Set(changedFiles.map((f) => f.replace(/\\/g, "/")));
|
|
996
|
+
const targetStems = changedFiles
|
|
997
|
+
.filter((f) => /\.(ts|tsx|js|jsx|mjs|py|go)$/i.test(f))
|
|
998
|
+
.slice(0, 8)
|
|
999
|
+
.map((f) => path.basename(f, path.extname(f)))
|
|
1000
|
+
.filter((stem) => stem && stem !== "index" && stem !== "__init__" && stem.length >= 3);
|
|
1001
|
+
const touchedSymbols = Array.from(new Set(structuralMap
|
|
1002
|
+
.flatMap((m) => m.touchedSymbols)
|
|
1003
|
+
.filter((s) => s.length >= 4 && !s.startsWith(".") && !s.startsWith("#")))).slice(0, 12);
|
|
1004
|
+
if (targetStems.length === 0 && touchedSymbols.length === 0) {
|
|
1005
|
+
return {
|
|
1006
|
+
modifiedDependents: [],
|
|
1007
|
+
unmodifiedDependents: [],
|
|
1008
|
+
referencedTouchedSymbols: {}
|
|
1009
|
+
};
|
|
1010
|
+
}
|
|
1011
|
+
const allSourceFiles = listWorkspaceSourceFiles(resolvedCwd);
|
|
1012
|
+
const modifiedDependents = [];
|
|
1013
|
+
const unmodifiedDependents = [];
|
|
1014
|
+
const referencedTouchedSymbols = {};
|
|
1015
|
+
for (const relFile of allSourceFiles) {
|
|
1016
|
+
if (modifiedDependents.length + unmodifiedDependents.length >= 16)
|
|
1017
|
+
break;
|
|
1018
|
+
const fullPath = path.join(resolvedCwd, relFile);
|
|
1019
|
+
try {
|
|
1020
|
+
const content = fs.readFileSync(fullPath, "utf8").slice(0, 12000);
|
|
1021
|
+
const importsChangedStem = targetStems.some((stem) => content.includes(`/${stem}`) ||
|
|
1022
|
+
content.includes(`.${stem}`) ||
|
|
1023
|
+
content.includes(`"${stem}"`) ||
|
|
1024
|
+
content.includes(`'${stem}'`));
|
|
1025
|
+
if (importsChangedStem) {
|
|
1026
|
+
if (changedNorm.has(relFile)) {
|
|
1027
|
+
if (!modifiedDependents.includes(relFile))
|
|
1028
|
+
modifiedDependents.push(relFile);
|
|
1029
|
+
}
|
|
1030
|
+
else if (!unmodifiedDependents.includes(relFile)) {
|
|
1031
|
+
unmodifiedDependents.push(relFile);
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
if (!changedNorm.has(relFile)) {
|
|
1035
|
+
for (const sym of touchedSymbols) {
|
|
1036
|
+
if (content.includes(sym)) {
|
|
1037
|
+
referencedTouchedSymbols[sym] = referencedTouchedSymbols[sym] ?? [];
|
|
1038
|
+
if (referencedTouchedSymbols[sym].length < 5 && !referencedTouchedSymbols[sym].includes(relFile)) {
|
|
1039
|
+
referencedTouchedSymbols[sym].push(relFile);
|
|
1040
|
+
}
|
|
1041
|
+
}
|
|
1042
|
+
}
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
catch {
|
|
1046
|
+
// ignore read errors
|
|
1047
|
+
}
|
|
1048
|
+
}
|
|
1049
|
+
return {
|
|
1050
|
+
modifiedDependents: modifiedDependents.slice(0, 10),
|
|
1051
|
+
unmodifiedDependents: unmodifiedDependents.slice(0, 10),
|
|
1052
|
+
referencedTouchedSymbols
|
|
1053
|
+
};
|
|
1054
|
+
}
|
|
1055
|
+
/**
|
|
1056
|
+
* Companion Test Suite Discovery:
|
|
1057
|
+
* Finds existing unit/integration test files (`*.test.ts`, `*.spec.ts`, `test_*.py`) on disk
|
|
1058
|
+
* corresponding to the modified files (even when those test files weren't edited in the diff!)
|
|
1059
|
+
* and extracts their test case titles so Jev knows what automated test coverage already exists.
|
|
1060
|
+
*/
|
|
1061
|
+
export function extractCompanionTestsContext(cwd, changedFiles, maxTestFiles = 6) {
|
|
1062
|
+
const resolvedCwd = path.resolve(cwd);
|
|
1063
|
+
const allFiles = listWorkspaceSourceFiles(resolvedCwd);
|
|
1064
|
+
const testFilesInRepo = allFiles.filter((f) => /\.(test|spec)\.(ts|tsx|js|jsx|mjs)$/i.test(f) ||
|
|
1065
|
+
/(?:^|\/)test_[^/]+\.py$/i.test(f) ||
|
|
1066
|
+
/_test\.(py|go)$/i.test(f));
|
|
1067
|
+
const stems = changedFiles
|
|
1068
|
+
.map((f) => path
|
|
1069
|
+
.basename(f, path.extname(f))
|
|
1070
|
+
.replace(/\.(test|spec)$/i, "")
|
|
1071
|
+
.replace(/^test_/i, ""))
|
|
1072
|
+
.filter((s) => s.length >= 3);
|
|
1073
|
+
const matchedTestFiles = [];
|
|
1074
|
+
for (const tf of testFilesInRepo) {
|
|
1075
|
+
if (matchedTestFiles.length >= maxTestFiles)
|
|
1076
|
+
break;
|
|
1077
|
+
const tfLower = tf.toLowerCase();
|
|
1078
|
+
const directNameMatch = changedFiles.some((cf) => cf.replace(/\\/g, "/").toLowerCase() === tfLower) ||
|
|
1079
|
+
stems.some((stem) => tfLower.includes(stem.toLowerCase()));
|
|
1080
|
+
if (directNameMatch) {
|
|
1081
|
+
matchedTestFiles.push(tf);
|
|
1082
|
+
continue;
|
|
1083
|
+
}
|
|
1084
|
+
// Also check if the test file imports any of the changed file stems (e.g. policy-presets.test.ts importing policy-engine)
|
|
1085
|
+
try {
|
|
1086
|
+
const head = fs.readFileSync(path.join(resolvedCwd, tf), "utf8").slice(0, 2500);
|
|
1087
|
+
if (stems.some((stem) => head.includes(stem))) {
|
|
1088
|
+
matchedTestFiles.push(tf);
|
|
1089
|
+
}
|
|
1090
|
+
}
|
|
1091
|
+
catch {
|
|
1092
|
+
// ignore
|
|
1093
|
+
}
|
|
1094
|
+
}
|
|
1095
|
+
const testCasesByFile = {};
|
|
1096
|
+
const testCaseRegex = /(?:^\s*(?:test|it|describe)\(\s*["'`]([^"'`]+)["'`]|^\s*(?:async\s+)?def\s+(test_[A-Za-z0-9_]+))/gm;
|
|
1097
|
+
for (const relTest of matchedTestFiles) {
|
|
1098
|
+
try {
|
|
1099
|
+
const raw = fs.readFileSync(path.join(resolvedCwd, relTest), "utf8").slice(0, 15000);
|
|
1100
|
+
const cases = [];
|
|
1101
|
+
for (const m of raw.matchAll(testCaseRegex)) {
|
|
1102
|
+
const title = (m[1] ?? m[2] ?? "").trim();
|
|
1103
|
+
if (title && cases.length < 12 && !cases.includes(title)) {
|
|
1104
|
+
cases.push(title.slice(0, 110));
|
|
1105
|
+
}
|
|
1106
|
+
}
|
|
1107
|
+
if (cases.length > 0) {
|
|
1108
|
+
testCasesByFile[relTest] = cases;
|
|
1109
|
+
}
|
|
1110
|
+
}
|
|
1111
|
+
catch {
|
|
1112
|
+
// ignore
|
|
1113
|
+
}
|
|
1114
|
+
}
|
|
1115
|
+
return testCasesByFile;
|
|
1116
|
+
}
|
|
1117
|
+
/**
|
|
1118
|
+
* Domain Schema, Auth/Validation Convention & Environment Contract Fingerprint:
|
|
1119
|
+
* Extracts database/domain models (`schema.prisma`, `models.py`, `packages/contracts`),
|
|
1120
|
+
* `.env.example` variable names (never secret values!), and security/runtime conventions
|
|
1121
|
+
* (e.g., whether the workspace is an infrastructure/Proxmox CLI lab repo or a web app).
|
|
1122
|
+
*/
|
|
1123
|
+
export function extractDomainAndRuntimeFingerprint(cwd) {
|
|
1124
|
+
const resolvedCwd = path.resolve(cwd);
|
|
1125
|
+
const parts = [];
|
|
1126
|
+
// 1. Check .env.example / .env.sample variable keys (only key names, never values)
|
|
1127
|
+
for (const envName of [".env.example", ".env.sample", "backend/.env.example"]) {
|
|
1128
|
+
const envPath = path.join(resolvedCwd, envName);
|
|
1129
|
+
if (fs.existsSync(envPath)) {
|
|
1130
|
+
try {
|
|
1131
|
+
const keys = fs
|
|
1132
|
+
.readFileSync(envPath, "utf8")
|
|
1133
|
+
.split(/\r?\n/)
|
|
1134
|
+
.map((l) => l.trim())
|
|
1135
|
+
.filter((l) => l && !l.startsWith("#") && l.includes("="))
|
|
1136
|
+
.map((l) => l.split("=")[0].trim())
|
|
1137
|
+
.filter(Boolean)
|
|
1138
|
+
.slice(0, 18);
|
|
1139
|
+
if (keys.length > 0) {
|
|
1140
|
+
parts.push(`env_contract_keys=[${keys.join(", ")}]`);
|
|
1141
|
+
break;
|
|
1142
|
+
}
|
|
1143
|
+
}
|
|
1144
|
+
catch {
|
|
1145
|
+
// ignore
|
|
1146
|
+
}
|
|
1147
|
+
}
|
|
1148
|
+
}
|
|
1149
|
+
// 2. Check Prisma / SQLAlchemy / Contracts domain models
|
|
1150
|
+
const prismaPath = [
|
|
1151
|
+
path.join(resolvedCwd, "prisma", "schema.prisma"),
|
|
1152
|
+
path.join(resolvedCwd, "packages", "db", "prisma", "schema.prisma"),
|
|
1153
|
+
path.join(resolvedCwd, "apps", "api", "prisma", "schema.prisma")
|
|
1154
|
+
].find((p) => fs.existsSync(p));
|
|
1155
|
+
if (prismaPath) {
|
|
1156
|
+
try {
|
|
1157
|
+
const raw = fs.readFileSync(prismaPath, "utf8");
|
|
1158
|
+
const models = Array.from(raw.matchAll(/^model\s+([A-Za-z0-9_]+)\s*\{/gm), (m) => m[1]);
|
|
1159
|
+
if (models.length > 0) {
|
|
1160
|
+
parts.push(`prisma_models=[${models.slice(0, 20).join(", ")}]`);
|
|
1161
|
+
}
|
|
1162
|
+
}
|
|
1163
|
+
catch {
|
|
1164
|
+
// ignore
|
|
1165
|
+
}
|
|
1166
|
+
}
|
|
1167
|
+
// 3. Detect execution & security archetype (e.g., Proxmox/Lab CLI ops vs Web API vs Game Server)
|
|
1168
|
+
const allFiles = listWorkspaceSourceFiles(resolvedCwd, 200);
|
|
1169
|
+
const hasLabScripts = allFiles.some((f) => /^scripts\/lab\//i.test(f) || /proxmox/i.test(f));
|
|
1170
|
+
const hasContractsPkg = allFiles.some((f) => /^packages\/contracts\//i.test(f));
|
|
1171
|
+
const hasFastApi = allFiles.some((f) => /^backend\/app\//i.test(f));
|
|
1172
|
+
const archetypes = [];
|
|
1173
|
+
if (hasLabScripts) {
|
|
1174
|
+
archetypes.push("authorized_infra_lab_automation (CLI/SSH/Proxmox scripts in scripts/lab/ are intended operator tools)");
|
|
1175
|
+
}
|
|
1176
|
+
if (hasContractsPkg) {
|
|
1177
|
+
archetypes.push("shared_typesafe_monorepo_contracts (packages/contracts)");
|
|
1178
|
+
}
|
|
1179
|
+
if (hasFastApi) {
|
|
1180
|
+
archetypes.push("fastapi_pydantic_backend (backend/app)");
|
|
1181
|
+
}
|
|
1182
|
+
if (archetypes.length > 0) {
|
|
1183
|
+
parts.push(`archetypes=[${archetypes.join("; ")}]`);
|
|
1184
|
+
}
|
|
1185
|
+
return parts.join(" | ").slice(0, 900);
|
|
1186
|
+
}
|
|
1187
|
+
/**
|
|
1188
|
+
* Persists a learned Project Brain profile to `~/.mcp-jev/projects/<workspaceName>.json`
|
|
1189
|
+
* so Jev retains permanent architectural memory of each project across restarts.
|
|
1190
|
+
*/
|
|
1191
|
+
export function getProjectBrainFilePath(workspaceName) {
|
|
1192
|
+
const safeName = (workspaceName || "workspace").replace(/[^A-Za-z0-9_.-]/g, "_");
|
|
1193
|
+
const brainDir = path.join(os.homedir(), ".mcp-jev", "projects");
|
|
1194
|
+
if (!fs.existsSync(brainDir)) {
|
|
1195
|
+
fs.mkdirSync(brainDir, { recursive: true });
|
|
1196
|
+
}
|
|
1197
|
+
return path.join(brainDir, `${safeName}.json`);
|
|
1198
|
+
}
|
|
1199
|
+
export function readLearnedHumanOverrides(workspaceName) {
|
|
1200
|
+
try {
|
|
1201
|
+
const brainPath = getProjectBrainFilePath(workspaceName);
|
|
1202
|
+
if (!fs.existsSync(brainPath))
|
|
1203
|
+
return [];
|
|
1204
|
+
const parsed = JSON.parse(fs.readFileSync(brainPath, "utf8"));
|
|
1205
|
+
return Array.isArray(parsed.learnedHumanOverrides) ? parsed.learnedHumanOverrides : [];
|
|
1206
|
+
}
|
|
1207
|
+
catch {
|
|
1208
|
+
return [];
|
|
1209
|
+
}
|
|
1210
|
+
}
|
|
1211
|
+
export function syncProjectBrainProfile(dna) {
|
|
1212
|
+
try {
|
|
1213
|
+
const brainPath = getProjectBrainFilePath(dna.workspaceName);
|
|
1214
|
+
const existingOverrides = readLearnedHumanOverrides(dna.workspaceName);
|
|
1215
|
+
const payload = {
|
|
1216
|
+
updatedAt: new Date().toISOString(),
|
|
1217
|
+
workspaceName: dna.workspaceName,
|
|
1218
|
+
workspacePath: dna.workspacePath,
|
|
1219
|
+
stackSummary: dna.stackSummary,
|
|
1220
|
+
repoTopology: dna.repoTopology,
|
|
1221
|
+
domainAndAuthFingerprint: dna.domainAndAuthFingerprint,
|
|
1222
|
+
projectRulesExcerpt: dna.projectRulesExcerpt?.slice(0, 1500),
|
|
1223
|
+
activeMemoryExcerpt: dna.activeMemoryExcerpt?.slice(0, 1000),
|
|
1224
|
+
learnedHumanOverrides: dna.learnedHumanOverrides && dna.learnedHumanOverrides.length > 0
|
|
1225
|
+
? dna.learnedHumanOverrides
|
|
1226
|
+
: existingOverrides
|
|
1227
|
+
};
|
|
1228
|
+
fs.writeFileSync(brainPath, JSON.stringify(payload, null, 2), "utf8");
|
|
1229
|
+
return brainPath;
|
|
1230
|
+
}
|
|
1231
|
+
catch {
|
|
1232
|
+
return undefined;
|
|
1233
|
+
}
|
|
1234
|
+
}
|
|
1235
|
+
/**
|
|
1236
|
+
* Records a human feedback / override rule into the persistent Project Brain (`~/.mcp-jev/projects/<workspaceName>.json`)
|
|
1237
|
+
* so Jev immediately learns from user corrections and never repeats a false-positive BLOCK on that project.
|
|
1238
|
+
*/
|
|
1239
|
+
export function recordProjectFeedbackRule(input) {
|
|
1240
|
+
const wsName = input.workspaceName || "workspace";
|
|
1241
|
+
if (input.workspacePath && fs.existsSync(input.workspacePath)) {
|
|
1242
|
+
buildProjectContextEnvelope(input.workspacePath);
|
|
1243
|
+
}
|
|
1244
|
+
const brainPath = getProjectBrainFilePath(wsName);
|
|
1245
|
+
let existingPayload = {
|
|
1246
|
+
updatedAt: new Date().toISOString(),
|
|
1247
|
+
workspaceName: wsName,
|
|
1248
|
+
workspacePath: input.workspacePath ?? wsName,
|
|
1249
|
+
stackSummary: "generic workspace",
|
|
1250
|
+
repoTopology: ""
|
|
1251
|
+
};
|
|
1252
|
+
if (fs.existsSync(brainPath)) {
|
|
1253
|
+
try {
|
|
1254
|
+
existingPayload = JSON.parse(fs.readFileSync(brainPath, "utf8"));
|
|
1255
|
+
}
|
|
1256
|
+
catch {
|
|
1257
|
+
// ignore malformed JSON
|
|
1258
|
+
}
|
|
1259
|
+
}
|
|
1260
|
+
const overrides = Array.isArray(existingPayload.learnedHumanOverrides)
|
|
1261
|
+
? existingPayload.learnedHumanOverrides
|
|
1262
|
+
: [];
|
|
1263
|
+
const newEntry = {
|
|
1264
|
+
id: `rule_${Date.now()}_${Math.random().toString(36).slice(2, 6)}`,
|
|
1265
|
+
createdAt: new Date().toISOString(),
|
|
1266
|
+
tool: input.tool || "all_tools",
|
|
1267
|
+
feedbackType: input.feedbackType,
|
|
1268
|
+
rule: input.rule.trim().slice(0, 500),
|
|
1269
|
+
eventId: input.eventId
|
|
1270
|
+
};
|
|
1271
|
+
const updatedOverrides = [newEntry, ...overrides.filter((o) => o.rule !== newEntry.rule)].slice(0, 25);
|
|
1272
|
+
existingPayload.updatedAt = new Date().toISOString();
|
|
1273
|
+
existingPayload.learnedHumanOverrides = updatedOverrides;
|
|
1274
|
+
fs.writeFileSync(brainPath, JSON.stringify(existingPayload, null, 2), "utf8");
|
|
1275
|
+
return newEntry;
|
|
1276
|
+
}
|
|
1277
|
+
export function removeProjectFeedbackRule(workspaceName, ruleId) {
|
|
1278
|
+
try {
|
|
1279
|
+
const brainPath = getProjectBrainFilePath(workspaceName);
|
|
1280
|
+
if (!fs.existsSync(brainPath))
|
|
1281
|
+
return false;
|
|
1282
|
+
const payload = JSON.parse(fs.readFileSync(brainPath, "utf8"));
|
|
1283
|
+
const overrides = Array.isArray(payload.learnedHumanOverrides)
|
|
1284
|
+
? payload.learnedHumanOverrides
|
|
1285
|
+
: [];
|
|
1286
|
+
payload.learnedHumanOverrides = overrides.filter((o) => o.id !== ruleId);
|
|
1287
|
+
payload.updatedAt = new Date().toISOString();
|
|
1288
|
+
fs.writeFileSync(brainPath, JSON.stringify(payload, null, 2), "utf8");
|
|
1289
|
+
return true;
|
|
1290
|
+
}
|
|
1291
|
+
catch {
|
|
1292
|
+
return false;
|
|
1293
|
+
}
|
|
1294
|
+
}
|
|
1295
|
+
export function listProjectBrainProfiles() {
|
|
1296
|
+
const brainDir = path.join(os.homedir(), ".mcp-jev", "projects");
|
|
1297
|
+
try {
|
|
1298
|
+
if (!fs.existsSync(brainDir)) {
|
|
1299
|
+
fs.mkdirSync(brainDir, { recursive: true });
|
|
1300
|
+
}
|
|
1301
|
+
// Ensure active workspaces from recent events have an up-to-date brain profile if they exist on disk
|
|
1302
|
+
const recentEvents = readSessionEvents(120);
|
|
1303
|
+
const seenWs = new Set();
|
|
1304
|
+
for (const ev of recentEvents) {
|
|
1305
|
+
if (ev.workspacePath &&
|
|
1306
|
+
!seenWs.has(ev.workspacePath) &&
|
|
1307
|
+
!isGenericHostDirectory(ev.workspacePath) &&
|
|
1308
|
+
fs.existsSync(ev.workspacePath)) {
|
|
1309
|
+
seenWs.add(ev.workspacePath);
|
|
1310
|
+
const targetJson = getProjectBrainFilePath(ev.workspace);
|
|
1311
|
+
if (!fs.existsSync(targetJson)) {
|
|
1312
|
+
buildProjectContextEnvelope(ev.workspacePath);
|
|
1313
|
+
}
|
|
1314
|
+
}
|
|
1315
|
+
}
|
|
1316
|
+
const files = fs.readdirSync(brainDir).filter((f) => f.endsWith(".json"));
|
|
1317
|
+
const profiles = [];
|
|
1318
|
+
for (const file of files) {
|
|
1319
|
+
try {
|
|
1320
|
+
const parsed = JSON.parse(fs.readFileSync(path.join(brainDir, file), "utf8"));
|
|
1321
|
+
profiles.push(parsed);
|
|
1322
|
+
}
|
|
1323
|
+
catch {
|
|
1324
|
+
// ignore
|
|
1325
|
+
}
|
|
1326
|
+
}
|
|
1327
|
+
return profiles;
|
|
1328
|
+
}
|
|
1329
|
+
catch {
|
|
1330
|
+
return [];
|
|
1331
|
+
}
|
|
1332
|
+
}
|
|
1333
|
+
/**
|
|
1334
|
+
* Fast Pre-Flight Syntax & Compiler Probe:
|
|
1335
|
+
* Runs deterministic <700ms syntax checks (`python -m py_compile` for `.py`, `node --check` for `.js`/`.mjs`,
|
|
1336
|
+
* `JSON.parse` for `.json`) on modified files before sending the diff to Jev so Jev gets hard compiler ground truth.
|
|
1337
|
+
*/
|
|
1338
|
+
export function runFastSyntaxProbe(cwd, changedFiles) {
|
|
1339
|
+
const resolvedCwd = path.resolve(cwd);
|
|
1340
|
+
const checkedFiles = [];
|
|
1341
|
+
const errors = [];
|
|
1342
|
+
for (const rel of changedFiles.slice(0, 6)) {
|
|
1343
|
+
const fullPath = path.isAbsolute(rel) ? rel : path.join(resolvedCwd, rel);
|
|
1344
|
+
if (!fs.existsSync(fullPath) || !fs.statSync(fullPath).isFile())
|
|
1345
|
+
continue;
|
|
1346
|
+
if (rel.endsWith(".json")) {
|
|
1347
|
+
checkedFiles.push(rel);
|
|
1348
|
+
try {
|
|
1349
|
+
JSON.parse(fs.readFileSync(fullPath, "utf8"));
|
|
1350
|
+
}
|
|
1351
|
+
catch (err) {
|
|
1352
|
+
errors.push(`${rel}: JSON syntax error (${err instanceof Error ? err.message : "invalid"})`);
|
|
1353
|
+
}
|
|
1354
|
+
}
|
|
1355
|
+
else if (/\.(js|mjs|cjs)$/i.test(rel)) {
|
|
1356
|
+
checkedFiles.push(rel);
|
|
1357
|
+
try {
|
|
1358
|
+
execFileSync(process.execPath, ["--check", fullPath], {
|
|
1359
|
+
cwd: resolvedCwd,
|
|
1360
|
+
encoding: "utf8",
|
|
1361
|
+
timeout: 700,
|
|
1362
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1363
|
+
});
|
|
1364
|
+
}
|
|
1365
|
+
catch (err) {
|
|
1366
|
+
const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr) : "SyntaxError";
|
|
1367
|
+
errors.push(`${rel}: ${stderr.trim().slice(0, 240)}`);
|
|
1368
|
+
}
|
|
1369
|
+
}
|
|
1370
|
+
else if (/\.py$/i.test(rel)) {
|
|
1371
|
+
checkedFiles.push(rel);
|
|
1372
|
+
try {
|
|
1373
|
+
execFileSync(resolvePythonExecutable(), ["-m", "py_compile", fullPath], {
|
|
1374
|
+
cwd: resolvedCwd,
|
|
1375
|
+
encoding: "utf8",
|
|
1376
|
+
timeout: 800,
|
|
1377
|
+
stdio: ["ignore", "pipe", "pipe"]
|
|
1378
|
+
});
|
|
1379
|
+
}
|
|
1380
|
+
catch (err) {
|
|
1381
|
+
const stderr = err && typeof err === "object" && "stderr" in err ? String(err.stderr) : "";
|
|
1382
|
+
if (stderr.includes("SyntaxError") || stderr.includes("IndentationError")) {
|
|
1383
|
+
errors.push(`${rel}: ${stderr.trim().slice(0, 240)}`);
|
|
1384
|
+
}
|
|
1385
|
+
}
|
|
1386
|
+
}
|
|
1387
|
+
}
|
|
1388
|
+
if (checkedFiles.length === 0) {
|
|
1389
|
+
return { status: "SKIPPED", checkedFiles: [], errors: [] };
|
|
1390
|
+
}
|
|
1391
|
+
return {
|
|
1392
|
+
status: errors.length > 0 ? "SYNTAX_ERROR" : "PASS",
|
|
1393
|
+
checkedFiles,
|
|
1394
|
+
errors
|
|
1395
|
+
};
|
|
1396
|
+
}
|
|
1397
|
+
//# sourceMappingURL=context-enricher.js.map
|