@plune-ai/cli 0.39.10 → 0.39.12

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.cjs CHANGED
@@ -299,13 +299,13 @@ function reportOutputs(flags2, cwd = process.cwd(), extra = {}) {
299
299
  named2[1] ?? "",
300
300
  extra.sarif === true ? [...FILE_FORMATS, "sarif"] : FILE_FORMATS
301
301
  );
302
- const path25 = named2 === null ? raw : named2[2] ?? "";
303
- if (path25 === "") throw new UsageError(`--out ${raw}: the file name is missing.`);
304
- return { format: fileFormat, path: path25, raw };
302
+ const path26 = named2 === null ? raw : named2[2] ?? "";
303
+ if (path26 === "") throw new UsageError(`--out ${raw}: the file name is missing.`);
304
+ return { format: fileFormat, path: path26, raw };
305
305
  });
306
306
  const seen = /* @__PURE__ */ new Map();
307
- for (const { path: path25, raw } of files) {
308
- const full2 = (0, import_node_path2.resolve)(cwd, path25);
307
+ for (const { path: path26, raw } of files) {
308
+ const full2 = (0, import_node_path2.resolve)(cwd, path26);
309
309
  const key = process.platform === "win32" ? full2.toLowerCase() : full2;
310
310
  const first = seen.get(key);
311
311
  if (first !== void 0) throw new UsageError(`--out ${raw}: the same file as --out ${first}.`);
@@ -313,9 +313,9 @@ function reportOutputs(flags2, cwd = process.cwd(), extra = {}) {
313
313
  if ((0, import_node_fs.statSync)(full2, { throwIfNoEntry: false })?.isDirectory() === true)
314
314
  throw new UsageError(`--out ${raw}: a folder, not a file.`);
315
315
  if ((0, import_node_fs.statSync)((0, import_node_path2.dirname)(full2), { throwIfNoEntry: false })?.isDirectory() !== true)
316
- throw new UsageError(`--out ${raw}: the folder ${(0, import_node_path2.dirname)(path25)} does not exist.`);
316
+ throw new UsageError(`--out ${raw}: the folder ${(0, import_node_path2.dirname)(path26)} does not exist.`);
317
317
  }
318
- return { format, files: files.map(({ format: f, path: path25 }) => ({ format: f, path: path25 })) };
318
+ return { format, files: files.map(({ format: f, path: path26 }) => ({ format: f, path: path26 })) };
319
319
  }
320
320
  var import_node_fs, import_node_path2, STDOUT_FORMATS, FILE_FORMATS, REPORTERS, collect2;
321
321
  var init_options2 = __esm({
@@ -653,11 +653,11 @@ var init_schema = __esm({
653
653
  config.evals.forEach((evalConfig, i) => {
654
654
  const server2 = evalConfig.mcp?.server;
655
655
  if (server2 === void 0) {
656
- const misplaced = (assertions, path25) => assertions.forEach((a, j) => {
656
+ const misplaced = (assertions, path26) => assertions.forEach((a, j) => {
657
657
  if (TOOL_CALL_TYPES.has(a.type))
658
658
  ctx.addIssue({
659
659
  code: "custom",
660
- path: [...path25, j, "type"],
660
+ path: [...path26, j, "type"],
661
661
  message: `"${a.type}" reads the tool calls of an eval with mcp, and eval "${evalConfig.id}" has no mcp block`
662
662
  });
663
663
  });
@@ -913,10 +913,18 @@ var init_loader = __esm({
913
913
  // src/config/model-matrix.ts
914
914
  function selfJudgeWarnings(config) {
915
915
  if ((config.providers?.length ?? 0) < 2) return [];
916
- const inherited = (config.defaults?.assertions ?? []).some((a) => a.type === "llm-judge" && a.provider === void 0);
917
- return config.evals.filter((ev) => inherited || ev.assertions.some((a) => a.type === "llm-judge" && a.provider === void 0)).map(
918
- (ev) => `eval "${ev.id}" has an llm-judge check without a provider: with several models each model judges its own answer, which favours it. Set provider on the check to name one judge for all`
919
- );
916
+ const follows = (a) => a.type === "llm-judge" && a.provider?.model === void 0;
917
+ const mixed = new Set(config.providers.map((p) => p.type)).size > 1;
918
+ const typeless = (a) => mixed && a.type === "llm-judge" && a.provider?.model !== void 0 && a.provider.type === void 0;
919
+ const any = (pred) => (ev) => (config.defaults?.assertions ?? []).some(pred) || ev.assertions.some(pred);
920
+ return config.evals.flatMap((ev) => [
921
+ ...any(follows)(ev) ? [
922
+ `eval "${ev.id}" has an llm-judge check whose provider names no model: with several models each model judges its own answer, which favours it. Set provider.type and provider.model on the check to name one judge for all`
923
+ ] : [],
924
+ ...any(typeless)(ev) ? [
925
+ `eval "${ev.id}" has an llm-judge check whose provider names a model but no type: the models of this run are of several types, so each cell sends that model to its own provider. Set provider.type on the check too`
926
+ ] : []
927
+ ]);
920
928
  }
921
929
  var init_model_matrix = __esm({
922
930
  "src/config/model-matrix.ts"() {
@@ -1078,7 +1086,7 @@ var init_retry = __esm({
1078
1086
  "use strict";
1079
1087
  init_cjs_shims();
1080
1088
  init_errors2();
1081
- defaultSleep = (ms) => new Promise((resolve23) => setTimeout(resolve23, ms));
1089
+ defaultSleep = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
1082
1090
  }
1083
1091
  });
1084
1092
 
@@ -2240,12 +2248,16 @@ var init_judge_helpers = __esm({
2240
2248
  });
2241
2249
 
2242
2250
  // src/assertions/llm-judge.ts
2243
- function prompt(criteria, output) {
2244
- return `You are a strict evaluator. Score from 0 to 1 how well the OUTPUT meets the CRITERIA. Respond ONLY with JSON: {"score": <0..1>, "reason": "<short explanation>"}.
2251
+ function prompt(criteria, output, input) {
2252
+ const given = input === void 0 ? "" : "The OUTPUT is the answer to the INPUT; the CRITERIA are about the OUTPUT given that INPUT. ";
2253
+ return "You are a strict evaluator. Score from 0 to 1 how well the OUTPUT meets the CRITERIA. " + given + `Respond ONLY with JSON: {"score": <0..1>, "reason": "<short explanation>"}.
2245
2254
 
2246
2255
  CRITERIA: ${criteria}
2247
2256
 
2248
- OUTPUT:
2257
+ ` + (input === void 0 ? "" : `INPUT:
2258
+ ${input}
2259
+
2260
+ `) + `OUTPUT:
2249
2261
  ${output}`;
2250
2262
  }
2251
2263
  var DEFAULT_PASS_THRESHOLD, llmJudge;
@@ -2263,7 +2275,9 @@ var init_llm_judge = __esm({
2263
2275
  }
2264
2276
  const criteria = interpolate(ctx.params.criteria, ctx);
2265
2277
  const threshold = ctx.params.pass_threshold ?? DEFAULT_PASS_THRESHOLD;
2266
- const { score, reason } = parseScored(await askJson(ctx.judge, prompt(criteria, ctx.output)));
2278
+ const { score, reason } = parseScored(
2279
+ await askJson(ctx.judge, prompt(criteria, ctx.output, ctx.input))
2280
+ );
2267
2281
  const passed2 = score >= threshold;
2268
2282
  return {
2269
2283
  passed: passed2,
@@ -3108,20 +3122,20 @@ function noteValue(out, v, at2) {
3108
3122
  where3.add(at2);
3109
3123
  out.values.set(h, where3);
3110
3124
  }
3111
- function walk(value2, path25, depth, out) {
3125
+ function walk(value2, path26, depth, out) {
3112
3126
  if (depth > SCAN_DEPTH) return;
3113
3127
  if (typeof value2 === "string" && UUID.test(value2)) {
3114
- const at2 = cap(path25 === "" ? "(root)" : path25);
3128
+ const at2 = cap(path26 === "" ? "(root)" : path26);
3115
3129
  out.paths.add(at2);
3116
3130
  noteValue(out, value2, at2);
3117
3131
  }
3118
3132
  if (Array.isArray(value2)) {
3119
- for (const item of value2.slice(0, SCAN_ITEMS)) walk(item, `${path25}[]`, depth + 1, out);
3133
+ for (const item of value2.slice(0, SCAN_ITEMS)) walk(item, `${path26}[]`, depth + 1, out);
3120
3134
  return;
3121
3135
  }
3122
3136
  if (!isRecord3(value2)) return;
3123
3137
  for (const [key, v] of Object.entries(value2)) {
3124
- const at2 = cap(path25 === "" ? segment(key) : `${path25}.${segment(key)}`);
3138
+ const at2 = cap(path26 === "" ? segment(key) : `${path26}.${segment(key)}`);
3125
3139
  if (isIdKey(key) && (isScalar(v) || Array.isArray(v) && v.length > 0 && v.every(isScalar))) {
3126
3140
  out.paths.add(at2);
3127
3141
  for (const x of Array.isArray(v) ? v : [v]) noteValue(out, x, at2);
@@ -3299,7 +3313,7 @@ var init_friction = __esm({
3299
3313
  isRecord3 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
3300
3314
  isScalar = (v) => typeof v === "string" && v !== "" || typeof v === "number" && Number.isFinite(v);
3301
3315
  EMAIL = /@/;
3302
- cap = (path25) => path25.length > MAX_PATH ? path25.slice(0, MAX_PATH) : path25;
3316
+ cap = (path26) => path26.length > MAX_PATH ? path26.slice(0, MAX_PATH) : path26;
3303
3317
  hashOf = (v) => sha256(v).slice(0, 16);
3304
3318
  ID_MARK = "<id>";
3305
3319
  UUID_IN_TEXT = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/gi;
@@ -3644,6 +3658,7 @@ async function runAgentRow(p) {
3644
3658
  const { records, assertionError, judgeCost, judgeUnpriced, advice } = await assess(
3645
3659
  p,
3646
3660
  output,
3661
+ prompt5,
3647
3662
  agent
3648
3663
  );
3649
3664
  const covered = p.assertions.filter((x) => x.type === "no-repeated-call");
@@ -3735,18 +3750,35 @@ function costFields(c) {
3735
3750
  function dryRunRow(vars, usage3) {
3736
3751
  return { vars, output: null, cached: false, usage: usage3, inconclusive: "skipped", assertions: [] };
3737
3752
  }
3738
- async function assess(p, output, transcript) {
3753
+ async function assess(p, output, input, transcript) {
3739
3754
  let judgeCost = 0;
3740
3755
  let judgeUnpriced = false;
3741
- const judge2 = buildJudge(p.provider, p.providerConfig, (u) => {
3742
- const c = p.provider.estimateCost(u);
3743
- judgeCost += c.cost_usd;
3744
- if (c.priced === false) judgeUnpriced = true;
3745
- });
3746
3756
  const records = [];
3747
3757
  const advice = [];
3748
3758
  let assertionError;
3749
3759
  for (const assertion of p.assertions) {
3760
+ const own3 = assertion.type === "llm-judge" ? assertion.provider : void 0;
3761
+ const judgeCfg = own3 === void 0 ? p.providerConfig : { ...p.providerConfig, ...own3 };
3762
+ let judgedBy;
3763
+ const judge2 = () => {
3764
+ let provider = p.provider;
3765
+ if (own3 !== void 0) {
3766
+ if (p.resolveJudge === void 0)
3767
+ throw new Error("this run cannot build the judge named by the provider of an llm-judge check");
3768
+ provider = p.resolveJudge(judgeCfg);
3769
+ }
3770
+ const inner = buildJudge(provider, judgeCfg, (u) => {
3771
+ const c = provider.estimateCost(u);
3772
+ judgeCost += c.cost_usd;
3773
+ if (c.priced === false) judgeUnpriced = true;
3774
+ });
3775
+ return {
3776
+ ask: (q) => {
3777
+ judgedBy = `${judgeCfg.type}/${judgeCfg.model}`;
3778
+ return inner.ask(q);
3779
+ }
3780
+ };
3781
+ };
3750
3782
  const run = () => usesExpected(assertion) && (p.row.expected === void 0 || p.row.expected === "") ? Promise.resolve({
3751
3783
  passed: false,
3752
3784
  reason: "the row has no expected value, and this check compares against {{expected}}"
@@ -3756,7 +3788,8 @@ async function assess(p, output, transcript) {
3756
3788
  row: p.row,
3757
3789
  params: assertion,
3758
3790
  embedder: p.embedder,
3759
- judge: judge2,
3791
+ judge: judge2(),
3792
+ ...input !== void 0 ? { input } : {},
3760
3793
  ...transcript !== void 0 ? { transcript } : {}
3761
3794
  });
3762
3795
  if (ASSERTION_CLASSES[assertion.type] === "heuristic") {
@@ -3773,7 +3806,8 @@ async function assess(p, output, transcript) {
3773
3806
  type: assertion.type,
3774
3807
  passed: result2.passed,
3775
3808
  ...result2.score !== void 0 ? { score: result2.score } : {},
3776
- ...result2.reason !== void 0 ? { reason: result2.reason } : {}
3809
+ ...result2.reason !== void 0 ? { reason: result2.reason } : {},
3810
+ ...judgedBy !== void 0 ? { judge_model: judgedBy } : {}
3777
3811
  });
3778
3812
  } catch (err) {
3779
3813
  assertionError = toRunError(err);
@@ -3869,7 +3903,7 @@ async function runRow(p) {
3869
3903
  };
3870
3904
  }
3871
3905
  }
3872
- const { records, assertionError, judgeCost, judgeUnpriced } = await assess(p, output);
3906
+ const { records, assertionError, judgeCost, judgeUnpriced } = await assess(p, output, prompt5);
3873
3907
  const finalUsage = {
3874
3908
  ...usage3,
3875
3909
  cost_usd: usage3.cost_usd + judgeCost,
@@ -4058,6 +4092,15 @@ async function runOrchestration(config, options, deps) {
4058
4092
  });
4059
4093
  return { ev, template, rows, cells };
4060
4094
  });
4095
+ const judges = /* @__PURE__ */ new Map();
4096
+ const resolveJudge = (cfg) => {
4097
+ const key = canonicalJson(cfg);
4098
+ const known = judges.get(key);
4099
+ if (known !== void 0) return known;
4100
+ const made = deps.resolveProvider(cfg);
4101
+ judges.set(key, made);
4102
+ return made;
4103
+ };
4061
4104
  const swapped = Object.keys(options.toolDescriptions ?? {}).length > 0;
4062
4105
  if (swapped && !prepared.some((x) => x.ev.mcp !== void 0))
4063
4106
  throw new RunConfigError(
@@ -4077,6 +4120,7 @@ async function runOrchestration(config, options, deps) {
4077
4120
  row,
4078
4121
  providerConfig,
4079
4122
  provider,
4123
+ resolveJudge,
4080
4124
  embedder: deps.embedder,
4081
4125
  cache: deps.cache,
4082
4126
  now: deps.now,
@@ -4316,12 +4360,12 @@ function machineless(raw, repoRoot, home) {
4316
4360
  if (repoRoot === void 0) text6 = text6.replace(ANY_HOME, "~");
4317
4361
  return text6;
4318
4362
  }
4319
- function pathIn(path25) {
4320
- const parts = path25.split(/[\\/]+/);
4363
+ function pathIn(path26) {
4364
+ const parts = path26.split(/[\\/]+/);
4321
4365
  while (parts.length > 1 && parts.at(-1) === "") parts.pop();
4322
4366
  if (!parts.some((part) => part !== "" && !/^[A-Za-z]:$/.test(part))) return void 0;
4323
4367
  const joined = parts.map((part) => part.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("[\\\\/]+");
4324
- const escaped = /^\/(?!\/)/.test(path25) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
4368
+ const escaped = /^\/(?!\/)/.test(path26) ? joined.replace("[\\\\/]+", "\\\\*\\/") : joined;
4325
4369
  const url = "(?:(?:file|webpack|webpack-internal):(?:\\\\*\\/){2,3})?";
4326
4370
  return new RegExp(`${url}${escaped}`, /^[A-Za-z]:$/.test(parts[0]) ? "gi" : "g");
4327
4371
  }
@@ -4367,12 +4411,12 @@ function placeOf(error, testFile) {
4367
4411
  }
4368
4412
  function fileOf(raw) {
4369
4413
  if (!raw.startsWith("file://")) return raw;
4370
- let path25 = raw.slice("file://".length);
4414
+ let path26 = raw.slice("file://".length);
4371
4415
  try {
4372
- path25 = decodeURIComponent(path25);
4416
+ path26 = decodeURIComponent(path26);
4373
4417
  } catch {
4374
4418
  }
4375
- return /^\/[A-Za-z]:\//.test(path25) ? path25.slice(1) : path25;
4419
+ return /^\/[A-Za-z]:\//.test(path26) ? path26.slice(1) : path26;
4376
4420
  }
4377
4421
  function fromRoot(place, root) {
4378
4422
  if (place === void 0 || root === void 0 || !Number.isInteger(place.line) || place.line < 1) return void 0;
@@ -4412,14 +4456,14 @@ var init_failure_detail = __esm({
4412
4456
  FRAME = /^\s+at (?:.*? \()?(.+?):(\d+):(\d+)\)?$/;
4413
4457
  FRAME_MAX = 8192;
4414
4458
  firstLine = (text6) => (0, import_node_util.stripVTControlCharacters)(text6).split("\n").map((line) => line.trim()).find((line) => line !== "");
4415
- normal = (path25) => import_node_path3.posix.normalize(path25.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
4459
+ normal = (path26) => import_node_path3.posix.normalize(path26.replace(/\\/g, "/")).replace(/^([a-z]):/, (_, drive) => `${drive.toUpperCase()}:`);
4416
4460
  }
4417
4461
  });
4418
4462
 
4419
4463
  // src/mcp-testing/connect/journal.ts
4420
- function openJournal(path25, redact2) {
4421
- if (path25 === void 0) return NONE;
4422
- const fd = (0, import_node_fs3.openSync)(path25, "w", 384);
4464
+ function openJournal(path26, redact2) {
4465
+ if (path26 === void 0) return NONE;
4466
+ const fd = (0, import_node_fs3.openSync)(path26, "w", 384);
4423
4467
  if (process.platform !== "win32") (0, import_node_fs3.fchmodSync)(fd, 384);
4424
4468
  const start2 = import_node_perf_hooks.performance.now();
4425
4469
  let closed = false;
@@ -4771,14 +4815,14 @@ function readLines(stream, onLine, stats) {
4771
4815
  if (stats !== void 0 && rest.length > stats.high) stats.high = rest.length;
4772
4816
  partial = rest.slice(0, STDERR_LINE_LIMIT);
4773
4817
  };
4774
- return new Promise((resolve23) => {
4818
+ return new Promise((resolve25) => {
4775
4819
  let done = false;
4776
4820
  const finish = () => {
4777
4821
  if (done) return;
4778
4822
  done = true;
4779
4823
  feed(decoder.end());
4780
4824
  if (partial !== "") onLine(partial.endsWith("\r") ? partial.slice(0, -1) : partial);
4781
- resolve23();
4825
+ resolve25();
4782
4826
  };
4783
4827
  stream.on(
4784
4828
  "data",
@@ -5076,7 +5120,7 @@ async function openSession(config, options = {}) {
5076
5120
  const stdin = transport._process?.stdin;
5077
5121
  if (stdin === null || stdin === void 0 || stdin.writableEnded)
5078
5122
  throw spawnError !== void 0 ? await toConnectError(spawnError) : new ConnectError("exited-early", `${LEAD["exited-early"][0]}.`, [...tail]);
5079
- return new Promise((resolve23, reject) => {
5123
+ return new Promise((resolve25, reject) => {
5080
5124
  const done = () => {
5081
5125
  clearTimeout(timer2);
5082
5126
  listeners.delete(listener);
@@ -5090,7 +5134,7 @@ async function openSession(config, options = {}) {
5090
5134
  const frame2 = parsed(line);
5091
5135
  if (!answers(frame2, id2)) return;
5092
5136
  done();
5093
- resolve23({ frame: frame2, text: clean3(line).slice(0, RAW_TEXT) });
5137
+ resolve25({ frame: frame2, text: clean3(line).slice(0, RAW_TEXT) });
5094
5138
  };
5095
5139
  const stop = () => {
5096
5140
  done();
@@ -5170,10 +5214,10 @@ async function openSession(config, options = {}) {
5170
5214
  const proc = transport._process;
5171
5215
  if (proc === void 0) return true;
5172
5216
  if (proc.exitCode !== null || proc.signalCode !== null) return true;
5173
- const exited = new Promise((resolve23) => proc.once("exit", () => resolve23(true)));
5217
+ const exited = new Promise((resolve25) => proc.once("exit", () => resolve25(true)));
5174
5218
  proc.stdin?.end();
5175
5219
  let timer2;
5176
- const late = new Promise((resolve23) => timer2 = setTimeout(() => resolve23(false), waitMs));
5220
+ const late = new Promise((resolve25) => timer2 = setTimeout(() => resolve25(false), waitMs));
5177
5221
  const result2 = await Promise.race([exited, late]);
5178
5222
  clearTimeout(timer2);
5179
5223
  return result2;
@@ -7218,8 +7262,8 @@ function sortKeys(value2) {
7218
7262
  function homePattern(home) {
7219
7263
  const trimmed = home?.replace(/[\\/]+$/, "");
7220
7264
  if (trimmed === void 0 || trimmed.length < 2) return void 0;
7221
- const path25 = trimmed.split(/[\\/]/).map(escapeRegExp).join("[\\\\/]");
7222
- return new RegExp(`(?<![\\w./\\\\-])${path25}(?![\\w-]|\\.\\w)`, /^[A-Za-z]:/.test(trimmed) ? "gi" : "g");
7265
+ const path26 = trimmed.split(/[\\/]/).map(escapeRegExp).join("[\\\\/]");
7266
+ return new RegExp(`(?<![\\w./\\\\-])${path26}(?![\\w-]|\\.\\w)`, /^[A-Za-z]:/.test(trimmed) ? "gi" : "g");
7223
7267
  }
7224
7268
  function redact(value2, secrets, home) {
7225
7269
  if (typeof value2 === "string") {
@@ -7400,10 +7444,10 @@ function same(a, b) {
7400
7444
  const ka = Object.keys(a);
7401
7445
  return ka.length === Object.keys(b).length && ka.every((k) => Object.hasOwn(b, k) && same(a[k], b[k]));
7402
7446
  }
7403
- function compareSchema(c, side, path25, before, after) {
7447
+ function compareSchema(c, side, path26, before, after) {
7404
7448
  if (same(before, after)) return;
7405
- const field = `${side}Schema${path25 === "" ? "" : `.${path25}`}`;
7406
- if (path25 === "" && (before === void 0 || after === void 0)) {
7449
+ const field = `${side}Schema${path26 === "" ? "" : `.${path26}`}`;
7450
+ if (path26 === "" && (before === void 0 || after === void 0)) {
7407
7451
  if (side === "output") {
7408
7452
  if (after === void 0) c.add(field, "breaking", "The output schema was removed; a client reading the result loses its shape.", before, after);
7409
7453
  else c.add(field, "non-breaking", "An output schema was added.", before, after);
@@ -7415,10 +7459,10 @@ function compareSchema(c, side, path25, before, after) {
7415
7459
  return c.add(`${field}`, "breaking", `The type changed from ${show(before["type"])} to ${show(after["type"])}.`, before["type"], after["type"]);
7416
7460
  }
7417
7461
  if (!same(before["enum"], after["enum"])) compareEnum(c, side, field, before["enum"], after["enum"]);
7418
- compareProperties(c, side, path25, field, before, after);
7419
- if (!same(before["items"], after["items"])) compareSchema(c, side, `${path25}[]`, before["items"], after["items"]);
7462
+ compareProperties(c, side, path26, field, before, after);
7463
+ if (!same(before["items"], after["items"])) compareSchema(c, side, `${path26}[]`, before["items"], after["items"]);
7420
7464
  if (!same(before["description"], after["description"])) {
7421
- const what = path25 === "" ? `whole ${side} schema` : side === "input" ? "parameter" : "field";
7465
+ const what = path26 === "" ? `whole ${side} schema` : side === "input" ? "parameter" : "field";
7422
7466
  c.add(field, "informational", `The ${what} description changed: it is what a model reads.`, before["description"], after["description"], {
7423
7467
  signal: "security"
7424
7468
  });
@@ -7478,7 +7522,7 @@ function compareEnum(c, side, field, before, after) {
7478
7522
  if (widened) return c.add(field, "breaking", `The result enum was widened: ${gained}; a client does not know the new value.`, before, after);
7479
7523
  c.add(field, "non-breaking", `The result enum was narrowed: ${lost}.`, before, after);
7480
7524
  }
7481
- function compareProperties(c, side, path25, field, before, after) {
7525
+ function compareProperties(c, side, path26, field, before, after) {
7482
7526
  const bp = isRecord7(before["properties"]) ? before["properties"] : {};
7483
7527
  const ap = isRecord7(after["properties"]) ? after["properties"] : {};
7484
7528
  const br = stringSet(before["required"]);
@@ -7491,7 +7535,7 @@ function compareProperties(c, side, path25, field, before, after) {
7491
7535
  }
7492
7536
  const what = side === "input" ? "parameter" : "field";
7493
7537
  for (const name of [.../* @__PURE__ */ new Set([...Object.keys(bp), ...Object.keys(ap)])].sort()) {
7494
- const sub = path25 === "" ? name : `${path25}.${name}`;
7538
+ const sub = path26 === "" ? name : `${path26}.${name}`;
7495
7539
  const f = `${side}Schema.${sub}`;
7496
7540
  const inBefore = Object.hasOwn(bp, name);
7497
7541
  const inAfter = Object.hasOwn(ap, name);
@@ -8121,6 +8165,16 @@ function flakyText(a) {
8121
8165
  if (a.passed <= 0 || a.passed >= a.runs) return "";
8122
8166
  return ` \xB7 flaky ${Number((a.passed / a.runs).toFixed(2))}`;
8123
8167
  }
8168
+ function unsteadyRows(result2) {
8169
+ if (result2.dry_run === true) return [];
8170
+ return result2.evals.flatMap(
8171
+ (ev) => ev.rows.flatMap((row) => {
8172
+ const a = row.attempts;
8173
+ const mark = a === void 0 || a.results.length === 0 ? "" : flakyText(a);
8174
+ return mark === "" ? [] : [{ id: ev.id, mark }];
8175
+ })
8176
+ );
8177
+ }
8124
8178
  var safeLine, mdCell, NOT_MEASURED_STABILITY, noRepeats;
8125
8179
  var init_helpers = __esm({
8126
8180
  "src/reporters/helpers.ts"() {
@@ -8375,14 +8429,21 @@ function matrixMarkdown(d, room) {
8375
8429
  ...tail.length > 0 ? ["_" + tail[0] + "_", ""] : []
8376
8430
  ];
8377
8431
  }
8378
- function renderDiffMarkdown2(d, budget = COMMENT_BUDGET) {
8432
+ function unsteadyLine(current) {
8433
+ const rows = current === void 0 ? [] : unsteadyRows(current);
8434
+ if (rows.length === 0) return [];
8435
+ const named2 = rows.slice(0, UNSTEADY_LISTED).map((r) => `\`${oneLine(r.id)}\`${r.mark}`);
8436
+ const more = rows.length > UNSTEADY_LISTED ? `, and ${rows.length - UNSTEADY_LISTED} more` : "";
8437
+ return ["", `Unsteady in this run: ${named2.join(", ")}${more}`];
8438
+ }
8439
+ function renderDiffMarkdown2(d, budget = COMMENT_BUDGET, current) {
8379
8440
  const out = [STICKY_MARKER, "## Plune eval diff", ""];
8380
8441
  const head = headline(d);
8381
8442
  out.push(head ? `### ${head.mark} ${capital(head.text)}` : "### \u2705 No regressions");
8382
8443
  out.push("");
8383
8444
  const notable = d.evals.filter((e) => e.status !== "stable-pass");
8384
8445
  if (d.matrix !== void 0) {
8385
- const rest = [...gatesMarkdown(d), ...adviceMarkdown(d), `_${summaryLine2(d)}_`].join("\n");
8446
+ const rest = [...gatesMarkdown(d), ...adviceMarkdown(d), `_${summaryLine2(d)}_`, ...unsteadyLine(current)].join("\n");
8386
8447
  out.push(...matrixMarkdown(d, budget - out.join("\n").length - rest.length - 2));
8387
8448
  } else if (notable.length > 0) {
8388
8449
  out.push("| Eval | Baseline \u2192 Current | Change |");
@@ -8395,6 +8456,7 @@ function renderDiffMarkdown2(d, budget = COMMENT_BUDGET) {
8395
8456
  out.push(...gatesMarkdown(d));
8396
8457
  out.push(...adviceMarkdown(d));
8397
8458
  out.push(`_${summaryLine2(d)}_`);
8459
+ out.push(...unsteadyLine(current));
8398
8460
  return out.join("\n");
8399
8461
  }
8400
8462
  function renderDiffConsole(d) {
@@ -8412,18 +8474,19 @@ function renderDiffConsole(d) {
8412
8474
  function renderDiffJson(d) {
8413
8475
  return JSON.stringify(d, null, 2);
8414
8476
  }
8415
- function renderDiff(d, format = "console") {
8477
+ function renderDiff(d, format = "console", current) {
8416
8478
  if (format === "json") return noCommandsJson(renderDiffJson(d));
8417
- if (format === "markdown") return noCommands(renderDiffMarkdown2(d));
8479
+ if (format === "markdown") return noCommands(renderDiffMarkdown2(d, COMMENT_BUDGET, current));
8418
8480
  return noCommands(renderDiffConsole(d));
8419
8481
  }
8420
- var NOT_MEASURED, STICKY_MARKER, BADGE, GATE_STATE, capital, oneLine, cell2, target2, WORD, comparisonText, countsText, NOT_COMPARED, DIFFERED, COMMENT_BUDGET, IMPORTANCE, plural3;
8482
+ var NOT_MEASURED, STICKY_MARKER, BADGE, GATE_STATE, capital, oneLine, cell2, target2, WORD, comparisonText, countsText, NOT_COMPARED, DIFFERED, COMMENT_BUDGET, IMPORTANCE, plural3, UNSTEADY_LISTED;
8421
8483
  var init_diff2 = __esm({
8422
8484
  "src/reporters/diff.ts"() {
8423
8485
  "use strict";
8424
8486
  init_cjs_shims();
8425
8487
  init_stats();
8426
8488
  init_human();
8489
+ init_helpers();
8427
8490
  NOT_MEASURED = "not measured";
8428
8491
  STICKY_MARKER = "<!-- plune-eval-diff -->";
8429
8492
  BADGE = {
@@ -8470,6 +8533,7 @@ var init_diff2 = __esm({
8470
8533
  "stable-pass"
8471
8534
  ];
8472
8535
  plural3 = (n, one, many) => `${n} ${n === 1 ? one : many}`;
8536
+ UNSTEADY_LISTED = 10;
8473
8537
  }
8474
8538
  });
8475
8539
 
@@ -8908,7 +8972,7 @@ function parseRetryAfter(raw, now = Date.now()) {
8908
8972
  return Math.min(Math.max(seconds, 0) * 1e3, RETRY_AFTER_CAP_MS);
8909
8973
  }
8910
8974
  function nodeTransport(url, init, idleMs = IDLE_MS) {
8911
- return new Promise((resolve23, reject) => {
8975
+ return new Promise((resolve25, reject) => {
8912
8976
  const target4 = new URL(url);
8913
8977
  const send3 = target4.protocol === "https:" ? import_node_https.request : import_node_http.request;
8914
8978
  const agent = POOLS[target4.protocol === "https:" ? "https:" : "http:"];
@@ -8919,7 +8983,7 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
8919
8983
  res.on("end", () => {
8920
8984
  const status2 = res.statusCode ?? 0;
8921
8985
  const text6 = Buffer.concat(chunks).toString("utf8");
8922
- resolve23({
8986
+ resolve25({
8923
8987
  ok: status2 >= 200 && status2 <= 299,
8924
8988
  status: status2,
8925
8989
  headers: {
@@ -8938,12 +9002,12 @@ function nodeTransport(url, init, idleMs = IDLE_MS) {
8938
9002
  });
8939
9003
  }
8940
9004
  function nodePut(url, headers, source, idleMs) {
8941
- return new Promise((resolve23, reject) => {
9005
+ return new Promise((resolve25, reject) => {
8942
9006
  const target4 = new URL(url);
8943
9007
  const send3 = target4.protocol === "https:" ? import_node_https.request : import_node_http.request;
8944
9008
  const length = "body" in source ? source.body.length : source.size;
8945
9009
  let answered;
8946
- const settle = (err) => answered !== void 0 ? resolve23(answered) : reject(err);
9010
+ const settle = (err) => answered !== void 0 ? resolve25(answered) : reject(err);
8947
9011
  const req = send3(
8948
9012
  target4,
8949
9013
  { method: "PUT", headers: { ...withoutLength(headers), "content-length": String(length) } },
@@ -8952,7 +9016,7 @@ function nodePut(url, headers, source, idleMs) {
8952
9016
  answered = { status: res.statusCode ?? 0, retryAfter: Array.isArray(retry) ? retry[0] ?? null : retry ?? null };
8953
9017
  res.on("error", settle);
8954
9018
  res.on("close", () => {
8955
- resolve23(answered);
9019
+ resolve25(answered);
8956
9020
  req.destroy();
8957
9021
  });
8958
9022
  res.resume();
@@ -9015,7 +9079,7 @@ function createClient(opts) {
9015
9079
  }
9016
9080
  const base = opts.apiUrl.replace(/\/+$/, "");
9017
9081
  const scrub = (text6) => opts.token === "" ? text6 : text6.split(opts.token).join("***");
9018
- async function send3(method, path25, payload2, retries = DEFAULT_RETRIES) {
9082
+ async function send3(method, path26, payload2, retries = DEFAULT_RETRIES) {
9019
9083
  let last = {
9020
9084
  kind: "unavailable",
9021
9085
  status: null,
@@ -9026,7 +9090,7 @@ function createClient(opts) {
9026
9090
  await respectPause(mine);
9027
9091
  let res;
9028
9092
  try {
9029
- res = await doFetch(`${base}${path25}`, {
9093
+ res = await doFetch(`${base}${path26}`, {
9030
9094
  method,
9031
9095
  headers: { "content-type": payload2?.type ?? "application/json", authorization: `Bearer ${opts.token}` },
9032
9096
  // A DELETE carries none. Sending `"undefined"` as a body is what a naive
@@ -9065,11 +9129,11 @@ function createClient(opts) {
9065
9129
  return { ok: false, ...last };
9066
9130
  }
9067
9131
  return {
9068
- post: (path25, body, retries) => send3("POST", path25, { body: JSON.stringify(body), type: "application/json" }, retries),
9069
- upload: (path25, bytes, contentType2) => send3("POST", path25, { body: bytes, type: contentType2 }, uploadRetries ?? DEFAULT_RETRIES),
9070
- del: (path25) => send3("DELETE", path25),
9071
- get: (path25) => send3("GET", path25),
9072
- patch: (path25, body) => send3("PATCH", path25, { body: JSON.stringify(body), type: "application/json" }),
9132
+ post: (path26, body, retries) => send3("POST", path26, { body: JSON.stringify(body), type: "application/json" }, retries),
9133
+ upload: (path26, bytes, contentType2) => send3("POST", path26, { body: bytes, type: contentType2 }, uploadRetries ?? DEFAULT_RETRIES),
9134
+ del: (path26) => send3("DELETE", path26),
9135
+ get: (path26) => send3("GET", path26),
9136
+ patch: (path26, body) => send3("PATCH", path26, { body: JSON.stringify(body), type: "application/json" }),
9073
9137
  async put(url, headers, source) {
9074
9138
  const putRetries = uploadRetries ?? 3;
9075
9139
  let last = { ok: false, status: null, code: "network" };
@@ -9305,9 +9369,9 @@ var init_fallback = __esm({
9305
9369
  });
9306
9370
 
9307
9371
  // src/reporter-core/files-batch.ts
9308
- async function sha256File(path25) {
9372
+ async function sha256File(path26) {
9309
9373
  const hash = (0, import_node_crypto3.createHash)("sha256");
9310
- for await (const part of (0, import_node_fs7.createReadStream)(path25)) hash.update(part);
9374
+ for await (const part of (0, import_node_fs7.createReadStream)(path26)) hash.update(part);
9311
9375
  return hash.digest("hex");
9312
9376
  }
9313
9377
  var import_node_crypto3, import_node_fs7, FILES_BATCH_MAX, DIRECT_BATCH_BYTES, BATCH_PIPELINES, sha256Bytes, BUCKET_CODES;
@@ -9728,7 +9792,7 @@ function fileSender(options) {
9728
9792
  let free = uploadsAtOnce;
9729
9793
  const waiting = [];
9730
9794
  async function gated(work) {
9731
- if (free === 0) await new Promise((resolve23) => waiting.push(resolve23));
9795
+ if (free === 0) await new Promise((resolve25) => waiting.push(resolve25));
9732
9796
  else free -= 1;
9733
9797
  try {
9734
9798
  return await work();
@@ -10788,14 +10852,14 @@ async function handleRunExec(options) {
10788
10852
  if (command === void 0) throw new RunCommandError("Nothing to run \u2014 pass a command after `--`.");
10789
10853
  const run = await handleRunStart(options);
10790
10854
  const spawnImpl = options.spawnImpl ?? import_node_child_process2.spawn;
10791
- const code = await new Promise((resolve23) => {
10855
+ const code = await new Promise((resolve25) => {
10792
10856
  const child = spawnImpl(command, args, {
10793
10857
  stdio: "inherit",
10794
10858
  shell: process.platform === "win32",
10795
10859
  env: { ...process.env, PLUNE_RUN: run.externalKey, PLUNE_PROCEED: "1" }
10796
10860
  });
10797
- child.on("close", (exitCode2) => resolve23(exitCode2 ?? 1));
10798
- child.on("error", () => resolve23(1));
10861
+ child.on("close", (exitCode2) => resolve25(exitCode2 ?? 1));
10862
+ child.on("error", () => resolve25(1));
10799
10863
  });
10800
10864
  return handleRunFinish(run.id, options, code);
10801
10865
  }
@@ -10927,7 +10991,7 @@ function traceUrlProblem(value2) {
10927
10991
  } catch {
10928
10992
  return "must be an https address";
10929
10993
  }
10930
- if (parsed4.protocol !== "https:" || parsed4.hostname === "") return "must be an https address";
10994
+ if (!url.startsWith("https://") || parsed4.hostname === "") return "must be an https address";
10931
10995
  if (parsed4.username !== "" || parsed4.password !== "") return "must carry no user name or password";
10932
10996
  return void 0;
10933
10997
  }
@@ -10951,7 +11015,9 @@ var init_run_result_schema = __esm({
10951
11015
  passed: import_zod3.z.boolean(),
10952
11016
  score: import_zod3.z.number().optional(),
10953
11017
  reason: import_zod3.z.string().optional(),
10954
- binaryVerdicts: import_zod3.z.array(binaryVerdictSchema).optional()
11018
+ binaryVerdicts: import_zod3.z.array(binaryVerdictSchema).optional(),
11019
+ /** plune-ai/cli#373. Optional and additive — a RunResult written before it validates unchanged. */
11020
+ judge_model: import_zod3.z.string().optional()
10955
11021
  });
10956
11022
  usageSchema = import_zod3.z.object({
10957
11023
  input_tokens: import_zod3.z.number(),
@@ -11395,10 +11461,10 @@ function platformGet(deps) {
11395
11461
  const token2 = (deps.loadToken ?? loadToken)();
11396
11462
  if (token2 === null) throw new NotLoggedInError();
11397
11463
  const doFetch = deps.fetchImpl ?? fetch;
11398
- return async (path25) => {
11464
+ return async (path26) => {
11399
11465
  let res;
11400
11466
  try {
11401
- res = await doFetch(`${apiUrl}${path25}`, { headers: { authorization: `Bearer ${token2}` } });
11467
+ res = await doFetch(`${apiUrl}${path26}`, { headers: { authorization: `Bearer ${token2}` } });
11402
11468
  } catch {
11403
11469
  throw new SyncNetworkError(apiUrl);
11404
11470
  }
@@ -11753,9 +11819,9 @@ var init_read_file = __esm({
11753
11819
  });
11754
11820
 
11755
11821
  // src/importers/allure.ts
11756
- function isFolder(path25) {
11822
+ function isFolder(path26) {
11757
11823
  try {
11758
- return fs12.statSync(path25).isDirectory();
11824
+ return fs12.statSync(path26).isDirectory();
11759
11825
  } catch {
11760
11826
  return false;
11761
11827
  }
@@ -12312,10 +12378,10 @@ function attemptOf(result2, file, ctx) {
12312
12378
  ...typeof at2?.file === "string" && typeof at2.line === "number" ? { location: { file: at2.file, line: at2.line, ...typeof at2.column === "number" ? { column: at2.column } : {} } } : {}
12313
12379
  })),
12314
12380
  steps: steps(result2.steps),
12315
- attachments: (result2.attachments ?? []).map(({ name, contentType: contentType2, path: path25, body }) => ({
12381
+ attachments: (result2.attachments ?? []).map(({ name, contentType: contentType2, path: path26, body }) => ({
12316
12382
  name: name ?? "",
12317
12383
  ...contentType2 !== void 0 ? { contentType: contentType2 } : {},
12318
- ...path25 !== void 0 ? { path: path25 } : {},
12384
+ ...path26 !== void 0 ? { path: path26 } : {},
12319
12385
  // Decoded only where the platform would take it: a report of screenshots kept as
12320
12386
  // bodies is megabytes of base64 that nothing here will read.
12321
12387
  ...typeof body === "string" && isTextType(contentType2) ? { body: Buffer.from(body, "base64") } : {}
@@ -12764,7 +12830,7 @@ async function timeoutMessage(limit3, runId, ours, options) {
12764
12830
  if (!ours) return `${head}; run ${runId} is shared with other jobs and was left open - close it with "plune run finish ${runId}" once they are done, then import this report again.`;
12765
12831
  const wait = options.terminateWaitMs ?? 15e3;
12766
12832
  let timer;
12767
- const gaveUp = new Promise((resolve23) => timer = setTimeout(() => resolve23("gaveup"), wait));
12833
+ const gaveUp = new Promise((resolve25) => timer = setTimeout(() => resolve25("gaveup"), wait));
12768
12834
  const quiet = () => void 0;
12769
12835
  const closed = handleRunFinish(runId, { ...options, write: quiet, terminate: true, reason: `import timed out after ${limit3} s` }).then(
12770
12836
  () => true,
@@ -12870,7 +12936,7 @@ async function handleRunImport(options) {
12870
12936
  else {
12871
12937
  sent.catch(() => void 0);
12872
12938
  let timer;
12873
- const late = new Promise((resolve23) => timer = setTimeout(() => resolve23("late"), limit3 * 1e3));
12939
+ const late = new Promise((resolve25) => timer = setTimeout(() => resolve25("late"), limit3 * 1e3));
12874
12940
  const first = await Promise.race([sent, late]).finally(() => clearTimeout(timer));
12875
12941
  if (first === "late") {
12876
12942
  throw new ImportTimeoutError(await timeoutMessage(limit3, session2?.runId ?? null, !env.keepOpen, { ...options, apiUrl, token: token2 }));
@@ -13545,6 +13611,7 @@ var init_advice = __esm({
13545
13611
  var diff_exports2 = {};
13546
13612
  __export(diff_exports2, {
13547
13613
  DiffInputError: () => DiffInputError,
13614
+ diffFiles: () => diffFiles,
13548
13615
  handleDiff: () => handleDiff
13549
13616
  });
13550
13617
  function isRunResult2(v) {
@@ -13593,6 +13660,9 @@ ${err.message}`);
13593
13660
  }
13594
13661
  }
13595
13662
  function handleDiff(opts) {
13663
+ return diffFiles(opts).diff;
13664
+ }
13665
+ function diffFiles(opts) {
13596
13666
  const gateOpts = {
13597
13667
  ...opts.failOnRegression === true ? { failOnRegression: true } : {}
13598
13668
  };
@@ -13612,8 +13682,8 @@ function handleDiff(opts) {
13612
13682
  const diff2 = diffRuns(baseline, current);
13613
13683
  const advice = adviceFor(baseline, current);
13614
13684
  const withAdvice = advice === void 0 ? diff2 : { ...diff2, advice };
13615
- if (!gatesEnabled(gateOpts)) return withAdvice;
13616
- return { ...withAdvice, gates: evaluateGates(baseline, current, diff2, gateOpts, waivers, now) };
13685
+ if (!gatesEnabled(gateOpts)) return { diff: withAdvice, current };
13686
+ return { diff: { ...withAdvice, gates: evaluateGates(baseline, current, diff2, gateOpts, waivers, now) }, current };
13617
13687
  }
13618
13688
  var fs14, DiffInputError;
13619
13689
  var init_diff4 = __esm({
@@ -13635,6 +13705,419 @@ var init_diff4 = __esm({
13635
13705
  }
13636
13706
  });
13637
13707
 
13708
+ // src/judge/agreement.ts
13709
+ function confusionOf(pairs2) {
13710
+ const c = { tp: 0, fn: 0, fp: 0, tn: 0 };
13711
+ for (const { human: human2, judge: judge2 } of pairs2) {
13712
+ if (human2) c[judge2 ? "tp" : "fn"] += 1;
13713
+ else c[judge2 ? "fp" : "tn"] += 1;
13714
+ }
13715
+ return c;
13716
+ }
13717
+ function kappaOf({ tp, fn, fp, tn }) {
13718
+ const n = tp + fn + fp + tn;
13719
+ if (n === 0) return null;
13720
+ const observed2 = (tp + tn) / n;
13721
+ const chance = ((tp + fp) * (tp + fn) + (fn + tn) * (fp + tn)) / (n * n);
13722
+ return chance === 1 ? null : (observed2 - chance) / (1 - chance);
13723
+ }
13724
+ function seeded(seed) {
13725
+ let a = seed >>> 0;
13726
+ return () => {
13727
+ a = a + 1831565813 >>> 0;
13728
+ let t = a;
13729
+ t = Math.imul(t ^ t >>> 15, t | 1);
13730
+ t ^= t + Math.imul(t ^ t >>> 7, t | 61);
13731
+ return ((t ^ t >>> 14) >>> 0) / 4294967296;
13732
+ };
13733
+ }
13734
+ function kappaInterval(pairs2, resamples = BOOTSTRAP_RESAMPLES, seed = BOOTSTRAP_SEED) {
13735
+ const n = pairs2.length;
13736
+ if (n === 0) return null;
13737
+ const next = seeded(seed);
13738
+ const values = [];
13739
+ for (let r = 0; r < resamples; r++) {
13740
+ const sample = [];
13741
+ for (let i = 0; i < n; i++) sample.push(pairs2[Math.floor(next() * n)]);
13742
+ const k = kappaOf(confusionOf(sample));
13743
+ if (k !== null) values.push(k);
13744
+ }
13745
+ if (values.length * 2 < resamples) return null;
13746
+ values.sort((a, b) => a - b);
13747
+ const at2 = (q) => values[Math.min(values.length - 1, Math.floor(q * values.length))];
13748
+ return { low: at2(0.025), high: at2(0.975) };
13749
+ }
13750
+ function agreementOf(pairs2) {
13751
+ const c = confusionOf(pairs2);
13752
+ const n = pairs2.length;
13753
+ const kappa = kappaOf(c);
13754
+ return {
13755
+ ...c,
13756
+ n,
13757
+ agreement: ratio(c.tp + c.tn, n),
13758
+ tpr: ratio(c.tp, c.tp + c.fn),
13759
+ tnr: ratio(c.tn, c.tn + c.fp),
13760
+ kappa,
13761
+ kappaInterval: kappa === null ? null : kappaInterval(pairs2)
13762
+ };
13763
+ }
13764
+ var ratio, BOOTSTRAP_RESAMPLES, BOOTSTRAP_SEED;
13765
+ var init_agreement = __esm({
13766
+ "src/judge/agreement.ts"() {
13767
+ "use strict";
13768
+ init_cjs_shims();
13769
+ ratio = (a, b) => b === 0 ? null : a / b;
13770
+ BOOTSTRAP_RESAMPLES = 2e3;
13771
+ BOOTSTRAP_SEED = 2888;
13772
+ }
13773
+ });
13774
+
13775
+ // src/judge/labels.ts
13776
+ var labels_exports = {};
13777
+ __export(labels_exports, {
13778
+ JudgeCheckError: () => JudgeCheckError,
13779
+ labelTemplate: () => labelTemplate,
13780
+ matchLabels: () => matchLabels,
13781
+ outputHashOf: () => outputHashOf,
13782
+ parseLabels: () => parseLabels,
13783
+ varsHashOf: () => varsHashOf
13784
+ });
13785
+ function parseLabels(text6) {
13786
+ const labels = [];
13787
+ text6.replace(/^/, "").split(/\r?\n/).forEach((line, i) => {
13788
+ if (line.trim() === "") return;
13789
+ const where3 = `labels line ${i + 1}`;
13790
+ let v;
13791
+ try {
13792
+ v = JSON.parse(line);
13793
+ } catch {
13794
+ throw new JudgeCheckError(`${where3} is not JSON`);
13795
+ }
13796
+ if (!isObj(v)) throw new JudgeCheckError(`${where3} is not an object`);
13797
+ if (typeof v.eval !== "string" || v.eval === "") throw new JudgeCheckError(`${where3}: eval is missing`);
13798
+ for (const k of ["vars_hash", "output_hash"]) {
13799
+ if (typeof v[k] !== "string" || !HEX64.test(v[k]))
13800
+ throw new JudgeCheckError(`${where3}: ${k} is not a sha256 in hex`);
13801
+ }
13802
+ if (v.human !== "pass" && v.human !== "fail" && v.human !== null)
13803
+ throw new JudgeCheckError(`${where3}: human is "pass", "fail" or null`);
13804
+ const by = typeof v.by === "string" ? v.by : "";
13805
+ const at2 = typeof v.at === "string" ? v.at : "";
13806
+ if (v.human !== null && (by === "" || at2 === ""))
13807
+ throw new JudgeCheckError(`${where3}: a label says who gave it and when (by, at)`);
13808
+ labels.push({
13809
+ eval: v.eval,
13810
+ vars_hash: v.vars_hash.toLowerCase(),
13811
+ output_hash: v.output_hash.toLowerCase(),
13812
+ human: v.human,
13813
+ by,
13814
+ at: at2,
13815
+ ...typeof v.note === "string" ? { note: v.note } : {}
13816
+ });
13817
+ });
13818
+ return labels;
13819
+ }
13820
+ function labelTemplate(run, evalId) {
13821
+ const evals = run.evals.filter((ev) => evalId === void 0 || ev.id === evalId || baseEvalId(ev) === evalId);
13822
+ if (evals.length === 0) throw new JudgeCheckError(`the run has no eval ${JSON.stringify(evalId)}`);
13823
+ const lines = [];
13824
+ for (const ev of evals) {
13825
+ const seen = /* @__PURE__ */ new Map();
13826
+ for (const row of ev.rows) {
13827
+ const hash = varsHashOf(row.vars);
13828
+ seen.set(hash, (seen.get(hash) ?? 0) + 1);
13829
+ }
13830
+ for (const row of ev.rows) {
13831
+ if (row.output === null || seen.get(varsHashOf(row.vars)) > 1) continue;
13832
+ lines.push(
13833
+ JSON.stringify({
13834
+ eval: ev.id,
13835
+ vars_hash: varsHashOf(row.vars),
13836
+ output_hash: outputHashOf(row.output),
13837
+ human: null,
13838
+ by: "",
13839
+ at: "",
13840
+ vars: row.vars,
13841
+ output: row.output
13842
+ })
13843
+ );
13844
+ }
13845
+ }
13846
+ return lines.join("\n") + (lines.length > 0 ? "\n" : "");
13847
+ }
13848
+ function matchLabels(ev, check5, checkType, labels) {
13849
+ const rows = /* @__PURE__ */ new Map();
13850
+ const repeats = /* @__PURE__ */ new Set();
13851
+ for (const row of ev.rows) {
13852
+ const hash = varsHashOf(row.vars);
13853
+ if (rows.has(hash)) repeats.add(hash);
13854
+ rows.set(hash, row);
13855
+ }
13856
+ const m = { pairs: [], unlabelled: 0, stale: 0, missing: 0, notJudged: 0, conflicting: 0, repeated: 0 };
13857
+ const byRow = /* @__PURE__ */ new Map();
13858
+ for (const l of labels) {
13859
+ if (l.eval !== ev.id) continue;
13860
+ if (l.human === null) {
13861
+ m.unlabelled += 1;
13862
+ continue;
13863
+ }
13864
+ const row = rows.get(l.vars_hash);
13865
+ if (row === void 0) {
13866
+ m.missing += 1;
13867
+ continue;
13868
+ }
13869
+ if (repeats.has(l.vars_hash)) {
13870
+ m.repeated += 1;
13871
+ continue;
13872
+ }
13873
+ if (row.output === null) {
13874
+ m.notJudged += 1;
13875
+ continue;
13876
+ }
13877
+ if (outputHashOf(row.output) !== l.output_hash) {
13878
+ m.stale += 1;
13879
+ continue;
13880
+ }
13881
+ const seen = byRow.get(l.vars_hash) ?? /* @__PURE__ */ new Set();
13882
+ seen.add(l.human);
13883
+ byRow.set(l.vars_hash, seen);
13884
+ }
13885
+ for (const [hash, said3] of byRow) {
13886
+ if (said3.size > 1) {
13887
+ m.conflicting += 1;
13888
+ continue;
13889
+ }
13890
+ const row = rows.get(hash);
13891
+ const verdict2 = row.assertions[check5];
13892
+ const judged2 = row.inconclusive == null && verdict2?.type === checkType;
13893
+ if (!judged2) {
13894
+ m.notJudged += 1;
13895
+ continue;
13896
+ }
13897
+ m.pairs.push({ human: said3.has("pass"), judge: verdict2.passed });
13898
+ }
13899
+ return m;
13900
+ }
13901
+ var JudgeCheckError, varsHashOf, outputHashOf, HEX64, isObj;
13902
+ var init_labels = __esm({
13903
+ "src/judge/labels.ts"() {
13904
+ "use strict";
13905
+ init_cjs_shims();
13906
+ init_canonical_json();
13907
+ init_hash();
13908
+ init_results();
13909
+ JudgeCheckError = class extends Error {
13910
+ constructor(message2) {
13911
+ super(message2);
13912
+ this.name = "JudgeCheckError";
13913
+ }
13914
+ };
13915
+ varsHashOf = (vars) => sha256(canonicalJson(vars));
13916
+ outputHashOf = (output) => sha256(output);
13917
+ HEX64 = /^[0-9a-f]{64}$/i;
13918
+ isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
13919
+ }
13920
+ });
13921
+
13922
+ // src/judge/check.ts
13923
+ function checkTypes(ev) {
13924
+ const row = ev.rows.reduce(
13925
+ (best, r) => r.assertions.length > (best?.assertions.length ?? 0) ? r : best,
13926
+ void 0
13927
+ );
13928
+ return row === void 0 ? [] : row.assertions.map((a) => a.type);
13929
+ }
13930
+ function pickCheck(ev, wanted) {
13931
+ const types = checkTypes(ev);
13932
+ const erred = ev.rows.every((r) => r.error != null) ? "; every row stopped at an error, so later checks have no verdict" : "";
13933
+ if (wanted !== void 0) {
13934
+ if (wanted > types.length)
13935
+ throw new JudgeCheckError(
13936
+ `eval ${ev.id} has ${types.length} ${types.length === 1 ? "check" : "checks"} in a row; --check ${wanted} is not one${erred}`
13937
+ );
13938
+ return wanted - 1;
13939
+ }
13940
+ const judged2 = types.flatMap((t, i) => JUDGE_TYPES.includes(t) ? [i] : []);
13941
+ if (judged2.length === 1) return judged2[0];
13942
+ const list3 = types.map((t, i) => `${i + 1} ${t}`).join(", ");
13943
+ throw new JudgeCheckError(
13944
+ judged2.length === 0 ? `eval ${ev.id} has no check a model judges; name the one to compare with --check <n> (${list3 || "no checks"})${erred}` : `eval ${ev.id} has ${judged2.length} checks a model judges; name one with --check <n> (${list3})`
13945
+ );
13946
+ }
13947
+ function selfJudge(ev, check5, checkType) {
13948
+ if (!JUDGE_TYPES.includes(checkType)) return void 0;
13949
+ const answered = ev.provider !== void 0 ? `${ev.provider.type}/${ev.provider.model}` : ev.measured?.model;
13950
+ if (answered === void 0) return void 0;
13951
+ const judged2 = ev.rows.find((r) => r.assertions[check5]?.judge_model !== void 0)?.assertions[check5].judge_model;
13952
+ if (judged2 !== void 0 && judged2 !== answered) return void 0;
13953
+ return answered.split("/").slice(1).join("/");
13954
+ }
13955
+ function judgeCheck(run, labels, options = {}) {
13956
+ const maxWidth = options.maxIntervalWidth ?? DEFAULT_MAX_INTERVAL_WIDTH;
13957
+ const labelled = new Set(labels.map((l) => l.eval));
13958
+ const evals = run.evals.filter(
13959
+ (ev) => options.evalId === void 0 ? labelled.has(ev.id) : ev.id === options.evalId || baseEvalId(ev) === options.evalId
13960
+ );
13961
+ if (evals.length === 0) {
13962
+ throw new JudgeCheckError(
13963
+ options.evalId === void 0 ? "no eval of the run has a label in the file" : `the run has no eval ${JSON.stringify(options.evalId)}`
13964
+ );
13965
+ }
13966
+ const out = [];
13967
+ let exitCode2 = 0;
13968
+ for (const ev of evals) {
13969
+ const check5 = pickCheck(ev, options.check);
13970
+ const checkType = checkTypes(ev)[check5];
13971
+ const matched = matchLabels(ev, check5, checkType, labels);
13972
+ const agreement = agreementOf(matched.pairs);
13973
+ const warnings = [];
13974
+ if (agreement.n < MIN_RELIABLE_N) {
13975
+ warnings.push(
13976
+ `${agreement.n} labelled rows, fewer than ${MIN_RELIABLE_N}: these figures are not reliable yet`
13977
+ );
13978
+ }
13979
+ const iv = agreement.kappaInterval;
13980
+ if (agreement.kappa !== null && (iv === null || iv.high - iv.low > maxWidth)) {
13981
+ warnings.push(
13982
+ iv === null ? "the 95% interval of kappa could not be estimated: most resamples had one answer only" : `the 95% interval of kappa is ${(iv.high - iv.low).toFixed(2)} wide, more than ${maxWidth}: label more rows before trusting the number`
13983
+ );
13984
+ }
13985
+ if (agreement.kappa === null && agreement.n > 0) {
13986
+ warnings.push("kappa has no value: the person and the judge each gave one answer only");
13987
+ }
13988
+ const self = selfJudge(ev, check5, checkType);
13989
+ if (self !== void 0) {
13990
+ warnings.push(`the judge is ${self}, the model that wrote the answers: a model tends to favour its own text`);
13991
+ }
13992
+ if (options.minKappa !== void 0 && !meetsKappa(agreement.kappa, options.minKappa)) exitCode2 = 1;
13993
+ out.push({ evalId: ev.id, check: check5, checkType, matched, agreement, warnings });
13994
+ }
13995
+ const inRun = new Set(run.evals.map((ev) => ev.id));
13996
+ const otherEvals = [...labelled].filter((id2) => !inRun.has(id2)).sort();
13997
+ return { evals: out, otherEvals, exitCode: exitCode2 };
13998
+ }
13999
+ function formatJudgeCheck(report, minKappa) {
14000
+ const lines = [];
14001
+ for (const e of report.evals) {
14002
+ const a = e.agreement;
14003
+ const m = e.matched;
14004
+ const skipped2 = [
14005
+ [m.unlabelled, "not labelled yet"],
14006
+ [m.stale, "answer changed since the label"],
14007
+ [m.missing, "not in this run"],
14008
+ [m.notJudged, "no verdict of this check"],
14009
+ [m.repeated, "on a row whose vars repeat in the run"],
14010
+ [m.conflicting, "labelled both pass and fail"]
14011
+ ].filter(([n]) => n > 0).map(([n, what]) => `${n} ${what}`);
14012
+ lines.push(`Judge check: ${e.evalId}, check ${e.check + 1} (${e.checkType})`);
14013
+ lines.push(` labelled rows: ${a.n}${skipped2.length > 0 ? ` (left out: ${skipped2.join(", ")})` : ""}`);
14014
+ lines.push(" person pass person fail");
14015
+ lines.push(` judge pass ${String(a.tp).padStart(11)} ${String(a.fp).padStart(11)}`);
14016
+ lines.push(` judge fail ${String(a.fn).padStart(11)} ${String(a.tn).padStart(11)}`);
14017
+ const iv = a.kappaInterval === null ? "" : ` (95% ${fmt(a.kappaInterval.low)} to ${fmt(a.kappaInterval.high)})`;
14018
+ lines.push(` agreement ${fmt(a.agreement)} \xB7 TPR ${fmt(a.tpr)} \xB7 TNR ${fmt(a.tnr)} \xB7 kappa ${fmt(a.kappa)}${iv}`);
14019
+ for (const w of e.warnings) lines.push(` warning: ${w}`);
14020
+ if (minKappa !== void 0) {
14021
+ lines.push(` --min-kappa ${minKappa}: ${meetsKappa(a.kappa, minKappa) ? "met" : "not met"}`);
14022
+ }
14023
+ lines.push("");
14024
+ }
14025
+ if (report.otherEvals.length > 0) {
14026
+ lines.push(`Labels of evals not in this run: ${report.otherEvals.join(", ")}`, "");
14027
+ }
14028
+ return lines.join("\n");
14029
+ }
14030
+ var meetsKappa, JUDGE_TYPES, MIN_RELIABLE_N, DEFAULT_MAX_INTERVAL_WIDTH, fmt;
14031
+ var init_check = __esm({
14032
+ "src/judge/check.ts"() {
14033
+ "use strict";
14034
+ init_cjs_shims();
14035
+ init_agreement();
14036
+ init_labels();
14037
+ init_results();
14038
+ meetsKappa = (kappa, min) => kappa !== null && kappa >= min - 1e-9;
14039
+ JUDGE_TYPES = ["llm-judge", "faithfulness", "answer-relevance", "context-precision"];
14040
+ MIN_RELIABLE_N = 30;
14041
+ DEFAULT_MAX_INTERVAL_WIDTH = 0.4;
14042
+ fmt = (v) => v === null ? "n/a" : v.toFixed(2);
14043
+ }
14044
+ });
14045
+
14046
+ // src/cli/commands/judge-check.ts
14047
+ var judge_check_exports = {};
14048
+ __export(judge_check_exports, {
14049
+ handleJudgeCheck: () => handleJudgeCheck
14050
+ });
14051
+ function number(flag2, raw, min, max) {
14052
+ if (raw === void 0) return void 0;
14053
+ const v = Number(raw);
14054
+ if (raw.trim() === "" || !Number.isFinite(v) || v < min || v > max)
14055
+ throw new JudgeCheckError(`${flag2} is a number from ${min} to ${max}, not ${JSON.stringify(raw)}`);
14056
+ return v;
14057
+ }
14058
+ function readRun2(cwd, file) {
14059
+ let text6;
14060
+ try {
14061
+ text6 = fs15.readFileSync(path18.resolve(cwd, file), "utf8");
14062
+ } catch {
14063
+ throw new JudgeCheckError(`cannot read the run ${file}: run "plune run" first, or name one with --run`);
14064
+ }
14065
+ try {
14066
+ return parseRunResult(JSON.parse(text6.replace(/^/, "")));
14067
+ } catch {
14068
+ throw new JudgeCheckError(`${file} is not a run that plune run writes`);
14069
+ }
14070
+ }
14071
+ async function handleJudgeCheck(labelsFile, flags2, cwd, write) {
14072
+ const run = readRun2(cwd, flags2.run ?? path18.join(".plune", "last-run.json"));
14073
+ const target4 = path18.resolve(cwd, labelsFile);
14074
+ if (flags2.init === true) {
14075
+ if (!flags2.force && fs15.existsSync(target4))
14076
+ throw new JudgeCheckError(`${labelsFile} exists: it may hold labels; --force writes over it`);
14077
+ const text7 = labelTemplate(run, flags2.eval);
14078
+ fs15.mkdirSync(path18.dirname(target4), { recursive: true });
14079
+ fs15.writeFileSync(target4, text7, "utf8");
14080
+ const n = text7 === "" ? 0 : text7.split("\n").length - 1;
14081
+ write(
14082
+ `Wrote ${labelsFile}: ${n} rows to label. Set "human" to "pass" or "fail", with "by" and "at", then run plune judge-check ${labelsFile}.
14083
+ `
14084
+ );
14085
+ return 0;
14086
+ }
14087
+ let text6;
14088
+ try {
14089
+ text6 = fs15.readFileSync(target4, "utf8");
14090
+ } catch {
14091
+ throw new JudgeCheckError(`cannot read the labels ${labelsFile}: --init writes one from the run`);
14092
+ }
14093
+ const options = {};
14094
+ const check5 = number("--check", flags2.check, 1, Number.MAX_SAFE_INTEGER);
14095
+ if (check5 !== void 0) {
14096
+ if (!Number.isInteger(check5)) throw new JudgeCheckError(`--check is a whole number, not ${flags2.check}`);
14097
+ options.check = check5;
14098
+ }
14099
+ const minKappa = number("--min-kappa", flags2.minKappa, -1, 1);
14100
+ if (minKappa !== void 0) options.minKappa = minKappa;
14101
+ const width = number("--max-interval-width", flags2.maxIntervalWidth, 0, 2);
14102
+ if (width !== void 0) options.maxIntervalWidth = width;
14103
+ if (flags2.eval !== void 0) options.evalId = flags2.eval;
14104
+ const report = judgeCheck(run, parseLabels(text6), options);
14105
+ write(formatJudgeCheck(report, options.minKappa));
14106
+ return report.exitCode;
14107
+ }
14108
+ var fs15, path18;
14109
+ var init_judge_check = __esm({
14110
+ "src/cli/commands/judge-check.ts"() {
14111
+ "use strict";
14112
+ init_cjs_shims();
14113
+ fs15 = __toESM(require("fs"), 1);
14114
+ path18 = __toESM(require("path"), 1);
14115
+ init_check();
14116
+ init_labels();
14117
+ init_run_result_schema();
14118
+ }
14119
+ });
14120
+
13638
14121
  // src/config/init/wizard.ts
13639
14122
  async function runInitWizard(cwd) {
13640
14123
  if (!process.stdin.isTTY) {
@@ -13673,8 +14156,8 @@ async function runInitWizard(cwd) {
13673
14156
  process.exit(1);
13674
14157
  return;
13675
14158
  }
13676
- const outputPath = path18.join(cwd, "plune.yaml");
13677
- if (fs15.existsSync(outputPath)) {
14159
+ const outputPath = path19.join(cwd, "plune.yaml");
14160
+ if (fs16.existsSync(outputPath)) {
13678
14161
  const overwrite = await clack.confirm({
13679
14162
  message: "plune.yaml already exists. Overwrite?"
13680
14163
  });
@@ -13714,18 +14197,18 @@ async function runInitWizard(cwd) {
13714
14197
  `;
13715
14198
  const spin = clack.spinner();
13716
14199
  spin.start("Writing plune.yaml\u2026");
13717
- fs15.writeFileSync(outputPath, header3 + "\n" + (0, import_yaml3.stringify)(config), "utf8");
14200
+ fs16.writeFileSync(outputPath, header3 + "\n" + (0, import_yaml3.stringify)(config), "utf8");
13718
14201
  spin.stop("plune.yaml created!");
13719
14202
  clack.outro("plune.yaml is ready.");
13720
14203
  }
13721
- var clack, fs15, path18, import_yaml3;
14204
+ var clack, fs16, path19, import_yaml3;
13722
14205
  var init_wizard = __esm({
13723
14206
  "src/config/init/wizard.ts"() {
13724
14207
  "use strict";
13725
14208
  init_cjs_shims();
13726
14209
  clack = __toESM(require("@clack/prompts"), 1);
13727
- fs15 = __toESM(require("fs"), 1);
13728
- path18 = __toESM(require("path"), 1);
14210
+ fs16 = __toESM(require("fs"), 1);
14211
+ path19 = __toESM(require("path"), 1);
13729
14212
  import_yaml3 = require("yaml");
13730
14213
  init_errors();
13731
14214
  }
@@ -13733,21 +14216,21 @@ var init_wizard = __esm({
13733
14216
 
13734
14217
  // src/cli/templates/index.ts
13735
14218
  function writeTemplateFile(cwd, rel, content, force) {
13736
- const target4 = path19.join(cwd, rel);
13737
- if (!force && fs16.existsSync(target4)) {
14219
+ const target4 = path20.join(cwd, rel);
14220
+ if (!force && fs17.existsSync(target4)) {
13738
14221
  return "skipped";
13739
14222
  }
13740
- fs16.mkdirSync(path19.dirname(target4), { recursive: true });
13741
- fs16.writeFileSync(target4, content, "utf8");
14223
+ fs17.mkdirSync(path20.dirname(target4), { recursive: true });
14224
+ fs17.writeFileSync(target4, content, "utf8");
13742
14225
  return "written";
13743
14226
  }
13744
- var fs16, path19, PROVIDER_KEY_VARS, ENV_EXAMPLE_TPL, EXAMPLE_JSONL_TPL, PLUNE_YAML_TPL;
14227
+ var fs17, path20, PROVIDER_KEY_VARS, ENV_EXAMPLE_TPL, EXAMPLE_JSONL_TPL, PLUNE_YAML_TPL;
13745
14228
  var init_templates = __esm({
13746
14229
  "src/cli/templates/index.ts"() {
13747
14230
  "use strict";
13748
14231
  init_cjs_shims();
13749
- fs16 = __toESM(require("fs"), 1);
13750
- path19 = __toESM(require("path"), 1);
14232
+ fs17 = __toESM(require("fs"), 1);
14233
+ path20 = __toESM(require("path"), 1);
13751
14234
  PROVIDER_KEY_VARS = {
13752
14235
  anthropic: "ANTHROPIC_API_KEY",
13753
14236
  openai: "OPENAI_API_KEY",
@@ -13785,10 +14268,355 @@ evals:
13785
14268
  }
13786
14269
  });
13787
14270
 
14271
+ // src/config/init/from-openai-eval.ts
14272
+ var from_openai_eval_exports = {};
14273
+ __export(from_openai_eval_exports, {
14274
+ OpenAiEvalImportError: () => OpenAiEvalImportError,
14275
+ convertOpenAiEval: () => convertOpenAiEval,
14276
+ formatReport: () => formatReport2
14277
+ });
14278
+ function rewriteItemRefs(text6, prefix, seen, bad) {
14279
+ return text6.replace(ITEM_REF, (match, name) => {
14280
+ if (!FLAT.test(name)) {
14281
+ bad.add(name);
14282
+ return match;
14283
+ }
14284
+ seen.add(name);
14285
+ return `{{${prefix}${name}}}`;
14286
+ });
14287
+ }
14288
+ function hasNonText(messages) {
14289
+ const nonText = (content) => Array.isArray(content) ? content.some(nonText) : isObj2(content) && typeof content.text !== "string";
14290
+ return Array.isArray(messages) && messages.some((m) => isObj2(m) && nonText(m.content));
14291
+ }
14292
+ function textOf2(content) {
14293
+ if (typeof content === "string") return content;
14294
+ if (Array.isArray(content))
14295
+ return content.map(textOf2).filter((t) => t !== "").join("\n");
14296
+ if (isObj2(content) && typeof content.text === "string") return content.text;
14297
+ return "";
14298
+ }
14299
+ function joinMessages(messages, keep = () => true) {
14300
+ if (!Array.isArray(messages)) return "";
14301
+ return messages.map((m) => isObj2(m) ? textOf2(m.content) : "").filter((t) => t !== "" && keep(t)).join("\n\n");
14302
+ }
14303
+ function slug(name) {
14304
+ const s = typeof name === "string" ? name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") : "";
14305
+ return s === "" ? "imported-eval" : s;
14306
+ }
14307
+ function criteriaOf(grader, seen, bad) {
14308
+ const more = (text6) => text6.replace(SAMPLE_REF, "").trim() !== "";
14309
+ return rewriteItemRefs(joinMessages(grader.input, more), "vars.", seen, bad).replace(
14310
+ SAMPLE_REF,
14311
+ "the OUTPUT"
14312
+ );
14313
+ }
14314
+ function judgeProvider(grader) {
14315
+ return typeof grader.model === "string" && grader.model !== "" ? { provider: { type: "openai", model: grader.model } } : {};
14316
+ }
14317
+ function convertGrader(grader, seen) {
14318
+ const type = typeof grader.type === "string" ? grader.type : "unknown";
14319
+ const subject2 = `${typeof grader.name === "string" ? grader.name : "(no name)"} [${type}]`;
14320
+ const skip = (note2) => ({
14321
+ line: { status: "not converted", subject: subject2, note: note2 }
14322
+ });
14323
+ if (type === "string_check" || type === "text_similarity") {
14324
+ if (typeof grader.input !== "string" || !OUTPUT_TEXT.test(grader.input.trim())) {
14325
+ return skip(
14326
+ `its input is ${JSON.stringify(grader.input)}; a check here reads the model's text answer ({{ sample.output_text }}) only`
14327
+ );
14328
+ }
14329
+ if (typeof grader.reference !== "string") return skip("it has no reference text");
14330
+ if (grader.reference === "" && !(type === "string_check" && grader.operation === "eq"))
14331
+ return skip("its reference is empty");
14332
+ if (SAMPLE_REF.test(grader.reference)) {
14333
+ SAMPLE_REF.lastIndex = 0;
14334
+ return skip(
14335
+ "its reference reads the model sample; a check here compares with the row or a fixed text"
14336
+ );
14337
+ }
14338
+ const local = /* @__PURE__ */ new Set();
14339
+ const bad = /* @__PURE__ */ new Set();
14340
+ const reference = rewriteItemRefs(grader.reference, "vars.", local, bad);
14341
+ if (bad.size > 0) return skip(`its reference points at ${badRefs(bad)}: ${NOT_FLAT}`);
14342
+ const ok2 = (assertion, status2, note2) => {
14343
+ local.forEach((n) => seen.add(n));
14344
+ return { assertion, line: { status: status2, subject: subject2, note: note2 } };
14345
+ };
14346
+ if (type === "string_check") {
14347
+ switch (grader.operation) {
14348
+ case "eq":
14349
+ return ok2({ type: "exact-match", value: reference }, "converted", "exact-match");
14350
+ case "like":
14351
+ return ok2({ type: "contains", value: reference }, "converted", "contains");
14352
+ case "ilike":
14353
+ return ok2(
14354
+ { type: "contains", value: reference, ignore_case: true },
14355
+ "converted",
14356
+ "contains, ignore_case"
14357
+ );
14358
+ default:
14359
+ return skip(
14360
+ `operation ${JSON.stringify(grader.operation)} has no check here (there is no negated check)`
14361
+ );
14362
+ }
14363
+ }
14364
+ if (grader.evaluation_metric !== "cosine") {
14365
+ return skip(
14366
+ `metric ${JSON.stringify(grader.evaluation_metric)} has no check here; only cosine has one (semantic-similarity)`
14367
+ );
14368
+ }
14369
+ const t = grader.pass_threshold;
14370
+ const inRange = typeof t === "number" && t >= 0 && t <= 1;
14371
+ return ok2(
14372
+ { type: "semantic-similarity", reference, ...inRange ? { threshold: t } : {} },
14373
+ "approximate",
14374
+ "semantic-similarity: the embedding model is a different, local one, so run it and look at the threshold again" + (t !== void 0 && !inRange ? `; pass_threshold ${JSON.stringify(t)} is not between 0 and 1 and was left out` : "")
14375
+ );
14376
+ }
14377
+ if (type === "score_model" || type === "label_model") {
14378
+ const local = /* @__PURE__ */ new Set();
14379
+ const bad = /* @__PURE__ */ new Set();
14380
+ const criteria = criteriaOf(grader, local, bad);
14381
+ if (bad.size > 0) return skip(`its messages point at ${badRefs(bad)}: ${NOT_FLAT}`);
14382
+ local.forEach((n) => seen.add(n));
14383
+ const parts = hasNonText(grader.input) ? "; parts of its messages that are not text were left out" : "";
14384
+ if (type === "label_model") return labelModel(grader, criteria, subject2, parts);
14385
+ if (criteria === "") return skip("its messages hold no text");
14386
+ const range = Array.isArray(grader.range) ? grader.range : [0, 1];
14387
+ const [min, max] = [range[0], range[1]];
14388
+ const t = grader.pass_threshold;
14389
+ let pass2 = {};
14390
+ let scale = "no pass_threshold in the grader, so the default of llm-judge applies";
14391
+ if (typeof t === "number" && typeof min === "number" && typeof max === "number" && max > min) {
14392
+ const scaled = Math.min(1, Math.max(0, (t - min) / (max - min)));
14393
+ pass2 = { pass_threshold: Number(scaled.toFixed(4)) };
14394
+ scale = `pass_threshold ${t} on ${min}..${max} became ${pass2.pass_threshold} on 0..1`;
14395
+ } else if (t !== void 0) {
14396
+ scale = `pass_threshold ${JSON.stringify(t)} could not be rescaled from the range ${JSON.stringify(grader.range)} and was left out, so the default of llm-judge applies`;
14397
+ }
14398
+ return {
14399
+ assertion: { type: "llm-judge", criteria, ...pass2, ...judgeProvider(grader) },
14400
+ line: {
14401
+ status: "approximate",
14402
+ subject: subject2,
14403
+ note: `llm-judge: the grader's messages are the criteria and the judge scores 0..1; ${scale}${parts}`
14404
+ }
14405
+ };
14406
+ }
14407
+ if (type === "python") return skip("a Python grader runs code; no check here runs code");
14408
+ return skip("this grader type has no check here");
14409
+ }
14410
+ function labelModel(grader, text6, subject2, parts) {
14411
+ const skip = (note2) => ({
14412
+ line: { status: "not converted", subject: subject2, note: note2 }
14413
+ });
14414
+ const labels = Array.isArray(grader.labels) ? grader.labels.filter((l) => typeof l === "string") : [];
14415
+ const passing = Array.isArray(grader.passing_labels) ? grader.passing_labels.filter((l) => typeof l === "string") : [];
14416
+ if (labels.length === 0 || passing.length === 0)
14417
+ return skip("it has no labels or no passing labels");
14418
+ const rule = `Pick one label for the OUTPUT from: ${labels.join(", ")}. Score 1 if the label is one of: ${passing.join(", ")}. Otherwise score 0.`;
14419
+ return {
14420
+ assertion: {
14421
+ type: "llm-judge",
14422
+ criteria: text6 === "" ? rule : `${text6}
14423
+
14424
+ ${rule}`,
14425
+ ...judgeProvider(grader)
14426
+ },
14427
+ line: {
14428
+ status: "approximate",
14429
+ subject: subject2,
14430
+ note: `llm-judge: the judge gives a score, 1 for a passing label, in place of the label itself${parts}`
14431
+ }
14432
+ };
14433
+ }
14434
+ function convertRows(items2, report) {
14435
+ const asText = /* @__PURE__ */ new Set();
14436
+ const rows = items2.map((raw, i) => {
14437
+ const item = isObj2(raw) && "item" in raw ? raw.item : raw;
14438
+ if (!isObj2(item)) throw new OpenAiEvalImportError(`test data row ${i + 1} is not an object`);
14439
+ const vars = Object.fromEntries(
14440
+ Object.entries(item).map(([key, value2]) => {
14441
+ if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean")
14442
+ return [key, value2];
14443
+ asText.add(key);
14444
+ return [key, JSON.stringify(value2)];
14445
+ })
14446
+ );
14447
+ return { vars };
14448
+ });
14449
+ if (asText.size > 0) {
14450
+ report.push({
14451
+ status: "check",
14452
+ subject: "test data",
14453
+ note: `written as JSON text, as a row value here is a string, a number or a boolean: ${[...asText].sort().join(", ")}`
14454
+ });
14455
+ }
14456
+ return rows;
14457
+ }
14458
+ function parseJsonl(text6) {
14459
+ const out = [];
14460
+ text6.split(/\r?\n/).forEach((line, i) => {
14461
+ if (line.trim() === "") return;
14462
+ try {
14463
+ out.push(JSON.parse(line));
14464
+ } catch {
14465
+ throw new OpenAiEvalImportError(`test data line ${i + 1} is not JSON`);
14466
+ }
14467
+ });
14468
+ return out;
14469
+ }
14470
+ function convertOpenAiEval({ evalObject, run, rows }) {
14471
+ if (!isObj2(evalObject) || !Array.isArray(evalObject.testing_criteria)) {
14472
+ throw new OpenAiEvalImportError(
14473
+ "the eval file is not an eval object: it has no testing_criteria list (save the answer of GET /v1/evals/{eval_id})"
14474
+ );
14475
+ }
14476
+ if (run !== void 0 && !isObj2(run))
14477
+ throw new OpenAiEvalImportError("the run file is not a run object");
14478
+ const id2 = slug(evalObject.name);
14479
+ const report = [];
14480
+ const seen = /* @__PURE__ */ new Set();
14481
+ const assertions = [];
14482
+ for (const grader of evalObject.testing_criteria) {
14483
+ const { assertion, line } = convertGrader(isObj2(grader) ? grader : {}, seen);
14484
+ if (assertion !== void 0) assertions.push(assertion);
14485
+ report.push(line);
14486
+ }
14487
+ if (assertions.length === 0) {
14488
+ report.push({
14489
+ status: "check",
14490
+ subject: "checks",
14491
+ note: "no grader was converted: the eval has no checks until you add some"
14492
+ });
14493
+ }
14494
+ const source = isObj2(run) && isObj2(run.data_source) ? run.data_source : {};
14495
+ const template = isObj2(source.input_messages) ? source.input_messages.template : void 0;
14496
+ const count6 = Array.isArray(template) ? template.length : 0;
14497
+ const inPrompt = /* @__PURE__ */ new Set();
14498
+ let prompt5 = rewriteItemRefs(joinMessages(template), "", inPrompt, /* @__PURE__ */ new Set());
14499
+ inPrompt.forEach((n) => seen.add(n));
14500
+ const left = [...new Set(prompt5.match(ANY_REF) ?? [])].filter(
14501
+ (m) => !inPrompt.has(m.slice(2, -2))
14502
+ );
14503
+ if (left.length > 0) {
14504
+ report.push({
14505
+ status: "check",
14506
+ subject: "prompt",
14507
+ note: `it still holds ${left.join(", ")}, which is not a field of a row: plune run refuses the prompt until you change it`
14508
+ });
14509
+ }
14510
+ if (hasNonText(template)) {
14511
+ report.push({
14512
+ status: "check",
14513
+ subject: "prompt",
14514
+ note: "parts of its messages that are not text were left out"
14515
+ });
14516
+ }
14517
+ const sampling = isObj2(source.sampling_params) ? Object.keys(source.sampling_params).sort() : [];
14518
+ if (sampling.length > 0) {
14519
+ report.push({
14520
+ status: "check",
14521
+ subject: "model",
14522
+ note: `the sampling parameters of the run are not carried over: ${sampling.join(", ")}`
14523
+ });
14524
+ }
14525
+ if (prompt5 === "") {
14526
+ prompt5 = "Replace this line with your prompt.";
14527
+ report.push({
14528
+ status: "check",
14529
+ subject: "prompt",
14530
+ note: "no prompt template was found (give a run with --run): the prompt is a placeholder"
14531
+ });
14532
+ } else if (count6 > 1) {
14533
+ report.push({
14534
+ status: "check",
14535
+ subject: "prompt",
14536
+ note: `${count6} messages were joined into one prompt; their roles are not kept`
14537
+ });
14538
+ }
14539
+ let model = typeof source.model === "string" && source.model !== "" ? source.model : void 0;
14540
+ if (model === void 0) {
14541
+ model = "gpt-4o";
14542
+ report.push({
14543
+ status: "check",
14544
+ subject: "model",
14545
+ note: "no model was found (give a run with --run): it is set to gpt-4o"
14546
+ });
14547
+ }
14548
+ const inline = isObj2(source.source) && Array.isArray(source.source.content) ? source.source.content : void 0;
14549
+ const fromFile = rows !== void 0 ? parseJsonl(rows) : [];
14550
+ const items2 = fromFile.length > 0 ? fromFile : inline;
14551
+ let dataset;
14552
+ let datasetField;
14553
+ if (items2 !== void 0 && items2.length > 0) {
14554
+ const path26 = `datasets/${id2}.jsonl`;
14555
+ dataset = {
14556
+ path: path26,
14557
+ jsonl: convertRows(items2, report).map((r) => JSON.stringify(r)).join("\n") + "\n"
14558
+ };
14559
+ datasetField = `./${path26}`;
14560
+ } else {
14561
+ const vars = Object.fromEntries([...seen].sort().map((n) => [n, "replace me"]));
14562
+ datasetField = { examples: [{ vars }] };
14563
+ report.push({
14564
+ status: "check",
14565
+ subject: "test data",
14566
+ note: rows !== void 0 ? "the test data file holds no rows: the dataset is one placeholder row" : "no test data was found (give the file with --data): the dataset is one placeholder row"
14567
+ });
14568
+ }
14569
+ const config = {
14570
+ version: 1,
14571
+ provider: { type: "openai", model },
14572
+ evals: [
14573
+ {
14574
+ id: id2,
14575
+ ...typeof evalObject.name === "string" ? { description: evalObject.name } : {},
14576
+ prompt: prompt5,
14577
+ dataset: datasetField,
14578
+ assertions
14579
+ }
14580
+ ]
14581
+ };
14582
+ const header3 = "# Plune configuration, written by `plune init --from-openai-eval`. Read the report it printed.\n";
14583
+ return { yaml: header3 + (0, import_yaml4.stringify)(config), ...dataset ? { dataset } : {}, report };
14584
+ }
14585
+ function formatReport2(report) {
14586
+ const count6 = (s) => report.filter((l) => l.status === s).length;
14587
+ return report.map((l) => ` ${l.status.padEnd(13)} ${l.subject}: ${l.note}`).join("\n") + `
14588
+
14589
+ ${count6("converted")} converted \xB7 ${count6("approximate")} approximate \xB7 ${count6("not converted")} not converted
14590
+ `;
14591
+ }
14592
+ var import_yaml4, OpenAiEvalImportError, isObj2, ITEM_REF, ANY_REF, FLAT, NOT_FLAT, SAMPLE_REF, OUTPUT_TEXT, badRefs;
14593
+ var init_from_openai_eval = __esm({
14594
+ "src/config/init/from-openai-eval.ts"() {
14595
+ "use strict";
14596
+ init_cjs_shims();
14597
+ import_yaml4 = require("yaml");
14598
+ OpenAiEvalImportError = class extends Error {
14599
+ constructor(message2) {
14600
+ super(message2);
14601
+ this.name = "OpenAiEvalImportError";
14602
+ }
14603
+ };
14604
+ isObj2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
14605
+ ITEM_REF = /\{\{\s*item\.([^{}]*?)\s*\}\}/g;
14606
+ ANY_REF = /\{\{[^{}]*\}\}/g;
14607
+ FLAT = /^\w+$/;
14608
+ NOT_FLAT = "a row here is flat, and a field a placeholder names is letters, digits and _";
14609
+ SAMPLE_REF = /\{\{\s*sample\.[\w.]+\s*\}\}/g;
14610
+ OUTPUT_TEXT = /^\{\{\s*sample\.output_text\s*\}\}$/;
14611
+ badRefs = (bad) => [...bad].sort().map((n) => `{{ item.${n} }}`).join(", ");
14612
+ }
14613
+ });
14614
+
13788
14615
  // src/cli/commands/init.ts
13789
14616
  var init_exports = {};
13790
14617
  __export(init_exports, {
13791
14618
  initCommand: () => initCommand,
14619
+ initFromOpenAiEval: () => initFromOpenAiEval,
13792
14620
  nextSteps: () => nextSteps
13793
14621
  });
13794
14622
  function reportWrite(cwd, rel, content, force) {
@@ -13815,13 +14643,46 @@ function nextSteps(keyVar) {
13815
14643
  }
13816
14644
  function keyVarOf(cwd) {
13817
14645
  try {
13818
- const cfg = (0, import_yaml4.parse)(fs17.readFileSync(path20.join(cwd, "plune.yaml"), "utf8"));
14646
+ const cfg = (0, import_yaml5.parse)(fs18.readFileSync(path21.join(cwd, "plune.yaml"), "utf8"));
13819
14647
  const type = cfg?.provider?.type;
13820
14648
  return typeof type === "string" && Object.hasOwn(PROVIDER_KEY_VARS, type) ? PROVIDER_KEY_VARS[type] : void 0;
13821
14649
  } catch {
13822
14650
  return void 0;
13823
14651
  }
13824
14652
  }
14653
+ async function initFromOpenAiEval(options) {
14654
+ const { cwd, force } = options;
14655
+ const { convertOpenAiEval: convertOpenAiEval2, formatReport: formatReport4, OpenAiEvalImportError: OpenAiEvalImportError2 } = await Promise.resolve().then(() => (init_from_openai_eval(), from_openai_eval_exports));
14656
+ const read = (file) => {
14657
+ try {
14658
+ return fs18.readFileSync(path21.resolve(cwd, file), "utf8").replace(/^/, "");
14659
+ } catch (err) {
14660
+ throw new OpenAiEvalImportError2(`cannot read ${file}: ${err.message}`);
14661
+ }
14662
+ };
14663
+ const json2 = (file) => {
14664
+ try {
14665
+ return JSON.parse(read(file));
14666
+ } catch (err) {
14667
+ if (err instanceof OpenAiEvalImportError2) throw err;
14668
+ throw new OpenAiEvalImportError2(`${file} is not JSON`);
14669
+ }
14670
+ };
14671
+ const converted = convertOpenAiEval2({
14672
+ evalObject: json2(options.evalPath),
14673
+ ...options.runPath !== void 0 ? { run: json2(options.runPath) } : {},
14674
+ ...options.dataPath !== void 0 ? { rows: read(options.dataPath) } : {}
14675
+ });
14676
+ try {
14677
+ reportWrite(cwd, "plune.yaml", converted.yaml, force);
14678
+ if (converted.dataset) reportWrite(cwd, converted.dataset.path, converted.dataset.jsonl, force);
14679
+ reportWrite(cwd, ".env.example", ENV_EXAMPLE_TPL, force);
14680
+ } catch (err) {
14681
+ throw new OpenAiEvalImportError2(`cannot write the files: ${err.message}`);
14682
+ }
14683
+ process.stdout.write("\n" + formatReport4(converted.report));
14684
+ process.stdout.write(nextSteps(keyVarOf(cwd)));
14685
+ }
13825
14686
  async function initCommand({ cwd, force, yes = false }) {
13826
14687
  if (yes) {
13827
14688
  reportWrite(cwd, "plune.yaml", PLUNE_YAML_TPL, force);
@@ -13833,14 +14694,14 @@ async function initCommand({ cwd, force, yes = false }) {
13833
14694
  }
13834
14695
  process.stdout.write(nextSteps(keyVarOf(cwd)));
13835
14696
  }
13836
- var fs17, path20, import_yaml4, TEMPLATES;
14697
+ var fs18, path21, import_yaml5, TEMPLATES;
13837
14698
  var init_init = __esm({
13838
14699
  "src/cli/commands/init.ts"() {
13839
14700
  "use strict";
13840
14701
  init_cjs_shims();
13841
- fs17 = __toESM(require("fs"), 1);
13842
- path20 = __toESM(require("path"), 1);
13843
- import_yaml4 = require("yaml");
14702
+ fs18 = __toESM(require("fs"), 1);
14703
+ path21 = __toESM(require("path"), 1);
14704
+ import_yaml5 = require("yaml");
13844
14705
  init_wizard();
13845
14706
  init_templates();
13846
14707
  TEMPLATES = [
@@ -14870,7 +15731,7 @@ function createPluneToolExecutor(opts) {
14870
15731
  },
14871
15732
  async plune_get(i) {
14872
15733
  const route = { "test-case": "/v1/test-cases/:id", run: "/v1/runs/:id", "review-item": "/v1/review-items/:id" }[str2(i["kind"])];
14873
- const res = await call2({ method: "GET", path: path21(route, str2(i["id"])) });
15734
+ const res = await call2({ method: "GET", path: path22(route, str2(i["id"])) });
14874
15735
  return { kind: str2(i["kind"]), item: asRecord(res.body) };
14875
15736
  },
14876
15737
  async plune_cases_search(i) {
@@ -14940,12 +15801,12 @@ function createPluneToolExecutor(opts) {
14940
15801
  const { dry_run, projectId: projectId2, ...body } = i;
14941
15802
  const project = projectId2 ?? opts.projectId;
14942
15803
  if (project === void 0) return fail2("invalid_input", NO_PROJECT);
14943
- return write({ method: "POST", path: path21("/v1/projects/:id/case-generations", project), body: withoutUndefined(body) }, dry_run);
15804
+ return write({ method: "POST", path: path22("/v1/projects/:id/case-generations", project), body: withoutUndefined(body) }, dry_run);
14944
15805
  },
14945
15806
  async plune_cases_generation_get(i) {
14946
15807
  const project = i["projectId"] ?? opts.projectId;
14947
15808
  if (project === void 0) return fail2("invalid_input", NO_PROJECT);
14948
- const res = await call2({ method: "GET", path: path21("/v1/projects/:id/case-generations/:generationId", project, str2(i["generationId"])) });
15809
+ const res = await call2({ method: "GET", path: path22("/v1/projects/:id/case-generations/:generationId", project, str2(i["generationId"])) });
14949
15810
  return { generation: asRecord(res.body) };
14950
15811
  },
14951
15812
  async plune_mission_create(i) {
@@ -14953,18 +15814,18 @@ function createPluneToolExecutor(opts) {
14953
15814
  return write({ method: "POST", path: "/v1/missions", body: withoutUndefined(body) }, dry_run);
14954
15815
  },
14955
15816
  async plune_mission_get(i) {
14956
- const res = await call2({ method: "GET", path: path21("/v1/missions/:id", str2(i["missionId"])) });
15817
+ const res = await call2({ method: "GET", path: path22("/v1/missions/:id", str2(i["missionId"])) });
14957
15818
  return { mission: asRecord(res.body) };
14958
15819
  },
14959
15820
  async plune_mission_update(i) {
14960
15821
  const { dry_run, missionId: missionId2, ...body } = i;
14961
- return write({ method: "PATCH", path: path21("/v1/missions/:id", str2(missionId2)), body: withoutUndefined(body) }, dry_run);
15822
+ return write({ method: "PATCH", path: path22("/v1/missions/:id", str2(missionId2)), body: withoutUndefined(body) }, dry_run);
14962
15823
  },
14963
15824
  async plune_source_add(i) {
14964
15825
  const parsed4 = (i["kind"] === "file" ? fileSource : linkSource).safeParse(withoutUndefined(i));
14965
15826
  if (!parsed4.success) return fail2("invalid_input", `The input does not fit: ${zodMessage(parsed4.error)}`);
14966
15827
  const { dry_run, missionId: missionId2, kind: kind2, ...rest } = parsed4.data;
14967
- const req = kind2 === "file" ? { method: "POST", path: path21("/v1/missions/:id/files", str2(missionId2)), body: withoutUndefined(rest) } : { method: "POST", path: path21("/v1/missions/:id/sources", str2(missionId2)), body: withoutUndefined({ kind: kind2, ...rest }) };
15828
+ const req = kind2 === "file" ? { method: "POST", path: path22("/v1/missions/:id/files", str2(missionId2)), body: withoutUndefined(rest) } : { method: "POST", path: path22("/v1/missions/:id/sources", str2(missionId2)), body: withoutUndefined({ kind: kind2, ...rest }) };
14968
15829
  return write(req, dry_run);
14969
15830
  },
14970
15831
  async plune_question_ask(i) {
@@ -14986,7 +15847,7 @@ function createPluneToolExecutor(opts) {
14986
15847
  return { questions, nextCursor: cursorOf(body["nextCursor"]) };
14987
15848
  },
14988
15849
  async plune_strategy_propose(i) {
14989
- const req = { method: "POST", path: path21("/v1/missions/:id/strategy", str2(i["missionId"])), body: i["content"] };
15850
+ const req = { method: "POST", path: path22("/v1/missions/:id/strategy", str2(i["missionId"])), body: i["content"] };
14990
15851
  if (i["dry_run"] === true) {
14991
15852
  try {
14992
15853
  const res = await call2({ ...req, path: `${req.path}/check` });
@@ -14996,10 +15857,10 @@ function createPluneToolExecutor(opts) {
14996
15857
  return { dryRun: true, checked: false, request: planned(req) };
14997
15858
  }
14998
15859
  }
14999
- return write({ method: "POST", path: path21("/v1/missions/:id/strategy", str2(i["missionId"])), body: i["content"] }, i["dry_run"]);
15860
+ return write({ method: "POST", path: path22("/v1/missions/:id/strategy", str2(i["missionId"])), body: i["content"] }, i["dry_run"]);
15000
15861
  },
15001
15862
  async plune_report_request(i) {
15002
- return write({ method: "POST", path: path21("/v1/missions/:id/report", str2(i["missionId"])), body: {} }, i["dry_run"]);
15863
+ return write({ method: "POST", path: path22("/v1/missions/:id/report", str2(i["missionId"])), body: {} }, i["dry_run"]);
15003
15864
  },
15004
15865
  async plune_discover_tools(i) {
15005
15866
  const names = i["names"] ?? [];
@@ -15023,7 +15884,7 @@ function createPluneToolExecutor(opts) {
15023
15884
  async plune_cases_update(i) {
15024
15885
  const cases = i["cases"];
15025
15886
  return batch(
15026
- cases.map((c) => ({ method: "PATCH", path: path21("/v1/test-cases/:id", c.id), body: c.changes })),
15887
+ cases.map((c) => ({ method: "PATCH", path: path22("/v1/test-cases/:id", c.id), body: c.changes })),
15027
15888
  i["dry_run"],
15028
15889
  (_b, n) => cases[n]?.id
15029
15890
  );
@@ -15035,7 +15896,7 @@ function createPluneToolExecutor(opts) {
15035
15896
  const results4 = i["results"];
15036
15897
  const req = {
15037
15898
  method: "POST",
15038
- path: path21("/v1/runs/:id/results", str2(i["runId"])),
15899
+ path: path22("/v1/runs/:id/results", str2(i["runId"])),
15039
15900
  body: withoutUndefined({ results: results4, combination: i["combination"], configuration: i["configuration"] })
15040
15901
  };
15041
15902
  if (i["dry_run"] === true) return { dryRun: true, requested: results4.length, applied: 0, requests: [planned(req)] };
@@ -15110,7 +15971,7 @@ function createPluneToolExecutor(opts) {
15110
15971
  }
15111
15972
  };
15112
15973
  }
15113
- var import_node_crypto6, import_zod6, CONFIRM_TTL_MS, READ_ONLY_REFUSAL, NO_PROJECT, readScopeMessage, fail2, zodMessage, path21, withoutUndefined, asRecord, asArray, cursorOf, rawWrites;
15974
+ var import_node_crypto6, import_zod6, CONFIRM_TTL_MS, READ_ONLY_REFUSAL, NO_PROJECT, readScopeMessage, fail2, zodMessage, path22, withoutUndefined, asRecord, asArray, cursorOf, rawWrites;
15114
15975
  var init_execute = __esm({
15115
15976
  "src/mcp-tools/execute.ts"() {
15116
15977
  "use strict";
@@ -15129,7 +15990,7 @@ var init_execute = __esm({
15129
15990
  error: { code, message: message2, ...extra }
15130
15991
  });
15131
15992
  zodMessage = (error) => error.issues.map((i) => `${i.path.join(".") || "(input)"}: ${i.message}`).join("; ");
15132
- path21 = (template, ...ids) => {
15993
+ path22 = (template, ...ids) => {
15133
15994
  let i = 0;
15134
15995
  return template.replace(/:[a-z]+/gi, () => encodeURIComponent(ids[i++] ?? ""));
15135
15996
  };
@@ -15261,7 +16122,7 @@ function answeringParseErrors(answer) {
15261
16122
  async function serveMcpStdio(opts) {
15262
16123
  const input = process.stdin.pipe(answeringParseErrors((line) => process.stdout.write(line)));
15263
16124
  const transport = new import_stdio2.StdioServerTransport(input, process.stdout);
15264
- await new Promise((resolve23) => {
16125
+ await new Promise((resolve25) => {
15265
16126
  (0, import_stdio2.serveStdio)((ctx) => createPluneMcpServer(opts, ctx.era), {
15266
16127
  transport,
15267
16128
  onerror: (error) => {
@@ -15279,7 +16140,7 @@ async function serveMcpStdio(opts) {
15279
16140
  const owned = transport.onclose;
15280
16141
  transport.onclose = () => {
15281
16142
  owned?.();
15282
- resolve23();
16143
+ resolve25();
15283
16144
  };
15284
16145
  });
15285
16146
  }
@@ -15412,7 +16273,7 @@ var init_run3 = __esm({
15412
16273
  now: () => import_node_perf_hooks2.performance.now(),
15413
16274
  after(ms) {
15414
16275
  let timer;
15415
- const done = new Promise((resolve23) => timer = setTimeout(resolve23, ms));
16276
+ const done = new Promise((resolve25) => timer = setTimeout(resolve25, ms));
15416
16277
  return { done, cancel: () => clearTimeout(timer) };
15417
16278
  }
15418
16279
  };
@@ -15695,10 +16556,10 @@ function schemaNodes(schema) {
15695
16556
  const children = [];
15696
16557
  for (const [name, p] of Object.entries(props(node.schema))) {
15697
16558
  if (!isRecord9(p)) continue;
15698
- const path25 = node.path === "" ? name : `${node.path}.${name}`;
16559
+ const path26 = node.path === "" ? name : `${node.path}.${name}`;
15699
16560
  const depth = node.depth + 1;
15700
- children.push({ path: path25, schema: p, kind: "param", depth });
15701
- if (isRecord9(p.items)) children.push({ path: `${path25}[]`, schema: p.items, kind: "items", depth: depth + 1 });
16561
+ children.push({ path: path26, schema: p, kind: "param", depth });
16562
+ if (isRecord9(p.items)) children.push({ path: `${path26}[]`, schema: p.items, kind: "items", depth: depth + 1 });
15702
16563
  }
15703
16564
  for (const child of children.reverse()) todo.push(child);
15704
16565
  }
@@ -17283,8 +18144,8 @@ var init_mcp_check = __esm({
17283
18144
 
17284
18145
  // src/mcp-testing/exceptions-file.ts
17285
18146
  function parseExceptionsFile(text6, name, today) {
17286
- const lines = new import_yaml5.LineCounter();
17287
- const doc = (0, import_yaml5.parseDocument)(text6, { lineCounter: lines });
18147
+ const lines = new import_yaml6.LineCounter();
18148
+ const doc = (0, import_yaml6.parseDocument)(text6, { lineCounter: lines });
17288
18149
  const lineOf = (node) => lines.linePos(node?.range?.[0] ?? 0).line;
17289
18150
  const problems = [];
17290
18151
  const fail3 = (node, message2) => problems.push(`${name}:${lineOf(node)}: ${message2}`);
@@ -17294,19 +18155,19 @@ function parseExceptionsFile(text6, name, today) {
17294
18155
  const expired = [];
17295
18156
  const root = doc.contents;
17296
18157
  if (problems.length === 0 && root !== null) {
17297
- const list3 = (0, import_yaml5.isMap)(root) ? root.get("ignore", true) : void 0;
17298
- if (!(0, import_yaml5.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml5.isSeq)(list3))
18158
+ const list3 = (0, import_yaml6.isMap)(root) ? root.get("ignore", true) : void 0;
18159
+ if (!(0, import_yaml6.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml6.isSeq)(list3))
17299
18160
  fail3(root, 'expected "ignore:" with a list of entries.');
17300
- else if ((0, import_yaml5.isSeq)(list3)) {
18161
+ else if ((0, import_yaml6.isSeq)(list3)) {
17301
18162
  for (const item of list3.items) {
17302
- if (!(0, import_yaml5.isMap)(item)) {
18163
+ if (!(0, import_yaml6.isMap)(item)) {
17303
18164
  fail3(item, "an entry needs rule and reason.");
17304
18165
  continue;
17305
18166
  }
17306
18167
  const field = (key) => {
17307
- const pair = item.items.find((p) => (0, import_yaml5.isScalar)(p.key) && p.key.value === key);
18168
+ const pair = item.items.find((p) => (0, import_yaml6.isScalar)(p.key) && p.key.value === key);
17308
18169
  if (pair === void 0) return void 0;
17309
- const plain = (0, import_yaml5.isScalar)(pair.value) ? pair.value.value : pair.value;
18170
+ const plain = (0, import_yaml6.isScalar)(pair.value) ? pair.value.value : pair.value;
17310
18171
  if (plain !== null && plain !== void 0 && typeof plain !== "string")
17311
18172
  fail3(
17312
18173
  pair.key,
@@ -17353,12 +18214,12 @@ function parseExceptionsFile(text6, name, today) {
17353
18214
  if (problems.length > 0) throw new ExceptionsFileError(problems.join("\n"));
17354
18215
  return { active, expired };
17355
18216
  }
17356
- var import_yaml5, ExceptionsFileError, DATE2, isDate2;
18217
+ var import_yaml6, ExceptionsFileError, DATE2, isDate2;
17357
18218
  var init_exceptions_file = __esm({
17358
18219
  "src/mcp-testing/exceptions-file.ts"() {
17359
18220
  "use strict";
17360
18221
  init_cjs_shims();
17361
- import_yaml5 = require("yaml");
18222
+ import_yaml6 = require("yaml");
17362
18223
  init_failure_detail();
17363
18224
  init_exit_codes();
17364
18225
  ExceptionsFileError = class extends Error {
@@ -17515,13 +18376,13 @@ async function lint(flags2, server2, io, rawOut) {
17515
18376
  }
17516
18377
  function readExceptions(flag2, io) {
17517
18378
  const name = flag2 ?? DEFAULT_IGNORE_FILE;
17518
- const path25 = (0, import_node_path7.resolve)(io.cwd, name);
17519
- if (!(0, import_node_fs12.existsSync)(path25)) {
18379
+ const path26 = (0, import_node_path7.resolve)(io.cwd, name);
18380
+ if (!(0, import_node_fs12.existsSync)(path26)) {
17520
18381
  if (flag2 !== void 0) throw new UsageError(`--ignore-file: ${name} does not exist.`);
17521
18382
  return void 0;
17522
18383
  }
17523
18384
  const today = io.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
17524
- return { name, ...parseExceptionsFile((0, import_node_fs12.readFileSync)(path25, "utf8"), name, today) };
18385
+ return { name, ...parseExceptionsFile((0, import_node_fs12.readFileSync)(path26, "utf8"), name, today) };
17525
18386
  }
17526
18387
  async function listTools(session2) {
17527
18388
  try {
@@ -17811,8 +18672,8 @@ async function pushSnapshot(snapshot, target4, token2, deps = {}) {
17811
18672
  sent,
17812
18673
  target4.serverId !== void 0 ? `MCP server '${serverId}'` : "the snapshot"
17813
18674
  );
17814
- const { number, hash, tools: tools2 } = sent.body;
17815
- if (typeof number !== "number" || !Number.isInteger(number) || typeof hash !== "string") {
18675
+ const { number: number2, hash, tools: tools2 } = sent.body;
18676
+ if (typeof number2 !== "number" || !Number.isInteger(number2) || typeof hash !== "string") {
17816
18677
  throw new SnapshotPushError(
17817
18678
  "other",
17818
18679
  "The platform answered, but not with a snapshot (no number or hash)."
@@ -17821,7 +18682,7 @@ async function pushSnapshot(snapshot, target4, token2, deps = {}) {
17821
18682
  return {
17822
18683
  serverId,
17823
18684
  ...target4.serverName !== void 0 ? { serverName: target4.serverName.trim() } : {},
17824
- number,
18685
+ number: number2,
17825
18686
  hash,
17826
18687
  tools: typeof tools2 === "number" ? tools2 : null,
17827
18688
  created: sent.status === 201,
@@ -18066,14 +18927,14 @@ async function listAll2(session2, method, key) {
18066
18927
  }
18067
18928
  return listing.items;
18068
18929
  }
18069
- function writeAtomically(path25, text6, shown4, flag2 = "--out") {
18930
+ function writeAtomically(path26, text6, shown4, flag2 = "--out") {
18070
18931
  const temporary = (0, import_node_path8.join)(
18071
- (0, import_node_path8.dirname)(path25),
18072
- `.${(0, import_node_path8.basename)(path25)}.${process.pid}.${(0, import_node_crypto7.randomBytes)(4).toString("hex")}.tmp`
18932
+ (0, import_node_path8.dirname)(path26),
18933
+ `.${(0, import_node_path8.basename)(path26)}.${process.pid}.${(0, import_node_crypto7.randomBytes)(4).toString("hex")}.tmp`
18073
18934
  );
18074
18935
  try {
18075
18936
  (0, import_node_fs13.writeFileSync)(temporary, text6, { flag: "wx" });
18076
- (0, import_node_fs13.renameSync)(temporary, path25);
18937
+ (0, import_node_fs13.renameSync)(temporary, path26);
18077
18938
  } catch (err) {
18078
18939
  (0, import_node_fs13.rmSync)(temporary, { force: true });
18079
18940
  const code = err.code ?? "an error";
@@ -18287,23 +19148,23 @@ function visible(s, max = EXCERPT) {
18287
19148
  }
18288
19149
  function descriptionTexts(snapshot) {
18289
19150
  const out = [];
18290
- const add = (surface, path25, v, key = false, stringParam = false) => {
18291
- if (typeof v === "string" && v !== "") out.push({ pointer: pointerOf(path25), surface, text: v, key, stringParam });
19151
+ const add = (surface, path26, v, key = false, stringParam = false) => {
19152
+ if (typeof v === "string" && v !== "") out.push({ pointer: pointerOf(path26), surface, text: v, key, stringParam });
18292
19153
  };
18293
- const schema = (path25, node) => {
18294
- if (typeof node === "string") add("tools", path25, node);
18295
- else if (Array.isArray(node)) node.forEach((v, i) => schema([...path25, i], v));
19154
+ const schema = (path26, node) => {
19155
+ if (typeof node === "string") add("tools", path26, node);
19156
+ else if (Array.isArray(node)) node.forEach((v, i) => schema([...path26, i], v));
18296
19157
  else if (isRecord12(node)) {
18297
- const param = path25.at(-2) === "properties" && hasStringType(node);
19158
+ const param = path26.at(-2) === "properties" && hasStringType(node);
18298
19159
  for (const [k, v] of Object.entries(node)) {
18299
- add("tools", [...path25, k], k, true);
18300
- if (k === "description" && typeof v === "string") add("tools", [...path25, k], v, false, param);
18301
- else schema([...path25, k], v);
19160
+ add("tools", [...path26, k], k, true);
19161
+ if (k === "description" && typeof v === "string") add("tools", [...path26, k], v, false, param);
19162
+ else schema([...path26, k], v);
18302
19163
  }
18303
19164
  }
18304
19165
  };
18305
- const fields = (surface, path25, entity2, names) => {
18306
- if (isRecord12(entity2)) for (const f of names) add(surface, [...path25, f], entity2[f]);
19166
+ const fields = (surface, path26, entity2, names) => {
19167
+ if (isRecord12(entity2)) for (const f of names) add(surface, [...path26, f], entity2[f]);
18307
19168
  };
18308
19169
  add("instructions", ["instructions"], snapshot.instructions);
18309
19170
  snapshot.tools?.forEach((t, i) => {
@@ -18564,7 +19425,7 @@ var init_descriptions = __esm({
18564
19425
  U = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
18565
19426
  SHOWN = /^[\p{L}\p{N}\p{P}\p{S} ]$/u;
18566
19427
  segment2 = (s) => typeof s === "number" ? String(s) : visible(s.replace(/~/g, "~0").replace(/\//g, "~1"), Infinity);
18567
- pointerOf = (path25) => `/${path25.map(segment2).join("/")}`;
19428
+ pointerOf = (path26) => `/${path26.map(segment2).join("/")}`;
18568
19429
  hasStringType = (schema) => schema["type"] === "string" || Array.isArray(schema["type"]) && schema["type"].includes("string");
18569
19430
  NAMES = {
18570
19431
  8234: "left-to-right embedding",
@@ -18961,14 +19822,14 @@ ${err.stderrTail.map((l) => ` ${l}
18961
19822
  throw err;
18962
19823
  }
18963
19824
  }
18964
- function readLock(path25, name, required) {
18965
- if (!(0, import_node_fs15.existsSync)(path25)) {
19825
+ function readLock(path26, name, required) {
19826
+ if (!(0, import_node_fs15.existsSync)(path26)) {
18966
19827
  if (required) throw new UsageError(`${name} does not exist; pin the server first with plune mcp pin.`);
18967
19828
  return emptyLock();
18968
19829
  }
18969
19830
  let text6;
18970
19831
  try {
18971
- text6 = (0, import_node_fs15.readFileSync)(path25, "utf8");
19832
+ text6 = (0, import_node_fs15.readFileSync)(path26, "utf8");
18972
19833
  } catch (err) {
18973
19834
  throw new UsageError(`${name}: cannot be read (${err.code ?? "an error"}).`);
18974
19835
  }
@@ -19295,12 +20156,12 @@ function hostFetch(target4, req, signal) {
19295
20156
  for (const [n, v] of Object.entries(target4.headers)) if (!given.has(n.toLowerCase())) headers.push(n, v);
19296
20157
  for (const [n, v] of req.headers) headers.push(n, v);
19297
20158
  const send3 = url.protocol === "https:" ? import_node_https2.request : import_node_http2.request;
19298
- return new Promise((resolve23, reject) => {
20159
+ return new Promise((resolve25, reject) => {
19299
20160
  const r = send3(url, { method: req.method, headers, signal }, (res) => {
19300
20161
  const pairs2 = [];
19301
20162
  for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) pairs2.push([res.rawHeaders[i], res.rawHeaders[i + 1]]);
19302
20163
  const nobody = res.statusCode === 204 || res.statusCode === 304;
19303
- resolve23(
20164
+ resolve25(
19304
20165
  new Response(nobody ? null : import_node_stream3.Readable.toWeb(res), {
19305
20166
  status: res.statusCode ?? 0,
19306
20167
  headers: pairs2
@@ -19461,14 +20322,14 @@ var init_raw_http = __esm({
19461
20322
  });
19462
20323
 
19463
20324
  // src/mcp-testing/conformance/checks/modern/meta.ts
19464
- function headerMarks(schema, path25 = [], inNames = false) {
19465
- if (Array.isArray(schema)) return schema.flatMap((s, i) => headerMarks(s, [...path25, String(i)]));
20325
+ function headerMarks(schema, path26 = [], inNames = false) {
20326
+ if (Array.isArray(schema)) return schema.flatMap((s, i) => headerMarks(s, [...path26, String(i)]));
19466
20327
  if (!isRecord15(schema)) return [];
19467
20328
  const marks = [];
19468
- if (!inNames && "x-mcp-header" in schema) marks.push({ path: path25, value: schema["x-mcp-header"], schema });
20329
+ if (!inNames && "x-mcp-header" in schema) marks.push({ path: path26, value: schema["x-mcp-header"], schema });
19469
20330
  for (const [k, v] of Object.entries(schema)) {
19470
20331
  if (!inNames && k === "x-mcp-header") continue;
19471
- marks.push(...headerMarks(v, [...path25, k], !inNames && k === "properties"));
20332
+ marks.push(...headerMarks(v, [...path26, k], !inNames && k === "properties"));
19472
20333
  }
19473
20334
  return marks;
19474
20335
  }
@@ -19505,7 +20366,7 @@ var init_meta = __esm({
19505
20366
  [META.capabilities]: {}
19506
20367
  });
19507
20368
  isRecord15 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
19508
- staticallyReachable = (path25) => path25.length > 0 && path25.length % 2 === 0 && path25.every((k, i) => i % 2 === 1 || k === "properties");
20369
+ staticallyReachable = (path26) => path26.length > 0 && path26.length % 2 === 0 && path26.every((k, i) => i % 2 === 1 || k === "properties");
19509
20370
  }
19510
20371
  });
19511
20372
 
@@ -19813,8 +20674,8 @@ function discoverPrm(ctx, challenge) {
19813
20674
  return prm;
19814
20675
  }
19815
20676
  }
19816
- const path25 = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
19817
- const urls = [.../* @__PURE__ */ new Set([`${url.origin}${WK_PRM}${path25}`, `${url.origin}${WK_PRM}`])];
20677
+ const path26 = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
20678
+ const urls = [.../* @__PURE__ */ new Set([`${url.origin}${WK_PRM}${path26}`, `${url.origin}${WK_PRM}`])];
19818
20679
  for (const u of urls) {
19819
20680
  const got2 = await getJson(ctx, u);
19820
20681
  prm.wellKnown.push(got2);
@@ -19834,14 +20695,14 @@ function discoverAs(ctx, issuer) {
19834
20695
  } catch {
19835
20696
  return { issuer, tried: [wrong(issuer, "it is not an absolute URL")], found: void 0 };
19836
20697
  }
19837
- const path25 = u.pathname === "/" ? "" : u.pathname.replace(/\/$/, "");
19838
- const urls = path25 === "" ? [
20698
+ const path26 = u.pathname === "/" ? "" : u.pathname.replace(/\/$/, "");
20699
+ const urls = path26 === "" ? [
19839
20700
  `${u.origin}/.well-known/oauth-authorization-server`,
19840
20701
  `${u.origin}/.well-known/openid-configuration`
19841
20702
  ] : [
19842
- `${u.origin}/.well-known/oauth-authorization-server${path25}`,
19843
- `${u.origin}/.well-known/openid-configuration${path25}`,
19844
- `${u.origin}${path25}/.well-known/openid-configuration`
20703
+ `${u.origin}/.well-known/oauth-authorization-server${path26}`,
20704
+ `${u.origin}/.well-known/openid-configuration${path26}`,
20705
+ `${u.origin}${path26}/.well-known/openid-configuration`
19845
20706
  ];
19846
20707
  const as = { issuer, tried: [], found: void 0 };
19847
20708
  for (const url of urls) {
@@ -23314,7 +24175,7 @@ var init_transport = __esm({
23314
24175
  const open2 = () => {
23315
24176
  let opened2 = () => {
23316
24177
  };
23317
- const ready2 = new Promise((resolve23) => opened2 = resolve23);
24178
+ const ready2 = new Promise((resolve25) => opened2 = resolve25);
23318
24179
  const req = {
23319
24180
  method: "GET",
23320
24181
  headers: [
@@ -28101,11 +28962,11 @@ var init_security = __esm({
28101
28962
  details
28102
28963
  };
28103
28964
  };
28104
- reach = (host, p) => new Promise((resolve23) => {
28965
+ reach = (host, p) => new Promise((resolve25) => {
28105
28966
  const socket = (0, import_node_net.connect)({ host, port: p });
28106
28967
  const done = (got2) => {
28107
28968
  socket.destroy();
28108
- resolve23(got2);
28969
+ resolve25(got2);
28109
28970
  };
28110
28971
  socket.setTimeout(CONNECT_MS, () => done(`no answer in ${CONNECT_MS} ms`));
28111
28972
  socket.once("connect", () => done("open"));
@@ -28986,7 +29847,7 @@ var init_tasks = __esm({
28986
29847
  reason: "needs-input",
28987
29848
  actual
28988
29849
  });
28989
- sleep3 = (ms) => new Promise((resolve23) => setTimeout(resolve23, ms));
29850
+ sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
28990
29851
  results3 = (answers3) => answers3.flatMap((a) => a.kind === "result" ? [a.result] : []);
28991
29852
  resultType2 = async (ctx) => {
28992
29853
  const s = await ready(ctx);
@@ -29447,11 +30308,11 @@ function parseRegistration(value2, label2) {
29447
30308
  return reg;
29448
30309
  }
29449
30310
  function readYaml(source) {
29450
- const parsed4 = (0, import_yaml6.parseDocument)(source, { merge: false, schema: "core", uniqueKeys: true });
30311
+ const parsed4 = (0, import_yaml7.parseDocument)(source, { merge: false, schema: "core", uniqueKeys: true });
29451
30312
  const first = parsed4.errors[0];
29452
30313
  if (first !== void 0)
29453
30314
  throw new UsageError(`--config: the file is not valid YAML (${first.code}).`);
29454
- (0, import_yaml6.visit)(parsed4, {
30315
+ (0, import_yaml7.visit)(parsed4, {
29455
30316
  Alias() {
29456
30317
  throw new UsageError("--config: YAML aliases and anchors are not allowed.");
29457
30318
  },
@@ -29462,7 +30323,7 @@ function readYaml(source) {
29462
30323
  throw new UsageError(`--config: a YAML tag (${node.tag.slice(0, 40)}) is not allowed.`);
29463
30324
  },
29464
30325
  Pair(_key, pair) {
29465
- if ((0, import_yaml6.isScalar)(pair.key) && pair.key.value === "<<")
30326
+ if ((0, import_yaml7.isScalar)(pair.key) && pair.key.value === "<<")
29466
30327
  throw new UsageError("--config: a YAML merge key (<<) is not allowed.");
29467
30328
  }
29468
30329
  });
@@ -29538,27 +30399,27 @@ function parseOauthConfig(source, format = "json") {
29538
30399
  }
29539
30400
  return config;
29540
30401
  }
29541
- function loadOauthConfig(path25) {
30402
+ function loadOauthConfig(path26) {
29542
30403
  let source;
29543
30404
  try {
29544
- if ((0, import_node_fs16.statSync)(path25).size > MAX_CONFIG_BYTES) throw new UsageError(tooLarge());
29545
- source = (0, import_node_fs16.readFileSync)(path25, "utf8");
30405
+ if ((0, import_node_fs16.statSync)(path26).size > MAX_CONFIG_BYTES) throw new UsageError(tooLarge());
30406
+ source = (0, import_node_fs16.readFileSync)(path26, "utf8");
29546
30407
  } catch (err) {
29547
30408
  if (err instanceof UsageError) throw err;
29548
30409
  const code = err.code;
29549
30410
  throw new UsageError(
29550
- `--config: could not read ${path25}${code === void 0 ? "" : ` (${code})`}.`
30411
+ `--config: could not read ${path26}${code === void 0 ? "" : ` (${code})`}.`
29551
30412
  );
29552
30413
  }
29553
- return parseOauthConfig(source, /\.ya?ml$/i.test(path25) ? "yaml" : "json");
30414
+ return parseOauthConfig(source, /\.ya?ml$/i.test(path26) ? "yaml" : "json");
29554
30415
  }
29555
- var import_node_fs16, import_yaml6, TOP, REGISTRATION2, METHODS, MODES, SECRET_KEY2, ENV_NAME, isObject6, MAX_CONFIG_BYTES, tooLarge;
30416
+ var import_node_fs16, import_yaml7, TOP, REGISTRATION2, METHODS, MODES, SECRET_KEY2, ENV_NAME, isObject6, MAX_CONFIG_BYTES, tooLarge;
29556
30417
  var init_auth_config = __esm({
29557
30418
  "src/mcp-testing/conformance/checks/auth-config.ts"() {
29558
30419
  "use strict";
29559
30420
  init_cjs_shims();
29560
30421
  import_node_fs16 = require("fs");
29561
- import_yaml6 = require("yaml");
30422
+ import_yaml7 = require("yaml");
29562
30423
  init_options();
29563
30424
  TOP = /* @__PURE__ */ new Set([
29564
30425
  "protocolVersions",
@@ -29607,13 +30468,13 @@ var mcp_conformance_exports = {};
29607
30468
  __export(mcp_conformance_exports, {
29608
30469
  handleMcpConformance: () => handleMcpConformance
29609
30470
  });
29610
- function loadFixture(path25) {
30471
+ function loadFixture(path26) {
29611
30472
  let doc;
29612
30473
  try {
29613
- doc = JSON.parse((0, import_node_fs17.readFileSync)(path25, "utf8"));
30474
+ doc = JSON.parse((0, import_node_fs17.readFileSync)(path26, "utf8"));
29614
30475
  } catch (err) {
29615
30476
  const code = err.code;
29616
- throw new UsageError(`--fixture: could not read ${path25} as JSON${code === void 0 ? "" : ` (${code})`}.`);
30477
+ throw new UsageError(`--fixture: could not read ${path26} as JSON${code === void 0 ? "" : ` (${code})`}.`);
29617
30478
  }
29618
30479
  if (!Array.isArray(doc)) throw new UsageError('--fixture must hold a JSON list of { "tool": "<name>", "arguments": { ... } }.');
29619
30480
  return doc.map((entry2, i) => {
@@ -30864,7 +31725,7 @@ function scanCross(run, snapshots, files) {
30864
31725
  if (!places.has(s.label))
30865
31726
  places.set(s.label, { file: f.path, line: s.line, column: s.column });
30866
31727
  const where3 = (label2) => places.get(safe(label2));
30867
- const add = (rule, label2, path25, message2) => {
31728
+ const add = (rule, label2, path26, message2) => {
30868
31729
  if (full(run)) {
30869
31730
  run.truncated = true;
30870
31731
  return;
@@ -30878,7 +31739,7 @@ function scanCross(run, snapshots, files) {
30878
31739
  origin: "snapshot",
30879
31740
  ...where3(label2),
30880
31741
  server: safe(label2),
30881
- path: safePointer(path25),
31742
+ path: safePointer(path26),
30882
31743
  message: message2,
30883
31744
  fix: def2.fix
30884
31745
  });
@@ -31206,8 +32067,8 @@ var init_config = __esm({
31206
32067
 
31207
32068
  // src/mcp-testing/scan/exceptions.ts
31208
32069
  function parseScanExceptions(text6, name, today, opts = {}) {
31209
- const lines = new import_yaml7.LineCounter();
31210
- const doc = (0, import_yaml7.parseDocument)(text6, { lineCounter: lines });
32070
+ const lines = new import_yaml8.LineCounter();
32071
+ const doc = (0, import_yaml8.parseDocument)(text6, { lineCounter: lines });
31211
32072
  const lineOf = (node) => lines.linePos(node?.range?.[0] ?? 0).line;
31212
32073
  const problems = [];
31213
32074
  const fail3 = (node, message2) => problems.push(`${name}:${lineOf(node)}: ${message2}`);
@@ -31217,25 +32078,25 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31217
32078
  const expired = [];
31218
32079
  const root = doc.contents;
31219
32080
  if (problems.length === 0 && root !== null) {
31220
- const list3 = (0, import_yaml7.isMap)(root) ? root.get("ignore", true) : void 0;
31221
- if (!(0, import_yaml7.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml7.isSeq)(list3))
32081
+ const list3 = (0, import_yaml8.isMap)(root) ? root.get("ignore", true) : void 0;
32082
+ if (!(0, import_yaml8.isMap)(root) || list3 !== void 0 && list3 !== null && !(0, import_yaml8.isSeq)(list3))
31222
32083
  fail3(root, 'expected "ignore:" with a list of entries.');
31223
- else if (root.items.some((p) => !((0, import_yaml7.isScalar)(p.key) && p.key.value === "ignore")))
32084
+ else if (root.items.some((p) => !((0, import_yaml8.isScalar)(p.key) && p.key.value === "ignore")))
31224
32085
  fail3(
31225
32086
  root,
31226
- `the only key of this file is "ignore:"; "${printable(String(root.items.map((p) => (0, import_yaml7.isScalar)(p.key) ? p.key.value : "?").find((k) => k !== "ignore")))}" is a typo or is not read.`
32087
+ `the only key of this file is "ignore:"; "${printable(String(root.items.map((p) => (0, import_yaml8.isScalar)(p.key) ? p.key.value : "?").find((k) => k !== "ignore")))}" is a typo or is not read.`
31227
32088
  );
31228
- else if ((0, import_yaml7.isSeq)(list3)) {
32089
+ else if ((0, import_yaml8.isSeq)(list3)) {
31229
32090
  for (const item of list3.items) {
31230
- if (!(0, import_yaml7.isMap)(item)) {
32091
+ if (!(0, import_yaml8.isMap)(item)) {
31231
32092
  fail3(item, "an entry needs rule, scope, reason and expires.");
31232
32093
  continue;
31233
32094
  }
31234
- const pair = (map, key) => map.items.find((p) => (0, import_yaml7.isScalar)(p.key) && p.key.value === key);
32095
+ const pair = (map, key) => map.items.find((p) => (0, import_yaml8.isScalar)(p.key) && p.key.value === key);
31235
32096
  const str2 = (map, key) => {
31236
32097
  const p = pair(map, key);
31237
32098
  if (p === void 0) return void 0;
31238
- const plain = (0, import_yaml7.isScalar)(p.value) ? p.value.value : p.value;
32099
+ const plain = (0, import_yaml8.isScalar)(p.value) ? p.value.value : p.value;
31239
32100
  if (plain !== null && plain !== void 0 && typeof plain !== "string") {
31240
32101
  fail3(
31241
32102
  p.key,
@@ -31248,13 +32109,13 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31248
32109
  const reason = str2(item, "reason");
31249
32110
  const expires = str2(item, "expires");
31250
32111
  let server2;
31251
- let path25;
32112
+ let path26;
31252
32113
  const scope = pair(item, "scope");
31253
- if (scope !== void 0 && (0, import_yaml7.isMap)(scope.value)) {
32114
+ if (scope !== void 0 && (0, import_yaml8.isMap)(scope.value)) {
31254
32115
  server2 = str2(scope.value, "server");
31255
- path25 = str2(scope.value, "path");
32116
+ path26 = str2(scope.value, "path");
31256
32117
  } else server2 = str2(item, "scope");
31257
- if (path25 !== void 0 && path25.trim() === "")
32118
+ if (path26 !== void 0 && path26.trim() === "")
31258
32119
  fail3(item, "path must name a field; leave it out to cover the whole server.");
31259
32120
  const subject2 = printable(rule ?? "a rule");
31260
32121
  if (rule === void 0 || rule.trim() === "") fail3(item, "an entry needs a rule.");
@@ -31286,7 +32147,7 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31286
32147
  const entry2 = {
31287
32148
  rule,
31288
32149
  server: server2,
31289
- ...path25 === void 0 ? {} : { path: path25 },
32150
+ ...path26 === void 0 ? {} : { path: path26 },
31290
32151
  reason,
31291
32152
  expires,
31292
32153
  line: lineOf(item)
@@ -31302,12 +32163,12 @@ function covers2(e, f) {
31302
32163
  if (e.rule !== f.rule || e.server !== f.target) return false;
31303
32164
  return e.path === void 0 || f.path === e.path || f.path.startsWith(`${e.path}.`) || f.path.startsWith(`${e.path}[`) || f.path.startsWith(`${e.path}/`);
31304
32165
  }
31305
- var import_yaml7, MAX_EXCEPTION_DAYS, DATE3, isDate3, days;
32166
+ var import_yaml8, MAX_EXCEPTION_DAYS, DATE3, isDate3, days;
31306
32167
  var init_exceptions2 = __esm({
31307
32168
  "src/mcp-testing/scan/exceptions.ts"() {
31308
32169
  "use strict";
31309
32170
  init_cjs_shims();
31310
- import_yaml7 = require("yaml");
32171
+ import_yaml8 = require("yaml");
31311
32172
  init_failure_detail();
31312
32173
  init_exceptions_file();
31313
32174
  MAX_EXCEPTION_DAYS = 180;
@@ -31464,10 +32325,10 @@ function journalHeaders(headers) {
31464
32325
  ])
31465
32326
  );
31466
32327
  }
31467
- function openProbeJournal(path25) {
32328
+ function openProbeJournal(path26) {
31468
32329
  let fd;
31469
32330
  try {
31470
- fd = (0, import_node_fs18.openSync)(path25, "w", 384);
32331
+ fd = (0, import_node_fs18.openSync)(path26, "w", 384);
31471
32332
  if (process.platform !== "win32") (0, import_node_fs18.fchmodSync)(fd, 384);
31472
32333
  } catch {
31473
32334
  throw new UsageError("--journal: the file cannot be opened for writing.");
@@ -32007,9 +32868,9 @@ async function startPage() {
32007
32868
  server2.headersTimeout = 5e3;
32008
32869
  server2.requestTimeout = 5e3;
32009
32870
  server2.keepAliveTimeout = 1e3;
32010
- await new Promise((resolve23, reject) => {
32871
+ await new Promise((resolve25, reject) => {
32011
32872
  server2.once("error", reject);
32012
- server2.listen(0, "127.0.0.1", resolve23);
32873
+ server2.listen(0, "127.0.0.1", resolve25);
32013
32874
  });
32014
32875
  const { address, port: port2 } = server2.address();
32015
32876
  return {
@@ -32022,9 +32883,9 @@ async function startPage() {
32022
32883
  requestTimeout: server2.requestTimeout,
32023
32884
  keepAliveTimeout: server2.keepAliveTimeout
32024
32885
  },
32025
- close: () => new Promise((resolve23) => {
32886
+ close: () => new Promise((resolve25) => {
32026
32887
  server2.closeAllConnections();
32027
- server2.close(() => resolve23());
32888
+ server2.close(() => resolve25());
32028
32889
  })
32029
32890
  };
32030
32891
  }
@@ -33020,9 +33881,9 @@ var init_report3 = __esm({
33020
33881
  init_types();
33021
33882
  GROUPS = ["descriptions", "pins", "config", "cross", "active"];
33022
33883
  DISCLAIMER = "No finding does not mean the server is safe: this is the result of the listed rules over the data that was read.";
33023
- fingerprintOf = (rule, target4, path25, nth) => (0, import_node_crypto15.createHash)("sha256").update(`${rule}
33884
+ fingerprintOf = (rule, target4, path26, nth) => (0, import_node_crypto15.createHash)("sha256").update(`${rule}
33024
33885
  ${target4}
33025
- ${path25}
33886
+ ${path26}
33026
33887
  ${nth}`, "utf8").digest("hex").slice(0, 32);
33027
33888
  where2 = (f) => f.location === void 0 ? "" : ` (${f.location.file}:${f.location.line}${f.location.column === void 0 ? "" : `:${f.location.column}`})`;
33028
33889
  IMPORT_WORDS = {
@@ -33678,15 +34539,15 @@ function groupsOf(flag2, values) {
33678
34539
  throw new UsageError(`${flag2}: "${n}" is not a group (${GROUPS.join(", ")}).`);
33679
34540
  return names;
33680
34541
  }
33681
- function shown3(cwd, path25) {
33682
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
34542
+ function shown3(cwd, path26) {
34543
+ const full2 = (0, import_node_path12.resolve)(cwd, path26);
33683
34544
  const rel = (0, import_node_path12.relative)(cwd, full2);
33684
34545
  return rel !== "" && !rel.startsWith("..") && !(0, import_node_path12.isAbsolute)(rel) ? rel.replace(/\\/g, "/") : (0, import_node_path12.basename)(full2);
33685
34546
  }
33686
- function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
33687
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
33688
- if (!(0, import_node_fs19.existsSync)(full2)) throw new UsageError(`${flag2}: ${path25} does not exist.`);
33689
- const unreadable2 = () => new UnreadableError(`${flag2}: ${safeText(shown3(cwd, path25))} cannot be read.`);
34547
+ function readText(cwd, path26, flag2, limit3 = true, max = MAX_FILE_BYTES) {
34548
+ const full2 = (0, import_node_path12.resolve)(cwd, path26);
34549
+ if (!(0, import_node_fs19.existsSync)(full2)) throw new UsageError(`${flag2}: ${path26} does not exist.`);
34550
+ const unreadable2 = () => new UnreadableError(`${flag2}: ${safeText(shown3(cwd, path26))} cannot be read.`);
33690
34551
  let size = 0;
33691
34552
  if (limit3)
33692
34553
  try {
@@ -33696,7 +34557,7 @@ function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
33696
34557
  }
33697
34558
  if (size > max)
33698
34559
  throw new TooLargeError(
33699
- `${flag2}: ${path25} is too large to read (over ${max >= 1024 * 1024 ? `${max / 1024 / 1024} MiB` : `${max / 1024} KiB`}).`
34560
+ `${flag2}: ${path26} is too large to read (over ${max >= 1024 * 1024 ? `${max / 1024 / 1024} MiB` : `${max / 1024} KiB`}).`
33700
34561
  );
33701
34562
  try {
33702
34563
  return (0, import_node_fs19.readFileSync)(full2, "utf8");
@@ -33704,8 +34565,8 @@ function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
33704
34565
  throw unreadable2();
33705
34566
  }
33706
34567
  }
33707
- function clientOf(path25) {
33708
- const p = path25.replace(/\\/g, "/").toLowerCase();
34568
+ function clientOf(path26) {
34569
+ const p = path26.replace(/\\/g, "/").toLowerCase();
33709
34570
  if (p.endsWith("claude_desktop_config.json")) return "claude-desktop";
33710
34571
  if (p.includes(".cursor/")) return "cursor";
33711
34572
  if (p.includes(".vscode/")) return "vscode";
@@ -33724,8 +34585,8 @@ async function handleMcpScan(flags2, server2, raw) {
33724
34585
  throw err;
33725
34586
  }
33726
34587
  }
33727
- function fileKeys(cwd, path25) {
33728
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
34588
+ function fileKeys(cwd, path26) {
34589
+ const full2 = (0, import_node_path12.resolve)(cwd, path26);
33729
34590
  const keys = [];
33730
34591
  let real = full2;
33731
34592
  try {
@@ -33760,9 +34621,9 @@ function noSharedFiles(flags2, outputs, cwd) {
33760
34621
  ...flags2.debugOut === void 0 ? [] : [["--debug-out", flags2.debugOut]]
33761
34622
  ];
33762
34623
  const seen = /* @__PURE__ */ new Map();
33763
- for (const [flag2, path25] of reads) for (const key of fileKeys(cwd, path25)) seen.set(key, flag2);
33764
- for (const [flag2, path25] of writes) {
33765
- const keys = fileKeys(cwd, path25);
34624
+ for (const [flag2, path26] of reads) for (const key of fileKeys(cwd, path26)) seen.set(key, flag2);
34625
+ for (const [flag2, path26] of writes) {
34626
+ const keys = fileKeys(cwd, path26);
33766
34627
  for (const key of keys) {
33767
34628
  const other = seen.get(key);
33768
34629
  if (other !== void 0 && other !== flag2 + "#w")
@@ -33807,14 +34668,14 @@ async function scan(flags2, server2, io) {
33807
34668
  const unreadable2 = [];
33808
34669
  for (const spec of flags2.snapshot ?? []) {
33809
34670
  const named2 = /^([A-Za-z0-9_.-]+)=(.+)$/s.exec(spec);
33810
- const path25 = named2 === null ? spec : named2[2] ?? "";
34671
+ const path26 = named2 === null ? spec : named2[2] ?? "";
33811
34672
  let text6;
33812
34673
  try {
33813
- text6 = readText(io.cwd, path25, "--snapshot");
34674
+ text6 = readText(io.cwd, path26, "--snapshot");
33814
34675
  } catch (err) {
33815
34676
  if (!(err instanceof TooLargeError) && !(err instanceof UnreadableError)) throw err;
33816
34677
  unreadable2.push({
33817
- target: shown3(io.cwd, path25),
34678
+ target: shown3(io.cwd, path26),
33818
34679
  reason: err instanceof TooLargeError ? "the file is too large to read (over 8 MiB)" : "the file cannot be read"
33819
34680
  });
33820
34681
  continue;
@@ -33824,11 +34685,11 @@ async function scan(flags2, server2, io) {
33824
34685
  snapshot = parseSnapshot(text6);
33825
34686
  } catch (err) {
33826
34687
  if (err instanceof SnapshotFormatError)
33827
- throw new UsageError(`--snapshot ${path25}: ${err.message}.`);
34688
+ throw new UsageError(`--snapshot ${path26}: ${err.message}.`);
33828
34689
  throw err;
33829
34690
  }
33830
- const label2 = named2?.[1] ?? (snapshot.server?.name !== void 0 && snapshot.server.name !== "" ? snapshot.server.name : (0, import_node_path12.basename)(path25).replace(/\.[^.]*$/, ""));
33831
- snapshots.push({ label: label2, snapshot, file: shown3(io.cwd, path25), text: text6 });
34691
+ const label2 = named2?.[1] ?? (snapshot.server?.name !== void 0 && snapshot.server.name !== "" ? snapshot.server.name : (0, import_node_path12.basename)(path26).replace(/\.[^.]*$/, ""));
34692
+ snapshots.push({ label: label2, snapshot, file: shown3(io.cwd, path26), text: text6 });
33832
34693
  }
33833
34694
  if (live) {
33834
34695
  const config = connectionConfig(flags2, server2, io.env);
@@ -33871,23 +34732,23 @@ async function scan(flags2, server2, io) {
33871
34732
  }
33872
34733
  const configFiles = [];
33873
34734
  let configMissing;
33874
- for (const path25 of flags2.config ?? [])
34735
+ for (const path26 of flags2.config ?? [])
33875
34736
  configFiles.push({
33876
- path: shown3(io.cwd, path25),
33877
- client: flags2.client ?? clientOf(path25),
33878
- text: readText(io.cwd, path25, "--config", false)
34737
+ path: shown3(io.cwd, path26),
34738
+ client: flags2.client ?? clientOf(path26),
34739
+ text: readText(io.cwd, path26, "--config", false)
33879
34740
  });
33880
34741
  let configRequested = (flags2.config ?? []).length > 0;
33881
34742
  if ((flags2.config ?? []).length === 0 && flags2.client !== void 0) {
33882
34743
  configRequested = true;
33883
- const path25 = CLIENT_FILES[flags2.client];
33884
- if ((0, import_node_fs19.existsSync)((0, import_node_path12.resolve)(io.cwd, path25)))
34744
+ const path26 = CLIENT_FILES[flags2.client];
34745
+ if ((0, import_node_fs19.existsSync)((0, import_node_path12.resolve)(io.cwd, path26)))
33885
34746
  configFiles.push({
33886
- path: path25,
34747
+ path: path26,
33887
34748
  client: flags2.client,
33888
- text: readText(io.cwd, path25, "--client", false)
34749
+ text: readText(io.cwd, path26, "--client", false)
33889
34750
  });
33890
- else configMissing = `${path25} is not in this folder`;
34751
+ else configMissing = `${path26} is not in this folder`;
33891
34752
  }
33892
34753
  let pin;
33893
34754
  let pinProblem;
@@ -34051,14 +34912,14 @@ var init_mcp_scan = __esm({
34051
34912
 
34052
34913
  // src/cli/commands/cairn-artifact.ts
34053
34914
  async function findLatestCairnRun(runsDir = "runs") {
34054
- const entries2 = await fs18.readdir(runsDir, { withFileTypes: true }).catch(() => null);
34915
+ const entries2 = await fs19.readdir(runsDir, { withFileTypes: true }).catch(() => null);
34055
34916
  if (entries2 === null) throw new NoCairnRunsError(runsDir);
34056
34917
  let newest;
34057
34918
  for (const entry2 of entries2) {
34058
34919
  if (!entry2.isDirectory()) continue;
34059
- const dir = path22.join(runsDir, entry2.name);
34920
+ const dir = path23.join(runsDir, entry2.name);
34060
34921
  try {
34061
- const report = await fs18.lstat(path22.join(dir, "report.json"));
34922
+ const report = await fs19.lstat(path23.join(dir, "report.json"));
34062
34923
  if (!report.isFile()) continue;
34063
34924
  if (newest === void 0 || report.mtimeMs > newest.at) {
34064
34925
  newest = { dir, at: report.mtimeMs };
@@ -34072,7 +34933,7 @@ async function findLatestCairnRun(runsDir = "runs") {
34072
34933
  async function checkSize(dir, file) {
34073
34934
  let size;
34074
34935
  try {
34075
- const st = await fs18.stat(path22.join(dir, file));
34936
+ const st = await fs19.stat(path23.join(dir, file));
34076
34937
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
34077
34938
  size = st.size;
34078
34939
  } catch (e) {
@@ -34090,7 +34951,7 @@ async function checkSize(dir, file) {
34090
34951
  }
34091
34952
  async function readJson(file) {
34092
34953
  try {
34093
- return JSON.parse(await fs18.readFile(file, "utf8"));
34954
+ return JSON.parse(await fs19.readFile(file, "utf8"));
34094
34955
  } catch {
34095
34956
  return void 0;
34096
34957
  }
@@ -34109,7 +34970,7 @@ async function readMcpEvidence(dir, states) {
34109
34970
  if (!await checkSize(dir, file)) return void 0;
34110
34971
  let raw;
34111
34972
  try {
34112
- raw = JSON.parse(await fs18.readFile(path22.join(dir, file), "utf8"));
34973
+ raw = JSON.parse(await fs19.readFile(path23.join(dir, file), "utf8"));
34113
34974
  } catch {
34114
34975
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
34115
34976
  }
@@ -34239,7 +35100,7 @@ async function casesFromMcp(dir, report) {
34239
35100
  });
34240
35101
  }
34241
35102
  async function defaultReadEvidence(dir) {
34242
- const raw = await readJson(path22.join(dir, "api-evidence.json"));
35103
+ const raw = await readJson(path23.join(dir, "api-evidence.json"));
34243
35104
  if (!Array.isArray(raw)) return void 0;
34244
35105
  return raw.map((r) => {
34245
35106
  const rec = asRecord2(r);
@@ -34247,21 +35108,37 @@ async function defaultReadEvidence(dir) {
34247
35108
  return { name: str(rec["name"]), passed: rec["passed"] === true, ...error !== "" ? { error } : {} };
34248
35109
  });
34249
35110
  }
34250
- function casesFromDesign(report) {
35111
+ function casesFromDesign(report, notes) {
34251
35112
  const list3 = Array.isArray(report["testCases"]) ? report["testCases"] : [];
34252
- return list3.map((raw) => {
35113
+ const refused = /* @__PURE__ */ new Map();
35114
+ const cases = list3.map((raw) => {
34253
35115
  const c = asRecord2(raw);
34254
35116
  const steps = (Array.isArray(c["steps"]) ? c["steps"] : []).map((s) => str(s)).filter((s) => s !== "");
35117
+ const title = str(c["title"], "untitled case");
35118
+ const link = own2(c, "traceUrl") ?? void 0;
35119
+ const said3 = [];
35120
+ const traceUrl = traceUrlOf(link, title, said3);
35121
+ if (said3.length > 0) {
35122
+ const key = typeof link === "string" ? link.trim() : typeof link;
35123
+ const before = refused.get(key) ?? 0;
35124
+ if (before === 0) notes.push(...said3);
35125
+ refused.set(key, before + 1);
35126
+ }
34255
35127
  return {
34256
35128
  stableId: str(c["stableId"]),
34257
- title: str(c["title"], "untitled case"),
35129
+ title,
34258
35130
  execution: c["execution"] === "manual" ? "manual" : "auto",
34259
35131
  steps: steps.length > 0 ? steps : ["(no steps recorded)"],
34260
35132
  expected: str(c["expected"], "(no expected result recorded)"),
34261
35133
  ...typeof c["technique"] === "string" ? { technique: c["technique"] } : {},
34262
- ...typeof c["priority"] === "string" ? { priority: c["priority"] } : {}
35134
+ ...typeof c["priority"] === "string" ? { priority: c["priority"] } : {},
35135
+ ...traceUrl !== void 0 ? { traceUrl } : {}
34263
35136
  };
34264
35137
  });
35138
+ for (const times of refused.values()) {
35139
+ if (times > 1) notes.push(`plune: ${times - 1} more case(s) carry the same trace link \u2014 sent without it.`);
35140
+ }
35141
+ return cases;
34265
35142
  }
34266
35143
  function casesFromApi(report, verdicts) {
34267
35144
  const list3 = Array.isArray(report["cases"]) ? report["cases"] : [];
@@ -34283,7 +35160,7 @@ function casesFromApi(report, verdicts) {
34283
35160
  }
34284
35161
  async function readCairnRun(dir, deps = {}) {
34285
35162
  await checkSize(dir, "report.json");
34286
- const raw = await readJson(path22.join(dir, "report.json"));
35163
+ const raw = await readJson(path23.join(dir, "report.json"));
34287
35164
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
34288
35165
  const report = asRecord2(raw);
34289
35166
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -34308,15 +35185,15 @@ async function readCairnRun(dir, deps = {}) {
34308
35185
  }
34309
35186
  cases = casesFromApi(report, verdicts);
34310
35187
  } else if (mode === "mcp") {
34311
- cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report) : await casesFromMcp(dir, report);
35188
+ cases = own2(report, "cases") === void 0 && Array.isArray(own2(report, "testCases")) ? casesFromDesign(report, deps.notes ?? []) : await casesFromMcp(dir, report);
34312
35189
  } else {
34313
- cases = casesFromDesign(report);
35190
+ cases = casesFromDesign(report, deps.notes ?? []);
34314
35191
  }
34315
35192
  const tokens2 = own2(asRecord2(own2(report, "cost")), "totalTokens");
34316
35193
  return {
34317
35194
  schemaVersion: INGEST_SCHEMA_VERSION,
34318
35195
  run: {
34319
- runId: str(report["runId"], path22.basename(dir)),
35196
+ runId: str(report["runId"], path23.basename(dir)),
34320
35197
  mode,
34321
35198
  target: str(report["url"], "unknown"),
34322
35199
  // Cairn states the run's tokens as `cost.totalTokens` in every mode; the platform copies it onto each proposal.
@@ -34326,22 +35203,22 @@ async function readCairnRun(dir, deps = {}) {
34326
35203
  };
34327
35204
  }
34328
35205
  async function readCairnSessionFiles(dir) {
34329
- const raw = await readJson(path22.join(dir, "screencasts", "screencasts.json"));
35206
+ const raw = await readJson(path23.join(dir, "screencasts", "screencasts.json"));
34330
35207
  if (!Array.isArray(raw)) return void 0;
34331
- const root = await fs18.realpath(dir).catch(() => path22.resolve(dir));
35208
+ const root = await fs19.realpath(dir).catch(() => path23.resolve(dir));
34332
35209
  const within2 = (p) => {
34333
- const rel = path22.relative(root, p);
34334
- return rel !== "" && !rel.startsWith("..") && !path22.isAbsolute(rel);
35210
+ const rel = path23.relative(root, p);
35211
+ return rel !== "" && !rel.startsWith("..") && !path23.isAbsolute(rel);
34335
35212
  };
34336
35213
  let outside = 0;
34337
35214
  const inside = async (p) => {
34338
35215
  if (typeof p !== "string" || p === "") return void 0;
34339
- const abs = path22.resolve(root, p);
34340
- const real = await fs18.realpath(abs).catch(() => void 0);
35216
+ const abs = path23.resolve(root, p);
35217
+ const real = await fs19.realpath(abs).catch(() => void 0);
34341
35218
  if (within2(abs) && (real === void 0 || within2(real))) {
34342
35219
  const file = real ?? abs;
34343
- const size = await fs18.stat(file).then((s) => s.size, () => void 0);
34344
- return { path: file, rel: path22.relative(root, abs).split(path22.sep).join("/"), ...size !== void 0 ? { size } : {} };
35220
+ const size = await fs19.stat(file).then((s) => s.size, () => void 0);
35221
+ return { path: file, rel: path23.relative(root, abs).split(path23.sep).join("/"), ...size !== void 0 ? { size } : {} };
34345
35222
  }
34346
35223
  outside += 1;
34347
35224
  return void 0;
@@ -34367,7 +35244,7 @@ async function readCairnSessionFiles(dir) {
34367
35244
  const keys = new Set(declared2.flatMap((s) => s.files.map((f) => f.key)));
34368
35245
  const title = clip(str(own2(rec, "test")));
34369
35246
  const files = found.filter((f) => {
34370
- if ((f.file.size ?? 0) < 1 || f.rel.length > DECLARED.text || path22.basename(f.file.path).length > DECLARED.name || keys.has(f.rel)) return false;
35247
+ if ((f.file.size ?? 0) < 1 || f.rel.length > DECLARED.text || path23.basename(f.file.path).length > DECLARED.name || keys.has(f.rel)) return false;
34371
35248
  keys.add(f.rel);
34372
35249
  return true;
34373
35250
  });
@@ -34383,19 +35260,20 @@ async function readCairnSessionFiles(dir) {
34383
35260
  const atMs = own2(chapter, "atMs");
34384
35261
  return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
34385
35262
  }).slice(0, DECLARED.chapters),
34386
- files: files.map((f) => ({ key: f.rel, name: path22.basename(f.file.path), kind: f.kind, size: f.file.size }))
35263
+ files: files.map((f) => ({ key: f.rel, name: path23.basename(f.file.path), kind: f.kind, size: f.file.size }))
34387
35264
  });
34388
35265
  screencasts.set(stableId, declared2);
34389
35266
  }
34390
35267
  return { byCase, screencasts, unmapped, outside };
34391
35268
  }
34392
- var fs18, path22, SUPPORTED_ARTIFACT_VERSION, INGEST_SCHEMA_VERSION, NoCairnRunsError, CairnRunNotFoundError, CairnRunVersionError, CairnRunPartialError, CairnArtifactShapeError, CairnEvidenceAmbiguousError, asRecord2, str, own2, MAX_ARTIFACT_BYTES, MAX_MCP_CASES, ARGS_CHARS2, SECRET_NAME, maskNamed, MCP_STATES, DECLARED, clip;
35269
+ var fs19, path23, SUPPORTED_ARTIFACT_VERSION, INGEST_SCHEMA_VERSION, NoCairnRunsError, CairnRunNotFoundError, CairnRunVersionError, CairnRunPartialError, CairnArtifactShapeError, CairnEvidenceAmbiguousError, asRecord2, str, own2, MAX_ARTIFACT_BYTES, MAX_MCP_CASES, ARGS_CHARS2, SECRET_NAME, maskNamed, MCP_STATES, DECLARED, clip;
34393
35270
  var init_cairn_artifact = __esm({
34394
35271
  "src/cli/commands/cairn-artifact.ts"() {
34395
35272
  "use strict";
34396
35273
  init_cjs_shims();
34397
- fs18 = __toESM(require("fs/promises"), 1);
34398
- path22 = __toESM(require("path"), 1);
35274
+ fs19 = __toESM(require("fs/promises"), 1);
35275
+ path23 = __toESM(require("path"), 1);
35276
+ init_trace_url();
34399
35277
  init_config();
34400
35278
  init_errors2();
34401
35279
  SUPPORTED_ARTIFACT_VERSION = 1;
@@ -34546,13 +35424,13 @@ async function sendSessionFiles(session2, sent, platform) {
34546
35424
  if (paths === void 0 || placed.has(item.stableId)) continue;
34547
35425
  placed.add(item.stableId);
34548
35426
  for (const { path: file, size, key } of paths) {
34549
- const name = path23.basename(file);
35427
+ const name = path24.basename(file);
34550
35428
  if (size !== void 0 && size > SESSION_FILE_MAX) {
34551
35429
  tooBig += 1;
34552
35430
  lines.push(`"${name}" skipped \u2014 larger than the ${SESSION_FILE_MAX / (1024 * 1024)} MiB a session file may be`);
34553
35431
  continue;
34554
35432
  }
34555
- const type = TYPE_BY_EXTENSION2[path23.extname(file).toLowerCase()] ?? "application/octet-stream";
35433
+ const type = TYPE_BY_EXTENSION2[path24.extname(file).toLowerCase()] ?? "application/octet-stream";
34556
35434
  jobs.push({
34557
35435
  id: item.reviewItemId ?? item.resultId,
34558
35436
  ...item.reviewItemId !== void 0 ? { owner: "review-items" } : {},
@@ -34618,7 +35496,8 @@ async function handleIngest(deps) {
34618
35496
  const token2 = (deps.loadToken ?? loadToken)();
34619
35497
  if (token2 === null) throw new IngestNotLoggedInError();
34620
35498
  const dir = deps.dir ?? await findLatestCairnRun(deps.runsDir);
34621
- const payload2 = await readCairnRun(dir);
35499
+ const notes = [];
35500
+ const payload2 = await readCairnRun(dir, { notes });
34622
35501
  const session2 = await readCairnSessionFiles(dir).catch(() => void 0);
34623
35502
  for (const c of payload2.cases) {
34624
35503
  const screencasts = session2?.screencasts.get(c.stableId);
@@ -34627,7 +35506,7 @@ async function handleIngest(deps) {
34627
35506
  const doFetch = deps.fetchImpl ?? fetch;
34628
35507
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
34629
35508
  const job = new JobReporter(doFetch, apiUrl, token2, "ingest");
34630
- await job.open(path23.basename(path23.resolve(dir)), payload2.cases.length);
35509
+ await job.open(path24.basename(path24.resolve(dir)), payload2.cases.length);
34631
35510
  try {
34632
35511
  const { result: result2, ...sent } = await upload();
34633
35512
  await job.uploaded({ subjectId: result2.runId || void 0 });
@@ -34636,6 +35515,7 @@ async function handleIngest(deps) {
34636
35515
  );
34637
35516
  if (files.length > 0) result2.files = files;
34638
35517
  if (sent.repeat) result2.repeat = true;
35518
+ if (notes.length > 0) result2.notes = notes;
34639
35519
  await job.finish({ ok: true });
34640
35520
  if (job.problem !== void 0) result2.jobProblem = job.problem;
34641
35521
  return result2;
@@ -34686,6 +35566,7 @@ function formatIngestResult(r) {
34686
35566
  const files = (r.files ?? []).map((line, i) => i === 0 ? ` ${line}` : ` ${line}`);
34687
35567
  if (r.repeat === true) {
34688
35568
  return `${[
35569
+ ...r.notes ?? [],
34689
35570
  `This Cairn run was already ingested \u2192 ${r.runId}`,
34690
35571
  " nothing new was proposed or attached; a run with a new run id is ingested as new",
34691
35572
  ...files
@@ -34693,6 +35574,7 @@ function formatIngestResult(r) {
34693
35574
  `;
34694
35575
  }
34695
35576
  const lines = [
35577
+ ...r.notes ?? [],
34696
35578
  `Ingested Cairn run \u2192 ${r.runId}`,
34697
35579
  ` ${r.linked} result(s) attached to existing cases`,
34698
35580
  ` ${r.proposed} case(s) proposed \u2014 review them in Plune to accept`,
@@ -34702,12 +35584,12 @@ function formatIngestResult(r) {
34702
35584
  return `${lines.join("\n")}
34703
35585
  `;
34704
35586
  }
34705
- var path23, IngestNotLoggedInError, IngestTokenRejectedError, IngestNetworkError, IngestHttpError, SESSION_FILE_MAX, SESSION_UPLOADS_AT_ONCE, TYPE_BY_EXTENSION2, RESULT_PAGES_MAX, namesOf, targetOf3;
35587
+ var path24, IngestNotLoggedInError, IngestTokenRejectedError, IngestNetworkError, IngestHttpError, SESSION_FILE_MAX, SESSION_UPLOADS_AT_ONCE, TYPE_BY_EXTENSION2, RESULT_PAGES_MAX, namesOf, targetOf3;
34706
35588
  var init_ingest = __esm({
34707
35589
  "src/cli/commands/ingest.ts"() {
34708
35590
  "use strict";
34709
35591
  init_cjs_shims();
34710
- path23 = __toESM(require("path"), 1);
35592
+ path24 = __toESM(require("path"), 1);
34711
35593
  init_client();
34712
35594
  init_env2();
34713
35595
  init_session2();
@@ -34759,7 +35641,7 @@ __export(requirements_import_exports, {
34759
35641
  cut: () => cut4,
34760
35642
  flat: () => flat2,
34761
35643
  formatDiscover: () => formatDiscover,
34762
- formatReport: () => formatReport2,
35644
+ formatReport: () => formatReport3,
34763
35645
  handleRequirementsImport: () => handleRequirementsImport,
34764
35646
  parseMap: () => parseMap,
34765
35647
  parseTableSpec: () => parseTableSpec,
@@ -34954,7 +35836,7 @@ function formatDiscover(file, r) {
34954
35836
  );
34955
35837
  return out.join("\n") + "\n";
34956
35838
  }
34957
- function formatReport2(report) {
35839
+ function formatReport3(report) {
34958
35840
  const s = report.summary;
34959
35841
  const out = [`create ${s.create} \xB7 update ${s.update} \xB7 unchanged ${s.unchanged} \xB7 skip ${s.skip}`];
34960
35842
  if (report.emptyTemplate === true) {
@@ -35332,8 +36214,8 @@ function filteredDotenv(text6, token2) {
35332
36214
  }).join("\n");
35333
36215
  }
35334
36216
  function filesUnder(dir) {
35335
- if (!fs19.existsSync(dir)) return [];
35336
- return fs19.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((p) => fs19.statSync(path24.join(dir, p)).isFile()).map((p) => p.split(path24.sep).join("/")).sort();
36217
+ if (!fs20.existsSync(dir)) return [];
36218
+ return fs20.readdirSync(dir, { recursive: true, encoding: "utf8" }).filter((p) => fs20.statSync(path25.join(dir, p)).isFile()).map((p) => p.split(path25.sep).join("/")).sort();
35337
36219
  }
35338
36220
  function newFilesDiff(files) {
35339
36221
  return files.map((f) => {
@@ -35349,13 +36231,13 @@ function newFilesDiff(files) {
35349
36231
  }).join("");
35350
36232
  }
35351
36233
  function findExecutable(command, env) {
35352
- if (command.includes("/") || command.includes("\\")) return fs19.existsSync(command) ? path24.resolve(command) : void 0;
36234
+ if (command.includes("/") || command.includes("\\")) return fs20.existsSync(command) ? path25.resolve(command) : void 0;
35353
36235
  const exts = process.platform === "win32" ? (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
35354
- const dirs = (env["PATH"] ?? env["Path"] ?? "").split(path24.delimiter).filter((d) => d !== "");
36236
+ const dirs = (env["PATH"] ?? env["Path"] ?? "").split(path25.delimiter).filter((d) => d !== "");
35355
36237
  for (const dir of dirs)
35356
36238
  for (const ext of exts) {
35357
- const candidate = path24.join(dir, command + ext);
35358
- if (fs19.existsSync(candidate) && fs19.statSync(candidate).isFile()) return candidate;
36239
+ const candidate = path25.join(dir, command + ext);
36240
+ if (fs20.existsSync(candidate) && fs20.statSync(candidate).isFile()) return candidate;
35359
36241
  }
35360
36242
  return void 0;
35361
36243
  }
@@ -35363,8 +36245,8 @@ async function handleAutomate(deps) {
35363
36245
  for (const a of deps.cairnArgs ?? [])
35364
36246
  if (/^--(run|into-project)(=|$)/.test(a))
35365
36247
  throw new SyncFileError(`${a} is not passed to Cairn: plune automate owns the run folder and does not write into the repo.`);
35366
- const repo = path24.resolve(deps.repo ?? process.cwd());
35367
- if (!fs19.existsSync(repo) || !fs19.statSync(repo).isDirectory()) throw new SyncFileError(`No directory at ${repo} (--repo).`);
36248
+ const repo = path25.resolve(deps.repo ?? process.cwd());
36249
+ if (!fs20.existsSync(repo) || !fs20.statSync(repo).isDirectory()) throw new SyncFileError(`No directory at ${repo} (--repo).`);
35368
36250
  const env = deps.env ?? process.env;
35369
36251
  const command = deps.cairn ?? "cairn";
35370
36252
  const executable = findExecutable(command, env);
@@ -35380,33 +36262,33 @@ async function handleAutomate(deps) {
35380
36262
  throw err;
35381
36263
  }
35382
36264
  if (!detail.steps?.length) throw new CaseNotAutomatableError(deps.caseId, detail.type);
35383
- const tmp = fs19.mkdtempSync(path24.join(os.tmpdir(), "plune-automate-"));
36265
+ const tmp = fs20.mkdtempSync(path25.join(os.tmpdir(), "plune-automate-"));
35384
36266
  try {
35385
- const runDir = path24.join(tmp, "run");
35386
- fs19.mkdirSync(path24.join(runDir, "testcases"), { recursive: true });
35387
- fs19.writeFileSync(path24.join(runDir, "report.json"), JSON.stringify({ url: deps.url ?? "", mode: "design" }, null, 2));
35388
- fs19.writeFileSync(path24.join(runDir, "testcases", "ATC-PLUNE-001.md"), caseToAtcMarkdown(detail));
35389
- const dotenvSource = env["DOTENV_PATH"] ?? env["DOTENV_CONFIG_PATH"] ?? path24.join(repo, ".env");
35390
- const dotenvCopy = path24.join(tmp, "cairn.env");
35391
- fs19.writeFileSync(dotenvCopy, fs19.existsSync(dotenvSource) ? filteredDotenv(fs19.readFileSync(dotenvSource, "utf8"), token2) : "");
36267
+ const runDir = path25.join(tmp, "run");
36268
+ fs20.mkdirSync(path25.join(runDir, "testcases"), { recursive: true });
36269
+ fs20.writeFileSync(path25.join(runDir, "report.json"), JSON.stringify({ url: deps.url ?? "", mode: "design" }, null, 2));
36270
+ fs20.writeFileSync(path25.join(runDir, "testcases", "ATC-PLUNE-001.md"), caseToAtcMarkdown(detail));
36271
+ const dotenvSource = env["DOTENV_PATH"] ?? env["DOTENV_CONFIG_PATH"] ?? path25.join(repo, ".env");
36272
+ const dotenvCopy = path25.join(tmp, "cairn.env");
36273
+ fs20.writeFileSync(dotenvCopy, fs20.existsSync(dotenvSource) ? filteredDotenv(fs20.readFileSync(dotenvSource, "utf8"), token2) : "");
35392
36274
  const childEnv = { ...cairnEnv(env, token2), DOTENV_PATH: dotenvCopy, DOTENV_CONFIG_PATH: dotenvCopy };
35393
36275
  const isScript = /\.[cm]?js$/i.test(executable);
35394
36276
  const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(executable);
35395
36277
  const quoted = (s) => `"${s.replace(/"/g, '""')}"`;
35396
36278
  const spawnImpl = deps.spawnImpl ?? import_node_child_process5.spawn;
35397
- const runCairn = (args, capture) => new Promise((resolve23) => {
36279
+ const runCairn = (args, capture) => new Promise((resolve25) => {
35398
36280
  const opts = { cwd: repo, env: childEnv, stdio: ["ignore", capture ? "pipe" : 2, 2] };
35399
36281
  const child = isScript ? spawnImpl(process.execPath, [executable, ...args], opts) : viaShell ? spawnImpl([executable, ...args].map(quoted).join(" "), { ...opts, shell: true }) : spawnImpl(executable, args, opts);
35400
36282
  let out = "";
35401
36283
  child.stdout?.on("data", (chunk2) => void (out += chunk2.toString("utf8")));
35402
- child.on("close", (exitCode2) => resolve23({ code: exitCode2 ?? 1, out }));
35403
- child.on("error", () => resolve23({ code: -1, out }));
36284
+ child.on("close", (exitCode2) => resolve25({ code: exitCode2 ?? 1, out }));
36285
+ child.on("error", () => resolve25({ code: -1, out }));
35404
36286
  });
35405
36287
  const { code } = await runCairn(["automate", "--run", runDir, ...deps.cairnArgs ?? []], false);
35406
36288
  if (code === -1) throw new CairnMissingError(command);
35407
36289
  if (code !== 0) throw new CairnFailedError(code);
35408
- const testsDir = path24.join(runDir, "tests");
35409
- const files = filesUnder(testsDir).map((p) => ({ path: p, content: fs19.readFileSync(path24.join(testsDir, p), "utf8") }));
36290
+ const testsDir = path25.join(runDir, "tests");
36291
+ const files = filesUnder(testsDir).map((p) => ({ path: p, content: fs20.readFileSync(path25.join(testsDir, p), "utf8") }));
35410
36292
  if (files.length === 0) throw new CairnProducedNothingError();
35411
36293
  const result2 = { case: detail, files, diff: newFilesDiff(files) };
35412
36294
  if (!deps.withCairnVersion) return result2;
@@ -35414,7 +36296,7 @@ async function handleAutomate(deps) {
35414
36296
  const cairnVersion = (v.code === 0 ? /\d+\.\d+[\w.+-]*/.exec(v.out)?.[0] : void 0) ?? "unknown";
35415
36297
  return { ...result2, cairnVersion: cairnVersion.slice(0, AUTOMATION_ORIGIN_MAX) };
35416
36298
  } finally {
35417
- fs19.rmSync(tmp, { recursive: true, force: true });
36299
+ fs20.rmSync(tmp, { recursive: true, force: true });
35418
36300
  }
35419
36301
  }
35420
36302
  function skipNonCode(s, i, prev) {
@@ -35577,15 +36459,15 @@ function reportAutomateFailure(err, write) {
35577
36459
  }
35578
36460
  return reportCasesFailure(err, write);
35579
36461
  }
35580
- var import_node_child_process5, fs19, os, path24, CairnMissingError, CaseNotFoundError, CaseNotAutomatableError, CairnFailedError, CairnProducedNothingError, AUTOMATION_FILES_MAX, AUTOMATION_FILE_MAX_BYTES, AUTOMATION_TOTAL_MAX_BYTES, AUTOMATION_PATH_MAX, AUTOMATION_ORIGIN_MAX, ProposalBoundsError, NoTestCallError, ProposalRefusedError, flat3, REGEX_AFTER, bytesOf, isSpec;
36462
+ var import_node_child_process5, fs20, os, path25, CairnMissingError, CaseNotFoundError, CaseNotAutomatableError, CairnFailedError, CairnProducedNothingError, AUTOMATION_FILES_MAX, AUTOMATION_FILE_MAX_BYTES, AUTOMATION_TOTAL_MAX_BYTES, AUTOMATION_PATH_MAX, AUTOMATION_ORIGIN_MAX, ProposalBoundsError, NoTestCallError, ProposalRefusedError, flat3, REGEX_AFTER, bytesOf, isSpec;
35581
36463
  var init_automate = __esm({
35582
36464
  "src/cli/commands/automate.ts"() {
35583
36465
  "use strict";
35584
36466
  init_cjs_shims();
35585
36467
  import_node_child_process5 = require("child_process");
35586
- fs19 = __toESM(require("fs"), 1);
36468
+ fs20 = __toESM(require("fs"), 1);
35587
36469
  os = __toESM(require("os"), 1);
35588
- path24 = __toESM(require("path"), 1);
36470
+ path25 = __toESM(require("path"), 1);
35589
36471
  init_api_url();
35590
36472
  init_credentials();
35591
36473
  init_plan();
@@ -35786,16 +36668,16 @@ init_options2();
35786
36668
 
35787
36669
  // src/cli/config-flag.ts
35788
36670
  init_cjs_shims();
35789
- function configFlagValues(args, path25) {
36671
+ function configFlagValues(args, path26) {
35790
36672
  const out = { before: [], after: [] };
35791
36673
  let next = 0;
35792
36674
  let side = "before";
35793
36675
  for (let i = 0; i < args.length; i++) {
35794
36676
  const arg = args[i];
35795
36677
  if (arg === "--") break;
35796
- if (side === "before" && arg === path25[next]) {
36678
+ if (side === "before" && arg === path26[next]) {
35797
36679
  next += 1;
35798
- if (next === path25.length) side = "after";
36680
+ if (next === path26.length) side = "after";
35799
36681
  continue;
35800
36682
  }
35801
36683
  const long = arg.startsWith("--config=") ? arg.slice("--config=".length) : void 0;
@@ -36214,14 +37096,14 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36214
37096
  ).option("--max-pass-rate-drop-percent <n>", "Gate: the overall pass rate may drop at most n percentage points").option("--max-cost-usd <n>", "Gate: the current run may cost at most n USD").option("--max-cost-increase-percent <n>", "Gate: the cost may grow at most n percent over the baseline").option("--max-tokens <n>", "Gate: the current run may use at most n tokens (input + output)").option("--waivers <file>", "YAML file of waivers for measured gate failures").option("-o, --output <path>", "Write the diff to a file instead of stdout").action(
36215
37097
  async (baseline, current, options, command) => {
36216
37098
  const verbose = command.optsWithGlobals().verbose === true;
36217
- const [{ handleDiff: handleDiff2, DiffInputError: DiffInputError2 }, { renderDiff: renderDiff2 }] = await Promise.all([
37099
+ const [{ diffFiles: diffFiles2, DiffInputError: DiffInputError2 }, { renderDiff: renderDiff2 }] = await Promise.all([
36218
37100
  Promise.resolve().then(() => (init_diff4(), diff_exports2)),
36219
37101
  Promise.resolve().then(() => (init_diff2(), diff_exports))
36220
37102
  ]);
36221
37103
  try {
36222
37104
  const { format: _format, output: _output, ...gateFlags } = options;
36223
- const diff2 = handleDiff2({ baselinePath: baseline, currentPath: current, ...gateFlags });
36224
- writeReport2(renderDiff2(diff2, toFormat(options.format)), options.output);
37105
+ const { diff: diff2, current: run } = diffFiles2({ baselinePath: baseline, currentPath: current, ...gateFlags });
37106
+ writeReport2(renderDiff2(diff2, toFormat(options.format), run), options.output);
36225
37107
  process.exitCode = diff2.gates?.exitCode ?? 0;
36226
37108
  } catch (err) {
36227
37109
  if (err instanceof DiffInputError2) {
@@ -36234,23 +37116,69 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36234
37116
  }
36235
37117
  }
36236
37118
  );
36237
- program.command("init").description("Scaffold plune.yaml (interactive), an example dataset, and .env.example").option("--force", "Overwrite existing files instead of skipping them", false).option("--yes", "Non-interactive: scaffold defaults without prompts (for CI)", false).action(async (options, command) => {
37119
+ program.command("judge-check").description(
37120
+ "Compare a judge's verdicts in a saved run with a person's pass/fail labels: TPR, TNR, Cohen's kappa and its 95% interval. Local only"
37121
+ ).argument("<labels.jsonl>", 'The labels file: one {"eval", "vars_hash", "output_hash", "human", "by", "at"} per line').option("--run <file>", "The saved run to read", ".plune/last-run.json").option("--init", "Write the labels file to fill in from the run, one line per row with an answer", false).option("--force", "With --init: write over an existing labels file", false).option("--eval <id>", "Only this eval").option("--check <n>", "The check to compare, by its position in a row from 1 (default: the one check a model judges)").option("--min-kappa <k>", "Exit 1 when an eval's kappa is below k or has no value").option("--max-interval-width <w>", "Warn when the 95% interval of kappa is wider than w (default 0.4)").exitOverride((err) => process.exit(err.exitCode === 0 ? 0 : 2)).action(async (labels, options, command) => {
36238
37122
  const verbose = command.optsWithGlobals().verbose === true;
36239
- const [{ initCommand: initCommand2 }, { NonTtyError: NonTtyError2 }] = await Promise.all([
36240
- Promise.resolve().then(() => (init_init(), init_exports)),
36241
- Promise.resolve().then(() => (init_errors(), errors_exports))
37123
+ const [{ handleJudgeCheck: handleJudgeCheck2 }, { JudgeCheckError: JudgeCheckError2 }] = await Promise.all([
37124
+ Promise.resolve().then(() => (init_judge_check(), judge_check_exports)),
37125
+ Promise.resolve().then(() => (init_labels(), labels_exports))
36242
37126
  ]);
36243
37127
  try {
36244
- await initCommand2({ cwd: process.cwd(), force: options.force, yes: options.yes });
37128
+ process.exitCode = await handleJudgeCheck2(labels, options, process.cwd(), (t) => {
37129
+ process.stdout.write(t);
37130
+ });
36245
37131
  } catch (err) {
36246
- if (err instanceof NonTtyError2) {
37132
+ if (err instanceof JudgeCheckError2) {
36247
37133
  process.stderr.write(err.message + "\n");
36248
- process.exit(1);
37134
+ process.exit(2);
36249
37135
  return;
36250
37136
  }
36251
37137
  failUnexpected(err, verbose);
36252
37138
  }
36253
37139
  });
37140
+ program.command("init").description("Scaffold plune.yaml (interactive), an example dataset, and .env.example").option("--force", "Overwrite existing files instead of skipping them", false).option("--yes", "Non-interactive: scaffold defaults without prompts (for CI)", false).option(
37141
+ "--from-openai-eval <eval.json>",
37142
+ "Build plune.yaml from an exported OpenAI eval (the answer of GET /v1/evals/{eval_id}) and print what each grader became"
37143
+ ).option("--run <run.json>", "With --from-openai-eval: one run of that eval, for the prompt and the model").option("--data <rows.jsonl>", 'With --from-openai-eval: the test data, one {"item": {...}} per line').action(
37144
+ async (options, command) => {
37145
+ const verbose = command.optsWithGlobals().verbose === true;
37146
+ const [{ initCommand: initCommand2, initFromOpenAiEval: initFromOpenAiEval2 }, { NonTtyError: NonTtyError2 }] = await Promise.all([
37147
+ Promise.resolve().then(() => (init_init(), init_exports)),
37148
+ Promise.resolve().then(() => (init_errors(), errors_exports))
37149
+ ]);
37150
+ if (options.fromOpenaiEval === void 0 && (options.run !== void 0 || options.data !== void 0)) {
37151
+ process.stderr.write("--run and --data need --from-openai-eval <eval.json>\n");
37152
+ process.exit(2);
37153
+ return;
37154
+ }
37155
+ try {
37156
+ if (options.fromOpenaiEval !== void 0) {
37157
+ await initFromOpenAiEval2({
37158
+ cwd: process.cwd(),
37159
+ force: options.force,
37160
+ evalPath: options.fromOpenaiEval,
37161
+ ...options.run !== void 0 ? { runPath: options.run } : {},
37162
+ ...options.data !== void 0 ? { dataPath: options.data } : {}
37163
+ });
37164
+ return;
37165
+ }
37166
+ await initCommand2({ cwd: process.cwd(), force: options.force, yes: options.yes });
37167
+ } catch (err) {
37168
+ if (err instanceof Error && err.name === "OpenAiEvalImportError") {
37169
+ process.stderr.write(err.message + "\n");
37170
+ process.exit(2);
37171
+ return;
37172
+ }
37173
+ if (err instanceof NonTtyError2) {
37174
+ process.stderr.write(err.message + "\n");
37175
+ process.exit(1);
37176
+ return;
37177
+ }
37178
+ failUnexpected(err, verbose);
37179
+ }
37180
+ }
37181
+ );
36254
37182
  program.command("login").description("Save your Plune API token (get one in the dashboard: Account \u2192 API tokens)").option("--token <token>", "API token (omit to paste it / pipe it via stdin)").option(
36255
37183
  "--skip-verify",
36256
37184
  "Save without checking the token against the API (offline setup)",
@@ -36260,10 +37188,10 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36260
37188
  const { handleLogin: handleLogin2, reportLoginFailure: reportLoginFailure2 } = await Promise.resolve().then(() => (init_login(), login_exports));
36261
37189
  try {
36262
37190
  const token2 = options.token ?? await readTokenFromStdin();
36263
- const { path: path25, verified } = await handleLogin2({ token: token2, skipVerify: options.skipVerify });
37191
+ const { path: path26, verified } = await handleLogin2({ token: token2, skipVerify: options.skipVerify });
36264
37192
  process.stdout.write(
36265
- verified ? `Logged in. Token checked against the API and saved to ${path25}
36266
- ` : `Token saved to ${path25} WITHOUT being checked (--skip-verify).
37193
+ verified ? `Logged in. Token checked against the API and saved to ${path26}
37194
+ ` : `Token saved to ${path26} WITHOUT being checked (--skip-verify).
36267
37195
  `
36268
37196
  );
36269
37197
  } catch (err) {
@@ -36280,9 +37208,9 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36280
37208
  const verbose = command.optsWithGlobals().verbose === true;
36281
37209
  const { handleLogout: handleLogout2 } = await Promise.resolve().then(() => (init_logout(), logout_exports));
36282
37210
  try {
36283
- const { removed, path: path25 } = handleLogout2();
37211
+ const { removed, path: path26 } = handleLogout2();
36284
37212
  process.stdout.write(
36285
- removed ? `Logged out. Removed ${path25}
37213
+ removed ? `Logged out. Removed ${path26}
36286
37214
  ` : "Not logged in \u2014 nothing to remove.\n"
36287
37215
  );
36288
37216
  } catch (err) {
@@ -36559,13 +37487,13 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36559
37487
  "Send a Markdown document of test cases back to Plune (POST /v1/test-cases/markdown)"
36560
37488
  ).option("--dry-run", "Show what would change and write nothing", false).action(async (file, options, command) => {
36561
37489
  const verbose = command.optsWithGlobals().verbose === true;
36562
- const { handlePush: handlePush2, formatReport: formatReport3, reportCasesFailure: reportCasesFailure2 } = await Promise.resolve().then(() => (init_cases(), cases_exports));
37490
+ const { handlePush: handlePush2, formatReport: formatReport4, reportCasesFailure: reportCasesFailure2 } = await Promise.resolve().then(() => (init_cases(), cases_exports));
36563
37491
  try {
36564
37492
  const report = await handlePush2({
36565
37493
  ...file !== void 0 ? { file } : {},
36566
37494
  dryRun: options.dryRun
36567
37495
  });
36568
- process.stdout.write(formatReport3(report));
37496
+ process.stdout.write(formatReport4(report));
36569
37497
  if (report.refused.length > 0) process.exitCode = 4;
36570
37498
  } catch (err) {
36571
37499
  const code = reportCasesFailure2(err, (s) => process.stderr.write(s));
@@ -36586,13 +37514,13 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36586
37514
  (value2, previous = []) => [...previous, value2]
36587
37515
  ).option("--key-column <header>", "Table: the column holding the requirement key").option("--title-column <header>", "Table: the column holding the title").option("--text-column <header>", "Table: one text column; the title is its first line (not with --title-column)").option("--description-column <header>", "Table: the description column").option("--priority-column <header>", "Table: the priority column").option("--category-column <header>", "Table: the category column").option("--type-column <header>", "Table: the type column").option("--status-column <header>", "Table: the status column (draft, active or done)").option("--criteria-column <header>", "Table: the acceptance criteria column").option("--map-priority <pairs>", 'Rename priority values, e.g. "Critical=Must-have,High=Should-have"').option("--map-category <pairs>", 'Table: rename category values, e.g. "Quality=non-functional"').option("--sections <heading|n>", "Read the section with this heading or number (from the list)").option("--unit <unit>", "Sections: bullets or subheadings (default: sub-headings if it has any)").option("--key-prefix <text>", "Sections: text a bullet or sub-heading starts with that carries its key").option("--priority-from <source>", "Sections: subheading \u2014 bullets take their sub-heading as priority").option("--type <type>", "What a row without a type becomes: user_story, feature or epic").option("--project <id>", "The project (default: PLUNE_PROJECT, else the only project of the account)").option("--yes", "Write it. Without it the import is a dry run", false).option("--json", "Print the platform\u2019s answer as JSON", false).action(async (file, options, command) => {
36588
37516
  const verbose = command.optsWithGlobals().verbose === true;
36589
- const { handleRequirementsImport: handleRequirementsImport2, formatDiscover: formatDiscover2, formatReport: formatReport3, reportRequirementsImportFailure: reportRequirementsImportFailure2 } = await Promise.resolve().then(() => (init_requirements_import(), requirements_import_exports));
37517
+ const { handleRequirementsImport: handleRequirementsImport2, formatDiscover: formatDiscover2, formatReport: formatReport4, reportRequirementsImportFailure: reportRequirementsImportFailure2 } = await Promise.resolve().then(() => (init_requirements_import(), requirements_import_exports));
36590
37518
  try {
36591
37519
  const res = await handleRequirementsImport2({ file, ...options });
36592
37520
  if (options.json === true) {
36593
37521
  process.stdout.write(JSON.stringify(res.step === "discover" ? res.result : res.report, null, 2) + "\n");
36594
37522
  } else {
36595
- process.stdout.write(res.step === "discover" ? formatDiscover2(file, res.result) : formatReport3(res.report));
37523
+ process.stdout.write(res.step === "discover" ? formatDiscover2(file, res.result) : formatReport4(res.report));
36596
37524
  }
36597
37525
  } catch (err) {
36598
37526
  const code = reportRequirementsImportFailure2(err, (s) => process.stderr.write(s));