@dzhechkov/harness-core 0.3.23 → 0.3.25

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.
@@ -0,0 +1,307 @@
1
+ /**
2
+ * Shared capability vocabulary — the single source of truth for how the harness
3
+ * classifies agent capabilities, used by BOTH `mcp-scan` (project settings audit)
4
+ * and `benchmark` (per-skill S15 capability-declaration check).
5
+ *
6
+ * Keeping these regexes/sets here (rather than private to mcp-scan) guarantees the
7
+ * project-level scan and the per-skill manifest speak ONE diffable vocabulary.
8
+ *
9
+ * @packageDocumentation
10
+ */
11
+
12
+ import { existsSync, lstatSync, readdirSync, readFileSync } from 'node:fs';
13
+ import { extname, join } from 'node:path';
14
+
15
+ /** The capability classes the harness recognises. */
16
+ export type CapabilityClass = 'shell' | 'network' | 'file-write' | 'secrets' | 'mcp' | 'policy';
17
+
18
+ // --- Claude permission-grammar tool sets (lowercase for case-insensitive tests) ---
19
+ export const SHELL_TOOLS = new Set(['bash', 'powershell', 'shell']);
20
+ export const NETWORK_TOOLS = new Set(['webfetch', 'websearch']);
21
+ export const WRITE_TOOLS = new Set(['write', 'edit', 'multiedit', 'notebookedit']);
22
+ export const READ_TOOLS = new Set(['read']);
23
+ /** Recognised + benign tools (so they aren't flagged "unknown"). */
24
+ export const SAFE_TOOLS = new Set([
25
+ 'glob', 'grep', 'task', 'bashoutput', 'killbash', 'todowrite',
26
+ 'notebookread', 'slashcommand', 'exitplanmode', 'ls',
27
+ ]);
28
+
29
+ /** Interpreter binaries that can run arbitrary code. */
30
+ export const INTERPRETER_RE = /^(bash|sh|zsh|fish|node|nodejs|python\d?|deno|ruby|perl|php)$/i;
31
+ /** Package runners that fetch + execute arbitrary remote code. */
32
+ export const PACKAGE_RUNNERS = new Set(['npx', 'npm', 'pnpm', 'yarn', 'uvx', 'uv', 'pipx', 'bunx', 'bun', 'deno']);
33
+ /** Inline-code argument flags. */
34
+ export const INLINE_CODE_ARGS = new Set(['-c', '-e', '-eval', '--eval', '-p']);
35
+
36
+ /** Binaries that imply outbound network. */
37
+ export const SHELL_NET_RE = /\b(curl|wget|nc|ncat|netcat|ssh|scp|sftp|telnet|ftp)\b/i;
38
+ /** Binaries / redirects that imply filesystem writes. */
39
+ export const SHELL_WRITE_RE = /\b(rm|mv|cp|tee|dd|truncate|chmod|chown|mkfifo)\b|>>?/;
40
+ /** Concrete secret-file location patterns (not bare "secret"/"credential" substrings). */
41
+ export const SECRET_FILE_RE =
42
+ /\.env\b|\.env\.|id_rsa|id_ed25519|id_ecdsa|\.ssh\/|\.aws\/|\.config\/gcloud|application_default_credentials|\.npmrc|\.netrc|\.git-credentials|\.kube\/config|\.pem\b|\.p12\b|\.pfx\b|\.key\b/i;
43
+
44
+ export const MAX_FILE_BYTES = 5 * 1024 * 1024;
45
+
46
+ // ---------------------------------------------------------------------------
47
+ // permission-grammar helpers
48
+ // ---------------------------------------------------------------------------
49
+
50
+ /** Parse a Claude permission grant like `Bash(git *)` → `{ tool, arg }`. Never throws. */
51
+ export function parseGrant(grant: unknown): { tool: string; arg: string | null } {
52
+ if (typeof grant !== 'string') return { tool: '', arg: null };
53
+ const s = grant.trim();
54
+ const m = /^([A-Za-z_][\w-]*)\s*\((.*)\)\s*$/.exec(s);
55
+ if (m) return { tool: m[1] ?? s, arg: m[2] ?? null };
56
+ const id = /^([A-Za-z_][\w-]*|\*)/.exec(s);
57
+ return { tool: id ? (id[1] ?? s) : s, arg: null };
58
+ }
59
+
60
+ export function isWildcard(arg: string | null): boolean {
61
+ return arg === null || arg.trim() === '' || arg.includes('*');
62
+ }
63
+
64
+ export function toolKind(tool: string): CapabilityClass | 'read' | 'safe' | 'unknown' {
65
+ const t = tool.toLowerCase();
66
+ if (t === '*') return 'shell';
67
+ if (SHELL_TOOLS.has(t)) return 'shell';
68
+ if (NETWORK_TOOLS.has(t)) return 'network';
69
+ if (WRITE_TOOLS.has(t)) return 'file-write';
70
+ if (READ_TOOLS.has(t)) return 'read';
71
+ if (t.startsWith('mcp__')) return 'mcp';
72
+ if (SAFE_TOOLS.has(t)) return 'safe';
73
+ return 'unknown';
74
+ }
75
+
76
+ // ---------------------------------------------------------------------------
77
+ // script capability detection (for the per-skill S15 check)
78
+ // ---------------------------------------------------------------------------
79
+
80
+ /** Self-declared capability surface parsed from a skill's `capabilities:` block. */
81
+ export interface DeclaredCapabilities {
82
+ network?: boolean;
83
+ shell?: boolean;
84
+ 'file-write'?: boolean;
85
+ dangerous?: boolean;
86
+ }
87
+
88
+ /** Capabilities statically detected in a skill's `scripts/`. P1: network + shell only. */
89
+ export interface DetectedCapabilities {
90
+ network: boolean;
91
+ shell: boolean;
92
+ }
93
+
94
+ /** Strip heredoc bodies (`<<EOF … EOF`, incl. `<<-'EOF'`) — unquoted free text. */
95
+ function stripHeredocs(text: string): string {
96
+ return text.replace(/<<-?\s*(['"]?)(\w+)\1[\s\S]*?\n[ \t]*\2\b/g, ' ');
97
+ }
98
+
99
+ /** Strip comments + heredocs (keeps string literals — curl inside an arg string is real). */
100
+ export function stripComments(text: string): string {
101
+ return stripHeredocs(text)
102
+ .replace(/\/\*[\s\S]*?\*\//g, ' ') // /* paired block */
103
+ .replace(/\/\*[\s\S]*$/g, ' ') // unterminated block → EOF
104
+ .replace(/(^|[^:])\/\/[^\n]*/g, '$1 ') // // line (not http://)
105
+ .replace(/(^|\s)#[^\n]*/g, '$1 '); // # shell/py
106
+ }
107
+
108
+ /**
109
+ * Strip comments, heredocs AND quoted string literals. Used for the IDENTIFIER
110
+ * pass (fetch/axios/execSync/http modules) where the token is real code, never a
111
+ * quoted search pattern — this is what kills FPs like `grep "writeFileSync"`.
112
+ */
113
+ export function stripCodeNoise(text: string): string {
114
+ return stripComments(text)
115
+ .replace(/'(?:[^'\\]|\\.)*'/g, ' ')
116
+ .replace(/"(?:[^"\\]|\\.)*"/g, ' ')
117
+ .replace(/`(?:[^`\\]|\\.)*`/g, ' ');
118
+ }
119
+
120
+ const SCRIPT_EXTS = new Set(['.sh', '.bash', '.zsh', '.js', '.mjs', '.cjs', '.ts', '.py', '.rb', '.pl', '.php']);
121
+
122
+ // command position = line start, after a shell separator, after `sudo`/`do`/`then`,
123
+ // inside `$( )`, or right after an opening quote (covers subprocess.run("curl …")).
124
+ const CMD_PREFIX = `(?:^|[;&|(\\n]|&&|\\|\\||\\$\\(|\\bsudo\\s+|\\bthen\\s+|\\bdo\\s+|["'\`])\\s*`;
125
+ // the next token must look like an argument/subcommand (a word/path/flag), not an
126
+ // operator — so `uv = coord` / `ssh = cfg` (assignments) and `grep "curl"` don't match.
127
+ const ARG_FOLLOWS = `(?=\\s+[\\w./~-])`;
128
+ // a network binary AT command position, followed by an argument.
129
+ const CMD_NET_RE = new RegExp(`${CMD_PREFIX}(curl|wget|nc|ncat|netcat|ssh|scp|sftp|telnet|ftp)\\b${ARG_FOLLOWS}`, 'i');
130
+ // a package-runner / interpreter AT command position, followed by an argument → shell.
131
+ const CMD_SHELL_RE = new RegExp(
132
+ `${CMD_PREFIX}(${[...PACKAGE_RUNNERS].join('|')}|python\\d?|node|nodejs|bash|sh|zsh|ruby|perl|php)\\b${ARG_FOLLOWS}`,
133
+ 'i',
134
+ );
135
+ // network via library identifiers (matched on noise-stripped code — never in a quote).
136
+ const NETWORK_CALL_RE =
137
+ /\bfetch\s*\(|\baxios\b|WebFetch\s*\(|\bWebSearch\b|\brequests\.|\burllib3?\b|\bhttpx\b|\baiohttp\b|\bparamiko\b|\bsmtplib\b|\bftplib\b|\bhttp\.client\b|\bsocket\.(?:socket|create_connection)\s*\(|\b(?:https?|net|dgram|tls|dns)\.(?:get|request|createConnection|connect|createSocket|resolve\w*)\s*\(|\bnew\s+WebSocket\b|(?:require\(|from\s+)['"](?:node:)?(?:http|https|net|dgram|tls|ws|node-fetch|got|undici)['"]/;
138
+ // shell exec via library identifiers (language-agnostic).
139
+ const EXEC_CALL_RE =
140
+ /child_process|execSync|execFileSync|spawnSync|\bspawn\s*\(|\bexec(?:File)?\s*\(|\bsubprocess\b|\bos\.system\b|\bos\.popen\b|\bPopen\b|\bOpen3\b|\bcommands\.get(?:status)?output\b|%x[([{]|(?:^|[^.\w])system\s*\(/m;
141
+
142
+ function isProbablyBinary(buf: string): boolean {
143
+ return /[\x00-\x08\x0E-\x1F]/.test(buf);
144
+ }
145
+
146
+ function collectScriptFiles(dir: string, depth: number, acc: string[]): void {
147
+ if (depth > 3 || acc.length >= 200) return;
148
+ let entries: string[];
149
+ try {
150
+ entries = readdirSync(dir);
151
+ } catch {
152
+ return;
153
+ }
154
+ for (const name of entries) {
155
+ if (acc.length >= 200) return;
156
+ const abs = join(dir, name);
157
+ let st;
158
+ try {
159
+ st = lstatSync(abs);
160
+ } catch {
161
+ continue;
162
+ }
163
+ if (st.isSymbolicLink()) continue;
164
+ if (st.isDirectory()) {
165
+ collectScriptFiles(abs, depth + 1, acc);
166
+ } else if (st.isFile() && st.size <= 256 * 1024) {
167
+ acc.push(abs);
168
+ }
169
+ }
170
+ }
171
+
172
+ /**
173
+ * Statically detect network + shell capability usage in a skill's `scripts/`.
174
+ * Reads only `scripts/` (never SKILL.md prose), recursively (bounded), skipping
175
+ * binary / symlinked / oversized files. Deterministic, no execution.
176
+ *
177
+ * Known scope (Phase 1, by design — documented, not bugs): file-write and
178
+ * `dangerous` are not auto-detected; dynamically-assembled commands
179
+ * (`$RUNNER install`, eval'd strings) and indirected calls evade static regexes.
180
+ * S15 is a best-effort self-consistency LINT, not a sandbox.
181
+ */
182
+ export function detectScriptCapabilities(skillDir: string): DetectedCapabilities {
183
+ const out: DetectedCapabilities = { network: false, shell: false };
184
+ const scriptsDir = join(skillDir, 'scripts');
185
+ if (!existsSync(scriptsDir)) return out;
186
+
187
+ const files: string[] = [];
188
+ collectScriptFiles(scriptsDir, 0, files);
189
+
190
+ for (const abs of files) {
191
+ const ext = extname(abs).toLowerCase();
192
+ let raw: string;
193
+ try {
194
+ raw = readFileSync(abs, 'utf-8');
195
+ } catch {
196
+ continue;
197
+ }
198
+ if (isProbablyBinary(raw)) continue;
199
+
200
+ const hasShebang = /^#!/.test(raw);
201
+ const isShellExt = ext === '.sh' || ext === '.bash' || ext === '.zsh';
202
+ // shell scripts (by extension, or extensionless with a shell shebang) ARE shell usage
203
+ if (isShellExt || (ext === '' && /^#![^\n]*\b(bash|sh|zsh)\b/.test(raw))) out.shell = true;
204
+ if (!SCRIPT_EXTS.has(ext) && !hasShebang) continue;
205
+
206
+ const commentless = stripComments(raw); // strings kept → curl in an arg string survives
207
+ const noiseless = stripCodeNoise(raw); // strings gone → identifier pass
208
+
209
+ if (CMD_NET_RE.test(commentless) || NETWORK_CALL_RE.test(noiseless)) out.network = true;
210
+ if (out.shell || CMD_SHELL_RE.test(commentless) || EXEC_CALL_RE.test(noiseless)) out.shell = true;
211
+ }
212
+ return out;
213
+ }
214
+
215
+ /**
216
+ * Parse the `capabilities:` block from a SKILL.md document. Reads only the
217
+ * frontmatter region (the first `---`-fenced block) and only DIRECT children of
218
+ * `capabilities:` (so a nested `limits.network` is never mistaken for a top-level
219
+ * declaration). Absent block or absent key → `undefined` ("not asserted").
220
+ */
221
+ export function parseDeclaredCapabilities(skillMd: string): DeclaredCapabilities {
222
+ const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---/.exec(skillMd);
223
+ const fm = fmMatch ? (fmMatch[1] ?? '') : '';
224
+ const block = /^capabilities:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(fm);
225
+ if (!block) return {};
226
+ const lines = (block[1] ?? '').split('\n');
227
+ const firstReal = lines.find((l) => l.trim() !== '');
228
+ if (!firstReal) return {};
229
+ const childIndent = (/^[ \t]*/.exec(firstReal)?.[0]) ?? '';
230
+
231
+ const out: DeclaredCapabilities = {};
232
+ const read = (key: string): boolean | undefined => {
233
+ const re = new RegExp(`^${childIndent}${key.replace('-', '\\-')}:[ \\t]*(true|false)\\b`);
234
+ for (const l of lines) {
235
+ const m = re.exec(l);
236
+ if (m) return m[1] === 'true';
237
+ }
238
+ return undefined;
239
+ };
240
+ const network = read('network');
241
+ const shell = read('shell');
242
+ const fileWrite = read('file-write');
243
+ const dangerous = read('dangerous');
244
+ if (network !== undefined) out.network = network;
245
+ if (shell !== undefined) out.shell = shell;
246
+ if (fileWrite !== undefined) out['file-write'] = fileWrite;
247
+ if (dangerous !== undefined) out.dangerous = dangerous;
248
+ return out;
249
+ }
250
+
251
+ /** Declared runtime limits (inert today — no enforcement home in Claude Code settings). */
252
+ export interface DeclaredLimits {
253
+ toolTimeoutMs?: number;
254
+ maxToolCallsPerTurn?: number;
255
+ requireApprovalForDangerous?: boolean;
256
+ }
257
+
258
+ /**
259
+ * Parse the nested `capabilities.limits` block from a SKILL.md frontmatter.
260
+ * Fail-open: a malformed/absent block yields `{}` (never throws). These values
261
+ * are INERT — Claude Code settings.json has no timeout/rate-limit field; they are
262
+ * only machine-actionable in an MCP host's policy.json.
263
+ */
264
+ export function parseDeclaredLimits(skillMd: string): DeclaredLimits {
265
+ const fmMatch = /^---\r?\n([\s\S]*?)\r?\n---/.exec(skillMd);
266
+ const fm = fmMatch ? (fmMatch[1] ?? '') : '';
267
+ // Anchor under capabilities: — only a `limits:` that is a DIRECT child of
268
+ // capabilities counts (not some unrelated indented `limits:` elsewhere).
269
+ const capBlock = /^capabilities:[ \t]*\r?\n((?:[ \t]+.*\r?\n?)*)/m.exec(fm);
270
+ if (!capBlock) return {};
271
+ const capLines = (capBlock[1] ?? '').split('\n');
272
+ const firstReal = capLines.find((l) => l.trim() !== '');
273
+ if (!firstReal) return {};
274
+ const childIndent = (/^[ \t]*/.exec(firstReal)?.[0]) ?? '';
275
+
276
+ // find the `limits:` line at the capabilities-child indent, then capture only
277
+ // its strictly-deeper-indented children.
278
+ const limitsIdx = capLines.findIndex((l) => new RegExp(`^${childIndent}limits:[ \\t]*$`).test(l));
279
+ if (limitsIdx === -1) return {};
280
+ const body: string[] = [];
281
+ for (let i = limitsIdx + 1; i < capLines.length; i++) {
282
+ const l = capLines[i] ?? '';
283
+ if (l.trim() === '') continue;
284
+ const indent = (/^[ \t]*/.exec(l)?.[0]) ?? '';
285
+ if (indent.length <= childIndent.length) break; // back to a sibling → end of limits
286
+ body.push(l);
287
+ }
288
+ const text = body.join('\n');
289
+ const out: DeclaredLimits = {};
290
+ const num = (key: string): number | undefined => {
291
+ const m = new RegExp(`^[ \\t]+${key}:[ \\t]*(\\d+)\\b`, 'm').exec(text);
292
+ if (!m) return undefined;
293
+ const n = Number(m[1]);
294
+ return Number.isSafeInteger(n) && n >= 0 ? n : undefined; // fail-open on absurd values
295
+ };
296
+ const bool = (key: string): boolean | undefined => {
297
+ const m = new RegExp(`^[ \\t]+${key}:[ \\t]*(true|false)\\b`, 'm').exec(text);
298
+ return m ? m[1] === 'true' : undefined;
299
+ };
300
+ const tt = num('toolTimeoutMs');
301
+ const mc = num('maxToolCallsPerTurn');
302
+ const ra = bool('requireApprovalForDangerous');
303
+ if (tt !== undefined) out.toolTimeoutMs = tt;
304
+ if (mc !== undefined) out.maxToolCallsPerTurn = mc;
305
+ if (ra !== undefined) out.requireApprovalForDangerous = ra;
306
+ return out;
307
+ }
package/src/index.ts CHANGED
@@ -56,5 +56,30 @@ export type {
56
56
  } from './cost-scoring.js';
57
57
  export { importEcc } from './import-ecc.js';
58
58
  export type { ImportEccReport, ImportEccOptions, ImportedSkill } from './import-ecc.js';
59
+ export { scanMcp, parseGrant } from './mcp-scan.js';
60
+ export {
61
+ detectScriptCapabilities,
62
+ parseDeclaredCapabilities,
63
+ parseDeclaredLimits,
64
+ stripCodeNoise,
65
+ toolKind,
66
+ } from './capability-vocab.js';
67
+ export type { CapabilityClass, DeclaredCapabilities, DetectedCapabilities, DeclaredLimits } from './capability-vocab.js';
68
+ export { reconcileCapabilities, RECONCILE_BANNER } from './reconcile.js';
69
+ export type {
70
+ ReconcileReport,
71
+ ReconcileFinding,
72
+ ReconcileAxis,
73
+ AxisState,
74
+ LimitsRollup,
75
+ PolicyArtifact,
76
+ } from './reconcile.js';
77
+ export type {
78
+ McpFinding,
79
+ McpScanReport,
80
+ McpVerdict,
81
+ McpSeverity,
82
+ McpCapability,
83
+ } from './mcp-scan.js';
59
84
  export type { RegistryEntry, Registry } from './registry.js';
60
85
  export type { BenchmarkCheck, BenchmarkScore, BenchmarkReport, CompareResult } from './benchmark.js';