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,435 @@
1
+ import fs from "node:fs";
2
+ import os from "node:os";
3
+ import path from "node:path";
4
+ import { fileURLToPath } from "node:url";
5
+ import { JEV_POLICY } from "./policy-config.js";
6
+ export const SECURITY_AUDIT_VECTORS = [
7
+ {
8
+ key: "unvalidated_input",
9
+ title: "Unvalidated Runtime Input (Missing Schema/Boundary Check)",
10
+ instructions: "Does the code consume untrusted input (request params, query, body, headers, cookies, formData, or CLI args) without strict runtime validation and type/length bounds (remembering that TypeScript types vanish at runtime)?",
11
+ searchKeywords: ["Untrusted input", "Input validation", "validation", "request.json", "schema"],
12
+ fallbackGuidance: "Validate and bound all untrusted input server-side using a strict schema validator (e.g., Zod/Pydantic) before passing to business logic. Never rely on compile-time TypeScript types as a security boundary."
13
+ },
14
+ {
15
+ key: "broken_authz_or_idor",
16
+ title: "Broken Authentication, Object-Level Authorization (IDOR), or Predictable IDs",
17
+ instructions: "Does the code perform state changes or sensitive reads without verifying both authentication AND object-level ownership/authorization (IDOR), or expose sequential auto-incrementing resource IDs?",
18
+ searchKeywords: ["Authorization", "Authentication", "IDOR", "Incrementing IDs", "session"],
19
+ fallbackGuidance: "Enforce authentication and object/action-level authorization server-side with least privilege on every route handler and Server Action. Use non-enumerable UUIDs for public resource identifiers."
20
+ },
21
+ {
22
+ key: "injection_sql_cmd_path",
23
+ title: "Injection Risk (SQL/NoSQL, Command Execution, or Path Traversal)",
24
+ instructions: "Does the code concatenate untrusted strings into SQL/ORM raw queries, execute shell commands with interpolated arguments (`exec`, `spawn(..., {shell: true})`), or join file paths without canonical boundary verification?",
25
+ searchKeywords: ["Injection", "SQL", "command execution", "path traversal", "File handling"],
26
+ fallbackGuidance: "Use parameterized queries and safe process APIs (`execFile` with array arguments, `shell: false`). Canonicalize file paths (`path.resolve`) and verify they remain inside the allowed base directory."
27
+ },
28
+ {
29
+ key: "xss_or_unsafe_html",
30
+ title: "Cross-Site Scripting (XSS) or Unsafe HTML Rendering",
31
+ instructions: "Does the code render unescaped or unsanitized HTML (`dangerouslySetInnerHTML`, `v-html`, `innerHTML`, `document.write`, `javascript:` URLs) or weaken Content-Security-Policy (CSP)?",
32
+ searchKeywords: ["XSS", "dangerouslySetInnerHTML", "HTML", "CSP", "sanitize"],
33
+ fallbackGuidance: "Rely on framework auto-escaping; if rich HTML is strictly required, sanitize with a maintained allowlist sanitizer (e.g., DOMPurify) and enforce strict CSP headers."
34
+ },
35
+ {
36
+ key: "ssrf_or_open_redirect",
37
+ title: "Server-Side Request Forgery (SSRF) or Open Redirect",
38
+ instructions: "Does the server make outbound HTTP/network requests (`fetch`, `axios`, `http.Get`) using a user-controlled URL/host (SSRF), or redirect users (`redirect()`, `res.redirect()`) to an unvalidated external target?",
39
+ searchKeywords: ["SSRF", "Outbound requests", "Redirect", "open redirect"],
40
+ fallbackGuidance: "Never pass raw user URLs to server-side `fetch` or `redirect`. Validate against an explicit allowlist of origins/hosts, block private/loopback IP ranges (127.0.0.1, 169.254.169.254, RFC1918), and disable automatic redirect following."
41
+ },
42
+ {
43
+ key: "csrf_or_cookie_flaw",
44
+ title: "CSRF Exposure or Insecure Cookie / Session Configuration",
45
+ instructions: "Do state-changing endpoints lack CSRF / Origin verification, or are session cookies configured with weak attributes (missing `httpOnly`, `sameSite`, or permissive CORS `*` with credentials)?",
46
+ searchKeywords: ["CSRF", "cookie", "CORS", "Origin", "sessions"],
47
+ fallbackGuidance: "Verify `Origin`/`Host` headers or CSRF tokens on all state-changing routes, set `httpOnly: true` and `sameSite: 'lax'` or `'strict'` on session cookies, and never combine `Access-Control-Allow-Origin: *` with credentials."
48
+ },
49
+ {
50
+ key: "secrets_or_env_leak",
51
+ title: "Hardcoded Secrets, Credential Logging, or Client Env Leak",
52
+ instructions: "Does the code hardcode API keys/passwords/tokens, log sensitive credentials/headers, or expose server-only secrets to client bundles (e.g., `NEXT_PUBLIC_` or returning full user/env objects)?",
53
+ searchKeywords: ["secrets", "process.env", "NEXT_PUBLIC", "logging", "credentials"],
54
+ fallbackGuidance: "Load secrets exclusively from server-side environment variables or secret managers, redact sensitive fields from logs and error responses, and never expose server secrets to client components."
55
+ },
56
+ {
57
+ key: "cache_or_state_leak",
58
+ title: "Cross-User Cache Poisoning or Shared State Data Leak",
59
+ instructions: "Could user-specific or authenticated data be cached in a shared/static cache (`use cache`, `force-cache`, CDN `Cache-Control: public`, or module-scoped mutable variables) and leaked to other users?",
60
+ searchKeywords: ["Cache", "data-leak", "static rendering", "use cache"],
61
+ fallbackGuidance: "Never cache per-user or authenticated responses in shared/static caches without strict per-user cache keys, and set `Cache-Control: private, no-store` on sensitive endpoints."
62
+ },
63
+ {
64
+ key: "dos_or_unbounded_resource",
65
+ title: "Denial of Service (DoS), Unbounded Pagination, or Unsafe File Upload",
66
+ instructions: "Does the code allow unbounded database queries (missing `limit` cap), unrestricted file uploads (missing size/count/MIME checks), expensive endpoints without rate-limiting, or external calls without timeouts?",
67
+ searchKeywords: ["upload", "pagination", "timeout", "rate limit", "size"],
68
+ fallbackGuidance: "Enforce hard upper bounds on pagination (`limit <= 100`), request body size, file upload size/type (with generated filenames), and outbound network timeouts."
69
+ },
70
+ {
71
+ key: "shallow_module_or_arch_flaw",
72
+ title: "Shallow Module / Leaky Interface / Poor Test Seam (Codebase Design)",
73
+ instructions: "Does the code expose internal implementation details through a complex/leaky interface, tangle I/O with pure domain logic, or make unit testing impossible without brittle private mocking?",
74
+ searchKeywords: ["deep module", "interface", "seam", "boundary"],
75
+ fallbackGuidance: "Design deep modules: keep public interfaces small and obvious while hiding implementation complexity behind clean dependency-injected seams."
76
+ }
77
+ ];
78
+ export const ARCHITECTURE_VECTOR_KEY = "shallow_module_or_arch_flaw";
79
+ export const GSAP_ANIMATION_VECTOR = {
80
+ key: "gsap_layout_thrashing_or_cleanup",
81
+ title: "GSAP Animation Performance / Lifecycle Violation (60fps Directive)",
82
+ instructions: "Does this animation code animate layout-triggering CSS properties (`top`, `left`, `width`, `height`, `margin`) instead of GPU transforms (`x`, `y`, `scale`, `rotation`, `opacity`), omit `useGSAP()` cleanup in React, or use `gsap.to()` inside mousemove loops instead of `gsap.quickTo()`?",
83
+ searchKeywords: ["transform", "quickTo", "useGSAP", "will-change", "pointer-events"],
84
+ fallbackGuidance: "Always animate GPU transform properties (`x`, `y`, `scale`, `rotation`, `opacity`) instead of `top`/`left`/`width`/`height`, use `useGSAP()` for React lifecycle cleanup, use `gsap.quickTo()` for high-frequency mouse tracking, and set `pointer-events: none` on overlays."
85
+ };
86
+ const STACK_TO_SKILL_FILE = {
87
+ nextjs: "security-best-practices/references/javascript-typescript-nextjs-web-server-security.md",
88
+ express: "security-best-practices/references/javascript-express-web-server-security.md",
89
+ react: "security-best-practices/references/javascript-typescript-react-web-frontend-security.md",
90
+ vue: "security-best-practices/references/javascript-typescript-vue-web-frontend-security.md",
91
+ frontend: "security-best-practices/references/javascript-general-web-frontend-security.md",
92
+ fastapi: "security-best-practices/references/python-fastapi-web-server-security.md",
93
+ django: "security-best-practices/references/python-django-web-server-security.md",
94
+ flask: "security-best-practices/references/python-flask-web-server-security.md",
95
+ golang: "security-best-practices/references/golang-general-backend-security.md",
96
+ gsap: "gsap-performance/SKILL.md",
97
+ general: "security-best-practices/SKILL.md"
98
+ };
99
+ /**
100
+ * Third-party remediation skills shipped inside this package (skills/vendor/), vendored
101
+ * verbatim at pinned commits by scripts/vendor-skills.mjs. See THIRD_PARTY_NOTICES.md.
102
+ * Resolved from this module's location (dist/src/core/), never from process.cwd().
103
+ */
104
+ export const BUNDLED_SKILLS_DIR = fileURLToPath(new URL("../../../skills/vendor/", import.meta.url));
105
+ export function resolveSkillsDir(customDir) {
106
+ const home = os.homedir();
107
+ if (customDir && customDir.trim().length > 0) {
108
+ return customDir.trim();
109
+ }
110
+ if (process.env.JEV_SKILLS_DIR && process.env.JEV_SKILLS_DIR.trim().length > 0) {
111
+ return process.env.JEV_SKILLS_DIR.trim();
112
+ }
113
+ const candidates = [
114
+ path.join(home, ".gemini", "config", "skills"),
115
+ path.join(home, ".claude", "skills"),
116
+ path.join(home, ".agents", "skills"),
117
+ path.join(home, ".cursor", "skills"),
118
+ path.resolve(process.cwd(), ".agents", "skills"),
119
+ path.resolve(process.cwd(), "skills")
120
+ ];
121
+ // Prefer a directory that actually contains the security/animation skill rubrics
122
+ for (const dir of candidates) {
123
+ if (fs.existsSync(path.join(dir, "security-best-practices")) ||
124
+ fs.existsSync(path.join(dir, "gsap-performance"))) {
125
+ return dir;
126
+ }
127
+ }
128
+ for (const dir of candidates) {
129
+ if (fs.existsSync(dir)) {
130
+ return dir;
131
+ }
132
+ }
133
+ return BUNDLED_SKILLS_DIR;
134
+ }
135
+ export function detectCodeStack(codeOrDiff, filePath = "") {
136
+ const sample = `${filePath}\n${codeOrDiff}`;
137
+ if (/\b(?:from|import)\s+["'](?:gsap|@gsap\/react)(?:\/[^"']*)?["']|\bgsap\.(?:to|from|fromTo|set|timeline|quickTo|registerPlugin|context|matchMedia)\s*\(|\buseGSAP\s*\(|\bScrollTrigger\.(?:create|refresh|batch|defaults)\s*\(/.test(sample)) {
138
+ return "gsap";
139
+ }
140
+ const hasExplicitExt = /\.[a-z0-9]+$/i.test(filePath);
141
+ const canBePython = !hasExplicitExt || /\.pyw?$/i.test(filePath);
142
+ const canBeGolang = !hasExplicitExt || /\.go$/i.test(filePath);
143
+ if (/\bnext\/server\b|\bnext\/headers\b|\bnext\/navigation\b|\bNextRequest\b|\bNextResponse\b|next\.config/i.test(sample)) {
144
+ return "nextjs";
145
+ }
146
+ if (canBePython && /\bfastapi\b|\bAPIRouter\b|\bDepends\(/.test(sample)) {
147
+ return "fastapi";
148
+ }
149
+ if (canBePython && /\bdjango\b|\bHttpResponse\b|\bmodels\.Model\b/i.test(sample)) {
150
+ return "django";
151
+ }
152
+ if (canBePython && /\bfrom\s+flask\s+import\b|\bFlask\(__name__\)/i.test(sample)) {
153
+ return "flask";
154
+ }
155
+ if (canBeGolang && (/\.go\b/.test(filePath) || /\bpackage\s+main\b|\bnet\/http\b|\bfmt\.Println\b/.test(sample))) {
156
+ return "golang";
157
+ }
158
+ if (/\bexpress\s*\(|\bapp\.use\(|\breq,\s*res,\s*next\b/.test(sample)) {
159
+ return "express";
160
+ }
161
+ if (/\.vue\b|\bv-html\b|\bdefineComponent\b/.test(sample)) {
162
+ return "vue";
163
+ }
164
+ if (/\.(tsx|jsx)$/i.test(filePath) ||
165
+ /\buseState\s*\(|\buseEffect\s*\(|\bdangerouslySetInnerHTML\b/.test(sample)) {
166
+ return "react";
167
+ }
168
+ if (/\.html\b|\bdocument\.querySelector\b|\bwindow\.location\b/.test(sample)) {
169
+ return "frontend";
170
+ }
171
+ return "general";
172
+ }
173
+ /** Vectors that are design/performance advice, never a security BLOCK on their own. */
174
+ const NON_SECURITY_VECTOR_KEYS = new Set([
175
+ ARCHITECTURE_VECTOR_KEY,
176
+ GSAP_ANIMATION_VECTOR.key
177
+ ]);
178
+ const ANIMATION_STACKS = new Set(["gsap", "react", "frontend"]);
179
+ export function stackIncludesAnimation(stack) {
180
+ return ANIMATION_STACKS.has(stack);
181
+ }
182
+ export function buildSkillAuditQuestions(stack, includeAnimation = stackIncludesAnimation(stack)) {
183
+ const questions = {};
184
+ for (const vec of SECURITY_AUDIT_VECTORS) {
185
+ questions[vec.key] = {
186
+ type: "noul",
187
+ instructions: `[Stack: ${stack}] ${vec.instructions}`
188
+ };
189
+ }
190
+ if (includeAnimation) {
191
+ questions[GSAP_ANIMATION_VECTOR.key] = {
192
+ type: "noul",
193
+ instructions: GSAP_ANIMATION_VECTOR.instructions
194
+ };
195
+ }
196
+ questions.overall_security_score = {
197
+ type: "score",
198
+ instructions: "Rate the overall security, resilience, and architectural quality of this code from 1 (critical vulnerabilities present) to 5 (exemplary secure-by-default implementation).",
199
+ criteria: {
200
+ "1": "Critical exploitable vulnerability or severe anti-pattern",
201
+ "2": "High-risk security gap or missing input/auth validation",
202
+ "3": "Moderate risk or incomplete defensive controls",
203
+ "4": "Solid implementation with only minor hardening suggestions",
204
+ "5": "Exemplary secure-by-default, well-bounded, and high-performance code"
205
+ }
206
+ };
207
+ questions.audit_verdict = {
208
+ type: "choice",
209
+ instructions: "What action should the coding agent take based on this skill audit?",
210
+ criteria: {
211
+ clean_pass: "Code adheres to security and engineering skills; proceed immediately",
212
+ review_warnings: "Minor hardening or structural improvements recommended",
213
+ block_and_fix: "Material security vulnerability or critical skill rule violation detected; must fix before completing"
214
+ }
215
+ };
216
+ return questions;
217
+ }
218
+ function extractMatchingSectionFromMarkdown(markdown, keywords, maxChars = 1100) {
219
+ const lines = markdown.split(/\r?\n/);
220
+ for (const kw of keywords) {
221
+ const lowerKw = kw.toLowerCase();
222
+ // Prefer matching markdown headings first
223
+ let matchIdx = lines.findIndex((line) => /^#{1,4}\s+/.test(line) && line.toLowerCase().includes(lowerKw));
224
+ if (matchIdx === -1) {
225
+ matchIdx = lines.findIndex((line) => line.toLowerCase().includes(lowerKw));
226
+ }
227
+ if (matchIdx !== -1) {
228
+ const start = Math.max(0, matchIdx);
229
+ const snippet = lines.slice(start, start + 28).join("\n").trim();
230
+ if (snippet.length > 0) {
231
+ return snippet.length > maxChars ? `${snippet.slice(0, maxChars)}\n...` : snippet;
232
+ }
233
+ }
234
+ }
235
+ return null;
236
+ }
237
+ export function extractSkillRemediation(skillsDir, stack, violatedVectors, bundledDir = BUNDLED_SKILLS_DIR) {
238
+ const allVectors = [...SECURITY_AUDIT_VECTORS, GSAP_ANIMATION_VECTOR];
239
+ const excerpts = [];
240
+ for (const item of violatedVectors) {
241
+ const meta = allVectors.find((v) => v.key === item.vector);
242
+ if (!meta)
243
+ continue;
244
+ let relativeSkillPath = stack === "gsap"
245
+ ? STACK_TO_SKILL_FILE.react
246
+ : STACK_TO_SKILL_FILE[stack] ?? STACK_TO_SKILL_FILE.general;
247
+ if (item.vector === GSAP_ANIMATION_VECTOR.key) {
248
+ relativeSkillPath = "gsap-performance/SKILL.md";
249
+ }
250
+ else if (item.vector === ARCHITECTURE_VECTOR_KEY) {
251
+ relativeSkillPath = "codebase-design/SKILL.md";
252
+ }
253
+ // The user's own installed skills win; the copy bundled in this package fills any gap.
254
+ const isBundled = (dir) => path.resolve(dir) === path.resolve(bundledDir);
255
+ const lookups = [[skillsDir, isBundled(skillsDir) ? "bundled" : "local"]];
256
+ if (!isBundled(skillsDir))
257
+ lookups.push([bundledDir, "bundled"]);
258
+ let extractedText = null;
259
+ let skillSource = "builtin";
260
+ for (const [dir, source] of lookups) {
261
+ extractedText = readSkillSection(path.join(dir, relativeSkillPath), meta.searchKeywords);
262
+ if (extractedText) {
263
+ skillSource = source;
264
+ break;
265
+ }
266
+ }
267
+ const sourceLabel = skillSource === "bundled" ? `${path.basename(relativeSkillPath)}, bundled with jev-codeguard` : path.basename(relativeSkillPath);
268
+ excerpts.push({
269
+ vector: item.vector,
270
+ probability: item.probability,
271
+ skillFile: relativeSkillPath,
272
+ skillSource,
273
+ title: meta.title,
274
+ excerpt: extractedText
275
+ ? `${meta.fallbackGuidance}\n\n--- [Extracted from ${sourceLabel}] ---\n${extractedText}`
276
+ : meta.fallbackGuidance
277
+ });
278
+ }
279
+ return excerpts;
280
+ }
281
+ function readSkillSection(fullPath, keywords) {
282
+ try {
283
+ if (!fs.existsSync(fullPath))
284
+ return null;
285
+ return extractMatchingSectionFromMarkdown(fs.readFileSync(fullPath, "utf8"), keywords);
286
+ }
287
+ catch {
288
+ return null;
289
+ }
290
+ }
291
+ function formatVectors(vectors) {
292
+ return vectors.map((v) => `${v.vector} (${v.probability.toFixed(2)})`).join(", ");
293
+ }
294
+ /**
295
+ * Builds the audit explanation from the verdict that was actually reached, so a BLOCK
296
+ * can never be described as "all checks passed" and GSAP is only mentioned when the
297
+ * animation vector was really evaluated.
298
+ */
299
+ export function buildAuditSummary(input) {
300
+ const score = `${input.securityScore.toFixed(2)}/5`;
301
+ const modelVote = input.modelChoice === "block_and_fix" ? ", model voted block_and_fix" : "";
302
+ if (input.verdict === "BLOCK") {
303
+ return `BLOCK: security vector(s) ${formatVectors(input.securityVectors)} with overall score ${score}${modelVote}.`;
304
+ }
305
+ if (input.verdict === "ASK_USER" && input.lowScoreReview) {
306
+ const findings = input.securityVectors.length > 0
307
+ ? `only low-confidence security findings (${formatVectors(input.securityVectors)})`
308
+ : `no security vector crossed ${input.threshold}`;
309
+ return `ASK_USER: ${findings}, but the overall score is ${score}${modelVote}; review manually before treating this code as clean.`;
310
+ }
311
+ if (input.verdict === "ASK_USER") {
312
+ return `ASK_USER: review security vector(s) ${formatVectors(input.securityVectors)}; overall score ${score}.`;
313
+ }
314
+ const findings = [...input.securityVectors, ...input.advisoryVectors];
315
+ if (findings.length > 0) {
316
+ return `ALLOW with non-blocking findings: ${formatVectors(findings)}; overall score ${score}.`;
317
+ }
318
+ const securityCount = SECURITY_AUDIT_VECTORS.filter((v) => !NON_SECURITY_VECTOR_KEYS.has(v.key)).length;
319
+ const families = [`${securityCount} security`, "1 architecture"];
320
+ if (input.includeAnimation)
321
+ families.push("1 GSAP animation");
322
+ return `ALLOW: every checked vector (${families.join(" + ")}) stayed below ${input.threshold}; overall score ${score}.`;
323
+ }
324
+ export async function auditCodeWithSkills(client, input) {
325
+ const policy = JEV_POLICY.audit;
326
+ const stack = input.stack ?? detectCodeStack(input.code, input.filePath);
327
+ const skillsDir = resolveSkillsDir(input.skillsDir);
328
+ const threshold = input.violationThreshold ?? policy.violationThreshold;
329
+ const includeAnimation = stackIncludesAnimation(stack);
330
+ const questions = buildSkillAuditQuestions(stack, includeAnimation);
331
+ const { response, latencyMs, cached } = await client.evaluate({
332
+ stack,
333
+ file_path: input.filePath ?? "unknown",
334
+ file_headers_and_auth_context: input.fileHeaderContext && Object.keys(input.fileHeaderContext).length > 0
335
+ ? input.fileHeaderContext
336
+ : undefined,
337
+ project_dna: input.projectContext,
338
+ code_or_diff: input.code.slice(0, 32000)
339
+ }, questions, { operation: "jev_audit_code" });
340
+ const allVectors = [...SECURITY_AUDIT_VECTORS, GSAP_ANIMATION_VECTOR];
341
+ const violatedVectors = [];
342
+ const cleanVectors = [];
343
+ for (const vec of allVectors) {
344
+ const ans = response.answers[vec.key];
345
+ if (!ans || ans.type !== "noul")
346
+ continue;
347
+ if (ans.noul >= threshold) {
348
+ violatedVectors.push({
349
+ vector: vec.key,
350
+ probability: ans.noul,
351
+ description: vec.title
352
+ });
353
+ }
354
+ else {
355
+ cleanVectors.push(vec.key);
356
+ }
357
+ }
358
+ violatedVectors.sort((a, b) => b.probability - a.probability);
359
+ const scoreAns = response.answers.overall_security_score;
360
+ let securityScore = 3.0;
361
+ if (scoreAns && scoreAns.type === "score") {
362
+ if (scoreAns.probabilities && "0" in scoreAns.probabilities && !("5" in scoreAns.probabilities)) {
363
+ let weighted = 0;
364
+ for (const [k, p] of Object.entries(scoreAns.probabilities)) {
365
+ const idx = Number(k);
366
+ if (Number.isFinite(idx) && typeof p === "number") {
367
+ weighted += (idx + 1) * p;
368
+ }
369
+ }
370
+ securityScore = Number(Math.max(1, Math.min(5, weighted)).toFixed(2));
371
+ }
372
+ else {
373
+ securityScore = scoreAns.score;
374
+ }
375
+ }
376
+ const choiceAns = response.answers.audit_verdict;
377
+ const modelChoice = choiceAns && choiceAns.type === "choice" ? choiceAns.selected : "clean_pass";
378
+ const isTestFile = Boolean(input.filePath &&
379
+ (/(?:^|[\\/])(tests?|__tests__|spec)(?:[\\/]|$)/i.test(input.filePath) ||
380
+ /\.(test|spec)\.[a-z0-9]+$/i.test(input.filePath)));
381
+ // Architecture and GSAP findings are advice; only security vectors can block. (The
382
+ // previous filter used a misspelled GSAP key, so GSAP findings counted as security.)
383
+ const securityVectorsOnly = violatedVectors.filter((v) => !NON_SECURITY_VECTOR_KEYS.has(v.vector));
384
+ const advisoryVectors = violatedVectors.filter((v) => NON_SECURITY_VECTOR_KEYS.has(v.vector));
385
+ let verdict = "ALLOW";
386
+ let lowScoreReview = false;
387
+ if (securityVectorsOnly.length > 0 &&
388
+ (securityScore < policy.blockScoreBelow ||
389
+ (modelChoice === "block_and_fix" && securityScore < policy.blockModelVoteScoreBelow) ||
390
+ (!isTestFile &&
391
+ securityScore < policy.blockStrongVectorScoreBelow &&
392
+ securityVectorsOnly.some((v) => v.probability >= policy.blockStrongVectorMin)) ||
393
+ securityVectorsOnly.some((v) => v.probability >= policy.blockCriticalVectorMin))) {
394
+ verdict = "BLOCK";
395
+ }
396
+ else if (!isTestFile &&
397
+ securityScore < policy.askScoreBelow &&
398
+ securityVectorsOnly.some((v) => v.probability >= policy.askVectorMin)) {
399
+ verdict = "ASK_USER";
400
+ }
401
+ else if (!isTestFile &&
402
+ securityVectorsOnly.every((v) => v.probability < policy.askVectorMin) &&
403
+ (securityScore < policy.lowScoreReviewBelow || modelChoice === "block_and_fix")) {
404
+ // A low overall score without an attributable vector is a review signal, not a pass.
405
+ verdict = "ASK_USER";
406
+ lowScoreReview = true;
407
+ }
408
+ const skillExcerpts = violatedVectors.length > 0
409
+ ? extractSkillRemediation(skillsDir, stack, violatedVectors)
410
+ : [];
411
+ const summary = buildAuditSummary({
412
+ verdict,
413
+ securityScore,
414
+ threshold,
415
+ includeAnimation,
416
+ modelChoice,
417
+ securityVectors: securityVectorsOnly,
418
+ advisoryVectors,
419
+ lowScoreReview
420
+ });
421
+ return {
422
+ stack,
423
+ verdict,
424
+ summary,
425
+ securityScore,
426
+ violatedVectors,
427
+ cleanVectors,
428
+ skillExcerpts,
429
+ rawAnswers: response.answers,
430
+ latencyMs,
431
+ cached,
432
+ usage: response.usage
433
+ };
434
+ }
435
+ //# sourceMappingURL=skill-auditor.js.map
@@ -0,0 +1 @@
1
+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,GAAG,MAAM,CAAC,YAAY,CAAC;QACrE,CAAC,aAAa,GAAG,MAAM,CAAC,mBAAmB,IAAI,WAAW,KAAK,eAAe,CAAC,EAC/E,CAAC;QACD,qFAAqF;QACrF,OAAO,GAAG,UAAU,CAAC;QACrB,cAAc,GAAG,IAAI,CAAC;IACxB,CAAC;IAED,MAAM,aAAa,GACjB,eAAe,CAAC,MAAM,GAAG,CAAC;QACxB,CAAC,CAAC,uBAAuB,CAAC,SAAS,EAAE,KAAK,EAAE,eAAe,CAAC;QAC5D,CAAC,CAAC,EAAE,CAAC;IAET,MAAM,OAAO,GAAG,iBAAiB,CAAC;QAChC,OAAO;QACP,aAAa;QACb,SAAS;QACT,gBAAgB;QAChB,WAAW;QACX,eAAe,EAAE,mBAAmB;QACpC,eAAe;QACf,cAAc;KACf,CAAC,CAAC;IAEH,OAAO;QACL,KAAK;QACL,OAAO;QACP,OAAO;QACP,aAAa;QACb,eAAe;QACf,YAAY;QACZ,aAAa;QACb,UAAU,EAAE,QAAQ,CAAC,OAAO;QAC5B,SAAS;QACT,MAAM;QACN,KAAK,EAAE,QAAQ,CAAC,KAAK;KACtB,CAAC;AACJ,CAAC"}
@@ -0,0 +1,30 @@
1
+ import type { GateVerdict } from "./types.js";
2
+ export interface TelemetryEvent {
3
+ operation: string;
4
+ latencyMs: number;
5
+ cached: boolean;
6
+ inputTokens: number;
7
+ outputTokens: number;
8
+ costUsd: number;
9
+ verdict?: GateVerdict;
10
+ timestamp?: string;
11
+ }
12
+ export interface TelemetrySummary {
13
+ totalCalls: number;
14
+ apiCalls: number;
15
+ cacheHits: number;
16
+ cacheHitRate: number;
17
+ avgApiLatencyMs: number;
18
+ totalInputTokens: number;
19
+ totalOutputTokens: number;
20
+ totalCostUsd: number;
21
+ verdictCounts: Record<GateVerdict, number>;
22
+ recentEvents: TelemetryEvent[];
23
+ }
24
+ export declare class TelemetryTracker {
25
+ private readonly events;
26
+ private readonly maxRecent;
27
+ constructor(maxRecent?: number);
28
+ record(event: TelemetryEvent): void;
29
+ getSummary(): TelemetrySummary;
30
+ }
@@ -0,0 +1,55 @@
1
+ export class TelemetryTracker {
2
+ events = [];
3
+ maxRecent;
4
+ constructor(maxRecent = 50) {
5
+ this.maxRecent = maxRecent;
6
+ }
7
+ record(event) {
8
+ this.events.push({
9
+ ...event,
10
+ timestamp: event.timestamp ?? new Date().toISOString()
11
+ });
12
+ }
13
+ getSummary() {
14
+ const totalCalls = this.events.length;
15
+ let apiCalls = 0;
16
+ let cacheHits = 0;
17
+ let totalApiLatency = 0;
18
+ let totalInputTokens = 0;
19
+ let totalOutputTokens = 0;
20
+ let totalCostUsd = 0;
21
+ const verdictCounts = {
22
+ ALLOW: 0,
23
+ ASK_USER: 0,
24
+ BLOCK: 0
25
+ };
26
+ for (const ev of this.events) {
27
+ if (ev.cached) {
28
+ cacheHits += 1;
29
+ }
30
+ else {
31
+ apiCalls += 1;
32
+ totalApiLatency += ev.latencyMs;
33
+ }
34
+ totalInputTokens += ev.inputTokens;
35
+ totalOutputTokens += ev.outputTokens;
36
+ totalCostUsd += ev.costUsd;
37
+ if (ev.verdict) {
38
+ verdictCounts[ev.verdict] = (verdictCounts[ev.verdict] ?? 0) + 1;
39
+ }
40
+ }
41
+ return {
42
+ totalCalls,
43
+ apiCalls,
44
+ cacheHits,
45
+ cacheHitRate: totalCalls > 0 ? Number((cacheHits / totalCalls).toFixed(3)) : 0,
46
+ avgApiLatencyMs: apiCalls > 0 ? Math.round(totalApiLatency / apiCalls) : 0,
47
+ totalInputTokens,
48
+ totalOutputTokens,
49
+ totalCostUsd: Number(totalCostUsd.toFixed(8)),
50
+ verdictCounts,
51
+ recentEvents: this.events.slice(-this.maxRecent)
52
+ };
53
+ }
54
+ }
55
+ //# sourceMappingURL=telemetry.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"telemetry.js","sourceRoot":"","sources":["../../../src/core/telemetry.ts"],"names":[],"mappings":"AA0BA,MAAM,OAAO,gBAAgB;IACV,MAAM,G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AC,CAAC,GAAG,CAAC,CAAC;YACnE,CAAC;QACH,CAAC;QAED,OAAO;YACL,UAAU;YACV,QAAQ;YACR,SAAS;YACT,YAAY,EAAE,UAAU,GAAG,CAAC,CAAC,CAAC,CAAC,MAAM,CAAC,CAAC,SAAS,GAAG,UAAU,CAAC,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC,CAAC;YAC9E,eAAe,EAAE,QAAQ,GAAG,CAAC,CAAC,CAAC,CAAC,IAAI,CAAC,KAAK,CAAC,eAAe,GAAG,QAAQ,CAAC,CAAC,CAAC,CAAC,CAAC;YAC1E,gBAAgB;YAChB,iBAAiB;YACjB,YAAY,EAAE,MAAM,CAAC,YAAY,CAAC,OAAO,CAAC,CAAC,CAAC,CAAC;YAC7C,aAAa;YACb,YAAY,EAAE,IAAI,CAAC,MAAM,CAAC,KAAK,CAAC,CAAC,IAAI,CAAC,SAAS,CAAC;SACjD,CAAC;IACJ,CAAC;CACF"}
@@ -0,0 +1,89 @@
1
+ export type JevQuestionType = "noul" | "choice" | "score";
2
+ export interface NoulQuestion {
3
+ type: "noul";
4
+ instructions: string;
5
+ criteria?: unknown;
6
+ }
7
+ export interface ChoiceQuestion {
8
+ type: "choice";
9
+ instructions: string;
10
+ criteria: Record<string, string>;
11
+ }
12
+ export interface ScoreQuestion {
13
+ type: "score";
14
+ instructions: string;
15
+ criteria?: string[] | Record<string, string>;
16
+ }
17
+ export type JevQuestion = NoulQuestion | ChoiceQuestion | ScoreQuestion;
18
+ export interface JevRequest {
19
+ model: string;
20
+ state: unknown;
21
+ questions: Record<string, JevQuestion>;
22
+ }
23
+ export interface NoulAnswer {
24
+ type: "noul";
25
+ noul: number;
26
+ }
27
+ export interface ChoiceAnswer {
28
+ type: "choice";
29
+ choice?: string;
30
+ selected: string;
31
+ confidence?: number;
32
+ probabilities: Record<string, number>;
33
+ }
34
+ export interface ScoreAnswer {
35
+ type: "score";
36
+ score: number;
37
+ confidence?: number;
38
+ legend?: Record<string, string>;
39
+ probabilities: Record<string, number>;
40
+ }
41
+ export type JevAnswer = NoulAnswer | ChoiceAnswer | ScoreAnswer;
42
+ export interface JevUsage {
43
+ input_tokens: number;
44
+ output_tokens: number;
45
+ cost: number;
46
+ }
47
+ export interface JevResponse {
48
+ model: string;
49
+ answers: Record<string, JevAnswer>;
50
+ usage?: JevUsage;
51
+ provider?: string;
52
+ }
53
+ export type GateVerdict = "ALLOW" | "ASK_USER" | "BLOCK";
54
+ export interface PolicyDecision {
55
+ verdict: GateVerdict;
56
+ confidence: number;
57
+ summary: string;
58
+ reasons: string[];
59
+ remediation: string[];
60
+ metrics: Record<string, number | string>;
61
+ }
62
+ export type CodeStack = "nextjs" | "express" | "react" | "vue" | "frontend" | "fastapi" | "django" | "flask" | "golang" | "gsap" | "general";
63
+ export interface SkillRemediationExcerpt {
64
+ vector: string;
65
+ probability: number;
66
+ skillFile: string;
67
+ /** Where the excerpt came from: the user's installed skills, the copy bundled in this package, or built-in guidance only. */
68
+ skillSource?: "local" | "bundled" | "builtin";
69
+ title: string;
70
+ excerpt: string;
71
+ }
72
+ export interface SkillAuditResult {
73
+ stack: CodeStack;
74
+ verdict: GateVerdict;
75
+ /** Human-readable explanation that always matches `verdict`. */
76
+ summary: string;
77
+ securityScore: number;
78
+ violatedVectors: Array<{
79
+ vector: string;
80
+ probability: number;
81
+ description: string;
82
+ }>;
83
+ cleanVectors: string[];
84
+ skillExcerpts: SkillRemediationExcerpt[];
85
+ rawAnswers: Record<string, JevAnswer>;
86
+ latencyMs: number;
87
+ cached: boolean;
88
+ usage?: JevUsage;
89
+ }
@@ -0,0 +1,2 @@
1
+ export {};
2
+ //# sourceMappingURL=types.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"file":"types.js","sourceRoot":"","sources":["../../../src/core/types.ts"],"names":[],"mappings":""}