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
package/LICENSE
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 MCP-Jev Contributors
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|
package/README.md
CHANGED
|
@@ -1,3 +1,365 @@
|
|
|
1
|
-
#
|
|
1
|
+
# Jev CodeGuard (`jev-codeguard`) — Command Firewall, AST Security Auditor & Diff Verifier for AI Coding Agents
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
[](https://github.com/undowhai113/jev-codeguard/actions/workflows/ci.yml)
|
|
4
|
+
[](LICENSE)
|
|
5
|
+
[](package.json)
|
|
6
|
+
[](tsconfig.json)
|
|
7
|
+
[](SECURITY.md)
|
|
8
|
+
[](https://modelcontextprotocol.io)
|
|
9
|
+
[-059669.svg)](https://typesafe.ai)
|
|
10
|
+
|
|
11
|
+
> **Stop AI coding agents from running destructive shell commands, shipping security bugs, or wasting thousands of tokens grading their own code.**
|
|
12
|
+
|
|
13
|
+
**Jev CodeGuard (`jev-codeguard`)** is an open-source **Model Context Protocol (MCP) server, `PreToolUse` CLI hook firewall, and real-time local monitoring dashboard** built specifically for **Claude Code**, **OpenAI Codex**, **Cursor**, **Windsurf**, and **Google Antigravity (Gemini)**.
|
|
14
|
+
|
|
15
|
+
> **How does `jev-codeguard` differ from generic Jev MCP wrappers (like `jev-mcp`)?**
|
|
16
|
+
> While minimal wrappers expose raw `/v1/jev` judgment calls, **`jev-codeguard`** is a full **coding-agent safety, static-analysis & verification runtime**: it combines **local AST & Rust linters (`ts-morph`, `oxlint`, `ruff`, `codegraph`)**, **anti-gaming prose command detection**, **9 OWASP/AppSec skill rubrics with lazy `SKILL.md` escalation**, **zero-token local `git diff` verification**, a **deterministic `PreToolUse` hook firewall (`jev-gate`)**, and a **live local SSE Radar Portal (`http://127.0.0.1:4399`)** with persistent per-repo Project Brain memory.
|
|
17
|
+
|
|
18
|
+
It pairs your frontier **System-2** coding agent with **[TypeSafe AI's Jev](https://typesafe.ai)** (~150ms calibrated probability engine at **$0.042 / 1M input tokens**, free output) and **local open-source static/AST engines (`ts-morph`, `oxlint`, `ruff`, `codegraph`)** to deliver five concrete superpowers:
|
|
19
|
+
|
|
20
|
+
1. **🛡️ Pre-Execution Command Firewall (`jev_guard_action` & `jev-gate`):** Evaluates literal shell commands for blast radius, destructiveness, and secret exfiltration before execution — automatically rejecting English prose summaries so agents cannot disguise risky commands.
|
|
21
|
+
2. **🔍 Zero-Token Local Git Diff Verifier (`jev_verify_diff`):** Reads staged, unstaged, and untracked changes directly from disk (zero agent tokens spent echoing diffs), enriches them with AST symbol skeletons, callers, and linter diagnostics, and flags regressions before commit.
|
|
22
|
+
3. **🔒 Skill-Backed Security & Quality Auditor (`jev_audit_code`):** Checks 9 OWASP/AppSec vectors + architecture + 60fps GSAP animation rules in ~150ms, lazily injecting remediation excerpts **only** when a risk crosses `P >= 0.55` — from your own installed skills, or from the licensed skills bundled with the package (OpenAI `security-best-practices`, GreenSock `gsap-performance`, Matt Pocock `codebase-design`).
|
|
23
|
+
4. **✂️ Context Pruner & Workflow Router (`jev_prune_context` & `jev_route_task`):** Scores up to 100 candidate files/skills in a single ~150ms parallel pass so noisy files never pollute your agent's context window.
|
|
24
|
+
5. **📡 Live Bilingual (`EN | VI`) Radar Portal (`http://127.0.0.1:4399`):** Zero-dependency local SSE dashboard showing every agent check, probability bar, latency, cost, and **1-click Project Brain override rules**.
|
|
25
|
+
|
|
26
|
+
<details>
|
|
27
|
+
<summary><strong>🇻🇳 Tóm tắt công dụng bằng Tiếng Việt (Click để mở)</strong></summary>
|
|
28
|
+
|
|
29
|
+
<br/>
|
|
30
|
+
|
|
31
|
+
**`mcp-jev`** là lớp **Tường lửa bảo vệ (Guardrail Firewall), Kiểm toán bảo mật AST và Trạm giám sát trực tiếp** dành cho các AI Coding Agent (**Claude Code, OpenAI Codex, Cursor, Windsurf, Antigravity / Gemini**):
|
|
32
|
+
- **Chặn lệnh nguy hiểm trước khi chạy (`jev_guard_action` / `jev-gate`):** Chấm xác suất an toàn trong ~150ms, tự động phát hiện và từ chối nếu Agent cố tình mô tả văn xuôi thay vì đưa câu lệnh thật.
|
|
33
|
+
- **Chấm điểm `git diff` tốn 0 token của Agent (`jev_verify_diff`):** Tự đọc code thay đổi dưới local (kể cả file mới chưa `git add`), kết hợp phân tích AST (`ts-morph`, Python `ast`), linter (`oxlint`, `ruff`) và đồ thị phụ thuộc (`codegraph`) để bắt lỗi bảo mật/regression trước khi báo cáo xong việc.
|
|
34
|
+
- **Audit bảo mật không làm phình ngữ cảnh (`jev_audit_code`):** Chỉ trích quy tắc sửa lỗi khi rủi ro vượt ngưỡng (`P >= 0.55`) — ưu tiên skill bạn đã cài trên máy, nếu chưa có thì dùng bộ skill đi kèm gói (OpenAI `security-best-practices` Apache-2.0, GreenSock `gsap-performance` MIT, Matt Pocock `codebase-design` MIT; xem [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)).
|
|
35
|
+
- **Dashboard trực tiếp `http://127.0.0.1:4399` (Song ngữ `EN | VI`):** Theo dõi thời gian thực mọi câu hỏi & phán quyết của các Agent ở nhiều cửa sổ terminal và dạy lại quy tắc riêng cho từng dự án (**Project Brain**).
|
|
36
|
+
|
|
37
|
+
</details>
|
|
38
|
+
|
|
39
|
+
---
|
|
40
|
+
|
|
41
|
+
## Why `mcp-jev`?
|
|
42
|
+
|
|
43
|
+
| Bottleneck in Standard Agent Workflows | How `mcp-jev` Solves It |
|
|
44
|
+
| :--- | :--- |
|
|
45
|
+
| **Uncalibrated Self-Grading:** Frontier LLMs rationalize risky commands or incomplete diffs when grading their own work. | **External RLCD Probabilities:** Returns mathematically calibrated probabilities (`noul` $P \in [0, 1]$, `choice` distributions, and `1..5` expected-value `score`s) evaluated against frozen policy thresholds (`JEV_POLICY`). |
|
|
46
|
+
| **Prose Gaming on Command Guards:** Agents often describe *"Read-only safe git check"* instead of passing the literal command they intend to run. | **Literal Command-Shape Gate (`assessCommandShape`):** Rejects English prose descriptions at zero API cost and requires the verbatim executable command line in `exact_command`. |
|
|
47
|
+
| **Autopilot Guardrail Bypass:** After a guard returns `ASK_USER`, agents may ask a decision tool whether they can skip human confirmation. | **Opt-In Autopilot + 15-Min Escalation Lock:** `jev_autopilot_decide` defaults to `ASK_HUMAN` unless `JEV_AUTOPILOT=1`, and automatically locks to `ASK_HUMAN` for 15 minutes across processes whenever `jev_guard_action` escalates in the same workspace. |
|
|
48
|
+
| **Blind Diff Reviews on Large Repos:** Truncated diffs miss surrounding functions, imported types, callers, and syntax errors. | **Deep Project Brain + Hybrid AST Engine:** Locally enriches evaluations with `ts-morph` / Python `ast` symbol skeletons, `oxlint` & `ruff` static diagnostics, `codegraph` affected-test intelligence, cross-file contracts, and reverse dependents. |
|
|
49
|
+
| **Context Window Bloat:** Loading security & framework guidelines (`SKILL.md`) into every turn wastes thousands of tokens. | **Lazy Skill Escalation:** `jev_audit_code` evaluates 10+ security/architecture/GSAP vectors in ~150ms and injects local `SKILL.md` remediation excerpts **only** when a vector crosses `P >= 0.55`. |
|
|
50
|
+
| **Zero Multi-Agent Visibility:** Hard to see what Codex, Claude, and Gemini are deciding across terminals. | **Live Radar Portal (`:4399`):** Zero-dependency SSE dashboard tracking every tool call, probability bar, cost, latency, and **1-click Human-in-the-Loop rules** (`~/.mcp-jev/projects/<workspace>.json`). |
|
|
51
|
+
|
|
52
|
+
---
|
|
53
|
+
|
|
54
|
+
## Architecture
|
|
55
|
+
|
|
56
|
+
```mermaid
|
|
57
|
+
flowchart TB
|
|
58
|
+
subgraph Agents["System-2 Coding Agents"]
|
|
59
|
+
CC["Claude Code"]
|
|
60
|
+
CX["OpenAI Codex"]
|
|
61
|
+
AG["Antigravity / Gemini"]
|
|
62
|
+
CU["Cursor / Windsurf"]
|
|
63
|
+
end
|
|
64
|
+
|
|
65
|
+
subgraph MCPJev["mcp-jev (Local Node.js Server & CLI)"]
|
|
66
|
+
direction TB
|
|
67
|
+
Hook["Mode B: jev-gate PreToolUse Firewall\n(Exit 0 ALLOW | Ask | Exit 2 BLOCK)"]
|
|
68
|
+
Tools["Mode A: 9 MCP Tools\n(guard_action, verify_diff, audit_code,\nautopilot_decide, prune_context, route_task, ...)"]
|
|
69
|
+
Enricher["Deep Context & Hybrid Open-Source Engine\n• ts-morph + Python AST Skeletons\n• Oxlint (Rust JS/TS) + Ruff (Rust Python/Bandit)\n• CodeGraph Affected Tests & Callers\n• Workspace Boundary & Secret Redaction"]
|
|
70
|
+
Brain["Persistent Project Brain\n~/.mcp-jev/projects/<workspace>.json"]
|
|
71
|
+
Policy["Frozen Calibrated Policy Engine (JEV_POLICY)\n• Prose Command Detector\n• 15-min Cross-Process Guard Escalation Lock\n• Lazy Local SKILL.md Escalation"]
|
|
72
|
+
Ledger["Atomic Rotated Event Ledger\n~/.mcp-jev/events.jsonl (5 MiB cap)"]
|
|
73
|
+
Radar["Live Radar Portal (SSE)\nhttp://localhost:4399"]
|
|
74
|
+
end
|
|
75
|
+
|
|
76
|
+
JevAPI["TypeSafe AI Jev API\nPOST /v1/jev (~150ms RLCD)"]
|
|
77
|
+
|
|
78
|
+
Agents -->|MCP stdio| Tools
|
|
79
|
+
CC -->|PreToolUse Hook| Hook
|
|
80
|
+
Tools --> Enricher
|
|
81
|
+
Hook --> Enricher
|
|
82
|
+
Enricher <--> Brain
|
|
83
|
+
Enricher -->|SHA-256 Cached| JevAPI
|
|
84
|
+
JevAPI --> Policy
|
|
85
|
+
Policy --> Ledger
|
|
86
|
+
Ledger <-->|Real-Time SSE + Human Feedback| Radar
|
|
87
|
+
Radar -->|Teach Override Rules| Brain
|
|
88
|
+
```
|
|
89
|
+
|
|
90
|
+
---
|
|
91
|
+
|
|
92
|
+
## Quickstart
|
|
93
|
+
|
|
94
|
+
### 1. Prerequisites
|
|
95
|
+
|
|
96
|
+
- **Node.js `>= 20.0.0`**
|
|
97
|
+
- A **TypeSafe AI Jev API Key** (`jev_live_...`) from [typesafe.ai](https://typesafe.ai)
|
|
98
|
+
- *(Optional Open-Source Analyzers)*:
|
|
99
|
+
- `oxlint` and `ts-morph` are **bundled out of the box** via `npm install`.
|
|
100
|
+
- Install [`ruff`](https://docs.astral.sh/ruff/) (`pip install ruff`) to enable Rust-powered Python + Bandit (`S`) static security checks.
|
|
101
|
+
- Install [`@colbymchenry/codegraph`](https://github.com/colbymchenry/codegraph) (`npm install -g @colbymchenry/codegraph`) to enable Tree-sitter dependency graph & affected-test discovery.
|
|
102
|
+
|
|
103
|
+
### 2. Install, Build & Configure
|
|
104
|
+
|
|
105
|
+
```bash
|
|
106
|
+
# Option A: Install globally from npm (once published)
|
|
107
|
+
npm install -g jev-codeguard
|
|
108
|
+
jev-codeguard setup --api-key jev_live_your_key_here
|
|
109
|
+
|
|
110
|
+
# Option B: Clone and build from source
|
|
111
|
+
git clone https://github.com/undowhai113/jev-codeguard.git
|
|
112
|
+
cd jev-codeguard
|
|
113
|
+
npm install
|
|
114
|
+
npm run build
|
|
115
|
+
node dist/src/cli/index.js setup --api-key jev_live_your_key_here
|
|
116
|
+
```
|
|
117
|
+
|
|
118
|
+
Run the test suite (46 unit, calibration, concurrency, and security boundary tests):
|
|
119
|
+
|
|
120
|
+
```bash
|
|
121
|
+
npm test
|
|
122
|
+
```
|
|
123
|
+
|
|
124
|
+
---
|
|
125
|
+
|
|
126
|
+
## Connecting Your Coding Agents
|
|
127
|
+
|
|
128
|
+
Replace `/absolute/path/to/jev-codeguard` below with the path printed by `node dist/src/cli/index.js setup`.
|
|
129
|
+
*(If you saved your key via `setup --api-key`, `jev-codeguard` automatically reads `~/.mcp-jev/config.json` so you don't need to hardcode `JEV_API_KEY` in every IDE config!)*
|
|
130
|
+
|
|
131
|
+
### 1. Claude Code (`~/.claude.json` + Optional Zero-Trust Hook)
|
|
132
|
+
|
|
133
|
+
Add `jev-codeguard` via CLI or `~/.claude.json`:
|
|
134
|
+
|
|
135
|
+
```bash
|
|
136
|
+
claude mcp add jev-codeguard -- node /absolute/path/to/jev-codeguard/dist/src/cli/index.js serve
|
|
137
|
+
```
|
|
138
|
+
|
|
139
|
+
**Optional — Deterministic `PreToolUse` Firewall (`.claude/settings.json`):**
|
|
140
|
+
Intercepts `Bash`, `Write`, and `Edit` calls *before* execution, even if the agent forgets to call an MCP tool:
|
|
141
|
+
|
|
142
|
+
```json
|
|
143
|
+
{
|
|
144
|
+
"hooks": {
|
|
145
|
+
"PreToolUse": [
|
|
146
|
+
{
|
|
147
|
+
"matcher": "Bash|Write|Edit",
|
|
148
|
+
"hooks": [
|
|
149
|
+
{
|
|
150
|
+
"type": "command",
|
|
151
|
+
"command": "node \"/absolute/path/to/jev-codeguard/dist/src/cli/index.js\" gate"
|
|
152
|
+
}
|
|
153
|
+
]
|
|
154
|
+
}
|
|
155
|
+
]
|
|
156
|
+
}
|
|
157
|
+
}
|
|
158
|
+
```
|
|
159
|
+
|
|
160
|
+
### 2. OpenAI Codex (`~/.codex/config.toml`)
|
|
161
|
+
|
|
162
|
+
```toml
|
|
163
|
+
[mcp_servers.jev-codeguard]
|
|
164
|
+
command = "node"
|
|
165
|
+
args = ["/absolute/path/to/jev-codeguard/dist/src/cli/index.js", "serve"]
|
|
166
|
+
```
|
|
167
|
+
|
|
168
|
+
### 3. Google Antigravity (`~/.gemini/antigravity/mcp_config.json`)
|
|
169
|
+
|
|
170
|
+
*(Automatically registered if `~/.gemini/antigravity/mcp_config.json` exists when you run `setup`)*
|
|
171
|
+
|
|
172
|
+
```json
|
|
173
|
+
{
|
|
174
|
+
"mcpServers": {
|
|
175
|
+
"jev-codeguard": {
|
|
176
|
+
"command": "node",
|
|
177
|
+
"args": ["/absolute/path/to/jev-codeguard/dist/src/cli/index.js", "serve"],
|
|
178
|
+
"env": {
|
|
179
|
+
"JEV_SKILLS_DIR": "/Users/you/.gemini/config/skills"
|
|
180
|
+
}
|
|
181
|
+
}
|
|
182
|
+
}
|
|
183
|
+
}
|
|
184
|
+
```
|
|
185
|
+
|
|
186
|
+
### 4. Cursor / Windsurf (`~/.cursor/mcp.json`)
|
|
187
|
+
|
|
188
|
+
```json
|
|
189
|
+
{
|
|
190
|
+
"mcpServers": {
|
|
191
|
+
"jev-codeguard": {
|
|
192
|
+
"command": "node",
|
|
193
|
+
"args": ["/absolute/path/to/jev-codeguard/dist/src/cli/index.js", "serve"]
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
}
|
|
197
|
+
```
|
|
198
|
+
|
|
199
|
+
---
|
|
200
|
+
|
|
201
|
+
## Complete Reference: 9 MCP Tools
|
|
202
|
+
|
|
203
|
+
### 1. `jev_guard_action` — Literal Pre-Execution Command Firewall
|
|
204
|
+
Evaluates `P(safe)`, `P(destructive)`, `P(secret_or_net_risk)`, and `blast_radius` (`1..5`) before an agent executes a shell command or external mutation.
|
|
205
|
+
- **Anti-Gaming Prose Detector:** Requires the verbatim executable command in `exact_command` (e.g. `git push --force origin main`) and human intent in `context`. If an agent passes a prose summary (`"Push only reviewed docs safely"`), `jev_guard_action` immediately returns `ASK_USER` without calling the API.
|
|
206
|
+
- **Returns:** `ALLOW`, `ASK_USER`, or `BLOCK` with concrete reasons and remediation steps.
|
|
207
|
+
|
|
208
|
+
### 2. `jev_verify_diff` — Deep Context & Hybrid AST Diff Gate
|
|
209
|
+
Collects `git diff HEAD` locally (**zero agent prompt tokens wasted echoing diffs**) and enriches it with:
|
|
210
|
+
- **Spec-to-Diff Alignment Matrix:** Maps numbered/bulleted spec requirements against touched files & symbols.
|
|
211
|
+
- **Hybrid AST & Static Linter Probe:** Runs `ts-morph` AST skeleton extraction, Python `ast`, `oxlint` (Rust JS/TS), `ruff` (Rust Python + Bandit security), and `codegraph` affected-test lookup.
|
|
212
|
+
- **Cross-File Context:** Extracts enclosing post-edit function scopes, imported interfaces/types, unmodified reverse dependents, and companion test suites.
|
|
213
|
+
- **Calibrated Verdict:** Only elevated `security_risk >= 0.50` or `bug_risk >= 0.45` triggers `BLOCK`. Uncertain spec alignment (`P(fulfills_spec) < 0.68`) or missing test coverage (`P >= 0.65`) returns `ASK_USER` (`[WARNING]`) so agents report uncertainty honestly instead of rewriting the spec to game the gate.
|
|
214
|
+
|
|
215
|
+
### 3. `jev_audit_code` — Skill-Backed Security, Architecture & GSAP Auditor
|
|
216
|
+
Scores code snippets, files, or the local `git diff` across **9 OWASP/AppSec vectors** (`unvalidated_input`, `broken_authz_or_idor`, `injection_sql_cmd_path`, `xss_or_unsafe_html`, `ssrf_or_open_redirect`, `csrf_or_cookie_flaw`, `secrets_or_env_leak`, `cache_or_state_leak`, `dos_or_unbounded_resource`) + **deep-module architecture** + **60fps GSAP animation** vectors (when React/Vue/GSAP is detected).
|
|
217
|
+
- **Auto-Detected Stacks:** `nextjs`, `express`, `react`, `vue`, `frontend`, `fastapi`, `django`, `flask`, `golang`, `gsap`, `general`.
|
|
218
|
+
- **Lazy Skill Escalation:** Only security vectors can `BLOCK`; GSAP and architecture vectors surface non-blocking advisory guidance. When a vector crosses the threshold, Jev quotes the matching section of a remediation skill: your own installed copy first (`JEV_SKILLS_DIR`, `~/.gemini/config/skills`, `~/.claude/skills`, `~/.agents/skills`, `~/.cursor/skills`), otherwise the copy **bundled with the package** — OpenAI's `security-best-practices` (Apache-2.0), GreenSock's `gsap-performance` (MIT) and Matt Pocock's `codebase-design` (MIT), vendored verbatim at pinned commits (see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md)). Each excerpt reports `skillSource: "local" | "bundled" | "builtin"`; an unrecognised (`general`) stack gets short built-in guidance instead.
|
|
219
|
+
|
|
220
|
+
### 4. `jev_autopilot_decide` — Opt-In Human-Proxy Technical Recommender
|
|
221
|
+
Evaluates multiple-choice technical trade-offs (library choice, transaction strategy, module seam) against developer engineering standards.
|
|
222
|
+
- **Safe by Default (`ASK_HUMAN`):** Unless `JEV_AUTOPILOT=1` is explicitly enabled in the server environment, `jev_autopilot_decide` **always** returns `mode: "ASK_HUMAN"` together with Jev's calibrated recommendation (`selectedOption`) so the user stays in control.
|
|
223
|
+
- **Anti-Bypass Lock:** Even when `JEV_AUTOPILOT=1` is enabled, `jev_autopilot_decide` refuses to auto-proceed (`escalationReason: "recent_guard_escalation"`) within **15 minutes** of any `jev_guard_action` `ASK_USER` or `BLOCK` in the same workspace (tracked both in-memory and across separate agent processes via `~/.mcp-jev/events.jsonl`), and enforces a hard floor of `min_confidence >= 0.65`.
|
|
224
|
+
|
|
225
|
+
### 5. `jev_prune_context` — Out-of-Context Parallel File/Skill Filter
|
|
226
|
+
Scores up to **100 candidate `{ id, summary }` items** against a task description in **one ~150ms parallel request**, returning only candidates with `P(relevant) >= threshold` (default `0.60`). Keeps irrelevant files out of your System-2 context window.
|
|
227
|
+
|
|
228
|
+
### 6. `jev_classify_batch` — High-Throughput Parallel Triage
|
|
229
|
+
Classifies up to **100 items** (logs, lint errors, PR comments, issue tickets) into custom `criteria` categories in a single API call.
|
|
230
|
+
|
|
231
|
+
### 7. `jev_route_task` — Multi-Agent Workflow & Model Tier Router
|
|
232
|
+
Recommends optimal execution strategy (`direct_edit`, `tdd_red_green`, `parallel_subagents`, `brainstorm_spec_first`, `deep_bug_diagnosis`), model tier (`fast_lightweight`, `balanced_coding`, `deep_reasoning_flagship`), complexity (`1..5`), and whether security or UI/UX skills should be loaded.
|
|
233
|
+
|
|
234
|
+
### 8. `jev_decide` — Raw Multi-Question System-1 Battery
|
|
235
|
+
Direct access to Jev's native `noul` ($P \in [0, 1]$), `choice`, and `score` (`1..5`) primitives for custom agent workflows.
|
|
236
|
+
|
|
237
|
+
### 9. `jev_stats` — Session Telemetry & Cost Tracker
|
|
238
|
+
Returns total calls, SHA-256 cache hits, average latency (`ms`), token usage, and cumulative USD cost.
|
|
239
|
+
|
|
240
|
+
---
|
|
241
|
+
|
|
242
|
+
## Live Radar Portal (`http://localhost:4399`) & Project Brain
|
|
243
|
+
|
|
244
|
+
Whenever `mcp-jev serve` runs (or when you launch `npx mcp-jev dashboard`), a lightweight local dashboard starts on **`http://127.0.0.1:4399`**:
|
|
245
|
+
|
|
246
|
+
- **Real-Time Multi-Agent Stream (SSE):** Watch **Claude**, **Codex**, **Gemini**, and **CLI** hooks evaluate commands, diffs, and audits live in one unified feed.
|
|
247
|
+
- **Open-Source Engine Badges:** Inspect `ts-morph`, `oxlint`, `ruff`, and `codegraph` diagnostics attached to each diff/audit event.
|
|
248
|
+
- **Human-in-the-Loop Project Brain (`~/.mcp-jev/projects/<workspace>.json`):** Click **Override / Teach Rule** on any event card to save persistent project-specific rules (`FALSE_POSITIVE_OVERRIDE` or `CUSTOM_RULE`) that are automatically injected into future Jev evaluations for that repository.
|
|
249
|
+
|
|
250
|
+
---
|
|
251
|
+
|
|
252
|
+
## Calibrated Policy Thresholds (`JEV_POLICY`)
|
|
253
|
+
|
|
254
|
+
All gate thresholds live in one frozen module ([`src/core/policy-config.ts`](src/core/policy-config.ts)), calibrated against 330+ real multi-agent events:
|
|
255
|
+
|
|
256
|
+
| Gate | Verdict | Calibrated Rule |
|
|
257
|
+
| :--- | :--- | :--- |
|
|
258
|
+
| **`jev_guard_action`** | `BLOCK` | `P(destructive) >= 0.65`, OR `P(secret_or_net_risk) >= 0.55`, OR `(P(safe) < 0.25 && (P(destructive) >= 0.15 \|\| P(secret) >= 0.15))`, OR model votes `block_immediately` with risk `>= 0.35..0.40`. |
|
|
259
|
+
| **`jev_guard_action`** | `ALLOW` | Literal command shape AND `P(destructive) <= 0.22` AND `P(secret) <= 0.20`, plus `P(safe) >= 0.70` (when `blast <= 2.2`), `>= 0.72` (when `blast <= 3.6`), or `>= 0.85` (when `blast <= 4.0`). Otherwise `ASK_USER`. |
|
|
260
|
+
| **`jev_verify_diff`** | `BLOCK` | `P(security_risk) >= 0.50` OR `P(bug_risk) >= 0.45`. |
|
|
261
|
+
| **`jev_verify_diff`** | `ASK_USER` | Clean of blockers, but `P(fulfills_spec) < 0.68` (non-docs diff) OR `P(missing_tests) >= 0.65`. Otherwise `ALLOW`. |
|
|
262
|
+
| **`jev_audit_code`** | `BLOCK` | At least one **security** vector `>= 0.55` combined with `score < 2.3`, strong vector `>= 0.78` (`score < 3.4`), critical vector `>= 0.88`, or model `block_and_fix` vote (`score < 3.0`). |
|
|
263
|
+
| **`jev_autopilot_decide`** | `AUTOPILOT_PROCEED` | Requires `JEV_AUTOPILOT=1`, no workspace guard escalation in the last `15 min`, `P(top_choice) >= 0.65`, `P(reversible) >= 0.58`, `P(human_taste) <= 0.48`, and `alignment >= 3.4/5`. |
|
|
264
|
+
|
|
265
|
+
---
|
|
266
|
+
|
|
267
|
+
## CLI Reference
|
|
268
|
+
|
|
269
|
+
```bash
|
|
270
|
+
# Start MCP stdio server (also ensures Live Radar Portal is up on 127.0.0.1:4399)
|
|
271
|
+
mcp-jev serve
|
|
272
|
+
|
|
273
|
+
# Launch standalone Live Radar Portal on a custom port
|
|
274
|
+
mcp-jev dashboard --port 4399
|
|
275
|
+
|
|
276
|
+
# Save API key (~/.mcp-jev/config.json, mode 0600), install SKILL.md, print IDE configs
|
|
277
|
+
mcp-jev setup --api-key jev_live_your_key_here
|
|
278
|
+
|
|
279
|
+
# Run Zero-Trust PreToolUse Hook Firewall (reads Claude/Cursor JSON from stdin or flags)
|
|
280
|
+
jev-gate --command "rm -rf dist && npm run build"
|
|
281
|
+
jev-gate --file src/api/route.ts
|
|
282
|
+
|
|
283
|
+
# Run Skill-Backed Security & Quality Audit on a file or current local git diff
|
|
284
|
+
mcp-jev audit --file src/mcp/server.ts
|
|
285
|
+
|
|
286
|
+
# Run Zero-Token Local Git Diff Verification against a specification
|
|
287
|
+
mcp-jev verify-diff --spec "Add rate limiting and input validation to /api/login"
|
|
288
|
+
|
|
289
|
+
# Run Human-Proxy Technical Recommender from terminal
|
|
290
|
+
mcp-jev autopilot --question "Which lock strategy?" \
|
|
291
|
+
--opt prisma_tx="Optimistic check inside Prisma $transaction" \
|
|
292
|
+
--opt redis_lock="External Redis Redlock cluster"
|
|
293
|
+
```
|
|
294
|
+
|
|
295
|
+
---
|
|
296
|
+
|
|
297
|
+
## Environment Variables
|
|
298
|
+
|
|
299
|
+
| Variable | Default | Description |
|
|
300
|
+
| :--- | :--- | :--- |
|
|
301
|
+
| `JEV_API_KEY` | `~/.mcp-jev/config.json` | TypeSafe AI API key (`jev_live_...`). Env var overrides config file. |
|
|
302
|
+
| `JEV_AUTOPILOT` | `0` (disabled) | Set to `1` to allow `jev_autopilot_decide` to return `AUTOPILOT_PROCEED` on reversible technical choices. |
|
|
303
|
+
| `JEV_SKILLS_DIR` | Auto-detected | Custom path to your own `SKILL.md` library (auto-scans `~/.gemini/config/skills`, `~/.claude/skills`, `~/.agents/skills`, `~/.cursor/skills`). Any skill missing there falls back to the copy bundled in `skills/vendor/`. |
|
|
304
|
+
| `JEV_FAIL_MODE` | `ask` | `jev-gate` hook fallback if Jev API is unreachable: `ask` (human prompt), `open` (allow), or `closed` (exit code `2` block). |
|
|
305
|
+
| `JEV_EVENTS_FILE` | `~/.mcp-jev/events.jsonl` | Custom path for the cross-process event ledger (auto-rotates to `events.1.jsonl` at `5 MiB`). |
|
|
306
|
+
| `JEV_EVENTS_MAX_BYTES` | `5242880` (5 MiB) | Byte threshold before atomic lockfile-guarded rotation of `events.jsonl`. |
|
|
307
|
+
| `JEV_WORKSPACE_ROOTS` | Parent of `cwd` | Path-delimited (`:` on macOS/Linux, `;` on Windows) parent directories used to resolve project roots when an IDE spawns MCP from a generic host folder. |
|
|
308
|
+
| `JEV_BASE_URL` | `https://api.typesafe.ai/v1/jev` | Custom Jev API endpoint override. |
|
|
309
|
+
|
|
310
|
+
---
|
|
311
|
+
|
|
312
|
+
## Security & Privacy Model
|
|
313
|
+
|
|
314
|
+
- **Zero Shell Interpolation (`shell: false`):** All child processes (`git`, `oxlint`, `ruff`, `codegraph`, `python`) are invoked via `execFileSync` / `spawn` argument arrays with `shell: false` across Windows, macOS, and Linux — eliminating `cmd.exe` and `/bin/sh` metacharacter injection.
|
|
315
|
+
- **Workspace Path Traversal & Secret Blocklist:** `jev_audit_code` and `extractReferencedDocsAndFiles` enforce canonical `realpathSync` workspace boundaries (`isWithinWorkspaceBoundary`) and automatically block sensitive files (`.env`, `.env.*`, `*.pem`, `*.key`, `*.p12`, `id_rsa`, `credentials.json`, `~/.ssh/*`, `~/.mcp-jev/config.json`) from ever being read or sent to the Jev API.
|
|
316
|
+
- **Hardened Local Dashboard (`127.0.0.1` Only):** The Radar Portal binds strictly to `127.0.0.1`, enforces `Content-Security-Policy`, `X-Frame-Options: DENY`, `Host` header DNS-rebinding checks, `Origin` CSRF validation on state-mutating endpoints, `64 KB` body caps, and `25` max SSE client caps.
|
|
317
|
+
- **Restricted Credential Permissions:** `mcp-jev setup` creates `~/.mcp-jev` with `0700` and writes `config.json` with `0600` permissions; API keys are never echoed in tool responses or event logs.
|
|
318
|
+
- **What Leaves Your Machine:** When a Jev tool is called, bounded state snippets (command string, budgeted git diff, or audited file content) are sent over HTTPS (`TLS`) to `https://api.typesafe.ai/v1/jev`. Local telemetry, Project Brain rules, and rotated event logs (`~/.mcp-jev/events.jsonl`) stay `100%` on your machine.
|
|
319
|
+
|
|
320
|
+
---
|
|
321
|
+
|
|
322
|
+
## Project Structure
|
|
323
|
+
|
|
324
|
+
```text
|
|
325
|
+
mcp-jev/
|
|
326
|
+
├── src/
|
|
327
|
+
│ ├── core/
|
|
328
|
+
│ │ ├── jev-client.ts # HTTPS client, SHA-256 TTL cache, retries, ~/.mcp-jev/config.json loader
|
|
329
|
+
│ │ ├── policy-config.ts # Frozen JEV_POLICY thresholds (single source of truth)
|
|
330
|
+
│ │ ├── policy-engine.ts # Calibrated command/diff/autopilot gates + 15-min guard escalation lock
|
|
331
|
+
│ │ ├── command-shape.ts # Literal command vs. prose detector (strips quotes, heredocs, comments)
|
|
332
|
+
│ │ ├── context-enricher.ts # Project Brain DNA, spec matrix, callers, contracts, boundary/secret guards
|
|
333
|
+
│ │ ├── hybrid-ast-engine.ts # ts-morph + Python AST, Oxlint, Ruff, and CodeGraph integration
|
|
334
|
+
│ │ ├── skill-auditor.ts # 10+ OWASP/Architecture/GSAP vectors + Lazy SKILL.md Escalation
|
|
335
|
+
│ │ ├── git-collector.ts # Zero-token local git diff collector & multi-file proportional budgeter
|
|
336
|
+
│ │ ├── event-log.ts # Multi-process atomic O_APPEND ledger, 5 MiB rotation & tail reader
|
|
337
|
+
│ │ ├── presets.ts # Prompt/question battery builders
|
|
338
|
+
│ │ ├── cache.ts # Deterministic SHA-256 in-memory cache
|
|
339
|
+
│ │ └── telemetry.ts # Session latency, cache hit & USD cost aggregator
|
|
340
|
+
│ ├── mcp/
|
|
341
|
+
│ │ └── server.ts # 9 MCP tools registered over StdioServerTransport
|
|
342
|
+
│ ├── dashboard/
|
|
343
|
+
│ │ └── server.ts # Live Radar Portal (127.0.0.1:4399, SSE + Project Brain rule editor)
|
|
344
|
+
│ └── cli/
|
|
345
|
+
│ ├── index.ts # `mcp-jev` & `jev-gate` CLI entrypoints
|
|
346
|
+
│ ├── hook-runner.ts # Zero-Trust PreToolUse hook runner (Claude Code / Cursor)
|
|
347
|
+
│ └── setup.ts # Interactive config writer & companion skill installer
|
|
348
|
+
├── skills/
|
|
349
|
+
│ ├── jev-system-one/SKILL.md # Companion agent workflow instructions
|
|
350
|
+
│ └── vendor/ # Bundled third-party remediation skills (pinned, verbatim, own licenses)
|
|
351
|
+
├── scripts/vendor-skills.mjs # Re-vendors skills/vendor from upstream at pinned commits
|
|
352
|
+
└── tests/ # Test suites (calibration, concurrency, security, AST engines, bundled skills)
|
|
353
|
+
```
|
|
354
|
+
|
|
355
|
+
---
|
|
356
|
+
|
|
357
|
+
## Contributing & Security
|
|
358
|
+
|
|
359
|
+
- **Contributing Guide:** See [CONTRIBUTING.md](CONTRIBUTING.md) for local setup, architecture map, and PR calibration rules.
|
|
360
|
+
- **Security Policy:** See [SECURITY.md](SECURITY.md) for trust boundaries and private vulnerability disclosure.
|
|
361
|
+
- **Release History:** See [CHANGELOG.md](CHANGELOG.md).
|
|
362
|
+
|
|
363
|
+
## License
|
|
364
|
+
|
|
365
|
+
Released under the [MIT License](LICENSE). Bundled third-party skills keep their own licenses (Apache-2.0 and MIT); see [THIRD_PARTY_NOTICES.md](THIRD_PARTY_NOTICES.md).
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
# Third-Party Notices
|
|
2
|
+
|
|
3
|
+
`jev-codeguard` is released under the [MIT License](LICENSE). It also ships three third-party
|
|
4
|
+
agent skills, unmodified, in [`skills/vendor/`](skills/vendor). `jev_audit_code` quotes short
|
|
5
|
+
remediation excerpts from them when a risk vector crosses its threshold and you have not
|
|
6
|
+
installed your own copy of the same skill.
|
|
7
|
+
|
|
8
|
+
Each skill keeps its own license, shipped next to it. The exact upstream commit and the SHA-256
|
|
9
|
+
of every vendored file are recorded in [`skills/vendor/manifest.json`](skills/vendor/manifest.json),
|
|
10
|
+
and the test suite fails if any vendored file is changed. To refresh them from upstream, run
|
|
11
|
+
`node scripts/vendor-skills.mjs` and review the diff.
|
|
12
|
+
|
|
13
|
+
| Bundled skill | Upstream | Pinned commit | License | Copyright |
|
|
14
|
+
| --- | --- | --- | --- | --- |
|
|
15
|
+
| `security-best-practices` (`SKILL.md` + 10 framework references) | [openai/skills](https://github.com/openai/skills/tree/49f948faa9258a0c61caceaf225e179651397431/skills/.curated/security-best-practices) | `49f948f` | Apache License 2.0 ([`LICENSE.txt`](skills/vendor/security-best-practices/LICENSE.txt)) | OpenAI |
|
|
16
|
+
| `gsap-performance` | [greensock/gsap-skills](https://github.com/greensock/gsap-skills/tree/aed9cfd3277740755f6bfc1155c7aa645403b760/skills/gsap-performance) | `aed9cfd` | MIT ([`LICENSE`](skills/vendor/gsap-performance/LICENSE)) | Copyright (c) 2026 GreenSock |
|
|
17
|
+
| `codebase-design` (`SKILL.md`, `DEEPENING.md`, `DESIGN-IT-TWICE.md`) | [mattpocock/skills](https://github.com/mattpocock/skills/tree/5863806dd4e15c63174bee4e7515a4256792ecfa/skills/engineering/codebase-design) | `5863806` | MIT ([`LICENSE`](skills/vendor/codebase-design/LICENSE)) | Copyright (c) 2026 Matt Pocock |
|
|
18
|
+
|
|
19
|
+
Notes:
|
|
20
|
+
|
|
21
|
+
- The files are redistributed verbatim. `jev-codeguard` does not modify them; it only reads
|
|
22
|
+
sections at runtime.
|
|
23
|
+
- The upstream `security-best-practices` skill ships no `NOTICE` file, so Apache 2.0 §4(d)
|
|
24
|
+
adds no further attribution text beyond its license and this notice.
|
|
25
|
+
- `jev-codeguard` is not endorsed by, or affiliated with, the authors of these skills.
|
|
@@ -0,0 +1,27 @@
|
|
|
1
|
+
import { JevClient } from "../core/jev-client.js";
|
|
2
|
+
import type { GateVerdict } from "../core/types.js";
|
|
3
|
+
export type HookFailMode = "open" | "ask" | "closed";
|
|
4
|
+
export interface HookPayload {
|
|
5
|
+
tool_name?: string;
|
|
6
|
+
toolName?: string;
|
|
7
|
+
tool_input?: {
|
|
8
|
+
command?: string;
|
|
9
|
+
CommandLine?: string;
|
|
10
|
+
file_path?: string;
|
|
11
|
+
Path?: string;
|
|
12
|
+
content?: string;
|
|
13
|
+
Content?: string;
|
|
14
|
+
new_string?: string;
|
|
15
|
+
Replacement?: string;
|
|
16
|
+
};
|
|
17
|
+
command?: string;
|
|
18
|
+
code?: string;
|
|
19
|
+
file_path?: string;
|
|
20
|
+
}
|
|
21
|
+
export interface HookRunResult {
|
|
22
|
+
exitCode: 0 | 1 | 2;
|
|
23
|
+
verdict: GateVerdict;
|
|
24
|
+
stdout: string;
|
|
25
|
+
stderr: string;
|
|
26
|
+
}
|
|
27
|
+
export declare function runPreToolHook(rawInput: string, client?: JevClient, failMode?: HookFailMode): Promise<HookRunResult>;
|
|
@@ -0,0 +1,196 @@
|
|
|
1
|
+
import path from "node:path";
|
|
2
|
+
import { JevClient } from "../core/jev-client.js";
|
|
3
|
+
import { buildCommandGuardQuestions } from "../core/presets.js";
|
|
4
|
+
import { buildUnverifiableCommandDecision, evaluateCommandGate } from "../core/policy-engine.js";
|
|
5
|
+
import { assessCommandShape } from "../core/command-shape.js";
|
|
6
|
+
import { recordSessionEvent } from "../core/event-log.js";
|
|
7
|
+
import { auditCodeWithSkills } from "../core/skill-auditor.js";
|
|
8
|
+
function formatHookStdout(decision, reason) {
|
|
9
|
+
return JSON.stringify({
|
|
10
|
+
hookSpecificOutput: {
|
|
11
|
+
hookEventName: "PreToolUse",
|
|
12
|
+
permissionDecision: decision,
|
|
13
|
+
permissionDecisionReason: reason
|
|
14
|
+
},
|
|
15
|
+
permissionDecision: decision,
|
|
16
|
+
reason
|
|
17
|
+
});
|
|
18
|
+
}
|
|
19
|
+
export async function runPreToolHook(rawInput, client = new JevClient(), failMode = process.env.JEV_FAIL_MODE ?? "ask") {
|
|
20
|
+
let payload = {};
|
|
21
|
+
try {
|
|
22
|
+
payload = rawInput.trim().startsWith("{")
|
|
23
|
+
? JSON.parse(rawInput)
|
|
24
|
+
: { command: rawInput.trim() };
|
|
25
|
+
}
|
|
26
|
+
catch {
|
|
27
|
+
payload = { command: rawInput.trim() };
|
|
28
|
+
}
|
|
29
|
+
const command = payload.command ??
|
|
30
|
+
payload.tool_input?.command ??
|
|
31
|
+
payload.tool_input?.CommandLine ??
|
|
32
|
+
"";
|
|
33
|
+
const codeContent = payload.code ??
|
|
34
|
+
payload.tool_input?.content ??
|
|
35
|
+
payload.tool_input?.Content ??
|
|
36
|
+
payload.tool_input?.new_string ??
|
|
37
|
+
payload.tool_input?.Replacement ??
|
|
38
|
+
"";
|
|
39
|
+
const filePath = payload.file_path ?? payload.tool_input?.file_path ?? payload.tool_input?.Path ?? "";
|
|
40
|
+
try {
|
|
41
|
+
// 1. If intercepting a shell command
|
|
42
|
+
if (command.trim().length > 0) {
|
|
43
|
+
const shape = assessCommandShape(command);
|
|
44
|
+
const cwd = process.cwd();
|
|
45
|
+
const workspace = path.basename(cwd) || "workspace";
|
|
46
|
+
if (shape.looksLikeProse) {
|
|
47
|
+
const decision = buildUnverifiableCommandDecision(shape.signals);
|
|
48
|
+
recordSessionEvent({
|
|
49
|
+
agent: "CLI",
|
|
50
|
+
workingDirectory: cwd,
|
|
51
|
+
workspace,
|
|
52
|
+
tool: "jev_guard_action",
|
|
53
|
+
questionOrTitle: `Hook Gate: \`${command.slice(0, 300)}\``,
|
|
54
|
+
optionsOrInput: {
|
|
55
|
+
command: command.slice(0, 2000),
|
|
56
|
+
command_shape: `prose (${shape.signals.join(", ")})`
|
|
57
|
+
},
|
|
58
|
+
verdict: "ASK_USER",
|
|
59
|
+
selectedOption: "ASK_USER (prose command input)",
|
|
60
|
+
selectedProbability: 0,
|
|
61
|
+
probabilities: {},
|
|
62
|
+
directive: decision.summary,
|
|
63
|
+
latencyMs: 0,
|
|
64
|
+
costUsd: 0,
|
|
65
|
+
cached: false
|
|
66
|
+
});
|
|
67
|
+
return {
|
|
68
|
+
exitCode: 0,
|
|
69
|
+
verdict: "ASK_USER",
|
|
70
|
+
stdout: formatHookStdout("ask", decision.summary),
|
|
71
|
+
stderr: ""
|
|
72
|
+
};
|
|
73
|
+
}
|
|
74
|
+
const questions = buildCommandGuardQuestions();
|
|
75
|
+
const { response, latencyMs, cached } = await client.evaluate({
|
|
76
|
+
tool: payload.tool_name ?? payload.toolName ?? "Bash",
|
|
77
|
+
exact_command: command
|
|
78
|
+
}, questions, { operation: "jev_gate_command" });
|
|
79
|
+
const decision = evaluateCommandGate(response.answers);
|
|
80
|
+
const pSafe = Number(decision.metrics.pSafe ?? 0.5);
|
|
81
|
+
const pDestructive = Number(decision.metrics.pDestructive ?? 0);
|
|
82
|
+
const pSecretRisk = Number(decision.metrics.pSecretRisk ?? 0);
|
|
83
|
+
const blastRadius = Number(decision.metrics.blastRadius ?? 2);
|
|
84
|
+
recordSessionEvent({
|
|
85
|
+
agent: "CLI",
|
|
86
|
+
workingDirectory: cwd,
|
|
87
|
+
workspace,
|
|
88
|
+
tool: "jev_guard_action",
|
|
89
|
+
questionOrTitle: `Hook Gate: \`${command.slice(0, 300)}\``,
|
|
90
|
+
optionsOrInput: {
|
|
91
|
+
command: command.slice(0, 2000),
|
|
92
|
+
command_shape: "literal"
|
|
93
|
+
},
|
|
94
|
+
verdict: decision.verdict,
|
|
95
|
+
selectedOption: `${decision.verdict} (Blast ${blastRadius.toFixed(1)}/5)`,
|
|
96
|
+
selectedProbability: Number(pSafe.toFixed(2)),
|
|
97
|
+
probabilities: {
|
|
98
|
+
safe_probability: Number(pSafe.toFixed(2)),
|
|
99
|
+
destructive_risk: Number(pDestructive.toFixed(2)),
|
|
100
|
+
secret_exfiltration: Number(pSecretRisk.toFixed(2)),
|
|
101
|
+
blast_radius_norm: Number((blastRadius / 5).toFixed(2))
|
|
102
|
+
},
|
|
103
|
+
directive: decision.reasons.join(" | ") || decision.summary,
|
|
104
|
+
latencyMs,
|
|
105
|
+
costUsd: response.usage?.cost ?? 0,
|
|
106
|
+
cached
|
|
107
|
+
});
|
|
108
|
+
if (decision.verdict === "ALLOW") {
|
|
109
|
+
return {
|
|
110
|
+
exitCode: 0,
|
|
111
|
+
verdict: "ALLOW",
|
|
112
|
+
stdout: formatHookStdout("allow", decision.summary),
|
|
113
|
+
stderr: ""
|
|
114
|
+
};
|
|
115
|
+
}
|
|
116
|
+
if (decision.verdict === "BLOCK") {
|
|
117
|
+
const errMessage = [
|
|
118
|
+
decision.summary,
|
|
119
|
+
...decision.reasons.map((r) => ` - Reason: ${r}`),
|
|
120
|
+
...decision.remediation.map((r) => ` - Fix: ${r}`)
|
|
121
|
+
].join("\n");
|
|
122
|
+
return {
|
|
123
|
+
exitCode: 2,
|
|
124
|
+
verdict: "BLOCK",
|
|
125
|
+
stdout: formatHookStdout("deny", decision.summary),
|
|
126
|
+
stderr: errMessage
|
|
127
|
+
};
|
|
128
|
+
}
|
|
129
|
+
return {
|
|
130
|
+
exitCode: 0,
|
|
131
|
+
verdict: "ASK_USER",
|
|
132
|
+
stdout: formatHookStdout("ask", decision.summary),
|
|
133
|
+
stderr: ""
|
|
134
|
+
};
|
|
135
|
+
}
|
|
136
|
+
// 2. If intercepting a file write/edit with code
|
|
137
|
+
if (codeContent.trim().length > 0) {
|
|
138
|
+
const audit = await auditCodeWithSkills(client, {
|
|
139
|
+
code: codeContent,
|
|
140
|
+
filePath
|
|
141
|
+
});
|
|
142
|
+
if (audit.verdict === "BLOCK") {
|
|
143
|
+
const excerptText = audit.skillExcerpts
|
|
144
|
+
.map((ex) => ` * [${ex.vector} P=${ex.probability.toFixed(2)}] ${ex.title}\n Rule (${ex.skillFile}): ${ex.excerpt.slice(0, 350)}`)
|
|
145
|
+
.join("\n");
|
|
146
|
+
const errMessage = `[Jev Skill-Backed Security Gate: BLOCK] Stack=${audit.stack} Score=${audit.securityScore.toFixed(1)}/5\n${excerptText}`;
|
|
147
|
+
return {
|
|
148
|
+
exitCode: 2,
|
|
149
|
+
verdict: "BLOCK",
|
|
150
|
+
stdout: formatHookStdout("deny", errMessage),
|
|
151
|
+
stderr: errMessage
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
const summary = `[Jev Skill Gate: ${audit.verdict}] Stack=${audit.stack} Score=${audit.securityScore.toFixed(1)}/5`;
|
|
155
|
+
return {
|
|
156
|
+
exitCode: 0,
|
|
157
|
+
verdict: audit.verdict,
|
|
158
|
+
stdout: formatHookStdout(audit.verdict === "ALLOW" ? "allow" : "ask", summary),
|
|
159
|
+
stderr: ""
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
// Nothing to guard
|
|
163
|
+
return {
|
|
164
|
+
exitCode: 0,
|
|
165
|
+
verdict: "ALLOW",
|
|
166
|
+
stdout: formatHookStdout("allow", "No command or code payload to guard."),
|
|
167
|
+
stderr: ""
|
|
168
|
+
};
|
|
169
|
+
}
|
|
170
|
+
catch (err) {
|
|
171
|
+
const msg = err instanceof Error ? err.message : String(err);
|
|
172
|
+
if (failMode === "closed") {
|
|
173
|
+
return {
|
|
174
|
+
exitCode: 2,
|
|
175
|
+
verdict: "BLOCK",
|
|
176
|
+
stdout: formatHookStdout("deny", `Jev Gate fail-closed error: ${msg}`),
|
|
177
|
+
stderr: `[Jev Gate Error - Fail Closed]: ${msg}`
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
if (failMode === "open") {
|
|
181
|
+
return {
|
|
182
|
+
exitCode: 0,
|
|
183
|
+
verdict: "ALLOW",
|
|
184
|
+
stdout: formatHookStdout("allow", `Jev Gate fail-open fallback: ${msg}`),
|
|
185
|
+
stderr: ""
|
|
186
|
+
};
|
|
187
|
+
}
|
|
188
|
+
return {
|
|
189
|
+
exitCode: 0,
|
|
190
|
+
verdict: "ASK_USER",
|
|
191
|
+
stdout: formatHookStdout("ask", `Jev Gate fallback to human confirmation: ${msg}`),
|
|
192
|
+
stderr: ""
|
|
193
|
+
};
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
//# sourceMappingURL=hook-runner.js.map
|