@intentrax/sdk 1.6.0 → 1.8.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 (62) hide show
  1. package/README.md +56 -3
  2. package/cli/intentrax.mjs +57 -1
  3. package/index.js +4 -2
  4. package/index.ts +4 -2
  5. package/mcp/README.md +138 -0
  6. package/mcp/canonical.d.ts +12 -0
  7. package/mcp/canonical.mjs +70 -0
  8. package/mcp/cli.d.ts +16 -0
  9. package/mcp/cli.mjs +214 -0
  10. package/mcp/client.d.ts +131 -0
  11. package/mcp/client.mjs +955 -0
  12. package/mcp/commands.d.ts +113 -0
  13. package/mcp/commands.mjs +575 -0
  14. package/mcp/index.d.ts +12 -0
  15. package/mcp/index.mjs +12 -0
  16. package/mcp/proxy.d.ts +47 -0
  17. package/mcp/proxy.mjs +434 -0
  18. package/mcp/receipt-meta.d.ts +59 -0
  19. package/mcp/receipt-meta.mjs +178 -0
  20. package/mcp/tool-manifest.d.ts +74 -0
  21. package/mcp/tool-manifest.mjs +154 -0
  22. package/package.json +19 -1
  23. package/readback/README.md +352 -0
  24. package/readback/bridge.mjs +71 -0
  25. package/readback/cli.mjs +150 -0
  26. package/readback/confirm.mjs +404 -0
  27. package/readback/index.mjs +12 -0
  28. package/readback/recipe-worker.mjs +33 -0
  29. package/readback/recipes/_shared.mjs +126 -0
  30. package/readback/recipes/email-delivery.mjs +136 -0
  31. package/readback/recipes/github-issue.mjs +88 -0
  32. package/readback/recipes/http-json.mjs +109 -0
  33. package/readback/recipes/sql-row.mjs +96 -0
  34. package/readback/recipes/stripe-refund.mjs +73 -0
  35. package/readback/redact.mjs +68 -0
  36. package/sandbox/README.md +255 -0
  37. package/sandbox/authority.mjs +66 -0
  38. package/sandbox/bundle.mjs +93 -0
  39. package/sandbox/canonical.mjs +64 -0
  40. package/sandbox/check-runner.mjs +50 -0
  41. package/sandbox/check-worker.mjs +30 -0
  42. package/sandbox/cli.mjs +376 -0
  43. package/sandbox/effect-verifier.mjs +242 -0
  44. package/sandbox/effects.mjs +80 -0
  45. package/sandbox/envelope.mjs +174 -0
  46. package/sandbox/examples/read-only-check.example.mjs +32 -0
  47. package/sandbox/external-decision.mjs +364 -0
  48. package/sandbox/keys.mjs +179 -0
  49. package/sandbox/model.mjs +170 -0
  50. package/sandbox/run.mjs +324 -0
  51. package/sandbox/time.mjs +18 -0
  52. package/sandbox/verifier.mjs +503 -0
  53. package/scan/README.md +211 -0
  54. package/scan/classify.mjs +276 -0
  55. package/scan/cli.mjs +102 -0
  56. package/scan/configs.mjs +261 -0
  57. package/scan/credentials.mjs +121 -0
  58. package/scan/extract.mjs +323 -0
  59. package/scan/gates.mjs +94 -0
  60. package/scan/report.mjs +58 -0
  61. package/scan/scan.mjs +571 -0
  62. package/scan/text.mjs +186 -0
