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.
Files changed (78) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +364 -2
  3. package/THIRD_PARTY_NOTICES.md +25 -0
  4. package/dist/src/cli/hook-runner.d.ts +27 -0
  5. package/dist/src/cli/hook-runner.js +196 -0
  6. package/dist/src/cli/hook-runner.js.map +1 -0
  7. package/dist/src/cli/index.d.ts +2 -0
  8. package/dist/src/cli/index.js +173 -0
  9. package/dist/src/cli/index.js.map +1 -0
  10. package/dist/src/cli/setup.d.ts +14 -0
  11. package/dist/src/cli/setup.js +122 -0
  12. package/dist/src/cli/setup.js.map +1 -0
  13. package/dist/src/core/cache.d.ts +16 -0
  14. package/dist/src/core/cache.js +64 -0
  15. package/dist/src/core/cache.js.map +1 -0
  16. package/dist/src/core/command-shape.d.ts +17 -0
  17. package/dist/src/core/command-shape.js +138 -0
  18. package/dist/src/core/command-shape.js.map +1 -0
  19. package/dist/src/core/context-enricher.d.ts +149 -0
  20. package/dist/src/core/context-enricher.js +1397 -0
  21. package/dist/src/core/context-enricher.js.map +1 -0
  22. package/dist/src/core/event-log.d.ts +35 -0
  23. package/dist/src/core/event-log.js +241 -0
  24. package/dist/src/core/event-log.js.map +1 -0
  25. package/dist/src/core/git-collector.d.ts +18 -0
  26. package/dist/src/core/git-collector.js +227 -0
  27. package/dist/src/core/git-collector.js.map +1 -0
  28. package/dist/src/core/hybrid-ast-engine.d.ts +46 -0
  29. package/dist/src/core/hybrid-ast-engine.js +641 -0
  30. package/dist/src/core/hybrid-ast-engine.js.map +1 -0
  31. package/dist/src/core/jev-client.d.ts +50 -0
  32. package/dist/src/core/jev-client.js +262 -0
  33. package/dist/src/core/jev-client.js.map +1 -0
  34. package/dist/src/core/policy-config.d.ts +96 -0
  35. package/dist/src/core/policy-config.js +60 -0
  36. package/dist/src/core/policy-config.js.map +1 -0
  37. package/dist/src/core/policy-engine.d.ts +65 -0
  38. package/dist/src/core/policy-engine.js +344 -0
  39. package/dist/src/core/policy-engine.js.map +1 -0
  40. package/dist/src/core/presets.d.ts +18 -0
  41. package/dist/src/core/presets.js +180 -0
  42. package/dist/src/core/presets.js.map +1 -0
  43. package/dist/src/core/skill-auditor.d.ts +56 -0
  44. package/dist/src/core/skill-auditor.js +435 -0
  45. package/dist/src/core/skill-auditor.js.map +1 -0
  46. package/dist/src/core/telemetry.d.ts +30 -0
  47. package/dist/src/core/telemetry.js +55 -0
  48. package/dist/src/core/telemetry.js.map +1 -0
  49. package/dist/src/core/types.d.ts +89 -0
  50. package/dist/src/core/types.js +2 -0
  51. package/dist/src/core/types.js.map +1 -0
  52. package/dist/src/dashboard/server.d.ts +9 -0
  53. package/dist/src/dashboard/server.js +2425 -0
  54. package/dist/src/dashboard/server.js.map +1 -0
  55. package/dist/src/mcp/server.d.ts +137 -0
  56. package/dist/src/mcp/server.js +875 -0
  57. package/dist/src/mcp/server.js.map +1 -0
  58. package/package.json +75 -4
  59. package/skills/jev-system-one/SKILL.md +54 -0
  60. package/skills/vendor/codebase-design/DEEPENING.md +37 -0
  61. package/skills/vendor/codebase-design/DESIGN-IT-TWICE.md +44 -0
  62. package/skills/vendor/codebase-design/LICENSE +21 -0
  63. package/skills/vendor/codebase-design/SKILL.md +114 -0
  64. package/skills/vendor/gsap-performance/LICENSE +21 -0
  65. package/skills/vendor/gsap-performance/SKILL.md +79 -0
  66. package/skills/vendor/manifest.json +122 -0
  67. package/skills/vendor/security-best-practices/LICENSE.txt +201 -0
  68. package/skills/vendor/security-best-practices/SKILL.md +86 -0
  69. package/skills/vendor/security-best-practices/references/golang-general-backend-security.md +826 -0
  70. package/skills/vendor/security-best-practices/references/javascript-express-web-server-security.md +1158 -0
  71. package/skills/vendor/security-best-practices/references/javascript-general-web-frontend-security.md +747 -0
  72. package/skills/vendor/security-best-practices/references/javascript-jquery-web-frontend-security.md +678 -0
  73. package/skills/vendor/security-best-practices/references/javascript-typescript-nextjs-web-server-security.md +1144 -0
  74. package/skills/vendor/security-best-practices/references/javascript-typescript-react-web-frontend-security.md +990 -0
  75. package/skills/vendor/security-best-practices/references/javascript-typescript-vue-web-frontend-security.md +791 -0
  76. package/skills/vendor/security-best-practices/references/python-django-web-server-security.md +882 -0
  77. package/skills/vendor/security-best-practices/references/python-fastapi-web-server-security.md +1036 -0
  78. package/skills/vendor/security-best-practices/references/python-flask-web-server-security.md +705 -0
