@uinaf/agent-plugin-stuff 0.0.0-stage → 2.0.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/dist/cli.js ADDED
@@ -0,0 +1,734 @@
1
+ #!/usr/bin/env node
2
+ import { lintSkills } from "./lint.js";
3
+ import { encodeRunNamePart, generateRun, isIsolated, requiredEvalPackages, resolvePackageDir, runNameFor } from "./scenario.js";
4
+ import { execFileSync, spawnSync } from "node:child_process";
5
+ import { createHash } from "node:crypto";
6
+ import fs from "node:fs";
7
+ import os from "node:os";
8
+ import path from "node:path";
9
+ // src/cli.ts
10
+ const here = import.meta.dirname;
11
+ const packageDir = path.resolve(here, "..");
12
+ const selfExt = path.extname(import.meta.filename);
13
+ function toolVersion() {
14
+ return JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8")).version;
15
+ }
16
+ function parsePositiveInt(flag, raw) {
17
+ const n = Number(raw);
18
+ if (!Number.isInteger(n) || n <= 0) throw new Error(`${flag} must be a positive integer, got ${JSON.stringify(raw)}`);
19
+ return n;
20
+ }
21
+ const AGENT_EFFORTS = [
22
+ "low",
23
+ "medium",
24
+ "high",
25
+ "xhigh",
26
+ "max"
27
+ ];
28
+ function fail(msg) {
29
+ console.error(msg);
30
+ process.exit(1);
31
+ }
32
+ function parseArgs(argv) {
33
+ const positional = [];
34
+ const flags = /* @__PURE__ */ new Map();
35
+ const takesValue = /* @__PURE__ */ new Set([
36
+ "--root",
37
+ "--agent",
38
+ "--judge",
39
+ "--judge-effort",
40
+ "--agent-effort",
41
+ "--harness",
42
+ "--max-turns",
43
+ "--trials"
44
+ ]);
45
+ for (let i = 0; i < argv.length; i++) {
46
+ const a = argv[i];
47
+ if (!a.startsWith("--")) positional.push(a);
48
+ else if (takesValue.has(a)) {
49
+ const v = argv[++i];
50
+ if (v === void 0 || v.startsWith("--")) throw new Error(`${a} needs a value`);
51
+ flags.set(a, v);
52
+ } else if (a === "--all" || a === "--allow-mixed" || a === "--control") flags.set(a, true);
53
+ else throw new Error(`unknown flag: ${a}`);
54
+ }
55
+ return {
56
+ positional,
57
+ flags
58
+ };
59
+ }
60
+ function resolveRoot(flags) {
61
+ return path.resolve(flags.get("--root") ?? process.cwd());
62
+ }
63
+ function stateDirs(root, uid = process.getuid?.()) {
64
+ const base = path.join(root, ".skillcheck");
65
+ const id = createHash("sha256").update(path.resolve(root)).digest("hex").slice(0, 12);
66
+ const owner = uid === void 0 ? "" : `${uid}-`;
67
+ return {
68
+ results: path.join(base, "results"),
69
+ scratch: path.join(fs.realpathSync(os.tmpdir()), `skillcheck-${owner}${id}`),
70
+ scorecards: path.join(base, "scorecards")
71
+ };
72
+ }
73
+ function runOptions(flags) {
74
+ const harness = flags.get("--harness") ?? "claude";
75
+ if (harness !== "claude" && harness !== "codex" && harness !== "grok") throw new Error(`--harness must be claude, codex, or grok, got ${harness}`);
76
+ if (flags.has("--max-turns") && harness !== "claude") throw new Error("--max-turns is only supported with --harness claude");
77
+ const agentEffort = flags.get("--agent-effort");
78
+ if (agentEffort !== void 0) {
79
+ if (harness !== "claude") throw new Error(`--agent-effort is only supported with --harness claude; ${harness} has no effort setting wired`);
80
+ if (!AGENT_EFFORTS.includes(agentEffort)) throw new Error(`--agent-effort must be ${AGENT_EFFORTS.join(", ")}, got ${agentEffort}`);
81
+ }
82
+ const agent = flags.get("--agent");
83
+ const judgeModel = flags.get("--judge") ?? "claude-opus-5";
84
+ const judgeEffort = flags.get("--judge-effort");
85
+ if (judgeEffort !== void 0) {
86
+ const levels = judgeModel.includes(":") ? [
87
+ "minimal",
88
+ "low",
89
+ "medium",
90
+ "high"
91
+ ] : AGENT_EFFORTS;
92
+ if (!levels.includes(judgeEffort)) throw new Error(`--judge-effort for ${judgeModel} must be ${levels.join(", ")}, got ${judgeEffort}`);
93
+ }
94
+ return {
95
+ harness,
96
+ agentModel: agent,
97
+ agentEffort,
98
+ judgeModel,
99
+ judgeEffort,
100
+ maxTurns: flags.has("--max-turns") ? parsePositiveInt("--max-turns", flags.get("--max-turns")) : void 0,
101
+ control: flags.get("--control") === true,
102
+ trials: flags.has("--trials") ? parsePositiveInt("--trials", flags.get("--trials")) : 1
103
+ };
104
+ }
105
+ function runConfigOf(opts) {
106
+ return {
107
+ agent_model: opts.agentModel ?? (opts.harness === "claude" ? "claude-opus-5" : `${opts.harness}-default`),
108
+ agent_effort: opts.agentEffort ?? null,
109
+ judge_model: opts.judgeModel,
110
+ judge_effort: opts.judgeEffort ?? null,
111
+ trials: opts.trials ?? 1,
112
+ agent_access: "online",
113
+ isolated: isIsolated()
114
+ };
115
+ }
116
+ function configKey(c) {
117
+ return JSON.stringify([
118
+ c.agent_model,
119
+ c.agent_effort ?? null,
120
+ c.judge_model,
121
+ c.judge_effort ?? null,
122
+ c.trials ?? 1,
123
+ c.agent_access ?? "offline",
124
+ c.isolated ?? false
125
+ ]);
126
+ }
127
+ const effortSuffix = (e) => e ? `@${e}` : "";
128
+ function describeConfig(c) {
129
+ return `agent ${c.agent_model}${effortSuffix(c.agent_effort)}, judge ${c.judge_model}${effortSuffix(c.judge_effort)}, trials ${c.trials ?? 1}, ${c.agent_access ?? "offline"}, ${c.isolated ? "isolated" : "host"}`;
130
+ }
131
+ function assertUniformConfig(entries, allowMixed) {
132
+ if (allowMixed) return;
133
+ const byHarness = /* @__PURE__ */ new Map();
134
+ for (const e of entries) {
135
+ const configs = byHarness.get(e.harness) ?? /* @__PURE__ */ new Map();
136
+ configs.set(configKey(e), e);
137
+ byHarness.set(e.harness, configs);
138
+ }
139
+ for (const [harness, configs] of byHarness) if (configs.size > 1) throw new Error(`${harness} results span multiple run configurations (${[...configs.values()].map(describeConfig).join("; ")}); rerun them to match or pass --allow-mixed`);
140
+ }
141
+ function ensureEvalPackages(opts) {
142
+ const missing = requiredEvalPackages(opts, Boolean(process.env.ANTHROPIC_API_KEY)).filter((pkg) => resolvePackageDir(pkg) === void 0);
143
+ if (missing.length === 0) return;
144
+ const peers = JSON.parse(fs.readFileSync(path.join(packageDir, "package.json"), "utf8")).peerDependencies ?? {};
145
+ const specs = missing.map((pkg) => `"${pkg}@${peers[pkg] ?? "latest"}"`).join(" ");
146
+ console.error([
147
+ `missing eval package(s): ${missing.join(", ")}`,
148
+ "",
149
+ "The eval engine is an optional peer so `skillcheck lint` installs stay",
150
+ "small. Evals are operator-run; install the peers next to @uinaf/agent-plugin-stuff:",
151
+ "",
152
+ ` pnpm add -D ${specs}`
153
+ ].join("\n"));
154
+ process.exit(2);
155
+ }
156
+ function promptfooEntry() {
157
+ const dir = resolvePackageDir("promptfoo");
158
+ if (dir === void 0) throw new Error("promptfoo is not installed");
159
+ const bin = JSON.parse(fs.readFileSync(path.join(dir, "package.json"), "utf8")).bin;
160
+ const rel = typeof bin === "string" ? bin : bin?.promptfoo;
161
+ if (typeof rel !== "string") throw new Error(`promptfoo at ${dir} declares no bin`);
162
+ return path.join(dir, rel);
163
+ }
164
+ const GRADED_REASONS = /* @__PURE__ */ new Set([0, 1]);
165
+ const ERRORED_REASON = 2;
166
+ function classifyResult(raw, expectedTrials) {
167
+ const root = raw;
168
+ const rows = root?.results?.results;
169
+ if (!Array.isArray(rows) || rows.length === 0) return { error: "promptfoo output carried no result" };
170
+ if (expectedTrials !== void 0 && rows.length !== expectedTrials) return { error: `promptfoo returned ${rows.length} of ${expectedTrials} trials` };
171
+ const stats = rows.length === 1 ? root?.results?.stats ?? void 0 : void 0;
172
+ const trials = [];
173
+ for (const [i, row] of rows.entries()) {
174
+ const verdict = classifyRow(row, stats);
175
+ if ("error" in verdict) return { error: rows.length === 1 ? verdict.error : `trial ${i + 1}: ${verdict.error}` };
176
+ trials.push(verdict);
177
+ }
178
+ return { trials };
179
+ }
180
+ function classifyRow(raw, stats) {
181
+ const res = raw;
182
+ if (res === void 0 || res === null) return { error: "promptfoo output carried no result" };
183
+ const message = typeof res.error === "string" ? res.error.trim() : "";
184
+ if (res.failureReason === ERRORED_REASON) return { error: message || "promptfoo reported an errored test" };
185
+ const graded = GRADED_REASONS.has(res.failureReason) || stats !== void 0 && (stats.errors ?? 0) === 0 && ((stats.failures ?? 0) > 0 || (stats.successes ?? 0) > 0);
186
+ if (message !== "" && !graded) return { error: message };
187
+ if (!graded && stats !== void 0 && (stats.errors ?? 0) > 0 && (stats.successes ?? 0) === 0 && (stats.failures ?? 0) === 0) return { error: "promptfoo reported an errored test with nothing graded" };
188
+ if (typeof res.score !== "number" || typeof res.success !== "boolean") return { error: "promptfoo result carried no usable score" };
189
+ const components = Array.isArray(res.gradingResult?.componentResults) ? res.gradingResult.componentResults : [];
190
+ const checklist = components.find((c) => c?.metadata?.assertionSet?.type === "assert-set");
191
+ const skillUsed = components.find((c) => c?.assertion?.type === "skill-used" || c?.assertion?.metric === "skill-used");
192
+ if (typeof checklist?.score !== "number" || typeof skillUsed?.score !== "number") return { error: "promptfoo result carried no checklist or skill-used verdict" };
193
+ const judgeError = (Array.isArray(checklist.componentResults) ? checklist.componentResults : []).find((c) => c?.metadata?.graderError === true);
194
+ if (judgeError) {
195
+ const reason = typeof judgeError.reason === "string" ? judgeError.reason.trim() : "";
196
+ return { error: `judge call failed${reason ? `: ${reason.slice(0, 300)}` : ""}` };
197
+ }
198
+ return {
199
+ score: checklist.score,
200
+ pass: res.success,
201
+ skillUsed: skillUsed.score >= 1
202
+ };
203
+ }
204
+ const NOISY_SPREAD = .2;
205
+ const round4 = (n) => Math.round(n * 1e4) / 1e4;
206
+ function aggregateTrials(trials) {
207
+ if (trials.length === 0) throw new Error("cannot aggregate zero trials");
208
+ const scores = trials.map((t) => t.score);
209
+ const passes = trials.filter((t) => t.pass).length;
210
+ const min = Math.min(...scores);
211
+ const spread = Math.max(...scores) - min;
212
+ const skillUsed = trials.filter((t) => t.skillUsed).length;
213
+ return {
214
+ trials: trials.length,
215
+ pass: passes === trials.length,
216
+ passes,
217
+ pass_rate: round4(passes / trials.length),
218
+ score: round4(scores.reduce((a, b) => a + b, 0) / trials.length),
219
+ score_min: round4(min),
220
+ score_spread: round4(spread),
221
+ skill_used: skillUsed,
222
+ skill_used_rate: round4(skillUsed / trials.length),
223
+ noisy: passes > 0 && passes < trials.length || spread >= .199999999
224
+ };
225
+ }
226
+ function formatStats(s) {
227
+ const line = `score=${s.score.toFixed(4)}`;
228
+ if (s.trials === 1) return line;
229
+ return [
230
+ line,
231
+ `min=${s.score_min.toFixed(4)}`,
232
+ `spread=${s.score_spread.toFixed(4)}`,
233
+ `pass^${s.trials}=${s.pass ? "yes" : "no"}`,
234
+ `passes=${s.passes}/${s.trials}`,
235
+ `skill-used=${s.skill_used}/${s.trials}`,
236
+ ...s.noisy ? ["NOISY"] : []
237
+ ].join(" ");
238
+ }
239
+ function gitHead(root) {
240
+ return execFileSync("git", ["rev-parse", "HEAD"], {
241
+ cwd: root,
242
+ encoding: "utf8"
243
+ }).trim();
244
+ }
245
+ function metaPath(resultPath) {
246
+ return resultPath.replace(/\.json$/, ".meta.json");
247
+ }
248
+ function attemptPath(resultPath) {
249
+ return `${resultPath}.attempt`;
250
+ }
251
+ function ensurePrivateDir(dir) {
252
+ fs.mkdirSync(dir, {
253
+ recursive: true,
254
+ mode: 448
255
+ });
256
+ const st = fs.lstatSync(dir);
257
+ const uid = process.getuid?.();
258
+ if (!st.isDirectory() || uid !== void 0 && st.uid !== uid) throw new Error(`scratch dir ${dir} is not a directory owned by this user`);
259
+ if ((st.mode & 63) !== 0) fs.chmodSync(dir, 448);
260
+ }
261
+ function runScenario(scenarioDir, opts, root) {
262
+ const dirs = stateDirs(root);
263
+ ensurePrivateDir(dirs.scratch);
264
+ const { name, configPath, skill, scenario } = generateRun(path.resolve(scenarioDir), opts, {
265
+ scratchDir: dirs.scratch,
266
+ transformPath: path.join(here, `transform${selfExt}`),
267
+ grokProviderPath: path.join(here, `grok-provider${selfExt}`),
268
+ skillEvidencePath: path.join(here, `skill-evidence${selfExt}`)
269
+ });
270
+ fs.mkdirSync(dirs.results, { recursive: true });
271
+ const resultPath = path.join(dirs.results, `${name}.json`);
272
+ const identity = {
273
+ skill,
274
+ scenario,
275
+ harness: opts.harness,
276
+ variant: opts.control ? "control" : "skill"
277
+ };
278
+ fs.writeFileSync(attemptPath(resultPath), JSON.stringify(identity) + "\n");
279
+ fs.rmSync(resultPath, { force: true });
280
+ fs.rmSync(metaPath(resultPath), { force: true });
281
+ const sha = gitHead(root);
282
+ const rc = spawnSync(process.execPath, [
283
+ promptfooEntry(),
284
+ "eval",
285
+ "--no-cache",
286
+ "--no-progress-bar",
287
+ "-j",
288
+ process.env.EVALS_CONCURRENCY ?? "4",
289
+ "-c",
290
+ configPath,
291
+ "-o",
292
+ resultPath
293
+ ], {
294
+ cwd: packageDir,
295
+ stdio: "inherit",
296
+ env: {
297
+ ...process.env,
298
+ PROMPTFOO_FAILED_TEST_EXIT_CODE: "0"
299
+ }
300
+ }).status ?? 1;
301
+ const outcome = {
302
+ name,
303
+ rc,
304
+ resultPath
305
+ };
306
+ if (rc !== 0) return outcome;
307
+ let verdict;
308
+ try {
309
+ verdict = classifyResult(JSON.parse(fs.readFileSync(resultPath, "utf8")), opts.trials ?? 1);
310
+ } catch {
311
+ verdict = { error: "promptfoo produced no parseable result file" };
312
+ }
313
+ if ("error" in verdict) return {
314
+ ...outcome,
315
+ error: verdict.error
316
+ };
317
+ outcome.stats = aggregateTrials(verdict.trials);
318
+ fs.writeFileSync(metaPath(resultPath), JSON.stringify({
319
+ skills_tree_sha: sha,
320
+ ...identity,
321
+ ...runConfigOf(opts),
322
+ aggregate: outcome.stats,
323
+ ran_at: (/* @__PURE__ */ new Date()).toISOString(),
324
+ tool_version: toolVersion()
325
+ }, null, 2) + "\n");
326
+ fs.rmSync(attemptPath(resultPath), { force: true });
327
+ return outcome;
328
+ }
329
+ function judgeName(judge) {
330
+ if (typeof judge === "string") return judge.replace(/^anthropic:messages:/, "");
331
+ const j = judge;
332
+ const name = j?.config?.model ?? j?.id;
333
+ if (typeof name !== "string") return "unknown";
334
+ return j?.config?.effort === void 0 ? name : name.replace(/^anthropic:messages:/, "");
335
+ }
336
+ function resultRunConfig(raw, meta, harness) {
337
+ const m = meta;
338
+ if (typeof m?.agent_model === "string" && typeof m.judge_model === "string") return {
339
+ agent_model: m.agent_model,
340
+ agent_effort: m.agent_effort ?? null,
341
+ judge_model: m.judge_model,
342
+ judge_effort: m.judge_effort ?? null,
343
+ trials: m.trials ?? 1,
344
+ agent_access: m.agent_access === "online" ? "online" : "offline",
345
+ isolated: m.isolated === true
346
+ };
347
+ const r = raw;
348
+ const agent = r?.config?.providers?.[0]?.config;
349
+ const judge = r?.config?.defaultTest?.options?.provider;
350
+ const judgeConfig = judge?.config;
351
+ const judgeEffort = judgeConfig?.reasoning_effort ?? judgeConfig?.effort;
352
+ return {
353
+ agent_model: typeof agent?.model === "string" ? agent.model : `${harness}-default`,
354
+ agent_effort: typeof agent?.effort === "string" ? agent.effort : null,
355
+ judge_model: judgeName(judge),
356
+ judge_effort: typeof judgeEffort === "string" ? judgeEffort : null,
357
+ trials: r?.results?.results?.length ?? 1,
358
+ agent_access: "offline",
359
+ isolated: false
360
+ };
361
+ }
362
+ function readJson(file) {
363
+ try {
364
+ return JSON.parse(fs.readFileSync(file, "utf8"));
365
+ } catch {
366
+ return;
367
+ }
368
+ }
369
+ function liveScenarios(root) {
370
+ const cli = path.join(root, "cli");
371
+ if (!(fs.existsSync(path.join(root, "skills")) || fs.existsSync(cli) && fs.readdirSync(cli).some((d) => fs.existsSync(path.join(cli, d, "skills"))))) return;
372
+ return new Set(discoverScenarios(root).map((dir) => {
373
+ const parts = dir.split(path.sep);
374
+ return `${parts.at(-3)}\0${parts.at(-1)}`;
375
+ }));
376
+ }
377
+ function isLive(live, e) {
378
+ return live === void 0 || live.has(`${e.skill}\0${e.scenario}`);
379
+ }
380
+ function discoverScenarios(root) {
381
+ const roots = [path.join(root, "skills")];
382
+ const cliDir = path.join(root, "cli");
383
+ if (fs.existsSync(cliDir)) {
384
+ for (const e of fs.readdirSync(cliDir, { withFileTypes: true })) if (e.isDirectory()) roots.push(path.join(cliDir, e.name, "skills"));
385
+ }
386
+ const found = [];
387
+ for (const dir of roots) {
388
+ if (!fs.existsSync(dir)) continue;
389
+ for (const skill of fs.readdirSync(dir, { withFileTypes: true })) {
390
+ const evalsDir = path.join(dir, skill.name, "evals");
391
+ if (!skill.isDirectory() || !fs.existsSync(evalsDir)) continue;
392
+ for (const sc of fs.readdirSync(evalsDir, { withFileTypes: true })) {
393
+ const scenarioDir = path.join(evalsDir, sc.name);
394
+ if (sc.isDirectory() && fs.existsSync(path.join(scenarioDir, "task.md")) && fs.existsSync(path.join(scenarioDir, "criteria.json"))) found.push(scenarioDir);
395
+ }
396
+ }
397
+ }
398
+ return found.sort();
399
+ }
400
+ const RUN_FLAGS = "[--root DIR] [--harness claude|codex|grok] [--agent MODEL] [--agent-effort EFFORT] [--judge MODEL] [--judge-effort EFFORT] [--trials K] [--max-turns N] [--control]";
401
+ function warnHostRun() {
402
+ if (isIsolated()) return;
403
+ console.error("warning: host run; the agent can read this machine's installed skills, plugins, and files, so scores are not isolated. Run in the isolated image: docs/usage.md#isolated-runs");
404
+ }
405
+ function cmdRun(argv) {
406
+ const { positional, flags } = parseArgs(argv);
407
+ if (positional.length !== 1) fail(`usage: skillcheck run <scenario-dir> ${RUN_FLAGS}`);
408
+ const opts = runOptions(flags);
409
+ ensureEvalPackages(opts);
410
+ warnHostRun();
411
+ const o = runScenario(positional[0], opts, resolveRoot(flags));
412
+ if (o.stats === void 0) {
413
+ console.error(`ERROR ${o.name}: ${o.error ?? "no usable result"} (promptfoo rc=${o.rc})`);
414
+ process.exit(2);
415
+ }
416
+ console.log(`${o.stats.pass ? "PASS" : "FAIL"} ${o.name} ${formatStats(o.stats)} (results: ${o.resultPath})`);
417
+ process.exit(o.stats.pass ? 0 : 1);
418
+ }
419
+ function cmdSweep(argv) {
420
+ const { positional, flags } = parseArgs(argv);
421
+ if (positional.length > 0) fail(`usage: skillcheck sweep ${RUN_FLAGS} [--all]`);
422
+ const root = resolveRoot(flags);
423
+ const opts = runOptions(flags);
424
+ ensureEvalPackages(opts);
425
+ warnHostRun();
426
+ const all = flags.get("--all") === true;
427
+ const resultsDir = stateDirs(root).results;
428
+ const wanted = configKey(runConfigOf(opts));
429
+ let passed = 0, failed = 0, errored = 0, skipped = 0;
430
+ for (const dir of discoverScenarios(root)) {
431
+ const name = runNameFor(dir, opts.harness, opts.control);
432
+ const resultPath = path.join(resultsDir, `${name}.json`);
433
+ if (!all && fs.existsSync(resultPath) && !fs.existsSync(attemptPath(resultPath))) {
434
+ const raw = readJson(resultPath);
435
+ const config = resultRunConfig(raw, readJson(metaPath(resultPath)), opts.harness);
436
+ const graded = !("error" in classifyResult(raw, config.trials));
437
+ if (graded && configKey(config) === wanted) {
438
+ skipped++;
439
+ console.log(`SKIP ${name} (results exist; use --all to rerun)`);
440
+ continue;
441
+ }
442
+ if (graded) console.log(`RERUN ${name} (results used ${describeConfig(config)})`);
443
+ }
444
+ const o = runScenario(dir, opts, root);
445
+ if (o.stats === void 0) {
446
+ errored++;
447
+ console.log(`ERROR ${o.name} ${o.error ?? "no usable result"} (promptfoo rc=${o.rc})`);
448
+ } else if (o.stats.pass) {
449
+ passed++;
450
+ console.log(`PASS ${o.name} ${formatStats(o.stats)}`);
451
+ } else {
452
+ failed++;
453
+ console.log(`FAIL ${o.name} ${formatStats(o.stats)}`);
454
+ }
455
+ }
456
+ console.log(`\nsweep: ${passed} passed, ${failed} failed, ${errored} errored, ${skipped} skipped`);
457
+ process.exit(errored > 0 ? 2 : failed > 0 ? 1 : 0);
458
+ }
459
+ const decodePart = (part) => {
460
+ if (!part.startsWith("~v2~")) return part;
461
+ try {
462
+ const decoded = decodeURIComponent(part.slice(4));
463
+ return encodeRunNamePart(decoded) === part ? decoded : part;
464
+ } catch {
465
+ return part;
466
+ }
467
+ };
468
+ function resultIdentity(file, dir) {
469
+ const base = file.replace(/\.json$/, "");
470
+ for (const sidecar of [`${base}.meta.json`, `${file}.attempt`]) {
471
+ const identity = readJson(path.join(dir, sidecar));
472
+ if (identity !== null && typeof identity === "object" && "skill" in identity && typeof identity.skill === "string" && "scenario" in identity && typeof identity.scenario === "string" && "harness" in identity && (identity.harness === "claude" || identity.harness === "codex" || identity.harness === "grok")) return {
473
+ skill: identity.skill,
474
+ scenario: identity.scenario,
475
+ harness: identity.harness,
476
+ variant: "variant" in identity && identity.variant === "control" ? "control" : "skill"
477
+ };
478
+ }
479
+ if (/^~v3~[0-9a-f]{64}$/.test(base)) throw new Error(`missing identity metadata for ${file}`);
480
+ const unsuffixed = base.replace(/--control$/, "");
481
+ const variant = unsuffixed !== base && unsuffixed.includes("--") ? "control" : "skill";
482
+ const stem = variant === "control" ? unsuffixed : base;
483
+ const suffix = stem.match(/--(codex|grok|cursor)$/);
484
+ const harness = suffix === null ? "claude" : suffix[1];
485
+ const [skill, ...rest] = stem.replace(/--(codex|grok|cursor)$/, "").split("--");
486
+ return {
487
+ skill: decodePart(skill),
488
+ scenario: decodePart(rest.join("--")),
489
+ harness,
490
+ variant
491
+ };
492
+ }
493
+ function reduceResults(dir, allowMixed, live) {
494
+ const entries = [];
495
+ const skipped = [];
496
+ const retired = /* @__PURE__ */ new Set();
497
+ const gradedAt = /* @__PURE__ */ new Map();
498
+ const shas = /* @__PURE__ */ new Set();
499
+ const files = fs.readdirSync(dir);
500
+ const incomplete = new Set(files.filter((f) => f.endsWith(".json.attempt")).map((f) => f.replace(/\.attempt$/, "")));
501
+ const results = files.filter((f) => f.endsWith(".json") && !f.endsWith(".meta.json"));
502
+ for (const f of [.../* @__PURE__ */ new Set([...results, ...incomplete])].sort()) {
503
+ let identity;
504
+ try {
505
+ identity = resultIdentity(f, dir);
506
+ } catch {
507
+ identity = void 0;
508
+ }
509
+ if (identity !== void 0 && identity.scenario !== "" && !isLive(live, identity)) {
510
+ retired.add(entryKey(identity));
511
+ continue;
512
+ }
513
+ if (f.endsWith("--cursor.json")) {
514
+ console.error(`skipping ${f}: Cursor harness is retired`);
515
+ skipped.push(f);
516
+ continue;
517
+ }
518
+ if (incomplete.has(f)) {
519
+ console.error(`skipping ${f}: attempt did not complete with a graded result`);
520
+ skipped.push(f);
521
+ continue;
522
+ }
523
+ const raw = readJson(path.join(dir, f));
524
+ const base = f.replace(/\.json$/, "");
525
+ const meta = readJson(path.join(dir, `${base}.meta.json`));
526
+ const { skill, scenario, harness, variant } = resultIdentity(f, dir);
527
+ const config = resultRunConfig(raw, meta, harness);
528
+ const verdict = classifyResult(raw, config.trials);
529
+ if ("error" in verdict) {
530
+ console.error(`skipping ${f}: ${verdict.error}`);
531
+ skipped.push(f);
532
+ continue;
533
+ }
534
+ const rows = raw.results.results;
535
+ const key = entryKey({
536
+ skill,
537
+ scenario,
538
+ harness,
539
+ variant
540
+ });
541
+ gradedAt.set(key, Math.max(gradedAt.get(key) ?? 0, fs.statSync(path.join(dir, f)).mtimeMs));
542
+ const sha = typeof meta?.skills_tree_sha === "string" ? meta.skills_tree_sha : "unattested";
543
+ shas.add(sha);
544
+ const stats = aggregateTrials(verdict.trials);
545
+ entries.push({
546
+ skill,
547
+ scenario,
548
+ harness,
549
+ variant,
550
+ skills_tree_sha: sha,
551
+ ...stats,
552
+ ...config,
553
+ latency_ms: Math.round(rows.reduce((a, r) => a + (r.latencyMs ?? 0), 0) / rows.length),
554
+ tokens: rows.reduce((a, r) => a + (r.tokenUsage?.total ?? 0) + (r.tokenUsage?.assertions?.total ?? 0), 0)
555
+ });
556
+ }
557
+ if (shas.size > 1 && !allowMixed) throw new Error(`results span multiple skills-tree revisions (${[...shas].join(", ")}); rerun stale ones or pass --allow-mixed`);
558
+ return {
559
+ treeSha: shas.size === 1 ? [...shas][0] : shas.size === 0 ? "none" : "mixed",
560
+ entries,
561
+ skipped,
562
+ gradedAt,
563
+ retired
564
+ };
565
+ }
566
+ function entryKey(e) {
567
+ return [
568
+ e.skill,
569
+ e.scenario,
570
+ e.harness,
571
+ e.variant ?? "skill"
572
+ ].join("\0");
573
+ }
574
+ function mergeScorecard(existing, fresh) {
575
+ const byKey = /* @__PURE__ */ new Map();
576
+ for (const e of existing) byKey.set(entryKey(e), e);
577
+ let carried = byKey.size;
578
+ for (const e of fresh) {
579
+ if (byKey.has(entryKey(e))) carried--;
580
+ byKey.set(entryKey(e), e);
581
+ }
582
+ return {
583
+ entries: [...byKey.values()].sort((a, b) => entryKey(a) < entryKey(b) ? -1 : entryKey(a) > entryKey(b) ? 1 : 0),
584
+ carried
585
+ };
586
+ }
587
+ function treeShaOf(entries) {
588
+ const shas = new Set(entries.map((e) => e.skills_tree_sha));
589
+ return shas.size === 1 ? [...shas][0] : shas.size === 0 ? "none" : "mixed";
590
+ }
591
+ function readExistingScorecard(out) {
592
+ if (!fs.existsSync(out)) return [];
593
+ let prev;
594
+ try {
595
+ prev = JSON.parse(fs.readFileSync(out, "utf8"));
596
+ } catch {
597
+ throw new Error(`existing scorecard ${out} is not valid JSON; refusing to overwrite it`);
598
+ }
599
+ const scenarios = prev?.scenarios;
600
+ if (!Array.isArray(scenarios)) throw new Error(`existing scorecard ${out} has no scenarios array; refusing to overwrite it`);
601
+ return scenarios;
602
+ }
603
+ function cmdSummarize(argv) {
604
+ const { positional, flags } = parseArgs(argv);
605
+ if (positional.length > 0) fail("usage: skillcheck summarize [--root DIR] [--allow-mixed]");
606
+ const root = resolveRoot(flags);
607
+ const dirs = stateDirs(root);
608
+ if (!fs.existsSync(dirs.results)) fail(`no results directory at ${dirs.results}; run some evals first`);
609
+ const live = liveScenarios(root);
610
+ const { entries, skipped, gradedAt, retired: retiredResults } = reduceResults(dirs.results, flags.get("--allow-mixed") === true, live);
611
+ fs.mkdirSync(dirs.scorecards, { recursive: true });
612
+ const out = path.join(dirs.scorecards, `${(/* @__PURE__ */ new Date()).toISOString().slice(0, 10)}.json`);
613
+ const previous = readExistingScorecard(out);
614
+ const existing = previous.filter((e) => isLive(live, e));
615
+ for (const e of previous) if (!isLive(live, e)) retiredResults.add(entryKey(e));
616
+ const retired = retiredResults.size;
617
+ const skippedKeys = new Set(skipped.map((file) => ({
618
+ key: entryKey(resultIdentity(file, dirs.results)),
619
+ modifiedAt: fs.statSync(fs.existsSync(path.join(dirs.results, `${file}.attempt`)) ? path.join(dirs.results, `${file}.attempt`) : path.join(dirs.results, file)).mtimeMs
620
+ })).filter(({ key, modifiedAt }) => (gradedAt.get(key) ?? 0) <= modifiedAt).map(({ key }) => key));
621
+ if (existing.some((entry) => skippedKeys.has(entryKey(entry)))) throw new Error("skipped rerun matches an existing score; refusing to carry it or overwrite the scorecard");
622
+ const merged = mergeScorecard(existing, entries);
623
+ const treeSha = treeShaOf(merged.entries);
624
+ const allowMixed = flags.get("--allow-mixed") === true;
625
+ if (treeSha === "mixed" && !allowMixed) throw new Error("scorecard spans multiple skills-tree revisions; rerun stale ones or pass --allow-mixed");
626
+ assertUniformConfig(merged.entries, allowMixed);
627
+ const scorecard = {
628
+ ran_at: (/* @__PURE__ */ new Date()).toISOString(),
629
+ skills_tree_sha: treeSha,
630
+ scenarios: merged.entries
631
+ };
632
+ fs.writeFileSync(out, JSON.stringify(scorecard, null, 2) + "\n");
633
+ if (retired > 0) console.log(`dropped ${retired} row(s) for scenarios no longer in the tree`);
634
+ const scenarios = merged.entries.filter((e) => e.variant !== "control");
635
+ console.log(`${out}: ${scenarios.length} scenario(s), ${scenarios.filter((e) => e.pass).length} passing, ${merged.entries.length - scenarios.length} control(s), ${skipped.length} skipped file(s)`);
636
+ if (existing.length > 0) console.log(`merged into today's scorecard: ${entries.length} from this run, ${merged.carried} carried over`);
637
+ console.log(`\n${formatSkillTable(summarizeSkills(merged.entries))}`);
638
+ for (const e of merged.entries.filter((x) => x.noisy)) {
639
+ const tag = e.variant === "control" ? ", control" : "";
640
+ console.log(`NOISY ${e.skill}/${e.scenario} (${e.harness}${tag}) ${formatStats(e)}`);
641
+ }
642
+ for (const s of summarizeSkills(merged.entries)) for (const scenario of s.no_lift) console.log(`NO LIFT ${s.skill}/${scenario} (${s.harness}): passes without the skill`);
643
+ }
644
+ const mean4 = (xs) => round4(xs.reduce((a, b) => a + b, 0) / xs.length);
645
+ function summarizeSkills(entries) {
646
+ const groups = /* @__PURE__ */ new Map();
647
+ const controls = /* @__PURE__ */ new Map();
648
+ for (const e of entries) {
649
+ const key = `${e.skill}\0${e.harness}`;
650
+ if (e.variant === "control") controls.set(`${key}\0${e.scenario}`, e);
651
+ else groups.set(key, [...groups.get(key) ?? [], e]);
652
+ }
653
+ return [...groups.entries()].map(([key, rows]) => {
654
+ const paired = rows.flatMap((r) => {
655
+ const c = controls.get(`${key}\0${r.scenario}`);
656
+ return c === void 0 ? [] : [{
657
+ skill: r,
658
+ control: c
659
+ }];
660
+ });
661
+ const controlScore = paired.length === 0 ? null : mean4(paired.map((p) => p.control.score));
662
+ return {
663
+ skill: rows[0].skill,
664
+ harness: rows[0].harness,
665
+ scenarios: rows.length,
666
+ pass_all: rows.filter((r) => r.pass).length,
667
+ pass_rate: mean4(rows.map((r) => r.pass_rate ?? (r.pass ? 1 : 0))),
668
+ score: mean4(rows.map((r) => r.score)),
669
+ noisy: rows.filter((r) => r.noisy).map((r) => r.scenario),
670
+ control_score: controlScore,
671
+ lift: controlScore === null ? null : round4(mean4(paired.map((p) => p.skill.score)) - controlScore),
672
+ no_lift: paired.filter((p) => p.control.pass).map((p) => p.skill.scenario)
673
+ };
674
+ });
675
+ }
676
+ function formatSkillTable(rows) {
677
+ const table = [[
678
+ "skill",
679
+ "harness",
680
+ "scenarios",
681
+ "pass^k",
682
+ "pass rate",
683
+ "score",
684
+ "noisy",
685
+ "control",
686
+ "lift"
687
+ ], ...rows.map((r) => [
688
+ r.skill,
689
+ r.harness,
690
+ String(r.scenarios),
691
+ `${r.pass_all}/${r.scenarios}`,
692
+ r.pass_rate.toFixed(2),
693
+ r.score.toFixed(2),
694
+ String(r.noisy.length),
695
+ r.control_score === null ? "-" : r.control_score.toFixed(2),
696
+ r.lift === null ? "-" : `${r.lift >= 0 ? "+" : ""}${r.lift.toFixed(2)}`
697
+ ])];
698
+ const widths = table[0].map((_, i) => Math.max(...table.map((row) => row[i].length)));
699
+ return table.map((row) => row.map((c, i) => c.padEnd(widths[i])).join(" ").trimEnd()).join("\n");
700
+ }
701
+ function cmdLint(argv) {
702
+ const { positional, flags } = parseArgs(argv);
703
+ if (positional.length > 1) fail("usage: skillcheck lint [<root>] [--root DIR]");
704
+ const root = positional.length === 1 ? path.resolve(positional[0]) : resolveRoot(flags);
705
+ const { errors, count } = lintSkills(root);
706
+ if (errors.length > 0) {
707
+ for (const e of errors) console.error(e);
708
+ console.error(`skill lint: ${errors.length} error(s) across ${count} package(s)`);
709
+ process.exit(1);
710
+ }
711
+ console.log(`skill lint: ${count} package(s) clean`);
712
+ }
713
+ function isMainModule() {
714
+ const entry = process.argv[1];
715
+ if (entry === void 0) return false;
716
+ try {
717
+ return fs.realpathSync(entry) === fs.realpathSync(import.meta.filename);
718
+ } catch {
719
+ return false;
720
+ }
721
+ }
722
+ if (isMainModule()) {
723
+ const [cmd, ...rest] = process.argv.slice(2);
724
+ try {
725
+ if (cmd === "run") cmdRun(rest);
726
+ else if (cmd === "sweep") cmdSweep(rest);
727
+ else if (cmd === "summarize") cmdSummarize(rest);
728
+ else if (cmd === "lint") cmdLint(rest);
729
+ else fail("usage: skillcheck <lint|run|sweep|summarize> ...");
730
+ } catch (error) {
731
+ fail(error instanceof Error ? error.message : String(error));
732
+ }
733
+ }
734
+ export { NOISY_SPREAD, aggregateTrials, assertUniformConfig, classifyResult, ensurePrivateDir, formatStats, liveScenarios, mergeScorecard, parseArgs, parsePositiveInt, reduceResults, resolveRoot, resultRunConfig, runConfigOf, runOptions, stateDirs, summarizeSkills, toolVersion, treeShaOf };