package/scan/scan.mjs ADDED
@@ -0,0 +1,571 @@
1
+ // `scanProject(dir, options)`: a local, static, no-account scan that lists the
2
+ // destructive or consequential actions an AI agent can reach in a project, and
3
+ // flags broad credentials, missing gates and self-reported success.
4
+ //
5
+ // It reads files only. It never imports or runs the scanned code, never makes
6
+ // a network call, and never records or prints a credential value: credentials
7
+ // are reported by variable or config name and file location only.
8
+
9
+ import { readdirSync, readFileSync, statSync } from "node:fs";
10
+ import { join, posix, resolve } from "node:path";
11
+ import { extractTools, relativeImports } from "./extract.mjs";
12
+ import { classifyAction } from "./classify.mjs";
13
+ import { credentialBreadth, envReadsIn, scopedAlternative } from "./credentials.mjs";
14
+ import { parseConfig, configKind, claudeRuleMatches, claudeMatcherMatches } from "./configs.mjs";
15
+ import { assessGate, assessReadBack, hookCommandKind } from "./gates.mjs";
16
+ import { makeLineIndex, toPosix } from "./text.mjs";
17
+
18
+ export const SCAN_NOTE = "Heuristic, static scan. It can miss actions and misclassify names.";
19
+ export const SCHEMA = "intentrax.scan.v1";
20
+ export const FINDING_TYPES = Object.freeze(["EXPOSED", "UNGATED", "SELF-REPORTED"]);
21
+
22
+ export class ScanError extends Error {
23
+ constructor(message) {
24
+ super(message);
25
+ this.name = "ScanError";
26
+ }
27
+ }
28
+
29
+ const SKIP_DIRS = new Set([
30
+ "node_modules", "dist", "build", "out", "coverage", "vendor", "third_party", "venv", "env", "__pycache__",
31
+ "target", "site-packages", "bower_components", "jspm_packages", "Pods",
32
+ ]);
33
+ const ALLOWED_DOT_DIRS = new Set([".claude", ".cursor", ".vscode", ".gemini", ".intentrax"]);
34
+ const TEST_DIRS = new Set(["test", "tests", "__tests__", "spec", "specs", "fixtures", "__fixtures__", "__mocks__", "testdata", "test-fixtures", "e2e"]);
35
+ const SOURCE_EXT = /\.(?:m?[jt]sx?|c[jt]s|py)$/i;
36
+ const TOOL_JSON = /(?:^|\/)[^/]*(?:tool|function)[^/]*\.json$/i;
37
+ const TEST_FILE = /\.(?:test|spec)\.[^./]+$|(?:^|\/)test_[^/]*\.py$|_test\.py$/i;
38
+ const MAX_FILE_BYTES = 1_000_000;
39
+
40
+ // Keys the agent uses to talk to its model, observability or Intentrax itself.
41
+ // They do not grant the agent's tools any reach, so they are not attached.
42
+ const NON_TOOL_CREDENTIAL = /^(?:OPENAI|ANTHROPIC|CLAUDE|GEMINI|GOOGLE_GENERATIVE_AI|GOOGLE_AI|MISTRAL|COHERE|GROQ|TOGETHER|OPENROUTER|DEEPSEEK|XAI|PERPLEXITY|FIREWORKS|REPLICATE|HUGGINGFACE|HF|AZURE_OPENAI|LANGCHAIN|LANGSMITH|LANGFUSE|HELICONE|BRAINTRUST|INTENTRAX|VOYAGE|ELEVENLABS)_/i;
43
+
44
+ function walk(root, { includeTests, maxFiles }) {
45
+ const files = [];
46
+ const warnings = [];
47
+ let hooksPresent = false;
48
+ let skippedLarge = 0;
49
+ const stack = [""];
50
+ while (stack.length) {
51
+ const rel = stack.pop();
52
+ let entries;
53
+ try {
54
+ entries = readdirSync(join(root, rel), { withFileTypes: true });
55
+ } catch {
56
+ if (rel === "") throw new ScanError(`cannot read directory ${root}`);
57
+ warnings.push(`could not read directory ${rel}`);
58
+ continue;
59
+ }
60
+ entries.sort((a, b) => (a.name < b.name ? 1 : -1));
61
+ for (const e of entries) {
62
+ const childRel = rel ? `${rel}/${e.name}` : e.name;
63
+ if (e.isSymbolicLink()) continue;
64
+ if (e.isDirectory()) {
65
+ if (e.name.startsWith(".") && !ALLOWED_DOT_DIRS.has(e.name)) continue;
66
+ if (SKIP_DIRS.has(e.name)) continue;
67
+ if (!includeTests && TEST_DIRS.has(e.name)) continue;
68
+ stack.push(childRel);
69
+ continue;
70
+ }
71
+ if (!e.isFile()) continue;
72
+ if (childRel.startsWith(".intentrax/hooks/")) hooksPresent = true;
73
+ const isConfig = Boolean(configKind(childRel));
74
+ const isSource = SOURCE_EXT.test(e.name) && (includeTests || !TEST_FILE.test(childRel));
75
+ const isToolJson = !isConfig && TOOL_JSON.test(childRel) && !/package(-lock)?\.json$|tsconfig/.test(e.name);
76
+ if (!isConfig && !isSource && !isToolJson) continue;
77
+ let size = 0;
78
+ try {
79
+ size = statSync(join(root, childRel)).size;
80
+ } catch {
81
+ continue;
82
+ }
83
+ if (size > MAX_FILE_BYTES) {
84
+ skippedLarge += 1;
85
+ continue;
86
+ }
87
+ if (files.length >= maxFiles) {
88
+ warnings.push(`stopped after ${maxFiles} files; the rest of the project was not scanned`);
89
+ return { files, warnings, hooksPresent };
90
+ }
91
+ files.push({ rel: childRel, isConfig, isSource: isSource || isToolJson });
92
+ }
93
+ }
94
+ if (skippedLarge) warnings.push(`${skippedLarge} file(s) over ${MAX_FILE_BYTES} bytes were skipped`);
95
+ return { files, warnings, hooksPresent };
96
+ }
97
+
98
+ function loc(file, line) {
99
+ return `${file}:${line}`;
100
+ }
101
+
102
+ function credKey(c) {
103
+ return c.refersTo ?? c.name;
104
+ }
105
+
106
+ export function scanProject(dir = ".", options = {}) {
107
+ const root = resolve(String(dir));
108
+ let st;
109
+ try {
110
+ st = statSync(root);
111
+ } catch {
112
+ throw new ScanError(`no such directory: ${dir}`);
113
+ }
114
+ if (!st.isDirectory()) throw new ScanError(`not a directory: ${dir}`);
115
+ const includeTests = options.includeTests === true;
116
+ const maxFiles = Number.isSafeInteger(options.maxFiles) && options.maxFiles > 0 ? options.maxFiles : 20000;
117
+
118
+ const { files, warnings, hooksPresent } = walk(root, { includeTests, maxFiles });
119
+ const fileSet = new Set(files.map((f) => f.rel));
120
+ const textCache = new Map();
121
+ const read = (rel) => {
122
+ if (!textCache.has(rel)) {
123
+ let t = null;
124
+ try {
125
+ t = readFileSync(join(root, rel), "utf8");
126
+ } catch {
127
+ warnings.push(`could not read ${rel}`);
128
+ }
129
+ textCache.set(rel, t);
130
+ }
131
+ return textCache.get(rel);
132
+ };
133
+
134
+ // 1. Agent-client configuration.
135
+ const servers = [];
136
+ const claudeByRoot = new Map();
137
+ const cursorByRoot = new Map();
138
+ for (const f of files.filter((x) => x.isConfig)) {
139
+ const text = read(f.rel);
140
+ if (text == null) continue;
141
+ const parsed = parseConfig(f.rel, text);
142
+ if (!parsed) continue;
143
+ if (parsed.warning) {
144
+ warnings.push(parsed.warning);
145
+ continue;
146
+ }
147
+ for (const s of parsed.servers) servers.push({ ...s, configText: text });
148
+ if (parsed.claude) {
149
+ const prev = claudeByRoot.get(parsed.root);
150
+ claudeByRoot.set(parsed.root, prev ? mergeClaude(prev, parsed.claude) : parsed.claude);
151
+ }
152
+ if (parsed.cursor) cursorByRoot.set(parsed.root, parsed.cursor);
153
+ }
154
+
155
+ // 2. Tool definitions in source.
156
+ const toolsByFile = new Map();
157
+ for (const f of files.filter((x) => x.isSource && !x.rel.startsWith(".intentrax/"))) {
158
+ const text = read(f.rel);
159
+ if (text == null) continue;
160
+ const tools = extractTools(text, f.rel);
161
+ if (tools.length) toolsByFile.set(f.rel, tools);
162
+ }
163
+
164
+ // 3. Link configured stdio servers to their in-repo source.
165
+ const linkedFiles = new Map(); // file -> [server]
166
+ for (const s of servers) {
167
+ s.sourceFiles = [];
168
+ if (s.disabled || s.transport !== "stdio") continue;
169
+ const entries = [];
170
+ for (const c of s.entries) {
171
+ for (const cand of entryVariants(posix.join(s.root || ".", c.base || ".", c.path))) {
172
+ if (fileSet.has(cand)) {
173
+ entries.push(cand);
174
+ break;
175
+ }
176
+ }
177
+ }
178
+ const seen = new Set();
179
+ const queue = entries.map((e) => ({ file: e, depth: 0 }));
180
+ while (queue.length) {
181
+ const { file, depth } = queue.shift();
182
+ if (seen.has(file)) continue;
183
+ seen.add(file);
184
+ const text = read(file);
185
+ if (text == null || depth >= 3) continue;
186
+ const isPy = /\.py$/.test(file);
187
+ for (const imp of relativeImports(text, isPy)) {
188
+ for (const cand of importVariants(file, imp.module, isPy, s.root)) {
189
+ if (fileSet.has(cand)) {
190
+ queue.push({ file: cand, depth: depth + 1 });
191
+ break;
192
+ }
193
+ }
194
+ }
195
+ }
196
+ s.sourceFiles = [...seen];
197
+ for (const file of seen) {
198
+ if (!linkedFiles.has(file)) linkedFiles.set(file, []);
199
+ linkedFiles.get(file).push(s);
200
+ }
201
+ }
202
+
203
+ // 4. Actions.
204
+ const actions = [];
205
+ for (const [file, tools] of toolsByFile) {
206
+ const fileText = read(file);
207
+ const lineOf = makeLineIndex(fileText);
208
+ const fileCreds = envReadsIn(fileText).map((r) => ({ name: r.name, refersTo: null, inline: false, file, line: lineOf(r.index), origin: "read in the same file" }));
209
+ const linked = linkedFiles.get(file) ?? [null];
210
+ for (const t of tools) {
211
+ const spanText = t.spans.map((s) => fileText.slice(s.start, s.end)).join("\n");
212
+ const spanCreds = t.spans.flatMap((s) => envReadsIn(fileText, s.start, s.end)).map((r) => ({ name: r.name, refersTo: null, inline: false, file, line: lineOf(r.index), origin: "read in the tool handler" }));
213
+ for (const server of linked) {
214
+ actions.push({
215
+ name: t.name,
216
+ kind: server ? "mcp-server-tool" : `${t.framework}-tool`,
217
+ framework: t.framework,
218
+ file,
219
+ line: t.line,
220
+ server: server ? { name: server.name, configFile: server.configFile, line: server.line, client: server.client, root: server.root } : null,
221
+ client: server?.client ?? null,
222
+ classification: classifyAction({ name: t.name, description: t.description, body: spanText, annotations: t.annotations }),
223
+ annotations: t.annotations,
224
+ credentials: dedupeCreds([...(server?.credentials ?? []).map((c) => ({ ...c, contextText: server.configText })), ...spanCreds, ...fileCreds].map((c) => ({ ...c, contextText: c.contextText ?? fileText }))),
225
+ codeGate: assessGate(spanText, fileText),
226
+ readBack: assessReadBack(spanText),
227
+ handlerVisible: true,
228
+ notes: [],
229
+ });
230
+ }
231
+ }
232
+ }
233
+ // External or unresolved servers: their tools cannot be listed statically.
234
+ for (const s of servers) {
235
+ if (s.disabled) continue;
236
+ const hasTools = s.sourceFiles.some((f) => toolsByFile.has(f));
237
+ if (hasTools) continue;
238
+ const classification = classifyAction({ name: s.name, domainTokens: s.domainTokens });
239
+ if (classification.category === "read") {
240
+ classification.reasons.push("its tools could not be listed statically");
241
+ }
242
+ actions.push({
243
+ name: s.name,
244
+ displayName: `MCP server "${s.name}"`,
245
+ kind: "mcp-server",
246
+ framework: "mcp",
247
+ file: s.configFile,
248
+ line: s.line,
249
+ server: { name: s.name, configFile: s.configFile, line: s.line, client: s.client, root: s.root },
250
+ client: s.client,
251
+ classification,
252
+ annotations: {},
253
+ credentials: dedupeCreds(s.credentials.map((c) => ({ ...c, contextText: s.configText }))),
254
+ codeGate: { gated: false, kind: null, heuristic: true, reasons: [] },
255
+ readBack: { present: null, heuristic: true, reasons: ["handler not in this repository"], successMessage: false },
256
+ handlerVisible: false,
257
+ toolsUnknown: true,
258
+ notes: [s.sourceFiles.length ? "entry file found, but no tool definitions were recognized in it" : s.transport === "http" ? "remote server; its tools are not in this repository" : "server code is not in this repository"],
259
+ });
260
+ }
261
+ // Claude Code built-in Bash when the project auto-approves it.
262
+ for (const [r, claude] of claudeByRoot) {
263
+ const allowRule = claude.allow.find((rule) => claudeRuleMatches(rule, "Bash"));
264
+ const bypass = claude.defaultMode === "bypassPermissions";
265
+ if (!allowRule && !bypass) continue;
266
+ actions.push({
267
+ name: "Bash",
268
+ displayName: "Bash (Claude Code shell)",
269
+ kind: "shell-tool",
270
+ framework: "claude-code",
271
+ file: claude.file,
272
+ line: 1,
273
+ server: { name: null, root: r, client: "claude-code" },
274
+ client: "claude-code",
275
+ claudeToolId: "Bash",
276
+ classification: { category: "shell", label: "runs shell commands", severity: 3, consequential: true, heuristic: true, reasons: [allowRule ? `permissions.allow contains "${allowRule}", so any command runs without a prompt` : 'defaultMode is "bypassPermissions", so any command runs without a prompt'] },
277
+ annotations: {},
278
+ credentials: [],
279
+ codeGate: { gated: false, kind: null, heuristic: true, reasons: [] },
280
+ readBack: { present: null, heuristic: true, reasons: [], successMessage: false },
281
+ handlerVisible: false,
282
+ notes: ["a shell reaches every credential in the agent's environment"],
283
+ });
284
+ }
285
+
286
+ // 5. Client-side gates and permissions; credential breadth.
287
+ for (const a of actions) {
288
+ a.gate = a.codeGate;
289
+ const r = a.server?.root ?? "";
290
+ if (a.client === "claude-code") {
291
+ const claude = claudeByRoot.get(r);
292
+ const toolId = a.claudeToolId ?? (a.toolsUnknown ? `mcp__${a.server.name}__tool` : `mcp__${a.server?.name}__${a.name}`);
293
+ if (claude) {
294
+ if (claude.deny.some((rule) => claudeRuleMatches(rule, toolId))) {
295
+ a.denied = true;
296
+ a.notes.push(`denied by permissions.deny in ${claude.file}`);
297
+ }
298
+ const hook = claude.preToolUse.find((h) => claudeMatcherMatches(h.matcher, toolId) && h.commands.some(hookCommandKind));
299
+ if (!a.gate.gated && hook) {
300
+ const kind = hook.commands.map(hookCommandKind).find(Boolean);
301
+ a.gate = { gated: true, kind: kind === "intentrax" ? "intentrax" : "approval", heuristic: true, reasons: [`Claude Code PreToolUse hook in ${hook.file} (matcher "${hook.matcher || "*"}") runs ${kind === "intentrax" ? "an Intentrax" : "an approval"} command`] };
302
+ }
303
+ if (!a.gate.gated && claude.ask.some((rule) => claudeRuleMatches(rule, toolId))) {
304
+ a.gate = { gated: true, kind: "approval", heuristic: true, reasons: [`Claude Code asks before running it (permissions.ask in ${claude.file})`] };
305
+ }
306
+ const allow = claude.allow.find((rule) => claudeRuleMatches(rule, toolId));
307
+ if (allow && !a.claudeToolId) a.notes.push(`auto-approved by permissions.allow "${allow}" in ${claude.file}`);
308
+ if (claude.defaultMode === "bypassPermissions" && !a.claudeToolId) a.notes.push(`defaultMode "bypassPermissions" in ${claude.file} auto-approves every tool`);
309
+ }
310
+ }
311
+ if (a.client === "cursor") {
312
+ const cursor = cursorByRoot.get(r);
313
+ const cmds = cursor ? (a.classification.category === "shell" ? cursor.beforeShellExecution : cursor.beforeMCPExecution) : [];
314
+ const kind = cmds.map(hookCommandKind).find(Boolean);
315
+ if (!a.gate.gated && kind) {
316
+ a.gate = { gated: true, kind: kind === "intentrax" ? "intentrax" : "approval", heuristic: true, reasons: [`Cursor hook in ${cursor.file} runs ${kind === "intentrax" ? "an Intentrax" : "an approval"} command before the call`] };
317
+ }
318
+ }
319
+ if (!a.gate.gated && hooksPresent) {
320
+ a.notes.push("Intentrax hooks are scaffolded in .intentrax/hooks/, but nothing in front of this action calls one");
321
+ }
322
+ for (const c of a.credentials) {
323
+ c.breadth = credentialBreadth(c.name, c.contextText) ?? (c.refersTo ? credentialBreadth(c.refersTo, c.contextText) : null);
324
+ }
325
+ // A server whose tools we cannot see, holding a broad credential, is
326
+ // treated as consequential: anything that credential allows is reachable.
327
+ if (a.toolsUnknown && !a.classification.consequential && a.credentials.some((c) => c.breadth)) {
328
+ a.classification = {
329
+ ...a.classification,
330
+ category: "unknown",
331
+ label: "tools not listed statically",
332
+ severity: 1,
333
+ consequential: true,
334
+ reasons: [...a.classification.reasons, "its tools could not be listed statically and it holds a broad credential"],
335
+ };
336
+ }
337
+ }
338
+
339
+ // Same credential reaching read-only and severe tools.
340
+ const readersByCred = new Map();
341
+ for (const a of actions) {
342
+ if (a.denied || a.classification.category !== "read") continue;
343
+ for (const c of a.credentials) {
344
+ const k = credKey(c);
345
+ if (!readersByCred.has(k)) readersByCred.set(k, new Set());
346
+ readersByCred.get(k).add(a.name);
347
+ }
348
+ }
349
+ for (const a of actions) {
350
+ a.sharedCredentials = [];
351
+ if (a.classification.severity < 3) continue;
352
+ for (const c of a.credentials) {
353
+ const readers = readersByCred.get(credKey(c));
354
+ if (readers && readers.size) a.sharedCredentials.push({ credential: c, readers: [...readers].sort() });
355
+ }
356
+ }
357
+
358
+ // 6. Findings.
359
+ const findings = [];
360
+ for (const a of actions) {
361
+ if (a.denied || !a.classification.consequential) continue;
362
+ const display = a.displayName ?? a.name;
363
+ const broad = a.credentials.filter((c) => c.breadth);
364
+ const gatePhrase = a.gate.gated ? `, gated (${a.gate.kind === "intentrax" ? "Intentrax" : "approval step"})` : ", no gate";
365
+ if (broad.length || a.sharedCredentials.length) {
366
+ let what;
367
+ if (broad.length) {
368
+ const c = broad[0];
369
+ what = `${c.breadth.label} (${credKey(c)})`;
370
+ } else {
371
+ const s = a.sharedCredentials[0];
372
+ what = `${credKey(s.credential)}, which also serves read tools (${s.readers.slice(0, 3).join(", ")}${s.readers.length > 3 ? ", ..." : ""})`;
373
+ }
374
+ findings.push(makeFinding("EXPOSED", a, `EXPOSED ${display} reachable with ${what}${gatePhrase}`, broad, hooksPresent));
375
+ } else if (!a.gate.gated) {
376
+ findings.push(makeFinding("UNGATED", a, `UNGATED ${display} (${a.classification.label}) runs with no gate or approval step`, broad, hooksPresent));
377
+ }
378
+ if (a.handlerVisible && a.readBack.present === false && (a.classification.severity >= 2 || a.readBack.successMessage)) {
379
+ const how = a.readBack.successMessage ? "reports success" : "returns its own result as the outcome";
380
+ findings.push(makeFinding("SELF-REPORTED", a, `SELF-REPORTED ${display} ${how} without reading the result back`, broad, hooksPresent));
381
+ }
382
+ }
383
+ const order = { EXPOSED: 0, UNGATED: 1, "SELF-REPORTED": 2 };
384
+ findings.sort((x, y) => y.severity - x.severity || order[x.type] - order[y.type] || x.action.localeCompare(y.action) || x.location.localeCompare(y.location));
385
+ findings.forEach((f, i) => {
386
+ f.id = i + 1;
387
+ });
388
+
389
+ const consequential = actions.filter((a) => a.classification.consequential && !a.denied);
390
+ const counts = Object.fromEntries(FINDING_TYPES.map((t) => [t, findings.filter((f) => f.type === t).length]));
391
+ const summary = {
392
+ filesScanned: files.length,
393
+ actionsFound: actions.length,
394
+ consequentialActions: consequential.length,
395
+ gatedActions: consequential.filter((a) => a.gate.gated).length,
396
+ mcpServers: servers.length,
397
+ serversWithUnlistedTools: actions.filter((a) => a.toolsUnknown).length,
398
+ findings: findings.length,
399
+ byType: counts,
400
+ warnings: warnings.length,
401
+ };
402
+ let firstLine;
403
+ if (findings.length) firstLine = findings[0].line;
404
+ else if (actions.length === 0) firstLine = "NO FINDINGS: no agent-reachable actions were recognized";
405
+ else if (consequential.length === 0) firstLine = `NO FINDINGS: ${actions.length} agent-reachable action(s), none classified as consequential`;
406
+ else firstLine = `NO FINDINGS: ${consequential.length} consequential action(s), each gated, without broad credentials, and read back where visible`;
407
+
408
+ return {
409
+ schema: SCHEMA,
410
+ firstLine,
411
+ findings,
412
+ actions: actions.map(publicAction),
413
+ summary,
414
+ warnings,
415
+ note: SCAN_NOTE,
416
+ };
417
+ }
418
+
419
+ function makeFinding(type, a, line, broad, hooksPresent) {
420
+ const recs = [];
421
+ const tool = a.displayName ?? a.name;
422
+ const inline = a.credentials.filter((c) => c.inline);
423
+ const inlineNote = inline.length ? ` ${inline.map((c) => c.name).join(", ")} ${inline.length > 1 ? "are" : "is"} written inline in ${[...new Set(inline.map((c) => c.file))].join(", ")}: move the value to a secret store and reference it by name.` : "";
424
+
425
+ if (type === "EXPOSED") {
426
+ const parts = [];
427
+ for (const c of broad) parts.push(`replace ${credKey(c)} with ${scopedAlternative(credKey(c))}`);
428
+ for (const s of a.sharedCredentials) {
429
+ if (broad.includes(s.credential)) continue;
430
+ parts.push(`split ${credKey(s.credential)}: give the read tools (${s.readers.slice(0, 3).join(", ")}) a read-only credential and give ${tool} its own, narrower one (${scopedAlternative(credKey(s.credential))})`);
431
+ }
432
+ recs.push({ kind: "least-privilege", text: `Narrow the credential first: ${parts.join("; ")}.${inlineNote}` });
433
+ if (!a.gate.gated) recs.push({ kind: "intentrax", text: gateRec(a, tool, hooksPresent) });
434
+ } else if (type === "UNGATED") {
435
+ let text;
436
+ if (a.classification.category === "shell") {
437
+ text = `Run the agent's shell without production credentials in its environment (a container or sandbox), and allowlist the commands it needs instead of auto-approving all of them.`;
438
+ } else {
439
+ const c = a.credentials[0];
440
+ text = `Give ${tool} only ${c ? scopedAlternative(credKey(c)) : "a credential limited to what it does"}, and remove it from the agent's tools if the agent does not need it.`;
441
+ }
442
+ recs.push({ kind: "least-privilege", text: text + inlineNote });
443
+ recs.push({ kind: "intentrax", text: gateRec(a, tool, hooksPresent) });
444
+ } else {
445
+ recs.push({ kind: "least-privilege", text: `Read the result back with a separate read-only credential, not the one that performed ${tool}, and report success only when the read-back matches.` });
446
+ recs.push({ kind: "intentrax", text: "Try the read-back locally: npx @intentrax/sdk sandbox --check ./check.mjs reads the outcome and flags a contradiction (a local, non-trust-bearing trial, not evidence)." });
447
+ }
448
+ return {
449
+ type,
450
+ line,
451
+ action: a.name,
452
+ severity: a.classification.severity,
453
+ category: a.classification.category,
454
+ location: loc(a.file, a.line),
455
+ server: a.server?.name ? { name: a.server.name, config: loc(a.server.configFile, a.server.line) } : null,
456
+ classification: a.classification,
457
+ credentials: a.credentials.map(publicCred),
458
+ gate: a.gate,
459
+ readBack: a.readBack,
460
+ notes: a.notes,
461
+ recommendations: recs,
462
+ heuristic: true,
463
+ };
464
+ }
465
+
466
+ function gateRec(a, tool, hooksPresent) {
467
+ const adapter = adapterFor(a);
468
+ const scaffold = hooksPresent ? "call the scaffolded .intentrax/hooks/ entrypoint" : `run npx @intentrax/sdk init ${adapter} and call the generated hook`;
469
+ return `Then gate it: ${scaffold} before ${tool} runs, at the tool dispatcher, so a denied or failed admission stops the call (fail closed).`;
470
+ }
471
+
472
+ function adapterFor(a) {
473
+ if (a.client === "claude-code") return "claude-code";
474
+ if (a.client === "cursor" && a.classification.category === "shell") return "cursor";
475
+ if (a.framework === "mcp" || a.server) return "mcp";
476
+ if (["langchain", "langgraph", "vercel-ai-sdk"].includes(a.framework)) return a.framework;
477
+ return "custom-agent";
478
+ }
479
+
480
+ function publicCred(c) {
481
+ const out = { name: c.name, location: loc(c.file, c.line), origin: c.origin };
482
+ if (c.refersTo) out.refersTo = c.refersTo;
483
+ if (c.inline) out.inline = true;
484
+ if (c.breadth) out.breadth = c.breadth;
485
+ return out;
486
+ }
487
+
488
+ function publicAction(a) {
489
+ return {
490
+ name: a.name,
491
+ displayName: a.displayName ?? a.name,
492
+ kind: a.kind,
493
+ framework: a.framework,
494
+ location: loc(a.file, a.line),
495
+ server: a.server?.name ? { name: a.server.name, config: loc(a.server.configFile, a.server.line), client: a.server.client } : null,
496
+ classification: a.classification,
497
+ credentials: a.credentials.map(publicCred),
498
+ gate: a.gate,
499
+ readBack: a.readBack,
500
+ denied: a.denied === true,
501
+ toolsUnknown: a.toolsUnknown === true,
502
+ notes: a.notes,
503
+ };
504
+ }
505
+
506
+ function dedupeCreds(creds) {
507
+ const out = [];
508
+ const seen = new Set();
509
+ for (const c of creds) {
510
+ const k = credKey(c);
511
+ if (NON_TOOL_CREDENTIAL.test(k)) continue;
512
+ if (seen.has(k)) continue;
513
+ seen.add(k);
514
+ out.push(c);
515
+ }
516
+ return out;
517
+ }
518
+
519
+ function mergeClaude(a, b) {
520
+ return {
521
+ file: a.file,
522
+ allow: [...a.allow, ...b.allow],
523
+ ask: [...a.ask, ...b.ask],
524
+ deny: [...a.deny, ...b.deny],
525
+ defaultMode: b.defaultMode ?? a.defaultMode,
526
+ enableAllProjectMcpServers: a.enableAllProjectMcpServers || b.enableAllProjectMcpServers,
527
+ preToolUse: [...a.preToolUse, ...b.preToolUse],
528
+ };
529
+ }
530
+
531
+ function norm(p) {
532
+ const n = posix.normalize(toPosix(p)).replace(/^\.\//, "");
533
+ return n === "." ? "" : n;
534
+ }
535
+
536
+ // node dist/index.js usually comes from src/index.ts.
537
+ function entryVariants(p) {
538
+ const base = norm(p);
539
+ const out = [base];
540
+ const noExt = base.replace(/\.(?:m?[jt]sx?|c[jt]s)$/, "");
541
+ for (const ext of [".ts", ".mts", ".tsx", ".js", ".mjs"]) out.push(noExt + ext);
542
+ const src = base.replace(/(^|\/)(?:dist|build|out|lib)\//, "$1src/");
543
+ if (src !== base) {
544
+ const srcNoExt = src.replace(/\.(?:m?[jt]sx?|c[jt]s)$/, "");
545
+ for (const ext of [".ts", ".mts", ".tsx", ".js", ".mjs"]) out.push(srcNoExt + ext);
546
+ }
547
+ return out;
548
+ }
549
+
550
+ function importVariants(fromFile, mod, isPy, serverRoot) {
551
+ const dir = posix.dirname(fromFile);
552
+ if (!isPy) {
553
+ const target = norm(posix.join(dir, mod));
554
+ const noExt = target.replace(/\.(?:m?[jt]sx?|c[jt]s)$/, "");
555
+ const out = [target];
556
+ for (const ext of [".ts", ".mts", ".tsx", ".js", ".mjs", ".cjs", ".jsx"]) out.push(noExt + ext);
557
+ for (const ext of [".ts", ".js", ".mjs"]) out.push(`${target}/index${ext}`);
558
+ return out;
559
+ }
560
+ let base;
561
+ if (mod.startsWith(".")) {
562
+ const dots = mod.match(/^\.+/)[0].length;
563
+ let d = dir;
564
+ for (let i = 1; i < dots; i += 1) d = posix.dirname(d);
565
+ base = posix.join(d, mod.slice(dots).replace(/\./g, "/"));
566
+ } else {
567
+ base = posix.join(serverRoot || ".", mod.replace(/\./g, "/"));
568
+ }
569
+ base = norm(base);
570
+ return [`${base}.py`, `${base}/__init__.py`];
571
+ }