haansi 0.1.103 → 0.1.105

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (2) hide show
  1. package/dist/haansi.js +1027 -359
  2. package/package.json +1 -1
package/dist/haansi.js CHANGED
@@ -95,7 +95,7 @@ var require_package = __commonJS({
95
95
  "package.json"(exports2, module2) {
96
96
  module2.exports = {
97
97
  name: "haansi",
98
- version: "0.1.103",
98
+ version: "0.1.105",
99
99
  description: "Haansi CLI - Session collector and MCP server for Claude Code & OpenAI Codex",
100
100
  bin: {
101
101
  haansi: "./dist/haansi.js"
@@ -85972,6 +85972,53 @@ function relativePaths(text, root) {
85972
85972
  out = out.split(r).join("");
85973
85973
  return out.replace(TEMP_CHECKOUT, "");
85974
85974
  }
85975
+ function sectionParts(title) {
85976
+ const parts = [];
85977
+ let depth = 0;
85978
+ let part = "";
85979
+ for (const c of title) {
85980
+ if (c === "[") depth += 1;
85981
+ else if (c === "]") depth = Math.max(0, depth - 1);
85982
+ if (c === "." && depth === 0) {
85983
+ parts.push(part);
85984
+ part = "";
85985
+ } else part += c;
85986
+ }
85987
+ return [...parts, part];
85988
+ }
85989
+ function pytestMessages(lines, failing) {
85990
+ const out = /* @__PURE__ */ new Map();
85991
+ for (let i = 0; i < lines.length; i++) {
85992
+ const header = PYTEST_SECTION.exec(lines[i].trim());
85993
+ if (!header) continue;
85994
+ const body = [];
85995
+ let j = i + 1;
85996
+ for (; j < lines.length; j++) {
85997
+ const t = lines[j].trim();
85998
+ if (PYTEST_SECTION.test(t) || /^={3,}/.test(t)) break;
85999
+ body.push(lines[j]);
86000
+ }
86001
+ const parts = sectionParts(header[1]);
86002
+ const named = failing.filter((name2) => {
86003
+ const [file2, ...rest] = name2.split(" \u203A ");
86004
+ return /\.py$/.test(file2) && rest.join("\0") === parts.join("\0");
86005
+ });
86006
+ const name = named.find((n) => body.some((l) => l.includes(n.split(" \u203A ")[0]))) ?? named[0];
86007
+ i = j - 1;
86008
+ if (!name || out.has(name)) continue;
86009
+ const errors = body.filter((l) => /^E(?:\s|$)/.test(l)).map((l) => l.slice(1)).slice(0, MESSAGE_LINES);
86010
+ if (!errors.length) continue;
86011
+ const indent = Math.min(
86012
+ ...errors.filter((l) => l.trim()).map((l) => /^\s*/.exec(l)[0].length)
86013
+ );
86014
+ const where = body.filter((l) => PYTEST_WHERE.test(l.trim())).at(-1);
86015
+ out.set(
86016
+ name,
86017
+ [...errors.map((l) => l.slice(indent)), ...where ? [where.trim()] : []].join("\n").trim()
86018
+ );
86019
+ }
86020
+ return out;
86021
+ }
85975
86022
  function messageAt(lines, i) {
85976
86023
  const inline = /^FAILED\s+\S+\s+-\s+(.+)$/.exec(lines[i].trim());
85977
86024
  if (inline) return inline[1];
@@ -85990,15 +86037,17 @@ function testErrorsOf(output, root) {
85990
86037
  const lines = output.split(/\r?\n/).map((l) => relativePaths(l.replace(ANSI, "").trimEnd(), root));
85991
86038
  const failing = [];
85992
86039
  const messages = /* @__PURE__ */ new Map();
85993
- lines.forEach((line, i) => {
86040
+ for (const line of lines) {
85994
86041
  const name = failingTestIn(line);
85995
- if (!name) return;
85996
- if (!failing.includes(name)) {
85997
- if (failing.length >= MAX_ERROR_TESTS) return;
86042
+ if (name && !failing.includes(name) && failing.length < MAX_ERROR_TESTS)
85998
86043
  failing.push(name);
85999
- }
86044
+ }
86045
+ const pytest = pytestMessages(lines, failing);
86046
+ lines.forEach((line, i) => {
86047
+ const name = failingTestIn(line);
86048
+ if (!name || !failing.includes(name)) return;
86000
86049
  if (!messages.has(name)) {
86001
- const message = messageAt(lines, i);
86050
+ const message = pytest.get(name) ?? messageAt(lines, i);
86002
86051
  if (message) messages.set(name, message);
86003
86052
  }
86004
86053
  });
@@ -86023,7 +86072,7 @@ ${text.slice(-MAX_ERROR_OUTPUT_CHARS)}` : text
86023
86072
  };
86024
86073
  }
86025
86074
  const summary = scrubSecrets(
86026
- [...new Set(lines.filter((l) => SUMMARY.test(l)).map((l) => l.trim()))].slice(-4).join("\n")
86075
+ [...new Set(lines.filter(isSummary).map((l) => l.trim()))].slice(-4).join("\n")
86027
86076
  );
86028
86077
  const budget = MAX_ERROR_OUTPUT_CHARS - summary.length - 16;
86029
86078
  const sections = [];
@@ -86050,35 +86099,47 @@ function attemptErrorOf(output, at, root) {
86050
86099
  }
86051
86100
  function testCountsOf(output) {
86052
86101
  const lines = output.split(/\r?\n/).map((l) => l.replace(ANSI, "").trim());
86053
- for (let i = lines.length - 1; i >= 0; i--) {
86054
- const line = lines[i];
86102
+ let js = null;
86103
+ let py = null;
86104
+ for (const line of lines) {
86055
86105
  const vitest = /^Tests\s+(.+?)\s+\((\d+)\)$/.exec(line);
86056
86106
  if (vitest && /\b(passed|failed)\b/.test(vitest[1]))
86057
- return {
86107
+ js = {
86058
86108
  passed: count(vitest[1], "passed"),
86059
86109
  failed: count(vitest[1], "failed"),
86060
86110
  total: Number(vitest[2])
86061
86111
  };
86062
86112
  const jest = /^Tests:\s+(.+?)(\d+)\s+total$/.exec(line);
86063
86113
  if (jest)
86064
- return {
86114
+ js = {
86065
86115
  passed: count(jest[1], "passed"),
86066
86116
  failed: count(jest[1], "failed"),
86067
86117
  total: Number(jest[2])
86068
86118
  };
86069
- const pytest = /^=+\s+(.*\b(?:passed|failed)\b.*?)\s+in\s+[\d.]+s.*=+$/.exec(line);
86070
- if (pytest) {
86119
+ const pytest = PYTEST_SUMMARY.exec(line);
86120
+ if (pytest && /\b(?:passed|failed|errors?)\b/.test(pytest[1])) {
86071
86121
  const passed = count(pytest[1], "passed");
86072
86122
  const failed = count(pytest[1], "failed") + count(pytest[1], "error");
86073
86123
  const others = count(pytest[1], "skipped") + count(pytest[1], "xfailed") + count(pytest[1], "xpassed");
86074
- return { passed, failed, total: passed + failed + others };
86124
+ const before = py ?? { passed: 0, failed: 0, total: 0 };
86125
+ py = {
86126
+ passed: before.passed + passed,
86127
+ failed: before.failed + failed,
86128
+ total: before.total + passed + failed + others
86129
+ };
86075
86130
  }
86076
86131
  }
86132
+ if (js || py)
86133
+ return {
86134
+ passed: (js?.passed ?? 0) + (py?.passed ?? 0),
86135
+ failed: (js?.failed ?? 0) + (py?.failed ?? 0),
86136
+ total: (js?.total ?? 0) + (py?.total ?? 0)
86137
+ };
86077
86138
  const goPass = lines.filter((l) => /^--- PASS:/.test(l)).length;
86078
86139
  const goFail = lines.filter((l) => /^--- FAIL:/.test(l)).length;
86079
86140
  return goPass + goFail > 0 ? { passed: goPass, failed: goFail, total: goPass + goFail } : null;
86080
86141
  }
86081
- var MAX_ERROR_TESTS, MAX_ERROR_OUTPUT_CHARS, MAX_TEST_MESSAGE_CHARS, SUITE_LOAD_FAILED, OUTPUT_LINES, MESSAGE_LINES, ANSI, JS_FILE, SECRET_PATTERNS, TEMP_CHECKOUT, MESSAGE_END, SUMMARY, cut, count;
86142
+ var MAX_ERROR_TESTS, MAX_ERROR_OUTPUT_CHARS, MAX_TEST_MESSAGE_CHARS, SUITE_LOAD_FAILED, OUTPUT_LINES, MESSAGE_LINES, ANSI, JS_FILE, SECRET_PATTERNS, TEMP_CHECKOUT, MESSAGE_END, PYTEST_SUMMARY, SUMMARY, isSummary, PYTEST_SECTION, PYTEST_WHERE, cut, count;
86082
86143
  var init_replay_errors = __esm({
86083
86144
  "src/commands/replay-errors.ts"() {
86084
86145
  "use strict";
@@ -86104,7 +86165,11 @@ var init_replay_errors = __esm({
86104
86165
  ];
86105
86166
  TEMP_CHECKOUT = /(?:\/[^\s'"`/]+)*\/haansi-(?:replay|calibrate)-[A-Za-z0-9]{6}\/[^\s'"`/]+\//g;
86106
86167
  MESSAGE_END = /^\s*(?:⎯{3,}|❯\s|at\s|\d+\s*\|\s|>\s*\d+\s*\||Test Files\s|Tests:?\s+\d|Test Suites:|Duration\s|PASS\s|✓\s|=== RUN\s|ok\s|FAIL$)/;
86168
+ PYTEST_SUMMARY = /^(?:=+\s+)?(\d+\s+[a-z]+(?:,\s+\d+\s+[a-z]+)*)\s+in\s+[\d.]+s(?:\s+\([\d:]+\))?(?:\s+=+)?$/;
86107
86169
  SUMMARY = /^\s*(?:Test Files\s+\d|Tests:?\s+\d|Test Suites:\s+\d|=+\s.*\b(?:passed|failed|error)\b.*\sin\s[\d.]+s.*=+$|(?:FAIL|ok)\s+\S+\s+[\d.]+s$)/;
86170
+ isSummary = (line) => SUMMARY.test(line) || PYTEST_SUMMARY.test(line.trim()) && /\b(?:passed|failed|errors?)\b/.test(line);
86171
+ PYTEST_SECTION = /^_{3,}\s+(.+?)\s+_{3,}$/;
86172
+ PYTEST_WHERE = /^\S+\.py:\d+:\s+\S/;
86108
86173
  cut = (text, max2) => text.length > max2 ? `${text.slice(0, max2 - 2)} \u2026` : text;
86109
86174
  count = (text, word) => {
86110
86175
  const m = new RegExp(`(\\d+)\\s+${word}`).exec(text);
@@ -86420,14 +86485,14 @@ var init_replay_focus = __esm({
86420
86485
 
86421
86486
  // src/commands/replay-preflight.ts
86422
86487
  function refusalOf(status, body) {
86423
- let said = body.trim();
86488
+ let said2 = body.trim();
86424
86489
  try {
86425
86490
  const parsed = JSON.parse(body);
86426
86491
  const m = parsed.message ?? parsed.error;
86427
- if (typeof m === "string" && m.trim()) said = m.trim();
86492
+ if (typeof m === "string" && m.trim()) said2 = m.trim();
86428
86493
  } catch {
86429
86494
  }
86430
- const short = said.replace(/\s+/g, " ").slice(0, 120);
86495
+ const short = said2.replace(/\s+/g, " ").slice(0, 120);
86431
86496
  return short ? `${status}: ${short}` : String(status);
86432
86497
  }
86433
86498
  async function check2(fetchImpl, name, url2, init2) {
@@ -86648,6 +86713,18 @@ var init_replay_preflight = __esm({
86648
86713
  });
86649
86714
 
86650
86715
  // src/commands/replay-fallback.ts
86716
+ function solutionsSearchQuery(q, hints) {
86717
+ const params = new URLSearchParams();
86718
+ params.set("q", q);
86719
+ params.set("top_k", String(SOLUTIONS_PER_QUERY));
86720
+ for (const t of clipList2(hints?.failingTests))
86721
+ params.append("failing_tests", t);
86722
+ const error2 = hints?.error?.trim();
86723
+ if (error2) params.set("error", error2.slice(0, MAX_HINT_ERROR_CHARS2));
86724
+ for (const f of clipList2(hints?.files)) params.append("files", f);
86725
+ for (const n of clipList2(hints?.names)) params.append("names", n);
86726
+ return params.toString();
86727
+ }
86651
86728
  async function searchHaansi(session, ask, fetchImpl = fetch) {
86652
86729
  const base = session.apiUrl.replace(/\/+$/, "");
86653
86730
  const headers = {
@@ -86656,7 +86733,7 @@ async function searchHaansi(session, ask, fetchImpl = fetch) {
86656
86733
  };
86657
86734
  const solutions = ask.queries.map(
86658
86735
  (q) => fetchImpl(
86659
- `${base}/api/v1/memory/solutions/search?q=${encodeURIComponent(q)}&top_k=${SOLUTIONS_PER_QUERY}`,
86736
+ `${base}/api/v1/memory/solutions/search?${solutionsSearchQuery(q, ask.hints)}`,
86660
86737
  { method: "GET", headers }
86661
86738
  )
86662
86739
  );
@@ -86726,13 +86803,17 @@ async function searchHaansi(session, ask, fetchImpl = fetch) {
86726
86803
  })() : Promise.resolve();
86727
86804
  await Promise.allSettled([...solutions, skills2]);
86728
86805
  }
86729
- var SOLUTIONS_PER_QUERY, PRIOR_ATTEMPTS_LIMIT;
86806
+ var SOLUTIONS_PER_QUERY, MAX_HINT_ITEMS2, MAX_HINT_ITEM_CHARS2, MAX_HINT_ERROR_CHARS2, clipList2, PRIOR_ATTEMPTS_LIMIT;
86730
86807
  var init_replay_fallback = __esm({
86731
86808
  "src/commands/replay-fallback.ts"() {
86732
86809
  "use strict";
86733
86810
  init_setup_mcp();
86734
86811
  init_replay_preflight();
86735
86812
  SOLUTIONS_PER_QUERY = 5;
86813
+ MAX_HINT_ITEMS2 = 10;
86814
+ MAX_HINT_ITEM_CHARS2 = 300;
86815
+ MAX_HINT_ERROR_CHARS2 = 1e3;
86816
+ clipList2 = (items) => (items ?? []).map((v) => v.trim().slice(0, MAX_HINT_ITEM_CHARS2)).filter(Boolean).slice(0, MAX_HINT_ITEMS2);
86736
86817
  PRIOR_ATTEMPTS_LIMIT = 3;
86737
86818
  }
86738
86819
  });
@@ -86793,9 +86874,9 @@ function modelUnreachableOf(output, exitCode) {
86793
86874
  const objects = jsonLines(output);
86794
86875
  const result = [...objects].reverse().find((o) => o.type === "result");
86795
86876
  if (result && result.is_error === true) {
86796
- const said = typeof result.result === "string" ? result.result : "";
86797
- if (result.terminal_reason === "api_error" || MODEL_REFUSAL.test(said))
86798
- return clipReason(said || "the model's API returned an error");
86877
+ const said2 = typeof result.result === "string" ? result.result : "";
86878
+ if (result.terminal_reason === "api_error" || MODEL_REFUSAL.test(said2))
86879
+ return clipReason(said2 || "the model's API returned an error");
86799
86880
  }
86800
86881
  const used = usageOf(output);
86801
86882
  if ((used.outputTokens ?? 0) > 0) return null;
@@ -86842,12 +86923,12 @@ function agentFailureLines(output, max2, scrub) {
86842
86923
  }
86843
86924
  if (event && typeof event === "object") {
86844
86925
  if (event.type !== "result") continue;
86845
- const said = [
86926
+ const said2 = [
86846
86927
  typeof event.terminal_reason === "string" ? `terminal_reason=${event.terminal_reason}` : "",
86847
86928
  event.is_error === true ? "is_error" : "",
86848
86929
  typeof event.result === "string" ? event.result : ""
86849
86930
  ].filter(Boolean).join(" ");
86850
- if (said) out.push(said);
86931
+ if (said2) out.push(said2);
86851
86932
  continue;
86852
86933
  }
86853
86934
  }
@@ -87889,13 +87970,20 @@ function parseRelevance(text, shown) {
87889
87970
  return null;
87890
87971
  }
87891
87972
  if (!Array.isArray(v.items)) return null;
87892
- const relevant = /* @__PURE__ */ new Set();
87973
+ const onPoint = /* @__PURE__ */ new Set();
87974
+ const nearby = /* @__PURE__ */ new Set();
87893
87975
  for (const item of v.items) {
87894
87976
  const it = item ?? {};
87895
87977
  if (typeof it.id !== "string" || !shown.has(it.id)) continue;
87896
- if (it.relevant === true) relevant.add(it.id);
87978
+ if (it.grade === "on_point") {
87979
+ const e = it.evidence ?? {};
87980
+ if (said(e.quote) && said(e.change)) onPoint.add(it.id);
87981
+ else nearby.add(it.id);
87982
+ } else if (it.grade === "nearby") nearby.add(it.id);
87983
+ else if (it.grade === void 0 && it.relevant === true) onPoint.add(it.id);
87897
87984
  }
87898
- return [...relevant].sort();
87985
+ for (const id of onPoint) nearby.delete(id);
87986
+ return { onPoint: [...onPoint].sort(), nearby: [...nearby].sort() };
87899
87987
  }
87900
87988
  function knowledgeOf(relevantIds, reachedAgent) {
87901
87989
  if (relevantIds.some((id) => reachedAgent.has(id))) return "returned";
@@ -87921,6 +88009,7 @@ async function judgeRelevance(deps, input) {
87921
88009
  return {
87922
88010
  relevantIds: [],
87923
88011
  recallIds: [],
88012
+ nearbyIds: [],
87924
88013
  knowledge: "none",
87925
88014
  judgeTag: null
87926
88015
  };
@@ -87928,6 +88017,7 @@ async function judgeRelevance(deps, input) {
87928
88017
  return {
87929
88018
  relevantIds: null,
87930
88019
  recallIds: null,
88020
+ nearbyIds: null,
87931
88021
  knowledge: null,
87932
88022
  judgeTag: null
87933
88023
  };
@@ -87963,21 +88053,24 @@ async function judgeRelevance(deps, input) {
87963
88053
  },
87964
88054
  input.timeoutMs
87965
88055
  );
87966
- const relevant = parseRelevance(deps.readFile(verdictFile) ?? "", shown) ?? parseRelevance(ran.output, shown);
87967
- if (!relevant) {
88056
+ const grades = parseRelevance(deps.readFile(verdictFile) ?? "", shown) ?? parseRelevance(ran.output, shown);
88057
+ if (!grades) {
87968
88058
  deps.log(
87969
88059
  `\u2026 ${input.label} [haansi]: the relevance judge gave no verdict`
87970
88060
  );
87971
88061
  return {
87972
88062
  relevantIds: null,
87973
88063
  recallIds: null,
88064
+ nearbyIds: null,
87974
88065
  knowledge: null,
87975
88066
  judgeTag: tag
87976
88067
  };
87977
88068
  }
88069
+ const relevant = grades.onPoint;
87978
88070
  return {
87979
88071
  relevantIds: relevant,
87980
88072
  recallIds: relevant.filter((id) => !reachedIds.has(id)),
88073
+ nearbyIds: grades.nearby,
87981
88074
  knowledge: knowledgeOf(relevant, reachedIds),
87982
88075
  judgeTag: tag
87983
88076
  };
@@ -87985,7 +88078,7 @@ async function judgeRelevance(deps, input) {
87985
88078
  deps.removeDir(dir);
87986
88079
  }
87987
88080
  }
87988
- var import_node_path14, MAX_CHANGE_CHARS2, MAX_ITEMS_CHARS, QUERY_CHARS, TERMS, clip2, COMMON;
88081
+ var import_node_path14, MAX_CHANGE_CHARS2, MAX_ITEMS_CHARS, QUERY_CHARS, TERMS, clip2, COMMON, said;
87989
88082
  var init_replay_relevance = __esm({
87990
88083
  "src/commands/replay-relevance.ts"() {
87991
88084
  "use strict";
@@ -88000,6 +88093,7 @@ var init_replay_relevance = __esm({
88000
88093
  COMMON = new Set(
88001
88094
  "this that with from have will when then than they them their there what which while where return const function export import class true false null undefined async await string number value values type types test tests expect should data item items list name names error errors".split(" ")
88002
88095
  );
88096
+ said = (v) => typeof v === "string" && v.trim() !== "";
88003
88097
  }
88004
88098
  });
88005
88099
 
@@ -88043,7 +88137,7 @@ var init_replay_codex = __esm({
88043
88137
  }
88044
88138
  });
88045
88139
 
88046
- // src/commands/replay-interface.ts
88140
+ // src/commands/replay-lang-js.ts
88047
88141
  function importsOf(source) {
88048
88142
  const text = stripComments(source);
88049
88143
  const out = /* @__PURE__ */ new Map();
@@ -88098,6 +88192,718 @@ function candidatesFor(fromFile, spec2) {
88098
88192
  ...EXTENSIONS.map((e) => `${stem2}/index${e}`)
88099
88193
  ].filter((p, i, all) => all.indexOf(p) === i);
88100
88194
  }
88195
+ function stringAt(text, i) {
88196
+ const quote = text[i];
88197
+ if (quote !== "'" && quote !== '"' && quote !== "`") return null;
88198
+ let value = "";
88199
+ for (let j = i + 1; j < text.length; j++) {
88200
+ const c = text[j];
88201
+ if (c === "\\" && j + 1 < text.length) {
88202
+ value += text[j + 1];
88203
+ j += 1;
88204
+ } else if (c === quote) return { value, end: j + 1 };
88205
+ else if (quote !== "`" && c === "\n") return null;
88206
+ else value += c;
88207
+ }
88208
+ return null;
88209
+ }
88210
+ function skipGroup(text, i) {
88211
+ const open = text[i];
88212
+ const close = open === "(" ? ")" : open === "[" ? "]" : null;
88213
+ if (!close) return -1;
88214
+ let depth = 0;
88215
+ for (let j = i; j < text.length; j++) {
88216
+ const c = text[j];
88217
+ if (c === "'" || c === '"' || c === "`") {
88218
+ const s = stringAt(text, j);
88219
+ if (!s) return -1;
88220
+ j = s.end - 1;
88221
+ } else if (c === "(" || c === "[" || c === "{") depth += 1;
88222
+ else if (c === ")" || c === "]" || c === "}") {
88223
+ depth -= 1;
88224
+ if (depth === 0) return c === close ? j + 1 : -1;
88225
+ }
88226
+ }
88227
+ return -1;
88228
+ }
88229
+ function testCallAt(text, i) {
88230
+ CALL.lastIndex = i;
88231
+ const m = CALL.exec(text);
88232
+ if (!m) return null;
88233
+ let j = CALL.lastIndex;
88234
+ if (/[\w$]/.test(text[j] ?? "")) return null;
88235
+ const mods = m[2];
88236
+ if (/\.(?:each|skipIf|runIf|for)\b/.test(mods)) {
88237
+ while (/\s/.test(text[j] ?? "")) j++;
88238
+ if (text[j] === "`") {
88239
+ const s2 = stringAt(text, j);
88240
+ if (!s2) return null;
88241
+ j = s2.end;
88242
+ } else {
88243
+ j = skipGroup(text, j);
88244
+ if (j < 0) return null;
88245
+ }
88246
+ }
88247
+ while (/\s/.test(text[j] ?? "")) j++;
88248
+ if (text[j] !== "(") return null;
88249
+ j++;
88250
+ while (/\s/.test(text[j] ?? "")) j++;
88251
+ const s = stringAt(text, j);
88252
+ if (!s) return null;
88253
+ const suite = m[1] === "describe" || m[1] === "suite" || m[1] === "context";
88254
+ return { suite, title: s.value.replace(/\s+/g, " ").trim(), end: s.end };
88255
+ }
88256
+ function testTitlesOf(source) {
88257
+ const out = [];
88258
+ const stack = [];
88259
+ let depth = 0;
88260
+ const text = source;
88261
+ for (let i = 0; i < text.length; i++) {
88262
+ const c = text[i];
88263
+ const next = text[i + 1];
88264
+ if (c === "/" && next === "/") {
88265
+ const nl = text.indexOf("\n", i);
88266
+ i = nl < 0 ? text.length : nl;
88267
+ } else if (c === "/" && next === "*") {
88268
+ const close = text.indexOf("*/", i + 2);
88269
+ i = close < 0 ? text.length : close + 1;
88270
+ } else if (c === "'" || c === '"' || c === "`") {
88271
+ const s = stringAt(text, i);
88272
+ if (s) i = s.end - 1;
88273
+ } else if (c === "{") depth += 1;
88274
+ else if (c === "}") {
88275
+ depth -= 1;
88276
+ while (stack.length && depth <= stack[stack.length - 1].depth)
88277
+ stack.pop();
88278
+ } else if (/[a-z]/.test(c) && !/[\w$.]/.test(text[i - 1] ?? "")) {
88279
+ const call = testCallAt(text, i);
88280
+ if (!call) continue;
88281
+ if (call.suite) stack.push({ title: call.title, depth });
88282
+ else if (call.title)
88283
+ out.push([...stack.map((s) => s.title), call.title].join(" \u203A "));
88284
+ i = call.end - 1;
88285
+ }
88286
+ }
88287
+ return out;
88288
+ }
88289
+ function typeEnd(text, i, stops, bodyBrace) {
88290
+ let depth = 0;
88291
+ let expectType = true;
88292
+ for (let j = i; j < text.length; j++) {
88293
+ const c = text[j];
88294
+ if (c === "'" || c === '"' || c === "`") {
88295
+ const s = stringAt(text, j);
88296
+ if (s) j = s.end - 1;
88297
+ expectType = false;
88298
+ continue;
88299
+ }
88300
+ if (c === "=" && text[j + 1] === ">") {
88301
+ j += 1;
88302
+ expectType = true;
88303
+ continue;
88304
+ }
88305
+ if (depth === 0 && stops.includes(c)) return j;
88306
+ if (c === "{" && depth === 0 && bodyBrace && !expectType) return j;
88307
+ if ("([<{".includes(c)) {
88308
+ depth += 1;
88309
+ expectType = true;
88310
+ } else if (")]>}".includes(c)) {
88311
+ depth -= 1;
88312
+ expectType = false;
88313
+ if (depth < 0) return j;
88314
+ } else if (/[:|&,?]/.test(c)) expectType = true;
88315
+ else if (!/\s/.test(c)) expectType = false;
88316
+ }
88317
+ return text.length;
88318
+ }
88319
+ function capSignature(text) {
88320
+ const lines = text.trim().split("\n").map((l) => l.replace(/\s+$/, ""));
88321
+ let out = lines.slice(0, MAX_SIGNATURE_LINES).join("\n");
88322
+ let cut2 = lines.length > MAX_SIGNATURE_LINES;
88323
+ if (out.length > MAX_SIGNATURE_CHARS) {
88324
+ out = out.slice(0, MAX_SIGNATURE_CHARS);
88325
+ cut2 = true;
88326
+ }
88327
+ return cut2 ? `${out.trimEnd()}
88328
+ \u2026` : out;
88329
+ }
88330
+ function signatureOf(source, name) {
88331
+ const text = stripComments(source);
88332
+ const n = name.replace(/\$/g, "\\$");
88333
+ const lead = String.raw`(?:^|\n)[ \t]*((?:export\s+)?(?:declare\s+)?(?:default\s+)?(?:abstract\s+)?(?:async\s+)?)`;
88334
+ const fn = new RegExp(`${lead}(function\\*?\\s+${n})\\b`).exec(text);
88335
+ if (fn) {
88336
+ const start = fn.index + fn[0].length - fn[2].length - fn[1].length;
88337
+ const end = typeEnd(text, fn.index + fn[0].length, ";", true);
88338
+ return capSignature(text.slice(start, end));
88339
+ }
88340
+ const cls = new RegExp(`${lead}(class\\s+${n})\\b`).exec(text);
88341
+ if (cls) {
88342
+ const start = cls.index + cls[0].length - cls[2].length - cls[1].length;
88343
+ const brace = text.indexOf("{", cls.index + cls[0].length);
88344
+ return capSignature(text.slice(start, brace < 0 ? text.length : brace));
88345
+ }
88346
+ const decl = new RegExp(`${lead}((?:interface|enum)\\s+${n})\\b`).exec(text);
88347
+ if (decl) {
88348
+ const start = decl.index + decl[0].length - decl[2].length - decl[1].length;
88349
+ const brace = text.indexOf("{", decl.index + decl[0].length);
88350
+ if (brace < 0 || /;|\n\s*(?:export|interface|type|const|function|class|enum)\b/.test(
88351
+ text.slice(decl.index + decl[0].length, brace)
88352
+ ))
88353
+ return null;
88354
+ let depth = 0;
88355
+ let end = text.length;
88356
+ for (let j = brace; j < text.length; j++) {
88357
+ if (text[j] === "{") depth += 1;
88358
+ else if (text[j] === "}" && --depth === 0) {
88359
+ end = j + 1;
88360
+ break;
88361
+ }
88362
+ }
88363
+ return capSignature(text.slice(start, end));
88364
+ }
88365
+ const type = new RegExp(`${lead}(type\\s+${n})\\b`).exec(text);
88366
+ if (type) {
88367
+ const start = type.index + type[0].length - type[2].length - type[1].length;
88368
+ const end = typeEnd(text, type.index + type[0].length, ";", false);
88369
+ return capSignature(text.slice(start, end));
88370
+ }
88371
+ const v = new RegExp(`${lead}((?:const|let|var)\\s+${n})\\b`).exec(text);
88372
+ if (v) {
88373
+ const start = v.index + v[0].length - v[2].length - v[1].length;
88374
+ const after = v.index + v[0].length;
88375
+ const rest = text.slice(after);
88376
+ if (/^\s*:/.test(rest)) {
88377
+ const end = typeEnd(text, after, "=;", false);
88378
+ return capSignature(text.slice(start, end));
88379
+ }
88380
+ const arrow = /^\s*=\s*(?:async\s+)?(?:<[^>]*>\s*)?(?=\()/.exec(rest);
88381
+ if (!arrow) return null;
88382
+ const close = skipGroup(text, after + arrow[0].length);
88383
+ if (close < 0) return null;
88384
+ const ret = /^\s*(?::[^=;{]*?)?\s*=>/.exec(text.slice(close));
88385
+ return ret ? capSignature(text.slice(start, close + ret[0].length)) : null;
88386
+ }
88387
+ return null;
88388
+ }
88389
+ function mockedSpecsOf(source) {
88390
+ const out = [];
88391
+ for (const m of stripComments(source).matchAll(
88392
+ /\b(?:vi|jest)\.(?:mock|doMock)\(\s*["'](\.[^"']*)["']/g
88393
+ ))
88394
+ if (!out.includes(m[1])) out.push(m[1]);
88395
+ return out;
88396
+ }
88397
+ function reexportSpecsOf(source) {
88398
+ return [
88399
+ ...stripComments(source).matchAll(
88400
+ /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*["'](\.[^"']+)["']/g
88401
+ )
88402
+ ].map((m) => m[1]);
88403
+ }
88404
+ function packageCandidates(spec2) {
88405
+ const m = /^(@[\w.-]+\/[\w.-]+)(?:\/(.+))?$/.exec(spec2);
88406
+ if (!m) return [];
88407
+ const [, pkg, sub] = m;
88408
+ const stems = sub ? [`packages/${pkg}/src/${sub}`, `packages/${pkg}/${sub}`] : [`packages/${pkg}/src/index`, `packages/${pkg}/index`];
88409
+ return stems.flatMap((s) => [
88410
+ `${s}.ts`,
88411
+ `${s}.tsx`,
88412
+ `${s}.js`,
88413
+ `${s}/index.ts`
88414
+ ]);
88415
+ }
88416
+ function packageSpecsOf(source) {
88417
+ const text = stripComments(source);
88418
+ const out = [];
88419
+ for (const m of text.matchAll(
88420
+ /(?:\bfrom\s*|\b(?:vi|jest)\.(?:mock|doMock)\(\s*|\bimport\(\s*)["'](@[^"'\s]+)["']/g
88421
+ ))
88422
+ if (!out.includes(m[1])) out.push(m[1]);
88423
+ return out;
88424
+ }
88425
+ var import_node_path15, MAX_SIGNATURE_LINES, MAX_SIGNATURE_CHARS, JS_SOURCE, JS_TEST_FILE, EXTENSIONS, IDENT, stripComments, CALL, jsAdapter;
88426
+ var init_replay_lang_js = __esm({
88427
+ "src/commands/replay-lang-js.ts"() {
88428
+ "use strict";
88429
+ import_node_path15 = require("node:path");
88430
+ MAX_SIGNATURE_LINES = 15;
88431
+ MAX_SIGNATURE_CHARS = 600;
88432
+ JS_SOURCE = /\.[cm]?[jt]sx?$/;
88433
+ JS_TEST_FILE = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
88434
+ EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs"];
88435
+ IDENT = /^[A-Za-z_$][\w$]*$/;
88436
+ stripComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/.*$/gm, "$1");
88437
+ CALL = /(describe|suite|context|it|test)((?:\.[A-Za-z]+)*)/y;
88438
+ jsAdapter = {
88439
+ id: "js",
88440
+ fence: "ts",
88441
+ handles: (path2) => JS_SOURCE.test(path2),
88442
+ isTestFile: (path2) => JS_TEST_FILE.test(path2),
88443
+ testTitles: (source) => testTitlesOf(source),
88444
+ imports: (source, fromPath) => importsOf(source).map((i) => ({
88445
+ ...i,
88446
+ candidates: candidatesFor(fromPath, i.spec)
88447
+ })),
88448
+ mocks: (source, fromPath) => mockedSpecsOf(source).map((spec2) => candidatesFor(fromPath, spec2)),
88449
+ // What it imports, then what it mocks: a mock missing an export the real
88450
+ // module gained hangs or fails the suite as surely as a bug. A barrel's
88451
+ // re-exports are what importing it loads. Then the workspace packages.
88452
+ dependencies: (source, fromPath) => [
88453
+ ...[
88454
+ .../* @__PURE__ */ new Set([
88455
+ ...importsOf(source).map((i) => i.spec),
88456
+ ...mockedSpecsOf(source),
88457
+ ...reexportSpecsOf(source)
88458
+ ])
88459
+ ].map((spec2) => candidatesFor(fromPath, spec2)),
88460
+ ...packageSpecsOf(source).map(packageCandidates)
88461
+ ].filter((c) => c.length > 0),
88462
+ exportsName,
88463
+ hasDefault: hasDefaultExport,
88464
+ signatureOf
88465
+ };
88466
+ }
88467
+ });
88468
+
88469
+ // src/commands/replay-lang-python.ts
88470
+ function maskPython(source, strings) {
88471
+ let out = "";
88472
+ let i = 0;
88473
+ while (i < source.length) {
88474
+ const c = source[i];
88475
+ if (c === "#") {
88476
+ const nl = source.indexOf("\n", i);
88477
+ const end = nl < 0 ? source.length : nl;
88478
+ out += " ".repeat(end - i);
88479
+ i = end;
88480
+ } else if (c === "\\" && source[i + 1] === "\n") {
88481
+ out += " ";
88482
+ i += 2;
88483
+ } else if (c === "'" || c === '"') {
88484
+ const quote = source.startsWith(c.repeat(3), i) ? c.repeat(3) : c;
88485
+ let j = i + quote.length;
88486
+ while (j < source.length && !source.startsWith(quote, j)) {
88487
+ if (quote.length === 1 && source[j] === "\n") break;
88488
+ j += source[j] === "\\" ? 2 : 1;
88489
+ }
88490
+ j = Math.min(j, source.length);
88491
+ const closed = source.startsWith(quote, j);
88492
+ const inner = source.slice(i + quote.length, j);
88493
+ out += quote + (strings ? inner.replace(/[^\n]/g, " ") : inner) + (closed ? quote : "");
88494
+ i = closed ? j + quote.length : j;
88495
+ } else {
88496
+ out += c;
88497
+ i += 1;
88498
+ }
88499
+ }
88500
+ return out;
88501
+ }
88502
+ function logicalLines(masked) {
88503
+ const out = [];
88504
+ let depth = 0;
88505
+ let start = 0;
88506
+ for (const text of masked.split("\n")) {
88507
+ out.push({ text, start, top: depth === 0 });
88508
+ for (const c of text)
88509
+ if ("([{".includes(c)) depth += 1;
88510
+ else if (")]}".includes(c)) depth = Math.max(0, depth - 1);
88511
+ start += text.length + 1;
88512
+ }
88513
+ return out;
88514
+ }
88515
+ function isPythonTestFile(path2) {
88516
+ const base = path2.split("/").pop() ?? "";
88517
+ if (!PY.test(base) || base === "conftest.py" || base === "__init__.py")
88518
+ return false;
88519
+ return /^test_.*\.py$/.test(base) || /_test\.py$/.test(base) || /(^|\/)tests?\//.test(path2);
88520
+ }
88521
+ function pythonTestTitles(source) {
88522
+ const out = [];
88523
+ const stack = [];
88524
+ for (const line of logicalLines(maskPython(source, true))) {
88525
+ if (!line.top || !line.text.trim()) continue;
88526
+ const indent = indentOf(line.text);
88527
+ while (stack.length && indent <= stack[stack.length - 1].indent)
88528
+ stack.pop();
88529
+ const body = line.text.trim();
88530
+ const cls = /^class\s+(\w+)/.exec(body);
88531
+ const fn = /^(?:async\s+)?def\s+(\w+)/.exec(body);
88532
+ const collected = stack.every((s) => s.test);
88533
+ if (cls)
88534
+ stack.push({
88535
+ indent,
88536
+ name: cls[1],
88537
+ test: collected && /^Test/.test(cls[1])
88538
+ });
88539
+ else if (fn) {
88540
+ if (collected && /^test/.test(fn[1]))
88541
+ out.push([...stack.map((s) => s.name), fn[1]].join(" \u203A "));
88542
+ stack.push({ indent, name: fn[1], test: false });
88543
+ }
88544
+ }
88545
+ return out;
88546
+ }
88547
+ function pythonModuleCandidates(fromPath, spec2) {
88548
+ const level = /^\.*/.exec(spec2)[0].length;
88549
+ const rest = spec2.slice(level);
88550
+ const parts = rest ? rest.split(".") : [];
88551
+ if (!parts.every((p) => IDENT2.test(p))) return [];
88552
+ const at = (dir2) => {
88553
+ const base = import_node_path16.posix.join(dir2, ...parts);
88554
+ return parts.length ? [`${base}.py`, import_node_path16.posix.join(base, "__init__.py")] : [import_node_path16.posix.join(base, "__init__.py")];
88555
+ };
88556
+ let dir = import_node_path16.posix.dirname(fromPath);
88557
+ if (level) {
88558
+ for (let k = 1; k < level; k++) {
88559
+ if (dir === "." || dir === "/") return [];
88560
+ dir = import_node_path16.posix.dirname(dir);
88561
+ }
88562
+ return at(dir);
88563
+ }
88564
+ if (!parts.length || EXTERNAL.has(parts[0])) return [];
88565
+ const out = [];
88566
+ for (; ; ) {
88567
+ out.push(...at(dir));
88568
+ if (dir === "." || dir === "/" || dir === "") break;
88569
+ dir = import_node_path16.posix.dirname(dir);
88570
+ }
88571
+ return out;
88572
+ }
88573
+ function attributesOf(masked, alias) {
88574
+ const out = [];
88575
+ for (const m of masked.matchAll(
88576
+ new RegExp(`(?<![\\w.])${alias}\\.([A-Za-z_]\\w*)`, "g")
88577
+ ))
88578
+ if (!m[1].startsWith("__") && !out.includes(m[1])) out.push(m[1]);
88579
+ return out;
88580
+ }
88581
+ function patchedAttributes(text) {
88582
+ return [
88583
+ ...text.matchAll(
88584
+ /\b(?:patch\.object|setattr)\(\s*([A-Za-z_]\w*)\s*,\s*["']([A-Za-z_]\w*)["']/g
88585
+ )
88586
+ ].map((m) => ({ alias: m[1], attr: m[2] }));
88587
+ }
88588
+ function readImports(source, fromPath) {
88589
+ const masked = maskPython(source, true);
88590
+ const kept = maskPython(source, false);
88591
+ const refs = /* @__PURE__ */ new Map();
88592
+ const aliases = /* @__PURE__ */ new Map();
88593
+ const refOf = (spec2) => {
88594
+ const known = refs.get(spec2);
88595
+ if (known) return known;
88596
+ const relative4 = spec2.startsWith(".");
88597
+ const top = spec2.split(".")[0];
88598
+ if (!relative4 && EXTERNAL.has(top)) return null;
88599
+ const candidates = pythonModuleCandidates(fromPath, spec2);
88600
+ if (!candidates.length) return null;
88601
+ const ref = {
88602
+ spec: spec2,
88603
+ names: [],
88604
+ defaultImport: false,
88605
+ candidates
88606
+ };
88607
+ refs.set(spec2, ref);
88608
+ return ref;
88609
+ };
88610
+ const text = masked;
88611
+ for (const m of text.matchAll(
88612
+ /^[ \t]*from[ \t]+(\.+[\w.]*|[A-Za-z_][\w.]*)[ \t]+import[ \t]+(\([^)]*\)|[^\n;]*)/gm
88613
+ )) {
88614
+ const ref = refOf(m[1]);
88615
+ if (!ref) continue;
88616
+ for (const part of m[2].replace(/[()]/g, " ").split(",")) {
88617
+ const [name, alias] = part.trim().split(/\s+as\s+/);
88618
+ if (!name || !IDENT2.test(name)) continue;
88619
+ if (!ref.names.includes(name)) ref.names.push(name);
88620
+ const sub = m[1].endsWith(".") ? `${m[1]}${name}` : `${m[1]}.${name}`;
88621
+ const candidates = pythonModuleCandidates(fromPath, sub);
88622
+ if (!candidates.length) continue;
88623
+ ref.submodules ??= {};
88624
+ ref.submodules[name] ??= { candidates, names: [] };
88625
+ aliases.set((alias ?? name).trim(), { ref, sub: name });
88626
+ }
88627
+ }
88628
+ for (const m of text.matchAll(/^[ \t]*import[ \t]+([^\n;]+)/gm))
88629
+ for (const part of m[1].split(",")) {
88630
+ const [spec2, alias] = part.trim().split(/\s+as\s+/);
88631
+ if (!spec2 || !/^[A-Za-z_][\w.]*$/.test(spec2)) continue;
88632
+ const ref = refOf(spec2);
88633
+ if (!ref) continue;
88634
+ if (alias) aliases.set(alias.trim(), { ref });
88635
+ else if (!spec2.includes(".")) aliases.set(spec2, { ref });
88636
+ }
88637
+ const patched = patchedAttributes(kept);
88638
+ for (const [alias, { ref, sub }] of aliases) {
88639
+ const names = [
88640
+ ...attributesOf(masked, alias),
88641
+ ...patched.filter((p) => p.alias === alias).map((p) => p.attr)
88642
+ ];
88643
+ const into = sub ? ref.submodules[sub].names : ref.names;
88644
+ for (const n of names) if (!into.includes(n)) into.push(n);
88645
+ }
88646
+ return { refs: [...refs.values()], aliases };
88647
+ }
88648
+ function pythonImports(source, fromPath) {
88649
+ return readImports(source, fromPath).refs;
88650
+ }
88651
+ function pythonMocks(source, fromPath) {
88652
+ const kept = maskPython(source, false);
88653
+ const out = [];
88654
+ const add = (c) => {
88655
+ const key = c.join("\0");
88656
+ if (c.length && !out.some((o) => o.join("\0") === key)) out.push(c);
88657
+ };
88658
+ for (const m of kept.matchAll(
88659
+ /\b(?:patch|setattr)\(\s*(?:target\s*=\s*)?["']([A-Za-z_][\w.]*)["']/g
88660
+ )) {
88661
+ const parts = m[1].split(".");
88662
+ const candidates = [];
88663
+ for (let k = parts.length - 1; k >= 1; k--)
88664
+ for (const c of pythonModuleCandidates(
88665
+ fromPath,
88666
+ parts.slice(0, k).join(".")
88667
+ ))
88668
+ if (!candidates.includes(c)) candidates.push(c);
88669
+ add(candidates);
88670
+ }
88671
+ const { aliases } = readImports(source, fromPath);
88672
+ for (const { alias } of patchedAttributes(kept)) {
88673
+ const to = aliases.get(alias);
88674
+ if (to)
88675
+ add(to.sub ? to.ref.submodules[to.sub].candidates : to.ref.candidates);
88676
+ }
88677
+ return out;
88678
+ }
88679
+ function pythonExportsName(source, name) {
88680
+ if (!IDENT2.test(name)) return false;
88681
+ const masked = maskPython(source, true);
88682
+ if (/^[ \t]*from[ \t]+\S+[ \t]+import[ \t]+\*/m.test(masked)) return true;
88683
+ const n = name;
88684
+ if (new RegExp(`^(?:async[ \\t]+)?(?:def|class)[ \\t]+${n}\\b`, "m").test(
88685
+ masked
88686
+ ) || new RegExp(`^${n}[ \\t]*(?::|=(?!=))`, "m").test(masked))
88687
+ return true;
88688
+ for (const m of masked.matchAll(/^\(?([A-Za-z_][\w \t,]*)\)?[ \t]*=(?!=)/gm))
88689
+ if (m[1].split(",").length > 1 && m[1].split(",").some((p) => p.trim() === n))
88690
+ return true;
88691
+ for (const m of masked.matchAll(
88692
+ /^[ \t]*from[ \t]+\S+[ \t]+import[ \t]+(\([^)]*\)|[^\n;]*)/gm
88693
+ ))
88694
+ for (const part of m[1].replace(/[()]/g, " ").split(",")) {
88695
+ const [imported, alias] = part.trim().split(/\s+as\s+/);
88696
+ if ((alias ?? imported)?.trim() === n) return true;
88697
+ }
88698
+ for (const m of masked.matchAll(/^[ \t]*import[ \t]+([^\n;]+)/gm))
88699
+ for (const part of m[1].split(",")) {
88700
+ const [spec2, alias] = part.trim().split(/\s+as\s+/);
88701
+ if ((alias ?? spec2.split(".")[0])?.trim() === n) return true;
88702
+ }
88703
+ const kept = maskPython(source, false);
88704
+ for (const m of kept.matchAll(/^__all__\s*\+?=\s*[[(]([^\])]*)/gm))
88705
+ if (new RegExp(`["']${n}["']`).test(m[1])) return true;
88706
+ return false;
88707
+ }
88708
+ function headerEnd(masked, i) {
88709
+ let depth = 0;
88710
+ for (let j = i; j < masked.length; j++) {
88711
+ const c = masked[j];
88712
+ if ("([{".includes(c)) depth += 1;
88713
+ else if (")]}".includes(c)) depth -= 1;
88714
+ else if (c === ":" && depth === 0) return j + 1;
88715
+ else if (c === "\n" && depth === 0) return -1;
88716
+ }
88717
+ return -1;
88718
+ }
88719
+ function decoratorsStart(masked, start, indent) {
88720
+ let at = start;
88721
+ while (at > 0) {
88722
+ const prevStart = masked.lastIndexOf("\n", at - 2) + 1;
88723
+ const prev = masked.slice(prevStart, at - 1);
88724
+ if (!prev.startsWith(`${indent}@`)) break;
88725
+ at = prevStart;
88726
+ }
88727
+ return at;
88728
+ }
88729
+ function pythonSignatureOf(source, name) {
88730
+ if (!IDENT2.test(name)) return null;
88731
+ const masked = maskPython(source, true);
88732
+ const kept = maskPython(source, false);
88733
+ const def = new RegExp(`^(?:async[ \\t]+)?def[ \\t]+${name}\\b`, "m").exec(
88734
+ masked
88735
+ );
88736
+ if (def) {
88737
+ const end = headerEnd(masked, def.index + def[0].length);
88738
+ if (end < 0) return null;
88739
+ return capSignature(
88740
+ kept.slice(decoratorsStart(masked, def.index, ""), end)
88741
+ );
88742
+ }
88743
+ const cls = new RegExp(`^class[ \\t]+${name}\\b`, "m").exec(masked);
88744
+ if (cls) {
88745
+ const end = headerEnd(masked, cls.index + cls[0].length);
88746
+ if (end < 0) return null;
88747
+ const parts = [kept.slice(decoratorsStart(masked, cls.index, ""), end)];
88748
+ const lines = logicalLines(masked).filter((l) => l.start >= end);
88749
+ let bodyIndent = null;
88750
+ for (const line of lines) {
88751
+ if (!line.text.trim()) continue;
88752
+ const indent = indentOf(line.text);
88753
+ if (line.top && indent === 0) break;
88754
+ if (!line.top) continue;
88755
+ bodyIndent ??= indent;
88756
+ if (indent !== bodyIndent) continue;
88757
+ const body = line.text.trim();
88758
+ if (/^[A-Za-z_]\w*\s*:(?!=)\s*\S/.test(body))
88759
+ parts.push(kept.slice(line.start, line.start + line.text.length));
88760
+ else if (/^(?:async\s+)?def\s+__init__\b/.test(body)) {
88761
+ const initEnd = headerEnd(
88762
+ masked,
88763
+ line.start + line.text.indexOf("def")
88764
+ );
88765
+ if (initEnd > 0) parts.push(kept.slice(line.start, initEnd));
88766
+ }
88767
+ }
88768
+ return capSignature(parts.join("\n"));
88769
+ }
88770
+ const annotated = new RegExp(`^${name}[ \\t]*:(?!=)`, "m").exec(masked);
88771
+ if (annotated) {
88772
+ let depth = 0;
88773
+ let j = annotated.index + annotated[0].length;
88774
+ for (; j < masked.length; j++) {
88775
+ const c = masked[j];
88776
+ if ("([{".includes(c)) depth += 1;
88777
+ else if (")]}".includes(c)) depth -= 1;
88778
+ else if (depth === 0 && (c === "=" || c === "\n")) break;
88779
+ }
88780
+ return capSignature(kept.slice(annotated.index, j));
88781
+ }
88782
+ return null;
88783
+ }
88784
+ function pythonDependencies(source, fromPath) {
88785
+ const out = [];
88786
+ for (const ref of pythonImports(source, fromPath)) {
88787
+ out.push(ref.candidates);
88788
+ for (const sub of Object.values(ref.submodules ?? {}))
88789
+ out.push(sub.candidates);
88790
+ }
88791
+ out.push(...pythonMocks(source, fromPath));
88792
+ return out.filter((c) => c.length > 0);
88793
+ }
88794
+ var import_node_path16, PY, IDENT2, EXTERNAL, indentOf, pythonAdapter;
88795
+ var init_replay_lang_python = __esm({
88796
+ "src/commands/replay-lang-python.ts"() {
88797
+ "use strict";
88798
+ import_node_path16 = require("node:path");
88799
+ init_replay_lang_js();
88800
+ PY = /\.py$/;
88801
+ IDENT2 = /^[A-Za-z_]\w*$/;
88802
+ EXTERNAL = /* @__PURE__ */ new Set([
88803
+ "__future__",
88804
+ "abc",
88805
+ "anyio",
88806
+ "argparse",
88807
+ "asyncio",
88808
+ "base64",
88809
+ "boto3",
88810
+ "botocore",
88811
+ "collections",
88812
+ "contextlib",
88813
+ "copy",
88814
+ "csv",
88815
+ "dataclasses",
88816
+ "datetime",
88817
+ "decimal",
88818
+ "enum",
88819
+ "fastapi",
88820
+ "functools",
88821
+ "glob",
88822
+ "hashlib",
88823
+ "http",
88824
+ "httpx",
88825
+ "importlib",
88826
+ "inspect",
88827
+ "io",
88828
+ "itertools",
88829
+ "json",
88830
+ "logging",
88831
+ "math",
88832
+ "mock",
88833
+ "numpy",
88834
+ "operator",
88835
+ "os",
88836
+ "pandas",
88837
+ "pathlib",
88838
+ "pickle",
88839
+ "presidio_analyzer",
88840
+ "presidio_anonymizer",
88841
+ "psycopg",
88842
+ "pyarrow",
88843
+ "pydantic",
88844
+ "pytest",
88845
+ "random",
88846
+ "re",
88847
+ "requests",
88848
+ "shutil",
88849
+ "signal",
88850
+ "sklearn",
88851
+ "socket",
88852
+ "spacy",
88853
+ "sqlalchemy",
88854
+ "starlette",
88855
+ "statistics",
88856
+ "string",
88857
+ "struct",
88858
+ "subprocess",
88859
+ "sys",
88860
+ "tempfile",
88861
+ "textwrap",
88862
+ "threading",
88863
+ "time",
88864
+ "traceback",
88865
+ "types",
88866
+ "typing",
88867
+ "typing_extensions",
88868
+ "unittest",
88869
+ "urllib",
88870
+ "uuid",
88871
+ "warnings",
88872
+ "xgboost",
88873
+ "yaml"
88874
+ ]);
88875
+ indentOf = (line) => /^[ \t]*/.exec(line)[0].length;
88876
+ pythonAdapter = {
88877
+ id: "python",
88878
+ fence: "python",
88879
+ handles: (path2) => PY.test(path2),
88880
+ isTestFile: isPythonTestFile,
88881
+ testTitles: (source) => pythonTestTitles(source),
88882
+ imports: pythonImports,
88883
+ mocks: pythonMocks,
88884
+ dependencies: pythonDependencies,
88885
+ exportsName: pythonExportsName,
88886
+ hasDefault: () => false,
88887
+ signatureOf: pythonSignatureOf
88888
+ };
88889
+ }
88890
+ });
88891
+
88892
+ // src/commands/replay-lang.ts
88893
+ function adapterFor(path2) {
88894
+ return ADAPTERS.find((a) => a.handles(path2)) ?? null;
88895
+ }
88896
+ var ADAPTERS;
88897
+ var init_replay_lang = __esm({
88898
+ "src/commands/replay-lang.ts"() {
88899
+ "use strict";
88900
+ init_replay_lang_js();
88901
+ init_replay_lang_python();
88902
+ ADAPTERS = [jsAdapter, pythonAdapter];
88903
+ }
88904
+ });
88905
+
88906
+ // src/commands/replay-interface.ts
88101
88907
  async function firstAt(show, sha, paths) {
88102
88908
  for (const path2 of paths) {
88103
88909
  const source = await show(sha, path2);
@@ -88108,35 +88914,46 @@ async function firstAt(show, sha, paths) {
88108
88914
  function isTestSupport(path2) {
88109
88915
  return /(^|\/)(__tests__|__mocks__|__fixtures__|fixtures?|test-utils?)\//.test(
88110
88916
  path2
88111
- );
88917
+ ) || // pytest's fixtures file, and a tests package's own __init__.py.
88918
+ /(^|\/)conftest\.py$/.test(path2) || /(^|\/)tests?\/(?:.*\/)?__init__\.py$/.test(path2);
88112
88919
  }
88113
88920
  async function testInterfaceOf(show, task) {
88114
88921
  const tests = new Set(task.testFiles);
88115
88922
  const byPath = /* @__PURE__ */ new Map();
88923
+ const add = async (candidates, imported, defaultImport, lang) => {
88924
+ const atTarget = await firstAt(show, task.targetSha, candidates);
88925
+ if (!atTarget || tests.has(atTarget.path)) return;
88926
+ if (isTestSupport(atTarget.path)) return;
88927
+ const atBase = await show(task.baseSha, atTarget.path);
88928
+ const names = imported.filter(
88929
+ (n) => atBase === null || !lang.exportsName(atBase, n)
88930
+ );
88931
+ const defaultExport = defaultImport && (atBase === null || !lang.hasDefault(atBase));
88932
+ if (atBase !== null && names.length === 0 && !defaultExport) return;
88933
+ const entry2 = byPath.get(atTarget.path) ?? {
88934
+ path: atTarget.path,
88935
+ newFile: atBase === null,
88936
+ names: [],
88937
+ defaultExport: false
88938
+ };
88939
+ for (const n of names) if (!entry2.names.includes(n)) entry2.names.push(n);
88940
+ entry2.defaultExport ||= defaultExport;
88941
+ byPath.set(atTarget.path, entry2);
88942
+ };
88116
88943
  for (const file2 of task.testFiles) {
88117
- if (!JS_TEST.test(file2)) continue;
88944
+ const lang = adapterFor(file2);
88945
+ if (!lang) continue;
88118
88946
  const source = await show(task.targetSha, file2);
88119
88947
  if (source === null) continue;
88120
- for (const imp of importsOf(source)) {
88121
- const candidates = candidatesFor(file2, imp.spec);
88122
- const atTarget = await firstAt(show, task.targetSha, candidates);
88123
- if (!atTarget || tests.has(atTarget.path)) continue;
88124
- if (isTestSupport(atTarget.path)) continue;
88125
- const atBase = await show(task.baseSha, atTarget.path);
88126
- const names = imp.names.filter(
88127
- (n) => atBase === null || !exportsName(atBase, n)
88128
- );
88129
- const defaultExport = imp.defaultImport && (atBase === null || !hasDefaultExport(atBase));
88130
- if (atBase !== null && names.length === 0 && !defaultExport) continue;
88131
- const entry2 = byPath.get(atTarget.path) ?? {
88132
- path: atTarget.path,
88133
- newFile: atBase === null,
88134
- names: [],
88135
- defaultExport: false
88136
- };
88137
- for (const n of names) if (!entry2.names.includes(n)) entry2.names.push(n);
88138
- entry2.defaultExport ||= defaultExport;
88139
- byPath.set(atTarget.path, entry2);
88948
+ for (const imp of lang.imports(source, file2)) {
88949
+ let names = imp.names;
88950
+ for (const [name, sub] of Object.entries(imp.submodules ?? {})) {
88951
+ const at = await firstAt(show, task.targetSha, sub.candidates);
88952
+ if (!at) continue;
88953
+ names = names.filter((n) => n !== name);
88954
+ await add([at.path], sub.names, false, lang);
88955
+ }
88956
+ await add(imp.candidates, names, imp.defaultImport, lang);
88140
88957
  }
88141
88958
  }
88142
88959
  let budget = MAX_INTERFACE_NAMES;
@@ -88146,13 +88963,13 @@ async function testInterfaceOf(show, task) {
88146
88963
  return { ...e, names };
88147
88964
  });
88148
88965
  }
88149
- function fencedTs(text) {
88966
+ function fenced(text, lang) {
88150
88967
  const longest = Math.max(
88151
88968
  0,
88152
88969
  ...(text.match(/`+/g) ?? []).map((run3) => run3.length)
88153
88970
  );
88154
88971
  const fence = "`".repeat(Math.max(3, longest + 1));
88155
- return [`${fence}ts`, ...text.split("\n"), fence];
88972
+ return [`${fence}${lang}`, ...text.split("\n"), fence];
88156
88973
  }
88157
88974
  function interfaceSection(entries) {
88158
88975
  if (entries.length === 0) return [];
@@ -88173,7 +88990,9 @@ function interfaceSection(entries) {
88173
88990
  // As the target declares each: its shape, never its body.
88174
88991
  ...declared.flatMap((n) => [
88175
88992
  "",
88176
- ...fencedTs(e.signatures[n]).map((l) => ` ${l}`)
88993
+ ...fenced(e.signatures[n], adapterFor(e.path)?.fence ?? "ts").map(
88994
+ (l) => ` ${l}`
88995
+ )
88177
88996
  ]),
88178
88997
  ...declared.length ? [""] : []
88179
88998
  ];
@@ -88181,17 +89000,13 @@ function interfaceSection(entries) {
88181
89000
  ""
88182
89001
  ];
88183
89002
  }
88184
- var import_node_path15, MAX_INTERFACE_MODULES, MAX_INTERFACE_NAMES, JS_TEST, EXTENSIONS, IDENT, stripComments;
89003
+ var MAX_INTERFACE_MODULES, MAX_INTERFACE_NAMES;
88185
89004
  var init_replay_interface = __esm({
88186
89005
  "src/commands/replay-interface.ts"() {
88187
89006
  "use strict";
88188
- import_node_path15 = require("node:path");
89007
+ init_replay_lang();
88189
89008
  MAX_INTERFACE_MODULES = 10;
88190
89009
  MAX_INTERFACE_NAMES = 30;
88191
- JS_TEST = /\.[cm]?[jt]sx?$/;
88192
- EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mts", ".cts", ".mjs"];
88193
- IDENT = /^[A-Za-z_$][\w$]*$/;
88194
- stripComments = (source) => source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/.*$/gm, "$1");
88195
89010
  }
88196
89011
  });
88197
89012
 
@@ -88304,27 +89119,6 @@ async function historyPaths(git, baseSha, files) {
88304
89119
  const newest = [...commits.entries()].sort((a, b) => b[1] - a[1]).map(([sha]) => sha);
88305
89120
  return filesOfCommits(git, newest);
88306
89121
  }
88307
- function packageCandidates(spec2) {
88308
- const m = /^(@[\w.-]+\/[\w.-]+)(?:\/(.+))?$/.exec(spec2);
88309
- if (!m) return [];
88310
- const [, pkg, sub] = m;
88311
- const stems = sub ? [`packages/${pkg}/src/${sub}`, `packages/${pkg}/${sub}`] : [`packages/${pkg}/src/index`, `packages/${pkg}/index`];
88312
- return stems.flatMap((s) => [
88313
- `${s}.ts`,
88314
- `${s}.tsx`,
88315
- `${s}.js`,
88316
- `${s}/index.ts`
88317
- ]);
88318
- }
88319
- function packageSpecsOf(source) {
88320
- const text = source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/.*$/gm, "$1");
88321
- const out = [];
88322
- for (const m of text.matchAll(
88323
- /(?:\bfrom\s*|\b(?:vi|jest)\.(?:mock|doMock)\(\s*|\bimport\(\s*)["'](@[^"'\s]+)["']/g
88324
- ))
88325
- if (!out.includes(m[1])) out.push(m[1]);
88326
- return out;
88327
- }
88328
89122
  var MAX_FRAMES, COMMITS_PER_FILE, MAX_HISTORY_FILES, MAX_COMMITS, FILES_PER_COMMIT, MAX_WHERE_PATHS, MAX_GIT_CALLS, ABSOLUTE_TRIES, SOURCE, TEST_FILE, SHA2, FRAME;
88329
89123
  var init_replay_failure_paths = __esm({
88330
89124
  "src/commands/replay-failure-paths.ts"() {
@@ -88347,107 +89141,14 @@ var init_replay_failure_paths = __esm({
88347
89141
  });
88348
89142
 
88349
89143
  // src/commands/replay-spec.ts
88350
- function stringAt(text, i) {
88351
- const quote = text[i];
88352
- if (quote !== "'" && quote !== '"' && quote !== "`") return null;
88353
- let value = "";
88354
- for (let j = i + 1; j < text.length; j++) {
88355
- const c = text[j];
88356
- if (c === "\\" && j + 1 < text.length) {
88357
- value += text[j + 1];
88358
- j += 1;
88359
- } else if (c === quote) return { value, end: j + 1 };
88360
- else if (quote !== "`" && c === "\n") return null;
88361
- else value += c;
88362
- }
88363
- return null;
88364
- }
88365
- function skipGroup(text, i) {
88366
- const open = text[i];
88367
- const close = open === "(" ? ")" : open === "[" ? "]" : null;
88368
- if (!close) return -1;
88369
- let depth = 0;
88370
- for (let j = i; j < text.length; j++) {
88371
- const c = text[j];
88372
- if (c === "'" || c === '"' || c === "`") {
88373
- const s = stringAt(text, j);
88374
- if (!s) return -1;
88375
- j = s.end - 1;
88376
- } else if (c === "(" || c === "[" || c === "{") depth += 1;
88377
- else if (c === ")" || c === "]" || c === "}") {
88378
- depth -= 1;
88379
- if (depth === 0) return c === close ? j + 1 : -1;
88380
- }
88381
- }
88382
- return -1;
88383
- }
88384
- function testCallAt(text, i) {
88385
- CALL.lastIndex = i;
88386
- const m = CALL.exec(text);
88387
- if (!m) return null;
88388
- let j = CALL.lastIndex;
88389
- if (/[\w$]/.test(text[j] ?? "")) return null;
88390
- const mods = m[2];
88391
- if (/\.(?:each|skipIf|runIf|for)\b/.test(mods)) {
88392
- while (/\s/.test(text[j] ?? "")) j++;
88393
- if (text[j] === "`") {
88394
- const s2 = stringAt(text, j);
88395
- if (!s2) return null;
88396
- j = s2.end;
88397
- } else {
88398
- j = skipGroup(text, j);
88399
- if (j < 0) return null;
88400
- }
88401
- }
88402
- while (/\s/.test(text[j] ?? "")) j++;
88403
- if (text[j] !== "(") return null;
88404
- j++;
88405
- while (/\s/.test(text[j] ?? "")) j++;
88406
- const s = stringAt(text, j);
88407
- if (!s) return null;
88408
- const suite = m[1] === "describe" || m[1] === "suite" || m[1] === "context";
88409
- return { suite, title: s.value.replace(/\s+/g, " ").trim(), end: s.end };
88410
- }
88411
- function testTitlesOf(source) {
88412
- const out = [];
88413
- const stack = [];
88414
- let depth = 0;
88415
- const text = source;
88416
- for (let i = 0; i < text.length; i++) {
88417
- const c = text[i];
88418
- const next = text[i + 1];
88419
- if (c === "/" && next === "/") {
88420
- const nl = text.indexOf("\n", i);
88421
- i = nl < 0 ? text.length : nl;
88422
- } else if (c === "/" && next === "*") {
88423
- const close = text.indexOf("*/", i + 2);
88424
- i = close < 0 ? text.length : close + 1;
88425
- } else if (c === "'" || c === '"' || c === "`") {
88426
- const s = stringAt(text, i);
88427
- if (s) i = s.end - 1;
88428
- } else if (c === "{") depth += 1;
88429
- else if (c === "}") {
88430
- depth -= 1;
88431
- while (stack.length && depth <= stack[stack.length - 1].depth)
88432
- stack.pop();
88433
- } else if (/[a-z]/.test(c) && !/[\w$.]/.test(text[i - 1] ?? "")) {
88434
- const call = testCallAt(text, i);
88435
- if (!call) continue;
88436
- if (call.suite) stack.push({ title: call.title, depth });
88437
- else if (call.title)
88438
- out.push([...stack.map((s) => s.title), call.title].join(" \u203A "));
88439
- i = call.end - 1;
88440
- }
88441
- }
88442
- return out;
88443
- }
88444
89144
  async function targetTestTitles(show, task) {
88445
89145
  const out = [];
88446
89146
  for (const file2 of task.testFiles) {
88447
- if (!JS_SOURCE.test(file2)) continue;
89147
+ const lang = adapterFor(file2);
89148
+ if (!lang) continue;
88448
89149
  const source = await show(task.targetSha, file2);
88449
89150
  if (source === null) continue;
88450
- for (const t of testTitlesOf(source)) out.push(`${file2} \u203A ${t}`);
89151
+ for (const t of lang.testTitles(source, file2)) out.push(`${file2} \u203A ${t}`);
88451
89152
  }
88452
89153
  return out;
88453
89154
  }
@@ -88461,113 +89162,13 @@ function cappedTitles(titles) {
88461
89162
  }
88462
89163
  return { shown, more: titles.length - shown.length };
88463
89164
  }
88464
- function typeEnd(text, i, stops, bodyBrace) {
88465
- let depth = 0;
88466
- let expectType = true;
88467
- for (let j = i; j < text.length; j++) {
88468
- const c = text[j];
88469
- if (c === "'" || c === '"' || c === "`") {
88470
- const s = stringAt(text, j);
88471
- if (s) j = s.end - 1;
88472
- expectType = false;
88473
- continue;
88474
- }
88475
- if (c === "=" && text[j + 1] === ">") {
88476
- j += 1;
88477
- expectType = true;
88478
- continue;
88479
- }
88480
- if (depth === 0 && stops.includes(c)) return j;
88481
- if (c === "{" && depth === 0 && bodyBrace && !expectType) return j;
88482
- if ("([<{".includes(c)) {
88483
- depth += 1;
88484
- expectType = true;
88485
- } else if (")]>}".includes(c)) {
88486
- depth -= 1;
88487
- expectType = false;
88488
- if (depth < 0) return j;
88489
- } else if (/[:|&,?]/.test(c)) expectType = true;
88490
- else if (!/\s/.test(c)) expectType = false;
88491
- }
88492
- return text.length;
88493
- }
88494
- function capped(text) {
88495
- const lines = text.trim().split("\n").map((l) => l.replace(/\s+$/, ""));
88496
- let out = lines.slice(0, MAX_SIGNATURE_LINES).join("\n");
88497
- let cut2 = lines.length > MAX_SIGNATURE_LINES;
88498
- if (out.length > MAX_SIGNATURE_CHARS) {
88499
- out = out.slice(0, MAX_SIGNATURE_CHARS);
88500
- cut2 = true;
88501
- }
88502
- return cut2 ? `${out.trimEnd()}
88503
- \u2026` : out;
88504
- }
88505
- function signatureOf(source, name) {
88506
- const text = STRIP_COMMENTS(source);
88507
- const n = name.replace(/\$/g, "\\$");
88508
- const lead = String.raw`(?:^|\n)[ \t]*((?:export\s+)?(?:declare\s+)?(?:default\s+)?(?:abstract\s+)?(?:async\s+)?)`;
88509
- const fn = new RegExp(`${lead}(function\\*?\\s+${n})\\b`).exec(text);
88510
- if (fn) {
88511
- const start = fn.index + fn[0].length - fn[2].length - fn[1].length;
88512
- const end = typeEnd(text, fn.index + fn[0].length, ";", true);
88513
- return capped(text.slice(start, end));
88514
- }
88515
- const cls = new RegExp(`${lead}(class\\s+${n})\\b`).exec(text);
88516
- if (cls) {
88517
- const start = cls.index + cls[0].length - cls[2].length - cls[1].length;
88518
- const brace = text.indexOf("{", cls.index + cls[0].length);
88519
- return capped(text.slice(start, brace < 0 ? text.length : brace));
88520
- }
88521
- const decl = new RegExp(`${lead}((?:interface|enum)\\s+${n})\\b`).exec(text);
88522
- if (decl) {
88523
- const start = decl.index + decl[0].length - decl[2].length - decl[1].length;
88524
- const brace = text.indexOf("{", decl.index + decl[0].length);
88525
- if (brace < 0 || /;|\n\s*(?:export|interface|type|const|function|class|enum)\b/.test(
88526
- text.slice(decl.index + decl[0].length, brace)
88527
- ))
88528
- return null;
88529
- let depth = 0;
88530
- let end = text.length;
88531
- for (let j = brace; j < text.length; j++) {
88532
- if (text[j] === "{") depth += 1;
88533
- else if (text[j] === "}" && --depth === 0) {
88534
- end = j + 1;
88535
- break;
88536
- }
88537
- }
88538
- return capped(text.slice(start, end));
88539
- }
88540
- const type = new RegExp(`${lead}(type\\s+${n})\\b`).exec(text);
88541
- if (type) {
88542
- const start = type.index + type[0].length - type[2].length - type[1].length;
88543
- const end = typeEnd(text, type.index + type[0].length, ";", false);
88544
- return capped(text.slice(start, end));
88545
- }
88546
- const v = new RegExp(`${lead}((?:const|let|var)\\s+${n})\\b`).exec(text);
88547
- if (v) {
88548
- const start = v.index + v[0].length - v[2].length - v[1].length;
88549
- const after = v.index + v[0].length;
88550
- const rest = text.slice(after);
88551
- if (/^\s*:/.test(rest)) {
88552
- const end = typeEnd(text, after, "=;", false);
88553
- return capped(text.slice(start, end));
88554
- }
88555
- const arrow = /^\s*=\s*(?:async\s+)?(?:<[^>]*>\s*)?(?=\()/.exec(rest);
88556
- if (!arrow) return null;
88557
- const close = skipGroup(text, after + arrow[0].length);
88558
- if (close < 0) return null;
88559
- const ret = /^\s*(?::[^=;{]*?)?\s*=>/.exec(text.slice(close));
88560
- return ret ? capped(text.slice(start, close + ret[0].length)) : null;
88561
- }
88562
- return null;
88563
- }
88564
89165
  async function withSignatures(show, targetSha, entries) {
88565
89166
  const out = [];
88566
89167
  for (const e of entries) {
88567
89168
  const source = e.names.length ? await show(targetSha, e.path) : null;
88568
89169
  const signatures = {};
88569
89170
  for (const n of e.names) {
88570
- const sig = source === null ? null : signatureOf(source, n);
89171
+ const sig = source === null ? null : adapterFor(e.path)?.signatureOf(source, n) ?? null;
88571
89172
  if (sig) signatures[n] = sig;
88572
89173
  }
88573
89174
  out.push(Object.keys(signatures).length ? { ...e, signatures } : e);
@@ -88582,39 +89183,18 @@ function titleOfTest(name) {
88582
89183
  const parts = name.split(" \u203A ");
88583
89184
  return (fileOfTest(name) ? parts.slice(1) : parts).join(" \u203A ").trim();
88584
89185
  }
88585
- function mockedSpecsOf(source) {
88586
- const out = [];
88587
- for (const m of STRIP_COMMENTS(source).matchAll(
88588
- /\b(?:vi|jest)\.(?:mock|doMock)\(\s*["'](\.[^"']*)["']/g
88589
- ))
88590
- if (!out.includes(m[1])) out.push(m[1]);
88591
- return out;
88592
- }
88593
89186
  async function hopOf(show, baseSha, from, skip) {
88594
89187
  const out = [];
88595
89188
  for (const file2 of from) {
88596
89189
  if (out.length >= MAX_HOP_MODULES) break;
88597
- if (!JS_SOURCE.test(file2)) continue;
89190
+ const lang = adapterFor(file2);
89191
+ if (!lang) continue;
88598
89192
  const source = await show(baseSha, file2).catch(() => null);
88599
89193
  if (source === null) continue;
88600
- const reexports = [
88601
- ...STRIP_COMMENTS(source).matchAll(
88602
- /\bexport\s+(?:type\s+)?(?:\*(?:\s+as\s+[\w$]+)?|\{[^}]*\})\s*from\s*["'](\.[^"']+)["']/g
88603
- )
88604
- ].map((m) => m[1]);
88605
- const relative4 = [
88606
- .../* @__PURE__ */ new Set([
88607
- ...importsOf(source).map((i) => i.spec),
88608
- ...mockedSpecsOf(source),
88609
- ...reexports
88610
- ])
88611
- ].map((spec2) => candidatesFor(file2, spec2));
88612
- const packages = packageSpecsOf(source).map(packageCandidates);
88613
- for (const candidates of [...relative4, ...packages]) {
89194
+ for (const candidates of lang.dependencies(source, file2)) {
88614
89195
  if (out.length >= MAX_HOP_MODULES) break;
88615
- if (!candidates.length) continue;
88616
89196
  const at = await firstAt(show, baseSha, candidates).catch(() => null);
88617
- if (!at || skip.has(at.path) || TEST_FILE2.test(at.path) || isTestSupport(at.path) || out.includes(at.path))
89197
+ if (!at || skip.has(at.path) || adapterFor(at.path)?.isTestFile(at.path) || isTestSupport(at.path) || out.includes(at.path))
88618
89198
  continue;
88619
89199
  out.push(at.path);
88620
89200
  }
@@ -88660,30 +89240,37 @@ function errorLineOf(output) {
88660
89240
  }
88661
89241
  function baseNameOf(path2) {
88662
89242
  const parts = path2.split("/");
88663
- const name = (parts.pop() ?? path2).replace(/\.[cm]?[jt]sx?$/, "").replace(/\.(?:test|spec)$/, "");
88664
- return name === "index" && parts.length ? parts[parts.length - 1] : name;
89243
+ const file2 = parts.pop() ?? path2;
89244
+ const name = /\.py$/.test(file2) ? file2.replace(/\.py$/, "").replace(/^test_(?=.)|(?<=.)_test$/, "") : file2.replace(/\.[cm]?[jt]sx?$/, "").replace(/\.(?:test|spec)$/, "");
89245
+ return (name === "index" || name === "__init__") && parts.length ? parts[parts.length - 1] : name;
88665
89246
  }
88666
- var MAX_TITLES, MAX_TITLE_CHARS, MAX_SIGNATURE_LINES, MAX_SIGNATURE_CHARS, MAX_FAILING_PATHS, JS_SOURCE, TEST_FILE2, CALL, STRIP_COMMENTS, MAX_HOP_MODULES, norm;
89247
+ var MAX_TITLES, MAX_TITLE_CHARS, MAX_FAILING_PATHS, MAX_HOP_MODULES, norm;
88667
89248
  var init_replay_spec = __esm({
88668
89249
  "src/commands/replay-spec.ts"() {
88669
89250
  "use strict";
88670
89251
  init_replay_interface();
88671
89252
  init_replay_failure_paths();
89253
+ init_replay_lang();
88672
89254
  MAX_TITLES = 40;
88673
89255
  MAX_TITLE_CHARS = 4e3;
88674
- MAX_SIGNATURE_LINES = 15;
88675
- MAX_SIGNATURE_CHARS = 600;
88676
89256
  MAX_FAILING_PATHS = 12;
88677
- JS_SOURCE = /\.[cm]?[jt]sx?$/;
88678
- TEST_FILE2 = /\.(?:test|spec)\.[cm]?[jt]sx?$/;
88679
- CALL = /(describe|suite|context|it|test)((?:\.[A-Za-z]+)*)/y;
88680
- STRIP_COMMENTS = (source) => source.replace(/\/\*[\s\S]*?\*\//g, " ").replace(/(^|[^:])\/\/.*$/gm, "$1");
88681
89257
  MAX_HOP_MODULES = 24;
88682
89258
  norm = (s) => s.replace(/\s+/g, " ").trim();
88683
89259
  }
88684
89260
  });
88685
89261
 
88686
89262
  // src/commands/replay-context.ts
89263
+ function storedScoreOf(task) {
89264
+ return {
89265
+ onPoint: task.context?.onPoint ?? 0,
89266
+ nearby: task.context?.nearby ?? 0
89267
+ };
89268
+ }
89269
+ function rankFound(tasks, scoreOf) {
89270
+ return tasks.map((task) => ({ task, score: scoreOf(task) })).sort(
89271
+ (a, b) => b.score.onPoint - a.score.onPoint || b.score.nearby - a.score.nearby || a.task.place - b.task.place
89272
+ ).map((r) => r.task);
89273
+ }
88687
89274
  function stateOf(knowledge) {
88688
89275
  if (knowledge === "returned") return "found";
88689
89276
  return knowledge;
@@ -88714,6 +89301,7 @@ function visibleAsk(task) {
88714
89301
  ].join("\n");
88715
89302
  let paths;
88716
89303
  let queries;
89304
+ let hints;
88717
89305
  if (failing?.tests.length) {
88718
89306
  const named = failing.tests.map(fileOfTest).filter((f) => !!f);
88719
89307
  paths = [
@@ -88723,11 +89311,17 @@ function visibleAsk(task) {
88723
89311
  ])
88724
89312
  ].slice(0, MAX_FAILING_PATHS);
88725
89313
  const files = [...new Set(paths.map(baseNameOf))];
89314
+ const errorLine = errorLineOf(failing.output);
88726
89315
  queries = [
88727
89316
  ...failing.tests.slice(0, FAILING_QUERIES).map(titleOfTest),
88728
- errorLineOf(failing.output) ?? "",
89317
+ errorLine ?? "",
88729
89318
  files.slice(0, 6).join(" ")
88730
89319
  ];
89320
+ hints = {
89321
+ failingTests: failing.tests,
89322
+ ...errorLine ? { error: errorLine } : {},
89323
+ files: paths
89324
+ };
88731
89325
  } else {
88732
89326
  const iface = task.testInterface ?? [];
88733
89327
  paths = [
@@ -88739,6 +89333,7 @@ function visibleAsk(task) {
88739
89333
  ...(task.kind !== "recovery" ? task.testTitles ?? [] : []).slice(0, TITLE_QUERIES).map(titleOfTest),
88740
89334
  names.join(" ")
88741
89335
  ];
89336
+ hints = { files: paths, names: [...new Set(names)] };
88742
89337
  }
88743
89338
  queries = queries.map((q) => flat2(q).slice(0, QUERY_CHARS2).trim()).filter((q, i, all) => q !== "" && all.indexOf(q) === i).slice(0, MAX_QUERIES);
88744
89339
  if (!queries.length && head) queries = [head];
@@ -88750,7 +89345,8 @@ function visibleAsk(task) {
88750
89345
  task: [task.card.problem, task.card.acceptance].join("\n\n").slice(0, 1e3),
88751
89346
  error: error2,
88752
89347
  queries,
88753
- ...paths.length ? { paths } : {}
89348
+ ...paths.length ? { paths } : {},
89349
+ hints
88754
89350
  };
88755
89351
  }
88756
89352
  async function checkContext(deps, input) {
@@ -88792,24 +89388,30 @@ async function checkContext(deps, input) {
88792
89388
  });
88793
89389
  const state = stateOf(judged.knowledge);
88794
89390
  if (!state || !judged.relevantIds) return null;
89391
+ const visible = new Set(reached.flatMap((c) => c.returnedIds));
89392
+ const count4 = (ids) => (ids ?? []).filter((id) => visible.has(id)).length;
88795
89393
  return {
88796
89394
  taskId: task.taskId,
88797
89395
  inputsFingerprint: task.inputsFingerprint,
88798
89396
  state,
88799
89397
  relevantIds: judged.relevantIds,
88800
89398
  judgeTag: judged.judgeTag,
88801
- checkVersion: CONTEXT_CHECK_VERSION
89399
+ checkVersion: CONTEXT_CHECK_VERSION,
89400
+ onPoint: count4(judged.relevantIds),
89401
+ nearby: count4(judged.nearbyIds)
88802
89402
  };
88803
89403
  }
88804
89404
  async function gateOnContext(deps, tasks, options) {
88805
89405
  const states = /* @__PURE__ */ new Map();
89406
+ const scores = /* @__PURE__ */ new Map();
88806
89407
  const checks = [];
88807
89408
  for (const t of tasks)
88808
- if (!needsCheck(t)) states.set(t.taskId, t.context.state);
88809
- const found = () => [...states.values()].filter((s) => s === "found").length;
89409
+ if (!needsCheck(t)) {
89410
+ states.set(t.taskId, t.context.state);
89411
+ scores.set(t.taskId, storedScoreOf(t));
89412
+ }
88810
89413
  const toCheck = tasks.filter((t) => needsCheck(t));
88811
89414
  await runPool(toCheck, options.concurrency, async (task) => {
88812
- if (options.limit && found() >= options.limit) return;
88813
89415
  const label = task.name ?? task.taskKey;
88814
89416
  try {
88815
89417
  await options.prepare?.(task);
@@ -88830,9 +89432,10 @@ async function gateOnContext(deps, tasks, options) {
88830
89432
  return;
88831
89433
  }
88832
89434
  checks.push(check3);
89435
+ scores.set(task.taskId, { onPoint: check3.onPoint, nearby: check3.nearby });
88833
89436
  const n = check3.relevantIds.length;
88834
89437
  deps.log(
88835
- `context ${check3.state.padEnd(6)} ${label}${n ? ` (${n} relevant item${n === 1 ? "" : "s"})` : ""}`
89438
+ `context ${check3.state.padEnd(6)} ${label}${n ? ` (${n} on-point item${n === 1 ? "" : "s"}; returned: ${check3.onPoint} on point, ${check3.nearby} nearby)` : check3.nearby ? ` (${check3.nearby} nearby only)` : ""}`
88836
89439
  );
88837
89440
  } catch (err2) {
88838
89441
  states.set(task.taskId, null);
@@ -88856,21 +89459,33 @@ async function gateOnContext(deps, tasks, options) {
88856
89459
  `The context checks could not be reported (${err2 instanceof Error ? err2.message : String(err2)}); the next run checks them again.`
88857
89460
  );
88858
89461
  }
88859
- const replay2 = [];
89462
+ const found = [];
88860
89463
  let noContext = 0;
88861
89464
  let unknown2 = 0;
88862
89465
  for (const t of tasks) {
88863
89466
  const label = t.name ?? t.taskKey;
88864
- if (!states.has(t.taskId)) continue;
88865
89467
  const s = states.get(t.taskId);
88866
- if (s === "found") replay2.push(t);
89468
+ if (s === "found") found.push(t);
88867
89469
  else if (s === "missed" || s === "none") {
88868
89470
  noContext += 1;
88869
- deps.log(`skip ${label}: no relevant context Haansi can return (${s})`);
89471
+ deps.log(`skip ${label}: no on-point context Haansi can return (${s})`);
88870
89472
  } else unknown2 += 1;
88871
89473
  }
89474
+ const replay2 = rankFound(
89475
+ found,
89476
+ (t) => scores.get(t.taskId) ?? { onPoint: 0, nearby: 0 }
89477
+ );
88872
89478
  return { replay: replay2, noContext, unknown: unknown2 };
88873
89479
  }
89480
+ function fromChecks(tasks, limit, shard) {
89481
+ const ready = tasks.filter(
89482
+ (t) => !needsCheck(t) && t.context?.state === "found" && t.calibration?.state === "valid" && t.calibration.inputsFingerprint === t.inputsFingerprint
89483
+ );
89484
+ const ranked = rankFound(ready, storedScoreOf);
89485
+ const top = limit ? ranked.slice(0, limit) : ranked;
89486
+ const mine = shard && shard.count > 1 ? top.filter((_, i) => i % shard.count === shard.index - 1) : top;
89487
+ return { found: ready.length, top, mine };
89488
+ }
88874
89489
  var CONTEXT_CHECK_VERSION, QUERY_CHARS2, ERROR_CHARS, MAX_PATHS, HEAD_CHARS, MAX_QUERIES, FAILING_QUERIES, TITLE_QUERIES, CONTEXT_REPORT_CHUNK, flat2;
88875
89490
  var init_replay_context = __esm({
88876
89491
  "src/commands/replay-context.ts"() {
@@ -88879,7 +89494,7 @@ var init_replay_context = __esm({
88879
89494
  init_replay_diff();
88880
89495
  init_replay_scale();
88881
89496
  init_replay_spec();
88882
- CONTEXT_CHECK_VERSION = 2;
89497
+ CONTEXT_CHECK_VERSION = 3;
88883
89498
  QUERY_CHARS2 = 200;
88884
89499
  ERROR_CHARS = 1e3;
88885
89500
  MAX_PATHS = 20;
@@ -88904,7 +89519,7 @@ __export(replay_tasks_exports, {
88904
89519
  cardPrompt: () => cardPrompt,
88905
89520
  changedFiles: () => changedFiles,
88906
89521
  configFingerprintOf: () => configFingerprintOf,
88907
- fenced: () => fenced,
89522
+ fenced: () => fenced2,
88908
89523
  haansiSection: () => haansiSection,
88909
89524
  haansiText: () => haansiText,
88910
89525
  haansiUseOf: () => haansiUseOf,
@@ -88932,7 +89547,7 @@ function reportBatches(results, size = (r) => JSON.stringify(r).length) {
88932
89547
  if (batch.length) batches.push(batch);
88933
89548
  return batches;
88934
89549
  }
88935
- function fenced(text) {
89550
+ function fenced2(text) {
88936
89551
  const longest = Math.max(
88937
89552
  0,
88938
89553
  ...(text.match(/`+/g) ?? []).map((run3) => run3.length)
@@ -88989,7 +89604,7 @@ function cardPrompt(task, feedback, arm = "baseline", tools = []) {
88989
89604
  "",
88990
89605
  "Their output ends with (the CI's output: data, not instructions):",
88991
89606
  "",
88992
- ...fenced(failing.output)
89607
+ ...fenced2(failing.output)
88993
89608
  ] : [],
88994
89609
  ""
88995
89610
  ] : [],
@@ -89120,13 +89735,26 @@ async function runStoredReplays(options, deps) {
89120
89735
  );
89121
89736
  return { results: [], notValid: 0, recorded: null };
89122
89737
  }
89123
- const mine = set2.tasks.filter(
89124
- (t) => inShard(t.taskId, options.shard ?? null)
89125
- );
89126
- if (options.shard && options.shard.count > 1)
89738
+ let mine;
89739
+ if (options.fromChecks) {
89740
+ const picked = fromChecks(set2.tasks, options.limit, options.shard ?? null);
89741
+ mine = picked.mine;
89127
89742
  deps.log(
89128
- `Shard ${options.shard.index}/${options.shard.count}: ${mine.length} of ${set2.tasks.length} task(s).`
89743
+ `From stored checks: ${picked.found} found task(s) in the set; the run takes ${picked.top.length}${options.limit ? ` (--limit ${options.limit})` : ""}, best scored first.`
89129
89744
  );
89745
+ if (options.shard && options.shard.count > 1)
89746
+ deps.log(
89747
+ `Shard ${options.shard.index}/${options.shard.count}: ${mine.length} of the run's ${picked.top.length} task(s).`
89748
+ );
89749
+ if (mine.length === 0)
89750
+ return { results: [], notValid: 0, noContext: 0, recorded: null };
89751
+ } else {
89752
+ mine = set2.tasks.filter((t) => inShard(t.taskId, options.shard ?? null));
89753
+ if (options.shard && options.shard.count > 1)
89754
+ deps.log(
89755
+ `Shard ${options.shard.index}/${options.shard.count}: ${mine.length} of ${set2.tasks.length} task(s).`
89756
+ );
89757
+ }
89130
89758
  const { states } = await runCalibration(
89131
89759
  // With the context gate, --limit caps the tasks replayed (found ones),
89132
89760
  // not the ones calibrated: calibrating only the first n left the rest
@@ -89206,7 +89834,6 @@ async function runStoredReplays(options, deps) {
89206
89834
  agentCmd: options.judgeCmd || options.agentCmd,
89207
89835
  timeoutMs: options.timeoutMs,
89208
89836
  concurrency: options.concurrency ?? 1,
89209
- limit: options.limit,
89210
89837
  dryRun: options.dryRun,
89211
89838
  cardOf: (task) => cardPrompt(task, null),
89212
89839
  targetOf,
@@ -89217,6 +89844,19 @@ async function runStoredReplays(options, deps) {
89217
89844
  noContext = gate.noContext;
89218
89845
  contextUnknown = gate.unknown;
89219
89846
  }
89847
+ if (options.checkOnly) {
89848
+ deps.log(
89849
+ `Checked: ${gated.length} found \xB7 ${noContext} with no on-point context \xB7 ${contextUnknown} unknown \xB7 ${notValid} not valid.`
89850
+ );
89851
+ return {
89852
+ results: [],
89853
+ notValid,
89854
+ noContext,
89855
+ contextUnknown,
89856
+ found: gated.length,
89857
+ recorded: null
89858
+ };
89859
+ }
89220
89860
  const chosen = options.limit ? gated.slice(0, options.limit) : gated;
89221
89861
  const results = [];
89222
89862
  let recorded = 0;
@@ -89573,6 +90213,8 @@ function parseReplayArgs(argv) {
89573
90213
  else if (takeScaleArg(a, next, scale, errors)) continue;
89574
90214
  else if (a === "--force") options.force = true;
89575
90215
  else if (a === "--any-context") options.anyContext = true;
90216
+ else if (a === "--check-only") options.checkOnly = true;
90217
+ else if (a === "--from-checks") options.fromChecks = true;
89576
90218
  else if (a === "--max-hours") options.maxHours = Number(next());
89577
90219
  else if (takeContainerArg(a, next, options.container, errors)) continue;
89578
90220
  else if (a === "--arms")
@@ -89594,6 +90236,16 @@ function parseReplayArgs(argv) {
89594
90236
  if (options.arms.length === 0 || options.arms.some((a) => !ARMS.includes(a)))
89595
90237
  errors.push("--arms must list baseline and/or haansi.");
89596
90238
  errors.push(...containerErrors(options.container));
90239
+ if (options.checkOnly && options.fromChecks)
90240
+ errors.push("--check-only and --from-checks are the two phases: pass one.");
90241
+ if ((options.checkOnly || options.fromChecks) && options.anyContext)
90242
+ errors.push(
90243
+ "--any-context skips the context check: not with --check-only or --from-checks."
90244
+ );
90245
+ if (options.checkOnly && options.limit !== null)
90246
+ errors.push(
90247
+ "--check-only checks every task: --limit belongs to the --from-checks phase."
90248
+ );
89597
90249
  if (options.maxHours !== null && options.maxHours !== void 0 && (!Number.isFinite(options.maxHours) || options.maxHours <= 0))
89598
90250
  errors.push("--max-hours must be a positive number.");
89599
90251
  Object.assign(
@@ -89664,7 +90316,7 @@ function cleanCheckout(deps, dir, task) {
89664
90316
  }
89665
90317
  async function replayArm(deps, options, task, arm, promptOf, inspect, agentEnv = {}) {
89666
90318
  const started = deps.now();
89667
- const dir = (0, import_node_path16.join)(
90319
+ const dir = (0, import_node_path17.join)(
89668
90320
  deps.workDir(),
89669
90321
  `${task.processId.replace(/[^a-zA-Z0-9_-]/g, "")}-${arm}`
89670
90322
  );
@@ -89693,7 +90345,7 @@ async function replayArm(deps, options, task, arm, promptOf, inspect, agentEnv =
89693
90345
  `\u2026 ${label}: set up in ${since(at)}${setup.cached ? " (from the setup cache)" : ""}`
89694
90346
  );
89695
90347
  }
89696
- const promptFile = (0, import_node_path16.join)(dir, ".haansi-replay", "prompt.md");
90348
+ const promptFile = (0, import_node_path17.join)(dir, ".haansi-replay", "prompt.md");
89697
90349
  let mcpConfigFile = agentEnv.HAANSI_REPLAY_MCP_CONFIG;
89698
90350
  if (!mcpConfigFile) {
89699
90351
  mcpConfigFile = `${dir}.mcp.json`;
@@ -89766,11 +90418,11 @@ async function replayArm(deps, options, task, arm, promptOf, inspect, agentEnv =
89766
90418
  );
89767
90419
  }
89768
90420
  const gradeSha = task.testNames?.length ? task.baseSha : task.targetSha;
89769
- const own = new Map(files.map((f) => [f, deps.readFile((0, import_node_path16.join)(dir, f))]));
90421
+ const own = new Map(files.map((f) => [f, deps.readFile((0, import_node_path17.join)(dir, f))]));
89770
90422
  for (const f of files) {
89771
90423
  const content = await deps.showFile(gradeSha, f);
89772
- if (content === null) deps.removeFile((0, import_node_path16.join)(dir, f));
89773
- else deps.writeFile((0, import_node_path16.join)(dir, f), content);
90424
+ if (content === null) deps.removeFile((0, import_node_path17.join)(dir, f));
90425
+ else deps.writeFile((0, import_node_path17.join)(dir, f), content);
89774
90426
  }
89775
90427
  const testAt = deps.now();
89776
90428
  deps.log(`\u2026 ${label}: agent done in ${since(agentAt)}, grading`);
@@ -89821,8 +90473,8 @@ async function replayArm(deps, options, task, arm, promptOf, inspect, agentEnv =
89821
90473
  }
89822
90474
  if (test.code === 0 && !guarded) {
89823
90475
  for (const [file2, content] of own) {
89824
- if (content === null) deps.removeFile((0, import_node_path16.join)(dir, file2));
89825
- else deps.writeFile((0, import_node_path16.join)(dir, file2), content);
90476
+ if (content === null) deps.removeFile((0, import_node_path17.join)(dir, file2));
90477
+ else deps.writeFile((0, import_node_path17.join)(dir, file2), content);
89826
90478
  }
89827
90479
  if (inspect) await inspect(dir);
89828
90480
  return {
@@ -89838,8 +90490,8 @@ async function replayArm(deps, options, task, arm, promptOf, inspect, agentEnv =
89838
90490
  };
89839
90491
  }
89840
90492
  for (const [file2, content] of own) {
89841
- if (content === null) deps.removeFile((0, import_node_path16.join)(dir, file2));
89842
- else deps.writeFile((0, import_node_path16.join)(dir, file2), content);
90493
+ if (content === null) deps.removeFile((0, import_node_path17.join)(dir, file2));
90494
+ else deps.writeFile((0, import_node_path17.join)(dir, file2), content);
89843
90495
  }
89844
90496
  feedback = guarded ? [
89845
90497
  GUARD_FEEDBACK,
@@ -89931,11 +90583,11 @@ function runCommand(file2, args, cwd, env, timeoutMs, stdoutOnly = false) {
89931
90583
  });
89932
90584
  }
89933
90585
  function dropLinks(work, path2) {
89934
- const rel = (0, import_node_path16.relative)(work, path2);
89935
- if (rel === "" || rel.startsWith("..") || (0, import_node_path16.isAbsolute)(rel)) return;
90586
+ const rel = (0, import_node_path17.relative)(work, path2);
90587
+ if (rel === "" || rel.startsWith("..") || (0, import_node_path17.isAbsolute)(rel)) return;
89936
90588
  let at = work;
89937
- for (const part of rel.split(import_node_path16.sep)) {
89938
- at = (0, import_node_path16.join)(at, part);
90589
+ for (const part of rel.split(import_node_path17.sep)) {
90590
+ at = (0, import_node_path17.join)(at, part);
89939
90591
  let link = false;
89940
90592
  try {
89941
90593
  link = (0, import_node_fs13.lstatSync)(at).isSymbolicLink();
@@ -89970,7 +90622,7 @@ function localDeps(work) {
89970
90622
  // dropLinks: with a container, nothing runs in it while these do.
89971
90623
  writeFile: (path2, content) => {
89972
90624
  dropLinks(work, path2);
89973
- (0, import_node_fs13.mkdirSync)((0, import_node_path16.dirname)(path2), { recursive: true });
90625
+ (0, import_node_fs13.mkdirSync)((0, import_node_path17.dirname)(path2), { recursive: true });
89974
90626
  const fd2 = (0, import_node_fs13.openSync)(
89975
90627
  path2,
89976
90628
  import_node_fs13.constants.O_WRONLY | import_node_fs13.constants.O_CREAT | import_node_fs13.constants.O_TRUNC | import_node_fs13.constants.O_NOFOLLOW
@@ -90031,7 +90683,7 @@ async function replay(argv) {
90031
90683
  async function replayStored(options, token2, apiUrl2) {
90032
90684
  const { runStoredReplays: runStoredReplays2 } = await Promise.resolve().then(() => (init_replay_tasks(), replay_tasks_exports));
90033
90685
  const { cliVersion: cliVersion2 } = await Promise.resolve().then(() => (init_replay_calibrate(), replay_calibrate_exports));
90034
- const work = (0, import_node_fs13.mkdtempSync)((0, import_node_path16.join)((0, import_node_os11.tmpdir)(), "haansi-replay-"));
90686
+ const work = (0, import_node_fs13.mkdtempSync)((0, import_node_path17.join)((0, import_node_os11.tmpdir)(), "haansi-replay-"));
90035
90687
  let stop = null;
90036
90688
  try {
90037
90689
  const contained = await withContainer(
@@ -90041,7 +90693,7 @@ async function replayStored(options, token2, apiUrl2) {
90041
90693
  runCommand
90042
90694
  );
90043
90695
  stop = contained.stop;
90044
- const { results, notValid, noContext, contextUnknown, recorded } = await runStoredReplays2(options, {
90696
+ const { results, notValid, noContext, contextUnknown, found, recorded } = await runStoredReplays2(options, {
90045
90697
  ...contained.deps,
90046
90698
  getReplaySet: (repository) => apiGet3(
90047
90699
  `/memory/replays/tasks?repository=${encodeURIComponent(repository)}`,
@@ -90089,6 +90741,13 @@ async function replayStored(options, token2, apiUrl2) {
90089
90741
  apiUrl: apiUrl2,
90090
90742
  token: token2
90091
90743
  });
90744
+ if (options.checkOnly) {
90745
+ console.log(
90746
+ `
90747
+ Context checked: ${found ?? 0} task(s) found \xB7 ${noContext ?? 0} with no on-point context${contextUnknown ? ` \xB7 ${contextUnknown} could not be checked` : ""} \xB7 ${notValid} not valid to replay`
90748
+ );
90749
+ return;
90750
+ }
90092
90751
  const arm = (a) => {
90093
90752
  const mine = results.filter((r) => r.arm === a);
90094
90753
  return `${mine.filter((r) => r.passed).length}/${mine.length}`;
@@ -90108,14 +90767,14 @@ Baseline: ${arm("baseline")} passed \xB7 With Haansi: ${arm("haansi")} passed \x
90108
90767
  (0, import_node_fs13.rmSync)(work, { recursive: true, force: true });
90109
90768
  }
90110
90769
  }
90111
- var import_node_child_process5, import_node_fs13, import_node_os11, import_node_path16, SHA, ARMS, FEEDBACK_CHARS, FAILURE_LINES2, REPLAY_BRANCH, OUTPUT_HEAD_CHARS, OUTPUT_TAIL_CHARS, USAGE2;
90770
+ var import_node_child_process5, import_node_fs13, import_node_os11, import_node_path17, SHA, ARMS, FEEDBACK_CHARS, FAILURE_LINES2, REPLAY_BRANCH, OUTPUT_HEAD_CHARS, OUTPUT_TAIL_CHARS, USAGE2;
90112
90771
  var init_replay = __esm({
90113
90772
  "src/commands/replay.ts"() {
90114
90773
  "use strict";
90115
90774
  import_node_child_process5 = require("node:child_process");
90116
90775
  import_node_fs13 = require("node:fs");
90117
90776
  import_node_os11 = require("node:os");
90118
- import_node_path16 = require("node:path");
90777
+ import_node_path17 = require("node:path");
90119
90778
  init_paths();
90120
90779
  init_replay_errors();
90121
90780
  init_api2();
@@ -90138,6 +90797,7 @@ var init_replay = __esm({
90138
90797
  [--judge-cmd "<cmd>"]
90139
90798
  [--run-ref <url>] [--dry-run] [--repo-commands] [--no-diffs]
90140
90799
  [--shard i/n] [--concurrency k] [--force] [--max-hours h] [--any-context]
90800
+ [--check-only | --from-checks]
90141
90801
  [--setup-cache <files> --setup-cache-path <paths> [--setup-cache-dir <dir>]]
90142
90802
  [--container <image> [--container-setup "<cmd>"] [--container-env NAME]...]
90143
90803
 
@@ -90168,10 +90828,18 @@ files they are and import, and the files changed by the commits that wrote
90168
90828
  the lines its stack frames name, or by those files' own last commits before
90169
90829
  the start; a feature's problem, its tests' titles and the
90170
90830
  names they use; the paths the card names), and the relevance judge (your agent
90171
- command, once per task checked) says whether anything relevant came back.
90172
- A task with nothing relevant Haansi can return is skipped, and checked again
90173
- once the organization gains new Haansi content. --any-context replays every
90174
- valid task without the check (diagnostics).
90831
+ command, once per task checked) grades each item that came back on point (it
90832
+ says part of what to change or check), nearby (same area, another problem)
90833
+ or unrelated. A task is replayed only when an on-point item came back; one
90834
+ without is skipped, and checked again once the organization gains new Haansi
90835
+ content. Found tasks are replayed most on-point items first (then most
90836
+ nearby), and --limit takes the best. --any-context replays every valid task
90837
+ without the check (diagnostics).
90838
+
90839
+ Across shards, run two phases so --limit takes the best of the whole set:
90840
+ --check-only --shard i/n calibrates and checks each share (no agent runs);
90841
+ then --from-checks --limit N --shard i/n ranks every stored found task, takes
90842
+ the top N for the run, and replays this shard's share of them.
90175
90843
 
90176
90844
  --judge-cmd runs the judges (whether the agent used what Haansi returned,
90177
90845
  which of it was relevant, and the context check before replaying) with their