@quikit/quikpilot-runner 9.3.0-rc.42 → 9.3.0-rc.44

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
@@ -30592,6 +30592,35 @@ function parseProgram(path, text2) {
30592
30592
  }
30593
30593
 
30594
30594
  // src/testLocate.ts
30595
+ function allTests(file) {
30596
+ return [...file.tests, ...file.generated];
30597
+ }
30598
+ var PLACEHOLDER = /%[sdifjoOp#%]|\$(?:#|[A-Za-z_]\w*(?:\.\w+)*)/g;
30599
+ var escapeRegExp = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
30600
+ function titlePattern(title) {
30601
+ let source = "";
30602
+ let placeholders = false;
30603
+ let at2 = 0;
30604
+ for (const m of title.matchAll(PLACEHOLDER)) {
30605
+ const index = m.index ?? 0;
30606
+ source += escapeRegExp(title.slice(at2, index));
30607
+ if (m[0] === "%%") {
30608
+ source += "%";
30609
+ } else {
30610
+ source += ".*?";
30611
+ placeholders = true;
30612
+ }
30613
+ at2 = index + m[0].length;
30614
+ }
30615
+ return { source: source + escapeRegExp(title.slice(at2)), placeholders };
30616
+ }
30617
+ function nameEndsWithTitle(name, title) {
30618
+ return new RegExp(`(?:^|(?: > | \u203A | ))${titlePattern(title).source}$`, "s").test(name);
30619
+ }
30620
+ function rowPattern(test) {
30621
+ const parts = [...test.describes, test.title].map((s) => titlePattern(s).source);
30622
+ return new RegExp(`^(?:${parts.join("(?: > | \u203A | )")}|${parts[parts.length - 1]})$`, "s");
30623
+ }
30595
30624
  var TEST_ROOTS = /* @__PURE__ */ new Set(["it", "test"]);
30596
30625
  var X_ROOTS = /* @__PURE__ */ new Set(["xit", "xtest"]);
30597
30626
  var DESCRIBE_ROOTS = /* @__PURE__ */ new Set(["describe", "context", "suite"]);
@@ -30645,12 +30674,17 @@ function locateTests(path, text2) {
30645
30674
  const call = node;
30646
30675
  const chain = chainOf(call.callee);
30647
30676
  const title = chain ? titleOf(call) : null;
30648
- const each = call.callee.type === "CallExpression" ? chainOf(call.callee.callee) : null;
30677
+ const each = call.callee.type === "CallExpression" ? chainOf(call.callee.callee) : call.callee.type === "TaggedTemplateExpression" ? chainOf(call.callee.tag) : null;
30649
30678
  if (each) {
30650
30679
  innerDynamic = true;
30651
30680
  const eachTitle = titleOf(call);
30652
- if (eachTitle && DESCRIBE_ROOTS.has(each.root)) inner = [...describes, eachTitle.text];
30653
- else if (eachTitle) generated.push(located(call, eachTitle, describes, each.skipped));
30681
+ if (eachTitle && DESCRIBE_ROOTS.has(each.root)) {
30682
+ inner = [...describes, eachTitle.text];
30683
+ } else if (eachTitle) {
30684
+ const test = located(call, eachTitle, describes, each.skipped);
30685
+ const body = call.arguments[1];
30686
+ generated.push(body ? { ...test, bodyStartLine: lineAt(parsed.code, body.start) } : test);
30687
+ }
30654
30688
  }
30655
30689
  if (chain && title) {
30656
30690
  if (DESCRIBE_ROOTS.has(chain.root)) {
@@ -30777,12 +30811,14 @@ function testEditOverreach(input) {
30777
30811
  const after = locateTests(input.path, input.after);
30778
30812
  if (!before) return "the file could not be read before the edit";
30779
30813
  if (!after) return "the file can no longer be read after the edit";
30780
- if (after.tests.length !== before.tests.length) return "a test was added or removed";
30814
+ if (after.tests.length !== before.tests.length || after.generated.length !== before.generated.length) return "a test was added or removed";
30815
+ const beforeAll = allTests(before);
30816
+ const afterAll = allTests(after);
30781
30817
  const wasTests = [];
30782
30818
  const nowTests = [];
30783
30819
  for (const index of input.indexes) {
30784
- const was = before.tests[index];
30785
- const now = after.tests[index];
30820
+ const was = beforeAll[index];
30821
+ const now = afterAll[index];
30786
30822
  if (!was || !now) return "the test could not be found again after the edit";
30787
30823
  wasTests.push(was);
30788
30824
  nowTests.push(now);
@@ -32495,7 +32531,7 @@ var CONFLICT_CASE_FIELDS = ["given", "when", "then"];
32495
32531
  var REJECT_MESSAGES = {
32496
32532
  not_existing_test: "That is not an existing test file of this project that can be reported.",
32497
32533
  unsupported_language: "Only JavaScript and TypeScript test files can be reported.",
32498
- title_not_found: "No test with that title was found in that file. Copy the title exactly as the file writes it.",
32534
+ title_not_found: "No test with that title was found in that file. Copy the title exactly as the file writes it. For a test written once for each row of a table, that is the title in the file with its $name or %s placeholders as they are, not the name of one row.",
32499
32535
  title_not_unique: "More than one test in that file has that title, so it cannot be told which one you mean.",
32500
32536
  no_match: "find was not found in that file. Copy it exactly as read_file shows it.",
32501
32537
  ambiguous: "find matches more than once in that file. Make it longer so it matches once.",
@@ -32506,7 +32542,7 @@ var REJECT_MESSAGES = {
32506
32542
  still_passes_old_code: "With your replacement that test still passes on the code before this run, so it would not show the bug.",
32507
32543
  already_decided: "A person has already decided about that test. Do not report it again.",
32508
32544
  too_many_conflicts: "Too many tests have been reported already. Finish with what you have.",
32509
- generated_test: "That test is written once and run for each row of a table (describe.each or it.each), so a report cannot propose a change to it. 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."
32545
+ 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."
32510
32546
  };
32511
32547
  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.";
32512
32548
  var BOUNDS = { find: 8e3, replace: 2e4, title: 300, reason: 300, caseText: 1e3, value: 120, why: 300 };
@@ -32533,13 +32569,17 @@ function nameIsTitle(name, title, describes = []) {
32533
32569
  const full = [...describes, title];
32534
32570
  return name === title || name === full.join(" > ") || name === full.join(" ") || name === full.join(" \u203A ");
32535
32571
  }
32536
- function isRowsTitle(sent, title) {
32537
- return sent === title || [" > ", " \u203A ", " "].some((sep) => sent.endsWith(`${sep}${title}`) && sent.length > sep.length + title.length);
32538
- }
32539
32572
  function splitTestId(id) {
32540
32573
  const at2 = id.indexOf("::");
32541
32574
  return at2 === -1 ? { file: null, name: id } : { file: id.slice(0, at2), name: id.slice(at2 + 2) };
32542
32575
  }
32576
+ function matchRows(results, path, test) {
32577
+ const pattern = rowPattern(test);
32578
+ return [...results.entries()].filter(([id]) => {
32579
+ const { file, name } = splitTestId(id);
32580
+ return (file === null || sameFile(file, path)) && pattern.test(name);
32581
+ });
32582
+ }
32543
32583
  function text(v, min, max) {
32544
32584
  return typeof v === "string" && v.length >= min && v.length <= max ? v : null;
32545
32585
  }
@@ -32619,6 +32659,8 @@ var TestConflictTool = class {
32619
32659
  counts = { calls: 0, recorded: 0, rejected: 0 };
32620
32660
  rejectedBy = {};
32621
32661
  generated = /* @__PURE__ */ new Map();
32662
+ /** QUIKTR-1827: every test the AI has reported, whatever the answer was: the tests it has looked at and said something about. */
32663
+ reported = [];
32622
32664
  max;
32623
32665
  /** The reports that stand, one per test, in the order they were first made. */
32624
32666
  recorded() {
@@ -32628,6 +32670,10 @@ var TestConflictTool = class {
32628
32670
  unreportable() {
32629
32671
  return [...this.generated.values()];
32630
32672
  }
32673
+ /** QUIKTR-1827: where each test the AI reported is and the title it gave, answered or rejected. For the check on a give-up; never sent anywhere. */
32674
+ reportedTests() {
32675
+ return this.reported.map((r) => ({ ...r }));
32676
+ }
32631
32677
  /** Counts and closed words only, for the run's log. */
32632
32678
  record() {
32633
32679
  return { ...this.counts, rejectedBy: { ...this.rejectedBy } };
@@ -32649,6 +32695,7 @@ var TestConflictTool = class {
32649
32695
  const parsed = parseConflictReport(call.args, this.deps.caseIds);
32650
32696
  if (!parsed.ok) return finish({ status: "bad_args", message: `${parsed.field} is not valid for report_test_conflict.` });
32651
32697
  const report = parsed.report;
32698
+ if (!this.reported.some((r) => r.path === report.path && r.title === report.testTitle)) this.reported.push({ path: report.path, title: report.testTitle });
32652
32699
  const dupKey = `${call.name}:${JSON.stringify(report)}`;
32653
32700
  const earlier = ledger.seen.get(dupKey);
32654
32701
  if (earlier !== void 0) {
@@ -32680,31 +32727,31 @@ var TestConflictTool = class {
32680
32727
  if (!loaded.ok) return this.reject("not_existing_test");
32681
32728
  const located = locateTests(path.path, loaded.lf);
32682
32729
  if (!located) return this.reject("unsupported_language");
32683
- const matches = located.tests.map((t, index2) => ({ t, index: index2 })).filter(({ t }) => t.title === r.testTitle);
32684
- if (matches.length === 0) {
32685
- const rows = located.generated.find((t) => isRowsTitle(r.testTitle, t.title));
32686
- if (!rows) return this.reject("title_not_found");
32687
- const rowsKey = `${path.path}\0${rows.startLine}`;
32688
- if (!this.generated.has(rowsKey)) this.generated.set(rowsKey, { path: path.path, line: rows.startLine, caseId: r.caseId });
32689
- return this.reject("generated_test");
32690
- }
32730
+ const matches = allTests(located).map((t, index2) => ({ t, index: index2 })).filter(({ t }) => t.title === r.testTitle);
32731
+ if (matches.length === 0) return this.reject("title_not_found");
32691
32732
  if (matches.length > 1) return this.reject("title_not_unique");
32692
32733
  const { t: test, index } = matches[0];
32734
+ const isTable = index >= located.tests.length;
32693
32735
  const applied = applyEdits(loaded.lf, [{ find: r.find, replace: r.replace }]);
32694
32736
  if (!applied.ok) return this.reject(applied.refusals[0]?.kind === "ambiguous" ? "ambiguous" : "no_match");
32695
32737
  const at2 = loaded.lf.indexOf(r.find);
32696
32738
  const changeLine = lineAt(loaded.lf, at2);
32697
32739
  const lastLine = lineAt(loaded.lf, at2 + r.find.length - 1);
32698
- if (changeLine < test.startLine || lastLine > test.endLine) return this.reject("find_outside_test");
32740
+ if (changeLine < (test.bodyStartLine ?? test.startLine) || lastLine > test.endLine) return this.reject("find_outside_test");
32699
32741
  if (testEditOverreach({ path: path.path, before: loaded.lf, after: applied.content, indexes: [index] }) !== null) return this.reject("beyond_expectations");
32700
32742
  const base = await d.baseline().catch(() => null);
32701
32743
  const results = base?.snapshot.results ?? null;
32702
32744
  if (!base || base.snapshot.timedOut === true || !results) return this.reject("baseline_unknown");
32703
- const mine = [...results.entries()].filter(([id]) => {
32745
+ const mine = isTable ? matchRows(results, path.path, test) : [...results.entries()].filter(([id]) => {
32704
32746
  const { file, name } = splitTestId(id);
32705
32747
  return (file === null || sameFile(file, path.path)) && nameIsTitle(name, r.testTitle, test.describes);
32706
32748
  });
32707
- if (mine.length === 0) return this.reject("baseline_unknown");
32749
+ if (mine.length === 0) {
32750
+ if (!isTable) return this.reject("baseline_unknown");
32751
+ const rowsKey = `${path.path}\0${test.startLine}`;
32752
+ if (!this.generated.has(rowsKey)) this.generated.set(rowsKey, { path: path.path, line: test.startLine, caseId: r.caseId });
32753
+ return this.reject("generated_test");
32754
+ }
32708
32755
  if (mine.some(([, passed]) => !passed)) return this.reject("not_passing_before");
32709
32756
  const scrub = d.scrub ?? ((s) => s);
32710
32757
  const history = mapHistory((d.history ?? ((p, title) => readTestHistory({ path: p, title })))(path.path, r.testTitle), scrub);
@@ -32716,6 +32763,7 @@ var TestConflictTool = class {
32716
32763
  endLine: test.endLine,
32717
32764
  changeLine,
32718
32765
  index,
32766
+ ...isTable ? { rows: mine.length } : {},
32719
32767
  history,
32720
32768
  originalLf: loaded.lf,
32721
32769
  ending: loaded.ending,
@@ -32724,7 +32772,7 @@ var TestConflictTool = class {
32724
32772
  };
32725
32773
  this.byTest.set(key, conflict);
32726
32774
  this.counts.recorded += 1;
32727
- d.log?.({ event: "codegen.conflict_recorded", reading: r.reading, phase: d.phase ?? null, historyAvailable: history.available });
32775
+ d.log?.({ event: "codegen.conflict_recorded", reading: r.reading, phase: d.phase ?? null, historyAvailable: history.available, ...isTable ? { rows: mine.length } : {} });
32728
32776
  return { status: "conflict_recorded", message: RECORDED_MESSAGE, output: { history } };
32729
32777
  }
32730
32778
  };
@@ -32763,7 +32811,7 @@ function buildProposalFiles(conflicts) {
32763
32811
  ending: first.ending,
32764
32812
  bom: first.bom,
32765
32813
  conflicts: kept,
32766
- newTitles: new Map(kept.map((c) => [c.index, located.tests[c.index]?.title ?? c.testTitle]))
32814
+ newTitles: new Map(kept.map((c) => [c.index, allTests(located)[c.index]?.title ?? c.testTitle]))
32767
32815
  });
32768
32816
  }
32769
32817
  return { files, dropped };
@@ -32806,7 +32854,8 @@ function lineOf2(c, file) {
32806
32854
  reason: c.reason,
32807
32855
  correction: c.correction,
32808
32856
  history: c.history,
32809
- oldCodeChecked: c.oldCodeChecked === true
32857
+ oldCodeChecked: c.oldCodeChecked === true,
32858
+ ...c.rows !== void 0 ? { rows: c.rows } : {}
32810
32859
  };
32811
32860
  }
32812
32861
  function oneLine(s) {
@@ -32854,7 +32903,7 @@ function parseProposalMessage(message) {
32854
32903
  const o = j;
32855
32904
  const c = o.correction;
32856
32905
  const h = o.history;
32857
- if (o.v !== 1 || !isStr(o.path, 300) || !isStr(o.title, 300) || o.newTitle !== void 0 && !isStr(o.newTitle, 300) || !isStr(o.caseId, 64) || !CONFLICT_READINGS.includes(o.reading) || !isLine(o.startLine) || !isLine(o.endLine) || !isLine(o.changeLine) || !isStr(o.reason, 300) || typeof c !== "object" || c === null || !CONFLICT_CASE_FIELDS.includes(c.field) || !isStr(c.text, 1e3) || !isStr(c.why, 300) || typeof h !== "object" || h === null || typeof h.available !== "boolean" || typeof o.oldCodeChecked !== "boolean") {
32906
+ if (o.v !== 1 || !isStr(o.path, 300) || !isStr(o.title, 300) || o.newTitle !== void 0 && !isStr(o.newTitle, 300) || !isStr(o.caseId, 64) || !CONFLICT_READINGS.includes(o.reading) || !isLine(o.startLine) || !isLine(o.endLine) || !isLine(o.changeLine) || !isStr(o.reason, 300) || typeof c !== "object" || c === null || !CONFLICT_CASE_FIELDS.includes(c.field) || !isStr(c.text, 1e3) || !isStr(c.why, 300) || typeof h !== "object" || h === null || typeof h.available !== "boolean" || typeof o.oldCodeChecked !== "boolean" || o.rows !== void 0 && !(typeof o.rows === "number" && Number.isInteger(o.rows) && o.rows >= 1 && o.rows <= 1e4)) {
32858
32907
  continue;
32859
32908
  }
32860
32909
  out.push(o);
@@ -32901,6 +32950,7 @@ function conflictsReport(p) {
32901
32950
  caseId: l.caseId,
32902
32951
  reading: l.reading,
32903
32952
  oldCodeChecked: l.oldCodeChecked,
32953
+ ...l.rows !== void 0 ? { rows: l.rows } : {},
32904
32954
  ...l.history.available ? {
32905
32955
  history: {
32906
32956
  ...l.history.addedAt ? { addedAt: l.history.addedAt } : {},
@@ -32982,7 +33032,7 @@ function loadApprovedTests(input) {
32982
33032
  continue;
32983
33033
  }
32984
33034
  const before = locateTests(path, toLf(stripBom(current2)));
32985
- const indexes = mine.map((l) => before?.tests.findIndex((t) => t.title === l.title) ?? -1);
33035
+ const indexes = mine.map((l) => (before ? allTests(before) : []).findIndex((t) => t.title === l.title));
32986
33036
  if (!before || indexes.some((i2) => i2 < 0)) {
32987
33037
  warnings.push(`The tests proposed for change in ${path} were not found in it, so that change was not applied.`);
32988
33038
  continue;
@@ -33091,9 +33141,82 @@ async function describeQuikTrackFailure(res) {
33091
33141
  return `${res.status} ${res.statusText}`;
33092
33142
  }
33093
33143
 
33144
+ // src/fetchOnOwnClock.ts
33145
+ var import_node_http = __toESM(require("node:http"));
33146
+ var import_node_https = __toESM(require("node:https"));
33147
+ var NATIVE_FETCH = globalThis.fetch;
33148
+ var KEEP_ALIVE_INITIAL_DELAY_MS = 6e4;
33149
+ var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
33150
+ async function fetchOnOwnClock(url, init) {
33151
+ if (!init.signal || globalThis.fetch !== NATIVE_FETCH) return globalThis.fetch(url, init);
33152
+ return requestWithoutHeadersLimit(url, init, init.signal);
33153
+ }
33154
+ async function requestWithoutHeadersLimit(url, init, signal) {
33155
+ if (init.body != null && typeof init.body !== "string") throw new TypeError("fetchOnOwnClock sends a string body only");
33156
+ const target = new URL(url);
33157
+ const client = target.protocol === "http:" ? import_node_http.default : import_node_https.default;
33158
+ const headers = Object.fromEntries(new Headers(init.headers).entries());
33159
+ return new Promise((resolve6, reject) => {
33160
+ const fail = (err) => reject(signal.aborted ? signal.reason : err);
33161
+ const req = client.request(target, { method: init.method ?? "GET", headers, signal }, (res) => {
33162
+ const chunks = [];
33163
+ res.on("data", (chunk) => chunks.push(chunk));
33164
+ res.on("error", fail);
33165
+ res.on("end", () => {
33166
+ const status = res.statusCode ?? 0;
33167
+ const responseHeaders = new Headers();
33168
+ for (const [name, value] of Object.entries(res.headers)) {
33169
+ for (const one of Array.isArray(value) ? value : value === void 0 ? [] : [value]) responseHeaders.append(name, one);
33170
+ }
33171
+ try {
33172
+ resolve6(new Response(NULL_BODY_STATUSES.has(status) ? null : Buffer.concat(chunks), { status, statusText: res.statusMessage ?? "", headers: responseHeaders }));
33173
+ } catch (err) {
33174
+ reject(err);
33175
+ }
33176
+ });
33177
+ });
33178
+ req.on("socket", (socket) => socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY_MS));
33179
+ req.on("error", fail);
33180
+ req.end(typeof init.body === "string" ? init.body : void 0);
33181
+ });
33182
+ }
33183
+
33184
+ // src/retryFetch.ts
33185
+ var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([502, 503, 504]);
33186
+ var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "ETIMEDOUT"]);
33187
+ function networkErrorCode(err) {
33188
+ const code = err?.cause?.code ?? err?.code;
33189
+ return typeof code === "string" ? code : void 0;
33190
+ }
33191
+ function isRetryableNetworkError(err) {
33192
+ const code = networkErrorCode(err);
33193
+ return code !== void 0 && RETRYABLE_NETWORK_ERROR_CODES.has(code);
33194
+ }
33195
+ async function fetchWithRetry(url, init, { retries = 2, backoffMs = 250 } = {}) {
33196
+ for (let attempt2 = 0; ; attempt2++) {
33197
+ try {
33198
+ const res = await fetchOnOwnClock(url, init);
33199
+ if (RETRYABLE_STATUS_CODES.has(res.status) && attempt2 < retries) {
33200
+ await new Promise((r) => setTimeout(r, backoffMs));
33201
+ continue;
33202
+ }
33203
+ return res;
33204
+ } catch (err) {
33205
+ if (isRetryableNetworkError(err) && attempt2 < retries) {
33206
+ await new Promise((r) => setTimeout(r, backoffMs));
33207
+ continue;
33208
+ }
33209
+ throw err;
33210
+ }
33211
+ }
33212
+ }
33213
+
33094
33214
  // src/callback.ts
33215
+ var REPORT_RETRY_STATUSES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
33216
+ var REPORT_RETRY_WAITS_MS = [2e3, 5e3, 1e4];
33095
33217
  async function reportBack(params) {
33096
33218
  const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, testsCorrected, codegenLoop, unresolved, aiCostUsd, testConflicts, approvedTestsApplied } = params;
33219
+ const sleep = params.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
33097
33220
  const body = { status };
33098
33221
  if (branch) body.branch = branch;
33099
33222
  if (warnings && warnings.length > 0) body.warnings = warnings;
@@ -33108,13 +33231,34 @@ async function reportBack(params) {
33108
33231
  if (typeof aiCostUsd === "number" && Number.isFinite(aiCostUsd) && aiCostUsd > 0) body.aiCostUsd = Math.round(aiCostUsd * 1e6) / 1e6;
33109
33232
  if (testConflicts) body.testConflicts = testConflicts;
33110
33233
  if (approvedTestsApplied && approvedTestsApplied.length > 0) body.approvedTestsApplied = approvedTestsApplied;
33111
- const res = await fetch(callbackUrl, {
33112
- method: "POST",
33113
- headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
33114
- body: JSON.stringify(body)
33115
- });
33116
- if (!res.ok) {
33117
- throw new Error(`Report back to QuikTrack failed: ${await describeQuikTrackFailure(res)}`);
33234
+ const payload = JSON.stringify(body);
33235
+ const tries = REPORT_RETRY_WAITS_MS.length + 1;
33236
+ for (let attempt2 = 1; ; attempt2++) {
33237
+ let failure;
33238
+ let res;
33239
+ try {
33240
+ res = await fetch(callbackUrl, {
33241
+ method: "POST",
33242
+ headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
33243
+ body: payload
33244
+ });
33245
+ } catch (err) {
33246
+ if (!isRetryableNetworkError(err)) throw err;
33247
+ failure = `the connection failed (${networkErrorCode(err)})`;
33248
+ if (attempt2 === tries) throw new Error(`Report back to QuikTrack failed: ${failure} after ${tries} tries`);
33249
+ await waitBeforeRetry(failure, attempt2);
33250
+ continue;
33251
+ }
33252
+ if (res.ok) return;
33253
+ failure = await describeQuikTrackFailure(res);
33254
+ if (!REPORT_RETRY_STATUSES.has(res.status)) throw new Error(`Report back to QuikTrack failed: ${failure}`);
33255
+ if (attempt2 === tries) throw new Error(`Report back to QuikTrack failed: ${failure} after ${tries} tries`);
33256
+ await waitBeforeRetry(failure, attempt2);
33257
+ }
33258
+ async function waitBeforeRetry(failure, attempt2) {
33259
+ const waitMs = REPORT_RETRY_WAITS_MS[attempt2 - 1];
33260
+ console.warn(`::warning::Report back to QuikTrack failed: ${failure}; trying again in ${waitMs / 1e3} s (try ${attempt2 + 1} of ${tries})`);
33261
+ await sleep(waitMs);
33118
33262
  }
33119
33263
  }
33120
33264
 
@@ -33578,8 +33722,8 @@ async function reportToQuikTest(params) {
33578
33722
  try {
33579
33723
  console.log(`reporting ${report}`);
33580
33724
  const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
33581
- const { readFileSync: readFileSync18 } = await import("node:fs");
33582
- const body = readFileSync18(report);
33725
+ const { readFileSync: readFileSync19 } = await import("node:fs");
33726
+ const body = readFileSync19(report);
33583
33727
  let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
33584
33728
  if (generatedFiles) {
33585
33729
  url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
@@ -33606,6 +33750,66 @@ async function reportToQuikTest(params) {
33606
33750
  }
33607
33751
  }
33608
33752
 
33753
+ // src/giveUpCheck.ts
33754
+ var GIVE_UP_RULE = "give_up_rule";
33755
+ var GIVE_UP_MESSAGE = "Your answer was sent back once: existing tests your change broke are neither reported nor explained. Report each one that expects what a bug case calls wrong with report_test_conflict; otherwise change your code. Read the test file to see what it expects.";
33756
+ var MAX_SENTENCES = 8;
33757
+ var MAX_SENTENCE_CHARS = 300;
33758
+ var MAX_TITLE_CHARS = 150;
33759
+ var MAX_FILE_CHARS = 100;
33760
+ function lastPart(name) {
33761
+ const at2 = Math.max(name.lastIndexOf(" > "), name.lastIndexOf(" \u203A "));
33762
+ return at2 === -1 ? name : name.slice(at2 + 3);
33763
+ }
33764
+ function groupRegressions(ids) {
33765
+ const groups = /* @__PURE__ */ new Map();
33766
+ for (const id of ids) {
33767
+ const { file, name } = splitTestId(id);
33768
+ const title = lastPart(name);
33769
+ const key = `${file ?? ""}\0${title}`;
33770
+ const have = groups.get(key);
33771
+ if (have) have.rows += 1;
33772
+ else groups.set(key, { file: file ?? "", title, rows: 1 });
33773
+ }
33774
+ return [...groups.values()];
33775
+ }
33776
+ var samePlace = (a, b) => {
33777
+ const x = a.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
33778
+ const y = b.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
33779
+ return x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`);
33780
+ };
33781
+ function unexplainedRegressions(answer, reported) {
33782
+ if (answer.regressions <= 0) return [];
33783
+ const regressed = answer.failingTests.slice(0, answer.regressions);
33784
+ return groupRegressions(regressed).filter(
33785
+ (g) => !reported.some((r) => (g.file === "" || samePlace(g.file, r.path)) && nameEndsWithTitle(g.title, r.title))
33786
+ );
33787
+ }
33788
+ var clip2 = (s, max) => s.length <= max ? s : `${s.slice(0, max - 1)}\u2026`;
33789
+ function sentenceOf(g) {
33790
+ const rows = g.rows > 1 ? ` (${g.rows} rows)` : "";
33791
+ return clip2(`${g.file ? `${clip2(g.file, MAX_FILE_CHARS)}: ` : ""}"${clip2(g.title, MAX_TITLE_CHARS)}"${rows} passed before this run and fails now.`, MAX_SENTENCE_CHARS);
33792
+ }
33793
+ function giveUpSentences(groups) {
33794
+ if (groups.length <= MAX_SENTENCES) return groups.map(sentenceOf);
33795
+ const shown = groups.slice(0, MAX_SENTENCES - 1).map(sentenceOf);
33796
+ return [...shown, `${groups.length - (MAX_SENTENCES - 1)} more existing tests passed before this run and fail now.`];
33797
+ }
33798
+ function oldBehaviourSentence(groups, max = 600) {
33799
+ const parts = groups.map((g) => `${g.file ? `${g.file}: ` : ""}"${g.title}"${g.rows > 1 ? ` (${g.rows} rows)` : ""}`);
33800
+ return clip2(`existing tests that may expect the old behaviour: ${parts.join("; ")}`, max);
33801
+ }
33802
+ function withoutLoop7Words(previous) {
33803
+ if (!previous.steps?.some((s) => s.refused?.includes(GIVE_UP_RULE))) return previous;
33804
+ const steps = previous.steps.map((s) => {
33805
+ if (!s.refused?.includes(GIVE_UP_RULE)) return s;
33806
+ const { refused: refused2, ...rest } = s;
33807
+ const kept = refused2.filter((w) => w !== GIVE_UP_RULE);
33808
+ return kept.length > 0 ? { ...rest, refused: kept } : rest;
33809
+ });
33810
+ return { ...previous, steps };
33811
+ }
33812
+
33609
33813
  // src/regressionCheck.ts
33610
33814
  var import_node_fs7 = require("node:fs");
33611
33815
 
@@ -33864,7 +34068,7 @@ function checkForRegressions(baseline, after) {
33864
34068
  }
33865
34069
  return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText, failureWhere, failureDetail };
33866
34070
  }
33867
- function describeRegressions(check) {
34071
+ function describeRegressions(check, options = {}) {
33868
34072
  const withText = (id) => {
33869
34073
  const text2 = check.failureText.get(id);
33870
34074
  return text2 ? `${id} (${text2})` : id;
@@ -33872,7 +34076,7 @@ function describeRegressions(check) {
33872
34076
  const parts = [];
33873
34077
  if (check.regressions.length > 0) {
33874
34078
  parts.push(
33875
- `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(", ")}`
34079
+ options.existingTestsMayExpectOldBehaviour === true ? `${check.regressions.length} regression(s) (passed before, now fail), ${oldBehaviourSentence(groupRegressions(check.regressions), 700)}` : `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(", ")}`
33876
34080
  );
33877
34081
  }
33878
34082
  if (check.newFailures.length > 0) {
@@ -34363,6 +34567,21 @@ var IMPORTERS_PER_FILE = 20;
34363
34567
  var RELATED_SENTENCE = "Related tests only; the whole suite runs last.";
34364
34568
  var forward2 = (p) => p.split("\\").join("/");
34365
34569
  var unique = (xs) => [...new Set(xs)];
34570
+ function buildTestWorld(d) {
34571
+ const isTest = testRule(d.discoveredTests ?? null);
34572
+ const listing = new Set(d.listing);
34573
+ const corpus = new TestCorpus(
34574
+ listing,
34575
+ (rel) => {
34576
+ const text2 = d.readRel(rel);
34577
+ if (text2 === null) throw new Error("unreadable");
34578
+ return text2;
34579
+ },
34580
+ d.deniedPaths,
34581
+ isTest
34582
+ );
34583
+ return { listing, corpus, mapSpecifier: createAliasMapper({ readText: d.readRel, writeRoot: d.writeRoot }), readRel: d.readRel, isTest };
34584
+ }
34366
34585
  function relatedLimitMs(baselineMs) {
34367
34586
  if (baselineMs === null || !Number.isFinite(baselineMs)) return 3e5;
34368
34587
  return Math.min(RELATED_MAX_LIMIT_MS, Math.max(RELATED_MIN_LIMIT_MS, baselineMs));
@@ -34410,20 +34629,13 @@ function createRelatedPlanner(d) {
34410
34629
  }
34411
34630
  let world = null;
34412
34631
  function theWorld() {
34413
- if (world) return world;
34414
- const readRel = (rel) => readText(abs(rel));
34415
- const listing = new Set(d.listing);
34416
- const corpus = new TestCorpus(
34417
- listing,
34418
- (rel) => {
34419
- const text2 = readRel(rel);
34420
- if (text2 === null) throw new Error("unreadable");
34421
- return text2;
34422
- },
34423
- d.deniedPaths,
34424
- isTest
34425
- );
34426
- world = { listing, corpus, mapSpecifier: createAliasMapper({ readText: readRel, writeRoot: d.writeRoot }), readRel };
34632
+ world ??= buildTestWorld({
34633
+ listing: d.listing,
34634
+ deniedPaths: d.deniedPaths,
34635
+ writeRoot: d.writeRoot,
34636
+ discoveredTests: d.discoveredTests ?? null,
34637
+ readRel: (rel) => readText(abs(rel))
34638
+ });
34427
34639
  return world;
34428
34640
  }
34429
34641
  function findAlwaysRun() {
@@ -34792,72 +35004,6 @@ function scrubEntriesForModel(entries, secrets, keep) {
34792
35004
  });
34793
35005
  }
34794
35006
 
34795
- // src/fetchOnOwnClock.ts
34796
- var import_node_http = __toESM(require("node:http"));
34797
- var import_node_https = __toESM(require("node:https"));
34798
- var NATIVE_FETCH = globalThis.fetch;
34799
- var KEEP_ALIVE_INITIAL_DELAY_MS = 6e4;
34800
- var NULL_BODY_STATUSES = /* @__PURE__ */ new Set([204, 205, 304]);
34801
- async function fetchOnOwnClock(url, init) {
34802
- if (!init.signal || globalThis.fetch !== NATIVE_FETCH) return globalThis.fetch(url, init);
34803
- return requestWithoutHeadersLimit(url, init, init.signal);
34804
- }
34805
- async function requestWithoutHeadersLimit(url, init, signal) {
34806
- if (init.body != null && typeof init.body !== "string") throw new TypeError("fetchOnOwnClock sends a string body only");
34807
- const target = new URL(url);
34808
- const client = target.protocol === "http:" ? import_node_http.default : import_node_https.default;
34809
- const headers = Object.fromEntries(new Headers(init.headers).entries());
34810
- return new Promise((resolve6, reject) => {
34811
- const fail = (err) => reject(signal.aborted ? signal.reason : err);
34812
- const req = client.request(target, { method: init.method ?? "GET", headers, signal }, (res) => {
34813
- const chunks = [];
34814
- res.on("data", (chunk) => chunks.push(chunk));
34815
- res.on("error", fail);
34816
- res.on("end", () => {
34817
- const status = res.statusCode ?? 0;
34818
- const responseHeaders = new Headers();
34819
- for (const [name, value] of Object.entries(res.headers)) {
34820
- for (const one of Array.isArray(value) ? value : value === void 0 ? [] : [value]) responseHeaders.append(name, one);
34821
- }
34822
- try {
34823
- resolve6(new Response(NULL_BODY_STATUSES.has(status) ? null : Buffer.concat(chunks), { status, statusText: res.statusMessage ?? "", headers: responseHeaders }));
34824
- } catch (err) {
34825
- reject(err);
34826
- }
34827
- });
34828
- });
34829
- req.on("socket", (socket) => socket.setKeepAlive(true, KEEP_ALIVE_INITIAL_DELAY_MS));
34830
- req.on("error", fail);
34831
- req.end(typeof init.body === "string" ? init.body : void 0);
34832
- });
34833
- }
34834
-
34835
- // src/retryFetch.ts
34836
- var RETRYABLE_STATUS_CODES = /* @__PURE__ */ new Set([502, 503, 504]);
34837
- var RETRYABLE_NETWORK_ERROR_CODES = /* @__PURE__ */ new Set(["ECONNRESET", "ETIMEDOUT"]);
34838
- function isRetryableNetworkError(err) {
34839
- const code = err?.cause?.code ?? err?.code;
34840
- return typeof code === "string" && RETRYABLE_NETWORK_ERROR_CODES.has(code);
34841
- }
34842
- async function fetchWithRetry(url, init, { retries = 2, backoffMs = 250 } = {}) {
34843
- for (let attempt2 = 0; ; attempt2++) {
34844
- try {
34845
- const res = await fetchOnOwnClock(url, init);
34846
- if (RETRYABLE_STATUS_CODES.has(res.status) && attempt2 < retries) {
34847
- await new Promise((r) => setTimeout(r, backoffMs));
34848
- continue;
34849
- }
34850
- return res;
34851
- } catch (err) {
34852
- if (isRetryableNetworkError(err) && attempt2 < retries) {
34853
- await new Promise((r) => setTimeout(r, backoffMs));
34854
- continue;
34855
- }
34856
- throw err;
34857
- }
34858
- }
34859
- }
34860
-
34861
35007
  // src/codegen.ts
34862
35008
  var FILE_TOO_LARGE_CODE = "CODEGEN_FILE_TOO_LARGE";
34863
35009
  var CONTEXT_TOO_LARGE_CODE = "CODEGEN_CONTEXT_TOO_LARGE";
@@ -35727,7 +35873,7 @@ function wholeFailure(text2, where, max) {
35727
35873
  return `${safe.slice(0, max - 1)}\u2026`;
35728
35874
  }
35729
35875
  var normalisePath = (p) => p.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
35730
- function samePlace(a, b) {
35876
+ function samePlace2(a, b) {
35731
35877
  const x = normalisePath(a);
35732
35878
  const y = normalisePath(b);
35733
35879
  return x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`);
@@ -35738,7 +35884,7 @@ function ownFailureIds(newFailures, changedPaths, requiredIds) {
35738
35884
  const sep = id.indexOf("::");
35739
35885
  const file = sep >= 0 ? id.slice(0, sep) : "";
35740
35886
  const name = sep >= 0 ? id.slice(sep + 2) : id;
35741
- const inChangedFile = file !== "" && changedPaths.some((p) => samePlace(file, p));
35887
+ const inChangedFile = file !== "" && changedPaths.some((p) => samePlace2(file, p));
35742
35888
  const hasToken = requiredIds.some((t) => name.includes(`[${t}]`));
35743
35889
  if (inChangedFile || hasToken) own.add(id);
35744
35890
  }
@@ -40858,7 +41004,7 @@ function withUnreportable(stop, tests) {
40858
41004
  if (stop.summary) carried.summary = stop.summary;
40859
41005
  return carried;
40860
41006
  }
40861
- function samePlace2(a, b) {
41007
+ function samePlace3(a, b) {
40862
41008
  const x = a.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
40863
41009
  const y = b.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
40864
41010
  return x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`);
@@ -40997,6 +41143,7 @@ async function runCodegenLoop(args, deps) {
40997
41143
  const redRuns = [];
40998
41144
  let redRefusals = 0;
40999
41145
  let importRefusals = 0;
41146
+ let giveUpRefusals = 0;
41000
41147
  let redUnproven;
41001
41148
  const currentRedRuns = () => {
41002
41149
  const now2 = versionOfFiles(filesOnDisk());
@@ -41037,11 +41184,15 @@ async function runCodegenLoop(args, deps) {
41037
41184
  let noProgressStreak = 0;
41038
41185
  let forced = null;
41039
41186
  const started = now();
41187
+ let toCheckList = null;
41188
+ const toCheck = () => toCheckList ??= (args.testsToCheck?.() ?? []).slice(0, 10);
41040
41189
  const buildContext = (turn, isFinal, finalReason) => ({
41041
41190
  ...args.baseContext,
41042
41191
  contractVersion,
41043
41192
  // QUIKTR-1717 (§38.6): what a person has already decided about existing tests. Loop-7 only, and only when there is something to say.
41044
41193
  ...conflictTool && args.conflicts && args.conflicts.decided.length > 0 ? { decidedTests: args.conflicts.decided } : {},
41194
+ // QUIKTR-1827 (§38.8): the existing test files to read first. The tests phase of loop-7 only.
41195
+ ...conflictTool && args.phase === "tests" && toCheck().length > 0 ? { testsToCheck: toCheck() } : {},
41045
41196
  loop: {
41046
41197
  turn,
41047
41198
  maxTurns: limits.maxTurns,
@@ -41049,7 +41200,8 @@ async function runCodegenLoop(args, deps) {
41049
41200
  ...isFinal ? { finalReason } : {},
41050
41201
  // Says this runner can carry a REFUSED answer (24.12a). Without it the runtime fails the request, as it always did.
41051
41202
  acceptsRefused: true,
41052
- ...previousAttempt ? { previousAttempt } : {},
41203
+ // QUIKTR-1827: a request below loop-7 is refused for a rule word only loop-7 raises, so the earlier attempt's steps are told without it.
41204
+ ...previousAttempt ? { previousAttempt: conflictTool ? previousAttempt : withoutLoop7Words(previousAttempt) } : {},
41053
41205
  // QUIKTR-1608 (§33): the phase, and the tests a disagreement step may amend. Harness version only.
41054
41206
  ...harness && args.phase ? { phase: args.phase } : {},
41055
41207
  ...harness && args.phase === "code" && args.lane?.kind === "code" && args.lane.amend ? { amend: args.lane.amend } : {},
@@ -41244,6 +41396,19 @@ async function runCodegenLoop(args, deps) {
41244
41396
  if (conflictTool && conflictTool.unreportable().length > 0) {
41245
41397
  throw unreportableFailure(conflictTool.unreportable(), new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said));
41246
41398
  }
41399
+ const unexplained = conflictTool && lastTestAnswer ? unexplainedRegressions(lastTestAnswer, conflictTool.reportedTests()) : [];
41400
+ if (unexplained.length > 0 && giveUpRefusals < 1 && !isFinal) {
41401
+ giveUpRefusals += 1;
41402
+ const answer = { rules: [GIVE_UP_RULE], violations: giveUpSentences(unexplained), message: GIVE_UP_MESSAGE };
41403
+ refusedStreak += 1;
41404
+ refusedTurns.push({ turn, rules: answer.rules });
41405
+ log({ event: "codegen.give_up_check", turn, outcome: "sent_back", tests: unexplained.length });
41406
+ transcript.push({ turn, toolCalls: [], refused: answer });
41407
+ if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
41408
+ forced = settleNextTurn(turn, forced);
41409
+ continue;
41410
+ }
41411
+ if (unexplained.length > 0) log({ event: "codegen.give_up_check", turn, outcome: "gave_up_again", tests: unexplained.length });
41247
41412
  const last = lastTestAnswer;
41248
41413
  const redLeft = harness && args.phase === "tests" ? redProblem() : null;
41249
41414
  if (harness && args.phase === "tests" && currentRedRuns().some((r) => r.failing.length > 0) && handOverRefusal(turn, true) === null && (redLeft === null || redLeft.kind === "passing")) {
@@ -41255,7 +41420,7 @@ async function runCodegenLoop(args, deps) {
41255
41420
  log({ event: "codegen.loop_kept", files: overlay.changedPaths().length, regressions: last.regressions, newFailures: last.newFailures });
41256
41421
  return { results: overlay.results(), summary: snapshot("gave_up_kept"), doneSummary: said ?? "", gaveUp: true, steps: sentSteps(), ...lastTestAnswer ? { lastTestAnswer } : {} };
41257
41422
  }
41258
- throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said);
41423
+ throw new CodegenLoopFailure("cannot_complete", void 0, void 0, unexplained.length > 0 ? oldBehaviourSentence(unexplained, MAX_PREVIOUS_DETAIL_CHARS) : said, said);
41259
41424
  }
41260
41425
  if (body.outcome === "DONE") {
41261
41426
  log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
@@ -41330,7 +41495,7 @@ async function runCodegenLoop(args, deps) {
41330
41495
  const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
41331
41496
  const lane = args.lane;
41332
41497
  if (harness && args.phase === "code" && lane?.kind === "code" && !lane.amend && args.keepOnGiveUp === true) {
41333
- const red2 = currentRedRuns().filter((r) => r.failing.some((name) => lane.frozen.some((p) => samePlace2(name.split("::")[0] ?? "", p)))).at(-1);
41498
+ const red2 = currentRedRuns().filter((r) => r.failing.some((name) => lane.frozen.some((p) => samePlace3(name.split("::")[0] ?? "", p)))).at(-1);
41334
41499
  if (red2) {
41335
41500
  log({ event: "codegen.loop_kept", files: overlay.changedPaths().length, regressions: red2.answer.regressions, newFailures: red2.answer.newFailures, after: "done" });
41336
41501
  return { results: overlay.results(), summary: snapshot("gave_up_kept"), doneSummary, gaveUp: true, steps: sentSteps(), lastTestAnswer: red2.answer };
@@ -41590,11 +41755,11 @@ async function runPhases(i2) {
41590
41755
  }
41591
41756
  const frozenFailing = (d2.lastTestAnswer?.failingTests ?? []).filter((name) => {
41592
41757
  const file2 = name.split("::")[0] ?? "";
41593
- return file2 !== "" && tests.frozen.some((path2) => samePlace2(file2, path2));
41758
+ return file2 !== "" && tests.frozen.some((path2) => samePlace3(file2, path2));
41594
41759
  });
41595
41760
  const token = frozenFailing.length === 1 && d2.lastTestAnswer?.truncated !== true ? QP_TOKEN.exec(frozenFailing[0])?.[0] : void 0;
41596
41761
  const file = token ? frozenFailing[0].split("::")[0] ?? "" : "";
41597
- const amend = token ? tests.frozen.filter((path2) => samePlace2(file, path2)).slice(0, 1) : [];
41762
+ const amend = token ? tests.frozen.filter((path2) => samePlace3(file, path2)).slice(0, 1) : [];
41598
41763
  phases.push(record("code", "gave_up", d2.summary));
41599
41764
  i2.log({ event: "codegen.phase_end", attempt: i2.attempt, phase: "code", outcome: "gave_up", amendFiles: amend.length, frozenFailing: frozenFailing.length });
41600
41765
  if (amend.length === 0 || !token) return { done: d2, tests, phases, summaries };
@@ -41914,8 +42079,8 @@ function pairedTestPaths(codePath, listing, isTest = isTestTarget) {
41914
42079
  const stem = m[1].toLowerCase();
41915
42080
  const dir = dirOf(codePath);
41916
42081
  const parent = parentOf(dir);
41917
- const join14 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
41918
- const homes = /* @__PURE__ */ new Set([dir, join14(dir, "__tests__"), join14(parent, "__tests__"), join14(parent, "tests"), join14(parent, "test")]);
42082
+ const join15 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
42083
+ const homes = /* @__PURE__ */ new Set([dir, join15(dir, "__tests__"), join15(parent, "__tests__"), join15(parent, "tests"), join15(parent, "test")]);
41919
42084
  const found = [];
41920
42085
  for (const path of listing) {
41921
42086
  if (!homes.has(dirOf(path))) continue;
@@ -42094,13 +42259,14 @@ function mapModeMessage(phase, reason) {
42094
42259
  var CUT_AT = 190;
42095
42260
  function failingNameIs(id, file, conflict) {
42096
42261
  const { file: where, name } = splitTestId(id);
42097
- if (where !== null && !samePlace3(where, file.path)) return false;
42262
+ if (where !== null && !samePlace4(where, file.path)) return false;
42098
42263
  const title = file.newTitles.get(conflict.index) ?? conflict.testTitle;
42264
+ if (conflict.rows !== void 0) return rowPattern({ describes: conflict.describes, title }).test(name);
42099
42265
  const full = [...conflict.describes, title];
42100
42266
  const candidates = [title, full.join(" > "), full.join(" "), full.join(" \u203A ")];
42101
42267
  return candidates.includes(name) || name.length >= CUT_AT && candidates.some((c) => c.startsWith(name));
42102
42268
  }
42103
- function samePlace3(a, b) {
42269
+ function samePlace4(a, b) {
42104
42270
  const x = a.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
42105
42271
  const y = b.replace(/\\/g, "/").replace(/^(\.\/)+/, "");
42106
42272
  return x === y || x.endsWith(`/${y}`) || y.endsWith(`/${x}`);
@@ -42140,6 +42306,34 @@ async function verifyOnOldCode(conflicts, run2, log = () => void 0) {
42140
42306
  return { kept, dropped };
42141
42307
  }
42142
42308
 
42309
+ // src/testsToCheck.ts
42310
+ var import_node_fs16 = require("node:fs");
42311
+ var import_node_path18 = require("node:path");
42312
+ var MAX_TESTS_TO_CHECK = 10;
42313
+ function testsToCheck(i2) {
42314
+ const limit = Math.min(MAX_TESTS_TO_CHECK, Math.max(0, i2.limit ?? MAX_TESTS_TO_CHECK));
42315
+ const world = buildTestWorld(i2);
42316
+ const code = i2.targets.filter((t) => t.kind === "EXISTING" && !world.isTest(t.path) && (t.automationIds?.length ?? 0) === 0);
42317
+ if (code.length === 0 || limit === 0) return [];
42318
+ const taken = new Set(i2.targets.map((t) => t.path));
42319
+ const out = [];
42320
+ const add = (path) => {
42321
+ if (out.length < limit && !taken.has(path) && !out.includes(path)) out.push(path);
42322
+ };
42323
+ for (const t of code) for (const path of pairedTestPaths(t.path, world.listing, world.isTest)) add(path);
42324
+ for (const t of code) {
42325
+ for (const path of testsImporting({ target: t.path, listing: world.listing, corpus: world.corpus, mapSpecifier: world.mapSpecifier, limit, isTest: world.isTest })) add(path);
42326
+ }
42327
+ return out;
42328
+ }
42329
+ var readFromRoot = (root) => (rel) => {
42330
+ try {
42331
+ return (0, import_node_fs16.readFileSync)((0, import_node_path18.join)(root, rel), "utf8");
42332
+ } catch {
42333
+ return null;
42334
+ }
42335
+ };
42336
+
42143
42337
  // src/codegenStep.ts
42144
42338
  function testTargetPaths(targets, discoveredTests) {
42145
42339
  const isTest = testRule(discoveredTests);
@@ -42200,6 +42394,26 @@ function orderProtectedForWire(protectedPaths, targetPaths, shownTests) {
42200
42394
  keyed.sort((a, b) => a.tier - b.tier || b.near - a.near || (a.path < b.path ? -1 : a.path > b.path ? 1 : 0));
42201
42395
  return keyed.map((k) => k.path);
42202
42396
  }
42397
+ function testsToCheckOf(p) {
42398
+ const tests = p.tests;
42399
+ if (!tests) return {};
42400
+ return {
42401
+ testsToCheck: () => {
42402
+ try {
42403
+ const read = p.readFile ? (rel) => {
42404
+ try {
42405
+ return p.readFile(rel);
42406
+ } catch {
42407
+ return null;
42408
+ }
42409
+ } : readFromRoot(tests.root);
42410
+ return testsToCheck({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, writeRoot: p.writeRoot ?? "", discoveredTests: discoveredTestsOf(p.testDiscovery) ?? null, readRel: read });
42411
+ } catch {
42412
+ return [];
42413
+ }
42414
+ }
42415
+ };
42416
+ }
42203
42417
  function buildCodegenLoopArgs(p, context = collectLoopContext({
42204
42418
  targets: p.targets,
42205
42419
  listing: p.workspaceListing,
@@ -42256,7 +42470,7 @@ function buildCodegenLoopArgs(p, context = collectLoopContext({
42256
42470
  ...p.mode === "loop-tests" && p.tests && p.harness !== false ? { harness: true } : {},
42257
42471
  ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2 ? { tools2: p.tools2 } : {},
42258
42472
  ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.callFunction ? { callFunction: p.callFunction } : {},
42259
- ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2?.notes === true && p.conflicts ? { conflicts: p.conflicts } : {},
42473
+ ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2?.notes === true && p.conflicts ? { conflicts: p.conflicts, ...testsToCheckOf(p) } : {},
42260
42474
  // An approved test change stands whatever version the AI Runtime speaks: a person decided it.
42261
42475
  ...p.approved && p.approved.length > 0 ? { approved: p.approved.map((r) => ({ targetPath: r.targetPath, newContent: r.newContent })) } : {}
42262
42476
  };
@@ -42320,6 +42534,23 @@ function oldCodeRunner(args, log, now) {
42320
42534
  return isTestAnswer(answer.output) ? answer.output : null;
42321
42535
  };
42322
42536
  }
42537
+ async function settleConflictStop(p, args, stop, clock) {
42538
+ const run2 = args?.tests && clock.now() < clock.hardStopAtMs ? oldCodeRunner(args, clock.log, clock.now) : null;
42539
+ const verified = await verifyOnOldCode(stop.conflicts, run2, clock.log);
42540
+ clock.log({ event: "codegen.conflict_stop", reported: stop.conflicts.length, standing: verified.kept.length, dropped: verified.dropped.length });
42541
+ if (verified.kept.length === 0) return null;
42542
+ const settled = new TestConflictStop(verified.kept, stop.fallback);
42543
+ if (stop.summary) {
42544
+ settled.summary = stop.summary;
42545
+ p.out.loop = buildCodegenLoopRecord({ ...stop.summary, stopReason: "test_conflict" });
42546
+ }
42547
+ return settled;
42548
+ }
42549
+ function warnUnreportable(p, stop) {
42550
+ for (const t of stop.unreportable) {
42551
+ warn(p, `Another existing test, in ${t.path} line ${t.line}, also expects what case ${t.caseId} calls wrong. It is written once for many rows, so no change to it was proposed: look at it before you approve.`);
42552
+ }
42553
+ }
42323
42554
  async function runCodegenStep(p) {
42324
42555
  if (p.mode !== "loop" && p.mode !== "loop-tests") return perFile(p);
42325
42556
  const testSetup = p.mode === "loop-tests" ? p.tests : void 0;
@@ -42395,9 +42626,7 @@ async function runCodegenStep(p) {
42395
42626
  if (err instanceof TestConflictStop) {
42396
42627
  const settled = await settleStop(err);
42397
42628
  if (settled) {
42398
- for (const t of err.unreportable) {
42399
- warn(p, `Another existing test, in ${t.path} line ${t.line}, also expects what case ${t.caseId} calls wrong. It is written once for many rows, so no change to it was proposed: look at it before you approve.`);
42400
- }
42629
+ warnUnreportable(p, err);
42401
42630
  throw settled;
42402
42631
  }
42403
42632
  return { failure: err.fallback instanceof CodegenLoopFailure ? err.fallback : new CodegenLoopFailure("cannot_complete") };
@@ -42407,16 +42636,7 @@ async function runCodegenStep(p) {
42407
42636
  };
42408
42637
  const settleStop = async (stop) => {
42409
42638
  await guardTree();
42410
- const run2 = args?.tests && now() < hardStopAtMs ? oldCodeRunner(args, log, now) : null;
42411
- const verified = await verifyOnOldCode(stop.conflicts, run2, log);
42412
- log({ event: "codegen.conflict_stop", reported: stop.conflicts.length, standing: verified.kept.length, dropped: verified.dropped.length });
42413
- if (verified.kept.length === 0) return null;
42414
- const settled = new TestConflictStop(verified.kept, stop.fallback);
42415
- if (stop.summary) {
42416
- settled.summary = stop.summary;
42417
- p.out.loop = buildCodegenLoopRecord({ ...stop.summary, stopReason: "test_conflict" });
42418
- }
42419
- return settled;
42639
+ return settleConflictStop(p, args, stop, { log, now, hardStopAtMs });
42420
42640
  };
42421
42641
  const finish = (done, attempts) => {
42422
42642
  if (done.steps && done.steps.steps.length > 0) p.out.steps = done.steps;
@@ -42522,7 +42742,7 @@ async function runCodegenStep(p) {
42522
42742
  }
42523
42743
 
42524
42744
  // src/codegenHeal.ts
42525
- var import_node_fs16 = require("node:fs");
42745
+ var import_node_fs17 = require("node:fs");
42526
42746
 
42527
42747
  // src/heal.ts
42528
42748
  var MAX_ATTEMPTS_IN_ALL = 3;
@@ -42588,7 +42808,7 @@ async function runHealAttempt(i2) {
42588
42808
  const created = i2.results.map((r) => r.targetPath).filter((path) => !listed.has(path));
42589
42809
  const workspaceListing = [...p.workspaceListing, ...created];
42590
42810
  const targets = p.targets.map((t) => t.kind === "NEW_FILE" && keptText.has(t.path) ? { ...t, kind: "EXISTING" } : t);
42591
- const disk = p.readFile ?? ((path) => (0, import_node_fs16.readFileSync)(path, "utf8"));
42811
+ const disk = p.readFile ?? ((path) => (0, import_node_fs17.readFileSync)(path, "utf8"));
42592
42812
  const readFile = (path) => keptText.get(path) ?? disk(path);
42593
42813
  const discoveredTests = discoveredTestsOf(p.testDiscovery);
42594
42814
  const context = collectLoopContext({ targets, listing: workspaceListing, deniedPaths: p.deniedPaths, writeRoot: p.writeRoot ?? "", ...discoveredTests ? { discoveredTests } : {}, readFile });
@@ -42597,7 +42817,7 @@ async function runHealAttempt(i2) {
42597
42817
  collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, writeRoot: p.writeRoot ?? "", ...discoveredTests ? { discoveredTests } : {}, readFile: disk })
42598
42818
  );
42599
42819
  const args = buildCodegenLoopArgs({ ...p, targets, workspaceListing }, context);
42600
- delete args.conflicts;
42820
+ if (i2.review !== void 0 || i2.answer.regressions <= 0) delete args.conflicts;
42601
42821
  args.protectedTestPaths = original.protectedTestPaths;
42602
42822
  if (original.baseContext.protectedTestPaths !== void 0) args.baseContext.protectedTestPaths = original.baseContext.protectedTestPaths;
42603
42823
  else delete args.baseContext.protectedTestPaths;
@@ -42630,6 +42850,18 @@ async function runHealAttempt(i2) {
42630
42850
  if (done.steps && done.steps.steps.length > 0) p.out.steps = done.steps;
42631
42851
  return done.results;
42632
42852
  } catch (err) {
42853
+ if (err instanceof TestConflictStop) {
42854
+ i2.out.summary = err.summary;
42855
+ const log = p.deps?.log ?? ((e) => console.log(JSON.stringify(e)));
42856
+ const settled = await settleConflictStop(p, args, err, { log, now, hardStopAtMs: i2.hardStopAtMs });
42857
+ if (settled) {
42858
+ warnUnreportable(p, err);
42859
+ throw settled;
42860
+ }
42861
+ const failure = err.fallback instanceof CodegenLoopFailure ? err.fallback : new CodegenLoopFailure("cannot_complete");
42862
+ i2.out.failure = failure;
42863
+ throw failure;
42864
+ }
42633
42865
  if (err instanceof CodegenLoopFailure) {
42634
42866
  i2.out.failure = err;
42635
42867
  i2.out.summary = err.summary;
@@ -42831,11 +43063,11 @@ async function runVerifyAndFix(p) {
42831
43063
 
42832
43064
  // src/hunkCheck.ts
42833
43065
  var import_node_child_process9 = require("node:child_process");
42834
- var import_node_fs18 = require("node:fs");
42835
- var import_node_path18 = require("node:path");
43066
+ var import_node_fs19 = require("node:fs");
43067
+ var import_node_path19 = require("node:path");
42836
43068
 
42837
43069
  // src/scopeCheck.ts
42838
- var import_node_fs17 = require("node:fs");
43070
+ var import_node_fs18 = require("node:fs");
42839
43071
  var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
42840
43072
  var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
42841
43073
  var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
@@ -42882,7 +43114,7 @@ function checkApiScope(results, targets, apiChanges) {
42882
43114
  } else {
42883
43115
  let currentContent;
42884
43116
  try {
42885
- currentContent = (0, import_node_fs17.readFileSync)(targetPath, "utf8");
43117
+ currentContent = (0, import_node_fs18.readFileSync)(targetPath, "utf8");
42886
43118
  } catch {
42887
43119
  currentContent = "";
42888
43120
  }
@@ -42978,7 +43210,7 @@ async function runHunkCheck(input) {
42978
43210
  let slowestRunMs = input.baselineMs ?? 3e4;
42979
43211
  const runOnce = async (c) => {
42980
43212
  const reportBefore = findReport(input.root);
42981
- const preserve = reportBefore ? [(0, import_node_path18.relative)(input.root, reportBefore).split("\\").join("/")] : [];
43213
+ const preserve = reportBefore ? [(0, import_node_path19.relative)(input.root, reportBefore).split("\\").join("/")] : [];
42982
43214
  const content = `${c.bom ? "\uFEFF" : ""}${fromLf(revertHunk(c.originalLf, c.currentLf, c.hunk), c.ending)}`;
42983
43215
  const startedWall = Date.now();
42984
43216
  const startedAt = now();
@@ -42988,13 +43220,13 @@ async function runHunkCheck(input) {
42988
43220
  input.root,
42989
43221
  [{ path: c.file, content }],
42990
43222
  async () => {
42991
- if (reportBefore) (0, import_node_fs18.rmSync)(reportBefore, { force: true });
43223
+ if (reportBefore) (0, import_node_fs19.rmSync)(reportBefore, { force: true });
42992
43224
  const run2 = await runCommand2(input.command, perRunMs, input.root);
42993
43225
  if (!run2.started || run2.timedOut) return "unknown";
42994
43226
  const report = findReport(input.root);
42995
43227
  if (!report) return "unknown";
42996
43228
  try {
42997
- if ((0, import_node_fs18.statSync)(report).mtimeMs < startedWall - FRESH_SLACK_MS3) return "unknown";
43229
+ if ((0, import_node_fs19.statSync)(report).mtimeMs < startedWall - FRESH_SLACK_MS3) return "unknown";
42998
43230
  } catch {
42999
43231
  return "unknown";
43000
43232
  }
@@ -43014,7 +43246,7 @@ async function runHunkCheck(input) {
43014
43246
  };
43015
43247
  const runRelated = async (c, plan, limitMs) => {
43016
43248
  const reportBefore = findReport(input.root);
43017
- const preserve = reportBefore ? [(0, import_node_path18.relative)(input.root, reportBefore).split("\\").join("/")] : [];
43249
+ const preserve = reportBefore ? [(0, import_node_path19.relative)(input.root, reportBefore).split("\\").join("/")] : [];
43018
43250
  const content = `${c.bom ? "\uFEFF" : ""}${fromLf(revertHunk(c.originalLf, c.currentLf, c.hunk), c.ending)}`;
43019
43251
  const startedAt = now();
43020
43252
  result.relatedRuns += 1;
@@ -43023,7 +43255,7 @@ async function runHunkCheck(input) {
43023
43255
  input.root,
43024
43256
  [{ path: c.file, content }],
43025
43257
  async () => {
43026
- (0, import_node_fs18.rmSync)(plan.report, { force: true });
43258
+ (0, import_node_fs19.rmSync)(plan.report, { force: true });
43027
43259
  try {
43028
43260
  const run2 = await runCommand2(plan.command, limitMs, plan.cwd);
43029
43261
  if (!run2.started || run2.timedOut) return "unknown";
@@ -43031,7 +43263,7 @@ async function runHunkCheck(input) {
43031
43263
  if (!after.results || after.results.size === 0) return "unknown";
43032
43264
  return checkForRegressions(input.baseline, after).blocked ? "needed" : "unneeded";
43033
43265
  } finally {
43034
- (0, import_node_fs18.rmSync)(plan.report, { force: true });
43266
+ (0, import_node_fs19.rmSync)(plan.report, { force: true });
43035
43267
  }
43036
43268
  },
43037
43269
  { ...input.tree, preserve }
@@ -43158,8 +43390,8 @@ function healFailureSuffix(heal) {
43158
43390
  }
43159
43391
 
43160
43392
  // src/dependencyCheck.ts
43161
- var import_node_fs19 = require("node:fs");
43162
- var import_node_path19 = require("node:path");
43393
+ var import_node_fs20 = require("node:fs");
43394
+ var import_node_path20 = require("node:path");
43163
43395
  var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
43164
43396
  var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
43165
43397
  var NODE_BUILTINS = /* @__PURE__ */ new Set([
@@ -43247,14 +43479,14 @@ function dependencyNames(pkg) {
43247
43479
  ]);
43248
43480
  }
43249
43481
  function readDeclaredDependencies(results, workspaceRoot) {
43250
- const packageJsonPath = (0, import_node_path19.join)((0, import_node_path19.resolve)(workspaceRoot ?? "."), "package.json");
43251
- const generated = results.find((r) => (0, import_node_path19.resolve)(r.targetPath) === packageJsonPath);
43482
+ const packageJsonPath = (0, import_node_path20.join)((0, import_node_path20.resolve)(workspaceRoot ?? "."), "package.json");
43483
+ const generated = results.find((r) => (0, import_node_path20.resolve)(r.targetPath) === packageJsonPath);
43252
43484
  let raw;
43253
43485
  if (generated) {
43254
43486
  raw = generated.newContent;
43255
43487
  } else {
43256
43488
  try {
43257
- raw = (0, import_node_fs19.readFileSync)(packageJsonPath, "utf8");
43489
+ raw = (0, import_node_fs20.readFileSync)(packageJsonPath, "utf8");
43258
43490
  } catch {
43259
43491
  raw = null;
43260
43492
  }
@@ -43318,16 +43550,16 @@ function stripJsonComments(text2) {
43318
43550
  return out.replace(/,(\s*[}\]])/g, "$1");
43319
43551
  }
43320
43552
  function resolveAliasPrefixes(results, workspaceRoot) {
43321
- const root = (0, import_node_path19.resolve)(workspaceRoot ?? ".");
43553
+ const root = (0, import_node_path20.resolve)(workspaceRoot ?? ".");
43322
43554
  for (const filename of ["tsconfig.json", "jsconfig.json"]) {
43323
- const configPath = (0, import_node_path19.join)(root, filename);
43324
- const generated = results.find((r) => (0, import_node_path19.resolve)(r.targetPath) === configPath);
43555
+ const configPath = (0, import_node_path20.join)(root, filename);
43556
+ const generated = results.find((r) => (0, import_node_path20.resolve)(r.targetPath) === configPath);
43325
43557
  let raw;
43326
43558
  if (generated) {
43327
43559
  raw = generated.newContent;
43328
43560
  } else {
43329
43561
  try {
43330
- raw = (0, import_node_fs19.readFileSync)(configPath, "utf8");
43562
+ raw = (0, import_node_fs20.readFileSync)(configPath, "utf8");
43331
43563
  } catch {
43332
43564
  raw = null;
43333
43565
  }
@@ -43577,13 +43809,13 @@ function describeUnsuppliedInputs(found) {
43577
43809
  }
43578
43810
 
43579
43811
  // src/unsuppliedInputsDisk.ts
43580
- var import_node_fs20 = require("node:fs");
43812
+ var import_node_fs21 = require("node:fs");
43581
43813
  var MAX_READ_BYTES = 1e6;
43582
43814
  function readCheckoutText(path) {
43583
43815
  try {
43584
- const info = (0, import_node_fs20.statSync)(path);
43816
+ const info = (0, import_node_fs21.statSync)(path);
43585
43817
  if (!info.isFile() || info.size > MAX_READ_BYTES) return null;
43586
- const bytes = (0, import_node_fs20.readFileSync)(path);
43818
+ const bytes = (0, import_node_fs21.readFileSync)(path);
43587
43819
  if (bytes.includes(0)) return null;
43588
43820
  return bytes.toString("utf8");
43589
43821
  } catch {
@@ -43613,7 +43845,7 @@ function describeVanishedTests(vanished) {
43613
43845
  }
43614
43846
 
43615
43847
  // src/verifyChange.ts
43616
- var import_node_path20 = require("node:path");
43848
+ var import_node_path21 = require("node:path");
43617
43849
 
43618
43850
  // src/packageUse.ts
43619
43851
  var import_node_child_process10 = require("node:child_process");
@@ -43640,7 +43872,7 @@ function packageImportedInWorkspace(pkg, root, cwd = process.cwd()) {
43640
43872
  }
43641
43873
 
43642
43874
  // src/verifyChange.ts
43643
- var import_node_fs21 = require("node:fs");
43875
+ var import_node_fs22 = require("node:fs");
43644
43876
  async function verifyChange(ctx, results, undoable) {
43645
43877
  const cwd = ctx.cwd ?? process.cwd();
43646
43878
  const now = ctx.now ?? Date.now;
@@ -43675,7 +43907,7 @@ async function verifyChange(ctx, results, undoable) {
43675
43907
  const depCheck = checkImportDependencies(results, readDeclaredDependencies(results, packet.workspaceRoot), resolveAliasPrefixes(results, packet.workspaceRoot), {
43676
43908
  originalOf: (path) => {
43677
43909
  try {
43678
- return (0, import_node_fs21.readFileSync)((0, import_node_path20.join)(cwd, path), "utf8");
43910
+ return (0, import_node_fs22.readFileSync)((0, import_node_path21.join)(cwd, path), "utf8");
43679
43911
  } catch (err) {
43680
43912
  return err.code === "ENOENT" ? "" : null;
43681
43913
  }
@@ -43725,7 +43957,7 @@ async function verifyChange(ctx, results, undoable) {
43725
43957
  flushedAt = now();
43726
43958
  if (undoable) {
43727
43959
  const report = findJUnitReport(cwd);
43728
- const ignore = report ? [(0, import_node_path20.relative)(cwd, report).split("\\").join("/")] : [];
43960
+ const ignore = report ? [(0, import_node_path21.relative)(cwd, report).split("\\").join("/")] : [];
43729
43961
  const flush = undoableFlush(cwd, results, flushCodegenResults, { ignore });
43730
43962
  undo = () => flush.undo();
43731
43963
  } else {
@@ -43772,7 +44004,7 @@ async function verifyChange(ctx, results, undoable) {
43772
44004
  if (check.blocked) {
43773
44005
  const readable = Boolean(baseline.results && after.results);
43774
44006
  const answered = readable ? testAnswerFrom({ baseline, after, changedPaths: results.map((r) => r.targetPath), requiredIds: ctx.requiredAutomationIds, harness: ctx.harness === true }) : null;
43775
- return fail(new Error(`QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`), {
44007
+ return fail(new Error(`QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check, { existingTestsMayExpectOldBehaviour: ctx.conflictsOn === true })}`), {
43776
44008
  check,
43777
44009
  bothSnapshotsReadable: readable,
43778
44010
  ...answered ? { answer: answered.output, failingKey: answered.failingKey } : {}
@@ -43801,7 +44033,7 @@ ${violations.join("\n")}`);
43801
44033
  }
43802
44034
 
43803
44035
  // src/run.ts
43804
- var import_node_fs24 = require("node:fs");
44036
+ var import_node_fs25 = require("node:fs");
43805
44037
 
43806
44038
  // src/mapMode.ts
43807
44039
  var MAP_ENV = "QUIKPILOT_MAP";
@@ -43859,7 +44091,7 @@ function buildToolsV2Env(i2) {
43859
44091
  }
43860
44092
 
43861
44093
  // src/repoMap.ts
43862
- var import_node_path21 = require("node:path");
44094
+ var import_node_path22 = require("node:path");
43863
44095
  var MAP_BUDGET_TOKENS = 4e3;
43864
44096
  var MAX_FOLDERS = 200;
43865
44097
  var MAX_LANGUAGES = 12;
@@ -43872,7 +44104,7 @@ var MAX_ENTRY_CHARS = 200;
43872
44104
  var inside = (path, root) => root === "" || path === root || path.startsWith(`${root}/`);
43873
44105
  var cap = (s) => s.length <= MAX_ENTRY_CHARS ? s : `${s.slice(0, MAX_ENTRY_CHARS - 1)}\u2026`;
43874
44106
  var parentOf2 = (d) => d.includes("/") ? d.slice(0, d.lastIndexOf("/")) : "";
43875
- function clip2(text2, max) {
44107
+ function clip3(text2, max) {
43876
44108
  if (text2.length <= max) return { text: text2, truncated: false };
43877
44109
  const cut = text2.slice(0, max);
43878
44110
  const nl = cut.lastIndexOf("\n");
@@ -43890,7 +44122,7 @@ function guidanceFiles(i2, perFile2, total) {
43890
44122
  if (!tracked.has(path) || matchesDeniedPath(path, denied)) continue;
43891
44123
  const raw = i2.readText(path);
43892
44124
  if (raw === null || raw.trim() === "") continue;
43893
- const clipped = clip2(i2.scrub(raw.replace(/\r\n/g, "\n")).trim(), Math.min(perFile2, left));
44125
+ const clipped = clip3(i2.scrub(raw.replace(/\r\n/g, "\n")).trim(), Math.min(perFile2, left));
43894
44126
  out.push({ path, ...clipped });
43895
44127
  left -= clipped.text.length;
43896
44128
  }
@@ -43901,7 +44133,7 @@ function guidanceFiles(i2, perFile2, total) {
43901
44133
  function languages(listing) {
43902
44134
  const counts = /* @__PURE__ */ new Map();
43903
44135
  for (const p of listing) {
43904
- const ext = import_node_path21.posix.extname(p).toLowerCase();
44136
+ const ext = import_node_path22.posix.extname(p).toLowerCase();
43905
44137
  if (ext && ext.length <= 12) counts.set(ext, (counts.get(ext) ?? 0) + 1);
43906
44138
  }
43907
44139
  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}`);
@@ -43917,7 +44149,7 @@ function testFacts(i2) {
43917
44149
  const depth = i2.writeRoot === "" ? 0 : i2.writeRoot.split("/").length;
43918
44150
  for (const t of tests) {
43919
44151
  const parts = t.split("/");
43920
- const folder = parts.length > depth + 1 ? parts.slice(0, depth + 1).join("/") : import_node_path21.posix.dirname(t);
44152
+ const folder = parts.length > depth + 1 ? parts.slice(0, depth + 1).join("/") : import_node_path22.posix.dirname(t);
43921
44153
  byFolder.set(folder, (byFolder.get(folder) ?? 0) + 1);
43922
44154
  }
43923
44155
  for (const [folder, n] of [...byFolder.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : 1)).slice(0, 3)) {
@@ -44027,7 +44259,7 @@ function buildRepoMap(i2) {
44027
44259
  }
44028
44260
 
44029
44261
  // src/workspacePackages.ts
44030
- var import_node_path22 = require("node:path");
44262
+ var import_node_path23 = require("node:path");
44031
44263
  var MAX_READ_ROOTS = 8;
44032
44264
  function isObject2(x) {
44033
44265
  return typeof x === "object" && x !== null && !Array.isArray(x);
@@ -44089,8 +44321,8 @@ function workspacePackages(readText, packageJsonPaths) {
44089
44321
  const exclude = patterns.filter((p) => p.startsWith("!")).map((p) => globMatcher(p.slice(1)));
44090
44322
  const out = [];
44091
44323
  for (const file of packageJsonPaths) {
44092
- if (import_node_path22.posix.basename(file) !== "package.json" || file === "package.json" || file.split("/").includes("node_modules")) continue;
44093
- const folder = import_node_path22.posix.dirname(file);
44324
+ if (import_node_path23.posix.basename(file) !== "package.json" || file === "package.json" || file.split("/").includes("node_modules")) continue;
44325
+ const folder = import_node_path23.posix.dirname(file);
44094
44326
  if (!include.some((re) => re.test(folder)) || exclude.some((re) => re.test(folder))) continue;
44095
44327
  const text2 = readText(file);
44096
44328
  const json = text2 === null ? null : parseJsonc(text2);
@@ -44359,34 +44591,34 @@ async function fetchPacket(packetUrl, runToken, githubRunId) {
44359
44591
  }
44360
44592
 
44361
44593
  // src/phase0.ts
44362
- var import_node_fs22 = require("node:fs");
44594
+ var import_node_fs23 = require("node:fs");
44363
44595
  function writePhase0Marker(runId) {
44364
- (0, import_node_fs22.mkdirSync)(".quikpilot", { recursive: true });
44365
- (0, import_node_fs22.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
44596
+ (0, import_node_fs23.mkdirSync)(".quikpilot", { recursive: true });
44597
+ (0, import_node_fs23.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
44366
44598
  `);
44367
44599
  }
44368
44600
 
44369
44601
  // src/failureArtifact.ts
44370
- var import_node_fs23 = require("node:fs");
44371
- var import_node_path23 = require("node:path");
44602
+ var import_node_fs24 = require("node:fs");
44603
+ var import_node_path24 = require("node:path");
44372
44604
  var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
44373
44605
  var REPORT_COPY = "final-test-report.xml";
44374
44606
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
44375
44607
  var MAX_FILES = 200;
44376
- var RUNNER_VERSION = true ? "9.3.0-rc.42" : "dev";
44608
+ var RUNNER_VERSION = true ? "9.3.0-rc.44" : "dev";
44377
44609
  function safeDestination(base, repoPath) {
44378
- if (!repoPath || (0, import_node_path23.isAbsolute)(repoPath)) return null;
44379
- const destination = (0, import_node_path23.resolve)(base, repoPath);
44380
- const rel = (0, import_node_path23.relative)(base, destination);
44381
- if (!rel || rel.startsWith("..") || (0, import_node_path23.isAbsolute)(rel)) return null;
44610
+ if (!repoPath || (0, import_node_path24.isAbsolute)(repoPath)) return null;
44611
+ const destination = (0, import_node_path24.resolve)(base, repoPath);
44612
+ const rel = (0, import_node_path24.relative)(base, destination);
44613
+ if (!rel || rel.startsWith("..") || (0, import_node_path24.isAbsolute)(rel)) return null;
44382
44614
  return destination;
44383
44615
  }
44384
44616
  function writeFailureArtifact(input) {
44385
44617
  if (input.results.length === 0) return { written: false };
44386
44618
  try {
44387
- const base = (0, import_node_path23.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
44388
- (0, import_node_fs23.rmSync)(base, { recursive: true, force: true });
44389
- (0, import_node_fs23.mkdirSync)(base, { recursive: true });
44619
+ const base = (0, import_node_path24.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
44620
+ (0, import_node_fs24.rmSync)(base, { recursive: true, force: true });
44621
+ (0, import_node_fs24.mkdirSync)(base, { recursive: true });
44390
44622
  const files = [];
44391
44623
  const skipped = [];
44392
44624
  for (const result of input.results) {
@@ -44395,8 +44627,8 @@ function writeFailureArtifact(input) {
44395
44627
  skipped.push(result.targetPath);
44396
44628
  continue;
44397
44629
  }
44398
- (0, import_node_fs23.mkdirSync)((0, import_node_path23.dirname)(destination), { recursive: true });
44399
- (0, import_node_fs23.writeFileSync)(destination, result.newContent);
44630
+ (0, import_node_fs24.mkdirSync)((0, import_node_path24.dirname)(destination), { recursive: true });
44631
+ (0, import_node_fs24.writeFileSync)(destination, result.newContent);
44400
44632
  files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
44401
44633
  }
44402
44634
  let testReport = "none";
@@ -44404,7 +44636,7 @@ function writeFailureArtifact(input) {
44404
44636
  if (input.testReport.byteLength > MAX_REPORT_BYTES) {
44405
44637
  testReport = "too-large";
44406
44638
  } else {
44407
- (0, import_node_fs23.writeFileSync)((0, import_node_path23.join)(base, REPORT_COPY), input.testReport);
44639
+ (0, import_node_fs24.writeFileSync)((0, import_node_path24.join)(base, REPORT_COPY), input.testReport);
44408
44640
  testReport = "included";
44409
44641
  }
44410
44642
  }
@@ -44424,8 +44656,8 @@ function writeFailureArtifact(input) {
44424
44656
  failureReasons: input.failureReasons
44425
44657
  };
44426
44658
  const text2 = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
44427
- (0, import_node_fs23.writeFileSync)((0, import_node_path23.join)(base, "manifest.json"), text2);
44428
- return { written: (0, import_node_fs23.existsSync)((0, import_node_path23.join)(base, "manifest.json")) };
44659
+ (0, import_node_fs24.writeFileSync)((0, import_node_path24.join)(base, "manifest.json"), text2);
44660
+ return { written: (0, import_node_fs24.existsSync)((0, import_node_path24.join)(base, "manifest.json")) };
44429
44661
  } catch (err) {
44430
44662
  console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
44431
44663
  return { written: false };
@@ -45023,7 +45255,7 @@ async function run(env2) {
45023
45255
  const workspaceListing = listWorkspaceFiles(writeRoot === "" ? null : writeRoot);
45024
45256
  const readCheckoutText2 = (path) => {
45025
45257
  try {
45026
- return (0, import_node_fs24.readFileSync)(path, "utf8");
45258
+ return (0, import_node_fs25.readFileSync)(path, "utf8");
45027
45259
  } catch {
45028
45260
  return null;
45029
45261
  }
@@ -45222,6 +45454,8 @@ async function run(env2) {
45222
45454
  requiredAutomationIds: claimedAutomationIds(stepParams),
45223
45455
  // The harness version, unless the AI Runtime refused it during code writing (then every fix speaks loop-2 too).
45224
45456
  harness: codegenMode === "loop-tests" && stepParams.harness !== false,
45457
+ // QUIKTR-1827: a regression of an existing test is worded as a test that may expect the old behaviour where a person can be asked.
45458
+ conflictsOn,
45225
45459
  // S4: the final run of the project's tests has a clock sized from how long the baseline took and from what is left of the job.
45226
45460
  baselineMs: timedBaseline.durationMs,
45227
45461
  jobStopAtMs,
@@ -45231,7 +45465,7 @@ async function run(env2) {
45231
45465
  const at2 = id.indexOf("::");
45232
45466
  const file = at2 === -1 ? "" : id.slice(0, at2);
45233
45467
  const name = at2 === -1 ? id : id.slice(at2 + 2);
45234
- return approved.titles.some((t) => (file === "" || file.endsWith(t.path) || t.path.endsWith(file)) && (name === t.title || name.endsWith(` ${t.title}`) || name.endsWith(`> ${t.title}`)));
45468
+ return approved.titles.some((t) => (file === "" || file.endsWith(t.path) || t.path.endsWith(file)) && nameEndsWithTitle(name, t.title));
45235
45469
  }
45236
45470
  } : {}
45237
45471
  };