@plune-ai/cli 0.39.11 → 0.39.13

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((resolve24) => setTimeout(resolve24, 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((resolve24) => {
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
- resolve24();
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((resolve24, 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
- resolve24({ 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((resolve24) => proc.once("exit", () => resolve24(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((resolve24) => timer2 = setTimeout(() => resolve24(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((resolve24, 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
- resolve24({
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((resolve24, 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 ? resolve24(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
- resolve24(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((resolve24) => waiting.push(resolve24));
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((resolve24) => {
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) => resolve24(exitCode2 ?? 1));
10798
- child.on("error", () => resolve24(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((resolve24) => timer = setTimeout(() => resolve24("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((resolve24) => timer = setTimeout(() => resolve24("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",
@@ -13803,19 +14286,19 @@ function rewriteItemRefs(text6, prefix, seen, bad) {
13803
14286
  });
13804
14287
  }
13805
14288
  function hasNonText(messages) {
13806
- const nonText = (content) => Array.isArray(content) ? content.some(nonText) : isObj(content) && typeof content.text !== "string";
13807
- return Array.isArray(messages) && messages.some((m) => isObj(m) && nonText(m.content));
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));
13808
14291
  }
13809
14292
  function textOf2(content) {
13810
14293
  if (typeof content === "string") return content;
13811
14294
  if (Array.isArray(content))
13812
14295
  return content.map(textOf2).filter((t) => t !== "").join("\n");
13813
- if (isObj(content) && typeof content.text === "string") return content.text;
14296
+ if (isObj2(content) && typeof content.text === "string") return content.text;
13814
14297
  return "";
13815
14298
  }
13816
14299
  function joinMessages(messages, keep = () => true) {
13817
14300
  if (!Array.isArray(messages)) return "";
13818
- return messages.map((m) => isObj(m) ? textOf2(m.content) : "").filter((t) => t !== "" && keep(t)).join("\n\n");
14301
+ return messages.map((m) => isObj2(m) ? textOf2(m.content) : "").filter((t) => t !== "" && keep(t)).join("\n\n");
13819
14302
  }
13820
14303
  function slug(name) {
13821
14304
  const s = typeof name === "string" ? name.toLowerCase().replace(/[^a-z0-9_-]+/g, "-").replace(/^-+|-+$/g, "") : "";
@@ -13951,8 +14434,8 @@ ${rule}`,
13951
14434
  function convertRows(items2, report) {
13952
14435
  const asText = /* @__PURE__ */ new Set();
13953
14436
  const rows = items2.map((raw, i) => {
13954
- const item = isObj(raw) && "item" in raw ? raw.item : raw;
13955
- if (!isObj(item)) throw new OpenAiEvalImportError(`test data row ${i + 1} is not an object`);
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`);
13956
14439
  const vars = Object.fromEntries(
13957
14440
  Object.entries(item).map(([key, value2]) => {
13958
14441
  if (typeof value2 === "string" || typeof value2 === "number" || typeof value2 === "boolean")
@@ -13985,19 +14468,19 @@ function parseJsonl(text6) {
13985
14468
  return out;
13986
14469
  }
13987
14470
  function convertOpenAiEval({ evalObject, run, rows }) {
13988
- if (!isObj(evalObject) || !Array.isArray(evalObject.testing_criteria)) {
14471
+ if (!isObj2(evalObject) || !Array.isArray(evalObject.testing_criteria)) {
13989
14472
  throw new OpenAiEvalImportError(
13990
14473
  "the eval file is not an eval object: it has no testing_criteria list (save the answer of GET /v1/evals/{eval_id})"
13991
14474
  );
13992
14475
  }
13993
- if (run !== void 0 && !isObj(run))
14476
+ if (run !== void 0 && !isObj2(run))
13994
14477
  throw new OpenAiEvalImportError("the run file is not a run object");
13995
14478
  const id2 = slug(evalObject.name);
13996
14479
  const report = [];
13997
14480
  const seen = /* @__PURE__ */ new Set();
13998
14481
  const assertions = [];
13999
14482
  for (const grader of evalObject.testing_criteria) {
14000
- const { assertion, line } = convertGrader(isObj(grader) ? grader : {}, seen);
14483
+ const { assertion, line } = convertGrader(isObj2(grader) ? grader : {}, seen);
14001
14484
  if (assertion !== void 0) assertions.push(assertion);
14002
14485
  report.push(line);
14003
14486
  }
@@ -14008,8 +14491,8 @@ function convertOpenAiEval({ evalObject, run, rows }) {
14008
14491
  note: "no grader was converted: the eval has no checks until you add some"
14009
14492
  });
14010
14493
  }
14011
- const source = isObj(run) && isObj(run.data_source) ? run.data_source : {};
14012
- const template = isObj(source.input_messages) ? source.input_messages.template : void 0;
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;
14013
14496
  const count6 = Array.isArray(template) ? template.length : 0;
14014
14497
  const inPrompt = /* @__PURE__ */ new Set();
14015
14498
  let prompt5 = rewriteItemRefs(joinMessages(template), "", inPrompt, /* @__PURE__ */ new Set());
@@ -14031,7 +14514,7 @@ function convertOpenAiEval({ evalObject, run, rows }) {
14031
14514
  note: "parts of its messages that are not text were left out"
14032
14515
  });
14033
14516
  }
14034
- const sampling = isObj(source.sampling_params) ? Object.keys(source.sampling_params).sort() : [];
14517
+ const sampling = isObj2(source.sampling_params) ? Object.keys(source.sampling_params).sort() : [];
14035
14518
  if (sampling.length > 0) {
14036
14519
  report.push({
14037
14520
  status: "check",
@@ -14062,18 +14545,18 @@ function convertOpenAiEval({ evalObject, run, rows }) {
14062
14545
  note: "no model was found (give a run with --run): it is set to gpt-4o"
14063
14546
  });
14064
14547
  }
14065
- const inline = isObj(source.source) && Array.isArray(source.source.content) ? source.source.content : void 0;
14548
+ const inline = isObj2(source.source) && Array.isArray(source.source.content) ? source.source.content : void 0;
14066
14549
  const fromFile = rows !== void 0 ? parseJsonl(rows) : [];
14067
14550
  const items2 = fromFile.length > 0 ? fromFile : inline;
14068
14551
  let dataset;
14069
14552
  let datasetField;
14070
14553
  if (items2 !== void 0 && items2.length > 0) {
14071
- const path25 = `datasets/${id2}.jsonl`;
14554
+ const path26 = `datasets/${id2}.jsonl`;
14072
14555
  dataset = {
14073
- path: path25,
14556
+ path: path26,
14074
14557
  jsonl: convertRows(items2, report).map((r) => JSON.stringify(r)).join("\n") + "\n"
14075
14558
  };
14076
- datasetField = `./${path25}`;
14559
+ datasetField = `./${path26}`;
14077
14560
  } else {
14078
14561
  const vars = Object.fromEntries([...seen].sort().map((n) => [n, "replace me"]));
14079
14562
  datasetField = { examples: [{ vars }] };
@@ -14106,7 +14589,7 @@ function formatReport2(report) {
14106
14589
  ${count6("converted")} converted \xB7 ${count6("approximate")} approximate \xB7 ${count6("not converted")} not converted
14107
14590
  `;
14108
14591
  }
14109
- var import_yaml4, OpenAiEvalImportError, isObj, ITEM_REF, ANY_REF, FLAT, NOT_FLAT, SAMPLE_REF, OUTPUT_TEXT, badRefs;
14592
+ var import_yaml4, OpenAiEvalImportError, isObj2, ITEM_REF, ANY_REF, FLAT, NOT_FLAT, SAMPLE_REF, OUTPUT_TEXT, badRefs;
14110
14593
  var init_from_openai_eval = __esm({
14111
14594
  "src/config/init/from-openai-eval.ts"() {
14112
14595
  "use strict";
@@ -14118,7 +14601,7 @@ var init_from_openai_eval = __esm({
14118
14601
  this.name = "OpenAiEvalImportError";
14119
14602
  }
14120
14603
  };
14121
- isObj = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
14604
+ isObj2 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
14122
14605
  ITEM_REF = /\{\{\s*item\.([^{}]*?)\s*\}\}/g;
14123
14606
  ANY_REF = /\{\{[^{}]*\}\}/g;
14124
14607
  FLAT = /^\w+$/;
@@ -14160,7 +14643,7 @@ function nextSteps(keyVar) {
14160
14643
  }
14161
14644
  function keyVarOf(cwd) {
14162
14645
  try {
14163
- const cfg = (0, import_yaml5.parse)(fs17.readFileSync(path20.join(cwd, "plune.yaml"), "utf8"));
14646
+ const cfg = (0, import_yaml5.parse)(fs18.readFileSync(path21.join(cwd, "plune.yaml"), "utf8"));
14164
14647
  const type = cfg?.provider?.type;
14165
14648
  return typeof type === "string" && Object.hasOwn(PROVIDER_KEY_VARS, type) ? PROVIDER_KEY_VARS[type] : void 0;
14166
14649
  } catch {
@@ -14172,7 +14655,7 @@ async function initFromOpenAiEval(options) {
14172
14655
  const { convertOpenAiEval: convertOpenAiEval2, formatReport: formatReport4, OpenAiEvalImportError: OpenAiEvalImportError2 } = await Promise.resolve().then(() => (init_from_openai_eval(), from_openai_eval_exports));
14173
14656
  const read = (file) => {
14174
14657
  try {
14175
- return fs17.readFileSync(path20.resolve(cwd, file), "utf8").replace(/^/, "");
14658
+ return fs18.readFileSync(path21.resolve(cwd, file), "utf8").replace(/^/, "");
14176
14659
  } catch (err) {
14177
14660
  throw new OpenAiEvalImportError2(`cannot read ${file}: ${err.message}`);
14178
14661
  }
@@ -14211,13 +14694,13 @@ async function initCommand({ cwd, force, yes = false }) {
14211
14694
  }
14212
14695
  process.stdout.write(nextSteps(keyVarOf(cwd)));
14213
14696
  }
14214
- var fs17, path20, import_yaml5, TEMPLATES;
14697
+ var fs18, path21, import_yaml5, TEMPLATES;
14215
14698
  var init_init = __esm({
14216
14699
  "src/cli/commands/init.ts"() {
14217
14700
  "use strict";
14218
14701
  init_cjs_shims();
14219
- fs17 = __toESM(require("fs"), 1);
14220
- path20 = __toESM(require("path"), 1);
14702
+ fs18 = __toESM(require("fs"), 1);
14703
+ path21 = __toESM(require("path"), 1);
14221
14704
  import_yaml5 = require("yaml");
14222
14705
  init_wizard();
14223
14706
  init_templates();
@@ -15248,7 +15731,7 @@ function createPluneToolExecutor(opts) {
15248
15731
  },
15249
15732
  async plune_get(i) {
15250
15733
  const route = { "test-case": "/v1/test-cases/:id", run: "/v1/runs/:id", "review-item": "/v1/review-items/:id" }[str2(i["kind"])];
15251
- 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"])) });
15252
15735
  return { kind: str2(i["kind"]), item: asRecord(res.body) };
15253
15736
  },
15254
15737
  async plune_cases_search(i) {
@@ -15318,12 +15801,12 @@ function createPluneToolExecutor(opts) {
15318
15801
  const { dry_run, projectId: projectId2, ...body } = i;
15319
15802
  const project = projectId2 ?? opts.projectId;
15320
15803
  if (project === void 0) return fail2("invalid_input", NO_PROJECT);
15321
- 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);
15322
15805
  },
15323
15806
  async plune_cases_generation_get(i) {
15324
15807
  const project = i["projectId"] ?? opts.projectId;
15325
15808
  if (project === void 0) return fail2("invalid_input", NO_PROJECT);
15326
- 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"])) });
15327
15810
  return { generation: asRecord(res.body) };
15328
15811
  },
15329
15812
  async plune_mission_create(i) {
@@ -15331,18 +15814,18 @@ function createPluneToolExecutor(opts) {
15331
15814
  return write({ method: "POST", path: "/v1/missions", body: withoutUndefined(body) }, dry_run);
15332
15815
  },
15333
15816
  async plune_mission_get(i) {
15334
- 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"])) });
15335
15818
  return { mission: asRecord(res.body) };
15336
15819
  },
15337
15820
  async plune_mission_update(i) {
15338
15821
  const { dry_run, missionId: missionId2, ...body } = i;
15339
- 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);
15340
15823
  },
15341
15824
  async plune_source_add(i) {
15342
15825
  const parsed4 = (i["kind"] === "file" ? fileSource : linkSource).safeParse(withoutUndefined(i));
15343
15826
  if (!parsed4.success) return fail2("invalid_input", `The input does not fit: ${zodMessage(parsed4.error)}`);
15344
15827
  const { dry_run, missionId: missionId2, kind: kind2, ...rest } = parsed4.data;
15345
- 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 }) };
15346
15829
  return write(req, dry_run);
15347
15830
  },
15348
15831
  async plune_question_ask(i) {
@@ -15364,7 +15847,7 @@ function createPluneToolExecutor(opts) {
15364
15847
  return { questions, nextCursor: cursorOf(body["nextCursor"]) };
15365
15848
  },
15366
15849
  async plune_strategy_propose(i) {
15367
- 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"] };
15368
15851
  if (i["dry_run"] === true) {
15369
15852
  try {
15370
15853
  const res = await call2({ ...req, path: `${req.path}/check` });
@@ -15374,10 +15857,10 @@ function createPluneToolExecutor(opts) {
15374
15857
  return { dryRun: true, checked: false, request: planned(req) };
15375
15858
  }
15376
15859
  }
15377
- 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"]);
15378
15861
  },
15379
15862
  async plune_report_request(i) {
15380
- 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"]);
15381
15864
  },
15382
15865
  async plune_discover_tools(i) {
15383
15866
  const names = i["names"] ?? [];
@@ -15401,7 +15884,7 @@ function createPluneToolExecutor(opts) {
15401
15884
  async plune_cases_update(i) {
15402
15885
  const cases = i["cases"];
15403
15886
  return batch(
15404
- 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 })),
15405
15888
  i["dry_run"],
15406
15889
  (_b, n) => cases[n]?.id
15407
15890
  );
@@ -15413,7 +15896,7 @@ function createPluneToolExecutor(opts) {
15413
15896
  const results4 = i["results"];
15414
15897
  const req = {
15415
15898
  method: "POST",
15416
- path: path21("/v1/runs/:id/results", str2(i["runId"])),
15899
+ path: path22("/v1/runs/:id/results", str2(i["runId"])),
15417
15900
  body: withoutUndefined({ results: results4, combination: i["combination"], configuration: i["configuration"] })
15418
15901
  };
15419
15902
  if (i["dry_run"] === true) return { dryRun: true, requested: results4.length, applied: 0, requests: [planned(req)] };
@@ -15488,7 +15971,7 @@ function createPluneToolExecutor(opts) {
15488
15971
  }
15489
15972
  };
15490
15973
  }
15491
- 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;
15492
15975
  var init_execute = __esm({
15493
15976
  "src/mcp-tools/execute.ts"() {
15494
15977
  "use strict";
@@ -15507,7 +15990,7 @@ var init_execute = __esm({
15507
15990
  error: { code, message: message2, ...extra }
15508
15991
  });
15509
15992
  zodMessage = (error) => error.issues.map((i) => `${i.path.join(".") || "(input)"}: ${i.message}`).join("; ");
15510
- path21 = (template, ...ids) => {
15993
+ path22 = (template, ...ids) => {
15511
15994
  let i = 0;
15512
15995
  return template.replace(/:[a-z]+/gi, () => encodeURIComponent(ids[i++] ?? ""));
15513
15996
  };
@@ -15639,7 +16122,7 @@ function answeringParseErrors(answer) {
15639
16122
  async function serveMcpStdio(opts) {
15640
16123
  const input = process.stdin.pipe(answeringParseErrors((line) => process.stdout.write(line)));
15641
16124
  const transport = new import_stdio2.StdioServerTransport(input, process.stdout);
15642
- await new Promise((resolve24) => {
16125
+ await new Promise((resolve25) => {
15643
16126
  (0, import_stdio2.serveStdio)((ctx) => createPluneMcpServer(opts, ctx.era), {
15644
16127
  transport,
15645
16128
  onerror: (error) => {
@@ -15657,7 +16140,7 @@ async function serveMcpStdio(opts) {
15657
16140
  const owned = transport.onclose;
15658
16141
  transport.onclose = () => {
15659
16142
  owned?.();
15660
- resolve24();
16143
+ resolve25();
15661
16144
  };
15662
16145
  });
15663
16146
  }
@@ -15790,7 +16273,7 @@ var init_run3 = __esm({
15790
16273
  now: () => import_node_perf_hooks2.performance.now(),
15791
16274
  after(ms) {
15792
16275
  let timer;
15793
- const done = new Promise((resolve24) => timer = setTimeout(resolve24, ms));
16276
+ const done = new Promise((resolve25) => timer = setTimeout(resolve25, ms));
15794
16277
  return { done, cancel: () => clearTimeout(timer) };
15795
16278
  }
15796
16279
  };
@@ -16073,10 +16556,10 @@ function schemaNodes(schema) {
16073
16556
  const children = [];
16074
16557
  for (const [name, p] of Object.entries(props(node.schema))) {
16075
16558
  if (!isRecord9(p)) continue;
16076
- const path25 = node.path === "" ? name : `${node.path}.${name}`;
16559
+ const path26 = node.path === "" ? name : `${node.path}.${name}`;
16077
16560
  const depth = node.depth + 1;
16078
- children.push({ path: path25, schema: p, kind: "param", depth });
16079
- 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 });
16080
16563
  }
16081
16564
  for (const child of children.reverse()) todo.push(child);
16082
16565
  }
@@ -17893,13 +18376,13 @@ async function lint(flags2, server2, io, rawOut) {
17893
18376
  }
17894
18377
  function readExceptions(flag2, io) {
17895
18378
  const name = flag2 ?? DEFAULT_IGNORE_FILE;
17896
- const path25 = (0, import_node_path7.resolve)(io.cwd, name);
17897
- 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)) {
17898
18381
  if (flag2 !== void 0) throw new UsageError(`--ignore-file: ${name} does not exist.`);
17899
18382
  return void 0;
17900
18383
  }
17901
18384
  const today = io.today ?? (/* @__PURE__ */ new Date()).toISOString().slice(0, 10);
17902
- 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) };
17903
18386
  }
17904
18387
  async function listTools(session2) {
17905
18388
  try {
@@ -18189,8 +18672,8 @@ async function pushSnapshot(snapshot, target4, token2, deps = {}) {
18189
18672
  sent,
18190
18673
  target4.serverId !== void 0 ? `MCP server '${serverId}'` : "the snapshot"
18191
18674
  );
18192
- const { number, hash, tools: tools2 } = sent.body;
18193
- 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") {
18194
18677
  throw new SnapshotPushError(
18195
18678
  "other",
18196
18679
  "The platform answered, but not with a snapshot (no number or hash)."
@@ -18199,7 +18682,7 @@ async function pushSnapshot(snapshot, target4, token2, deps = {}) {
18199
18682
  return {
18200
18683
  serverId,
18201
18684
  ...target4.serverName !== void 0 ? { serverName: target4.serverName.trim() } : {},
18202
- number,
18685
+ number: number2,
18203
18686
  hash,
18204
18687
  tools: typeof tools2 === "number" ? tools2 : null,
18205
18688
  created: sent.status === 201,
@@ -18444,14 +18927,14 @@ async function listAll2(session2, method, key) {
18444
18927
  }
18445
18928
  return listing.items;
18446
18929
  }
18447
- function writeAtomically(path25, text6, shown4, flag2 = "--out") {
18930
+ function writeAtomically(path26, text6, shown4, flag2 = "--out") {
18448
18931
  const temporary = (0, import_node_path8.join)(
18449
- (0, import_node_path8.dirname)(path25),
18450
- `.${(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`
18451
18934
  );
18452
18935
  try {
18453
18936
  (0, import_node_fs13.writeFileSync)(temporary, text6, { flag: "wx" });
18454
- (0, import_node_fs13.renameSync)(temporary, path25);
18937
+ (0, import_node_fs13.renameSync)(temporary, path26);
18455
18938
  } catch (err) {
18456
18939
  (0, import_node_fs13.rmSync)(temporary, { force: true });
18457
18940
  const code = err.code ?? "an error";
@@ -18665,23 +19148,23 @@ function visible(s, max = EXCERPT) {
18665
19148
  }
18666
19149
  function descriptionTexts(snapshot) {
18667
19150
  const out = [];
18668
- const add = (surface, path25, v, key = false, stringParam = false) => {
18669
- 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 });
18670
19153
  };
18671
- const schema = (path25, node) => {
18672
- if (typeof node === "string") add("tools", path25, node);
18673
- 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));
18674
19157
  else if (isRecord12(node)) {
18675
- const param = path25.at(-2) === "properties" && hasStringType(node);
19158
+ const param = path26.at(-2) === "properties" && hasStringType(node);
18676
19159
  for (const [k, v] of Object.entries(node)) {
18677
- add("tools", [...path25, k], k, true);
18678
- if (k === "description" && typeof v === "string") add("tools", [...path25, k], v, false, param);
18679
- 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);
18680
19163
  }
18681
19164
  }
18682
19165
  };
18683
- const fields = (surface, path25, entity2, names) => {
18684
- 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]);
18685
19168
  };
18686
19169
  add("instructions", ["instructions"], snapshot.instructions);
18687
19170
  snapshot.tools?.forEach((t, i) => {
@@ -18942,7 +19425,7 @@ var init_descriptions = __esm({
18942
19425
  U = (cp) => `U+${cp.toString(16).toUpperCase().padStart(4, "0")}`;
18943
19426
  SHOWN = /^[\p{L}\p{N}\p{P}\p{S} ]$/u;
18944
19427
  segment2 = (s) => typeof s === "number" ? String(s) : visible(s.replace(/~/g, "~0").replace(/\//g, "~1"), Infinity);
18945
- pointerOf = (path25) => `/${path25.map(segment2).join("/")}`;
19428
+ pointerOf = (path26) => `/${path26.map(segment2).join("/")}`;
18946
19429
  hasStringType = (schema) => schema["type"] === "string" || Array.isArray(schema["type"]) && schema["type"].includes("string");
18947
19430
  NAMES = {
18948
19431
  8234: "left-to-right embedding",
@@ -19339,14 +19822,14 @@ ${err.stderrTail.map((l) => ` ${l}
19339
19822
  throw err;
19340
19823
  }
19341
19824
  }
19342
- function readLock(path25, name, required) {
19343
- if (!(0, import_node_fs15.existsSync)(path25)) {
19825
+ function readLock(path26, name, required) {
19826
+ if (!(0, import_node_fs15.existsSync)(path26)) {
19344
19827
  if (required) throw new UsageError(`${name} does not exist; pin the server first with plune mcp pin.`);
19345
19828
  return emptyLock();
19346
19829
  }
19347
19830
  let text6;
19348
19831
  try {
19349
- text6 = (0, import_node_fs15.readFileSync)(path25, "utf8");
19832
+ text6 = (0, import_node_fs15.readFileSync)(path26, "utf8");
19350
19833
  } catch (err) {
19351
19834
  throw new UsageError(`${name}: cannot be read (${err.code ?? "an error"}).`);
19352
19835
  }
@@ -19673,12 +20156,12 @@ function hostFetch(target4, req, signal) {
19673
20156
  for (const [n, v] of Object.entries(target4.headers)) if (!given.has(n.toLowerCase())) headers.push(n, v);
19674
20157
  for (const [n, v] of req.headers) headers.push(n, v);
19675
20158
  const send3 = url.protocol === "https:" ? import_node_https2.request : import_node_http2.request;
19676
- return new Promise((resolve24, reject) => {
20159
+ return new Promise((resolve25, reject) => {
19677
20160
  const r = send3(url, { method: req.method, headers, signal }, (res) => {
19678
20161
  const pairs2 = [];
19679
20162
  for (let i = 0; i + 1 < res.rawHeaders.length; i += 2) pairs2.push([res.rawHeaders[i], res.rawHeaders[i + 1]]);
19680
20163
  const nobody = res.statusCode === 204 || res.statusCode === 304;
19681
- resolve24(
20164
+ resolve25(
19682
20165
  new Response(nobody ? null : import_node_stream3.Readable.toWeb(res), {
19683
20166
  status: res.statusCode ?? 0,
19684
20167
  headers: pairs2
@@ -19839,14 +20322,14 @@ var init_raw_http = __esm({
19839
20322
  });
19840
20323
 
19841
20324
  // src/mcp-testing/conformance/checks/modern/meta.ts
19842
- function headerMarks(schema, path25 = [], inNames = false) {
19843
- 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)]));
19844
20327
  if (!isRecord15(schema)) return [];
19845
20328
  const marks = [];
19846
- 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 });
19847
20330
  for (const [k, v] of Object.entries(schema)) {
19848
20331
  if (!inNames && k === "x-mcp-header") continue;
19849
- marks.push(...headerMarks(v, [...path25, k], !inNames && k === "properties"));
20332
+ marks.push(...headerMarks(v, [...path26, k], !inNames && k === "properties"));
19850
20333
  }
19851
20334
  return marks;
19852
20335
  }
@@ -19883,7 +20366,7 @@ var init_meta = __esm({
19883
20366
  [META.capabilities]: {}
19884
20367
  });
19885
20368
  isRecord15 = (v) => v !== null && typeof v === "object" && !Array.isArray(v);
19886
- 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");
19887
20370
  }
19888
20371
  });
19889
20372
 
@@ -20191,8 +20674,8 @@ function discoverPrm(ctx, challenge) {
20191
20674
  return prm;
20192
20675
  }
20193
20676
  }
20194
- const path25 = url.pathname === "/" ? "" : url.pathname.replace(/\/$/, "");
20195
- 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}`])];
20196
20679
  for (const u of urls) {
20197
20680
  const got2 = await getJson(ctx, u);
20198
20681
  prm.wellKnown.push(got2);
@@ -20212,14 +20695,14 @@ function discoverAs(ctx, issuer) {
20212
20695
  } catch {
20213
20696
  return { issuer, tried: [wrong(issuer, "it is not an absolute URL")], found: void 0 };
20214
20697
  }
20215
- const path25 = u.pathname === "/" ? "" : u.pathname.replace(/\/$/, "");
20216
- const urls = path25 === "" ? [
20698
+ const path26 = u.pathname === "/" ? "" : u.pathname.replace(/\/$/, "");
20699
+ const urls = path26 === "" ? [
20217
20700
  `${u.origin}/.well-known/oauth-authorization-server`,
20218
20701
  `${u.origin}/.well-known/openid-configuration`
20219
20702
  ] : [
20220
- `${u.origin}/.well-known/oauth-authorization-server${path25}`,
20221
- `${u.origin}/.well-known/openid-configuration${path25}`,
20222
- `${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`
20223
20706
  ];
20224
20707
  const as = { issuer, tried: [], found: void 0 };
20225
20708
  for (const url of urls) {
@@ -23692,7 +24175,7 @@ var init_transport = __esm({
23692
24175
  const open2 = () => {
23693
24176
  let opened2 = () => {
23694
24177
  };
23695
- const ready2 = new Promise((resolve24) => opened2 = resolve24);
24178
+ const ready2 = new Promise((resolve25) => opened2 = resolve25);
23696
24179
  const req = {
23697
24180
  method: "GET",
23698
24181
  headers: [
@@ -28479,11 +28962,11 @@ var init_security = __esm({
28479
28962
  details
28480
28963
  };
28481
28964
  };
28482
- reach = (host, p) => new Promise((resolve24) => {
28965
+ reach = (host, p) => new Promise((resolve25) => {
28483
28966
  const socket = (0, import_node_net.connect)({ host, port: p });
28484
28967
  const done = (got2) => {
28485
28968
  socket.destroy();
28486
- resolve24(got2);
28969
+ resolve25(got2);
28487
28970
  };
28488
28971
  socket.setTimeout(CONNECT_MS, () => done(`no answer in ${CONNECT_MS} ms`));
28489
28972
  socket.once("connect", () => done("open"));
@@ -29364,7 +29847,7 @@ var init_tasks = __esm({
29364
29847
  reason: "needs-input",
29365
29848
  actual
29366
29849
  });
29367
- sleep3 = (ms) => new Promise((resolve24) => setTimeout(resolve24, ms));
29850
+ sleep3 = (ms) => new Promise((resolve25) => setTimeout(resolve25, ms));
29368
29851
  results3 = (answers3) => answers3.flatMap((a) => a.kind === "result" ? [a.result] : []);
29369
29852
  resultType2 = async (ctx) => {
29370
29853
  const s = await ready(ctx);
@@ -29916,19 +30399,19 @@ function parseOauthConfig(source, format = "json") {
29916
30399
  }
29917
30400
  return config;
29918
30401
  }
29919
- function loadOauthConfig(path25) {
30402
+ function loadOauthConfig(path26) {
29920
30403
  let source;
29921
30404
  try {
29922
- if ((0, import_node_fs16.statSync)(path25).size > MAX_CONFIG_BYTES) throw new UsageError(tooLarge());
29923
- 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");
29924
30407
  } catch (err) {
29925
30408
  if (err instanceof UsageError) throw err;
29926
30409
  const code = err.code;
29927
30410
  throw new UsageError(
29928
- `--config: could not read ${path25}${code === void 0 ? "" : ` (${code})`}.`
30411
+ `--config: could not read ${path26}${code === void 0 ? "" : ` (${code})`}.`
29929
30412
  );
29930
30413
  }
29931
- return parseOauthConfig(source, /\.ya?ml$/i.test(path25) ? "yaml" : "json");
30414
+ return parseOauthConfig(source, /\.ya?ml$/i.test(path26) ? "yaml" : "json");
29932
30415
  }
29933
30416
  var import_node_fs16, import_yaml7, TOP, REGISTRATION2, METHODS, MODES, SECRET_KEY2, ENV_NAME, isObject6, MAX_CONFIG_BYTES, tooLarge;
29934
30417
  var init_auth_config = __esm({
@@ -29985,13 +30468,13 @@ var mcp_conformance_exports = {};
29985
30468
  __export(mcp_conformance_exports, {
29986
30469
  handleMcpConformance: () => handleMcpConformance
29987
30470
  });
29988
- function loadFixture(path25) {
30471
+ function loadFixture(path26) {
29989
30472
  let doc;
29990
30473
  try {
29991
- doc = JSON.parse((0, import_node_fs17.readFileSync)(path25, "utf8"));
30474
+ doc = JSON.parse((0, import_node_fs17.readFileSync)(path26, "utf8"));
29992
30475
  } catch (err) {
29993
30476
  const code = err.code;
29994
- 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})`}.`);
29995
30478
  }
29996
30479
  if (!Array.isArray(doc)) throw new UsageError('--fixture must hold a JSON list of { "tool": "<name>", "arguments": { ... } }.');
29997
30480
  return doc.map((entry2, i) => {
@@ -31242,7 +31725,7 @@ function scanCross(run, snapshots, files) {
31242
31725
  if (!places.has(s.label))
31243
31726
  places.set(s.label, { file: f.path, line: s.line, column: s.column });
31244
31727
  const where3 = (label2) => places.get(safe(label2));
31245
- const add = (rule, label2, path25, message2) => {
31728
+ const add = (rule, label2, path26, message2) => {
31246
31729
  if (full(run)) {
31247
31730
  run.truncated = true;
31248
31731
  return;
@@ -31256,7 +31739,7 @@ function scanCross(run, snapshots, files) {
31256
31739
  origin: "snapshot",
31257
31740
  ...where3(label2),
31258
31741
  server: safe(label2),
31259
- path: safePointer(path25),
31742
+ path: safePointer(path26),
31260
31743
  message: message2,
31261
31744
  fix: def2.fix
31262
31745
  });
@@ -31626,13 +32109,13 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31626
32109
  const reason = str2(item, "reason");
31627
32110
  const expires = str2(item, "expires");
31628
32111
  let server2;
31629
- let path25;
32112
+ let path26;
31630
32113
  const scope = pair(item, "scope");
31631
32114
  if (scope !== void 0 && (0, import_yaml8.isMap)(scope.value)) {
31632
32115
  server2 = str2(scope.value, "server");
31633
- path25 = str2(scope.value, "path");
32116
+ path26 = str2(scope.value, "path");
31634
32117
  } else server2 = str2(item, "scope");
31635
- if (path25 !== void 0 && path25.trim() === "")
32118
+ if (path26 !== void 0 && path26.trim() === "")
31636
32119
  fail3(item, "path must name a field; leave it out to cover the whole server.");
31637
32120
  const subject2 = printable(rule ?? "a rule");
31638
32121
  if (rule === void 0 || rule.trim() === "") fail3(item, "an entry needs a rule.");
@@ -31664,7 +32147,7 @@ function parseScanExceptions(text6, name, today, opts = {}) {
31664
32147
  const entry2 = {
31665
32148
  rule,
31666
32149
  server: server2,
31667
- ...path25 === void 0 ? {} : { path: path25 },
32150
+ ...path26 === void 0 ? {} : { path: path26 },
31668
32151
  reason,
31669
32152
  expires,
31670
32153
  line: lineOf(item)
@@ -31842,10 +32325,10 @@ function journalHeaders(headers) {
31842
32325
  ])
31843
32326
  );
31844
32327
  }
31845
- function openProbeJournal(path25) {
32328
+ function openProbeJournal(path26) {
31846
32329
  let fd;
31847
32330
  try {
31848
- fd = (0, import_node_fs18.openSync)(path25, "w", 384);
32331
+ fd = (0, import_node_fs18.openSync)(path26, "w", 384);
31849
32332
  if (process.platform !== "win32") (0, import_node_fs18.fchmodSync)(fd, 384);
31850
32333
  } catch {
31851
32334
  throw new UsageError("--journal: the file cannot be opened for writing.");
@@ -32385,9 +32868,9 @@ async function startPage() {
32385
32868
  server2.headersTimeout = 5e3;
32386
32869
  server2.requestTimeout = 5e3;
32387
32870
  server2.keepAliveTimeout = 1e3;
32388
- await new Promise((resolve24, reject) => {
32871
+ await new Promise((resolve25, reject) => {
32389
32872
  server2.once("error", reject);
32390
- server2.listen(0, "127.0.0.1", resolve24);
32873
+ server2.listen(0, "127.0.0.1", resolve25);
32391
32874
  });
32392
32875
  const { address, port: port2 } = server2.address();
32393
32876
  return {
@@ -32400,9 +32883,9 @@ async function startPage() {
32400
32883
  requestTimeout: server2.requestTimeout,
32401
32884
  keepAliveTimeout: server2.keepAliveTimeout
32402
32885
  },
32403
- close: () => new Promise((resolve24) => {
32886
+ close: () => new Promise((resolve25) => {
32404
32887
  server2.closeAllConnections();
32405
- server2.close(() => resolve24());
32888
+ server2.close(() => resolve25());
32406
32889
  })
32407
32890
  };
32408
32891
  }
@@ -33398,9 +33881,9 @@ var init_report3 = __esm({
33398
33881
  init_types();
33399
33882
  GROUPS = ["descriptions", "pins", "config", "cross", "active"];
33400
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.";
33401
- 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}
33402
33885
  ${target4}
33403
- ${path25}
33886
+ ${path26}
33404
33887
  ${nth}`, "utf8").digest("hex").slice(0, 32);
33405
33888
  where2 = (f) => f.location === void 0 ? "" : ` (${f.location.file}:${f.location.line}${f.location.column === void 0 ? "" : `:${f.location.column}`})`;
33406
33889
  IMPORT_WORDS = {
@@ -34056,15 +34539,15 @@ function groupsOf(flag2, values) {
34056
34539
  throw new UsageError(`${flag2}: "${n}" is not a group (${GROUPS.join(", ")}).`);
34057
34540
  return names;
34058
34541
  }
34059
- function shown3(cwd, path25) {
34060
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
34542
+ function shown3(cwd, path26) {
34543
+ const full2 = (0, import_node_path12.resolve)(cwd, path26);
34061
34544
  const rel = (0, import_node_path12.relative)(cwd, full2);
34062
34545
  return rel !== "" && !rel.startsWith("..") && !(0, import_node_path12.isAbsolute)(rel) ? rel.replace(/\\/g, "/") : (0, import_node_path12.basename)(full2);
34063
34546
  }
34064
- function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
34065
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
34066
- if (!(0, import_node_fs19.existsSync)(full2)) throw new UsageError(`${flag2}: ${path25} does not exist.`);
34067
- 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.`);
34068
34551
  let size = 0;
34069
34552
  if (limit3)
34070
34553
  try {
@@ -34074,7 +34557,7 @@ function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
34074
34557
  }
34075
34558
  if (size > max)
34076
34559
  throw new TooLargeError(
34077
- `${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`}).`
34078
34561
  );
34079
34562
  try {
34080
34563
  return (0, import_node_fs19.readFileSync)(full2, "utf8");
@@ -34082,8 +34565,8 @@ function readText(cwd, path25, flag2, limit3 = true, max = MAX_FILE_BYTES) {
34082
34565
  throw unreadable2();
34083
34566
  }
34084
34567
  }
34085
- function clientOf(path25) {
34086
- const p = path25.replace(/\\/g, "/").toLowerCase();
34568
+ function clientOf(path26) {
34569
+ const p = path26.replace(/\\/g, "/").toLowerCase();
34087
34570
  if (p.endsWith("claude_desktop_config.json")) return "claude-desktop";
34088
34571
  if (p.includes(".cursor/")) return "cursor";
34089
34572
  if (p.includes(".vscode/")) return "vscode";
@@ -34102,8 +34585,8 @@ async function handleMcpScan(flags2, server2, raw) {
34102
34585
  throw err;
34103
34586
  }
34104
34587
  }
34105
- function fileKeys(cwd, path25) {
34106
- const full2 = (0, import_node_path12.resolve)(cwd, path25);
34588
+ function fileKeys(cwd, path26) {
34589
+ const full2 = (0, import_node_path12.resolve)(cwd, path26);
34107
34590
  const keys = [];
34108
34591
  let real = full2;
34109
34592
  try {
@@ -34138,9 +34621,9 @@ function noSharedFiles(flags2, outputs, cwd) {
34138
34621
  ...flags2.debugOut === void 0 ? [] : [["--debug-out", flags2.debugOut]]
34139
34622
  ];
34140
34623
  const seen = /* @__PURE__ */ new Map();
34141
- for (const [flag2, path25] of reads) for (const key of fileKeys(cwd, path25)) seen.set(key, flag2);
34142
- for (const [flag2, path25] of writes) {
34143
- 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);
34144
34627
  for (const key of keys) {
34145
34628
  const other = seen.get(key);
34146
34629
  if (other !== void 0 && other !== flag2 + "#w")
@@ -34185,14 +34668,14 @@ async function scan(flags2, server2, io) {
34185
34668
  const unreadable2 = [];
34186
34669
  for (const spec of flags2.snapshot ?? []) {
34187
34670
  const named2 = /^([A-Za-z0-9_.-]+)=(.+)$/s.exec(spec);
34188
- const path25 = named2 === null ? spec : named2[2] ?? "";
34671
+ const path26 = named2 === null ? spec : named2[2] ?? "";
34189
34672
  let text6;
34190
34673
  try {
34191
- text6 = readText(io.cwd, path25, "--snapshot");
34674
+ text6 = readText(io.cwd, path26, "--snapshot");
34192
34675
  } catch (err) {
34193
34676
  if (!(err instanceof TooLargeError) && !(err instanceof UnreadableError)) throw err;
34194
34677
  unreadable2.push({
34195
- target: shown3(io.cwd, path25),
34678
+ target: shown3(io.cwd, path26),
34196
34679
  reason: err instanceof TooLargeError ? "the file is too large to read (over 8 MiB)" : "the file cannot be read"
34197
34680
  });
34198
34681
  continue;
@@ -34202,11 +34685,11 @@ async function scan(flags2, server2, io) {
34202
34685
  snapshot = parseSnapshot(text6);
34203
34686
  } catch (err) {
34204
34687
  if (err instanceof SnapshotFormatError)
34205
- throw new UsageError(`--snapshot ${path25}: ${err.message}.`);
34688
+ throw new UsageError(`--snapshot ${path26}: ${err.message}.`);
34206
34689
  throw err;
34207
34690
  }
34208
- const label2 = named2?.[1] ?? (snapshot.server?.name !== void 0 && snapshot.server.name !== "" ? snapshot.server.name : (0, import_node_path12.basename)(path25).replace(/\.[^.]*$/, ""));
34209
- 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 });
34210
34693
  }
34211
34694
  if (live) {
34212
34695
  const config = connectionConfig(flags2, server2, io.env);
@@ -34249,23 +34732,23 @@ async function scan(flags2, server2, io) {
34249
34732
  }
34250
34733
  const configFiles = [];
34251
34734
  let configMissing;
34252
- for (const path25 of flags2.config ?? [])
34735
+ for (const path26 of flags2.config ?? [])
34253
34736
  configFiles.push({
34254
- path: shown3(io.cwd, path25),
34255
- client: flags2.client ?? clientOf(path25),
34256
- 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)
34257
34740
  });
34258
34741
  let configRequested = (flags2.config ?? []).length > 0;
34259
34742
  if ((flags2.config ?? []).length === 0 && flags2.client !== void 0) {
34260
34743
  configRequested = true;
34261
- const path25 = CLIENT_FILES[flags2.client];
34262
- 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)))
34263
34746
  configFiles.push({
34264
- path: path25,
34747
+ path: path26,
34265
34748
  client: flags2.client,
34266
- text: readText(io.cwd, path25, "--client", false)
34749
+ text: readText(io.cwd, path26, "--client", false)
34267
34750
  });
34268
- else configMissing = `${path25} is not in this folder`;
34751
+ else configMissing = `${path26} is not in this folder`;
34269
34752
  }
34270
34753
  let pin;
34271
34754
  let pinProblem;
@@ -34429,14 +34912,14 @@ var init_mcp_scan = __esm({
34429
34912
 
34430
34913
  // src/cli/commands/cairn-artifact.ts
34431
34914
  async function findLatestCairnRun(runsDir = "runs") {
34432
- const entries2 = await fs18.readdir(runsDir, { withFileTypes: true }).catch(() => null);
34915
+ const entries2 = await fs19.readdir(runsDir, { withFileTypes: true }).catch(() => null);
34433
34916
  if (entries2 === null) throw new NoCairnRunsError(runsDir);
34434
34917
  let newest;
34435
34918
  for (const entry2 of entries2) {
34436
34919
  if (!entry2.isDirectory()) continue;
34437
- const dir = path22.join(runsDir, entry2.name);
34920
+ const dir = path23.join(runsDir, entry2.name);
34438
34921
  try {
34439
- const report = await fs18.lstat(path22.join(dir, "report.json"));
34922
+ const report = await fs19.lstat(path23.join(dir, "report.json"));
34440
34923
  if (!report.isFile()) continue;
34441
34924
  if (newest === void 0 || report.mtimeMs > newest.at) {
34442
34925
  newest = { dir, at: report.mtimeMs };
@@ -34450,7 +34933,7 @@ async function findLatestCairnRun(runsDir = "runs") {
34450
34933
  async function checkSize(dir, file) {
34451
34934
  let size;
34452
34935
  try {
34453
- const st = await fs18.stat(path22.join(dir, file));
34936
+ const st = await fs19.stat(path23.join(dir, file));
34454
34937
  if (!st.isFile()) throw new CairnArtifactShapeError(file, "", "is not a regular file");
34455
34938
  size = st.size;
34456
34939
  } catch (e) {
@@ -34468,7 +34951,7 @@ async function checkSize(dir, file) {
34468
34951
  }
34469
34952
  async function readJson(file) {
34470
34953
  try {
34471
- return JSON.parse(await fs18.readFile(file, "utf8"));
34954
+ return JSON.parse(await fs19.readFile(file, "utf8"));
34472
34955
  } catch {
34473
34956
  return void 0;
34474
34957
  }
@@ -34487,7 +34970,7 @@ async function readMcpEvidence(dir, states) {
34487
34970
  if (!await checkSize(dir, file)) return void 0;
34488
34971
  let raw;
34489
34972
  try {
34490
- raw = JSON.parse(await fs18.readFile(path22.join(dir, file), "utf8"));
34973
+ raw = JSON.parse(await fs19.readFile(path23.join(dir, file), "utf8"));
34491
34974
  } catch {
34492
34975
  throw new CairnArtifactShapeError(file, "", "is not valid JSON");
34493
34976
  }
@@ -34617,7 +35100,7 @@ async function casesFromMcp(dir, report) {
34617
35100
  });
34618
35101
  }
34619
35102
  async function defaultReadEvidence(dir) {
34620
- const raw = await readJson(path22.join(dir, "api-evidence.json"));
35103
+ const raw = await readJson(path23.join(dir, "api-evidence.json"));
34621
35104
  if (!Array.isArray(raw)) return void 0;
34622
35105
  return raw.map((r) => {
34623
35106
  const rec = asRecord2(r);
@@ -34677,7 +35160,7 @@ function casesFromApi(report, verdicts) {
34677
35160
  }
34678
35161
  async function readCairnRun(dir, deps = {}) {
34679
35162
  await checkSize(dir, "report.json");
34680
- const raw = await readJson(path22.join(dir, "report.json"));
35163
+ const raw = await readJson(path23.join(dir, "report.json"));
34681
35164
  if (raw === void 0) throw new CairnRunNotFoundError(dir);
34682
35165
  const report = asRecord2(raw);
34683
35166
  if (report["schemaVersion"] !== SUPPORTED_ARTIFACT_VERSION) {
@@ -34710,7 +35193,7 @@ async function readCairnRun(dir, deps = {}) {
34710
35193
  return {
34711
35194
  schemaVersion: INGEST_SCHEMA_VERSION,
34712
35195
  run: {
34713
- runId: str(report["runId"], path22.basename(dir)),
35196
+ runId: str(report["runId"], path23.basename(dir)),
34714
35197
  mode,
34715
35198
  target: str(report["url"], "unknown"),
34716
35199
  // Cairn states the run's tokens as `cost.totalTokens` in every mode; the platform copies it onto each proposal.
@@ -34720,22 +35203,22 @@ async function readCairnRun(dir, deps = {}) {
34720
35203
  };
34721
35204
  }
34722
35205
  async function readCairnSessionFiles(dir) {
34723
- const raw = await readJson(path22.join(dir, "screencasts", "screencasts.json"));
35206
+ const raw = await readJson(path23.join(dir, "screencasts", "screencasts.json"));
34724
35207
  if (!Array.isArray(raw)) return void 0;
34725
- const root = await fs18.realpath(dir).catch(() => path22.resolve(dir));
35208
+ const root = await fs19.realpath(dir).catch(() => path23.resolve(dir));
34726
35209
  const within2 = (p) => {
34727
- const rel = path22.relative(root, p);
34728
- return rel !== "" && !rel.startsWith("..") && !path22.isAbsolute(rel);
35210
+ const rel = path23.relative(root, p);
35211
+ return rel !== "" && !rel.startsWith("..") && !path23.isAbsolute(rel);
34729
35212
  };
34730
35213
  let outside = 0;
34731
35214
  const inside = async (p) => {
34732
35215
  if (typeof p !== "string" || p === "") return void 0;
34733
- const abs = path22.resolve(root, p);
34734
- 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);
34735
35218
  if (within2(abs) && (real === void 0 || within2(real))) {
34736
35219
  const file = real ?? abs;
34737
- const size = await fs18.stat(file).then((s) => s.size, () => void 0);
34738
- 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 } : {} };
34739
35222
  }
34740
35223
  outside += 1;
34741
35224
  return void 0;
@@ -34761,7 +35244,7 @@ async function readCairnSessionFiles(dir) {
34761
35244
  const keys = new Set(declared2.flatMap((s) => s.files.map((f) => f.key)));
34762
35245
  const title = clip(str(own2(rec, "test")));
34763
35246
  const files = found.filter((f) => {
34764
- 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;
34765
35248
  keys.add(f.rel);
34766
35249
  return true;
34767
35250
  });
@@ -34777,19 +35260,19 @@ async function readCairnSessionFiles(dir) {
34777
35260
  const atMs = own2(chapter, "atMs");
34778
35261
  return t !== "" && Number.isInteger(atMs) && atMs >= 0 ? [{ title: t, atMs }] : [];
34779
35262
  }).slice(0, DECLARED.chapters),
34780
- 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 }))
34781
35264
  });
34782
35265
  screencasts.set(stableId, declared2);
34783
35266
  }
34784
35267
  return { byCase, screencasts, unmapped, outside };
34785
35268
  }
34786
- 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;
34787
35270
  var init_cairn_artifact = __esm({
34788
35271
  "src/cli/commands/cairn-artifact.ts"() {
34789
35272
  "use strict";
34790
35273
  init_cjs_shims();
34791
- fs18 = __toESM(require("fs/promises"), 1);
34792
- path22 = __toESM(require("path"), 1);
35274
+ fs19 = __toESM(require("fs/promises"), 1);
35275
+ path23 = __toESM(require("path"), 1);
34793
35276
  init_trace_url();
34794
35277
  init_config();
34795
35278
  init_errors2();
@@ -34941,13 +35424,13 @@ async function sendSessionFiles(session2, sent, platform) {
34941
35424
  if (paths === void 0 || placed.has(item.stableId)) continue;
34942
35425
  placed.add(item.stableId);
34943
35426
  for (const { path: file, size, key } of paths) {
34944
- const name = path23.basename(file);
35427
+ const name = path24.basename(file);
34945
35428
  if (size !== void 0 && size > SESSION_FILE_MAX) {
34946
35429
  tooBig += 1;
34947
35430
  lines.push(`"${name}" skipped \u2014 larger than the ${SESSION_FILE_MAX / (1024 * 1024)} MiB a session file may be`);
34948
35431
  continue;
34949
35432
  }
34950
- 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";
34951
35434
  jobs.push({
34952
35435
  id: item.reviewItemId ?? item.resultId,
34953
35436
  ...item.reviewItemId !== void 0 ? { owner: "review-items" } : {},
@@ -35023,7 +35506,7 @@ async function handleIngest(deps) {
35023
35506
  const doFetch = deps.fetchImpl ?? fetch;
35024
35507
  const endpoint = `${apiUrl}/v1/ingest/cairn`;
35025
35508
  const job = new JobReporter(doFetch, apiUrl, token2, "ingest");
35026
- await job.open(path23.basename(path23.resolve(dir)), payload2.cases.length);
35509
+ await job.open(path24.basename(path24.resolve(dir)), payload2.cases.length);
35027
35510
  try {
35028
35511
  const { result: result2, ...sent } = await upload();
35029
35512
  await job.uploaded({ subjectId: result2.runId || void 0 });
@@ -35101,12 +35584,12 @@ function formatIngestResult(r) {
35101
35584
  return `${lines.join("\n")}
35102
35585
  `;
35103
35586
  }
35104
- 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;
35105
35588
  var init_ingest = __esm({
35106
35589
  "src/cli/commands/ingest.ts"() {
35107
35590
  "use strict";
35108
35591
  init_cjs_shims();
35109
- path23 = __toESM(require("path"), 1);
35592
+ path24 = __toESM(require("path"), 1);
35110
35593
  init_client();
35111
35594
  init_env2();
35112
35595
  init_session2();
@@ -35731,8 +36214,8 @@ function filteredDotenv(text6, token2) {
35731
36214
  }).join("\n");
35732
36215
  }
35733
36216
  function filesUnder(dir) {
35734
- if (!fs19.existsSync(dir)) return [];
35735
- 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();
35736
36219
  }
35737
36220
  function newFilesDiff(files) {
35738
36221
  return files.map((f) => {
@@ -35748,13 +36231,13 @@ function newFilesDiff(files) {
35748
36231
  }).join("");
35749
36232
  }
35750
36233
  function findExecutable(command, env) {
35751
- 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;
35752
36235
  const exts = process.platform === "win32" ? (env["PATHEXT"] ?? ".COM;.EXE;.BAT;.CMD").split(";") : [""];
35753
- 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 !== "");
35754
36237
  for (const dir of dirs)
35755
36238
  for (const ext of exts) {
35756
- const candidate = path24.join(dir, command + ext);
35757
- 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;
35758
36241
  }
35759
36242
  return void 0;
35760
36243
  }
@@ -35762,8 +36245,8 @@ async function handleAutomate(deps) {
35762
36245
  for (const a of deps.cairnArgs ?? [])
35763
36246
  if (/^--(run|into-project)(=|$)/.test(a))
35764
36247
  throw new SyncFileError(`${a} is not passed to Cairn: plune automate owns the run folder and does not write into the repo.`);
35765
- const repo = path24.resolve(deps.repo ?? process.cwd());
35766
- 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).`);
35767
36250
  const env = deps.env ?? process.env;
35768
36251
  const command = deps.cairn ?? "cairn";
35769
36252
  const executable = findExecutable(command, env);
@@ -35779,33 +36262,33 @@ async function handleAutomate(deps) {
35779
36262
  throw err;
35780
36263
  }
35781
36264
  if (!detail.steps?.length) throw new CaseNotAutomatableError(deps.caseId, detail.type);
35782
- const tmp = fs19.mkdtempSync(path24.join(os.tmpdir(), "plune-automate-"));
36265
+ const tmp = fs20.mkdtempSync(path25.join(os.tmpdir(), "plune-automate-"));
35783
36266
  try {
35784
- const runDir = path24.join(tmp, "run");
35785
- fs19.mkdirSync(path24.join(runDir, "testcases"), { recursive: true });
35786
- fs19.writeFileSync(path24.join(runDir, "report.json"), JSON.stringify({ url: deps.url ?? "", mode: "design" }, null, 2));
35787
- fs19.writeFileSync(path24.join(runDir, "testcases", "ATC-PLUNE-001.md"), caseToAtcMarkdown(detail));
35788
- const dotenvSource = env["DOTENV_PATH"] ?? env["DOTENV_CONFIG_PATH"] ?? path24.join(repo, ".env");
35789
- const dotenvCopy = path24.join(tmp, "cairn.env");
35790
- 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) : "");
35791
36274
  const childEnv = { ...cairnEnv(env, token2), DOTENV_PATH: dotenvCopy, DOTENV_CONFIG_PATH: dotenvCopy };
35792
36275
  const isScript = /\.[cm]?js$/i.test(executable);
35793
36276
  const viaShell = process.platform === "win32" && /\.(cmd|bat)$/i.test(executable);
35794
36277
  const quoted = (s) => `"${s.replace(/"/g, '""')}"`;
35795
36278
  const spawnImpl = deps.spawnImpl ?? import_node_child_process5.spawn;
35796
- const runCairn = (args, capture) => new Promise((resolve24) => {
36279
+ const runCairn = (args, capture) => new Promise((resolve25) => {
35797
36280
  const opts = { cwd: repo, env: childEnv, stdio: ["ignore", capture ? "pipe" : 2, 2] };
35798
36281
  const child = isScript ? spawnImpl(process.execPath, [executable, ...args], opts) : viaShell ? spawnImpl([executable, ...args].map(quoted).join(" "), { ...opts, shell: true }) : spawnImpl(executable, args, opts);
35799
36282
  let out = "";
35800
36283
  child.stdout?.on("data", (chunk2) => void (out += chunk2.toString("utf8")));
35801
- child.on("close", (exitCode2) => resolve24({ code: exitCode2 ?? 1, out }));
35802
- child.on("error", () => resolve24({ code: -1, out }));
36284
+ child.on("close", (exitCode2) => resolve25({ code: exitCode2 ?? 1, out }));
36285
+ child.on("error", () => resolve25({ code: -1, out }));
35803
36286
  });
35804
36287
  const { code } = await runCairn(["automate", "--run", runDir, ...deps.cairnArgs ?? []], false);
35805
36288
  if (code === -1) throw new CairnMissingError(command);
35806
36289
  if (code !== 0) throw new CairnFailedError(code);
35807
- const testsDir = path24.join(runDir, "tests");
35808
- 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") }));
35809
36292
  if (files.length === 0) throw new CairnProducedNothingError();
35810
36293
  const result2 = { case: detail, files, diff: newFilesDiff(files) };
35811
36294
  if (!deps.withCairnVersion) return result2;
@@ -35813,7 +36296,7 @@ async function handleAutomate(deps) {
35813
36296
  const cairnVersion = (v.code === 0 ? /\d+\.\d+[\w.+-]*/.exec(v.out)?.[0] : void 0) ?? "unknown";
35814
36297
  return { ...result2, cairnVersion: cairnVersion.slice(0, AUTOMATION_ORIGIN_MAX) };
35815
36298
  } finally {
35816
- fs19.rmSync(tmp, { recursive: true, force: true });
36299
+ fs20.rmSync(tmp, { recursive: true, force: true });
35817
36300
  }
35818
36301
  }
35819
36302
  function skipNonCode(s, i, prev) {
@@ -35976,15 +36459,15 @@ function reportAutomateFailure(err, write) {
35976
36459
  }
35977
36460
  return reportCasesFailure(err, write);
35978
36461
  }
35979
- 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;
35980
36463
  var init_automate = __esm({
35981
36464
  "src/cli/commands/automate.ts"() {
35982
36465
  "use strict";
35983
36466
  init_cjs_shims();
35984
36467
  import_node_child_process5 = require("child_process");
35985
- fs19 = __toESM(require("fs"), 1);
36468
+ fs20 = __toESM(require("fs"), 1);
35986
36469
  os = __toESM(require("os"), 1);
35987
- path24 = __toESM(require("path"), 1);
36470
+ path25 = __toESM(require("path"), 1);
35988
36471
  init_api_url();
35989
36472
  init_credentials();
35990
36473
  init_plan();
@@ -36185,16 +36668,16 @@ init_options2();
36185
36668
 
36186
36669
  // src/cli/config-flag.ts
36187
36670
  init_cjs_shims();
36188
- function configFlagValues(args, path25) {
36671
+ function configFlagValues(args, path26) {
36189
36672
  const out = { before: [], after: [] };
36190
36673
  let next = 0;
36191
36674
  let side = "before";
36192
36675
  for (let i = 0; i < args.length; i++) {
36193
36676
  const arg = args[i];
36194
36677
  if (arg === "--") break;
36195
- if (side === "before" && arg === path25[next]) {
36678
+ if (side === "before" && arg === path26[next]) {
36196
36679
  next += 1;
36197
- if (next === path25.length) side = "after";
36680
+ if (next === path26.length) side = "after";
36198
36681
  continue;
36199
36682
  }
36200
36683
  const long = arg.startsWith("--config=") ? arg.slice("--config=".length) : void 0;
@@ -36613,14 +37096,14 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36613
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(
36614
37097
  async (baseline, current, options, command) => {
36615
37098
  const verbose = command.optsWithGlobals().verbose === true;
36616
- const [{ handleDiff: handleDiff2, DiffInputError: DiffInputError2 }, { renderDiff: renderDiff2 }] = await Promise.all([
37099
+ const [{ diffFiles: diffFiles2, DiffInputError: DiffInputError2 }, { renderDiff: renderDiff2 }] = await Promise.all([
36617
37100
  Promise.resolve().then(() => (init_diff4(), diff_exports2)),
36618
37101
  Promise.resolve().then(() => (init_diff2(), diff_exports))
36619
37102
  ]);
36620
37103
  try {
36621
37104
  const { format: _format, output: _output, ...gateFlags } = options;
36622
- const diff2 = handleDiff2({ baselinePath: baseline, currentPath: current, ...gateFlags });
36623
- 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);
36624
37107
  process.exitCode = diff2.gates?.exitCode ?? 0;
36625
37108
  } catch (err) {
36626
37109
  if (err instanceof DiffInputError2) {
@@ -36633,6 +37116,27 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36633
37116
  }
36634
37117
  }
36635
37118
  );
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) => {
37122
+ const verbose = command.optsWithGlobals().verbose === true;
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))
37126
+ ]);
37127
+ try {
37128
+ process.exitCode = await handleJudgeCheck2(labels, options, process.cwd(), (t) => {
37129
+ process.stdout.write(t);
37130
+ });
37131
+ } catch (err) {
37132
+ if (err instanceof JudgeCheckError2) {
37133
+ process.stderr.write(err.message + "\n");
37134
+ process.exit(2);
37135
+ return;
37136
+ }
37137
+ failUnexpected(err, verbose);
37138
+ }
37139
+ });
36636
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(
36637
37141
  "--from-openai-eval <eval.json>",
36638
37142
  "Build plune.yaml from an exported OpenAI eval (the answer of GET /v1/evals/{eval_id}) and print what each grader became"
@@ -36684,10 +37188,10 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36684
37188
  const { handleLogin: handleLogin2, reportLoginFailure: reportLoginFailure2 } = await Promise.resolve().then(() => (init_login(), login_exports));
36685
37189
  try {
36686
37190
  const token2 = options.token ?? await readTokenFromStdin();
36687
- const { path: path25, verified } = await handleLogin2({ token: token2, skipVerify: options.skipVerify });
37191
+ const { path: path26, verified } = await handleLogin2({ token: token2, skipVerify: options.skipVerify });
36688
37192
  process.stdout.write(
36689
- verified ? `Logged in. Token checked against the API and saved to ${path25}
36690
- ` : `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).
36691
37195
  `
36692
37196
  );
36693
37197
  } catch (err) {
@@ -36704,9 +37208,9 @@ ${missed.map((m) => ` - ${m}`).join("\n")}
36704
37208
  const verbose = command.optsWithGlobals().verbose === true;
36705
37209
  const { handleLogout: handleLogout2 } = await Promise.resolve().then(() => (init_logout(), logout_exports));
36706
37210
  try {
36707
- const { removed, path: path25 } = handleLogout2();
37211
+ const { removed, path: path26 } = handleLogout2();
36708
37212
  process.stdout.write(
36709
- removed ? `Logged out. Removed ${path25}
37213
+ removed ? `Logged out. Removed ${path26}
36710
37214
  ` : "Not logged in \u2014 nothing to remove.\n"
36711
37215
  );
36712
37216
  } catch (err) {