@@ -0,0 +1,875 @@
1
+ import fs from "node:fs";
2
+ import path from "node:path";
3
+ import { McpServer } from "@modelcontextprotocol/sdk/server/mcp.js";
4
+ import { StdioServerTransport } from "@modelcontextprotocol/sdk/server/stdio.js";
5
+ import { z } from "zod";
6
+ import { JevClient } from "../core/jev-client.js";
7
+ import { buildAutopilotProxyQuestions, buildBatchClassifyQuestions, buildCommandGuardQuestions, buildContextPruneQuestions, buildDiffVerificationQuestions, buildTaskRouteQuestions, DEFAULT_DEVELOPER_PROFILE } from "../core/presets.js";
8
+ import { buildUnverifiableCommandDecision, evaluateAutopilotProxy, evaluateCommandGate, evaluateDiffGate, extractContextPruneResults, findBlockingGuardEscalation } from "../core/policy-engine.js";
9
+ import { isAutopilotEnabled, JEV_POLICY } from "../core/policy-config.js";
10
+ import { assessCommandShape } from "../core/command-shape.js";
11
+ import { budgetMultiFileDiff, collectGitContext } from "../core/git-collector.js";
12
+ import { buildProjectContextEnvelope, buildSpecRequirementMatrix, extractCompanionTestsContext, extractCrossFileContracts, extractFileHeaderContext, extractPostEditHunkScopes, extractReferencedDocsAndFiles, extractReverseDependents, extractStructuralDiffMap, isGenericHostDirectory, isSensitiveFilePath, isWithinWorkspaceBoundary, resolveTargetWorkspace, runFastSyntaxProbe } from "../core/context-enricher.js";
13
+ import { auditCodeWithSkills } from "../core/skill-auditor.js";
14
+ import { extractHybridAstSkeletons, queryCodeGraphIntelligence, runHybridStaticAnalysis } from "../core/hybrid-ast-engine.js";
15
+ import { readSessionEvents, recordSessionEvent } from "../core/event-log.js";
16
+ const MAX_EXACT_COMMAND_CHARS = 20000;
17
+ const MAX_GUARD_CONTEXT_CHARS = 8000;
18
+ const MAX_LOGGED_COMMAND_CHARS = 2000;
19
+ const MAX_SPEC_CHARS = 16000;
20
+ const MAX_AUDIT_CODE_CHARS = 45000;
21
+ const MAX_TASK_CHARS = 12000;
22
+ const MAX_BATCH_ITEMS = 100;
23
+ const MAX_REMEMBERED_ESCALATIONS = 50;
24
+ /** How many recent log events to scan for cross-process guard escalations. */
25
+ const ESCALATION_SCAN_EVENTS = 300;
26
+ export class McpJevDispatcher {
27
+ client;
28
+ /** Guard ASK_USER/BLOCK verdicts issued by this process (works even if the log is read-only). */
29
+ guardEscalations = [];
30
+ constructor(client = new JevClient()) {
31
+ this.client = client;
32
+ }
33
+ getClient() {
34
+ return this.client;
35
+ }
36
+ rememberGuardEscalation(verdict, command, workspace, agent) {
37
+ if (verdict !== "ASK_USER" && verdict !== "BLOCK")
38
+ return;
39
+ this.guardEscalations.push({
40
+ timestamp: new Date().toISOString(),
41
+ verdict,
42
+ command: command.slice(0, MAX_LOGGED_COMMAND_CHARS),
43
+ workspace: workspace.workspaceName,
44
+ workspacePath: workspace.workspacePath,
45
+ agent
46
+ });
47
+ if (this.guardEscalations.length > MAX_REMEMBERED_ESCALATIONS) {
48
+ this.guardEscalations.splice(0, this.guardEscalations.length - MAX_REMEMBERED_ESCALATIONS);
49
+ }
50
+ }
51
+ /** Guard escalations from this process plus other agents' processes (shared event log). */
52
+ collectGuardEscalations() {
53
+ const logged = [];
54
+ for (const evt of readSessionEvents(ESCALATION_SCAN_EVENTS)) {
55
+ if (evt.tool !== "jev_guard_action")
56
+ continue;
57
+ if (evt.verdict !== "ASK_USER" && evt.verdict !== "BLOCK")
58
+ continue;
59
+ logged.push({
60
+ timestamp: evt.timestamp,
61
+ verdict: evt.verdict,
62
+ command: evt.optionsOrInput?.command ?? evt.questionOrTitle,
63
+ workspace: evt.workspace,
64
+ workspacePath: evt.workspacePath,
65
+ agent: evt.agent
66
+ });
67
+ }
68
+ return [...this.guardEscalations, ...logged];
69
+ }
70
+ async decide(input) {
71
+ const stateStr = typeof input.state === "string" ? input.state : JSON.stringify(input.state ?? "");
72
+ const resolvedCwd = resolveTargetWorkspace(input.working_directory, [stateStr]);
73
+ const projectDna = buildProjectContextEnvelope(resolvedCwd, [stateStr]);
74
+ const enrichedState = input.state && typeof input.state === "object" && !Array.isArray(input.state)
75
+ ? {
76
+ ...input.state,
77
+ project_dna: input.state.project_dna ?? {
78
+ workspace: projectDna.workspaceName,
79
+ stack: projectDna.stackSummary,
80
+ repo_topology: projectDna.repoTopology,
81
+ rules_excerpt: projectDna.projectRulesExcerpt
82
+ }
83
+ }
84
+ : input.state;
85
+ const { response, latencyMs, cached } = await this.client.evaluate(enrichedState, input.questions, { skipCache: input.skip_cache, operation: "jev_decide" });
86
+ const qKeys = Object.keys(input.questions);
87
+ const firstKey = qKeys[0] ?? "decision";
88
+ const firstAns = response.answers[firstKey];
89
+ let selectedOption = firstKey;
90
+ let selectedProbability = 0.8;
91
+ const probabilities = {};
92
+ for (const [k, ans] of Object.entries(response.answers)) {
93
+ if (ans.type === "noul") {
94
+ probabilities[k] = Number(ans.noul.toFixed(2));
95
+ }
96
+ else if (ans.type === "choice") {
97
+ selectedOption = `${k}: ${ans.selected}`;
98
+ selectedProbability = ans.probabilities[ans.selected] ?? 0.8;
99
+ for (const [optK, p] of Object.entries(ans.probabilities)) {
100
+ probabilities[`${k}.${optK}`] = Number(p.toFixed(2));
101
+ }
102
+ }
103
+ else if (ans.type === "score") {
104
+ probabilities[k] = Number((ans.score / 5).toFixed(2));
105
+ }
106
+ }
107
+ if (firstAns?.type === "noul") {
108
+ selectedProbability = firstAns.noul;
109
+ }
110
+ const questionSummary = Object.entries(input.questions)
111
+ .map(([k, q]) => `${k} (${q.type}): ${q.instructions}`)
112
+ .slice(0, 4);
113
+ const optionsMap = {};
114
+ for (const [k, q] of Object.entries(input.questions)) {
115
+ optionsMap[k] = `[${q.type}] ${q.instructions}`;
116
+ }
117
+ recordSessionEvent({
118
+ agent: input.agent,
119
+ workingDirectory: projectDna.workspacePath,
120
+ workspace: projectDna.workspaceName,
121
+ tool: "jev_decide",
122
+ questionOrTitle: `System-1 Parallel Evaluation (${qKeys.length} question${qKeys.length === 1 ? "" : "s"}: ${qKeys.join(", ")})`,
123
+ optionsOrInput: optionsMap,
124
+ verdict: "INFO",
125
+ selectedOption,
126
+ selectedProbability,
127
+ probabilities,
128
+ directive: `Answered ${qKeys.length} parallel System-1 primitives (${questionSummary.join(" | ")})`,
129
+ latencyMs,
130
+ costUsd: response.usage?.cost ?? 0,
131
+ cached
132
+ });
133
+ return {
134
+ model: response.model,
135
+ latencyMs,
136
+ cached,
137
+ usage: response.usage,
138
+ answers: response.answers
139
+ };
140
+ }
141
+ async guardAction(input) {
142
+ const exactCommand = String(input.exact_command ?? "").slice(0, MAX_EXACT_COMMAND_CHARS).trim();
143
+ const context = String(input.context ?? "").slice(0, MAX_GUARD_CONTEXT_CHARS);
144
+ const loggedCommand = exactCommand.slice(0, MAX_LOGGED_COMMAND_CHARS);
145
+ const cwd = resolveTargetWorkspace(input.working_directory, [exactCommand, context]);
146
+ const projectDna = buildProjectContextEnvelope(cwd, [exactCommand, context]);
147
+ const commandShape = assessCommandShape(exactCommand);
148
+ if (commandShape.looksLikeProse) {
149
+ // Scoring a self-written description is meaningless; ask for the real command.
150
+ const decision = buildUnverifiableCommandDecision(commandShape.signals);
151
+ this.rememberGuardEscalation(decision.verdict, exactCommand, projectDna, input.agent);
152
+ recordSessionEvent({
153
+ agent: input.agent,
154
+ workingDirectory: projectDna.workspacePath,
155
+ workspace: projectDna.workspaceName,
156
+ tool: "jev_guard_action",
157
+ questionOrTitle: `Guard Action: \`${loggedCommand.slice(0, 300)}\``,
158
+ optionsOrInput: {
159
+ command: loggedCommand,
160
+ context: context || "(no extra context)",
161
+ command_shape: `prose (${commandShape.signals.join(", ")})`
162
+ },
163
+ verdict: decision.verdict,
164
+ selectedOption: "ASK_USER (exact_command is not a literal command)",
165
+ selectedProbability: 0,
166
+ probabilities: {},
167
+ directive: [...decision.reasons, ...decision.remediation].join(" | "),
168
+ latencyMs: 0,
169
+ costUsd: 0,
170
+ cached: false
171
+ });
172
+ return {
173
+ decision,
174
+ commandShape,
175
+ latencyMs: 0,
176
+ cached: false,
177
+ usage: undefined,
178
+ rawAnswers: {}
179
+ };
180
+ }
181
+ const referencedFiles = extractReferencedDocsAndFiles(cwd, [exactCommand, context], 3, 1500);
182
+ const questions = buildCommandGuardQuestions();
183
+ const { response, latencyMs, cached } = await this.client.evaluate({
184
+ exact_command: exactCommand,
185
+ context,
186
+ working_directory: cwd,
187
+ referenced_scripts_or_docs: Object.keys(referencedFiles).length > 0 ? referencedFiles : undefined,
188
+ project_dna: {
189
+ workspace: projectDna.workspaceName,
190
+ stack: projectDna.stackSummary,
191
+ repo_topology: projectDna.repoTopology,
192
+ domain_and_auth_fingerprint: projectDna.domainAndAuthFingerprint,
193
+ learned_human_feedback_rules: projectDna.learnedHumanOverrides && projectDna.learnedHumanOverrides.length > 0
194
+ ? projectDna.learnedHumanOverrides
195
+ : undefined,
196
+ rules_excerpt: projectDna.projectRulesExcerpt,
197
+ active_memory: projectDna.activeMemoryExcerpt,
198
+ recent_decisions: projectDna.recentWorkspaceDecisions
199
+ }
200
+ }, questions, { operation: "jev_guard_action" });
201
+ const decision = evaluateCommandGate(response.answers);
202
+ this.rememberGuardEscalation(decision.verdict, exactCommand, projectDna, input.agent);
203
+ const pSafe = Number(decision.metrics.pSafe ?? 0.5);
204
+ const pDestructive = Number(decision.metrics.pDestructive ?? 0);
205
+ const pSecretRisk = Number(decision.metrics.pSecretRisk ?? 0);
206
+ const blastRadius = Number(decision.metrics.blastRadius ?? 2);
207
+ recordSessionEvent({
208
+ agent: input.agent,
209
+ workingDirectory: projectDna.workspacePath,
210
+ workspace: projectDna.workspaceName,
211
+ tool: "jev_guard_action",
212
+ questionOrTitle: `Guard Action: \`${loggedCommand.slice(0, 300)}\``,
213
+ optionsOrInput: {
214
+ command: loggedCommand,
215
+ context: context || "(no extra context)",
216
+ command_shape: "literal"
217
+ },
218
+ verdict: decision.verdict,
219
+ selectedOption: `${decision.verdict} (Blast ${blastRadius.toFixed(1)}/5)`,
220
+ selectedProbability: Number(pSafe.toFixed(2)),
221
+ probabilities: {
222
+ safe_probability: Number(pSafe.toFixed(2)),
223
+ destructive_risk: Number(pDestructive.toFixed(2)),
224
+ secret_exfiltration: Number(pSecretRisk.toFixed(2)),
225
+ blast_radius_norm: Number((blastRadius / 5).toFixed(2))
226
+ },
227
+ directive: decision.reasons.join(" | ") || decision.summary,
228
+ latencyMs,
229
+ costUsd: response.usage?.cost ?? 0,
230
+ cached
231
+ });
232
+ return {
233
+ decision,
234
+ commandShape,
235
+ latencyMs,
236
+ cached,
237
+ usage: response.usage,
238
+ rawAnswers: response.answers
239
+ };
240
+ }
241
+ async verifyDiff(input) {
242
+ const boundedSpec = z.string().min(1).max(MAX_SPEC_CHARS).parse(String(input.spec ?? "").slice(0, MAX_SPEC_CHARS));
243
+ input = {
244
+ ...input,
245
+ spec: boundedSpec,
246
+ test_output: input.test_output ? String(input.test_output).slice(0, 12000) : undefined
247
+ };
248
+ const cwd = resolveTargetWorkspace(input.working_directory, [input.spec, input.git_diff]);
249
+ const gitCtx = input.git_diff ? null : collectGitContext(cwd);
250
+ const rawEffectiveDiff = input.git_diff ?? gitCtx?.diff ?? gitCtx?.stagedDiff ?? "";
251
+ const effectiveDiff = input.git_diff
252
+ ? budgetMultiFileDiff(rawEffectiveDiff, "", 45000)
253
+ : rawEffectiveDiff;
254
+ // Extract file paths from inline git_diff when gitCtx is null (e.g., Codex/Gemini inline diffs)
255
+ const inlineFiles = input.git_diff
256
+ ? Array.from(new Set(Array.from(input.git_diff.matchAll(/^(?:diff --git a\/.+? b\/|\+\+\+ (?:b\/)?)([^\r\n\t]+)$/gm), (m) => m[1].trim()).filter((f) => f && f !== "/dev/null")))
257
+ : [];
258
+ let changedFiles = gitCtx && gitCtx.changedFiles.length > 0 ? gitCtx.changedFiles : inlineFiles;
259
+ if (changedFiles.length === 0) {
260
+ const specPathRegex = /(?:^|[\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;
261
+ const specCandidates = new Set();
262
+ for (const m of `${input.spec}\n${(input.git_diff ?? "").slice(0, 4000)}`.matchAll(specPathRegex)) {
263
+ const rel = m[1]?.trim().replace(/^[./\\]+/, "");
264
+ if (rel && fs.existsSync(path.join(cwd, rel))) {
265
+ specCandidates.add(rel);
266
+ }
267
+ }
268
+ if (specCandidates.size > 0) {
269
+ changedFiles = Array.from(specCandidates);
270
+ }
271
+ }
272
+ const projectDna = buildProjectContextEnvelope(cwd, [input.spec, ...changedFiles]);
273
+ const fullRawForMap = input.git_diff ?? gitCtx?.rawDiff ?? rawEffectiveDiff;
274
+ const structuralDiffMap = extractStructuralDiffMap(fullRawForMap);
275
+ const specCoverageMatrix = buildSpecRequirementMatrix(input.spec, structuralDiffMap, fullRawForMap);
276
+ const referencedDocs = extractReferencedDocsAndFiles(cwd, [input.spec], 4, 2200);
277
+ const postEditScopes = extractPostEditHunkScopes(cwd, fullRawForMap, 6, 7000);
278
+ const crossFileContracts = extractCrossFileContracts(cwd, changedFiles, 6, 4500);
279
+ const reverseDependents = extractReverseDependents(cwd, changedFiles, structuralDiffMap);
280
+ const companionTests = extractCompanionTestsContext(cwd, changedFiles, 6);
281
+ const preFlightSyntax = runFastSyntaxProbe(cwd, changedFiles);
282
+ const astSkeletons = extractHybridAstSkeletons(cwd, changedFiles, fullRawForMap, 8);
283
+ const staticLinterReport = runHybridStaticAnalysis(cwd, changedFiles);
284
+ const codeGraphIntel = queryCodeGraphIntelligence(cwd, input.spec, changedFiles);
285
+ const questions = buildDiffVerificationQuestions();
286
+ const { response, latencyMs, cached } = await this.client.evaluate({
287
+ specification: input.spec,
288
+ referenced_handoff_or_spec_docs: Object.keys(referencedDocs).length > 0 ? referencedDocs : undefined,
289
+ project_dna: {
290
+ workspace: projectDna.workspaceName,
291
+ stack: projectDna.stackSummary,
292
+ repo_topology: projectDna.repoTopology,
293
+ domain_and_auth_fingerprint: projectDna.domainAndAuthFingerprint,
294
+ learned_human_feedback_rules: projectDna.learnedHumanOverrides && projectDna.learnedHumanOverrides.length > 0
295
+ ? projectDna.learnedHumanOverrides
296
+ : undefined,
297
+ rules_excerpt: projectDna.projectRulesExcerpt,
298
+ active_memory: projectDna.activeMemoryExcerpt
299
+ },
300
+ git_branch: gitCtx?.branch || undefined,
301
+ git_status: gitCtx?.statusShort ?? "provided-inline",
302
+ recent_branch_commits: gitCtx?.branchCommitsSinceBase && gitCtx.branchCommitsSinceBase.length > 0
303
+ ? gitCtx.branchCommitsSinceBase
304
+ : gitCtx?.recentCommits,
305
+ changed_files: changedFiles,
306
+ pre_flight_syntax_probe: preFlightSyntax.status !== "SKIPPED" ? preFlightSyntax : undefined,
307
+ hybrid_static_linter_analysis: staticLinterReport.status !== "SKIPPED" ? staticLinterReport : undefined,
308
+ ast_symbol_skeletons: astSkeletons.length > 0 ? astSkeletons : undefined,
309
+ codegraph_intelligence: codeGraphIntel.indexed ? codeGraphIntel : undefined,
310
+ spec_requirement_alignment_matrix: specCoverageMatrix.length > 0 ? specCoverageMatrix : undefined,
311
+ structural_change_summary: structuralDiffMap.length > 0 ? structuralDiffMap : undefined,
312
+ reverse_dependents_and_callers: reverseDependents.modifiedDependents.length > 0 ||
313
+ reverseDependents.unmodifiedDependents.length > 0
314
+ ? reverseDependents
315
+ : undefined,
316
+ existing_companion_test_suites: Object.keys(companionTests).length > 0 ? companionTests : undefined,
317
+ imported_contracts_and_types: Object.keys(crossFileContracts).length > 0 ? crossFileContracts : undefined,
318
+ post_edit_enclosing_function_scopes: Object.keys(postEditScopes).length > 0 ? postEditScopes : undefined,
319
+ git_diff: effectiveDiff || "(no git diff detected)",
320
+ test_output: input.test_output ?? "(not provided)"
321
+ }, questions, { operation: "jev_verify_diff" });
322
+ const specIndicatesDocsOnly = /\b(docs[- ]only|documentation[- /](?:only|checkpoint|update)|planning\/handoff-only|only handoff\/planning|only memory docs changed|focused configuration\/docs (?:diff|addition))\b/i.test(input.spec);
323
+ const allChangedFilesAreDocs = changedFiles.length > 0 &&
324
+ changedFiles.every((f) => /\.(md|txt|rst|gitignore|gitattributes)$/i.test(f.trim()) ||
325
+ /^docs\//i.test(f.trim()));
326
+ const isDocsOnlyDiff = allChangedFilesAreDocs || (changedFiles.length === 0 && specIndicatesDocsOnly);
327
+ const decision = evaluateDiffGate(response.answers, {}, { isDocsOnlyDiff });
328
+ const pFulfillsSpec = Number(decision.metrics.pFulfillsSpec ?? 0.5);
329
+ const pBugRisk = Number(decision.metrics.pBugRisk ?? 0);
330
+ const pSecurityRisk = Number(decision.metrics.pSecurityRisk ?? 0);
331
+ const codeQuality = Number(decision.metrics.codeQuality ?? 3);
332
+ const linterSummary = staticLinterReport.status !== "SKIPPED"
333
+ ? `[${staticLinterReport.enginesUsed.join("+")}] ${staticLinterReport.status} (${staticLinterReport.errorCount} errors, ${staticLinterReport.warningCount} warnings across ${staticLinterReport.checkedFiles.length} files)`
334
+ : "SKIPPED (markdown/docs only)";
335
+ const astSummary = astSkeletons.length > 0
336
+ ? `${astSkeletons.length} files parsed (${astSkeletons.reduce((acc, s) => acc + s.exportedSignatures.length, 0)} symbols, ${astSkeletons.reduce((acc, s) => acc + s.enclosingModifiedNodes.length, 0)} modified scopes)`
337
+ : "none";
338
+ const cgSummary = codeGraphIntel.indexed
339
+ ? `INDEXED (${codeGraphIntel.graphAffectedTests.length} affected test suites, ${codeGraphIntel.symbolRelations.length} graph relations)`
340
+ : "NOT_INDEXED (auto-indexing triggered)";
341
+ recordSessionEvent({
342
+ agent: input.agent,
343
+ workingDirectory: projectDna.workspacePath,
344
+ workspace: projectDna.workspaceName,
345
+ tool: "jev_verify_diff",
346
+ questionOrTitle: `Verify Diff against Spec: "${input.spec}"`,
347
+ optionsOrInput: {
348
+ spec: input.spec,
349
+ changed_files: changedFiles.length > 0
350
+ ? `${changedFiles.length} files (${changedFiles.slice(0, 5).join(", ")})`
351
+ : "inline git diff",
352
+ opensource_linter: linterSummary,
353
+ opensource_ast: astSummary,
354
+ opensource_codegraph: cgSummary
355
+ },
356
+ verdict: decision.verdict,
357
+ selectedOption: `${decision.verdict} (Quality ${codeQuality.toFixed(2)}/5)`,
358
+ selectedProbability: Number(pFulfillsSpec.toFixed(2)),
359
+ probabilities: {
360
+ spec_fulfilled: Number(pFulfillsSpec.toFixed(2)),
361
+ quality_norm: Number((codeQuality / 5).toFixed(2)),
362
+ regression_risk: Number(pBugRisk.toFixed(2)),
363
+ security_risk: Number(pSecurityRisk.toFixed(2))
364
+ },
365
+ directive: decision.reasons.join(" | ") || decision.summary,
366
+ latencyMs,
367
+ costUsd: response.usage?.cost ?? 0,
368
+ cached
369
+ });
370
+ return {
371
+ decision,
372
+ changedFiles,
373
+ latencyMs,
374
+ cached,
375
+ usage: response.usage,
376
+ rawAnswers: response.answers
377
+ };
378
+ }
379
+ async auditCode(input) {
380
+ const safeFilePath = input.file_path ? z.string().max(512).parse(input.file_path) : undefined;
381
+ const cwd = resolveTargetWorkspace(input.working_directory, [safeFilePath, input.code]);
382
+ let targetCode = (input.code ?? "").slice(0, MAX_AUDIT_CODE_CHARS);
383
+ let changedFiles = [];
384
+ if (safeFilePath) {
385
+ const absTarget = path.isAbsolute(safeFilePath)
386
+ ? safeFilePath
387
+ : path.resolve(cwd, safeFilePath);
388
+ if (!isSensitiveFilePath(absTarget) &&
389
+ isWithinWorkspaceBoundary(cwd, absTarget) &&
390
+ fs.existsSync(absTarget) &&
391
+ fs.statSync(absTarget).isFile()) {
392
+ try {
393
+ const diskContent = fs.readFileSync(absTarget, "utf8").slice(0, 26000);
394
+ const isDiffOnly = targetCode.includes("diff --git") || targetCode.includes("@@ -");
395
+ if (!targetCode.trim()) {
396
+ targetCode = diskContent;
397
+ }
398
+ else if (isDiffOnly && !targetCode.includes("=== FULL FILE CONTENT ON DISK")) {
399
+ targetCode = `${targetCode.slice(0, 14000)}\n\n=== FULL FILE CONTENT ON DISK (${safeFilePath}) ===\n${diskContent}`;
400
+ }
401
+ }
402
+ catch {
403
+ // ignore read error
404
+ }
405
+ }
406
+ }
407
+ if (!targetCode.trim()) {
408
+ const gitCtx = collectGitContext(cwd);
409
+ targetCode = gitCtx.diff || gitCtx.stagedDiff;
410
+ changedFiles = gitCtx.changedFiles;
411
+ }
412
+ const targetFileList = safeFilePath && !changedFiles.includes(safeFilePath)
413
+ ? [safeFilePath, ...changedFiles]
414
+ : changedFiles;
415
+ const projectDna = buildProjectContextEnvelope(cwd, [input.file_path, ...targetFileList]);
416
+ const fileHeaderContext = extractFileHeaderContext(cwd, input.file_path, changedFiles);
417
+ const crossFileContracts = extractCrossFileContracts(cwd, targetFileList, 4, 3200);
418
+ const postEditScopes = extractPostEditHunkScopes(cwd, targetCode, 4, 4500);
419
+ const preFlightSyntax = runFastSyntaxProbe(cwd, targetFileList);
420
+ const astSkeletons = extractHybridAstSkeletons(cwd, targetFileList, targetCode, 6);
421
+ const staticLinterReport = runHybridStaticAnalysis(cwd, targetFileList);
422
+ const res = await auditCodeWithSkills(this.client, {
423
+ code: targetCode,
424
+ filePath: input.file_path,
425
+ stack: input.stack,
426
+ violationThreshold: input.violation_threshold,
427
+ projectContext: {
428
+ workspace: projectDna.workspaceName,
429
+ stack: projectDna.stackSummary,
430
+ repo_topology: projectDna.repoTopology,
431
+ domain_and_auth_fingerprint: projectDna.domainAndAuthFingerprint,
432
+ learned_human_feedback_rules: projectDna.learnedHumanOverrides && projectDna.learnedHumanOverrides.length > 0
433
+ ? projectDna.learnedHumanOverrides
434
+ : undefined,
435
+ pre_flight_syntax_probe: preFlightSyntax.status !== "SKIPPED" ? preFlightSyntax : undefined,
436
+ hybrid_static_linter_analysis: staticLinterReport.status !== "SKIPPED" ? staticLinterReport : undefined,
437
+ ast_symbol_skeletons: astSkeletons.length > 0 ? astSkeletons : undefined,
438
+ rules_excerpt: projectDna.projectRulesExcerpt,
439
+ imported_contracts: Object.keys(crossFileContracts).length > 0 ? crossFileContracts : undefined,
440
+ enclosing_function_scopes: Object.keys(postEditScopes).length > 0 ? postEditScopes : undefined
441
+ },
442
+ fileHeaderContext
443
+ });
444
+ const probs = {
445
+ security_score_norm: Number((res.securityScore / 5).toFixed(2))
446
+ };
447
+ for (const v of res.violatedVectors) {
448
+ probs[v.vector] = Number(v.probability.toFixed(2));
449
+ }
450
+ const violatedNames = res.violatedVectors.map((v) => v.vector);
451
+ const auditLinterSummary = staticLinterReport.status !== "SKIPPED"
452
+ ? `[${staticLinterReport.enginesUsed.join("+")}] ${staticLinterReport.status} (${staticLinterReport.errorCount} errors, ${staticLinterReport.warningCount} warnings)`
453
+ : "SKIPPED";
454
+ const auditAstSummary = astSkeletons.length > 0
455
+ ? `${astSkeletons.length} files parsed (${astSkeletons.reduce((acc, s) => acc + s.exportedSignatures.length, 0)} symbols)`
456
+ : "none";
457
+ recordSessionEvent({
458
+ agent: input.agent,
459
+ workingDirectory: projectDna.workspacePath,
460
+ workspace: projectDna.workspaceName,
461
+ tool: "jev_audit_code",
462
+ questionOrTitle: `Skill-Backed Security & Quality Audit (${input.file_path || res.stack})`,
463
+ optionsOrInput: {
464
+ stack: res.stack,
465
+ target: input.file_path || "local git diff",
466
+ violations: violatedNames.length > 0 ? violatedNames.join(", ") : "0 violations detected",
467
+ opensource_linter: auditLinterSummary,
468
+ opensource_ast: auditAstSummary
469
+ },
470
+ verdict: res.verdict,
471
+ selectedOption: `${res.verdict} (${res.securityScore.toFixed(2)}/5)`,
472
+ selectedProbability: Number((res.securityScore / 5).toFixed(2)),
473
+ probabilities: probs,
474
+ directive: res.summary,
475
+ latencyMs: res.latencyMs,
476
+ costUsd: res.usage?.cost ?? 0,
477
+ cached: res.cached
478
+ });
479
+ return res;
480
+ }
481
+ async pruneContext(input) {
482
+ const boundedTask = z.string().min(1).max(MAX_TASK_CHARS).parse(String(input.task ?? "").slice(0, MAX_TASK_CHARS));
483
+ const boundedCandidates = input.candidates.slice(0, MAX_BATCH_ITEMS);
484
+ input = { ...input, task: boundedTask, candidates: boundedCandidates };
485
+ const threshold = Math.min(1, Math.max(0, input.threshold ?? 0.60));
486
+ const candidateIds = input.candidates.slice(0, 15).map((c) => c.id);
487
+ const cwd = resolveTargetWorkspace(input.working_directory, [input.task, ...candidateIds]);
488
+ const projectDna = buildProjectContextEnvelope(cwd, [input.task]);
489
+ const questions = buildContextPruneQuestions(input.task, input.candidates);
490
+ const { response, latencyMs, cached } = await this.client.evaluate({
491
+ task: input.task,
492
+ workspace: projectDna.workspaceName,
493
+ stack: projectDna.stackSummary,
494
+ candidates: input.candidates
495
+ }, questions, { operation: "jev_prune_context" });
496
+ const kept = extractContextPruneResults(input.candidates, response.answers, threshold);
497
+ const probs = {};
498
+ for (const entry of kept.slice(0, 6)) {
499
+ probs[entry.item.id] = Number(entry.probability.toFixed(2));
500
+ }
501
+ recordSessionEvent({
502
+ agent: input.agent,
503
+ workingDirectory: projectDna.workspacePath,
504
+ workspace: projectDna.workspaceName,
505
+ tool: "jev_prune_context",
506
+ questionOrTitle: `Prune Context for Task: "${input.task}"`,
507
+ optionsOrInput: {
508
+ total_candidates: `${input.candidates.length} items`,
509
+ kept_items: kept.map((k) => `${k.item.id} (${Math.round(k.probability * 100)}%)`).join(", ") || "none"
510
+ },
511
+ verdict: "ALLOW",
512
+ selectedOption: `Kept ${kept.length}/${input.candidates.length} candidates`,
513
+ selectedProbability: kept[0]?.probability ?? 1,
514
+ probabilities: probs,
515
+ directive: `Filtered ${input.candidates.length} candidates down to ${kept.length} relevant items (threshold >= ${threshold})`,
516
+ latencyMs,
517
+ costUsd: response.usage?.cost ?? 0,
518
+ cached
519
+ });
520
+ return {
521
+ totalCandidates: input.candidates.length,
522
+ keptCount: kept.length,
523
+ prunedCount: input.candidates.length - kept.length,
524
+ threshold,
525
+ latencyMs,
526
+ cached,
527
+ kept
528
+ };
529
+ }
530
+ async classifyBatch(input) {
531
+ const boundedItems = input.items.slice(0, MAX_BATCH_ITEMS).map((s) => String(s).slice(0, 2000));
532
+ const boundedInstructions = z.string().min(1).max(MAX_TASK_CHARS).parse(String(input.instructions ?? "").slice(0, MAX_TASK_CHARS));
533
+ input = { ...input, items: boundedItems, instructions: boundedInstructions };
534
+ const questions = buildBatchClassifyQuestions(input.items, input.criteria, input.instructions);
535
+ const { response, latencyMs, cached } = await this.client.evaluate({ items: input.items }, questions, { operation: "jev_classify_batch" });
536
+ const results = input.items.slice(0, 100).map((item, idx) => {
537
+ const ans = response.answers[`item_${idx}`];
538
+ if (ans && ans.type === "choice") {
539
+ return {
540
+ index: idx,
541
+ item,
542
+ selected: ans.selected,
543
+ probabilities: ans.probabilities
544
+ };
545
+ }
546
+ return {
547
+ index: idx,
548
+ item,
549
+ selected: "unknown",
550
+ probabilities: {}
551
+ };
552
+ });
553
+ return {
554
+ count: results.length,
555
+ latencyMs,
556
+ cached,
557
+ results
558
+ };
559
+ }
560
+ async routeTask(input) {
561
+ const boundedTaskDesc = z
562
+ .string()
563
+ .min(1)
564
+ .max(MAX_TASK_CHARS)
565
+ .parse(String(input.task_description ?? "").slice(0, MAX_TASK_CHARS));
566
+ input = {
567
+ ...input,
568
+ task_description: boundedTaskDesc,
569
+ repo_context: input.repo_context ? String(input.repo_context).slice(0, MAX_TASK_CHARS) : undefined
570
+ };
571
+ const cwd = resolveTargetWorkspace(input.working_directory, [
572
+ input.task_description,
573
+ input.repo_context
574
+ ]);
575
+ const projectDna = buildProjectContextEnvelope(cwd, [
576
+ input.task_description,
577
+ input.repo_context
578
+ ]);
579
+ const referencedDocs = extractReferencedDocsAndFiles(cwd, [input.task_description, input.repo_context], 3, 1800);
580
+ const codeGraphIntel = queryCodeGraphIntelligence(cwd, input.task_description);
581
+ const questions = buildTaskRouteQuestions();
582
+ const { response, latencyMs, cached } = await this.client.evaluate({
583
+ task_description: input.task_description,
584
+ repo_context: input.repo_context ?? "",
585
+ referenced_docs_or_files: Object.keys(referencedDocs).length > 0 ? referencedDocs : undefined,
586
+ codegraph_intelligence: codeGraphIntel.indexed ? codeGraphIntel : undefined,
587
+ project_dna: {
588
+ workspace: projectDna.workspaceName,
589
+ stack: projectDna.stackSummary,
590
+ repo_topology: projectDna.repoTopology,
591
+ domain_and_auth_fingerprint: projectDna.domainAndAuthFingerprint,
592
+ learned_human_feedback_rules: projectDna.learnedHumanOverrides && projectDna.learnedHumanOverrides.length > 0
593
+ ? projectDna.learnedHumanOverrides
594
+ : undefined,
595
+ rules_excerpt: projectDna.projectRulesExcerpt,
596
+ active_memory: projectDna.activeMemoryExcerpt
597
+ }
598
+ }, questions, { operation: "jev_route_task" });
599
+ const strategyAns = response.answers.execution_strategy;
600
+ const tierAns = response.answers.recommended_model_tier;
601
+ const secAns = response.answers.requires_security_review;
602
+ const uiAns = response.answers.requires_ui_ux_design_system;
603
+ const ambAns = response.answers.ambiguity_needs_user_question;
604
+ const compAns = response.answers.complexity_score;
605
+ const strategy = strategyAns?.type === "choice" ? strategyAns.selected : "direct_edit";
606
+ const recommendedModelTier = tierAns?.type === "choice" ? tierAns.selected : "balanced_coding";
607
+ const complexityScore = compAns?.type === "score" ? compAns.score : 2.5;
608
+ recordSessionEvent({
609
+ agent: input.agent,
610
+ workingDirectory: projectDna.workspacePath,
611
+ workspace: projectDna.workspaceName,
612
+ tool: "jev_route_task",
613
+ questionOrTitle: `Route Task: "${input.task_description}"`,
614
+ optionsOrInput: {
615
+ task: input.task_description,
616
+ repo_context: input.repo_context || `${projectDna.workspaceName} (${projectDna.stackSummary.slice(0, 120)})`
617
+ },
618
+ verdict: "INFO",
619
+ selectedOption: `${strategy} (${recommendedModelTier})`,
620
+ selectedProbability: strategyAns?.type === "choice"
621
+ ? Number((strategyAns.probabilities[strategy] ?? 0.8).toFixed(2))
622
+ : 0.8,
623
+ probabilities: strategyAns?.type === "choice" ? strategyAns.probabilities : { [strategy]: 0.8 },
624
+ directive: `Strategy: ${strategy} | Tier: ${recommendedModelTier} | Complexity: ${complexityScore.toFixed(1)}/5`,
625
+ latencyMs,
626
+ costUsd: response.usage?.cost ?? 0,
627
+ cached
628
+ });
629
+ return {
630
+ strategy,
631
+ recommendedModelTier,
632
+ requiresSecuritySkill: secAns?.type === "noul" ? secAns.noul >= 0.55 : false,
633
+ requiresUiUxSkill: uiAns?.type === "noul" ? uiAns.noul >= 0.55 : false,
634
+ shouldAskClarifyingQuestion: ambAns?.type === "noul" ? ambAns.noul >= 0.60 : false,
635
+ complexityScore,
636
+ latencyMs,
637
+ cached,
638
+ rawAnswers: response.answers
639
+ };
640
+ }
641
+ getStats() {
642
+ return this.client.getTelemetry().getSummary();
643
+ }
644
+ async autopilotDecide(input) {
645
+ const cwd = resolveTargetWorkspace(input.working_directory, [
646
+ input.question,
647
+ input.context,
648
+ ...Object.values(input.options)
649
+ ]);
650
+ const projectDna = buildProjectContextEnvelope(cwd, [input.question, input.context]);
651
+ const referencedDocs = extractReferencedDocsAndFiles(cwd, [input.question, input.context], 3, 1800);
652
+ const questions = buildAutopilotProxyQuestions(input.options);
653
+ const { response, latencyMs, cached } = await this.client.evaluate({
654
+ decision_question_for_user: input.question,
655
+ candidate_options: input.options,
656
+ project_context: input.context ?? "",
657
+ referenced_docs_or_files: Object.keys(referencedDocs).length > 0 ? referencedDocs : undefined,
658
+ project_dna: {
659
+ workspace: projectDna.workspaceName,
660
+ stack: projectDna.stackSummary,
661
+ repo_topology: projectDna.repoTopology,
662
+ domain_and_auth_fingerprint: projectDna.domainAndAuthFingerprint,
663
+ learned_human_feedback_rules: projectDna.learnedHumanOverrides && projectDna.learnedHumanOverrides.length > 0
664
+ ? projectDna.learnedHumanOverrides
665
+ : undefined,
666
+ rules_excerpt: projectDna.projectRulesExcerpt,
667
+ active_memory: projectDna.activeMemoryExcerpt,
668
+ recent_decisions: projectDna.recentWorkspaceDecisions
669
+ },
670
+ developer_profile: input.developer_preferences ?? DEFAULT_DEVELOPER_PROFILE
671
+ }, questions, { operation: "jev_autopilot_decide" });
672
+ // Agents may raise the confidence bar but never lower it below the policy floor.
673
+ const requestedMin = Number.isFinite(input.min_confidence) ? Number(input.min_confidence) : 0;
674
+ const minChoiceProbability = Math.min(1, Math.max(JEV_POLICY.autopilot.minChoiceProbability, requestedMin));
675
+ const guardEscalation = findBlockingGuardEscalation(this.collectGuardEscalations(), {
676
+ workspaceName: projectDna.workspaceName,
677
+ workspacePath: projectDna.workspacePath,
678
+ workspaceIsUnknown: isGenericHostDirectory(projectDna.workspacePath)
679
+ });
680
+ const verdict = evaluateAutopilotProxy(response.answers, { minChoiceProbability }, { enabled: isAutopilotEnabled(), guardEscalation });
681
+ recordSessionEvent({
682
+ agent: input.agent,
683
+ workingDirectory: projectDna.workspacePath,
684
+ workspace: projectDna.workspaceName,
685
+ tool: "jev_autopilot_decide",
686
+ questionOrTitle: input.question,
687
+ optionsOrInput: input.options,
688
+ verdict: verdict.mode,
689
+ selectedOption: verdict.selectedOption,
690
+ selectedProbability: verdict.selectedProbability,
691
+ probabilities: verdict.allProbabilities,
692
+ directive: verdict.agentDirective,
693
+ latencyMs,
694
+ costUsd: response.usage?.cost ?? 0,
695
+ cached
696
+ });
697
+ return {
698
+ ...verdict,
699
+ latencyMs,
700
+ cached,
701
+ usage: response.usage
702
+ };
703
+ }
704
+ }
705
+ export function createMcpJevServer(client) {
706
+ const dispatcher = new McpJevDispatcher(client);
707
+ const server = new McpServer({
708
+ name: "mcp-jev",
709
+ version: "1.1.0"
710
+ });
711
+ server.tool("jev_decide", "System-1 parallel decision engine (TypeSafe AI Jev). Evaluates state against typed questions (noul, choice, score) and returns mathematically calibrated probabilities in ~150ms.", {
712
+ state: z.any().describe("Application context, git diff, JSON object, or text to evaluate"),
713
+ questions: z
714
+ .record(z.string(), z.object({
715
+ type: z.enum(["noul", "choice", "score"]),
716
+ instructions: z.string(),
717
+ criteria: z.record(z.string(), z.string()).optional()
718
+ }))
719
+ .describe("Map of question keys to typed Jev primitives (noul, choice, score)"),
720
+ skip_cache: z.boolean().optional().describe("Bypass local SHA-256 LRU cache"),
721
+ working_directory: z.string().optional().describe("Optional project workspace directory")
722
+ }, async (args) => {
723
+ const res = await dispatcher.decide({
724
+ state: args.state,
725
+ questions: args.questions,
726
+ skip_cache: args.skip_cache,
727
+ working_directory: args.working_directory
728
+ });
729
+ return {
730
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
731
+ };
732
+ });
733
+ server.tool("jev_verify_diff", "Zero-token Spec-to-Diff verification gate. Automatically collects local `git diff` (if omitted) and evaluates spec fulfillment, bug risk, security risk, and test coverage in 1 parallel pass. BLOCK = elevated security or regression risk: fix before finishing. ASK_USER = warning (spec alignment uncertain or tests missing): tell the user which parts are uncertain instead of rewriting the spec to pass. ALLOW = clean.", {
734
+ spec: z
735
+ .string()
736
+ .describe("The user's original request or acceptance criteria for this step, verbatim where possible. Do not paraphrase the diff."),
737
+ git_diff: z
738
+ .string()
739
+ .optional()
740
+ .describe("Optional git diff string. Leave empty to auto-collect local `git diff HEAD`"),
741
+ test_output: z.string().optional().describe("Optional test runner output"),
742
+ working_directory: z.string().optional().describe("Workspace path for local git collection")
743
+ }, async (args) => {
744
+ const res = await dispatcher.verifyDiff(args);
745
+ return {
746
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
747
+ };
748
+ });
749
+ server.tool("jev_audit_code", "Skill-Backed Security, Animation & Architecture Auditor. Scores code or local git diff against 10+ security/GSAP/architecture vectors and automatically extracts remediation rules from your installed skills (`security-best-practices`, `gsap-performance`, `codebase-design`) when violations are detected.", {
750
+ code: z
751
+ .string()
752
+ .optional()
753
+ .describe("Code snippet or diff to audit. If omitted, automatically audits current local `git diff`"),
754
+ file_path: z.string().optional().describe("File path to help auto-detect framework stack"),
755
+ stack: z
756
+ .enum([
757
+ "nextjs",
758
+ "express",
759
+ "react",
760
+ "vue",
761
+ "frontend",
762
+ "fastapi",
763
+ "django",
764
+ "flask",
765
+ "golang",
766
+ "gsap",
767
+ "general"
768
+ ])
769
+ .optional()
770
+ .describe("Explicit stack override"),
771
+ working_directory: z.string().optional().describe("Workspace directory if auditing local git diff"),
772
+ violation_threshold: z
773
+ .number()
774
+ .optional()
775
+ .describe("Probability threshold (0-1) to trigger local skill reference extraction (default 0.55)")
776
+ }, async (args) => {
777
+ const res = await dispatcher.auditCode(args);
778
+ return {
779
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
780
+ };
781
+ });
782
+ server.tool("jev_guard_action", "Pre-flight safety & blast-radius gate for a terminal command, migration, or destructive edit. Put the literal command line in `exact_command` and the explanation in `context`. Returns ALLOW, ASK_USER, or BLOCK with calibrated probabilities. ASK_USER means a human must confirm before running it (jev_autopilot_decide cannot replace that confirmation); a prose description instead of a command always returns ASK_USER.", {
783
+ exact_command: z
784
+ .string()
785
+ .min(1)
786
+ .max(MAX_EXACT_COMMAND_CHARS)
787
+ .describe("The exact command line that will be executed, verbatim (program + arguments), e.g. `git add -- docs/a.md; git commit -m \"docs: update\"`. Not a description of the action."),
788
+ context: z
789
+ .string()
790
+ .max(MAX_GUARD_CONTEXT_CHARS)
791
+ .optional()
792
+ .describe("Why the command is run, what it should touch, and any explicit user authorization"),
793
+ working_directory: z.string().max(1000).optional().describe("Target working directory")
794
+ }, async (args) => {
795
+ const res = await dispatcher.guardAction(args);
796
+ return {
797
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
798
+ };
799
+ });
800
+ server.tool("jev_prune_context", "Out-of-context parallel relevance filter & reranker. Scores up to 100 candidate files, skills, or search results in a single ~150ms API call and returns only relevant items sorted by probability.", {
801
+ task: z.string().describe("Current coding task or bug description"),
802
+ candidates: z
803
+ .array(z.object({
804
+ id: z.string().describe("File path, skill name, or identifier"),
805
+ summary: z.string().optional().describe("Brief summary or snippet")
806
+ }))
807
+ .describe("Candidate items to filter and rank (up to 100)"),
808
+ threshold: z
809
+ .number()
810
+ .optional()
811
+ .describe("Minimum relevance probability (0-1) to keep an item (default 0.60)"),
812
+ working_directory: z.string().optional().describe("Optional project workspace directory")
813
+ }, async (args) => {
814
+ const res = await dispatcher.pruneContext(args);
815
+ return {
816
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
817
+ };
818
+ });
819
+ server.tool("jev_classify_batch", "High-speed parallel batch classifier. Categorizes up to 100 items (logs, lint errors, files, tickets) into defined criteria in a single pass.", {
820
+ items: z.array(z.string()).describe("List of items to classify (up to 100)"),
821
+ criteria: z.record(z.string(), z.string()).describe("Map of category key -> description"),
822
+ instructions: z.string().describe("Classification instruction")
823
+ }, async (args) => {
824
+ const res = await dispatcher.classifyBatch(args);
825
+ return {
826
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
827
+ };
828
+ });
829
+ server.tool("jev_route_task", "Multi-agent workflow & model tier dispatcher. Determines the optimal execution strategy (direct edit, TDD, parallel subagents, brainstorm) and whether security/UI skills are required.", {
830
+ task_description: z.string().describe("User prompt or ticket description"),
831
+ repo_context: z.string().optional().describe("Optional summary of repo structure or tech stack"),
832
+ working_directory: z.string().optional().describe("Optional project workspace directory")
833
+ }, async (args) => {
834
+ const res = await dispatcher.routeTask(args);
835
+ return {
836
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
837
+ };
838
+ });
839
+ server.tool("jev_stats", "Returns session telemetry: total System-1 calls, SHA-256 cache hit rate, average latency (ms), token usage, USD cost, and ALLOW/BLOCK gate counts.", {}, async () => {
840
+ const stats = dispatcher.getStats();
841
+ return {
842
+ content: [{ type: "text", text: JSON.stringify(stats, null, 2) }]
843
+ };
844
+ });
845
+ server.tool("jev_autopilot_decide", "Human-Proxy Autopilot Decision Maker (disabled by default; enabled only when the server runs with JEV_AUTOPILOT=1). Call it before asking the user a multiple-choice technical question. Returns `AUTOPILOT_PROCEED` only when autopilot is enabled, the choice is a clear reversible engineering decision (P >= 0.65), and jev_guard_action has not returned ASK_USER/BLOCK in this workspace within the last 15 minutes. Otherwise returns `ASK_HUMAN` with Jev's recommended option to list first.", {
846
+ question: z.string().describe("The question the coding agent is considering asking the user"),
847
+ options: z
848
+ .record(z.string(), z.string())
849
+ .describe("Map of option_id -> description of each candidate approach or choice"),
850
+ context: z.string().optional().describe("Current project/code context relevant to the decision"),
851
+ developer_preferences: z
852
+ .string()
853
+ .optional()
854
+ .describe("Optional override for the developer's architectural/taste preferences"),
855
+ min_confidence: z
856
+ .number()
857
+ .min(0)
858
+ .max(1)
859
+ .optional()
860
+ .describe("Raise the minimum probability (0-1) required to auto-decide; values below the 0.65 floor are ignored"),
861
+ working_directory: z.string().optional().describe("Optional project workspace directory")
862
+ }, async (args) => {
863
+ const res = await dispatcher.autopilotDecide(args);
864
+ return {
865
+ content: [{ type: "text", text: JSON.stringify(res, null, 2) }]
866
+ };
867
+ });
868
+ return server;
869
+ }
870
+ export async function startStdioServer(client) {
871
+ const server = createMcpJevServer(client);
872
+ const transport = new StdioServerTransport();
873
+ await server.connect(transport);
874
+ }
875
+ //# sourceMappingURL=server.js.map