@quikit/quikpilot-runner 9.3.0-rc.87 → 9.3.0-rc.89

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
@@ -16872,7 +16872,7 @@ var require_sourcemap_codec_umd = __commonJS2({
16872
16872
  intToChar[i3] = c;
16873
16873
  charToInt[c] = i3;
16874
16874
  }
16875
- function decodeInteger(reader, relative11) {
16875
+ function decodeInteger(reader, relative12) {
16876
16876
  let value = 0;
16877
16877
  let shift = 0;
16878
16878
  let integer = 0;
@@ -16887,10 +16887,10 @@ var require_sourcemap_codec_umd = __commonJS2({
16887
16887
  if (shouldNegate) {
16888
16888
  value = -2147483648 | -value;
16889
16889
  }
16890
- return relative11 + value;
16890
+ return relative12 + value;
16891
16891
  }
16892
- function encodeInteger(builder, num2, relative11) {
16893
- let delta = num2 - relative11;
16892
+ function encodeInteger(builder, num2, relative12) {
16893
+ let delta = num2 - relative12;
16894
16894
  delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
16895
16895
  do {
16896
16896
  let clamped = delta & 31;
@@ -29103,6 +29103,18 @@ function listFiles(pathspec) {
29103
29103
  const out2 = (0, import_node_child_process.execFileSync)("git", [...NO_HOOKS_ARGS, "ls-files", "-z", "--", pathspec], { encoding: "utf8", maxBuffer: LIST_MAX_BUFFER_BYTES, env: gitEnv() });
29104
29104
  return out2.split("\0").filter(Boolean);
29105
29105
  }
29106
+ function stagedDeletions() {
29107
+ const out2 = (0, import_node_child_process.execFileSync)("git", [...NO_HOOKS_ARGS, "diff", "--cached", "--name-only", "-z", "--no-renames", "--diff-filter=D"], {
29108
+ encoding: "utf8",
29109
+ maxBuffer: LIST_MAX_BUFFER_BYTES,
29110
+ env: gitEnv()
29111
+ });
29112
+ return out2.split("\0").filter(Boolean);
29113
+ }
29114
+ function unstage(paths) {
29115
+ if (paths.length === 0) return;
29116
+ (0, import_node_child_process.execFileSync)("git", [...NO_HOOKS_ARGS, "restore", "--staged", "--", ...paths], { encoding: "utf8", env: gitEnv() });
29117
+ }
29106
29118
  function hasStagedChanges() {
29107
29119
  try {
29108
29120
  (0, import_node_child_process.execFileSync)("git", [...NO_HOOKS_ARGS, "diff", "--cached", "--quiet"], { env: gitEnv() });
@@ -37528,8 +37540,8 @@ function resolveImport(fromPath, specifier, listing, mapSpecifier) {
37528
37540
  }
37529
37541
  if (/^(?:@\/|~\/|#|\$|\/)/.test(specifier)) return { kind: "unresolved", reason: "alias" };
37530
37542
  const clean = specifier.replace(/[?#].*$/, "");
37531
- const relative11 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
37532
- if (!relative11) return { kind: "external" };
37543
+ const relative12 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
37544
+ if (!relative12) return { kind: "external" };
37533
37545
  const base = import_node_path4.posix.normalize(import_node_path4.posix.join(import_node_path4.posix.dirname(fromPath), clean));
37534
37546
  if (base === ".." || base.startsWith("../") || import_node_path4.posix.isAbsolute(base)) return { kind: "unresolved", reason: "not found" };
37535
37547
  return probeBase(base, listing);
@@ -40059,6 +40071,7 @@ async function fetchWithRetry(url, init2, { retries = 2, backoffMs = 250 } = {})
40059
40071
  // src/callback.ts
40060
40072
  var REPORT_RETRY_STATUSES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
40061
40073
  var REPORT_RETRY_WAITS_MS = [2e3, 5e3, 1e4];
40074
+ var URGENT_REPORT_TIMEOUT_MS = 6e3;
40062
40075
  async function reportBack(params) {
40063
40076
  const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, testsCorrected, codegenLoop, unresolved, aiCostUsd, testConflicts, approvedTestsApplied, databaseChange } = params;
40064
40077
  const sleep = params.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
@@ -40078,7 +40091,7 @@ async function reportBack(params) {
40078
40091
  if (approvedTestsApplied && approvedTestsApplied.length > 0) body2.approvedTestsApplied = approvedTestsApplied;
40079
40092
  if (databaseChange && status === "completed") body2.databaseChange = databaseChange;
40080
40093
  const payload = JSON.stringify(body2);
40081
- const tries = REPORT_RETRY_WAITS_MS.length + 1;
40094
+ const tries = params.urgent ? 1 : REPORT_RETRY_WAITS_MS.length + 1;
40082
40095
  for (let attempt2 = 1; ; attempt2++) {
40083
40096
  let failure;
40084
40097
  let res;
@@ -40086,7 +40099,8 @@ async function reportBack(params) {
40086
40099
  res = await fetch(callbackUrl, {
40087
40100
  method: "POST",
40088
40101
  headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
40089
- body: payload
40102
+ body: payload,
40103
+ ...params.urgent ? { signal: AbortSignal.timeout(URGENT_REPORT_TIMEOUT_MS) } : {}
40090
40104
  });
40091
40105
  } catch (err2) {
40092
40106
  if (!isRetryableNetworkError(err2)) throw err2;
@@ -40110,6 +40124,87 @@ async function reportBack(params) {
40110
40124
 
40111
40125
  // src/commands.ts
40112
40126
  var import_node_child_process5 = require("node:child_process");
40127
+
40128
+ // src/testLimits.ts
40129
+ var BASELINE_MIN_MS = 5 * 6e4;
40130
+ var BASELINE_MAX_MS = 25 * 6e4;
40131
+ var BASELINE_SHARE = 2.5;
40132
+ var GATE_MIN_MS = 5 * 6e4;
40133
+ var GATE_MAX_MS = 20 * 6e4;
40134
+ var GATE_BASELINES = 2.5;
40135
+ var GATE_MIN_START_MS = 6e4;
40136
+ var FILE_RUN_LIMIT_MS = 3 * 6e4;
40137
+ function testLimitsOff(env2 = process.env) {
40138
+ return env2.QUIKPILOT_TEST_LIMITS?.trim().toLowerCase() === "off";
40139
+ }
40140
+ var clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
40141
+ function baselineLimitMs(leftMs) {
40142
+ if (!Number.isFinite(leftMs)) return null;
40143
+ return Math.round(clamp(leftMs / BASELINE_SHARE, BASELINE_MIN_MS, BASELINE_MAX_MS));
40144
+ }
40145
+ function gateLimitMs(i3) {
40146
+ if (!Number.isFinite(i3.leftMs)) return null;
40147
+ const baseline = typeof i3.baselineMs === "number" && Number.isFinite(i3.baselineMs) && i3.baselineMs >= 0 ? i3.baselineMs : 0;
40148
+ if (i3.leftMs < Math.max(GATE_MIN_START_MS, baseline / 2)) return "no_time";
40149
+ return Math.round(Math.min(clamp(baseline * GATE_BASELINES, GATE_MIN_MS, GATE_MAX_MS), i3.leftMs));
40150
+ }
40151
+ var minutes = (ms) => Math.max(1, Math.round(ms / 6e4));
40152
+ function baselineTimeoutMessage(limitMs, jobMinutes) {
40153
+ return `QuikPilot could not check this change against the project's tests: they did not finish within ${minutes(limitMs)} minutes on the code as it is, and a second full run after the change would not fit in this job's ${jobMinutes} minutes. Nothing was pushed.`;
40154
+ }
40155
+ function gateTimeoutMessage(limitMs, baselineMs) {
40156
+ const before = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they took ${minutes(baselineMs)} minutes before it)` : "";
40157
+ return `The project's tests did not finish within ${minutes(limitMs)} minutes after QuikPilot's change${before}, so the change could not be checked and nothing was pushed.`;
40158
+ }
40159
+ function gateNoTimeMessage(baselineMs) {
40160
+ const about = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they take about ${minutes(baselineMs)} minutes)` : "";
40161
+ return `There was not enough time left in this job to run the project's tests on QuikPilot's change${about}, so the change could not be checked and nothing was pushed.`;
40162
+ }
40163
+
40164
+ // src/runDeadline.ts
40165
+ var RUN_RESERVE_MS = 7 * 6e4;
40166
+ var CHECKS_ALLOWANCE_MS = 2 * 6e4;
40167
+ var MIN_WRITING_MS = 5 * 6e4;
40168
+ var SETUP_FLOOR_MS = 5 * 6e4;
40169
+ var CHECK_COMMAND_FLOOR_MS = 2 * 6e4;
40170
+ var WATCHDOG_AFTER_STOP_MS = 3 * 6e4;
40171
+ var finite = (n) => typeof n === "number" && Number.isFinite(n);
40172
+ var clamp2 = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
40173
+ var minutes2 = (ms) => Math.max(1, Math.round(ms / 6e4));
40174
+ function runStopAtMs(startedAt, maxWallClockMinutes) {
40175
+ return startedAt + maxWallClockMinutes * 6e4 - RUN_RESERVE_MS;
40176
+ }
40177
+ function watchdogAtMs(stopAtMs) {
40178
+ return stopAtMs + WATCHDOG_AFTER_STOP_MS;
40179
+ }
40180
+ function finalChecksReserveMs(i3) {
40181
+ const base = finite(i3.baselineMs) && i3.baselineMs >= 0 ? i3.baselineMs : finite(i3.baselineLimitMs) ? i3.baselineLimitMs : BASELINE_MIN_MS;
40182
+ return clamp2(base + CHECKS_ALLOWANCE_MS, GATE_MIN_MS, GATE_MAX_MS);
40183
+ }
40184
+ function codegenStopAtMs(i3) {
40185
+ const byBudget = i3.now + i3.budgetMs;
40186
+ return finite(i3.stopAtMs) ? Math.min(byBudget, i3.stopAtMs - i3.reserveMs) : byBudget;
40187
+ }
40188
+ function commandLimitMs(kind, i3) {
40189
+ if (testLimitsOff(i3.env) || !finite(i3.stopAtMs)) return null;
40190
+ const left = i3.stopAtMs - i3.now;
40191
+ if (kind === "setup") return Math.round(Math.max(SETUP_FLOOR_MS, left - (BASELINE_MIN_MS + GATE_MIN_MS)));
40192
+ return Math.round(Math.max(CHECK_COMMAND_FLOOR_MS, left - (i3.reserveMs ?? 0)));
40193
+ }
40194
+ function commandTimeoutMessage(label, limitMs) {
40195
+ return `${label} did not finish within the ${minutes2(limitMs)} minutes this job could spare for it, so QuikPilot stopped it. Nothing was pushed. Make ${label} faster (for example, cache what it installs) or raise the job's time limit in the project's QuikPilot settings.`;
40196
+ }
40197
+ function writeNoTimeMessage(leftMs, reserveMs) {
40198
+ return `There was not enough time left in this job to write the change (${Math.max(0, Math.round(leftMs / 6e4))} minutes left, about ${minutes2(reserveMs)} needed afterwards for the project's checks and tests), so QuikPilot did not start it. Nothing was pushed.`;
40199
+ }
40200
+ function jobTimeLimitMessage(jobMinutes) {
40201
+ return `The job was about to reach its ${jobMinutes}-minute time limit before QuikPilot finished, so QuikPilot stopped and reported. Nothing more was pushed.`;
40202
+ }
40203
+ function jobStoppedMessage() {
40204
+ return "The job was stopped before QuikPilot finished, so QuikPilot reported what it had. Nothing more was pushed.";
40205
+ }
40206
+
40207
+ // src/commands.ts
40113
40208
  var withheldLogged = false;
40114
40209
  function repositoryCommandEnv() {
40115
40210
  if (!withheldLogged) {
@@ -40161,6 +40256,7 @@ function runCommandWithTimeout(command, timeoutMs) {
40161
40256
  detached: true,
40162
40257
  env: repositoryCommandEnv()
40163
40258
  });
40259
+ track(child);
40164
40260
  const timer = setTimeout(() => {
40165
40261
  killProcessGroup(child);
40166
40262
  finish("timeout");
@@ -40169,6 +40265,30 @@ function runCommandWithTimeout(command, timeoutMs) {
40169
40265
  child.on("error", () => finish("error"));
40170
40266
  });
40171
40267
  }
40268
+ var liveGroups = /* @__PURE__ */ new Set();
40269
+ function track(child) {
40270
+ liveGroups.add(child);
40271
+ const forget = () => liveGroups.delete(child);
40272
+ if (typeof child.once !== "function") return;
40273
+ child.once("exit", forget);
40274
+ child.once("error", forget);
40275
+ }
40276
+ function killAllChildren() {
40277
+ for (const child of [...liveGroups]) {
40278
+ killProcessGroup(child);
40279
+ liveGroups.delete(child);
40280
+ }
40281
+ }
40282
+ async function runLimitedCommand(command, label, limitMs) {
40283
+ if (!command) return;
40284
+ if (limitMs === null) {
40285
+ runCommand(command, label);
40286
+ return;
40287
+ }
40288
+ const run3 = await runTestCommandWithLimit(command, limitMs);
40289
+ if (run3.timedOut) throw new Error(`${label} failed: ${commandTimeoutMessage(label, limitMs)}`);
40290
+ if (run3.outcome !== "success") throw new Error(`${label} failed: Command failed: ${command}`);
40291
+ }
40172
40292
  function killProcessGroup(child) {
40173
40293
  try {
40174
40294
  if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
@@ -40200,6 +40320,7 @@ function runCapturedCommand(argv, opts) {
40200
40320
  detached: true,
40201
40321
  env: repositoryCommandEnv()
40202
40322
  });
40323
+ track(child);
40203
40324
  child.stdout?.on("data", (chunk) => {
40204
40325
  if (bytes >= opts.maxStdoutBytes) return;
40205
40326
  const room = opts.maxStdoutBytes - bytes;
@@ -40242,6 +40363,7 @@ function runShellCaptured(command, opts) {
40242
40363
  detached: true,
40243
40364
  env: repositoryCommandEnv()
40244
40365
  });
40366
+ track(child);
40245
40367
  child.stdout?.on("data", keep);
40246
40368
  child.stderr?.on("data", keep);
40247
40369
  const timer = setTimeout(() => {
@@ -40273,6 +40395,7 @@ function runTestCommandWithLimit(command, timeoutMs, cwd) {
40273
40395
  env: repositoryCommandEnv(),
40274
40396
  ...cwd ? { cwd } : {}
40275
40397
  });
40398
+ track(child);
40276
40399
  const timer = setTimeout(() => {
40277
40400
  timedOut = true;
40278
40401
  killProcessGroup(child);
@@ -40283,40 +40406,312 @@ function runTestCommandWithLimit(command, timeoutMs, cwd) {
40283
40406
  });
40284
40407
  }
40285
40408
 
40286
- // src/testLimits.ts
40287
- var BASELINE_MIN_MS = 5 * 6e4;
40288
- var BASELINE_MAX_MS = 25 * 6e4;
40289
- var BASELINE_SHARE = 2.5;
40290
- var GATE_MIN_MS = 5 * 6e4;
40291
- var GATE_MAX_MS = 20 * 6e4;
40292
- var GATE_BASELINES = 2.5;
40293
- var GATE_MIN_START_MS = 6e4;
40294
- var FILE_RUN_LIMIT_MS = 3 * 6e4;
40295
- function testLimitsOff(env2 = process.env) {
40296
- return env2.QUIKPILOT_TEST_LIMITS?.trim().toLowerCase() === "off";
40409
+ // src/finalReportGuard.ts
40410
+ var SIGNALS = ["SIGINT", "SIGTERM"];
40411
+ function createFinalReportGuard(deps = {}) {
40412
+ const proc = deps.proc ?? process;
40413
+ const now = deps.now ?? Date.now;
40414
+ const setTimer = deps.setTimer ?? ((fn, ms) => setTimeout(fn, ms));
40415
+ const clearTimer = deps.clearTimer ?? ((t) => clearTimeout(t));
40416
+ const killChildren = deps.killChildren ?? (() => {
40417
+ });
40418
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
40419
+ let claimed = false;
40420
+ let timer;
40421
+ let onSignal;
40422
+ const claim = () => {
40423
+ if (claimed) return false;
40424
+ claimed = true;
40425
+ return true;
40426
+ };
40427
+ const disarm = () => {
40428
+ if (timer !== void 0) clearTimer(timer);
40429
+ timer = void 0;
40430
+ if (onSignal) for (const s of SIGNALS) proc.off(s, onSignal);
40431
+ onSignal = void 0;
40432
+ };
40433
+ return {
40434
+ claim,
40435
+ disarm,
40436
+ arm({ stopAtMs, watchdogAtMs: watchdogAtMs2, send }) {
40437
+ disarm();
40438
+ const fire = async (reason, source) => {
40439
+ if (!claim()) return;
40440
+ disarm();
40441
+ log({ event: "deadline.last_resort", reason, source });
40442
+ try {
40443
+ await send(reason);
40444
+ } catch (err2) {
40445
+ console.error(`The last-resort report could not be sent: ${err2 instanceof Error ? err2.message : String(err2)}`);
40446
+ } finally {
40447
+ try {
40448
+ killChildren();
40449
+ } catch {
40450
+ }
40451
+ proc.exit(1);
40452
+ }
40453
+ };
40454
+ if (Number.isFinite(watchdogAtMs2)) {
40455
+ const t = setTimer(() => void fire("time_limit", "timer"), Math.max(0, watchdogAtMs2 - now()));
40456
+ t.unref?.();
40457
+ timer = t;
40458
+ }
40459
+ onSignal = () => void fire(Number.isFinite(stopAtMs) && now() >= stopAtMs ? "time_limit" : "stopped", "signal");
40460
+ for (const s of SIGNALS) proc.on(s, onSignal);
40461
+ }
40462
+ };
40297
40463
  }
40298
- var clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
40299
- function baselineLimitMs(leftMs) {
40300
- if (!Number.isFinite(leftMs)) return null;
40301
- return Math.round(clamp(leftMs / BASELINE_SHARE, BASELINE_MIN_MS, BASELINE_MAX_MS));
40464
+
40465
+ // src/attemptSentences.ts
40466
+ var MAX_PREVIOUS_DETAIL_CHARS = 300;
40467
+ var MAX_PREVIOUS_RULES = 15;
40468
+ var MAX_PREVIOUS_TESTS = 20;
40469
+ var MAX_PREVIOUS_NAME_CHARS = 200;
40470
+ var MAX_PREVIOUS_WHOLE_MESSAGE_CHARS = 1e3;
40471
+ var MAX_PREVIOUS_MESSAGES_TOTAL_CHARS = 4e3;
40472
+ var MAX_PREVIOUS_COUNT = 1e5;
40473
+ var RUNTIME_CODE_SHAPE = /^[A-Z][A-Z0-9_]{0,39}$/;
40474
+ function runtimeCodeWord(code) {
40475
+ return RUNTIME_CODE_SHAPE.test(code) ? code : "other";
40302
40476
  }
40303
- function gateLimitMs(i3) {
40304
- if (!Number.isFinite(i3.leftMs)) return null;
40305
- const baseline = typeof i3.baselineMs === "number" && Number.isFinite(i3.baselineMs) && i3.baselineMs >= 0 ? i3.baselineMs : 0;
40306
- if (i3.leftMs < Math.max(GATE_MIN_START_MS, baseline / 2)) return "no_time";
40307
- return Math.round(Math.min(clamp(baseline * GATE_BASELINES, GATE_MIN_MS, GATE_MAX_MS), i3.leftMs));
40477
+ var COVERAGE_PREFIX = "Required test cases not written: ";
40478
+ function coverageSentence(ids) {
40479
+ const total = ids.length;
40480
+ for (let shown = total; shown >= 1; shown--) {
40481
+ const rest = total - shown;
40482
+ const text3 = `${COVERAGE_PREFIX}${ids.slice(0, shown).join(", ")}${rest > 0 ? `, and ${rest} more` : ""}.`;
40483
+ if (text3.length <= MAX_PREVIOUS_DETAIL_CHARS) return text3;
40484
+ }
40485
+ return `${COVERAGE_PREFIX}${total} of them.`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
40308
40486
  }
40309
- var minutes = (ms) => Math.max(1, Math.round(ms / 6e4));
40310
- function baselineTimeoutMessage(limitMs, jobMinutes) {
40311
- return `QuikPilot could not check this change against the project's tests: they did not finish within ${minutes(limitMs)} minutes on the code as it is, and a second full run after the change would not fit in this job's ${jobMinutes} minutes. Nothing was pushed.`;
40487
+ function truncationPhrase(suspect) {
40488
+ if (/^contains placeholder text/i.test(suspect)) return "placeholder text that suggests an abbreviated rewrite";
40489
+ if (/^sharp length drop/i.test(suspect)) return "a sharp drop in length";
40490
+ if (/^removed \d+ of \d+ lines/i.test(suspect)) return "many lines removed";
40491
+ if (/^removed exported symbol/i.test(suspect)) return "some of the file's exports were removed";
40492
+ return "the file came out much shorter than the original";
40312
40493
  }
40313
- function gateTimeoutMessage(limitMs, baselineMs) {
40314
- const before = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they took ${minutes(baselineMs)} minutes before it)` : "";
40315
- return `The project's tests did not finish within ${minutes(limitMs)} minutes after QuikPilot's change${before}, so the change could not be checked and nothing was pushed.`;
40494
+ function truncationSentence(path, suspect) {
40495
+ return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
40316
40496
  }
40317
- function gateNoTimeMessage(baselineMs) {
40318
- const about = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they take about ${minutes(baselineMs)} minutes)` : "";
40319
- return `There was not enough time left in this job to run the project's tests on QuikPilot's change${about}, so the change could not be checked and nothing was pushed.`;
40497
+
40498
+ // src/refusedReply.ts
40499
+ var REFUSED_OUTCOME = "REFUSED";
40500
+ var REFUSED_STREAK_LIMIT = 3;
40501
+ var MAX_REFUSED_RULES = 8;
40502
+ var MAX_REFUSED_SENTENCES = 8;
40503
+ var MAX_REFUSED_SENTENCE_CHARS = 300;
40504
+ var MAX_REFUSED_RULE_CHARS = 40;
40505
+ var REFUSED_RULE_IDS = [
40506
+ "reply_shape",
40507
+ "last_turn",
40508
+ "no_calls_left",
40509
+ "too_many_calls",
40510
+ "call_id",
40511
+ "unknown_tool",
40512
+ "bad_args",
40513
+ "bad_path",
40514
+ "protected_path",
40515
+ "file_state",
40516
+ "budget",
40517
+ "run_tests_rule",
40518
+ "repeat_call",
40519
+ "done_rule",
40520
+ "length"
40521
+ ];
40522
+ var KNOWN_RULES = new Set(REFUSED_RULE_IDS);
40523
+ function readRefusedAnswer(body2) {
40524
+ const { rules, violations, message } = body2;
40525
+ if (!Array.isArray(rules) || rules.length < 1 || rules.length > MAX_REFUSED_RULES) return null;
40526
+ if (!rules.every((r) => typeof r === "string" && r.length > 0 && r.length <= MAX_REFUSED_RULE_CHARS)) return null;
40527
+ if (!Array.isArray(violations) || violations.length < 1 || violations.length > MAX_REFUSED_SENTENCES) return null;
40528
+ if (!violations.every((v) => typeof v === "string" && v.length <= MAX_REFUSED_SENTENCE_CHARS)) return null;
40529
+ if (typeof message !== "string" || message.length > MAX_REFUSED_SENTENCE_CHARS) return null;
40530
+ return { rules: [...rules], violations: [...violations], message };
40531
+ }
40532
+ var RULE_WORD_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
40533
+ function recordRuleWord(word) {
40534
+ if (typeof word !== "string") return "other";
40535
+ return KNOWN_RULES.has(word) || RULE_WORD_SHAPE.test(word) ? word : "other";
40536
+ }
40537
+ var MAX_RECORD_REFUSED_TURNS = 30;
40538
+ var MAX_RECORD_REFUSED_RULES = 8;
40539
+ function wholeNumber(n) {
40540
+ return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
40541
+ }
40542
+ function clampRefusedTurns(turns) {
40543
+ const rows = [];
40544
+ let cut2 = false;
40545
+ for (const t of turns ?? []) {
40546
+ if (rows.length >= MAX_RECORD_REFUSED_TURNS) {
40547
+ cut2 = true;
40548
+ break;
40549
+ }
40550
+ if (t.rules.length > MAX_RECORD_REFUSED_RULES) cut2 = true;
40551
+ const rules = [...new Set(t.rules.map(recordRuleWord))].slice(0, MAX_RECORD_REFUSED_RULES);
40552
+ if (rules.length > 0) rows.push({ turn: wholeNumber(t.turn), rules });
40553
+ }
40554
+ return { rows, cut: cut2 };
40555
+ }
40556
+
40557
+ // src/codegenAttempts.ts
40558
+ var CODEGEN_BUDGET_MS = 30 * 6e4;
40559
+ var MIN_SECOND_ATTEMPT_MS = 3 * 6e4;
40560
+ function secondAttemptFloorMs(a) {
40561
+ return Math.max(a.firstAttemptMs, a.testLimitMs ?? 0, MIN_SECOND_ATTEMPT_MS);
40562
+ }
40563
+ var REASON_WORDS = {
40564
+ contract_rejected: "the AI service did not accept the request (it may be switched off)",
40565
+ test_case_disagree: "its code and its own test for an approved case still disagreed after one correction of the test",
40566
+ no_test_shows_bug: "none of its tests failed on the code before the change, so none of them showed the bug",
40567
+ semantic_mismatch: "the AI service and the runner disagreed about the request",
40568
+ http_error: "the AI service returned an error",
40569
+ transport: "the AI service could not be reached",
40570
+ turn_timeout: "one step took too long",
40571
+ loop_deadline: "the whole change took too long",
40572
+ runtime_failed: "the AI service returned an error",
40573
+ // QUIKTR-1824: the AI Service's CODEGEN_OUTPUT_TOO_LARGE / OUTPUT_TRUNCATED; told apart from a failing service (live run QTRIA-12).
40574
+ output_too_large: "the AI's answer was too long and was cut off",
40575
+ bad_reply: "the AI service sent a reply that could not be used",
40576
+ duplicate_call_ids: "the AI service repeated a request",
40577
+ final_not_produced: "it never reached an answer",
40578
+ token_ceiling: "the request grew too large for one step",
40579
+ executor_error: "reading or changing the code failed",
40580
+ internal_error: "the runner hit an internal error",
40581
+ cannot_complete: "the AI said it could not make the change from what it could see",
40582
+ no_writes: "it said it was finished but had changed nothing",
40583
+ coverage_missing: "it said it was finished but had not written a test for every case",
40584
+ truncation_guard: "a file it rewrote looked cut short",
40585
+ syntax_error: "a file it changed would not run (a syntax error, or a name that is used but never defined or imported)",
40586
+ out_of_time: "the time allowed for writing the change ran out",
40587
+ // QUIKTR-1854: an existing test that QuikPilot cannot read pins the bug. QUIKTR-1855: JavaScript, TypeScript, Python, Go and Java test files can be read.
40588
+ test_unsupported_language: "an existing test expects what an approved case calls wrong, but QuikPilot could not read that test file to ask about it (it reads JavaScript, TypeScript, Python, Go and Java test files), so no change to it could be proposed",
40589
+ test_conflict_unreportable: "an existing test expects what an approved case calls wrong, and it is written once for many rows, so no change to it could be proposed",
40590
+ // QUIKTR-2325 / QUIKTR-2326: the parts check. Only `part_missing` ends an attempt; the other two stop the run before any code.
40591
+ part_missing: "it said it was finished but had not built every part of the feature the design lists",
40592
+ part_not_placed: "the plan chose no file for a part of the feature the design lists",
40593
+ needs_database_change: "the feature needs a stored value (a database change) QuikPilot cannot make here"
40594
+ };
40595
+ function reasonInWords(reason) {
40596
+ return REASON_WORDS[reason] ?? reason;
40597
+ }
40598
+ function failedAttemptRecord(n, failure) {
40599
+ return {
40600
+ n,
40601
+ outcome: "failed",
40602
+ reason: failure.reason,
40603
+ ...failure.runtimeCode ? { runtimeCode: runtimeCodeWord(failure.runtimeCode) } : {},
40604
+ ...failure.afterRecovery ? { afterRecovery: true } : {},
40605
+ turns: failure.summary?.turns ?? 0,
40606
+ toolCalls: failure.summary?.toolCalls ?? 0
40607
+ };
40608
+ }
40609
+ function attemptInWords(a, fallback) {
40610
+ const words2 = a?.afterRecovery ? `${reasonInWords(a?.reason ?? fallback)}, a second time in a row, even after the AI was asked to take a smaller step` : reasonInWords(a?.reason ?? fallback);
40611
+ return a?.runtimeCode && a.runtimeCode !== "other" ? `${words2} (error code ${a.runtimeCode})` : words2;
40612
+ }
40613
+ function exhaustedMessage(attempts, stop2, unreportable) {
40614
+ const first = attempts[0];
40615
+ const second = attempts[1];
40616
+ const firstWords = attemptInWords(first, "internal_error");
40617
+ const blocking = unreportable[0];
40618
+ if (blocking) {
40619
+ const more = unreportable.length > 1 ? `, and ${unreportable.length - 1} more like it` : "";
40620
+ return `QuikPilot could not write the change: an existing test in ${blocking.path} (line ${blocking.line}) expects what approved case ${blocking.caseId} calls wrong${more}. It is written once and run for many rows, so QuikPilot cannot propose a change to it for you to approve. Change that test by hand, or correct the case if the test is right, then run QuikPilot again. Nothing was written.`;
40621
+ }
40622
+ if (stop2 === "failed" && attempts.length === 1 && first?.reason === "test_case_disagree") {
40623
+ return "QuikPilot could not write the change: its code and its own test for an approved case still disagreed after one correction of the test, so no pull request was opened. Look at that case's expected result: it may be unclear, or conflict with what the code already does.";
40624
+ }
40625
+ if (stop2 === "failed") {
40626
+ return `QuikPilot could not write the change: neither attempt reached a result. The first attempt ended because ${firstWords}. The second attempt ended because ${attemptInWords(second, "internal_error")}. Nothing was written.`;
40627
+ }
40628
+ const head = "QuikPilot could not write the change in the time allowed. ";
40629
+ if (second?.outcome === "not_started") {
40630
+ return first?.reason === "out_of_time" ? `${head}The first attempt ended because ${firstWords}, so there was no time for a second attempt. Nothing was written.` : `${head}The first attempt ended because ${firstWords}, and there was not enough time left for a second attempt. Nothing was written.`;
40631
+ }
40632
+ return `${head}The first attempt ended because ${firstWords}. The second attempt ended because ${attemptInWords(second, "out_of_time")}. Nothing was written.`;
40633
+ }
40634
+ var CodegenAttemptsExhausted = class extends Error {
40635
+ attempts;
40636
+ /** `out_of_time` when the shared clock decided the end, `failed` when both attempts ended without a result for any other reason. */
40637
+ stopReason;
40638
+ /** QUIKTR-1823: existing tests written once for many rows that stood in the way (path, line, case), when that is why the step ended. */
40639
+ unreportable;
40640
+ /**
40641
+ * QUIKTR-2325: `partsMissing` - the runner's own sentence naming the parts of the feature the last attempt did not build (`part_missing`).
40642
+ * It goes FIRST: QuikProjects explains a run's reason by how it starts ("A part of the feature was not built:"), and the attempts follow.
40643
+ * Built from the design's words and the planned paths; never a file's text.
40644
+ */
40645
+ constructor(attempts, stopReason, unreportable = [], partsMissing) {
40646
+ const message = exhaustedMessage(attempts, stopReason, unreportable);
40647
+ super(partsMissing ? `${partsMissing} ${message}` : message);
40648
+ this.name = "CodegenAttemptsExhausted";
40649
+ this.attempts = attempts;
40650
+ this.stopReason = stopReason;
40651
+ this.unreportable = [...unreportable];
40652
+ }
40653
+ };
40654
+ var RULE_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
40655
+ function count2(n) {
40656
+ return typeof n === "number" && Number.isInteger(n) ? Math.min(MAX_PREVIOUS_COUNT, Math.max(0, n)) : 0;
40657
+ }
40658
+ function isRecord(x) {
40659
+ return typeof x === "object" && x !== null && !Array.isArray(x);
40660
+ }
40661
+ function testRunFrom(answer) {
40662
+ if (!isRecord(answer)) return void 0;
40663
+ const numbers = ["passed", "failed", "total", "regressions", "newFailures", "alreadyFailing"];
40664
+ if (!numbers.every((k) => typeof answer[k] === "number") || !Array.isArray(answer.failingTests)) return void 0;
40665
+ const failingTests = answer.failingTests.filter((n) => typeof n === "string").map((n) => n.slice(0, MAX_PREVIOUS_NAME_CHARS)).filter((n) => n.length > 0).slice(0, MAX_PREVIOUS_TESTS);
40666
+ const run3 = {
40667
+ passed: count2(answer.passed),
40668
+ failed: count2(answer.failed),
40669
+ total: count2(answer.total),
40670
+ regressions: count2(answer.regressions),
40671
+ newFailures: count2(answer.newFailures),
40672
+ alreadyFailing: count2(answer.alreadyFailing),
40673
+ failingTests
40674
+ };
40675
+ if (isRecord(answer.messages)) {
40676
+ const listed = new Set(failingTests);
40677
+ const messages = {};
40678
+ let total = 0;
40679
+ for (const [name2, text3] of Object.entries(answer.messages)) {
40680
+ const key = name2.slice(0, MAX_PREVIOUS_NAME_CHARS);
40681
+ if (typeof text3 !== "string" || !listed.has(key) || Object.keys(messages).length >= MAX_PREVIOUS_TESTS) continue;
40682
+ const cut2 = text3.slice(0, Math.min(MAX_PREVIOUS_WHOLE_MESSAGE_CHARS, MAX_PREVIOUS_MESSAGES_TOTAL_CHARS - total));
40683
+ if (cut2.length > 0) {
40684
+ messages[key] = cut2;
40685
+ total += cut2.length;
40686
+ }
40687
+ }
40688
+ if (Object.keys(messages).length > 0) run3.messages = messages;
40689
+ }
40690
+ return run3;
40691
+ }
40692
+ function rulesFrom(rows) {
40693
+ if (!Array.isArray(rows) || rows.length === 0) return void 0;
40694
+ const counts = /* @__PURE__ */ new Map();
40695
+ for (const row of rows) {
40696
+ for (const raw of row.rules) {
40697
+ const word = recordRuleWord(raw);
40698
+ counts.set(word, (counts.get(word) ?? 0) + 1);
40699
+ }
40700
+ }
40701
+ const ordered = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([word]) => word);
40702
+ return ordered.length > 0 ? ordered.slice(0, MAX_PREVIOUS_RULES) : void 0;
40703
+ }
40704
+ function previousAttemptFrom(failure, attempt2) {
40705
+ const told = typeof failure.told === "string" ? failure.told.slice(0, MAX_PREVIOUS_DETAIL_CHARS) : "";
40706
+ const lastTestRun = testRunFrom(failure.lastTestAnswer);
40707
+ const rules = rulesFrom(failure.summary?.refusedTurns);
40708
+ return {
40709
+ attempt: attempt2,
40710
+ endedWith: RULE_SHAPE.test(failure.reason) ? failure.reason : "other",
40711
+ ...told.length > 0 ? { detail: told } : {},
40712
+ ...lastTestRun ? { lastTestRun } : {},
40713
+ ...rules ? { rules } : {}
40714
+ };
40320
40715
  }
40321
40716
 
40322
40717
  // src/testPlan.ts
@@ -40468,11 +40863,12 @@ var import_node_module = require("node:module");
40468
40863
  var import_node_path12 = require("node:path");
40469
40864
 
40470
40865
  // src/baselineCheck.ts
40471
- var import_node_child_process6 = require("node:child_process");
40866
+ var import_node_child_process7 = require("node:child_process");
40472
40867
  var import_node_fs8 = require("node:fs");
40473
40868
  var import_node_path11 = require("node:path");
40474
40869
 
40475
40870
  // src/quiktest.ts
40871
+ var import_node_child_process6 = require("node:child_process");
40476
40872
  var import_node_fs6 = require("node:fs");
40477
40873
  var import_node_path10 = require("node:path");
40478
40874
  var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
@@ -40538,6 +40934,34 @@ function findJUnitReports(cwd = process.cwd(), opts = {}) {
40538
40934
  const named2 = (p) => /^junit.*\.xml$/i.test(p.split(/[\\/]/).pop() ?? "") ? 0 : 1;
40539
40935
  return found.sort((a, b) => named2(a) - named2(b) || a.localeCompare(b));
40540
40936
  }
40937
+ function trackedPaths(paths, cwd = process.cwd()) {
40938
+ if (paths.length === 0) return /* @__PURE__ */ new Set();
40939
+ try {
40940
+ const rel = paths.map((p) => (0, import_node_path10.relative)(cwd, p).replace(/\\/g, "/"));
40941
+ const out2 = (0, import_node_child_process6.execFileSync)("git", [...NO_HOOKS_ARGS, "ls-files", "-z", "--", ...rel], {
40942
+ cwd,
40943
+ encoding: "utf8",
40944
+ env: gitEnv(),
40945
+ maxBuffer: 16 * 1024 * 1024,
40946
+ stdio: ["ignore", "pipe", "pipe"]
40947
+ });
40948
+ const tracked = new Set(out2.split("\0").filter(Boolean));
40949
+ return new Set(paths.filter((_, i3) => tracked.has(rel[i3])));
40950
+ } catch (err2) {
40951
+ const said = String(err2.stderr ?? "");
40952
+ return /not a git repository/i.test(said) ? /* @__PURE__ */ new Set() : new Set(paths);
40953
+ }
40954
+ }
40955
+ function runReports(cwd = process.cwd(), opts = {}) {
40956
+ const found = findJUnitReports(cwd, opts);
40957
+ const tracked = trackedPaths(found, cwd);
40958
+ return found.filter((p) => !tracked.has(p));
40959
+ }
40960
+ function removeRunReports(cwd = process.cwd()) {
40961
+ const reports = runReports(cwd);
40962
+ for (const report of reports) (0, import_node_fs6.rmSync)(report, { force: true });
40963
+ return reports.length;
40964
+ }
40541
40965
  function mergeJUnitReports(texts) {
40542
40966
  if (texts.length === 1) return texts[0];
40543
40967
  const inner = texts.map((t) => {
@@ -40587,9 +41011,9 @@ function firstXmlIn(dir, namePattern) {
40587
41011
  const match = entries.find((e) => namePattern.test(e));
40588
41012
  return match ? (0, import_node_path10.join)(dir, match) : null;
40589
41013
  }
40590
- function readTestReportBytes(cwd = process.cwd()) {
41014
+ function readTestReportBytes(cwd = process.cwd(), opts = {}) {
40591
41015
  try {
40592
- const reports = findJUnitReports(cwd);
41016
+ const reports = runReports(cwd, opts);
40593
41017
  if (reports.length === 0) return null;
40594
41018
  if (reports.length === 1) return (0, import_node_fs6.readFileSync)(reports[0]);
40595
41019
  return Buffer.from(mergeJUnitReports(reports.map((r) => (0, import_node_fs6.readFileSync)(r, "utf8"))), "utf8");
@@ -40609,12 +41033,12 @@ function describeUnmatchedAutomationIds(unmatched) {
40609
41033
  return `${unmatched.length} generated test result(s) did not match any test case: ${named2} \u2014 check the automationId format.`;
40610
41034
  }
40611
41035
  async function reportToQuikTest(params) {
40612
- const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;
41036
+ const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd, freshSinceMs } = params;
40613
41037
  if (!resultsUrl) {
40614
41038
  console.log("packet.quikTest is null \u2014 this run has no QuikTest run to report into.");
40615
41039
  return null;
40616
41040
  }
40617
- const reports = findJUnitReports(cwd);
41041
+ const reports = runReports(cwd, { freshSinceMs });
40618
41042
  if (reports.length === 0) {
40619
41043
  console.warn("::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.");
40620
41044
  return null;
@@ -40635,7 +41059,6 @@ async function reportToQuikTest(params) {
40635
41059
  if (!res.ok) {
40636
41060
  throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);
40637
41061
  }
40638
- for (const report of reports) (0, import_node_fs6.rmSync)(report, { force: true });
40639
41062
  let unmatched = [];
40640
41063
  try {
40641
41064
  const json = await res.json();
@@ -41110,7 +41533,7 @@ function restore(written) {
41110
41533
  }
41111
41534
  function untrackedFiles(cwd) {
41112
41535
  try {
41113
- const out2 = (0, import_node_child_process6.execFileSync)("git", [...NO_HOOKS_ARGS, "ls-files", "--others", "--exclude-standard", "-z"], {
41536
+ const out2 = (0, import_node_child_process7.execFileSync)("git", [...NO_HOOKS_ARGS, "ls-files", "--others", "--exclude-standard", "-z"], {
41114
41537
  env: gitEnv(),
41115
41538
  cwd,
41116
41539
  encoding: "utf8",
@@ -42323,19 +42746,19 @@ var import_node_crypto4 = require("node:crypto");
42323
42746
  var import_node_path19 = require("node:path");
42324
42747
 
42325
42748
  // src/overlayOnDisk.ts
42326
- var import_node_child_process8 = require("node:child_process");
42749
+ var import_node_child_process9 = require("node:child_process");
42327
42750
  var import_node_fs13 = require("node:fs");
42328
42751
  var import_node_path17 = require("node:path");
42329
42752
 
42330
42753
  // src/treeFingerprint.ts
42331
42754
  var import_node_crypto2 = require("node:crypto");
42332
- var import_node_child_process7 = require("node:child_process");
42755
+ var import_node_child_process8 = require("node:child_process");
42333
42756
  var import_node_fs12 = require("node:fs");
42334
42757
  var import_node_path16 = require("node:path");
42335
42758
  var MAX_HASHED_BYTES = 8 * 1024 * 1024;
42336
42759
  function defaultGitStatus(root) {
42337
42760
  try {
42338
- return (0, import_node_child_process7.execFileSync)("git", [...NO_HOOKS_ARGS, "status", "--porcelain=v1", "-z", "--untracked-files=all"], {
42761
+ return (0, import_node_child_process8.execFileSync)("git", [...NO_HOOKS_ARGS, "status", "--porcelain=v1", "-z", "--untracked-files=all"], {
42339
42762
  env: gitEnv(),
42340
42763
  cwd: root,
42341
42764
  encoding: "utf8",
@@ -42509,7 +42932,7 @@ function applyOverlay(root, files) {
42509
42932
  return { restore: restore2 };
42510
42933
  }
42511
42934
  function git2(root, args2) {
42512
- (0, import_node_child_process8.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd: root, stdio: ["ignore", "ignore", "ignore"] });
42935
+ (0, import_node_child_process9.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd: root, stdio: ["ignore", "ignore", "ignore"] });
42513
42936
  }
42514
42937
  function cleanUpAfterRun(root, beforePaths, afterStatus) {
42515
42938
  for (const token of afterStatus) {
@@ -42692,6 +43115,7 @@ var MAX_FILE_ARG_CHARS = 300;
42692
43115
  var LINE_BREAK = /\r\n|\n|\r|&#0*10;|&#x0*a;/i;
42693
43116
  var CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
42694
43117
  var FRESH_SLACK_MS2 = 2e3;
43118
+ var MIN_RUN_LIMIT_MS = 3e4;
42695
43119
  function testTimeLimitMs(baselineMs) {
42696
43120
  if (baselineMs === null) return DEFAULT_TEST_LIMIT_MS;
42697
43121
  if (baselineMs > MAX_TEST_LIMIT_MS) return "too_slow";
@@ -42980,8 +43404,9 @@ var RunTestsTool = class {
42980
43404
  const baselineMs = baseline?.durationMs ?? null;
42981
43405
  const plan = file === void 0 && d.planner ? d.planner.plan({ overlayPaths: files.map((f) => f.path), baselineMs }) : { scope: "full", why: null };
42982
43406
  const related = plan.scope === "related" ? plan : null;
42983
- const limit = related ? related.limitMs : testTimeLimitMs(baselineMs);
42984
- if (limit === "too_slow") return this.answer(callId, "tests_too_slow", { reason: "baseline_over_ten_minutes", scope });
43407
+ const fullLimit = related ? related.limitMs : testTimeLimitMs(baselineMs);
43408
+ if (fullLimit === "too_slow") return this.answer(callId, "tests_too_slow", { reason: "baseline_over_ten_minutes", scope });
43409
+ const limit = d.stopAtMs === void 0 ? fullLimit : Math.max(MIN_RUN_LIMIT_MS, Math.min(fullLimit, d.stopAtMs - now()));
42985
43410
  const findReport = d.findReport ?? findJUnitReport;
42986
43411
  const runCommand2 = d.runCommand ?? runTestCommandWithLimit;
42987
43412
  const readSnapshot = d.readSnapshot ?? readTestSnapshot;
@@ -43385,258 +43810,6 @@ async function executeCallFunctionCall(call, tool, ledger, limits) {
43385
43810
  return result;
43386
43811
  }
43387
43812
 
43388
- // src/attemptSentences.ts
43389
- var MAX_PREVIOUS_DETAIL_CHARS = 300;
43390
- var MAX_PREVIOUS_RULES = 15;
43391
- var MAX_PREVIOUS_TESTS = 20;
43392
- var MAX_PREVIOUS_NAME_CHARS = 200;
43393
- var MAX_PREVIOUS_WHOLE_MESSAGE_CHARS = 1e3;
43394
- var MAX_PREVIOUS_MESSAGES_TOTAL_CHARS = 4e3;
43395
- var MAX_PREVIOUS_COUNT = 1e5;
43396
- var RUNTIME_CODE_SHAPE = /^[A-Z][A-Z0-9_]{0,39}$/;
43397
- function runtimeCodeWord(code) {
43398
- return RUNTIME_CODE_SHAPE.test(code) ? code : "other";
43399
- }
43400
- var COVERAGE_PREFIX = "Required test cases not written: ";
43401
- function coverageSentence(ids) {
43402
- const total = ids.length;
43403
- for (let shown = total; shown >= 1; shown--) {
43404
- const rest = total - shown;
43405
- const text3 = `${COVERAGE_PREFIX}${ids.slice(0, shown).join(", ")}${rest > 0 ? `, and ${rest} more` : ""}.`;
43406
- if (text3.length <= MAX_PREVIOUS_DETAIL_CHARS) return text3;
43407
- }
43408
- return `${COVERAGE_PREFIX}${total} of them.`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
43409
- }
43410
- function truncationPhrase(suspect) {
43411
- if (/^contains placeholder text/i.test(suspect)) return "placeholder text that suggests an abbreviated rewrite";
43412
- if (/^sharp length drop/i.test(suspect)) return "a sharp drop in length";
43413
- if (/^removed \d+ of \d+ lines/i.test(suspect)) return "many lines removed";
43414
- if (/^removed exported symbol/i.test(suspect)) return "some of the file's exports were removed";
43415
- return "the file came out much shorter than the original";
43416
- }
43417
- function truncationSentence(path, suspect) {
43418
- return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
43419
- }
43420
-
43421
- // src/refusedReply.ts
43422
- var REFUSED_OUTCOME = "REFUSED";
43423
- var REFUSED_STREAK_LIMIT = 3;
43424
- var MAX_REFUSED_RULES = 8;
43425
- var MAX_REFUSED_SENTENCES = 8;
43426
- var MAX_REFUSED_SENTENCE_CHARS = 300;
43427
- var MAX_REFUSED_RULE_CHARS = 40;
43428
- var REFUSED_RULE_IDS = [
43429
- "reply_shape",
43430
- "last_turn",
43431
- "no_calls_left",
43432
- "too_many_calls",
43433
- "call_id",
43434
- "unknown_tool",
43435
- "bad_args",
43436
- "bad_path",
43437
- "protected_path",
43438
- "file_state",
43439
- "budget",
43440
- "run_tests_rule",
43441
- "repeat_call",
43442
- "done_rule",
43443
- "length"
43444
- ];
43445
- var KNOWN_RULES = new Set(REFUSED_RULE_IDS);
43446
- function readRefusedAnswer(body2) {
43447
- const { rules, violations, message } = body2;
43448
- if (!Array.isArray(rules) || rules.length < 1 || rules.length > MAX_REFUSED_RULES) return null;
43449
- if (!rules.every((r) => typeof r === "string" && r.length > 0 && r.length <= MAX_REFUSED_RULE_CHARS)) return null;
43450
- if (!Array.isArray(violations) || violations.length < 1 || violations.length > MAX_REFUSED_SENTENCES) return null;
43451
- if (!violations.every((v) => typeof v === "string" && v.length <= MAX_REFUSED_SENTENCE_CHARS)) return null;
43452
- if (typeof message !== "string" || message.length > MAX_REFUSED_SENTENCE_CHARS) return null;
43453
- return { rules: [...rules], violations: [...violations], message };
43454
- }
43455
- var RULE_WORD_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
43456
- function recordRuleWord(word) {
43457
- if (typeof word !== "string") return "other";
43458
- return KNOWN_RULES.has(word) || RULE_WORD_SHAPE.test(word) ? word : "other";
43459
- }
43460
- var MAX_RECORD_REFUSED_TURNS = 30;
43461
- var MAX_RECORD_REFUSED_RULES = 8;
43462
- function wholeNumber(n) {
43463
- return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
43464
- }
43465
- function clampRefusedTurns(turns) {
43466
- const rows = [];
43467
- let cut2 = false;
43468
- for (const t of turns ?? []) {
43469
- if (rows.length >= MAX_RECORD_REFUSED_TURNS) {
43470
- cut2 = true;
43471
- break;
43472
- }
43473
- if (t.rules.length > MAX_RECORD_REFUSED_RULES) cut2 = true;
43474
- const rules = [...new Set(t.rules.map(recordRuleWord))].slice(0, MAX_RECORD_REFUSED_RULES);
43475
- if (rules.length > 0) rows.push({ turn: wholeNumber(t.turn), rules });
43476
- }
43477
- return { rows, cut: cut2 };
43478
- }
43479
-
43480
- // src/codegenAttempts.ts
43481
- var CODEGEN_BUDGET_MS = 30 * 6e4;
43482
- var MIN_SECOND_ATTEMPT_MS = 3 * 6e4;
43483
- function secondAttemptFloorMs(a) {
43484
- return Math.max(a.firstAttemptMs, a.testLimitMs ?? 0, MIN_SECOND_ATTEMPT_MS);
43485
- }
43486
- var REASON_WORDS = {
43487
- contract_rejected: "the AI service did not accept the request (it may be switched off)",
43488
- test_case_disagree: "its code and its own test for an approved case still disagreed after one correction of the test",
43489
- no_test_shows_bug: "none of its tests failed on the code before the change, so none of them showed the bug",
43490
- semantic_mismatch: "the AI service and the runner disagreed about the request",
43491
- http_error: "the AI service returned an error",
43492
- transport: "the AI service could not be reached",
43493
- turn_timeout: "one step took too long",
43494
- loop_deadline: "the whole change took too long",
43495
- runtime_failed: "the AI service returned an error",
43496
- // QUIKTR-1824: the AI Service's CODEGEN_OUTPUT_TOO_LARGE / OUTPUT_TRUNCATED; told apart from a failing service (live run QTRIA-12).
43497
- output_too_large: "the AI's answer was too long and was cut off",
43498
- bad_reply: "the AI service sent a reply that could not be used",
43499
- duplicate_call_ids: "the AI service repeated a request",
43500
- final_not_produced: "it never reached an answer",
43501
- token_ceiling: "the request grew too large for one step",
43502
- executor_error: "reading or changing the code failed",
43503
- internal_error: "the runner hit an internal error",
43504
- cannot_complete: "the AI said it could not make the change from what it could see",
43505
- no_writes: "it said it was finished but had changed nothing",
43506
- coverage_missing: "it said it was finished but had not written a test for every case",
43507
- truncation_guard: "a file it rewrote looked cut short",
43508
- syntax_error: "a file it changed would not run (a syntax error, or a name that is used but never defined or imported)",
43509
- out_of_time: "the time allowed for writing the change ran out",
43510
- // QUIKTR-1854: an existing test that QuikPilot cannot read pins the bug. QUIKTR-1855: JavaScript, TypeScript, Python, Go and Java test files can be read.
43511
- test_unsupported_language: "an existing test expects what an approved case calls wrong, but QuikPilot could not read that test file to ask about it (it reads JavaScript, TypeScript, Python, Go and Java test files), so no change to it could be proposed",
43512
- test_conflict_unreportable: "an existing test expects what an approved case calls wrong, and it is written once for many rows, so no change to it could be proposed",
43513
- // QUIKTR-2325 / QUIKTR-2326: the parts check. Only `part_missing` ends an attempt; the other two stop the run before any code.
43514
- part_missing: "it said it was finished but had not built every part of the feature the design lists",
43515
- part_not_placed: "the plan chose no file for a part of the feature the design lists",
43516
- needs_database_change: "the feature needs a stored value (a database change) QuikPilot cannot make here"
43517
- };
43518
- function reasonInWords(reason) {
43519
- return REASON_WORDS[reason] ?? reason;
43520
- }
43521
- function failedAttemptRecord(n, failure) {
43522
- return {
43523
- n,
43524
- outcome: "failed",
43525
- reason: failure.reason,
43526
- ...failure.runtimeCode ? { runtimeCode: runtimeCodeWord(failure.runtimeCode) } : {},
43527
- ...failure.afterRecovery ? { afterRecovery: true } : {},
43528
- turns: failure.summary?.turns ?? 0,
43529
- toolCalls: failure.summary?.toolCalls ?? 0
43530
- };
43531
- }
43532
- function attemptInWords(a, fallback) {
43533
- const words2 = a?.afterRecovery ? `${reasonInWords(a?.reason ?? fallback)}, a second time in a row, even after the AI was asked to take a smaller step` : reasonInWords(a?.reason ?? fallback);
43534
- return a?.runtimeCode && a.runtimeCode !== "other" ? `${words2} (error code ${a.runtimeCode})` : words2;
43535
- }
43536
- function exhaustedMessage(attempts, stop2, unreportable) {
43537
- const first = attempts[0];
43538
- const second = attempts[1];
43539
- const firstWords = attemptInWords(first, "internal_error");
43540
- const blocking = unreportable[0];
43541
- if (blocking) {
43542
- const more = unreportable.length > 1 ? `, and ${unreportable.length - 1} more like it` : "";
43543
- return `QuikPilot could not write the change: an existing test in ${blocking.path} (line ${blocking.line}) expects what approved case ${blocking.caseId} calls wrong${more}. It is written once and run for many rows, so QuikPilot cannot propose a change to it for you to approve. Change that test by hand, or correct the case if the test is right, then run QuikPilot again. Nothing was written.`;
43544
- }
43545
- if (stop2 === "failed" && attempts.length === 1 && first?.reason === "test_case_disagree") {
43546
- return "QuikPilot could not write the change: its code and its own test for an approved case still disagreed after one correction of the test, so no pull request was opened. Look at that case's expected result: it may be unclear, or conflict with what the code already does.";
43547
- }
43548
- if (stop2 === "failed") {
43549
- return `QuikPilot could not write the change: neither attempt reached a result. The first attempt ended because ${firstWords}. The second attempt ended because ${attemptInWords(second, "internal_error")}. Nothing was written.`;
43550
- }
43551
- const head = "QuikPilot could not write the change in the time allowed. ";
43552
- if (second?.outcome === "not_started") {
43553
- return first?.reason === "out_of_time" ? `${head}The first attempt ended because ${firstWords}, so there was no time for a second attempt. Nothing was written.` : `${head}The first attempt ended because ${firstWords}, and there was not enough time left for a second attempt. Nothing was written.`;
43554
- }
43555
- return `${head}The first attempt ended because ${firstWords}. The second attempt ended because ${attemptInWords(second, "out_of_time")}. Nothing was written.`;
43556
- }
43557
- var CodegenAttemptsExhausted = class extends Error {
43558
- attempts;
43559
- /** `out_of_time` when the shared clock decided the end, `failed` when both attempts ended without a result for any other reason. */
43560
- stopReason;
43561
- /** QUIKTR-1823: existing tests written once for many rows that stood in the way (path, line, case), when that is why the step ended. */
43562
- unreportable;
43563
- /**
43564
- * QUIKTR-2325: `partsMissing` - the runner's own sentence naming the parts of the feature the last attempt did not build (`part_missing`).
43565
- * It goes FIRST: QuikProjects explains a run's reason by how it starts ("A part of the feature was not built:"), and the attempts follow.
43566
- * Built from the design's words and the planned paths; never a file's text.
43567
- */
43568
- constructor(attempts, stopReason, unreportable = [], partsMissing) {
43569
- const message = exhaustedMessage(attempts, stopReason, unreportable);
43570
- super(partsMissing ? `${partsMissing} ${message}` : message);
43571
- this.name = "CodegenAttemptsExhausted";
43572
- this.attempts = attempts;
43573
- this.stopReason = stopReason;
43574
- this.unreportable = [...unreportable];
43575
- }
43576
- };
43577
- var RULE_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
43578
- function count2(n) {
43579
- return typeof n === "number" && Number.isInteger(n) ? Math.min(MAX_PREVIOUS_COUNT, Math.max(0, n)) : 0;
43580
- }
43581
- function isRecord(x) {
43582
- return typeof x === "object" && x !== null && !Array.isArray(x);
43583
- }
43584
- function testRunFrom(answer) {
43585
- if (!isRecord(answer)) return void 0;
43586
- const numbers = ["passed", "failed", "total", "regressions", "newFailures", "alreadyFailing"];
43587
- if (!numbers.every((k) => typeof answer[k] === "number") || !Array.isArray(answer.failingTests)) return void 0;
43588
- const failingTests = answer.failingTests.filter((n) => typeof n === "string").map((n) => n.slice(0, MAX_PREVIOUS_NAME_CHARS)).filter((n) => n.length > 0).slice(0, MAX_PREVIOUS_TESTS);
43589
- const run3 = {
43590
- passed: count2(answer.passed),
43591
- failed: count2(answer.failed),
43592
- total: count2(answer.total),
43593
- regressions: count2(answer.regressions),
43594
- newFailures: count2(answer.newFailures),
43595
- alreadyFailing: count2(answer.alreadyFailing),
43596
- failingTests
43597
- };
43598
- if (isRecord(answer.messages)) {
43599
- const listed = new Set(failingTests);
43600
- const messages = {};
43601
- let total = 0;
43602
- for (const [name2, text3] of Object.entries(answer.messages)) {
43603
- const key = name2.slice(0, MAX_PREVIOUS_NAME_CHARS);
43604
- if (typeof text3 !== "string" || !listed.has(key) || Object.keys(messages).length >= MAX_PREVIOUS_TESTS) continue;
43605
- const cut2 = text3.slice(0, Math.min(MAX_PREVIOUS_WHOLE_MESSAGE_CHARS, MAX_PREVIOUS_MESSAGES_TOTAL_CHARS - total));
43606
- if (cut2.length > 0) {
43607
- messages[key] = cut2;
43608
- total += cut2.length;
43609
- }
43610
- }
43611
- if (Object.keys(messages).length > 0) run3.messages = messages;
43612
- }
43613
- return run3;
43614
- }
43615
- function rulesFrom(rows) {
43616
- if (!Array.isArray(rows) || rows.length === 0) return void 0;
43617
- const counts = /* @__PURE__ */ new Map();
43618
- for (const row of rows) {
43619
- for (const raw of row.rules) {
43620
- const word = recordRuleWord(raw);
43621
- counts.set(word, (counts.get(word) ?? 0) + 1);
43622
- }
43623
- }
43624
- const ordered = [...counts.entries()].sort((a, b) => b[1] - a[1] || (a[0] < b[0] ? -1 : a[0] > b[0] ? 1 : 0)).map(([word]) => word);
43625
- return ordered.length > 0 ? ordered.slice(0, MAX_PREVIOUS_RULES) : void 0;
43626
- }
43627
- function previousAttemptFrom(failure, attempt2) {
43628
- const told = typeof failure.told === "string" ? failure.told.slice(0, MAX_PREVIOUS_DETAIL_CHARS) : "";
43629
- const lastTestRun = testRunFrom(failure.lastTestAnswer);
43630
- const rules = rulesFrom(failure.summary?.refusedTurns);
43631
- return {
43632
- attempt: attempt2,
43633
- endedWith: RULE_SHAPE.test(failure.reason) ? failure.reason : "other",
43634
- ...told.length > 0 ? { detail: told } : {},
43635
- ...lastTestRun ? { lastTestRun } : {},
43636
- ...rules ? { rules } : {}
43637
- };
43638
- }
43639
-
43640
43813
  // src/anchorPlaces.ts
43641
43814
  var MAX_NAMED = 4;
43642
43815
  var QUOTE_WIDTH = 50;
@@ -48337,7 +48510,7 @@ var TargetingHttpError = class extends Error {
48337
48510
  };
48338
48511
 
48339
48512
  // src/dataPathCheck.ts
48340
- var import_node_child_process9 = require("node:child_process");
48513
+ var import_node_child_process10 = require("node:child_process");
48341
48514
  var import_node_fs17 = require("node:fs");
48342
48515
  var import_node_path21 = require("node:path");
48343
48516
 
@@ -48484,7 +48657,7 @@ function addressMatches(route, call) {
48484
48657
  }
48485
48658
  var git3 = (cwd, args2) => {
48486
48659
  try {
48487
- return (0, import_node_child_process9.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48660
+ return (0, import_node_child_process10.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48488
48661
  } catch {
48489
48662
  return "";
48490
48663
  }
@@ -49977,6 +50150,8 @@ async function runCodegenLoop(args2, deps) {
49977
50150
  isRunnableTestFile: (path) => matchesDeniedPath(path, args2.deniedPaths) === null && (looksLikeTest(path) || args2.protectedTestPaths.includes(path)) && (args2.listing.includes(path) || overlay.changedPaths().includes(path)),
49978
50151
  overlayFiles: filesOnDisk,
49979
50152
  overlayVersion: () => versionOfFiles(filesOnDisk()),
50153
+ // QUIKTR-2706: the AI's own test runs never run past the writing step's stop.
50154
+ ...deps.hardStopAtMs !== void 0 ? { stopAtMs: deps.hardStopAtMs } : {},
49980
50155
  log,
49981
50156
  now
49982
50157
  }) : null;
@@ -51578,7 +51753,7 @@ function pythonImports(file, text3, ix) {
51578
51753
  const lookup = (dotted) => {
51579
51754
  for (const hit of ix.pyModules.get(dotted) ?? []) if (hit !== file) out2.add(hit);
51580
51755
  };
51581
- const relative11 = (dots, rest) => {
51756
+ const relative12 = (dots, rest) => {
51582
51757
  let base = dirOf(file);
51583
51758
  for (let i3 = 1; i3 < dots; i3++) base = dirOf(base);
51584
51759
  const joined = rest ? import_node_path22.posix.join(base, rest.replace(/\./g, "/")) : base;
@@ -51591,8 +51766,8 @@ function pythonImports(file, text3, ix) {
51591
51766
  const mod = from[2];
51592
51767
  const names = from[3].replace(/[()\\]/g, "").split(",").map((s) => s.trim().split(/\s+as\s+/)[0].trim()).filter((s) => /^\w+$/.test(s));
51593
51768
  if (dots > 0) {
51594
- for (const p of relative11(dots, mod)) out2.add(p);
51595
- for (const n of names) for (const p of relative11(dots, mod ? `${mod}.${n}` : n)) out2.add(p);
51769
+ for (const p of relative12(dots, mod)) out2.add(p);
51770
+ for (const n of names) for (const p of relative12(dots, mod ? `${mod}.${n}` : n)) out2.add(p);
51596
51771
  } else {
51597
51772
  lookup(mod);
51598
51773
  for (const n of names) lookup(`${mod}.${n}`);
@@ -52320,7 +52495,7 @@ async function runCodegenStep(p) {
52320
52495
  );
52321
52496
  const now = p.deps?.now ?? Date.now;
52322
52497
  const log = p.deps?.log ?? ((e) => console.log(JSON.stringify(e)));
52323
- const hardStopAtMs = now() + (p.budgetMs ?? CODEGEN_BUDGET_MS);
52498
+ const hardStopAtMs = codegenStopAtMs({ now: now(), budgetMs: p.budgetMs ?? CODEGEN_BUDGET_MS, stopAtMs: p.stopAtMs ?? Number.NaN, reserveMs: 0 });
52324
52499
  let args2;
52325
52500
  const loopDeps = {
52326
52501
  post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
@@ -52867,7 +53042,7 @@ async function runVerifyAndFix(p) {
52867
53042
  }
52868
53043
 
52869
53044
  // src/hunkCheck.ts
52870
- var import_node_child_process10 = require("node:child_process");
53045
+ var import_node_child_process11 = require("node:child_process");
52871
53046
  var import_node_fs21 = require("node:fs");
52872
53047
  var import_node_path24 = require("node:path");
52873
53048
  var MAX_REPORTED_HUNKS = 20;
@@ -52896,7 +53071,7 @@ function collectHunkCheckFiles(results, root, readHead = readCommittedText) {
52896
53071
  }
52897
53072
  function readCommittedText(root, path) {
52898
53073
  try {
52899
- return (0, import_node_child_process10.execFileSync)("git", [...NO_HOOKS_ARGS, "show", `HEAD:${path}`], { env: gitEnv(), cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024 });
53074
+ return (0, import_node_child_process11.execFileSync)("git", [...NO_HOOKS_ARGS, "show", `HEAD:${path}`], { env: gitEnv(), cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024 });
52900
53075
  } catch {
52901
53076
  return null;
52902
53077
  }
@@ -53384,7 +53559,7 @@ function exitCodeFailedMessage() {
53384
53559
  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.";
53385
53560
 
53386
53561
  // src/existingRoutes.ts
53387
- var import_node_child_process11 = require("node:child_process");
53562
+ var import_node_child_process12 = require("node:child_process");
53388
53563
  var GREP_TIMEOUT_MS = 1e4;
53389
53564
  var MAX_HIT_LINES = 400;
53390
53565
  var MAX_OUTPUT_BYTES = 4e6;
@@ -53399,7 +53574,7 @@ function routeAlreadyNamed(cwd, mention) {
53399
53574
  const wanted = normalizePath(mention.path);
53400
53575
  let out2;
53401
53576
  try {
53402
- out2 = (0, import_node_child_process11.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-I", "-n", "-F", "-e", anchor], {
53577
+ out2 = (0, import_node_child_process12.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-I", "-n", "-F", "-e", anchor], {
53403
53578
  env: gitEnv(),
53404
53579
  cwd,
53405
53580
  encoding: "utf8",
@@ -53696,7 +53871,7 @@ function describeVanishedTests(vanished) {
53696
53871
  var import_node_path26 = require("node:path");
53697
53872
 
53698
53873
  // src/packageUse.ts
53699
- var import_node_child_process12 = require("node:child_process");
53874
+ var import_node_child_process13 = require("node:child_process");
53700
53875
  var PACKAGE_NAME = /^(?:@[a-z0-9][a-z0-9._-]*\/)?[a-z0-9][a-z0-9._-]*$/;
53701
53876
  var FILE_TYPES = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
53702
53877
  var GREP_TIMEOUT_MS2 = 1e4;
@@ -53708,7 +53883,7 @@ function packageImportedInWorkspace(pkg, root, cwd = process.cwd()) {
53708
53883
  if (!PACKAGE_NAME.test(pkg)) return false;
53709
53884
  const pathspecs = FILE_TYPES.map((type) => root ? `:(glob)${root}/**/${type}` : `:(glob)**/${type}`);
53710
53885
  try {
53711
- (0, import_node_child_process12.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-q", "-E", "-e", importPattern(pkg), "--", ...pathspecs], {
53886
+ (0, import_node_child_process13.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-q", "-E", "-e", importPattern(pkg), "--", ...pathspecs], {
53712
53887
  env: gitEnv(),
53713
53888
  cwd,
53714
53889
  stdio: "ignore",
@@ -53825,17 +54000,18 @@ async function verifyChange(ctx, results, undoable) {
53825
54000
  const timing = (phase, since, command) => {
53826
54001
  if (command) console.log(JSON.stringify({ event: "timing", phase, seconds: Math.round((now() - since) / 1e3) }));
53827
54002
  };
54003
+ const checkLimit = (at2) => commandLimitMs("check", { now: at2, stopAtMs: ctx.jobStopAtMs ?? Number.NaN, reserveMs: finalChecksReserveMs({ baselineMs: ctx.baselineMs }) });
53828
54004
  stage = "format";
53829
54005
  const formatStartedAt = now();
53830
54006
  try {
53831
- runCommand(packet.commands.format, "Format");
54007
+ await runLimitedCommand(packet.commands.format, "Format", checkLimit(formatStartedAt));
53832
54008
  } catch (err2) {
53833
54009
  console.error(`Format failed (not blocking): ${err2 instanceof Error ? err2.message : String(err2)}`);
53834
54010
  }
53835
54011
  timing("format", formatStartedAt, packet.commands.format);
53836
54012
  stage = "lint";
53837
54013
  const lintStartedAt = now();
53838
- runCommand(packet.commands.lint, "Lint");
54014
+ await runLimitedCommand(packet.commands.lint, "Lint", checkLimit(lintStartedAt));
53839
54015
  timing("lint", lintStartedAt, packet.commands.lint);
53840
54016
  stage = "gate";
53841
54017
  if (!packet.commands.test || packet.commands.test.trim() === "") return fail(new Error(unverifiedMessage("no_command")));
@@ -53852,7 +54028,8 @@ async function verifyChange(ctx, results, undoable) {
53852
54028
  return fail(new Error(gateTimeoutMessage(limit, ctx.baselineMs)));
53853
54029
  }
53854
54030
  timing("gate", gateStartedAt, packet.commands.test);
53855
- outputs.finalTestReport = readTestReportBytes();
54031
+ outputs.finalTestStartedAt = gateStartedAt;
54032
+ outputs.finalTestReport = readTestReportBytes(void 0, { freshSinceMs: gateStartedAt });
53856
54033
  outputs.testCount = after.results?.size;
53857
54034
  outputs.vanishedTests = findVanishedTests(baseline, after, ctx.ignoreVanished) ?? void 0;
53858
54035
  if (outputs.vanishedTests) {
@@ -53911,16 +54088,19 @@ async function verifyChange(ctx, results, undoable) {
53911
54088
  var MAX_LEFT_OUT_NAMES2 = 10;
53912
54089
  function checkGuardrail(deniedPaths, writeRoot = "") {
53913
54090
  addAll(writeRoot || void 0);
54091
+ const deleted = stagedDeletions();
54092
+ unstage(deleted);
54093
+ const deletionsLeftOut = { count: deleted.length, names: deleted.filter((p) => matchesDeniedPath(p, readDenied(deniedPaths)) === null).slice(0, MAX_LEFT_OUT_NAMES2) };
53914
54094
  const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
53915
54095
  if (violations.length > 0) {
53916
54096
  throw new Error(`QuikPilot touched denied paths:
53917
54097
  ${violations.join("\n")}`);
53918
54098
  }
53919
- if (!writeRoot) return { leftOut: 0, names: [], hidden: 0 };
54099
+ if (!writeRoot) return { leftOut: 0, names: [], hidden: 0, deletionsLeftOut };
53920
54100
  const outside = changedOutside(writeRoot);
53921
54101
  const protectedPatterns = readDenied(deniedPaths);
53922
54102
  const nameable = outside.filter((path) => matchesDeniedPath(path, protectedPatterns) === null);
53923
- return { leftOut: outside.length, names: nameable.slice(0, MAX_LEFT_OUT_NAMES2), hidden: outside.length - nameable.length };
54103
+ return { leftOut: outside.length, names: nameable.slice(0, MAX_LEFT_OUT_NAMES2), hidden: outside.length - nameable.length, deletionsLeftOut };
53924
54104
  }
53925
54105
 
53926
54106
  // src/run.ts
@@ -54482,6 +54662,50 @@ async function fetchPacket(packetUrl, runToken, githubRunId) {
54482
54662
  return body2.data;
54483
54663
  }
54484
54664
 
54665
+ // src/runnerSwitches.ts
54666
+ var RUNNER_SWITCHES = {
54667
+ // Opt-ins (named in QUIKPILOT_FEATURES on QuikProjects).
54668
+ QUIKPILOT_SCREEN_TRACE: ["on"],
54669
+ QUIKPILOT_RED_REVIEW: ["on"],
54670
+ QUIKPILOT_PARTS_CHECK: ["on"],
54671
+ QUIKPILOT_FEATURE_TEST_UPDATES: ["on"],
54672
+ QUIKPILOT_KEEP_WORKING_FILES: ["on"],
54673
+ // `on` opens run_scratch on any repository; `off` closes it everywhere.
54674
+ QUIKPILOT_RUN_SCRATCH: ["on", "off"],
54675
+ // Brakes (named in QUIKPILOT_RUNNER_OFF on QuikProjects).
54676
+ QUIKPILOT_KEEP_ON_GIVE_UP: ["off"],
54677
+ QUIKPILOT_TWO_PHASE: ["off"],
54678
+ QUIKPILOT_HUNK_CHECK: ["off"],
54679
+ QUIKPILOT_REVIEW_FIX: ["off"],
54680
+ QUIKPILOT_TESTS_CORRECTED: ["off"],
54681
+ QUIKPILOT_CALL_FUNCTION: ["off"],
54682
+ QUIKPILOT_FIX_FIRST: ["off"],
54683
+ QUIKPILOT_NOTES: ["off"],
54684
+ QUIKPILOT_TEST_LIMITS: ["off"],
54685
+ QUIKPILOT_TURN_RECOVERY: ["off"],
54686
+ QUIKPILOT_RELATED_TESTS: ["off"],
54687
+ QUIKPILOT_MAP: ["off"],
54688
+ QUIKPILOT_TOOLS2: ["off"],
54689
+ QUIKPILOT_TEST_RULES: ["js"],
54690
+ QUIKPILOT_TEST_LOCATE: ["js"],
54691
+ QUIKPILOT_ROW_NAMES: ["js"],
54692
+ QUIKPILOT_LANG_CHECKS: ["js"]
54693
+ };
54694
+ function applyPacketSwitches(fromPacket, env2 = process.env) {
54695
+ const result = { applied: [], ignored: [] };
54696
+ if (fromPacket === null || typeof fromPacket !== "object" || Array.isArray(fromPacket)) return result;
54697
+ for (const [name2, value] of Object.entries(fromPacket)) {
54698
+ const allowed = Object.prototype.hasOwnProperty.call(RUNNER_SWITCHES, name2) ? RUNNER_SWITCHES[name2] : void 0;
54699
+ if (allowed === void 0 || typeof value !== "string" || !allowed.includes(value)) {
54700
+ result.ignored.push(name2);
54701
+ continue;
54702
+ }
54703
+ env2[name2] = value;
54704
+ result.applied.push(name2);
54705
+ }
54706
+ return result;
54707
+ }
54708
+
54485
54709
  // src/phase0.ts
54486
54710
  var import_node_fs25 = require("node:fs");
54487
54711
  function writePhase0Marker(runId) {
@@ -54491,14 +54715,14 @@ function writePhase0Marker(runId) {
54491
54715
  }
54492
54716
 
54493
54717
  // src/failureArtifact.ts
54494
- var import_node_child_process13 = require("node:child_process");
54718
+ var import_node_child_process14 = require("node:child_process");
54495
54719
  var import_node_fs26 = require("node:fs");
54496
54720
  var import_node_path29 = require("node:path");
54497
54721
  var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
54498
54722
  var REPORT_COPY = "final-test-report.xml";
54499
54723
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
54500
54724
  var MAX_FILES = 200;
54501
- var RUNNER_VERSION = true ? "9.3.0-rc.87" : "dev";
54725
+ var RUNNER_VERSION = true ? "9.3.0-rc.89" : "dev";
54502
54726
  function safeDestination(base, repoPath) {
54503
54727
  if (!repoPath || (0, import_node_path29.isAbsolute)(repoPath)) return null;
54504
54728
  const destination = (0, import_node_path29.resolve)(base, repoPath);
@@ -54508,7 +54732,7 @@ function safeDestination(base, repoPath) {
54508
54732
  }
54509
54733
  var BUNDLE_FILE = "quikpilot-change.bundle";
54510
54734
  function keepCommitBundle(repo, folder, branch) {
54511
- const git4 = (args2) => (0, import_node_child_process13.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
54735
+ const git4 = (args2) => (0, import_node_child_process14.execFileSync)("git", [...NO_HOOKS_ARGS, ...args2], { env: gitEnv(), cwd: repo, encoding: "utf8", stdio: ["ignore", "pipe", "pipe"] }).trim();
54512
54736
  try {
54513
54737
  if (git4(["rev-parse", "--abbrev-ref", "HEAD"]) !== branch) return null;
54514
54738
  if (git4(["diff", "--name-only", "HEAD~1", "HEAD"]) === "") return null;
@@ -54580,11 +54804,11 @@ function writeFailureArtifact(input) {
54580
54804
  }
54581
54805
 
54582
54806
  // src/finalChange.ts
54583
- var import_node_child_process14 = require("node:child_process");
54807
+ var import_node_child_process15 = require("node:child_process");
54584
54808
  var import_node_fs27 = require("node:fs");
54585
54809
  var import_node_path30 = require("node:path");
54586
54810
  function statusPaths(root) {
54587
- const status = (0, import_node_child_process14.execFileSync)("git", [...NO_HOOKS_ARGS, "status", "--porcelain", "-z", "--untracked-files=all", "--no-renames"], {
54811
+ const status = (0, import_node_child_process15.execFileSync)("git", [...NO_HOOKS_ARGS, "status", "--porcelain", "-z", "--untracked-files=all", "--no-renames"], {
54588
54812
  env: gitEnv(),
54589
54813
  cwd: root,
54590
54814
  encoding: "utf8",
@@ -54616,7 +54840,7 @@ function allChangesAgainstBase(root) {
54616
54840
  }
54617
54841
 
54618
54842
  // src/nameEvidence.ts
54619
- var import_node_child_process15 = require("node:child_process");
54843
+ var import_node_child_process16 = require("node:child_process");
54620
54844
  var import_node_fs28 = require("node:fs");
54621
54845
  var import_node_path31 = require("node:path");
54622
54846
 
@@ -54683,7 +54907,7 @@ var escapeRegExp5 = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
54683
54907
  function filesNaming(word, ev, readable, denied) {
54684
54908
  let out2;
54685
54909
  try {
54686
- out2 = (0, import_node_child_process15.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-l", "-I", "-w", "-F", "-e", word], {
54910
+ out2 = (0, import_node_child_process16.execFileSync)("git", [...NO_HOOKS_ARGS, "grep", "-l", "-I", "-w", "-F", "-e", word], {
54687
54911
  env: gitEnv(),
54688
54912
  cwd: ev.cwd,
54689
54913
  encoding: "utf8",
@@ -54729,24 +54953,24 @@ var slashes = (p) => p.replace(/\\/g, "/");
54729
54953
  var withoutDotSlash = (p) => p.replace(/^(\.\/)+/, "");
54730
54954
  function relativeToRepository(raw, cwd) {
54731
54955
  const path = withoutDotSlash(slashes(raw.trim()));
54732
- let relative11 = path;
54956
+ let relative12 = path;
54733
54957
  if (path.startsWith("/") || DRIVE_RE.test(path)) {
54734
54958
  const root = slashes(cwd).replace(/\/+$/, "");
54735
54959
  const windows = DRIVE_RE.test(path) || DRIVE_RE.test(root);
54736
54960
  const a = windows ? path.toLowerCase() : path;
54737
54961
  const b = windows ? root.toLowerCase() : root;
54738
54962
  if (!a.startsWith(`${b}/`)) return null;
54739
- relative11 = path.slice(root.length + 1);
54963
+ relative12 = path.slice(root.length + 1);
54740
54964
  }
54741
- return relative11;
54965
+ return relative12;
54742
54966
  }
54743
54967
  function inListing(raw, listing, cwd, workspaceRoot) {
54744
- const relative11 = relativeToRepository(raw, cwd);
54745
- if (relative11 === null) return null;
54746
- if (listing.has(relative11)) return relative11;
54968
+ const relative12 = relativeToRepository(raw, cwd);
54969
+ if (relative12 === null) return null;
54970
+ if (listing.has(relative12)) return relative12;
54747
54971
  if (workspaceRoot) {
54748
54972
  const root = slashes(workspaceRoot).replace(/\/+$/, "");
54749
- const joined = `${root}/${relative11}`;
54973
+ const joined = `${root}/${relative12}`;
54750
54974
  if (listing.has(joined)) return joined;
54751
54975
  }
54752
54976
  return null;
@@ -55423,7 +55647,6 @@ async function exchangeForRunToken(tokenUrl, oidcToken) {
55423
55647
  }
55424
55648
 
55425
55649
  // src/run.ts
55426
- var JOB_RESERVE_MS = 7 * 6e4;
55427
55650
  var HUNK_CHECK_MAX_MS = 6 * 6e4;
55428
55651
  var HUNK_CHECK_MIN_BUDGET_MS = 3 * 6e4;
55429
55652
  var HUNK_CHECK_END_BEFORE_STOP_MS = 2 * 6e4;
@@ -55436,8 +55659,24 @@ function leftOutNote(root, out2) {
55436
55659
  const head = `${out2.leftOut} changed file${out2.leftOut === 1 ? "" : "s"} outside ${root} ${out2.leftOut === 1 ? "was" : "were"} left out of the pull request`;
55437
55660
  return `${head} (changed while the project's commands ran): ${listed}.`;
55438
55661
  }
55439
- async function run2(env2) {
55662
+ function deletionsLeftOutNote(out2) {
55663
+ const more = Math.max(0, out2.count - out2.names.length);
55664
+ const listed = out2.names.length > 0 ? `${out2.names.join(", ")}${more > 0 ? ` and ${more} more` : ""}` : `${out2.count} not named`;
55665
+ const one = out2.count === 1;
55666
+ return `${out2.count} file${one ? "" : "s"} in the repository that a command deleted during the run ${one ? "was" : "were"} left out of the pull request (${one ? "it is" : "they are"} not deleted): ${listed}.`;
55667
+ }
55668
+ async function run2(env2, opts = {}) {
55669
+ const guard = opts.guard ?? createFinalReportGuard({ killChildren: () => killAllChildren() });
55670
+ try {
55671
+ return await runUnderGuard(env2, guard);
55672
+ } finally {
55673
+ guard.disarm();
55674
+ }
55675
+ }
55676
+ async function runUnderGuard(env2, guard) {
55440
55677
  const runStartedAt = Date.now();
55678
+ let jobStopAtMs = Number.NaN;
55679
+ let baselineDurationMs;
55441
55680
  let hardFailure = false;
55442
55681
  let packet;
55443
55682
  let branch;
@@ -55455,6 +55694,7 @@ async function run2(env2) {
55455
55694
  let generatedFilePaths = [];
55456
55695
  let generatedResults = [];
55457
55696
  let finalTestReport = null;
55697
+ let finalTestStartedAt;
55458
55698
  let targetingResult;
55459
55699
  let baselineFindings;
55460
55700
  let vanishedTests;
@@ -55474,9 +55714,55 @@ async function run2(env2) {
55474
55714
  } catch {
55475
55715
  }
55476
55716
  };
55717
+ const finalReportBody = (forcedReason) => {
55718
+ const failed = hardFailure || forcedReason !== void 0;
55719
+ const reasons = forcedReason === void 0 ? failureReasons : [...failureReasons, forcedReason];
55720
+ const targetingRecord = targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0;
55721
+ const targetingUsage = clampTotals(spendOf("targeting"));
55722
+ if (targetingRecord?.loop && targetingUsage) targetingRecord.loop = { ...targetingRecord.loop, usage: targetingUsage };
55723
+ const codegenUsage = clampTotals(spendOf("codegen"));
55724
+ const codegenRecord = codegenOut.loop && codegenUsage ? { ...codegenOut.loop, usage: codegenUsage } : codegenOut.loop;
55725
+ return {
55726
+ status: failed ? "failed" : conflictStop ? "blocked" : "completed",
55727
+ branch,
55728
+ warnings,
55729
+ // Omitted when targeting itself never produced a result (nothing exists to record).
55730
+ targeting: targetingRecord,
55731
+ baselineFindings,
55732
+ vanishedTests,
55733
+ unsuppliedInputs,
55734
+ changesNoTestDependsOn,
55735
+ testsCorrected,
55736
+ codegenLoop: codegenRecord,
55737
+ unresolved: reasons.length > 0 ? reasons : void 0,
55738
+ aiCostUsd: spendSoFar().costUsd,
55739
+ ...testConflicts && !failed ? { testConflicts } : {},
55740
+ // Only for a run that is going to a pull request: a stop or a failure delivers none, so nothing is claimed as applied.
55741
+ ...approvedApplied && !failed && !conflictStop ? { approvedTestsApplied: approvedApplied } : {},
55742
+ // QUIKTR-2445: only for a completed run that pushed its branch: QuikProjects opens that pull request as a draft with the change at its top.
55743
+ ...databaseChange && !failed && !conflictStop && branch ? { databaseChange } : {}
55744
+ };
55745
+ };
55746
+ const lastResort = async (reason) => {
55747
+ if (!runToken) return;
55748
+ const message = reason === "time_limit" && packet ? jobTimeLimitMessage(packet.guardrails.maxWallClockMinutes) : jobStoppedMessage();
55749
+ let body2;
55750
+ try {
55751
+ body2 = finalReportBody(message);
55752
+ } catch {
55753
+ body2 = { status: "failed", unresolved: [message], ...branch ? { branch } : {} };
55754
+ }
55755
+ await reportBack({ callbackUrl: env2.callbackUrl, runToken, ...body2, urgent: true });
55756
+ };
55477
55757
  try {
55478
55758
  runToken = await exchangeForRunToken(env2.tokenUrl, await fetchGithubOidcToken());
55479
55759
  packet = await fetchPacket(env2.packetUrl, runToken, env2.githubRunId);
55760
+ const switches = applyPacketSwitches(packet.runnerSwitches);
55761
+ if (switches.applied.length + switches.ignored.length > 0) {
55762
+ console.log(JSON.stringify({ event: "runner.switches", applied: switches.applied, ignored: switches.ignored.length }));
55763
+ }
55764
+ jobStopAtMs = runStopAtMs(runStartedAt, packet.guardrails.maxWallClockMinutes);
55765
+ guard.arm({ stopAtMs: jobStopAtMs, watchdogAtMs: watchdogAtMs(jobStopAtMs), send: lastResort });
55480
55766
  checkoutTargetBranch(packet.targetBranch);
55481
55767
  const writeRoot = normaliseWorkspaceRoot(packet.workspaceRoot);
55482
55768
  scopeRoot = writeRoot;
@@ -55521,15 +55807,14 @@ async function run2(env2) {
55521
55807
  if (partsOn) console.log(JSON.stringify({ event: "parts_check.on", parts: designParts.length, ...designRead.cut > 0 ? { cut: designRead.cut } : {} }));
55522
55808
  const featureSwitch = featureTestUpdatesOn();
55523
55809
  const setupStartedAt = Date.now();
55524
- runCommand(packet.commands.setup, "Setup");
55810
+ await runLimitedCommand(packet.commands.setup, "Setup", commandLimitMs("setup", { now: setupStartedAt, stopAtMs: jobStopAtMs }));
55525
55811
  if (packet.commands.setup) console.log(JSON.stringify({ event: "timing", phase: "setup", seconds: Math.round((Date.now() - setupStartedAt) / 1e3) }));
55526
55812
  const baselineStartedAt = Date.now();
55527
- const jobStopAtMs = runStartedAt + packet.guardrails.maxWallClockMinutes * 6e4 - JOB_RESERVE_MS;
55528
55813
  const baselineLimit = testLimitsOff() ? null : baselineLimitMs(jobStopAtMs - baselineStartedAt);
55529
- const baselineRun = (baselineLimit === null ? captureBaselineSnapshot(packet.commands.test) : captureBaselineSnapshot(packet.commands.test, process.cwd(), { limitMs: baselineLimit })).then((snapshot) => ({
55530
- snapshot,
55531
- durationMs: Date.now() - baselineStartedAt
55532
- }));
55814
+ const baselineRun = (baselineLimit === null ? captureBaselineSnapshot(packet.commands.test) : captureBaselineSnapshot(packet.commands.test, process.cwd(), { limitMs: baselineLimit })).then((snapshot) => {
55815
+ baselineDurationMs = Date.now() - baselineStartedAt;
55816
+ return { snapshot, durationMs: baselineDurationMs };
55817
+ });
55533
55818
  pendingBaseline = baselineRun;
55534
55819
  const discovery = await resolveTestDiscovery({
55535
55820
  command: packet.commands.test,
@@ -55715,7 +56000,7 @@ async function run2(env2) {
55715
56000
  mode: codegenMode,
55716
56001
  ...keepOnGiveUp ? { keepOnGiveUp: true } : {},
55717
56002
  ...conflictsOn ? { conflicts: { decided, titles: approved?.titles ?? [], approvedTests: approved?.approvedTests ?? [] } } : {},
55718
- // QUIKTR-1851: write the fix first, then ask once; the project switched it on, and `QUIKPILOT_FIX_FIRST=off` turns it off without a rebuild.
56003
+ // QUIKTR-1851: write the fix first, then ask once; the project switched it on, and `QUIKPILOT_FIX_FIRST=off` turns it off (QuikProjects: `fix_first` in QUIKPILOT_RUNNER_OFF), no rebuild.
55719
56004
  ...conflictsOn && packet.fixFirst === true && process.env.QUIKPILOT_FIX_FIRST?.trim().toLowerCase() !== "off" ? { fixFirst: true } : {},
55720
56005
  // QUIKTR-2442: a feature run may propose add-only set-up for an existing test its change breaks.
55721
56006
  ...featureUpdates ? { featureTestUpdates: true } : {},
@@ -55766,6 +56051,14 @@ async function run2(env2) {
55766
56051
  out: codegenOut
55767
56052
  };
55768
56053
  const writeStartedAt = Date.now();
56054
+ if (Number.isFinite(jobStopAtMs)) {
56055
+ const reserveMs = finalChecksReserveMs({ baselineMs: baselineDurationMs, baselineLimitMs: baselineLimit });
56056
+ const writeStopAtMs = codegenStopAtMs({ now: writeStartedAt, budgetMs: CODEGEN_BUDGET_MS, stopAtMs: jobStopAtMs, reserveMs });
56057
+ const room = writeStopAtMs - writeStartedAt;
56058
+ console.log(JSON.stringify({ event: "deadline.write", stopInSeconds: Math.round(room / 1e3), reserveSeconds: Math.round(reserveMs / 1e3) }));
56059
+ if (room < MIN_WRITING_MS) throw new Error(writeNoTimeMessage(jobStopAtMs - writeStartedAt, reserveMs));
56060
+ stepParams.stopAtMs = writeStopAtMs;
56061
+ }
55769
56062
  const [timedBaseline, results] = await Promise.all([baselineRun, runCodegenStep(stepParams)]);
55770
56063
  const lastAttemptMs = Date.now() - writeStartedAt;
55771
56064
  console.log(JSON.stringify({ event: "timing", phase: "baseline", seconds: Math.round(timedBaseline.durationMs / 1e3), reportInTime: discovery.result.source === "live" }));
@@ -55884,6 +56177,7 @@ async function run2(env2) {
55884
56177
  unsuppliedInputs = final.outputs.unsuppliedInputs;
55885
56178
  generatedFilePaths = final.outputs.generatedFilePaths;
55886
56179
  finalTestReport = final.outputs.finalTestReport;
56180
+ finalTestStartedAt = final.outputs.finalTestStartedAt;
55887
56181
  vanishedTests = final.outputs.vanishedTests;
55888
56182
  if (fixed2.heal && codegenMode === "loop-tests") codegenOut.loop = mergeHealRecord(codegenOut.loop, fixed2.heal, healCalls);
55889
56183
  if (!final.ok) {
@@ -55994,8 +56288,11 @@ async function run2(env2) {
55994
56288
  githubServerUrl: env2.githubServerUrl,
55995
56289
  githubRepository: env2.githubRepository,
55996
56290
  githubRunId: env2.githubRunId,
55997
- generatedFiles: generatedFilePaths
56291
+ generatedFiles: generatedFilePaths,
56292
+ freshSinceMs: finalTestStartedAt
55998
56293
  });
56294
+ const removedReports = removeRunReports();
56295
+ if (removedReports > 0) console.log(JSON.stringify({ event: "quiktest.reports_removed", count: removedReports }));
55999
56296
  const unmatchedWarning = quikTestReport ? describeUnmatchedAutomationIds(quikTestReport.unmatched) : null;
56000
56297
  if (unmatchedWarning) {
56001
56298
  warnings.push(unmatchedWarning);
@@ -56022,6 +56319,10 @@ async function run2(env2) {
56022
56319
  warnings.push(leftOutNote(scopeRoot, guarded));
56023
56320
  console.log(JSON.stringify({ event: "scope.left_out", count: guarded.leftOut, ...guarded.hidden > 0 ? { hidden: guarded.hidden } : {} }));
56024
56321
  }
56322
+ if (guarded?.deletionsLeftOut && guarded.deletionsLeftOut.count > 0) {
56323
+ warnings.push(deletionsLeftOutNote(guarded.deletionsLeftOut));
56324
+ console.log(JSON.stringify({ event: "commit.deletions_left_out", count: guarded.deletionsLeftOut.count }));
56325
+ }
56025
56326
  const installationToken = await exchangeForInstallationToken(
56026
56327
  env2.installationTokenUrl,
56027
56328
  runToken
@@ -56057,33 +56358,8 @@ async function run2(env2) {
56057
56358
  console.warn(`::warning::Could not keep the failed run's files: ${err2 instanceof Error ? err2.message : String(err2)}`);
56058
56359
  }
56059
56360
  }
56060
- const targetingRecord = targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0;
56061
- const targetingUsage = clampTotals(spendOf("targeting"));
56062
- if (targetingRecord?.loop && targetingUsage) targetingRecord.loop = { ...targetingRecord.loop, usage: targetingUsage };
56063
- const codegenUsage = clampTotals(spendOf("codegen"));
56064
- const codegenRecord = codegenOut.loop && codegenUsage ? { ...codegenOut.loop, usage: codegenUsage } : codegenOut.loop;
56065
- await reportBack({
56066
- callbackUrl: env2.callbackUrl,
56067
- runToken,
56068
- status: hardFailure ? "failed" : conflictStop ? "blocked" : "completed",
56069
- branch,
56070
- warnings,
56071
- // Omitted when targeting itself never produced a result (nothing exists to record).
56072
- targeting: targetingRecord,
56073
- baselineFindings,
56074
- vanishedTests,
56075
- unsuppliedInputs,
56076
- changesNoTestDependsOn,
56077
- testsCorrected,
56078
- codegenLoop: codegenRecord,
56079
- unresolved: failureReasons.length > 0 ? failureReasons : void 0,
56080
- aiCostUsd: spendSoFar().costUsd,
56081
- ...testConflicts && !hardFailure ? { testConflicts } : {},
56082
- // Only for a run that is going to a pull request: a stop or a failure delivers none, so nothing is claimed as applied.
56083
- ...approvedApplied && !hardFailure && !conflictStop ? { approvedTestsApplied: approvedApplied } : {},
56084
- // QUIKTR-2445: only for a completed run that pushed its branch: QuikProjects opens that pull request as a draft with the change at its top.
56085
- ...databaseChange && !hardFailure && !conflictStop && branch ? { databaseChange } : {}
56086
- });
56361
+ if (!guard.claim()) return { hardFailure: true };
56362
+ await reportBack({ callbackUrl: env2.callbackUrl, runToken, ...finalReportBody() });
56087
56363
  return { hardFailure };
56088
56364
  }
56089
56365