@quikit/quikpilot-runner 9.3.0-rc.79 → 9.3.0-rc.80

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/index.js CHANGED
@@ -28904,13 +28904,13 @@ function parseFileCommits(log) {
28904
28904
  return out2;
28905
28905
  }
28906
28906
  function readTestHistory(input) {
28907
- const git3 = input.git ?? readGit;
28907
+ const git4 = input.git ?? readGit;
28908
28908
  const isTest = input.isTest ?? testRule();
28909
28909
  const now = input.now ?? Date.now;
28910
28910
  try {
28911
- if (git3(["rev-parse", "--is-shallow-repository"]).trim() === "true") return { available: false };
28911
+ if (git4(["rev-parse", "--is-shallow-repository"]).trim() === "true") return { available: false };
28912
28912
  if (input.title === "" || input.title.includes("\n")) return { available: false };
28913
- const log = git3(["log", "--follow", "--no-color", "--name-status", "-M", "--format=%x01%H%x00%cI%x00%s", "--", input.path]);
28913
+ const log = git4(["log", "--follow", "--no-color", "--name-status", "-M", "--format=%x01%H%x00%cI%x00%s", "--", input.path]);
28914
28914
  const commits = parseFileCommits(log).reverse();
28915
28915
  const started = now();
28916
28916
  let added = null;
@@ -28919,7 +28919,7 @@ function readTestHistory(input) {
28919
28919
  if (now() - started > WALK_BUDGET_MS) return { available: false };
28920
28920
  let text3;
28921
28921
  try {
28922
- text3 = git3(["show", `${commit2.sha}:${commit2.pathThen}`]);
28922
+ text3 = git4(["show", `${commit2.sha}:${commit2.pathThen}`]);
28923
28923
  } catch {
28924
28924
  continue;
28925
28925
  }
@@ -28929,7 +28929,7 @@ function readTestHistory(input) {
28929
28929
  }
28930
28930
  }
28931
28931
  if (!added || added.date === "" || added.date.length > MAX_HISTORY_DATE_CHARS) return { available: false };
28932
- const changed = git3(["show", "--name-only", "--no-color", "--format=", added.sha]).split("\n").map((line2) => line2.trim()).filter((line2) => line2 !== "");
28932
+ const changed = git4(["show", "--name-only", "--no-color", "--format=", added.sha]).split("\n").map((line2) => line2.trim()).filter((line2) => line2 !== "");
28933
28933
  const others = changed.filter((file) => file !== input.path && file !== added.pathThen && file.length <= MAX_HISTORY_PATH_CHARS && !isTest(file));
28934
28934
  return {
28935
28935
  available: true,
@@ -35415,13 +35415,13 @@ function titlePattern(title) {
35415
35415
  return { source: source + escapeRegExp2(title.slice(at2)), placeholders };
35416
35416
  }
35417
35417
  function nameEndsWithTitle(name2, title, place) {
35418
- const tail = rowSuffixApplies(place) ? `(?:${ROW_SUFFIX})?` : "";
35419
- return new RegExp(`(?:^|(?: > | \u203A | ))${titlePattern(title).source}${tail}$`, "s").test(name2);
35418
+ const tail2 = rowSuffixApplies(place) ? `(?:${ROW_SUFFIX})?` : "";
35419
+ return new RegExp(`(?:^|(?: > | \u203A | ))${titlePattern(title).source}${tail2}$`, "s").test(name2);
35420
35420
  }
35421
35421
  function rowPattern(test, place) {
35422
35422
  const parts2 = [...test.describes, test.title].map((s) => titlePattern(s).source);
35423
- const tail = rowSuffixApplies(place) ? `(?:${ROW_SUFFIX})?` : "";
35424
- return new RegExp(`^(?:${parts2.join("(?: > | \u203A | )")}|${parts2[parts2.length - 1]})${tail}$`, "s");
35423
+ const tail2 = rowSuffixApplies(place) ? `(?:${ROW_SUFFIX})?` : "";
35424
+ return new RegExp(`^(?:${parts2.join("(?: > | \u203A | )")}|${parts2[parts2.length - 1]})${tail2}$`, "s");
35425
35425
  }
35426
35426
  var TEST_ROOTS = /* @__PURE__ */ new Set(["it", "test"]);
35427
35427
  var X_ROOTS = /* @__PURE__ */ new Set(["xit", "xtest"]);
@@ -38176,6 +38176,36 @@ function prepareFindDefinition(args2, env2) {
38176
38176
  }
38177
38177
 
38178
38178
  // src/targetingTools.ts
38179
+ var RESULT_MESSAGE_LIMIT = 500;
38180
+ var RESULT_REASON_LIMIT = 200;
38181
+ function cutText(text3, max, ellipsis) {
38182
+ const room = ellipsis ? max - 1 : max;
38183
+ let end = room;
38184
+ const last = text3.charCodeAt(end - 1);
38185
+ if (last >= 55296 && last <= 56319) end -= 1;
38186
+ return `${text3.slice(0, end)}${ellipsis ? "\u2026" : ""}`;
38187
+ }
38188
+ function fitResult(result) {
38189
+ const cutMessage = typeof result.message === "string" && result.message.length > RESULT_MESSAGE_LIMIT;
38190
+ const cutReason = typeof result.reason === "string" && result.reason.length > RESULT_REASON_LIMIT;
38191
+ if (!cutMessage && !cutReason) return { result, cutMessage: false, cutReason: false };
38192
+ return {
38193
+ result: {
38194
+ ...result,
38195
+ ...cutMessage ? { message: cutText(result.message, RESULT_MESSAGE_LIMIT, true) } : {},
38196
+ ...cutReason ? { reason: cutText(result.reason, RESULT_REASON_LIMIT, false) } : {}
38197
+ },
38198
+ cutMessage,
38199
+ cutReason
38200
+ };
38201
+ }
38202
+ function fitResults(results) {
38203
+ const fitted = results.map(fitResult);
38204
+ const messages = fitted.filter((f) => f.cutMessage).length;
38205
+ const reasons = fitted.filter((f) => f.cutReason).length;
38206
+ if (messages === 0 && reasons === 0) return { results, messages: 0, reasons: 0 };
38207
+ return { results: fitted.map((f) => f.result), messages, reasons };
38208
+ }
38179
38209
  var DEFAULT_LIMITS = {
38180
38210
  maxTurns: 12,
38181
38211
  maxToolCalls: 25,
@@ -38750,9 +38780,15 @@ var REJECT_MESSAGES = {
38750
38780
  generated_test: "That test is written once and run for each row of a table (describe.each or it.each), and its rows were not found in the test run made before your change, so it cannot be checked. Do not report it again: answer CANNOT_COMPLETE, and in your summary name the test and the case it contradicts. A person will change it."
38751
38781
  };
38752
38782
  var OTHER_LANGUAGE_EXPECTATIONS = "In this language only literal values (text, numbers, true/false), assertion statements, comments and the test's name may differ from find; everything else the test does must stay as it is.";
38753
- function titlesHint(tests) {
38754
- const shown = tests.slice(0, 12).map((t) => `"${t.title.length > 60 ? `${t.title.slice(0, 59)}\u2026` : t.title}"`);
38755
- return shown.length === 0 ? "none" : `${shown.join(", ")}${tests.length > 12 ? ", ..." : ""}`;
38783
+ var NOT_FOUND_LEAD = "The tests in that file are: ";
38784
+ var NOT_FOUND_TAIL = ". The title is the name of the test function.";
38785
+ function titlesHint(tests, room = Number.POSITIVE_INFINITY) {
38786
+ const quoted2 = tests.slice(0, 12).map((t) => `"${t.title.length > 60 ? `${t.title.slice(0, 59)}\u2026` : t.title}"`);
38787
+ if (quoted2.length === 0) return "none";
38788
+ const text3 = (xs) => `${xs.join(", ")}${tests.length > xs.length ? ", ..." : ""}`;
38789
+ let shown = quoted2;
38790
+ while (text3(shown).length > room && shown.length > 1) shown = shown.slice(0, -1);
38791
+ return text3(shown).length <= room ? text3(shown) : null;
38756
38792
  }
38757
38793
  var APPROVED_AGAIN_HINT = "A person approved a change to that test and it is already in the file. If another row of it still expects the old behaviour, finish your code first: if rows of that test still fail in the final test run, the fix step can report it once more.";
38758
38794
  var RECORDED_MESSAGE = "Recorded. This run will now stop before any code is delivered, and a person will decide about this test. Finish your answer; there is nothing more to do for this test.";
@@ -38998,7 +39034,9 @@ var TestConflictTool = class {
38998
39034
  const other = langOfPath(served.path) !== null;
38999
39035
  const matches = allTests(located).map((t, index2) => ({ t, index: index2 })).filter(({ t }) => t.title === r.testTitle);
39000
39036
  if (matches.length === 0) {
39001
- return this.reject("title_not_found", other ? `The tests in that file are: ${titlesHint(allTests(located))}. The title is the name of the test function.` : void 0);
39037
+ const room = RESULT_MESSAGE_LIMIT - REJECT_MESSAGES.title_not_found.length - 1 - NOT_FOUND_LEAD.length - NOT_FOUND_TAIL.length;
39038
+ const titles = other ? titlesHint(allTests(located), room) : null;
39039
+ return this.reject("title_not_found", titles !== null ? `${NOT_FOUND_LEAD}${titles}${NOT_FOUND_TAIL}` : void 0);
39002
39040
  }
39003
39041
  if (matches.length > 1) return this.reject("title_not_unique");
39004
39042
  const { t: test, index } = matches[0];
@@ -39343,7 +39381,7 @@ function parseProposalMessage(message) {
39343
39381
  return out2;
39344
39382
  }
39345
39383
  function createProposalCommit(input) {
39346
- const git3 = input.git ?? runGit;
39384
+ const git4 = input.git ?? runGit;
39347
39385
  const cwd = input.cwd;
39348
39386
  const { files, dropped } = buildProposalFiles(input.conflicts);
39349
39387
  if (files.length === 0) return null;
@@ -39352,18 +39390,18 @@ function createProposalCommit(input) {
39352
39390
  const dir = (0, import_node_fs4.mkdtempSync)((0, import_node_path6.join)((0, import_node_os.tmpdir)(), "qp-proposal-"));
39353
39391
  try {
39354
39392
  const env2 = { GIT_INDEX_FILE: (0, import_node_path6.join)(dir, "index"), ...BOT_ENV };
39355
- const head = git3(["rev-parse", "HEAD"], { cwd }).trim();
39356
- git3(["read-tree", head], { env: env2, cwd });
39393
+ const head = git4(["rev-parse", "HEAD"], { cwd }).trim();
39394
+ git4(["read-tree", head], { env: env2, cwd });
39357
39395
  for (const f of files) {
39358
- const tree = git3(["ls-tree", head, "--", f.path], { cwd }).trim();
39396
+ const tree = git4(["ls-tree", head, "--", f.path], { cwd }).trim();
39359
39397
  const mode = /^(\d{6}) blob /.exec(tree)?.[1];
39360
39398
  if (!mode) throw new Error("A file of the proposal is not in the tip of the target branch.");
39361
- const blob = git3(["hash-object", "-w", "--stdin"], { input: Buffer.from(fileText(f.newLf, f.ending, f.bom), "utf8"), cwd }).trim();
39362
- git3(["update-index", "--cacheinfo", `${mode},${blob},${f.path}`], { env: env2, cwd });
39399
+ const blob = git4(["hash-object", "-w", "--stdin"], { input: Buffer.from(fileText(f.newLf, f.ending, f.bom), "utf8"), cwd }).trim();
39400
+ git4(["update-index", "--cacheinfo", `${mode},${blob},${f.path}`], { env: env2, cwd });
39363
39401
  }
39364
- const treeSha = git3(["write-tree"], { env: env2, cwd }).trim();
39365
- const sha2 = git3(["commit-tree", treeSha, "-p", head, "-F", "-"], { input: buildProposalMessage({ issueKey: input.issueKey, lines }), env: env2, cwd }).trim();
39366
- git3(["update-ref", `refs/heads/${input.branch}`, sha2], { cwd });
39402
+ const treeSha = git4(["write-tree"], { env: env2, cwd }).trim();
39403
+ const sha2 = git4(["commit-tree", treeSha, "-p", head, "-F", "-"], { input: buildProposalMessage({ issueKey: input.issueKey, lines }), env: env2, cwd }).trim();
39404
+ git4(["update-ref", `refs/heads/${input.branch}`, sha2], { cwd });
39367
39405
  return { sha: sha2, branch: input.branch, files, lines, dropped, ...setupFor.some((s) => s !== void 0) ? { setupFor } : {} };
39368
39406
  } finally {
39369
39407
  (0, import_node_fs4.rmSync)(dir, { recursive: true, force: true });
@@ -39411,7 +39449,7 @@ var SHA2 = /^[0-9a-f]{40}$/;
39411
39449
  var REF = "refs/quikpilot/proposal";
39412
39450
  var stripBom = (s) => s.charCodeAt(0) === 65279 ? s.slice(1) : s;
39413
39451
  function loadApprovedTests(input) {
39414
- const git3 = input.git ?? runGit;
39452
+ const git4 = input.git ?? runGit;
39415
39453
  const cwd = input.cwd;
39416
39454
  const log = input.log ?? (() => void 0);
39417
39455
  const warnings = [];
@@ -39424,10 +39462,10 @@ function loadApprovedTests(input) {
39424
39462
  if (!BRANCH.test(branch) || !SHA2.test(sha2) || decision !== "TEST_CHANGED" && decision !== "TEST_RIGHT") return drop("the proposal is not named properly", "bad_change");
39425
39463
  let lines;
39426
39464
  try {
39427
- const shallow = git3(["rev-parse", "--is-shallow-repository"], { cwd }).trim() === "true";
39428
- git3(["fetch", "--no-tags", ...shallow ? ["--depth=2"] : [], "origin", `+refs/heads/${branch}:${REF}`], { cwd });
39429
- if (git3(["rev-parse", REF], { cwd }).trim() !== sha2) return drop("the proposal branch has moved since it was shown", "moved");
39430
- lines = parseProposalMessage(git3(["log", "-1", "--format=%B", sha2], { cwd }));
39465
+ const shallow = git4(["rev-parse", "--is-shallow-repository"], { cwd }).trim() === "true";
39466
+ git4(["fetch", "--no-tags", ...shallow ? ["--depth=2"] : [], "origin", `+refs/heads/${branch}:${REF}`], { cwd });
39467
+ if (git4(["rev-parse", REF], { cwd }).trim() !== sha2) return drop("the proposal branch has moved since it was shown", "moved");
39468
+ lines = parseProposalMessage(git4(["log", "-1", "--format=%B", sha2], { cwd }));
39431
39469
  } catch {
39432
39470
  return drop("the proposal could not be fetched", "fetch_failed");
39433
39471
  }
@@ -39435,7 +39473,7 @@ function loadApprovedTests(input) {
39435
39473
  const paths = [...new Set(lines.map((l) => l.path))];
39436
39474
  let changed;
39437
39475
  try {
39438
- changed = git3(["diff-tree", "--no-commit-id", "--name-only", "-r", sha2], { cwd }).split("\n").map((l) => l.trim()).filter(Boolean);
39476
+ changed = git4(["diff-tree", "--no-commit-id", "--name-only", "-r", sha2], { cwd }).split("\n").map((l) => l.trim()).filter(Boolean);
39439
39477
  } catch {
39440
39478
  return drop("the proposal could not be read", "read_failed");
39441
39479
  }
@@ -39459,8 +39497,8 @@ function loadApprovedTests(input) {
39459
39497
  let proposed;
39460
39498
  let base;
39461
39499
  try {
39462
- proposed = git3(["show", `${sha2}:${path}`], { cwd });
39463
- base = git3(["show", `${sha2}^:${path}`], { cwd });
39500
+ proposed = git4(["show", `${sha2}:${path}`], { cwd });
39501
+ base = git4(["show", `${sha2}^:${path}`], { cwd });
39464
39502
  } catch {
39465
39503
  warnings.push(`The proposed change to ${path} could not be read, so it was not applied.`);
39466
39504
  continue;
@@ -40051,17 +40089,17 @@ function runShellCaptured(command, opts) {
40051
40089
  let settled = false;
40052
40090
  let timedOut = false;
40053
40091
  let graceTimer;
40054
- let tail = Buffer.alloc(0);
40092
+ let tail2 = Buffer.alloc(0);
40055
40093
  const keep = (chunk) => {
40056
- tail = tail.length === 0 ? chunk : Buffer.concat([tail, chunk]);
40057
- if (tail.length > opts.maxTailBytes * 2) tail = tail.subarray(tail.length - opts.maxTailBytes);
40094
+ tail2 = tail2.length === 0 ? chunk : Buffer.concat([tail2, chunk]);
40095
+ if (tail2.length > opts.maxTailBytes * 2) tail2 = tail2.subarray(tail2.length - opts.maxTailBytes);
40058
40096
  };
40059
40097
  const finish = (exitCode, started) => {
40060
40098
  if (settled) return;
40061
40099
  settled = true;
40062
40100
  clearTimeout(timer);
40063
40101
  if (graceTimer) clearTimeout(graceTimer);
40064
- const kept = tail.length > opts.maxTailBytes ? tail.subarray(tail.length - opts.maxTailBytes) : tail;
40102
+ const kept = tail2.length > opts.maxTailBytes ? tail2.subarray(tail2.length - opts.maxTailBytes) : tail2;
40065
40103
  resolve6({ output: kept.toString("utf8"), exitCode, timedOut, started });
40066
40104
  };
40067
40105
  const child = (0, import_node_child_process5.spawn)(command, {
@@ -42530,9 +42568,8 @@ function moreFailSentence(before, now) {
42530
42568
  var HARNESS_TESTS_FAILED = "Some tests failed. output lists their names, regressions first: a regression passed before your change. For a test you wrote in this run, messages gives the whole failure: what was expected and what was received.";
42531
42569
  var TESTS_FAILED_ONLY_OLD = "Some tests failed, and every one of them was already failing before your change. No test that passed before your change fails now, and no test that is new in this run fails.";
42532
42570
  var HARNESS_TESTS_FAILED_NO_OLD_TEST_BROKE = "Some tests failed. No test that passed before your change fails now: the failures counted in newFailures are tests that were not in the test run before your change. For a test you wrote in this run, messages gives the whole failure: what was expected and what was received.";
42533
- var MAX_RESULT_MESSAGE_CHARS = 500;
42534
42571
  function withRelatedNote(message, related) {
42535
- return related && message.length + 1 + RELATED_SENTENCE.length <= MAX_RESULT_MESSAGE_CHARS ? `${message} ${RELATED_SENTENCE}` : message;
42572
+ return related && message.length + 1 + RELATED_SENTENCE.length <= RESULT_MESSAGE_LIMIT ? `${message} ${RELATED_SENTENCE}` : message;
42536
42573
  }
42537
42574
  var sha = (s) => (0, import_node_crypto3.createHash)("sha256").update(s).digest("hex");
42538
42575
  var LOCATION_SUFFIX = / \[at [^\]\r\n]{1,70}\]$/;
@@ -43497,7 +43534,7 @@ var GUIDANCE_NAMES = ["AGENTS.md", "CLAUDE.md", "README.md"];
43497
43534
  var GUIDANCE_TEXT_CHARS = 2e3;
43498
43535
  var GUIDANCE_PER_RUN = 6;
43499
43536
  var LOOK_TOOLS = /* @__PURE__ */ new Set(["list_files", "read_file", "grep", "find_definition"]);
43500
- function cutText(text3, max) {
43537
+ function cutText2(text3, max) {
43501
43538
  if (text3.length <= max) return text3;
43502
43539
  let out2 = text3.slice(0, max);
43503
43540
  const last = out2.charCodeAt(out2.length - 1);
@@ -43507,7 +43544,7 @@ function cutText(text3, max) {
43507
43544
  function keepNotes(kept, reply, scrub) {
43508
43545
  if (typeof reply !== "string") return kept;
43509
43546
  const cleaned = (scrub ? scrub(reply) : reply).trim();
43510
- return cutText(cleaned, NOTES_KEPT_CHARS).trim();
43547
+ return cutText2(cleaned, NOTES_KEPT_CHARS).trim();
43511
43548
  }
43512
43549
  function buildRecap(i3) {
43513
43550
  const cases = [];
@@ -43519,8 +43556,8 @@ function buildRecap(i3) {
43519
43556
  const { automationId, title } = entry;
43520
43557
  if (typeof automationId !== "string" || automationId.length === 0) continue;
43521
43558
  cases.push({
43522
- automationId: cutText(automationId, MAX_RECAP_ID_CHARS),
43523
- title: typeof title === "string" ? cutText(title, MAX_RECAP_TITLE_CHARS) : ""
43559
+ automationId: cutText2(automationId, MAX_RECAP_ID_CHARS),
43560
+ title: typeof title === "string" ? cutText2(title, MAX_RECAP_TITLE_CHARS) : ""
43524
43561
  });
43525
43562
  }
43526
43563
  }
@@ -43532,7 +43569,7 @@ function argOf(args2, key) {
43532
43569
  }
43533
43570
  function textArg(args2, key, max) {
43534
43571
  const v = argOf(args2, key);
43535
- return typeof v === "string" ? cutText(v.replace(/\s+/g, " ").trim(), max) : "";
43572
+ return typeof v === "string" ? cutText2(v.replace(/\s+/g, " ").trim(), max) : "";
43536
43573
  }
43537
43574
  function stubNoteFor(call) {
43538
43575
  let note;
@@ -43554,7 +43591,7 @@ function stubNoteFor(call) {
43554
43591
  } else {
43555
43592
  note = call.name;
43556
43593
  }
43557
- return cutText(note, MAX_STUB_NOTE_CHARS);
43594
+ return cutText2(note, MAX_STUB_NOTE_CHARS);
43558
43595
  }
43559
43596
  function isStubbed(output) {
43560
43597
  return typeof output === "object" && output !== null && output.dropped === true;
@@ -43613,7 +43650,7 @@ function makeGuidanceFinder(i3) {
43613
43650
  const raw = i3.readText(candidate);
43614
43651
  given.add(candidate);
43615
43652
  if (raw === null) continue;
43616
- const text3 = cutText((i3.scrub ? i3.scrub(raw) : raw).trim(), GUIDANCE_TEXT_CHARS);
43653
+ const text3 = cutText2((i3.scrub ? i3.scrub(raw) : raw).trim(), GUIDANCE_TEXT_CHARS);
43617
43654
  if (text3.length === 0) continue;
43618
43655
  done.add(folder);
43619
43656
  count3 += 1;
@@ -47179,9 +47216,9 @@ function fitBlocks(blocks, paths, room) {
47179
47216
  let used = 0;
47180
47217
  for (let i3 = 0; i3 < blocks.length; i3++) {
47181
47218
  const block = blocks[i3];
47182
- const tail = i3 + 1 < blocks.length ? note(i3 + 1) : "";
47219
+ const tail2 = i3 + 1 < blocks.length ? note(i3 + 1) : "";
47183
47220
  const sep = kept.length > 0 ? 1 : 0;
47184
- if (used + sep + block.length + (tail ? tail.length + 1 : 0) <= room) {
47221
+ if (used + sep + block.length + (tail2 ? tail2.length + 1 : 0) <= room) {
47185
47222
  kept.push(block);
47186
47223
  used += sep + block.length;
47187
47224
  continue;
@@ -48077,10 +48114,10 @@ async function proveProposals(input) {
48077
48114
  const { files, dropped } = buildProposalFiles(input.conflicts);
48078
48115
  for (const c of dropped) evidence.set(keyOf2(c), { newCode: "not_checked" });
48079
48116
  const notChecked = () => {
48080
- for (const f of files) for (const c of f.conflicts) evidence.set(keyOf2(c), { newCode: "not_checked", ...endOf(f, c) });
48117
+ for (const f of files) for (const c of f.conflicts) evidence.set(keyOf2(c), { newCode: "not_checked", ...endOf2(f, c) });
48081
48118
  return { ran: false, evidence, stillFailing: [], unexplained: [] };
48082
48119
  };
48083
- const endOf = (f, c) => {
48120
+ const endOf2 = (f, c) => {
48084
48121
  const line2 = newEndLineOf(f, c);
48085
48122
  return line2 === void 0 ? {} : { newEndLine: line2 };
48086
48123
  };
@@ -48101,7 +48138,7 @@ async function proveProposals(input) {
48101
48138
  const failing = answer.failingTests.filter((id) => proposalNameIs(id, f, c));
48102
48139
  for (const id of failing) covered.add(id);
48103
48140
  const newCode = failing.length > 0 ? "fails" : answer.truncated ? "not_checked" : "passes";
48104
- evidence.set(keyOf2(c), { newCode, ...endOf(f, c) });
48141
+ evidence.set(keyOf2(c), { newCode, ...endOf2(f, c) });
48105
48142
  if (newCode === "fails") stillFailing.push(c);
48106
48143
  }
48107
48144
  }
@@ -48612,6 +48649,318 @@ function reviewAnswer(lines) {
48612
48649
  return { rules: ["done_rule"], violations: [...lines.slice(0, MAX_REVIEW_CASES), REVIEW_CLOSING], message: REVIEW_MESSAGE };
48613
48650
  }
48614
48651
 
48652
+ // src/dataPathCheck.ts
48653
+ var import_node_child_process9 = require("node:child_process");
48654
+ var import_node_fs17 = require("node:fs");
48655
+ var import_node_path20 = require("node:path");
48656
+
48657
+ // src/scopeCheck.ts
48658
+ var import_node_fs16 = require("node:fs");
48659
+ var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
48660
+ var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
48661
+ var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
48662
+ var CALL_LINE_RE = /fetch\s*\(|\baxios\b|(?:\$|\bjQuery)\.(?:ajax|get|post|getJSON)\s*\(|\bXMLHttpRequest\b|\.open\(\s*["'`](?:GET|POST|PUT|PATCH|DELETE)["'`]|\bhttp\.(?:get|post|put|patch|delete|head|request|postform|newrequest|newrequestwithcontext)\s*\(|\b(?:requests|httpx)\.(?:get|post|put|patch|delete|head|request)\s*\(|\bHttpRequest\.newBuilder\b|\bcurl\b/i;
48663
+ var NO_PATH = "(this file's route)";
48664
+ function detectMentions(text3) {
48665
+ const found = [];
48666
+ for (const line2 of text3.split("\n")) {
48667
+ const methodMatch = ROUTE_METHOD_RE.exec(line2);
48668
+ const pathMatch = ROUTE_PATH_RE.exec(line2);
48669
+ if (methodMatch && pathMatch && !CALL_LINE_RE.test(line2)) {
48670
+ found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0].replace(/:+$/, "") });
48671
+ }
48672
+ const exportMatch = ROUTE_EXPORT_RE.exec(line2);
48673
+ if (exportMatch) {
48674
+ found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
48675
+ }
48676
+ }
48677
+ return found;
48678
+ }
48679
+ function normalizePath(path) {
48680
+ return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
48681
+ }
48682
+ function surfaceCovers(surface, mention) {
48683
+ if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
48684
+ if (mention.path === NO_PATH) return true;
48685
+ const declaredPath = normalizePath(surface);
48686
+ const mentionPath = normalizePath(mention.path);
48687
+ return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
48688
+ }
48689
+ function addedLines(before, after) {
48690
+ const beforeLines = new Set(before.split("\n"));
48691
+ return after.split("\n").filter((line2) => !beforeLines.has(line2)).join("\n");
48692
+ }
48693
+ function checkApiScope(results, targets, apiChanges, existing) {
48694
+ const targetsByPath = new Map(targets.map((t) => [t.path, t]));
48695
+ const violations = [];
48696
+ for (const { targetPath, newContent } of results) {
48697
+ if (isTestFile(targetPath)) continue;
48698
+ const target = targetsByPath.get(targetPath);
48699
+ const isNewFile = target?.kind === "NEW_FILE";
48700
+ let scanned;
48701
+ if (isNewFile) {
48702
+ scanned = newContent;
48703
+ } else {
48704
+ let currentContent;
48705
+ try {
48706
+ currentContent = (0, import_node_fs16.readFileSync)(targetPath, "utf8");
48707
+ } catch {
48708
+ currentContent = "";
48709
+ }
48710
+ scanned = addedLines(currentContent, newContent);
48711
+ }
48712
+ for (const mention of detectMentions(scanned)) {
48713
+ if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
48714
+ if (existing && mention.path !== NO_PATH && existing.has(mention)) continue;
48715
+ violations.push({ file: targetPath, method: mention.method, path: mention.path });
48716
+ }
48717
+ }
48718
+ }
48719
+ return { blocked: violations.length > 0, violations };
48720
+ }
48721
+ function describeScopeViolations(check) {
48722
+ return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
48723
+ }
48724
+
48725
+ // src/dataPathCheck.ts
48726
+ var SOURCE_PATHSPECS = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
48727
+ var SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
48728
+ var UI_FILE = /\.(?:tsx|jsx|vue|svelte|html?)$/i;
48729
+ var MAX_CANDIDATES = 80;
48730
+ var MAX_LOADING_FILES = 60;
48731
+ var MAX_SECOND_HOP = 12;
48732
+ var SCAN_BUDGET_MS = 8e3;
48733
+ var MAX_FILE_CHARS2 = 3e5;
48734
+ var MAX_LISTING = 3e4;
48735
+ var GIT_TIMEOUT_MS2 = 1e4;
48736
+ var GIT_MAX_BUFFER3 = 2e7;
48737
+ function routeSegment(seg) {
48738
+ if (/^\(.*\)$/.test(seg) || seg.startsWith("@")) return null;
48739
+ if (/^\[\[?\.\.\..*\]\]?$/.test(seg)) return "**";
48740
+ if (/^\[.*\]$/.test(seg)) return "*";
48741
+ return seg;
48742
+ }
48743
+ function routeAddressOf(file) {
48744
+ const segs = file.replace(/\\/g, "/").split("/");
48745
+ const last = segs[segs.length - 1] ?? "";
48746
+ const appAt = segs.indexOf("app");
48747
+ if (appAt >= 0 && /^route\.[cm]?[jt]sx?$/.test(last)) {
48748
+ const parts2 = segs.slice(appAt + 1, -1).map(routeSegment).filter((s) => s !== null);
48749
+ return `/${parts2.join("/")}`;
48750
+ }
48751
+ const pagesAt = segs.indexOf("pages");
48752
+ if (pagesAt >= 0 && segs[pagesAt + 1] === "api" && SOURCE_FILE.test(last)) {
48753
+ const name2 = last.replace(/\.[cm]?[jt]sx?$/, "");
48754
+ const parts2 = [...segs.slice(pagesAt + 1, -1), ...name2 === "index" ? [] : [name2]].map(routeSegment).filter((s) => s !== null);
48755
+ return `/${parts2.join("/")}`;
48756
+ }
48757
+ return null;
48758
+ }
48759
+ var LITERAL_RE = /[`'"]((?:\$\{[^}]*\})?\/[^`'"\s?#]*)/g;
48760
+ var API_LITERAL = /^(?:\$\{[^}]*\})?\/api\//;
48761
+ function literalsOf(line2) {
48762
+ return [...line2.matchAll(LITERAL_RE)].map((m) => m[1]);
48763
+ }
48764
+ function toAddress(raw) {
48765
+ const address = normalizePath(raw.replace(/\$\{[^}]*\}/g, "*")).replace(/\/+$/, "");
48766
+ if (address.startsWith("//")) return null;
48767
+ const segs = address.split("/").filter((s) => s !== "");
48768
+ return segs.some((s) => s !== "*") ? address : null;
48769
+ }
48770
+ function callAddressesIn(text3) {
48771
+ const lines = text3.split("\n");
48772
+ const found = [];
48773
+ const add2 = (raw) => {
48774
+ const a = raw === void 0 ? null : toAddress(raw);
48775
+ if (a !== null && !found.includes(a)) found.push(a);
48776
+ };
48777
+ for (let i3 = 0; i3 < lines.length; i3++) {
48778
+ const lits = literalsOf(lines[i3]);
48779
+ if (CALL_LINE_RE.test(lines[i3])) {
48780
+ let first = lits[0];
48781
+ for (let j = i3 + 1; first === void 0 && j <= i3 + 2 && j < lines.length; j++) first = literalsOf(lines[j])[0];
48782
+ add2(first);
48783
+ }
48784
+ for (const lit of lits) if (API_LITERAL.test(lit)) add2(lit);
48785
+ }
48786
+ return found;
48787
+ }
48788
+ function addressMatches(route, call) {
48789
+ const r = route.split("/").filter((s) => s !== "");
48790
+ const c = call.split("/").filter((s) => s !== "");
48791
+ const same = (a, b) => a === b || a === "*" || b === "*";
48792
+ const wide = r.indexOf("**");
48793
+ if (wide >= 0) return c.length >= wide && r.slice(0, wide).every((s, i3) => same(s, c[i3]));
48794
+ if (c.length > r.length) return false;
48795
+ const tail2 = r.slice(r.length - c.length);
48796
+ return c.every((s, i3) => same(tail2[i3], s));
48797
+ }
48798
+ var git3 = (cwd, args2) => {
48799
+ try {
48800
+ return (0, import_node_child_process9.execFileSync)("git", args2, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48801
+ } catch {
48802
+ return "";
48803
+ }
48804
+ };
48805
+ function lastSegment(spec) {
48806
+ const segs = spec.split("/").filter((s) => s !== "" && s !== "." && s !== "..");
48807
+ let name2 = segs.pop() ?? "";
48808
+ if (/^index(?:\.[cm]?[jt]sx?)?$/.test(name2)) name2 = segs.pop() ?? "";
48809
+ return name2.replace(/\.[cm]?[jt]sx?$/, "");
48810
+ }
48811
+ function baseOf(path) {
48812
+ return lastSegment(path);
48813
+ }
48814
+ var GENERIC_BASES = /* @__PURE__ */ new Set(["index", "page", "layout", "route", "main", "app", "utils", "util", "types", "type", "constants", "config", "client", "server", "loading", "error", "default"]);
48815
+ var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48816
+ function graph(cwd, read, skip, expired) {
48817
+ const listing = git3(cwd, ["ls-files"]).split("\n").filter((p) => SOURCE_FILE.test(p));
48818
+ const byBase = /* @__PURE__ */ new Map();
48819
+ if (listing.length <= MAX_LISTING) {
48820
+ for (const p of listing) {
48821
+ const base = baseOf(p);
48822
+ if (base === "") continue;
48823
+ const held = byBase.get(base);
48824
+ if (held) held.push(p);
48825
+ else byBase.set(base, [p]);
48826
+ }
48827
+ }
48828
+ const text3 = (p) => {
48829
+ const t = read(p);
48830
+ return t !== null && t.length <= MAX_FILE_CHARS2 ? t : null;
48831
+ };
48832
+ const specifiers = (p) => {
48833
+ const t = supportsImportScan(p) ? text3(p) : null;
48834
+ return t === null ? [] : extractImportSpecifiers(t);
48835
+ };
48836
+ return {
48837
+ importersOf(file) {
48838
+ const base = baseOf(file);
48839
+ if (base.length < 3 || GENERIC_BASES.has(base) || expired()) return [];
48840
+ const pattern = `['"/]${escapeRegex(base)}(/index)?(\\.[cm]?[jt]sx?)?['"]`;
48841
+ const hits = git3(cwd, ["grep", "-l", "-I", "-E", "-e", pattern, "--", ...SOURCE_PATHSPECS]).split("\n").filter((p) => p !== "" && p !== file && !skip(p));
48842
+ return hits.slice(0, MAX_CANDIDATES).filter((p) => !expired() && specifiers(p).some((s) => lastSegment(s) === base));
48843
+ },
48844
+ importsOf(file) {
48845
+ const out2 = [];
48846
+ for (const s of specifiers(file)) {
48847
+ if (!s.startsWith(".") && !s.startsWith("@/") && !s.startsWith("~/")) continue;
48848
+ for (const p of (byBase.get(lastSegment(s)) ?? []).slice(0, 6)) if (p !== file && !skip(p) && !out2.includes(p)) out2.push(p);
48849
+ }
48850
+ return out2;
48851
+ }
48852
+ };
48853
+ }
48854
+ function loadingFiles(cwd, screens, read, skip, expired) {
48855
+ const g = graph(cwd, read, skip, expired);
48856
+ const files = [];
48857
+ const add2 = (p) => {
48858
+ if (files.length < MAX_LOADING_FILES && !files.includes(p)) files.push(p);
48859
+ };
48860
+ const hop1 = unique2(screens.flatMap((s) => g.importersOf(s)));
48861
+ for (const p of hop1) add2(p);
48862
+ for (const p of hop1.slice(0, MAX_SECOND_HOP).flatMap((f) => g.importersOf(f))) add2(p);
48863
+ for (const s of screens) add2(s);
48864
+ for (const p of [...files].flatMap((f) => expired() ? [] : g.importsOf(f))) add2(p);
48865
+ return files;
48866
+ }
48867
+ function readFromCheckout(root) {
48868
+ return (path) => {
48869
+ try {
48870
+ const abs = (0, import_node_path20.join)(root, path);
48871
+ const st = (0, import_node_fs17.lstatSync)(abs);
48872
+ return st.isSymbolicLink() || !st.isFile() || st.size > MAX_FILE_CHARS2 ? null : (0, import_node_fs17.readFileSync)(abs, "utf8");
48873
+ } catch {
48874
+ return null;
48875
+ }
48876
+ };
48877
+ }
48878
+ var unique2 = (xs) => [...new Set(xs)];
48879
+ var slashed = (p) => p.replace(/\\/g, "/");
48880
+ function plannedChanged(input, changed, kind) {
48881
+ return unique2(input.parts.filter((p) => p.kind === kind).flatMap((p) => p.paths.map(slashed))).filter((p) => changed.has(p) && !input.isTest(p));
48882
+ }
48883
+ var withAddress = (files) => files.flatMap((file) => {
48884
+ const address = routeAddressOf(file);
48885
+ return address === null ? [] : [{ file, address }];
48886
+ });
48887
+ function unplannedRoutes(input, changed) {
48888
+ const planned = new Set(input.parts.flatMap((p) => p.paths.map(slashed)));
48889
+ return withAddress([...changed].sort().filter((f) => !planned.has(f) && !input.isTest(f)));
48890
+ }
48891
+ function callsLoadingScreens(input, screens) {
48892
+ const started = Date.now();
48893
+ const expired = () => Date.now() - started > SCAN_BUDGET_MS;
48894
+ const denied = [...input.deniedPaths];
48895
+ const skip = (p) => input.isTest(p) || matchesDeniedPath(p, denied) !== null || input.readable != null && !input.readable.has(p);
48896
+ const calls = [];
48897
+ const files = loadingFiles(input.cwd, screens, input.read, skip, expired);
48898
+ for (const file of files) {
48899
+ const text3 = input.read(file);
48900
+ if (text3 === null || text3.length > MAX_FILE_CHARS2) continue;
48901
+ for (const call of callAddressesIn(text3)) calls.push({ file, call });
48902
+ }
48903
+ input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
48904
+ return calls;
48905
+ }
48906
+ function dataPathGap(input) {
48907
+ const changed = new Set(input.changed.map(slashed));
48908
+ const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48909
+ const routes = withAddress(plannedChanged(input, changed, "data"));
48910
+ if (screens.length === 0 || routes.length === 0) return null;
48911
+ const calls = callsLoadingScreens(input, screens);
48912
+ if (calls.length === 0) return null;
48913
+ const answering = [...routes, ...unplannedRoutes(input, changed)];
48914
+ if (answering.some((r) => calls.some((c) => addressMatches(r.address, c.call)))) return null;
48915
+ return { screen: screens[0], loader: calls[0].file, call: calls[0].call, routeFile: routes[0].file, route: routes[0].address };
48916
+ }
48917
+ function withoutMovedData(missing, input) {
48918
+ const open = missing.filter((m) => m.why === "unchanged" && m.part.kind === "data" && m.part.database === void 0);
48919
+ if (open.length === 0) return [...missing];
48920
+ const changed = new Set(input.changed.map(slashed));
48921
+ const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48922
+ if (screens.length === 0) return [...missing];
48923
+ const moved = unplannedRoutes(input, changed);
48924
+ if (moved.length === 0) return [...missing];
48925
+ const calls = callsLoadingScreens(input, screens);
48926
+ let excuses = moved.filter((r) => calls.some((c) => addressMatches(r.address, c.call))).length;
48927
+ return missing.filter((m) => {
48928
+ if (excuses > 0 && open.includes(m)) {
48929
+ excuses -= 1;
48930
+ return false;
48931
+ }
48932
+ return true;
48933
+ });
48934
+ }
48935
+ var tail = (path, n) => path.split("/").slice(-n).join("/");
48936
+ var endOf = (s, n) => s.length <= n ? s : `\u2026${s.slice(s.length - (n - 1))}`;
48937
+ function fit(limit, build) {
48938
+ const whole4 = (s) => s;
48939
+ const spellings = [
48940
+ [whole4, whole4],
48941
+ [(p) => tail(p, 2), whole4],
48942
+ [(p) => tail(p, 1), whole4]
48943
+ ];
48944
+ for (const [file, address] of spellings) {
48945
+ const s = build(file, address);
48946
+ if (s.length <= limit) return s;
48947
+ }
48948
+ return build((p) => endOf(tail(p, 1), 22), (a) => endOf(a, 22)).slice(0, limit);
48949
+ }
48950
+ function dataPathSentence(g) {
48951
+ return fit(
48952
+ MAX_REFUSED_SENTENCE_CHARS,
48953
+ (f, a) => `${f(g.screen)} is shown from ${f(g.loader)}, which loads ${a(g.call)}; the data was added in ${f(g.routeFile)} (${a(g.route)}). Add it where ${a(g.call)} is answered too and keep that change, or say why ${a(g.route)} alone is right.`
48954
+ );
48955
+ }
48956
+ var DATA_PATH_MESSAGE = "Your answer was sent back: the data this feature adds may not reach the screen that shows it. The sentence names the screen, where its data is loaded from, and the route that was changed instead. This check is made once.";
48957
+ function dataPathAnswer(g) {
48958
+ return { rules: ["done_rule"], violations: [dataPathSentence(g)], message: DATA_PATH_MESSAGE };
48959
+ }
48960
+ function dataPathWarning(g) {
48961
+ return `QuikPilot could not confirm that the new data reaches the screen: ${g.screen} is shown from ${g.loader}, which loads its data from ${g.call}, but the data was added in ${g.routeFile} (${g.route}). Check that the screen shows it.`.slice(0, 1500);
48962
+ }
48963
+
48615
48964
  // src/databaseChange.ts
48616
48965
  var DATABASE_CHANGE_KEY = "databaseChange";
48617
48966
  var DATABASE_CHANGE_PATH = ".quikpilot/database-change.json";
@@ -49068,7 +49417,9 @@ function partMissingSentence(missing, opts = {}) {
49068
49417
  // src/sameFailureHint.ts
49069
49418
  var MAX_NAMES = 2;
49070
49419
  var MAX_HINT_CHARS = 300;
49420
+ var MIN_NAME_CHARS = 8;
49071
49421
  var SAME_FAILURE_TAIL = " If it should now pass, check the code; if it looks unrelated (say, a 500 from set-up the test lacks), compare its set-up with the tests around it.";
49422
+ var SAME_FAILURE_TAIL_SHORT = " If it should now pass, check the code; if it looks unrelated, compare its set-up with the tests around it.";
49072
49423
  var collapse = (text3) => text3.replace(/\s+/g, " ").trim();
49073
49424
  var line = (text3) => collapse(
49074
49425
  (text3.split("\n").find((l) => l.trim() !== "") ?? "").replace(/\s*\[at [^\]]*\]/g, "")
@@ -49078,21 +49429,47 @@ function titleOf3(id) {
49078
49429
  return collapse(at2 >= 0 ? id.slice(at2 + 2) : id);
49079
49430
  }
49080
49431
  var cut = (text3, max) => text3.length > max ? `${text3.slice(0, Math.max(1, max - 1))}\u2026` : text3;
49081
- function sameFailureHint(before, now) {
49082
- const same = Object.keys(now).filter((id) => {
49432
+ function sameIds(before, now) {
49433
+ return Object.keys(now).filter((id) => {
49083
49434
  const was = line(before[id] ?? "");
49084
49435
  return was !== "" && was === line(now[id] ?? "");
49085
49436
  });
49086
- if (same.length === 0) return null;
49087
- const rest = same.length - Math.min(MAX_NAMES, same.length);
49437
+ }
49438
+ function sameFailureCount(before, now) {
49439
+ return sameIds(before, now).length;
49440
+ }
49441
+ function render(same, shown, tail2, maxChars, whole4) {
49442
+ const names = same.slice(0, shown);
49443
+ const rest = same.length - names.length;
49088
49444
  const more = rest > 0 ? ` and ${rest} more` : "";
49089
49445
  const head = "Your change has not changed how ";
49090
- const end = ` fails (same message as before).${SAME_FAILURE_TAIL}`;
49091
- const shown = same.slice(0, MAX_NAMES);
49092
- const room = MAX_HINT_CHARS - head.length - end.length - more.length - shown.length * 2 - (shown.length - 1) * 2;
49093
- const each = Math.max(8, Math.floor(room / shown.length));
49094
- const names = shown.map((id) => `"${cut(titleOf3(id), each)}"`).join(", ");
49095
- return `${head}${names}${more}${end}`;
49446
+ const end = ` fails (same message as before).${tail2}`;
49447
+ const room = maxChars - head.length - end.length - more.length - names.length * 2 - (names.length - 1) * 2;
49448
+ const each = Math.floor(room / names.length);
49449
+ if (each < MIN_NAME_CHARS) return null;
49450
+ if (whole4 && names.some((id) => titleOf3(id).length > each)) return null;
49451
+ const text3 = `${head}${names.map((id) => `"${cut(titleOf3(id), each)}"`).join(", ")}${more}${end}`;
49452
+ return text3.length <= maxChars ? text3 : null;
49453
+ }
49454
+ function sameFailureHint(before, now, maxChars = MAX_HINT_CHARS) {
49455
+ const same = sameIds(before, now);
49456
+ if (same.length === 0) return null;
49457
+ const many = Math.min(MAX_NAMES, same.length);
49458
+ const forms = [];
49459
+ for (const shown of many > 1 ? [many, 1] : [1]) for (const tail2 of [SAME_FAILURE_TAIL, SAME_FAILURE_TAIL_SHORT]) forms.push([shown, tail2]);
49460
+ for (const whole4 of [true, false]) {
49461
+ for (const [shown, tail2] of forms) {
49462
+ const text3 = render(same, shown, tail2, maxChars, whole4);
49463
+ if (text3 !== null) return text3;
49464
+ }
49465
+ }
49466
+ return null;
49467
+ }
49468
+ function addSameFailureHint(message, before, now, limit) {
49469
+ const same = sameFailureCount(before, now);
49470
+ if (same === 0) return { message, outcome: "none", same };
49471
+ const hint = sameFailureHint(before, now, Math.min(MAX_HINT_CHARS, limit - message.length - 1));
49472
+ return hint === null ? { message, outcome: "left_out", same } : { message: `${message} ${hint}`.trim(), outcome: "added", same };
49096
49473
  }
49097
49474
 
49098
49475
  // src/codegenLoop.ts
@@ -49366,6 +49743,7 @@ async function runCodegenLoop(args2, deps) {
49366
49743
  let redRefusals = 0;
49367
49744
  let importRefusals = 0;
49368
49745
  let partRefusals = 0;
49746
+ let dataPathRefusals = 0;
49369
49747
  let proofSendBacks = 0;
49370
49748
  let giveUpRefusals = 0;
49371
49749
  let redUnproven;
@@ -49720,7 +50098,8 @@ async function runCodegenLoop(args2, deps) {
49720
50098
  } catch (err2) {
49721
50099
  if (code === "CONTRACT_REJECTED") {
49722
50100
  const said = envelope;
49723
- const text3 = typeof said?.error === "string" ? said.error : typeof said?.normalizedText === "string" ? said.normalizedText : "";
50101
+ const rule = typeof said?.normalizedText === "string" && said.normalizedText.trim() ? said.normalizedText : "";
50102
+ const text3 = rule || (typeof said?.error === "string" ? said.error : "");
49724
50103
  const reason = text3.trim() ? firstLine(scrub(text3), void 0, 300) : "";
49725
50104
  const version2 = contextData.contractVersion;
49726
50105
  log({ event: "codegen.contract_rejected", turn, ...typeof version2 === "string" ? { version: version2 } : {}, ...reason ? { reason } : {} });
@@ -49970,7 +50349,21 @@ async function runCodegenLoop(args2, deps) {
49970
50349
  if (heldParts.length > 0) {
49971
50350
  const proposalIds = databaseOn ? note?.recorded()?.parts ?? [] : void 0;
49972
50351
  const dbLog = databaseOn ? { database: args2.databaseChange.parts.length, proposed: proposalIds.length > 0 } : {};
49973
- const missingParts = missingAtDone(heldParts, overlay.changedPaths(), looksLikeTest, proposalIds);
50352
+ const changedNow = overlay.changedPaths();
50353
+ const checkoutRoot = deps.fs?.rootReal ?? process.cwd();
50354
+ const fromDisk = readFromCheckout(checkoutRoot);
50355
+ const trace = {
50356
+ cwd: checkoutRoot,
50357
+ parts: heldParts,
50358
+ changed: changedNow,
50359
+ read: (path) => overlay.fullText(path) ?? fromDisk(path),
50360
+ isTest: looksLikeTest,
50361
+ deniedPaths: args2.deniedPaths,
50362
+ readable: new Set(args2.readListing ?? args2.listing)
50363
+ };
50364
+ const missingBefore = missingAtDone(heldParts, changedNow, looksLikeTest, proposalIds);
50365
+ const missingParts = withoutMovedData(missingBefore, trace);
50366
+ const moved = missingBefore.length - missingParts.length;
49974
50367
  if (missingParts.length > 0) {
49975
50368
  const ids = missingParts.map((m) => m.part.id);
49976
50369
  if (partRefusals < 1 && !isFinal) {
@@ -49988,7 +50381,26 @@ async function runCodegenLoop(args2, deps) {
49988
50381
  const sentence = partMissingSentence(missingParts);
49989
50382
  throw new CodegenLoopFailure("part_missing", void 0, void 0, sentence, sentence.slice(0, MAX_PREVIOUS_DETAIL_CHARS));
49990
50383
  }
49991
- log({ event: "codegen.parts_check", turn, outcome: "ok", parts: heldParts.length, ...dbLog });
50384
+ log({ event: "codegen.parts_check", turn, outcome: "ok", parts: heldParts.length, ...moved > 0 ? { moved } : {}, ...dbLog });
50385
+ const scanned = {};
50386
+ const dataGap = dataPathGap({
50387
+ onScan: (i3) => Object.assign(scanned, { files: i3.files.length, calls: i3.calls.length, ms: i3.ms }),
50388
+ ...trace
50389
+ });
50390
+ if (dataGap !== null) {
50391
+ if (dataPathRefusals < 1 && !isFinal) {
50392
+ dataPathRefusals += 1;
50393
+ const answer = dataPathAnswer(dataGap);
50394
+ refusedStreak += 1;
50395
+ refusedTurns.push({ turn, rules: answer.rules });
50396
+ log({ event: "codegen.data_path", turn, outcome: "sent", ...scanned });
50397
+ transcript.push({ turn, toolCalls: [], refused: answer });
50398
+ if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
50399
+ forced = settleNextTurn(turn, forced);
50400
+ continue;
50401
+ }
50402
+ log({ event: "codegen.data_path", turn, outcome: "kept", ...scanned });
50403
+ }
49992
50404
  }
49993
50405
  const doneSummary = typeof body2.summary === "string" ? body2.summary.slice(0, MAX_SUMMARY_CHARS) : "";
49994
50406
  const lane = args2.lane;
@@ -50087,8 +50499,9 @@ async function runCodegenLoop(args2, deps) {
50087
50499
  }
50088
50500
  }
50089
50501
  if (featureOn && args2.seedOwnFailures && call.name === RUN_TESTS_TOOL && isTestAnswer(result.output) && result.output.messages) {
50090
- const hint = sameFailureHint(args2.seedOwnFailures, result.output.messages);
50091
- if (hint) result = { ...result, message: `${result.message ?? ""} ${hint}`.trim() };
50502
+ const hinted = addSameFailureHint(result.message ?? "", args2.seedOwnFailures, result.output.messages, RESULT_MESSAGE_LIMIT);
50503
+ if (hinted.outcome !== "none") log({ event: "codegen.same_failure_hint", turn, outcome: hinted.outcome, same: hinted.same });
50504
+ if (hinted.outcome === "added") result = { ...result, message: hinted.message };
50092
50505
  }
50093
50506
  results.push(result);
50094
50507
  if (call.name === "read_file" && isPlainObject3(call.args) && typeof call.args.path === "string" && (result.status === "ok" || result.status === "duplicate")) {
@@ -50127,7 +50540,9 @@ async function runCodegenLoop(args2, deps) {
50127
50540
  }
50128
50541
  if (reasonText) reasoning.push({ turn, text: reasonText });
50129
50542
  transcript.push({ turn, ...reasonText ? { reasoning: reasonText } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });
50130
- toolResults.push(...results);
50543
+ const fitted = fitResults(results);
50544
+ if (fitted.messages > 0 || fitted.reasons > 0) log({ event: "codegen.result_cut", turn, messages: fitted.messages, reasons: fitted.reasons });
50545
+ toolResults.push(...fitted.results);
50131
50546
  refusedStreak = 0;
50132
50547
  if (notesOn) {
50133
50548
  for (const c of calls) {
@@ -50309,13 +50724,17 @@ async function runPhases(i3) {
50309
50724
  ...d1.proposals ? { proposals: d1.proposals } : {}
50310
50725
  };
50311
50726
  }
50727
+ const claimOnly = new Set(i3.claimOnlySource ?? []);
50728
+ const codeLaneTests = i3.testPaths.filter((p) => !claimOnly.has(p));
50729
+ const unfrozen = codeLaneTests.length < i3.testPaths.length ? i3.testPaths.filter((p) => claimOnly.has(p) && !tests.frozen.includes(p)).length : 0;
50312
50730
  i3.log({ event: "codegen.phase_start", attempt: i3.attempt, phase: "code" });
50731
+ if (unfrozen > 0) i3.log({ event: "codegen.claim_only_source", attempt: i3.attempt, files: unfrozen });
50313
50732
  let d2;
50314
50733
  try {
50315
50734
  d2 = await i3.run({
50316
50735
  ...i3.args,
50317
50736
  phase: "code",
50318
- lane: { kind: "code", testPaths: i3.testPaths, frozen: tests.frozen },
50737
+ lane: { kind: "code", testPaths: codeLaneTests, frozen: tests.frozen },
50319
50738
  seed: tests.results,
50320
50739
  ...tests.proposals ? { seedProposals: tests.proposals } : {},
50321
50740
  // QUIKTR-2446 part B: how the run's own tests failed on the code before the change (phase 1's last whole-suite run), for the one thing the
@@ -50351,7 +50770,7 @@ async function runPhases(i3) {
50351
50770
  d3 = await i3.run({
50352
50771
  ...i3.args,
50353
50772
  phase: "code",
50354
- lane: { kind: "code", testPaths: i3.testPaths, frozen: tests.frozen, amend },
50773
+ lane: { kind: "code", testPaths: codeLaneTests, frozen: tests.frozen, amend },
50355
50774
  seed: d2.results,
50356
50775
  keepOnGiveUp: false,
50357
50776
  previousAttempt: keptChange(i3.attempt, "test_disagrees", d2.lastTestAnswer, d2.steps)
@@ -50643,10 +51062,10 @@ function buildCodegenLoopRecord(loop) {
50643
51062
  }
50644
51063
 
50645
51064
  // src/codegenLoopContext.ts
50646
- var import_node_fs16 = require("node:fs");
51065
+ var import_node_fs18 = require("node:fs");
50647
51066
 
50648
51067
  // src/langReach.ts
50649
- var import_node_path20 = require("node:path");
51068
+ var import_node_path21 = require("node:path");
50650
51069
  var LANGUAGE_BY_EXT = {
50651
51070
  ".go": "go",
50652
51071
  ".py": "python",
@@ -50662,7 +51081,7 @@ var LANGUAGE_BY_EXT = {
50662
51081
  ".swift": "swift"
50663
51082
  };
50664
51083
  function languageOf(path) {
50665
- return LANGUAGE_BY_EXT[import_node_path20.posix.extname(path).toLowerCase()] ?? null;
51084
+ return LANGUAGE_BY_EXT[import_node_path21.posix.extname(path).toLowerCase()] ?? null;
50666
51085
  }
50667
51086
  var MAX_REACH_TESTS = 10;
50668
51087
  var MAX_IMPORT_STEPS = 3;
@@ -50671,8 +51090,8 @@ var MAX_WALK_FILES = 5e3;
50671
51090
  var HUB_LIMIT = 25;
50672
51091
  var COMMON_MENTION_LIMIT = 12;
50673
51092
  var MAX_FILES_READ2 = 4e3;
50674
- var MAX_FILE_CHARS2 = 2e5;
50675
- var MIN_NAME_CHARS = 4;
51093
+ var MAX_FILE_CHARS3 = 2e5;
51094
+ var MIN_NAME_CHARS2 = 4;
50676
51095
  var MIN_CLASS_NAME_CHARS = 3;
50677
51096
  var GENERIC_NAMES = /* @__PURE__ */ new Set(["main", "init", "test", "tests", "self", "this", "none", "true", "false", "null", "name", "value", "data", "type", "list", "dict", "string", "int", "bool", "error", "result", "new", "get", "set", "run"]);
50678
51097
  function lookSymbolsOf(findings) {
@@ -50686,14 +51105,14 @@ function lookSymbolsOf(findings) {
50686
51105
  for (const c of findings.callPath) add2(c.path, c.symbol);
50687
51106
  return out2;
50688
51107
  }
50689
- var baseNoExt = (p) => import_node_path20.posix.basename(p).replace(/\.[^.]+$/, "");
50690
- var dirOf = (p) => import_node_path20.posix.dirname(p) === "." ? "" : import_node_path20.posix.dirname(p);
51108
+ var baseNoExt = (p) => import_node_path21.posix.basename(p).replace(/\.[^.]+$/, "");
51109
+ var dirOf = (p) => import_node_path21.posix.dirname(p) === "." ? "" : import_node_path21.posix.dirname(p);
50691
51110
  function testStem(path) {
50692
51111
  return baseNoExt(path).replace(/^test_/i, "").replace(/(_test|_spec)$/i, "").replace(/Tests?$/, "").toLowerCase();
50693
51112
  }
50694
51113
  function codeStem(path) {
50695
51114
  const b = baseNoExt(path);
50696
- if (b === "__init__" || b === "mod" || b === "index") return import_node_path20.posix.basename(dirOf(path)).toLowerCase();
51115
+ if (b === "__init__" || b === "mod" || b === "index") return import_node_path21.posix.basename(dirOf(path)).toLowerCase();
50697
51116
  return b.toLowerCase();
50698
51117
  }
50699
51118
  function sharedPrefix2(a, b) {
@@ -50716,7 +51135,7 @@ function mentionsOf(names) {
50716
51135
  }
50717
51136
  };
50718
51137
  for (const name2 of names) {
50719
- if (name2.length < MIN_NAME_CHARS || GENERIC_NAMES.has(name2.toLowerCase())) continue;
51138
+ if (name2.length < MIN_NAME_CHARS2 || GENERIC_NAMES.has(name2.toLowerCase())) continue;
50720
51139
  const tokens = splitName(name2);
50721
51140
  if (tokens.length >= 2) {
50722
51141
  const two = squash(tokens.slice(0, 2).join(""));
@@ -50776,7 +51195,7 @@ function buildIndex(files, readText) {
50776
51195
  }
50777
51196
  }
50778
51197
  let goModule = null;
50779
- const gomod = files.filter((f) => import_node_path20.posix.basename(f) === "go.mod").sort((a, b) => a.length - b.length)[0];
51198
+ const gomod = files.filter((f) => import_node_path21.posix.basename(f) === "go.mod").sort((a, b) => a.length - b.length)[0];
50780
51199
  if (gomod) {
50781
51200
  const m = /^module[ \t]+(\S+)/m.exec(readText(gomod) ?? "");
50782
51201
  if (m) goModule = { root: dirOf(gomod), module: m[1].replace(/^"|"$/g, "") };
@@ -50791,7 +51210,7 @@ function pythonImports(file, text3, ix) {
50791
51210
  const relative11 = (dots, rest) => {
50792
51211
  let base = dirOf(file);
50793
51212
  for (let i3 = 1; i3 < dots; i3++) base = dirOf(base);
50794
- const joined = rest ? import_node_path20.posix.join(base, rest.replace(/\./g, "/")) : base;
51213
+ const joined = rest ? import_node_path21.posix.join(base, rest.replace(/\./g, "/")) : base;
50795
51214
  return [`${joined}.py`, `${joined}/__init__.py`].filter((p) => ix.set.has(p) && p !== file);
50796
51215
  };
50797
51216
  for (const line2 of text3.split("\n")) {
@@ -50831,10 +51250,10 @@ function goImports(file, text3, ix) {
50831
51250
  let dir = null;
50832
51251
  if (ix.goModule && (p === ix.goModule.module || p.startsWith(`${ix.goModule.module}/`))) {
50833
51252
  const rest = p.slice(ix.goModule.module.length).replace(/^\//, "");
50834
- dir = ix.goModule.root ? import_node_path20.posix.join(ix.goModule.root, rest) : rest;
51253
+ dir = ix.goModule.root ? import_node_path21.posix.join(ix.goModule.root, rest) : rest;
50835
51254
  } else {
50836
- const tail = p.split("/").slice(-2).join("/");
50837
- for (const d of ix.byDir.keys()) if (d === tail || d.endsWith(`/${tail}`)) {
51255
+ const tail2 = p.split("/").slice(-2).join("/");
51256
+ for (const d of ix.byDir.keys()) if (d === tail2 || d.endsWith(`/${tail2}`)) {
50838
51257
  dir = d;
50839
51258
  break;
50840
51259
  }
@@ -50864,9 +51283,9 @@ function jvmImports(file, text3, ix) {
50864
51283
  }
50865
51284
  }
50866
51285
  const pkg = /^[ \t]*package[ \t]+([\w.]+)/m.exec(text3);
50867
- const tail = pkg ? pkg[1].replace(/\./g, "/") : null;
51286
+ const tail2 = pkg ? pkg[1].replace(/\./g, "/") : null;
50868
51287
  const siblings = [];
50869
- for (const [d, fs2] of ix.byDir) if (d === dirOf(file) || tail !== null && (d === tail || d.endsWith(`/${tail}`))) siblings.push(...fs2);
51288
+ for (const [d, fs2] of ix.byDir) if (d === dirOf(file) || tail2 !== null && (d === tail2 || d.endsWith(`/${tail2}`))) siblings.push(...fs2);
50870
51289
  if (siblings.length <= 400) {
50871
51290
  for (const f of siblings) {
50872
51291
  if (f === file || languageOf(f) !== "jvm") continue;
@@ -50882,7 +51301,7 @@ function importsOf(language, file, text3, ix) {
50882
51301
  if (language === "jvm") return jvmImports(file, text3, ix);
50883
51302
  return [];
50884
51303
  }
50885
- var isPackageInit = (p) => import_node_path20.posix.basename(p) === "__init__.py";
51304
+ var isPackageInit = (p) => import_node_path21.posix.basename(p) === "__init__.py";
50886
51305
  function testsReaching(input) {
50887
51306
  const limit = Math.min(MAX_REACH_TESTS, Math.max(0, input.limit ?? MAX_REACH_TESTS));
50888
51307
  const listing = input.isDenied ? input.listing.filter((p) => !input.isDenied(p)) : [...input.listing];
@@ -50901,7 +51320,7 @@ function testsReaching(input) {
50901
51320
  } catch {
50902
51321
  t = null;
50903
51322
  }
50904
- if (t !== null && (t.length > MAX_FILE_CHARS2 || t.includes("\0"))) t = null;
51323
+ if (t !== null && (t.length > MAX_FILE_CHARS3 || t.includes("\0"))) t = null;
50905
51324
  }
50906
51325
  cache2.set(p, t);
50907
51326
  return t;
@@ -51012,7 +51431,7 @@ function dirOf2(path) {
51012
51431
  const i3 = path.lastIndexOf("/");
51013
51432
  return i3 === -1 ? "" : path.slice(0, i3);
51014
51433
  }
51015
- function baseOf(path) {
51434
+ function baseOf2(path) {
51016
51435
  return path.slice(path.lastIndexOf("/") + 1);
51017
51436
  }
51018
51437
  function parentOf(dir) {
@@ -51020,17 +51439,17 @@ function parentOf(dir) {
51020
51439
  }
51021
51440
  function pairedTestPaths(codePath, listing, isTest = isTestTarget) {
51022
51441
  if (isTest(codePath)) return [];
51023
- const m = CODE_NAME_RE.exec(baseOf(codePath));
51442
+ const m = CODE_NAME_RE.exec(baseOf2(codePath));
51024
51443
  if (!m) return [];
51025
51444
  const stem = m[1].toLowerCase();
51026
51445
  const dir = dirOf2(codePath);
51027
51446
  const parent = parentOf(dir);
51028
- const join18 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
51029
- const homes = /* @__PURE__ */ new Set([dir, join18(dir, "__tests__"), join18(parent, "__tests__"), join18(parent, "tests"), join18(parent, "test")]);
51447
+ const join19 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
51448
+ const homes = /* @__PURE__ */ new Set([dir, join19(dir, "__tests__"), join19(parent, "__tests__"), join19(parent, "tests"), join19(parent, "test")]);
51030
51449
  const found = [];
51031
51450
  for (const path of listing) {
51032
51451
  if (!homes.has(dirOf2(path))) continue;
51033
- const t = TEST_NAME_RE.exec(baseOf(path));
51452
+ const t = TEST_NAME_RE.exec(baseOf2(path));
51034
51453
  if (t && t[1].toLowerCase() === stem) found.push(path);
51035
51454
  }
51036
51455
  return found.sort();
@@ -51039,7 +51458,7 @@ function asLf(text3) {
51039
51458
  return toLf(text3.charCodeAt(0) === 65279 ? text3.slice(1) : text3);
51040
51459
  }
51041
51460
  function collectLoopContext(p) {
51042
- const readFile = p.readFile ?? ((path) => (0, import_node_fs16.readFileSync)(path, "utf8"));
51461
+ const readFile = p.readFile ?? ((path) => (0, import_node_fs18.readFileSync)(path, "utf8"));
51043
51462
  const listing = new Set(p.listing);
51044
51463
  const mapSpecifier = p.mapSpecifier ?? createAliasMapper({
51045
51464
  readText: (path) => {
@@ -51206,8 +51625,8 @@ function mapModeMessage(phase, reason) {
51206
51625
  }
51207
51626
 
51208
51627
  // src/testsToCheck.ts
51209
- var import_node_fs17 = require("node:fs");
51210
- var import_node_path21 = require("node:path");
51628
+ var import_node_fs19 = require("node:fs");
51629
+ var import_node_path22 = require("node:path");
51211
51630
  var MAX_TESTS_TO_CHECK = 10;
51212
51631
  var SECOND_HOP_BELOW = 3;
51213
51632
  function testsToCheck(i3) {
@@ -51258,7 +51677,7 @@ function testsToCheck(i3) {
51258
51677
  }
51259
51678
  var readFromRoot = (root) => (rel) => {
51260
51679
  try {
51261
- return (0, import_node_fs17.readFileSync)((0, import_node_path21.join)(root, rel), "utf8");
51680
+ return (0, import_node_fs19.readFileSync)((0, import_node_path22.join)(root, rel), "utf8");
51262
51681
  } catch {
51263
51682
  return null;
51264
51683
  }
@@ -51269,6 +51688,14 @@ function testTargetPaths(targets, discoveredTests) {
51269
51688
  const isTest = testRule(discoveredTests);
51270
51689
  return targets.filter((t) => (t.automationIds?.length ?? 0) > 0 || isTest(t.path)).map((t) => t.path);
51271
51690
  }
51691
+ function claimOnlySourcePaths(targets, discoveredTests) {
51692
+ const isTest = testRule(discoveredTests);
51693
+ return targets.filter((t) => t.kind === "EXISTING" && (t.automationIds?.length ?? 0) > 0 && !isTest(t.path)).map((t) => t.path);
51694
+ }
51695
+ function codeLaneTestPaths(targets, discoveredTests) {
51696
+ const claimOnly = new Set(claimOnlySourcePaths(targets, discoveredTests));
51697
+ return testTargetPaths(targets, discoveredTests).filter((p) => !claimOnly.has(p));
51698
+ }
51272
51699
  function discoveredTestsOf(testDiscovery) {
51273
51700
  return testDiscovery.report === "PRESENT" ? testDiscovery.discoveredTestFiles : void 0;
51274
51701
  }
@@ -51541,6 +51968,7 @@ async function runCodegenStep(p) {
51541
51968
  ...previousAttempt ? { previous: previousAttempt } : {},
51542
51969
  ...resume ? { resume } : {},
51543
51970
  testPaths: testTargetPaths(p.targets, discoveredTestsOf(p.testDiscovery)),
51971
+ claimOnlySource: claimOnlySourcePaths(p.targets, discoveredTestsOf(p.testDiscovery)),
51544
51972
  redCheckIds: checkableIds(args2.requiredAutomationIds, p.requiredTestTypes),
51545
51973
  ...p.redReview === true ? { redReview: true } : {},
51546
51974
  ...p.parts && p.parts.length > 0 ? { parts: p.parts } : {},
@@ -51715,7 +52143,7 @@ async function runCodegenStep(p) {
51715
52143
  }
51716
52144
 
51717
52145
  // src/codegenHeal.ts
51718
- var import_node_fs18 = require("node:fs");
52146
+ var import_node_fs20 = require("node:fs");
51719
52147
 
51720
52148
  // src/heal.ts
51721
52149
  var MAX_ATTEMPTS_IN_ALL = 3;
@@ -51795,7 +52223,7 @@ async function runHealAttempt(i3) {
51795
52223
  const created = i3.results.map((r) => r.targetPath).filter((path) => !listed.has(path));
51796
52224
  const workspaceListing = [...p.workspaceListing, ...created];
51797
52225
  const targets = p.targets.map((t) => t.kind === "NEW_FILE" && keptText.has(t.path) ? { ...t, kind: "EXISTING" } : t);
51798
- const disk = p.readFile ?? ((path) => (0, import_node_fs18.readFileSync)(path, "utf8"));
52226
+ const disk = p.readFile ?? ((path) => (0, import_node_fs20.readFileSync)(path, "utf8"));
51799
52227
  const readFile = (path) => keptText.get(path) ?? disk(path);
51800
52228
  const discoveredTests = discoveredTestsOf(p.testDiscovery);
51801
52229
  const context = collectLoopContext({ targets, listing: workspaceListing, deniedPaths: p.deniedPaths, writeRoot: p.writeRoot ?? "", ...discoveredTests ? { discoveredTests } : {}, readFile });
@@ -51819,7 +52247,7 @@ async function runHealAttempt(i3) {
51819
52247
  {
51820
52248
  ...args2,
51821
52249
  // QUIKTR-1608 (§33.2): after a change written in phases, a fix is code only and the tests phase 1 wrote stay frozen.
51822
- ...args2.harness === true && p.out.frozen && p.out.frozen.length > 0 ? { phase: "code", lane: { kind: "code", testPaths: testTargetPaths(p.targets, discoveredTests), frozen: p.out.frozen } } : {},
52250
+ ...args2.harness === true && p.out.frozen && p.out.frozen.length > 0 ? { phase: "code", lane: { kind: "code", testPaths: codeLaneTestPaths(p.targets, discoveredTests), frozen: p.out.frozen } } : {},
51823
52251
  keepOnGiveUp: false,
51824
52252
  seed: i3.results,
51825
52253
  // QUIKTR-1607 (§32): and what the attempt whose change this fix keeps did, step by step (left out when the loop speaks loop-2).
@@ -52060,79 +52488,9 @@ async function runVerifyAndFix(p) {
52060
52488
  }
52061
52489
 
52062
52490
  // src/hunkCheck.ts
52063
- var import_node_child_process9 = require("node:child_process");
52064
- var import_node_fs20 = require("node:fs");
52065
- var import_node_path22 = require("node:path");
52066
-
52067
- // src/scopeCheck.ts
52068
- var import_node_fs19 = require("node:fs");
52069
- var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
52070
- var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
52071
- var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
52072
- var CALL_LINE_RE = /fetch\s*\(|\baxios\b|(?:\$|\bjQuery)\.(?:ajax|get|post|getJSON)\s*\(|\bXMLHttpRequest\b|\.open\(\s*["'`](?:GET|POST|PUT|PATCH|DELETE)["'`]|\bhttp\.(?:get|post|put|patch|delete|head|request|postform|newrequest|newrequestwithcontext)\s*\(|\b(?:requests|httpx)\.(?:get|post|put|patch|delete|head|request)\s*\(|\bHttpRequest\.newBuilder\b|\bcurl\b/i;
52073
- var NO_PATH = "(this file's route)";
52074
- function detectMentions(text3) {
52075
- const found = [];
52076
- for (const line2 of text3.split("\n")) {
52077
- const methodMatch = ROUTE_METHOD_RE.exec(line2);
52078
- const pathMatch = ROUTE_PATH_RE.exec(line2);
52079
- if (methodMatch && pathMatch && !CALL_LINE_RE.test(line2)) {
52080
- found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0].replace(/:+$/, "") });
52081
- }
52082
- const exportMatch = ROUTE_EXPORT_RE.exec(line2);
52083
- if (exportMatch) {
52084
- found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
52085
- }
52086
- }
52087
- return found;
52088
- }
52089
- function normalizePath(path) {
52090
- return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
52091
- }
52092
- function surfaceCovers(surface, mention) {
52093
- if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
52094
- if (mention.path === NO_PATH) return true;
52095
- const declaredPath = normalizePath(surface);
52096
- const mentionPath = normalizePath(mention.path);
52097
- return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
52098
- }
52099
- function addedLines(before, after) {
52100
- const beforeLines = new Set(before.split("\n"));
52101
- return after.split("\n").filter((line2) => !beforeLines.has(line2)).join("\n");
52102
- }
52103
- function checkApiScope(results, targets, apiChanges, existing) {
52104
- const targetsByPath = new Map(targets.map((t) => [t.path, t]));
52105
- const violations = [];
52106
- for (const { targetPath, newContent } of results) {
52107
- if (isTestFile(targetPath)) continue;
52108
- const target = targetsByPath.get(targetPath);
52109
- const isNewFile = target?.kind === "NEW_FILE";
52110
- let scanned;
52111
- if (isNewFile) {
52112
- scanned = newContent;
52113
- } else {
52114
- let currentContent;
52115
- try {
52116
- currentContent = (0, import_node_fs19.readFileSync)(targetPath, "utf8");
52117
- } catch {
52118
- currentContent = "";
52119
- }
52120
- scanned = addedLines(currentContent, newContent);
52121
- }
52122
- for (const mention of detectMentions(scanned)) {
52123
- if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
52124
- if (existing && mention.path !== NO_PATH && existing.has(mention)) continue;
52125
- violations.push({ file: targetPath, method: mention.method, path: mention.path });
52126
- }
52127
- }
52128
- }
52129
- return { blocked: violations.length > 0, violations };
52130
- }
52131
- function describeScopeViolations(check) {
52132
- return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
52133
- }
52134
-
52135
- // src/hunkCheck.ts
52491
+ var import_node_child_process10 = require("node:child_process");
52492
+ var import_node_fs21 = require("node:fs");
52493
+ var import_node_path23 = require("node:path");
52136
52494
  var MAX_REPORTED_HUNKS = 20;
52137
52495
  function toFinding(r) {
52138
52496
  if (r.unnecessary.length === 0) return void 0;
@@ -52159,7 +52517,7 @@ function collectHunkCheckFiles(results, root, readHead = readCommittedText) {
52159
52517
  }
52160
52518
  function readCommittedText(root, path) {
52161
52519
  try {
52162
- return (0, import_node_child_process9.execFileSync)("git", ["show", `HEAD:${path}`], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024 });
52520
+ return (0, import_node_child_process10.execFileSync)("git", ["show", `HEAD:${path}`], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024 });
52163
52521
  } catch {
52164
52522
  return null;
52165
52523
  }
@@ -52210,7 +52568,7 @@ async function runHunkCheck(input) {
52210
52568
  let slowestRunMs = input.baselineMs ?? 3e4;
52211
52569
  const runOnce = async (c) => {
52212
52570
  const reportBefore = findReport(input.root);
52213
- const preserve = reportBefore ? [(0, import_node_path22.relative)(input.root, reportBefore).split("\\").join("/")] : [];
52571
+ const preserve = reportBefore ? [(0, import_node_path23.relative)(input.root, reportBefore).split("\\").join("/")] : [];
52214
52572
  const content = `${c.bom ? "\uFEFF" : ""}${fromLf(revertHunk(c.originalLf, c.currentLf, c.hunk), c.ending)}`;
52215
52573
  const startedWall = Date.now();
52216
52574
  const startedAt = now();
@@ -52220,13 +52578,13 @@ async function runHunkCheck(input) {
52220
52578
  input.root,
52221
52579
  [{ path: c.file, content }],
52222
52580
  async () => {
52223
- if (reportBefore) (0, import_node_fs20.rmSync)(reportBefore, { force: true });
52581
+ if (reportBefore) (0, import_node_fs21.rmSync)(reportBefore, { force: true });
52224
52582
  const run3 = await runCommand2(input.command, perRunMs, input.root);
52225
52583
  if (!run3.started || run3.timedOut) return "unknown";
52226
52584
  const report = findReport(input.root);
52227
52585
  if (!report) return "unknown";
52228
52586
  try {
52229
- if ((0, import_node_fs20.statSync)(report).mtimeMs < startedWall - FRESH_SLACK_MS3) return "unknown";
52587
+ if ((0, import_node_fs21.statSync)(report).mtimeMs < startedWall - FRESH_SLACK_MS3) return "unknown";
52230
52588
  } catch {
52231
52589
  return "unknown";
52232
52590
  }
@@ -52246,7 +52604,7 @@ async function runHunkCheck(input) {
52246
52604
  };
52247
52605
  const runRelated = async (c, plan, limitMs) => {
52248
52606
  const reportBefore = findReport(input.root);
52249
- const preserve = reportBefore ? [(0, import_node_path22.relative)(input.root, reportBefore).split("\\").join("/")] : [];
52607
+ const preserve = reportBefore ? [(0, import_node_path23.relative)(input.root, reportBefore).split("\\").join("/")] : [];
52250
52608
  const content = `${c.bom ? "\uFEFF" : ""}${fromLf(revertHunk(c.originalLf, c.currentLf, c.hunk), c.ending)}`;
52251
52609
  const startedAt = now();
52252
52610
  result.relatedRuns += 1;
@@ -52255,7 +52613,7 @@ async function runHunkCheck(input) {
52255
52613
  input.root,
52256
52614
  [{ path: c.file, content }],
52257
52615
  async () => {
52258
- (0, import_node_fs20.rmSync)(plan.report, { force: true });
52616
+ (0, import_node_fs21.rmSync)(plan.report, { force: true });
52259
52617
  try {
52260
52618
  const run3 = await runCommand2(plan.command, limitMs, plan.cwd);
52261
52619
  if (!run3.started || run3.timedOut) return "unknown";
@@ -52263,7 +52621,7 @@ async function runHunkCheck(input) {
52263
52621
  if (!after.results || after.results.size === 0) return "unknown";
52264
52622
  return checkForRegressions(input.baseline, after).blocked ? "needed" : "unneeded";
52265
52623
  } finally {
52266
- (0, import_node_fs20.rmSync)(plan.report, { force: true });
52624
+ (0, import_node_fs21.rmSync)(plan.report, { force: true });
52267
52625
  }
52268
52626
  },
52269
52627
  { ...input.tree, preserve }
@@ -52390,8 +52748,8 @@ function healFailureSuffix(heal) {
52390
52748
  }
52391
52749
 
52392
52750
  // src/dependencyCheck.ts
52393
- var import_node_fs21 = require("node:fs");
52394
- var import_node_path23 = require("node:path");
52751
+ var import_node_fs22 = require("node:fs");
52752
+ var import_node_path24 = require("node:path");
52395
52753
  var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
52396
52754
  var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
52397
52755
  var NODE_BUILTINS = /* @__PURE__ */ new Set([
@@ -52479,14 +52837,14 @@ function dependencyNames(pkg) {
52479
52837
  ]);
52480
52838
  }
52481
52839
  function readDeclaredDependencies(results, workspaceRoot) {
52482
- const packageJsonPath = (0, import_node_path23.join)((0, import_node_path23.resolve)(workspaceRoot ?? "."), "package.json");
52483
- const generated = results.find((r) => (0, import_node_path23.resolve)(r.targetPath) === packageJsonPath);
52840
+ const packageJsonPath = (0, import_node_path24.join)((0, import_node_path24.resolve)(workspaceRoot ?? "."), "package.json");
52841
+ const generated = results.find((r) => (0, import_node_path24.resolve)(r.targetPath) === packageJsonPath);
52484
52842
  let raw;
52485
52843
  if (generated) {
52486
52844
  raw = generated.newContent;
52487
52845
  } else {
52488
52846
  try {
52489
- raw = (0, import_node_fs21.readFileSync)(packageJsonPath, "utf8");
52847
+ raw = (0, import_node_fs22.readFileSync)(packageJsonPath, "utf8");
52490
52848
  } catch {
52491
52849
  raw = null;
52492
52850
  }
@@ -52550,16 +52908,16 @@ function stripJsonComments(text3) {
52550
52908
  return out2.replace(/,(\s*[}\]])/g, "$1");
52551
52909
  }
52552
52910
  function resolveAliasPrefixes(results, workspaceRoot) {
52553
- const root = (0, import_node_path23.resolve)(workspaceRoot ?? ".");
52911
+ const root = (0, import_node_path24.resolve)(workspaceRoot ?? ".");
52554
52912
  for (const filename of ["tsconfig.json", "jsconfig.json"]) {
52555
- const configPath = (0, import_node_path23.join)(root, filename);
52556
- const generated = results.find((r) => (0, import_node_path23.resolve)(r.targetPath) === configPath);
52913
+ const configPath = (0, import_node_path24.join)(root, filename);
52914
+ const generated = results.find((r) => (0, import_node_path24.resolve)(r.targetPath) === configPath);
52557
52915
  let raw;
52558
52916
  if (generated) {
52559
52917
  raw = generated.newContent;
52560
52918
  } else {
52561
52919
  try {
52562
- raw = (0, import_node_fs21.readFileSync)(configPath, "utf8");
52920
+ raw = (0, import_node_fs22.readFileSync)(configPath, "utf8");
52563
52921
  } catch {
52564
52922
  raw = null;
52565
52923
  }
@@ -52647,7 +53005,7 @@ function exitCodeFailedMessage() {
52647
53005
  var EXIT_CODE_ONLY_NOTE = "The change was checked by the Test command's result only: it passed before and after the change, but no test report was found, so QuikPilot could not see individual tests or confirm that its new tests ran.";
52648
53006
 
52649
53007
  // src/existingRoutes.ts
52650
- var import_node_child_process10 = require("node:child_process");
53008
+ var import_node_child_process11 = require("node:child_process");
52651
53009
  var GREP_TIMEOUT_MS = 1e4;
52652
53010
  var MAX_HIT_LINES = 400;
52653
53011
  var MAX_OUTPUT_BYTES = 4e6;
@@ -52662,7 +53020,7 @@ function routeAlreadyNamed(cwd, mention) {
52662
53020
  const wanted = normalizePath(mention.path);
52663
53021
  let out2;
52664
53022
  try {
52665
- out2 = (0, import_node_child_process10.execFileSync)("git", ["grep", "-I", "-n", "-F", "-e", anchor], {
53023
+ out2 = (0, import_node_child_process11.execFileSync)("git", ["grep", "-I", "-n", "-F", "-e", anchor], {
52666
53024
  cwd,
52667
53025
  encoding: "utf8",
52668
53026
  stdio: ["ignore", "pipe", "ignore"],
@@ -52695,18 +53053,22 @@ function isDiscovered(targetPath, discoveredFiles) {
52695
53053
  }
52696
53054
  return false;
52697
53055
  }
52698
- function checkTestPlacement(targets, discoveredFiles) {
53056
+ function checkTestPlacement(targets, discoveredFiles, written) {
52699
53057
  if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };
52700
53058
  const violations = [];
52701
53059
  for (const target of targets) {
52702
53060
  if (target.kind !== "EXISTING") continue;
52703
53061
  if (!target.automationIds || target.automationIds.length === 0) continue;
52704
- if (!isDiscovered(target.path, discoveredFiles)) {
52705
- violations.push({ file: target.path, automationIds: target.automationIds });
52706
- }
53062
+ if (isDiscovered(target.path, discoveredFiles)) continue;
53063
+ const ids = written === void 0 ? target.automationIds : target.automationIds.filter((id) => !heldInAnotherTestFile(id, target.path, written, discoveredFiles));
53064
+ if (ids.length > 0) violations.push({ file: target.path, automationIds: ids });
52707
53065
  }
52708
53066
  return { blocked: violations.length > 0, violations };
52709
53067
  }
53068
+ function heldInAnotherTestFile(id, claimedPath, written, discovered) {
53069
+ const tests = written.filter((w) => w.path !== claimedPath && isTestTarget(w.path, discovered));
53070
+ return tests.some((w) => w.text.includes(`[${id}]`)) || declaredIn(id, new Map(tests.map((w) => [w.path, w.text])));
53071
+ }
52710
53072
  function describeTestPlacementViolations(check) {
52711
53073
  return check.violations.map(
52712
53074
  (v) => `${v.file} claims test case(s) ${v.automationIds.join(", ")} but the repository's own test runner never discovered this file`
@@ -52915,13 +53277,13 @@ function describeUnsuppliedInputs(found) {
52915
53277
  }
52916
53278
 
52917
53279
  // src/unsuppliedInputsDisk.ts
52918
- var import_node_fs22 = require("node:fs");
53280
+ var import_node_fs23 = require("node:fs");
52919
53281
  var MAX_READ_BYTES = 1e6;
52920
53282
  function readCheckoutText(path) {
52921
53283
  try {
52922
- const info2 = (0, import_node_fs22.statSync)(path);
53284
+ const info2 = (0, import_node_fs23.statSync)(path);
52923
53285
  if (!info2.isFile() || info2.size > MAX_READ_BYTES) return null;
52924
- const bytes = (0, import_node_fs22.readFileSync)(path);
53286
+ const bytes = (0, import_node_fs23.readFileSync)(path);
52925
53287
  if (bytes.includes(0)) return null;
52926
53288
  return bytes.toString("utf8");
52927
53289
  } catch {
@@ -52951,10 +53313,10 @@ function describeVanishedTests(vanished) {
52951
53313
  }
52952
53314
 
52953
53315
  // src/verifyChange.ts
52954
- var import_node_path24 = require("node:path");
53316
+ var import_node_path25 = require("node:path");
52955
53317
 
52956
53318
  // src/packageUse.ts
52957
- var import_node_child_process11 = require("node:child_process");
53319
+ var import_node_child_process12 = require("node:child_process");
52958
53320
  var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
52959
53321
  var FILE_TYPES = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
52960
53322
  var GREP_TIMEOUT_MS2 = 1e4;
@@ -52966,7 +53328,7 @@ function packageImportedInWorkspace(pkg, root, cwd = process.cwd()) {
52966
53328
  if (!PACKAGE_NAME.test(pkg)) return false;
52967
53329
  const pathspecs = FILE_TYPES.map((type) => root ? `:(glob)${root}/**/${type}` : `:(glob)**/${type}`);
52968
53330
  try {
52969
- (0, import_node_child_process11.execFileSync)("git", ["grep", "-q", "-E", "-e", importPattern(pkg), "--", ...pathspecs], {
53331
+ (0, import_node_child_process12.execFileSync)("git", ["grep", "-q", "-E", "-e", importPattern(pkg), "--", ...pathspecs], {
52970
53332
  cwd,
52971
53333
  stdio: "ignore",
52972
53334
  timeout: GREP_TIMEOUT_MS2
@@ -52978,7 +53340,7 @@ function packageImportedInWorkspace(pkg, root, cwd = process.cwd()) {
52978
53340
  }
52979
53341
 
52980
53342
  // src/verifyChange.ts
52981
- var import_node_fs23 = require("node:fs");
53343
+ var import_node_fs24 = require("node:fs");
52982
53344
  async function verifyChange(ctx, results, undoable) {
52983
53345
  const cwd = ctx.cwd ?? process.cwd();
52984
53346
  const now = ctx.now ?? Date.now;
@@ -53013,7 +53375,7 @@ async function verifyChange(ctx, results, undoable) {
53013
53375
  const depCheck = checkImportDependencies(results, readDeclaredDependencies(results, packet.workspaceRoot), resolveAliasPrefixes(results, packet.workspaceRoot), {
53014
53376
  originalOf: (path) => {
53015
53377
  try {
53016
- return (0, import_node_fs23.readFileSync)((0, import_node_path24.join)(cwd, path), "utf8");
53378
+ return (0, import_node_fs24.readFileSync)((0, import_node_path25.join)(cwd, path), "utf8");
53017
53379
  } catch (err2) {
53018
53380
  return err2.code === "ENOENT" ? "" : null;
53019
53381
  }
@@ -53035,7 +53397,11 @@ async function verifyChange(ctx, results, undoable) {
53035
53397
  return fail(new Error(`QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`));
53036
53398
  }
53037
53399
  stage = "placement";
53038
- const placementCheck = checkTestPlacement(targets, baseline.discoveredFiles);
53400
+ const placementCheck = checkTestPlacement(
53401
+ targets,
53402
+ baseline.discoveredFiles,
53403
+ results.map((r) => ({ path: r.targetPath, text: r.newContent }))
53404
+ );
53039
53405
  if (placementCheck.blocked) {
53040
53406
  return fail(new Error(`QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`));
53041
53407
  }
@@ -53069,7 +53435,7 @@ async function verifyChange(ctx, results, undoable) {
53069
53435
  flushedAt = now();
53070
53436
  if (undoable) {
53071
53437
  const report = findJUnitReport(cwd);
53072
- const ignore = report ? [(0, import_node_path24.relative)(cwd, report).split("\\").join("/")] : [];
53438
+ const ignore = report ? [(0, import_node_path25.relative)(cwd, report).split("\\").join("/")] : [];
53073
53439
  const flush = undoableFlush(cwd, results, flushCodegenResults, { ignore });
53074
53440
  undo = () => flush.undo();
53075
53441
  } else {
@@ -53177,7 +53543,7 @@ ${violations.join("\n")}`);
53177
53543
  }
53178
53544
 
53179
53545
  // src/run.ts
53180
- var import_node_fs28 = require("node:fs");
53546
+ var import_node_fs29 = require("node:fs");
53181
53547
 
53182
53548
  // src/mapMode.ts
53183
53549
  var MAP_ENV = "QUIKPILOT_MAP";
@@ -53235,7 +53601,7 @@ function buildToolsV2Env(i3) {
53235
53601
  }
53236
53602
 
53237
53603
  // src/repoMap.ts
53238
- var import_node_path25 = require("node:path");
53604
+ var import_node_path26 = require("node:path");
53239
53605
  var MAP_BUDGET_TOKENS = 4e3;
53240
53606
  var MAX_FOLDERS = 200;
53241
53607
  var MAX_LANGUAGES = 12;
@@ -53277,7 +53643,7 @@ function guidanceFiles(i3, perFile2, total) {
53277
53643
  function languages2(listing) {
53278
53644
  const counts = /* @__PURE__ */ new Map();
53279
53645
  for (const p of listing) {
53280
- const ext = import_node_path25.posix.extname(p).toLowerCase();
53646
+ const ext = import_node_path26.posix.extname(p).toLowerCase();
53281
53647
  if (ext && ext.length <= 12) counts.set(ext, (counts.get(ext) ?? 0) + 1);
53282
53648
  }
53283
53649
  return [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, MAX_LANGUAGES).map(([ext, n]) => `${ext} ${n}`);
@@ -53293,7 +53659,7 @@ function testFacts(i3) {
53293
53659
  const depth = i3.writeRoot === "" ? 0 : i3.writeRoot.split("/").length;
53294
53660
  for (const t of tests) {
53295
53661
  const parts2 = t.split("/");
53296
- const folder = parts2.length > depth + 1 ? parts2.slice(0, depth + 1).join("/") : import_node_path25.posix.dirname(t);
53662
+ const folder = parts2.length > depth + 1 ? parts2.slice(0, depth + 1).join("/") : import_node_path26.posix.dirname(t);
53297
53663
  byFolder.set(folder, (byFolder.get(folder) ?? 0) + 1);
53298
53664
  }
53299
53665
  for (const [folder, n] of [...byFolder.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 3)) {
@@ -53403,7 +53769,7 @@ function buildRepoMap(i3) {
53403
53769
  }
53404
53770
 
53405
53771
  // src/workspacePackages.ts
53406
- var import_node_path26 = require("node:path");
53772
+ var import_node_path27 = require("node:path");
53407
53773
  var MAX_READ_ROOTS = 8;
53408
53774
  function isObject2(x) {
53409
53775
  return typeof x === "object" && x !== null && !Array.isArray(x);
@@ -53465,8 +53831,8 @@ function workspacePackages(readText, packageJsonPaths) {
53465
53831
  const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => globMatcher(p.slice(1)));
53466
53832
  const out2 = [];
53467
53833
  for (const file of packageJsonPaths) {
53468
- if (import_node_path26.posix.basename(file) !== "package.json" || file === "package.json" || file.split("/").includes("node_modules")) continue;
53469
- const folder = import_node_path26.posix.dirname(file);
53834
+ if (import_node_path27.posix.basename(file) !== "package.json" || file === "package.json" || file.split("/").includes("node_modules")) continue;
53835
+ const folder = import_node_path27.posix.dirname(file);
53470
53836
  if (!include.some((re) => re.test(folder)) || exclude.some((re) => re.test(folder))) continue;
53471
53837
  const text3 = readText(file);
53472
53838
  const json = text3 === null ? null : parseJsonc(text3);
@@ -53736,41 +54102,41 @@ async function fetchPacket(packetUrl, runToken, githubRunId) {
53736
54102
  }
53737
54103
 
53738
54104
  // src/phase0.ts
53739
- var import_node_fs24 = require("node:fs");
54105
+ var import_node_fs25 = require("node:fs");
53740
54106
  function writePhase0Marker(runId) {
53741
- (0, import_node_fs24.mkdirSync)(".quikpilot", { recursive: true });
53742
- (0, import_node_fs24.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
54107
+ (0, import_node_fs25.mkdirSync)(".quikpilot", { recursive: true });
54108
+ (0, import_node_fs25.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
53743
54109
  `);
53744
54110
  }
53745
54111
 
53746
54112
  // src/failureArtifact.ts
53747
- var import_node_child_process12 = require("node:child_process");
53748
- var import_node_fs25 = require("node:fs");
53749
- var import_node_path27 = require("node:path");
54113
+ var import_node_child_process13 = require("node:child_process");
54114
+ var import_node_fs26 = require("node:fs");
54115
+ var import_node_path28 = require("node:path");
53750
54116
  var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
53751
54117
  var REPORT_COPY = "final-test-report.xml";
53752
54118
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
53753
54119
  var MAX_FILES = 200;
53754
- var RUNNER_VERSION = true ? "9.3.0-rc.79" : "dev";
54120
+ var RUNNER_VERSION = true ? "9.3.0-rc.80" : "dev";
53755
54121
  function safeDestination(base, repoPath) {
53756
- if (!repoPath || (0, import_node_path27.isAbsolute)(repoPath)) return null;
53757
- const destination = (0, import_node_path27.resolve)(base, repoPath);
53758
- const rel = (0, import_node_path27.relative)(base, destination);
53759
- if (!rel || rel.startsWith("..") || (0, import_node_path27.isAbsolute)(rel)) return null;
54122
+ if (!repoPath || (0, import_node_path28.isAbsolute)(repoPath)) return null;
54123
+ const destination = (0, import_node_path28.resolve)(base, repoPath);
54124
+ const rel = (0, import_node_path28.relative)(base, destination);
54125
+ if (!rel || rel.startsWith("..") || (0, import_node_path28.isAbsolute)(rel)) return null;
53760
54126
  return destination;
53761
54127
  }
53762
54128
  var BUNDLE_FILE = "quikpilot-change.bundle";
53763
54129
  function keepCommitBundle(repo, folder, branch) {
53764
- const git3 = (args2) => (0, import_node_child_process12.execFileSync)("git", args2, { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
54130
+ const git4 = (args2) => (0, import_node_child_process13.execFileSync)("git", args2, { cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
53765
54131
  try {
53766
- if (git3(["rev-parse", "--abbrev-ref", "HEAD"]) !== branch) return null;
53767
- if (git3(["diff", "--name-only", "HEAD~1", "HEAD"]) === "") return null;
53768
- const commit2 = git3(["rev-parse", "HEAD"]);
53769
- const file = (0, import_node_path27.join)(folder, BUNDLE_FILE);
53770
- git3(["bundle", "create", file, "HEAD", "^HEAD~1"]);
54132
+ if (git4(["rev-parse", "--abbrev-ref", "HEAD"]) !== branch) return null;
54133
+ if (git4(["diff", "--name-only", "HEAD~1", "HEAD"]) === "") return null;
54134
+ const commit2 = git4(["rev-parse", "HEAD"]);
54135
+ const file = (0, import_node_path28.join)(folder, BUNDLE_FILE);
54136
+ git4(["bundle", "create", file, "HEAD", "^HEAD~1"]);
53771
54137
  let verified = true;
53772
54138
  try {
53773
- git3(["bundle", "verify", file]);
54139
+ git4(["bundle", "verify", file]);
53774
54140
  } catch {
53775
54141
  verified = false;
53776
54142
  }
@@ -53782,9 +54148,9 @@ function keepCommitBundle(repo, folder, branch) {
53782
54148
  function writeFailureArtifact(input) {
53783
54149
  if (input.results.length === 0) return { written: false };
53784
54150
  try {
53785
- const base = (0, import_node_path27.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
53786
- (0, import_node_fs25.rmSync)(base, { recursive: true, force: true });
53787
- (0, import_node_fs25.mkdirSync)(base, { recursive: true });
54151
+ const base = (0, import_node_path28.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
54152
+ (0, import_node_fs26.rmSync)(base, { recursive: true, force: true });
54153
+ (0, import_node_fs26.mkdirSync)(base, { recursive: true });
53788
54154
  const files = [];
53789
54155
  const skipped = [];
53790
54156
  for (const result of input.results) {
@@ -53793,8 +54159,8 @@ function writeFailureArtifact(input) {
53793
54159
  skipped.push(result.targetPath);
53794
54160
  continue;
53795
54161
  }
53796
- (0, import_node_fs25.mkdirSync)((0, import_node_path27.dirname)(destination), { recursive: true });
53797
- (0, import_node_fs25.writeFileSync)(destination, result.newContent);
54162
+ (0, import_node_fs26.mkdirSync)((0, import_node_path28.dirname)(destination), { recursive: true });
54163
+ (0, import_node_fs26.writeFileSync)(destination, result.newContent);
53798
54164
  files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
53799
54165
  }
53800
54166
  let testReport = "none";
@@ -53802,7 +54168,7 @@ function writeFailureArtifact(input) {
53802
54168
  if (input.testReport.byteLength > MAX_REPORT_BYTES) {
53803
54169
  testReport = "too-large";
53804
54170
  } else {
53805
- (0, import_node_fs25.writeFileSync)((0, import_node_path27.join)(base, REPORT_COPY), input.testReport);
54171
+ (0, import_node_fs26.writeFileSync)((0, import_node_path28.join)(base, REPORT_COPY), input.testReport);
53806
54172
  testReport = "included";
53807
54173
  }
53808
54174
  }
@@ -53824,8 +54190,8 @@ function writeFailureArtifact(input) {
53824
54190
  bundle
53825
54191
  };
53826
54192
  const text3 = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
53827
- (0, import_node_fs25.writeFileSync)((0, import_node_path27.join)(base, "manifest.json"), text3);
53828
- return { written: (0, import_node_fs25.existsSync)((0, import_node_path27.join)(base, "manifest.json")) };
54193
+ (0, import_node_fs26.writeFileSync)((0, import_node_path28.join)(base, "manifest.json"), text3);
54194
+ return { written: (0, import_node_fs26.existsSync)((0, import_node_path28.join)(base, "manifest.json")) };
53829
54195
  } catch (err2) {
53830
54196
  console.warn(`::warning::Could not keep the failed run's files: ${err2 instanceof Error ? err2.message : String(err2)}`);
53831
54197
  return { written: false };
@@ -53833,33 +54199,44 @@ function writeFailureArtifact(input) {
53833
54199
  }
53834
54200
 
53835
54201
  // src/finalChange.ts
53836
- var import_node_child_process13 = require("node:child_process");
53837
- var import_node_fs26 = require("node:fs");
53838
- var import_node_path28 = require("node:path");
53839
- function changesAgainstBase(root, wanted) {
53840
- if (wanted.size === 0) return [];
53841
- const status = (0, import_node_child_process13.execFileSync)("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--no-renames"], {
54202
+ var import_node_child_process14 = require("node:child_process");
54203
+ var import_node_fs27 = require("node:fs");
54204
+ var import_node_path29 = require("node:path");
54205
+ function statusPaths(root) {
54206
+ const status = (0, import_node_child_process14.execFileSync)("git", ["status", "--porcelain", "-z", "--untracked-files=all", "--no-renames"], {
53842
54207
  cwd: root,
53843
54208
  encoding: "utf8",
53844
54209
  maxBuffer: 64 * 1024 * 1024
53845
54210
  });
53846
- const changed = new Set(
54211
+ return new Set(
53847
54212
  status.split("\0").filter((entry) => entry.length > 3).map((entry) => entry.slice(3))
53848
54213
  );
53849
- return [...wanted].sort().filter((path) => {
53850
- if (!changed.has(path)) return false;
53851
- try {
53852
- return (0, import_node_fs26.statSync)((0, import_node_path28.join)(root, path)).isFile();
53853
- } catch {
53854
- return false;
53855
- }
53856
- });
54214
+ }
54215
+ var isFileOnDisk = (root, path) => {
54216
+ try {
54217
+ return (0, import_node_fs27.statSync)((0, import_node_path29.join)(root, path)).isFile();
54218
+ } catch {
54219
+ return false;
54220
+ }
54221
+ };
54222
+ function changesAgainstBase(root, wanted) {
54223
+ if (wanted.size === 0) return [];
54224
+ const changed = statusPaths(root);
54225
+ return [...wanted].sort().filter((path) => changed.has(path) && isFileOnDisk(root, path));
54226
+ }
54227
+ var MAX_ALL_CHANGES = 2e3;
54228
+ function allChangesAgainstBase(root) {
54229
+ try {
54230
+ return [...statusPaths(root)].sort().filter((path) => isFileOnDisk(root, path)).slice(0, MAX_ALL_CHANGES);
54231
+ } catch {
54232
+ return [];
54233
+ }
53857
54234
  }
53858
54235
 
53859
54236
  // src/nameEvidence.ts
53860
- var import_node_child_process14 = require("node:child_process");
53861
- var import_node_fs27 = require("node:fs");
53862
- var import_node_path29 = require("node:path");
54237
+ var import_node_child_process15 = require("node:child_process");
54238
+ var import_node_fs28 = require("node:fs");
54239
+ var import_node_path30 = require("node:path");
53863
54240
 
53864
54241
  // src/migrationNames.ts
53865
54242
  var PART = String.raw`(?:"[^"]+"|\x60[^\x60]+\x60|\[[^\]]+\]|[\w$]+)`;
@@ -53924,7 +54301,7 @@ var escapeRegExp5 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
53924
54301
  function filesNaming(word, ev, readable, denied) {
53925
54302
  let out2;
53926
54303
  try {
53927
- out2 = (0, import_node_child_process14.execFileSync)("git", ["grep", "-l", "-I", "-w", "-F", "-e", word], {
54304
+ out2 = (0, import_node_child_process15.execFileSync)("git", ["grep", "-l", "-I", "-w", "-F", "-e", word], {
53928
54305
  cwd: ev.cwd,
53929
54306
  encoding: "utf8",
53930
54307
  stdio: ["ignore", "pipe", "ignore"],
@@ -53938,9 +54315,9 @@ function filesNaming(word, ev, readable, denied) {
53938
54315
  }
53939
54316
  function fileHasWord(cwd, file, word) {
53940
54317
  try {
53941
- const path = (0, import_node_path29.join)(cwd, file);
53942
- if ((0, import_node_fs27.statSync)(path).size > MAX_FILE_BYTES2) return false;
53943
- return new RegExp(`(?<![\\w$])${escapeRegExp5(word)}(?![\\w$])`).test((0, import_node_fs27.readFileSync)(path, "utf8"));
54318
+ const path = (0, import_node_path30.join)(cwd, file);
54319
+ if ((0, import_node_fs28.statSync)(path).size > MAX_FILE_BYTES2) return false;
54320
+ return new RegExp(`(?<![\\w$])${escapeRegExp5(word)}(?![\\w$])`).test((0, import_node_fs28.readFileSync)(path, "utf8"));
53944
54321
  } catch {
53945
54322
  return false;
53946
54323
  }
@@ -54037,7 +54414,7 @@ function listForCodegen(live, stored) {
54037
54414
  var TWO_PHASE_SKIPPED_NOTE = "Tests-first was skipped: this project's test command writes no per-test report, so QuikPilot could not tell which tests fail on the code as it was.";
54038
54415
  var TIMEOUT_WARNING = "QuikPilot could not list the project's test files in time, so it skipped the early check of where tests are placed.";
54039
54416
  function lateReportWarning(waitedSeconds, namedTestFiles) {
54040
- return `The project's test report was not ready after ${waitedSeconds} seconds, so QuikPilot listed the test files by their names (${namedTestFiles} found) and skipped the early check of where tests are placed.`;
54417
+ return `The project's test report was not ready after ${waitedSeconds} seconds, so QuikPilot skipped the early check of where tests are placed. ${namedTestFiles} files look like tests by their names; the names were counted, not used for that check.`;
54041
54418
  }
54042
54419
  async function resolveTestDiscovery(i3) {
54043
54420
  const now = i3.now ?? Date.now;
@@ -54588,7 +54965,7 @@ async function run2(env2) {
54588
54965
  await preloadLanguages(workspaceListing);
54589
54966
  const readCheckoutText2 = (path) => {
54590
54967
  try {
54591
- return (0, import_node_fs28.readFileSync)(path, "utf8");
54968
+ return (0, import_node_fs29.readFileSync)(path, "utf8");
54592
54969
  } catch {
54593
54970
  return null;
54594
54971
  }
@@ -54724,7 +55101,7 @@ async function run2(env2) {
54724
55101
  );
54725
55102
  }
54726
55103
  const codegenMode = mapMode ? "loop-tests" : resolveCodegenMode(process.env, packet.codegenMode);
54727
- const noteTaken = workspaceListing.includes(DATABASE_CHANGE_PATH) || scope.readListing.includes(DATABASE_CHANGE_PATH) || (0, import_node_fs28.existsSync)(DATABASE_CHANGE_PATH);
55104
+ const noteTaken = workspaceListing.includes(DATABASE_CHANGE_PATH) || scope.readListing.includes(DATABASE_CHANGE_PATH) || (0, import_node_fs29.existsSync)(DATABASE_CHANGE_PATH);
54728
55105
  const proposals = designParts.length > 0 && codegenMode === "loop-tests" && !noteTaken;
54729
55106
  if (designParts.some((p) => p.kind === "stored") && codegenMode === "loop-tests" && noteTaken) console.log(JSON.stringify({ event: "database_change.off", reason: "note_path_taken" }));
54730
55107
  if (designParts.length > 0) {
@@ -54847,6 +55224,7 @@ async function run2(env2) {
54847
55224
  const writeStartedAt = Date.now();
54848
55225
  const [timedBaseline, results] = await Promise.all([baselineRun, runCodegenStep(stepParams)]);
54849
55226
  const lastAttemptMs = Date.now() - writeStartedAt;
55227
+ console.log(JSON.stringify({ event: "timing", phase: "baseline", seconds: Math.round(timedBaseline.durationMs / 1e3), reportInTime: discovery.result.source === "live" }));
54850
55228
  if (timedBaseline.snapshot.timedOut === true && baselineLimit !== null) {
54851
55229
  console.log(JSON.stringify({ event: "baseline.timeout", limitSeconds: Math.round(baselineLimit / 1e3), jobMinutes: packet.guardrails.maxWallClockMinutes }));
54852
55230
  throw new Error(baselineTimeoutMessage(baselineLimit, packet.guardrails.maxWallClockMinutes));
@@ -54970,12 +55348,33 @@ async function run2(env2) {
54970
55348
  }
54971
55349
  if (designParts.length > 0) {
54972
55350
  const finalParts = partsForCode(designParts, targeting.targets, proposals ? { proposals: true } : {});
54973
- const changed = changesAgainstBase(process.cwd(), new Set(finalParts.flatMap((p) => p.paths)));
55351
+ const marked = changesAgainstBase(process.cwd(), new Set(finalParts.flatMap((p) => p.paths)));
55352
+ const wroteByAi = new Set(generatedResults.map((r) => r.targetPath));
55353
+ const changed = [.../* @__PURE__ */ new Set([...marked, ...allChangesAgainstBase(process.cwd()).filter((p) => wroteByAi.has(p))])];
55354
+ const isTestFile2 = testRule(discoveredTestsOf(codegenDiscovery));
55355
+ const trace = {
55356
+ cwd: process.cwd(),
55357
+ parts: finalParts,
55358
+ changed,
55359
+ read: readFromCheckout(process.cwd()),
55360
+ isTest: isTestFile2,
55361
+ deniedPaths: packet.guardrails.deniedPaths,
55362
+ readable: new Set(scope.readListing)
55363
+ };
54974
55364
  const proposalIds = dbParts.length > 0 ? codegenOut.databaseChange?.parts ?? [] : void 0;
54975
- const missing = missingAtDone(finalParts, changed, testRule(discoveredTestsOf(codegenDiscovery)), proposalIds);
55365
+ const missing = withoutMovedData(missingAtDone(finalParts, marked, isTestFile2, proposalIds), trace);
54976
55366
  const ids = missing.map((m) => m.part.id);
54977
55367
  console.log(JSON.stringify({ event: "parts_check.final", outcome: missing.length > 0 ? "missing" : "ok", missing: missing.length, ids }));
54978
55368
  if (missing.length > 0) throw new PartsStopError({ reason: "part_missing", ids, sentence: partMissingSentence(missing, { lastGate: true }) });
55369
+ const scanned = {};
55370
+ const dataGap = dataPathGap({
55371
+ onScan: (i3) => Object.assign(scanned, { files: i3.files.length, calls: i3.calls.length, ms: i3.ms }),
55372
+ ...trace
55373
+ });
55374
+ if (dataGap !== null) {
55375
+ warnings.push(dataPathWarning(dataGap));
55376
+ console.log(JSON.stringify({ event: "parts_check.data_path", outcome: "warned", ...scanned }));
55377
+ }
54979
55378
  }
54980
55379
  if (dbParts.length > 0 && codegenOut.databaseChange) {
54981
55380
  const proposal = codegenOut.databaseChange;