@quikit/quikpilot-runner 9.3.0-rc.88 → 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
@@ -40071,6 +40071,7 @@ async function fetchWithRetry(url, init2, { retries = 2, backoffMs = 250 } = {})
40071
40071
  // src/callback.ts
40072
40072
  var REPORT_RETRY_STATUSES = /* @__PURE__ */ new Set([500, 502, 503, 504]);
40073
40073
  var REPORT_RETRY_WAITS_MS = [2e3, 5e3, 1e4];
40074
+ var URGENT_REPORT_TIMEOUT_MS = 6e3;
40074
40075
  async function reportBack(params) {
40075
40076
  const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, testsCorrected, codegenLoop, unresolved, aiCostUsd, testConflicts, approvedTestsApplied, databaseChange } = params;
40076
40077
  const sleep = params.sleep ?? ((ms) => new Promise((resolve6) => setTimeout(resolve6, ms)));
@@ -40090,7 +40091,7 @@ async function reportBack(params) {
40090
40091
  if (approvedTestsApplied && approvedTestsApplied.length > 0) body2.approvedTestsApplied = approvedTestsApplied;
40091
40092
  if (databaseChange && status === "completed") body2.databaseChange = databaseChange;
40092
40093
  const payload = JSON.stringify(body2);
40093
- const tries = REPORT_RETRY_WAITS_MS.length + 1;
40094
+ const tries = params.urgent ? 1 : REPORT_RETRY_WAITS_MS.length + 1;
40094
40095
  for (let attempt2 = 1; ; attempt2++) {
40095
40096
  let failure;
40096
40097
  let res;
@@ -40098,7 +40099,8 @@ async function reportBack(params) {
40098
40099
  res = await fetch(callbackUrl, {
40099
40100
  method: "POST",
40100
40101
  headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
40101
- body: payload
40102
+ body: payload,
40103
+ ...params.urgent ? { signal: AbortSignal.timeout(URGENT_REPORT_TIMEOUT_MS) } : {}
40102
40104
  });
40103
40105
  } catch (err2) {
40104
40106
  if (!isRetryableNetworkError(err2)) throw err2;
@@ -40122,6 +40124,87 @@ async function reportBack(params) {
40122
40124
 
40123
40125
  // src/commands.ts
40124
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
40125
40208
  var withheldLogged = false;
40126
40209
  function repositoryCommandEnv() {
40127
40210
  if (!withheldLogged) {
@@ -40173,6 +40256,7 @@ function runCommandWithTimeout(command, timeoutMs) {
40173
40256
  detached: true,
40174
40257
  env: repositoryCommandEnv()
40175
40258
  });
40259
+ track(child);
40176
40260
  const timer = setTimeout(() => {
40177
40261
  killProcessGroup(child);
40178
40262
  finish("timeout");
@@ -40181,6 +40265,30 @@ function runCommandWithTimeout(command, timeoutMs) {
40181
40265
  child.on("error", () => finish("error"));
40182
40266
  });
40183
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
+ }
40184
40292
  function killProcessGroup(child) {
40185
40293
  try {
40186
40294
  if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
@@ -40212,6 +40320,7 @@ function runCapturedCommand(argv, opts) {
40212
40320
  detached: true,
40213
40321
  env: repositoryCommandEnv()
40214
40322
  });
40323
+ track(child);
40215
40324
  child.stdout?.on("data", (chunk) => {
40216
40325
  if (bytes >= opts.maxStdoutBytes) return;
40217
40326
  const room = opts.maxStdoutBytes - bytes;
@@ -40254,6 +40363,7 @@ function runShellCaptured(command, opts) {
40254
40363
  detached: true,
40255
40364
  env: repositoryCommandEnv()
40256
40365
  });
40366
+ track(child);
40257
40367
  child.stdout?.on("data", keep);
40258
40368
  child.stderr?.on("data", keep);
40259
40369
  const timer = setTimeout(() => {
@@ -40285,6 +40395,7 @@ function runTestCommandWithLimit(command, timeoutMs, cwd) {
40285
40395
  env: repositoryCommandEnv(),
40286
40396
  ...cwd ? { cwd } : {}
40287
40397
  });
40398
+ track(child);
40288
40399
  const timer = setTimeout(() => {
40289
40400
  timedOut = true;
40290
40401
  killProcessGroup(child);
@@ -40295,123 +40406,395 @@ function runTestCommandWithLimit(command, timeoutMs, cwd) {
40295
40406
  });
40296
40407
  }
40297
40408
 
40298
- // src/testLimits.ts
40299
- var BASELINE_MIN_MS = 5 * 6e4;
40300
- var BASELINE_MAX_MS = 25 * 6e4;
40301
- var BASELINE_SHARE = 2.5;
40302
- var GATE_MIN_MS = 5 * 6e4;
40303
- var GATE_MAX_MS = 20 * 6e4;
40304
- var GATE_BASELINES = 2.5;
40305
- var GATE_MIN_START_MS = 6e4;
40306
- var FILE_RUN_LIMIT_MS = 3 * 6e4;
40307
- function testLimitsOff(env2 = process.env) {
40308
- return env2.QUIKPILOT_TEST_LIMITS?.trim().toLowerCase() === "off";
40309
- }
40310
- var clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
40311
- function baselineLimitMs(leftMs) {
40312
- if (!Number.isFinite(leftMs)) return null;
40313
- return Math.round(clamp(leftMs / BASELINE_SHARE, BASELINE_MIN_MS, BASELINE_MAX_MS));
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
+ };
40314
40463
  }
40315
- function gateLimitMs(i3) {
40316
- if (!Number.isFinite(i3.leftMs)) return null;
40317
- const baseline = typeof i3.baselineMs === "number" && Number.isFinite(i3.baselineMs) && i3.baselineMs >= 0 ? i3.baselineMs : 0;
40318
- if (i3.leftMs < Math.max(GATE_MIN_START_MS, baseline / 2)) return "no_time";
40319
- return Math.round(Math.min(clamp(baseline * GATE_BASELINES, GATE_MIN_MS, GATE_MAX_MS), i3.leftMs));
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";
40320
40476
  }
40321
- var minutes = (ms) => Math.max(1, Math.round(ms / 6e4));
40322
- function baselineTimeoutMessage(limitMs, jobMinutes) {
40323
- 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.`;
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);
40324
40486
  }
40325
- function gateTimeoutMessage(limitMs, baselineMs) {
40326
- const before = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they took ${minutes(baselineMs)} minutes before it)` : "";
40327
- 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.`;
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";
40328
40493
  }
40329
- function gateNoTimeMessage(baselineMs) {
40330
- const about = typeof baselineMs === "number" && Number.isFinite(baselineMs) && baselineMs > 0 ? ` (they take about ${minutes(baselineMs)} minutes)` : "";
40331
- 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.`;
40494
+ function truncationSentence(path, suspect) {
40495
+ return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
40332
40496
  }
40333
40497
 
40334
- // src/testPlan.ts
40335
- var import_node_crypto = require("node:crypto");
40336
- var import_node_fs10 = require("node:fs");
40337
- var import_node_os4 = require("node:os");
40338
- var import_node_path14 = require("node:path");
40339
-
40340
- // src/pairedTests.ts
40341
- var import_node_path9 = require("node:path");
40342
- var MAX_TESTS_PER_TARGET = 3;
40343
- var MAX_REVERSE_TEST_CHARS = 24e3;
40344
- var MAX_TEST_FILE_CHARS = 2e5;
40345
- var MAX_CORPUS_CHARS = 4e7;
40346
- var MAX_FILES_IN_BETWEEN = 150;
40347
- var COMMON_IMPORTER_LIMIT = 12;
40348
- var ROUTE_FILE_NAMES = /* @__PURE__ */ new Set(["route", "page", "layout", "index", "default", "loading", "error"]);
40349
- var TestCorpus = class {
40350
- constructor(listing, readFile, deniedPaths, isTest = isTestTarget) {
40351
- this.listing = listing;
40352
- this.readFile = readFile;
40353
- this.deniedPaths = deniedPaths;
40354
- this.isTest = isTest;
40355
- }
40356
- listing;
40357
- readFile;
40358
- deniedPaths;
40359
- isTest;
40360
- cached = null;
40361
- files() {
40362
- if (this.cached) return this.cached;
40363
- const out2 = [];
40364
- let total = 0;
40365
- for (const path of [...this.listing].sort()) {
40366
- if (!supportsImportScan(path) || !this.isTest(path) || matchesDeniedPath(path, this.deniedPaths)) continue;
40367
- let text3;
40368
- try {
40369
- text3 = this.readFile(path);
40370
- } catch {
40371
- continue;
40372
- }
40373
- if (text3.length > MAX_TEST_FILE_CHARS) continue;
40374
- total += text3.length;
40375
- if (total > MAX_CORPUS_CHARS) break;
40376
- out2.push({ path, text: text3 });
40377
- }
40378
- this.cached = out2;
40379
- return out2;
40380
- }
40381
- };
40382
- function stemOf(path) {
40383
- const base = import_node_path9.posix.basename(path).replace(/\.[cm]?[jt]sx?$/i, "");
40384
- return base === "index" ? import_node_path9.posix.basename(import_node_path9.posix.dirname(path)) : base;
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 };
40385
40531
  }
40386
- function sharedPrefix(a, b) {
40387
- const x = import_node_path9.posix.dirname(a).split("/");
40388
- const y = import_node_path9.posix.dirname(b).split("/");
40389
- let n = 0;
40390
- while (n < x.length && n < y.length && x[n] === y[n]) n++;
40391
- return n;
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";
40392
40536
  }
40393
- function namesOf(path) {
40394
- const base = import_node_path9.posix.basename(path).replace(/\.[cm]?[jt]sx?$/i, "").toLowerCase();
40395
- const names = base.length >= 2 ? [base] : [];
40396
- if (ROUTE_FILE_NAMES.has(base)) {
40397
- const parts2 = import_node_path9.posix.dirname(path).split("/").filter(Boolean);
40398
- while (parts2.length > 0 && /^[[(]/.test(parts2[parts2.length - 1])) parts2.pop();
40399
- const folder = parts2[parts2.length - 1];
40400
- if (folder && folder.length >= 3) names.push(folder.toLowerCase());
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 });
40401
40553
  }
40402
- return names;
40554
+ return { rows, cut: cut2 };
40403
40555
  }
40404
- var namedAfter = (test, path) => namesOf(path).some((n) => import_node_path9.posix.basename(test).toLowerCase().startsWith(n));
40405
- function testsImporting(p) {
40406
- if (p.limit <= 0 || (p.isTest ?? isTestTarget)(p.target) || !supportsImportScan(p.target)) return [];
40407
- const stem = stemOf(p.target);
40408
- if (stem.length < 2) return [];
40409
- const hits = [];
40410
- for (const file of p.corpus.files()) {
40411
- if (p.exclude?.has(file.path) || file.path === p.target || !file.text.includes(stem)) continue;
40412
- const imports = extractImportSpecifiers(file.text);
40413
- const imported = imports.some((spec) => {
40414
- const r = resolveImport(file.path, spec, p.listing, p.mapSpecifier);
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
+ };
40715
+ }
40716
+
40717
+ // src/testPlan.ts
40718
+ var import_node_crypto = require("node:crypto");
40719
+ var import_node_fs10 = require("node:fs");
40720
+ var import_node_os4 = require("node:os");
40721
+ var import_node_path14 = require("node:path");
40722
+
40723
+ // src/pairedTests.ts
40724
+ var import_node_path9 = require("node:path");
40725
+ var MAX_TESTS_PER_TARGET = 3;
40726
+ var MAX_REVERSE_TEST_CHARS = 24e3;
40727
+ var MAX_TEST_FILE_CHARS = 2e5;
40728
+ var MAX_CORPUS_CHARS = 4e7;
40729
+ var MAX_FILES_IN_BETWEEN = 150;
40730
+ var COMMON_IMPORTER_LIMIT = 12;
40731
+ var ROUTE_FILE_NAMES = /* @__PURE__ */ new Set(["route", "page", "layout", "index", "default", "loading", "error"]);
40732
+ var TestCorpus = class {
40733
+ constructor(listing, readFile, deniedPaths, isTest = isTestTarget) {
40734
+ this.listing = listing;
40735
+ this.readFile = readFile;
40736
+ this.deniedPaths = deniedPaths;
40737
+ this.isTest = isTest;
40738
+ }
40739
+ listing;
40740
+ readFile;
40741
+ deniedPaths;
40742
+ isTest;
40743
+ cached = null;
40744
+ files() {
40745
+ if (this.cached) return this.cached;
40746
+ const out2 = [];
40747
+ let total = 0;
40748
+ for (const path of [...this.listing].sort()) {
40749
+ if (!supportsImportScan(path) || !this.isTest(path) || matchesDeniedPath(path, this.deniedPaths)) continue;
40750
+ let text3;
40751
+ try {
40752
+ text3 = this.readFile(path);
40753
+ } catch {
40754
+ continue;
40755
+ }
40756
+ if (text3.length > MAX_TEST_FILE_CHARS) continue;
40757
+ total += text3.length;
40758
+ if (total > MAX_CORPUS_CHARS) break;
40759
+ out2.push({ path, text: text3 });
40760
+ }
40761
+ this.cached = out2;
40762
+ return out2;
40763
+ }
40764
+ };
40765
+ function stemOf(path) {
40766
+ const base = import_node_path9.posix.basename(path).replace(/\.[cm]?[jt]sx?$/i, "");
40767
+ return base === "index" ? import_node_path9.posix.basename(import_node_path9.posix.dirname(path)) : base;
40768
+ }
40769
+ function sharedPrefix(a, b) {
40770
+ const x = import_node_path9.posix.dirname(a).split("/");
40771
+ const y = import_node_path9.posix.dirname(b).split("/");
40772
+ let n = 0;
40773
+ while (n < x.length && n < y.length && x[n] === y[n]) n++;
40774
+ return n;
40775
+ }
40776
+ function namesOf(path) {
40777
+ const base = import_node_path9.posix.basename(path).replace(/\.[cm]?[jt]sx?$/i, "").toLowerCase();
40778
+ const names = base.length >= 2 ? [base] : [];
40779
+ if (ROUTE_FILE_NAMES.has(base)) {
40780
+ const parts2 = import_node_path9.posix.dirname(path).split("/").filter(Boolean);
40781
+ while (parts2.length > 0 && /^[[(]/.test(parts2[parts2.length - 1])) parts2.pop();
40782
+ const folder = parts2[parts2.length - 1];
40783
+ if (folder && folder.length >= 3) names.push(folder.toLowerCase());
40784
+ }
40785
+ return names;
40786
+ }
40787
+ var namedAfter = (test, path) => namesOf(path).some((n) => import_node_path9.posix.basename(test).toLowerCase().startsWith(n));
40788
+ function testsImporting(p) {
40789
+ if (p.limit <= 0 || (p.isTest ?? isTestTarget)(p.target) || !supportsImportScan(p.target)) return [];
40790
+ const stem = stemOf(p.target);
40791
+ if (stem.length < 2) return [];
40792
+ const hits = [];
40793
+ for (const file of p.corpus.files()) {
40794
+ if (p.exclude?.has(file.path) || file.path === p.target || !file.text.includes(stem)) continue;
40795
+ const imports = extractImportSpecifiers(file.text);
40796
+ const imported = imports.some((spec) => {
40797
+ const r = resolveImport(file.path, spec, p.listing, p.mapSpecifier);
40415
40798
  return r.kind === "repo" && r.path === p.target;
40416
40799
  });
40417
40800
  if (!imported) continue;
@@ -42732,6 +43115,7 @@ var MAX_FILE_ARG_CHARS = 300;
42732
43115
  var LINE_BREAK = /\r\n|\n|\r|&#0*10;|&#x0*a;/i;
42733
43116
  var CONTROL_CHARS = /[\u0000-\u0008\u000B\u000C\u000E-\u001F\u007F]/g;
42734
43117
  var FRESH_SLACK_MS2 = 2e3;
43118
+ var MIN_RUN_LIMIT_MS = 3e4;
42735
43119
  function testTimeLimitMs(baselineMs) {
42736
43120
  if (baselineMs === null) return DEFAULT_TEST_LIMIT_MS;
42737
43121
  if (baselineMs > MAX_TEST_LIMIT_MS) return "too_slow";
@@ -43020,8 +43404,9 @@ var RunTestsTool = class {
43020
43404
  const baselineMs = baseline?.durationMs ?? null;
43021
43405
  const plan = file === void 0 && d.planner ? d.planner.plan({ overlayPaths: files.map((f) => f.path), baselineMs }) : { scope: "full", why: null };
43022
43406
  const related = plan.scope === "related" ? plan : null;
43023
- const limit = related ? related.limitMs : testTimeLimitMs(baselineMs);
43024
- 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()));
43025
43410
  const findReport = d.findReport ?? findJUnitReport;
43026
43411
  const runCommand2 = d.runCommand ?? runTestCommandWithLimit;
43027
43412
  const readSnapshot = d.readSnapshot ?? readTestSnapshot;
@@ -43276,405 +43661,153 @@ function readHelperOutput(stdout) {
43276
43661
  if (o.kind === "returned" && typeof o.text === "string") return { kind: "returned", text: o.text };
43277
43662
  if (o.kind === "threw") return { kind: "threw", name: typeof o.name === "string" ? o.name : "Error", message: typeof o.message === "string" ? o.message : "" };
43278
43663
  if (o.kind === "not_found" || o.kind === "not_a_function") return { kind: o.kind };
43279
- } catch {
43280
- }
43281
- return null;
43282
- }
43283
- function bounded(text3, max, secrets) {
43284
- const clean = scrubForModel(text3, secrets).text;
43285
- return clean.length <= max ? clean : `${clean.slice(0, max - 1)}\u2026`;
43286
- }
43287
- function firstLineOf(text3) {
43288
- return text3.split(/\r\n|\n|\r/).find((l) => l.trim() !== "")?.trim() ?? "";
43289
- }
43290
- var CallFunctionTool = class {
43291
- constructor(deps) {
43292
- this.deps = deps;
43293
- this.maxCalls = deps.maxCalls ?? MAX_FUNCTION_CALLS;
43294
- }
43295
- deps;
43296
- calls = 0;
43297
- /** QUIKTR-1606 (§31.2): the last answer to each call, with the version of the change it was made on. */
43298
- answered = /* @__PURE__ */ new Map();
43299
- entries = [];
43300
- maxCalls;
43301
- /** Calls made so far. `run_scratch` (QUIKTR-1702) shares the budget, so the loop adds the two. */
43302
- get callsMade() {
43303
- return this.calls;
43304
- }
43305
- /** `remaining.functionCalls`. */
43306
- get callsLeft() {
43307
- return Math.max(0, this.maxCalls - this.calls);
43308
- }
43309
- record() {
43310
- return this.entries.map((e) => ({ ...e }));
43311
- }
43312
- answer(id, status, parts2 = {}) {
43313
- if (parts2.counted !== false) {
43314
- const entry = { n: this.entries.length + 1, status, ...parts2.reason ? { reason: parts2.reason } : {}, seconds: parts2.seconds ?? 0, chars: parts2.text?.length ?? 0 };
43315
- this.entries.push(entry);
43316
- this.deps.log?.({ event: "codegen.call_function", ...entry });
43317
- }
43318
- return {
43319
- id,
43320
- name: CALL_FUNCTION_TOOL,
43321
- status,
43322
- ...parts2.reason ? { reason: parts2.reason } : {},
43323
- message: MESSAGES2[status] ?? "",
43324
- ...parts2.text !== void 0 ? { output: { text: parts2.text } } : {}
43325
- };
43326
- }
43327
- /** The arguments, checked; `null` when they are not what the tool takes (then nothing runs). */
43328
- parseArgs(args2) {
43329
- if (typeof args2 !== "object" || args2 === null || Array.isArray(args2)) return null;
43330
- const a = args2;
43331
- if (Object.keys(a).some((k) => k !== "path" && k !== "export" && k !== "callArgs")) return null;
43332
- const { path, export: exportName, callArgs } = a;
43333
- if (typeof path !== "string" || path.length === 0 || path.length > 300) return null;
43334
- if (typeof exportName !== "string" || exportName.length > MAX_EXPORT_CHARS || !EXPORT_NAME.test(exportName)) return null;
43335
- if (typeof callArgs !== "string" || callArgs.length > MAX_CALL_ARGS_CHARS) return null;
43336
- let parsed;
43337
- try {
43338
- parsed = JSON.parse(callArgs);
43339
- } catch {
43340
- return null;
43341
- }
43342
- if (!Array.isArray(parsed)) return null;
43343
- return { path, exportName, callArgs: parsed };
43344
- }
43345
- async execute(callId, args2) {
43346
- const d = this.deps;
43347
- const now = d.now ?? Date.now;
43348
- if (this.calls >= this.maxCalls) return this.answer(callId, "budget_exhausted", { reason: "function_calls", counted: false });
43349
- const parsed = this.parseArgs(args2);
43350
- if (!parsed) return this.answer(callId, "bad_args", { counted: false });
43351
- const files = d.overlayFiles();
43352
- const known = d.listing.includes(parsed.path) || files.some((f) => f.path === parsed.path);
43353
- if (!known || matchesDeniedPath(parsed.path, d.deniedPaths) !== null) return this.answer(callId, "bad_args", { counted: false });
43354
- if (!JS_FILE.test(parsed.path) || testRule(d.discoveredTests)(parsed.path) || d.protectedTestPaths.includes(parsed.path)) {
43355
- return this.answer(callId, "call_unavailable", { reason: "unsupported_file", counted: false });
43356
- }
43357
- const key = JSON.stringify([parsed.path, parsed.exportName, parsed.callArgs]);
43358
- const version2 = versionOfFiles(files);
43359
- const before = this.answered.get(key);
43360
- if (before && before.version === version2) {
43361
- return {
43362
- id: callId,
43363
- name: CALL_FUNCTION_TOOL,
43364
- status: "duplicate",
43365
- reason: before.id,
43366
- message: `Same call as ${before.id}: this is its answer again; nothing was run or changed again.`,
43367
- ...before.result.output !== void 0 ? { output: before.result.output } : {}
43368
- };
43369
- }
43370
- const result = await this.runOnce(callId, parsed, files);
43371
- const done = result.status === "ok" || result.status === "call_threw" || result.status === "call_unavailable" && (result.reason === "not_found" || result.reason === "not_a_function" || result.reason === "timed_out");
43372
- if (done) this.answered.set(key, { id: callId, version: version2, result });
43373
- return result;
43374
- }
43375
- async runOnce(callId, parsed, files) {
43376
- const d = this.deps;
43377
- const now = d.now ?? Date.now;
43378
- const helper = {
43379
- path: `.quikpilot-call-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}.mjs`,
43380
- content: helperSource({ target: (0, import_node_path19.join)(d.root, parsed.path), exportName: parsed.exportName, args: parsed.callArgs })
43381
- };
43382
- const run3 = d.run ?? runCapturedCommand;
43383
- this.calls += 1;
43384
- const startedAt = now();
43385
- let captured;
43386
- try {
43387
- captured = await withOverlayOnDisk(
43388
- d.root,
43389
- [...files, helper],
43390
- () => run3([d.nodePath ?? process.execPath, (0, import_node_path19.join)(d.root, helper.path)], { cwd: d.root, timeoutMs: d.timeoutMs ?? CALL_TIMEOUT_MS, maxStdoutBytes: MAX_STDOUT_BYTES }),
43391
- { ...d.tree }
43392
- );
43393
- } catch (err2) {
43394
- if (err2 instanceof TreeNotRestoredError) throw err2;
43395
- this.calls -= 1;
43396
- if (err2 instanceof TreeUnverifiableError) return this.answer(callId, "call_unavailable", { reason: "checkout_unverifiable" });
43397
- if (err2 instanceof DiskWriteRefused) return this.answer(callId, "call_unavailable", { reason: "write_refused" });
43398
- throw err2;
43399
- }
43400
- const seconds = Math.round((now() - startedAt) / 1e3);
43401
- const secrets = d.secrets ?? [];
43402
- if (!captured.started) {
43403
- this.calls -= 1;
43404
- return this.answer(callId, "call_unavailable", { reason: "could_not_start", seconds });
43405
- }
43406
- if (captured.timedOut) return this.answer(callId, "call_unavailable", { reason: "timed_out", seconds });
43407
- const out2 = readHelperOutput(captured.stdout);
43408
- if (!out2) return this.answer(callId, "call_unavailable", { reason: "could_not_start", seconds });
43409
- if (out2.kind === "not_found" || out2.kind === "not_a_function") return this.answer(callId, "call_unavailable", { reason: out2.kind, seconds });
43410
- if (out2.kind === "threw") {
43411
- return this.answer(callId, "call_threw", { seconds, text: bounded(`${out2.name}: ${firstLineOf(out2.message)}`, MAX_THREW_CHARS, secrets) });
43412
- }
43413
- return this.answer(callId, "ok", { seconds, text: bounded(out2.text, MAX_CALL_TEXT_CHARS, secrets) });
43414
- }
43415
- };
43416
- async function executeCallFunctionCall(call, tool, ledger, limits) {
43417
- if (ledger.toolCalls >= limits.maxToolCalls) {
43418
- const result2 = { id: call.id, name: call.name, ...budgetResult("tool_calls") };
43419
- ledger.resultChars += JSON.stringify(result2).length;
43420
- return result2;
43421
- }
43422
- ledger.toolCalls += 1;
43423
- const result = await tool.execute(call.id, call.args);
43424
- ledger.resultChars += JSON.stringify(result).length;
43425
- return result;
43426
- }
43427
-
43428
- // src/attemptSentences.ts
43429
- var MAX_PREVIOUS_DETAIL_CHARS = 300;
43430
- var MAX_PREVIOUS_RULES = 15;
43431
- var MAX_PREVIOUS_TESTS = 20;
43432
- var MAX_PREVIOUS_NAME_CHARS = 200;
43433
- var MAX_PREVIOUS_WHOLE_MESSAGE_CHARS = 1e3;
43434
- var MAX_PREVIOUS_MESSAGES_TOTAL_CHARS = 4e3;
43435
- var MAX_PREVIOUS_COUNT = 1e5;
43436
- var RUNTIME_CODE_SHAPE = /^[A-Z][A-Z0-9_]{0,39}$/;
43437
- function runtimeCodeWord(code) {
43438
- return RUNTIME_CODE_SHAPE.test(code) ? code : "other";
43439
- }
43440
- var COVERAGE_PREFIX = "Required test cases not written: ";
43441
- function coverageSentence(ids) {
43442
- const total = ids.length;
43443
- for (let shown = total; shown >= 1; shown--) {
43444
- const rest = total - shown;
43445
- const text3 = `${COVERAGE_PREFIX}${ids.slice(0, shown).join(", ")}${rest > 0 ? `, and ${rest} more` : ""}.`;
43446
- if (text3.length <= MAX_PREVIOUS_DETAIL_CHARS) return text3;
43447
- }
43448
- return `${COVERAGE_PREFIX}${total} of them.`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
43449
- }
43450
- function truncationPhrase(suspect) {
43451
- if (/^contains placeholder text/i.test(suspect)) return "placeholder text that suggests an abbreviated rewrite";
43452
- if (/^sharp length drop/i.test(suspect)) return "a sharp drop in length";
43453
- if (/^removed \d+ of \d+ lines/i.test(suspect)) return "many lines removed";
43454
- if (/^removed exported symbol/i.test(suspect)) return "some of the file's exports were removed";
43455
- return "the file came out much shorter than the original";
43456
- }
43457
- function truncationSentence(path, suspect) {
43458
- return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
43459
- }
43460
-
43461
- // src/refusedReply.ts
43462
- var REFUSED_OUTCOME = "REFUSED";
43463
- var REFUSED_STREAK_LIMIT = 3;
43464
- var MAX_REFUSED_RULES = 8;
43465
- var MAX_REFUSED_SENTENCES = 8;
43466
- var MAX_REFUSED_SENTENCE_CHARS = 300;
43467
- var MAX_REFUSED_RULE_CHARS = 40;
43468
- var REFUSED_RULE_IDS = [
43469
- "reply_shape",
43470
- "last_turn",
43471
- "no_calls_left",
43472
- "too_many_calls",
43473
- "call_id",
43474
- "unknown_tool",
43475
- "bad_args",
43476
- "bad_path",
43477
- "protected_path",
43478
- "file_state",
43479
- "budget",
43480
- "run_tests_rule",
43481
- "repeat_call",
43482
- "done_rule",
43483
- "length"
43484
- ];
43485
- var KNOWN_RULES = new Set(REFUSED_RULE_IDS);
43486
- function readRefusedAnswer(body2) {
43487
- const { rules, violations, message } = body2;
43488
- if (!Array.isArray(rules) || rules.length < 1 || rules.length > MAX_REFUSED_RULES) return null;
43489
- if (!rules.every((r) => typeof r === "string" && r.length > 0 && r.length <= MAX_REFUSED_RULE_CHARS)) return null;
43490
- if (!Array.isArray(violations) || violations.length < 1 || violations.length > MAX_REFUSED_SENTENCES) return null;
43491
- if (!violations.every((v) => typeof v === "string" && v.length <= MAX_REFUSED_SENTENCE_CHARS)) return null;
43492
- if (typeof message !== "string" || message.length > MAX_REFUSED_SENTENCE_CHARS) return null;
43493
- return { rules: [...rules], violations: [...violations], message };
43494
- }
43495
- var RULE_WORD_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
43496
- function recordRuleWord(word) {
43497
- if (typeof word !== "string") return "other";
43498
- return KNOWN_RULES.has(word) || RULE_WORD_SHAPE.test(word) ? word : "other";
43499
- }
43500
- var MAX_RECORD_REFUSED_TURNS = 30;
43501
- var MAX_RECORD_REFUSED_RULES = 8;
43502
- function wholeNumber(n) {
43503
- return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
43504
- }
43505
- function clampRefusedTurns(turns) {
43506
- const rows = [];
43507
- let cut2 = false;
43508
- for (const t of turns ?? []) {
43509
- if (rows.length >= MAX_RECORD_REFUSED_TURNS) {
43510
- cut2 = true;
43511
- break;
43512
- }
43513
- if (t.rules.length > MAX_RECORD_REFUSED_RULES) cut2 = true;
43514
- const rules = [...new Set(t.rules.map(recordRuleWord))].slice(0, MAX_RECORD_REFUSED_RULES);
43515
- if (rules.length > 0) rows.push({ turn: wholeNumber(t.turn), rules });
43516
- }
43517
- return { rows, cut: cut2 };
43518
- }
43519
-
43520
- // src/codegenAttempts.ts
43521
- var CODEGEN_BUDGET_MS = 30 * 6e4;
43522
- var MIN_SECOND_ATTEMPT_MS = 3 * 6e4;
43523
- function secondAttemptFloorMs(a) {
43524
- return Math.max(a.firstAttemptMs, a.testLimitMs ?? 0, MIN_SECOND_ATTEMPT_MS);
43525
- }
43526
- var REASON_WORDS = {
43527
- contract_rejected: "the AI service did not accept the request (it may be switched off)",
43528
- test_case_disagree: "its code and its own test for an approved case still disagreed after one correction of the test",
43529
- no_test_shows_bug: "none of its tests failed on the code before the change, so none of them showed the bug",
43530
- semantic_mismatch: "the AI service and the runner disagreed about the request",
43531
- http_error: "the AI service returned an error",
43532
- transport: "the AI service could not be reached",
43533
- turn_timeout: "one step took too long",
43534
- loop_deadline: "the whole change took too long",
43535
- runtime_failed: "the AI service returned an error",
43536
- // QUIKTR-1824: the AI Service's CODEGEN_OUTPUT_TOO_LARGE / OUTPUT_TRUNCATED; told apart from a failing service (live run QTRIA-12).
43537
- output_too_large: "the AI's answer was too long and was cut off",
43538
- bad_reply: "the AI service sent a reply that could not be used",
43539
- duplicate_call_ids: "the AI service repeated a request",
43540
- final_not_produced: "it never reached an answer",
43541
- token_ceiling: "the request grew too large for one step",
43542
- executor_error: "reading or changing the code failed",
43543
- internal_error: "the runner hit an internal error",
43544
- cannot_complete: "the AI said it could not make the change from what it could see",
43545
- no_writes: "it said it was finished but had changed nothing",
43546
- coverage_missing: "it said it was finished but had not written a test for every case",
43547
- truncation_guard: "a file it rewrote looked cut short",
43548
- syntax_error: "a file it changed would not run (a syntax error, or a name that is used but never defined or imported)",
43549
- out_of_time: "the time allowed for writing the change ran out",
43550
- // 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.
43551
- 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",
43552
- 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",
43553
- // QUIKTR-2325 / QUIKTR-2326: the parts check. Only `part_missing` ends an attempt; the other two stop the run before any code.
43554
- part_missing: "it said it was finished but had not built every part of the feature the design lists",
43555
- part_not_placed: "the plan chose no file for a part of the feature the design lists",
43556
- needs_database_change: "the feature needs a stored value (a database change) QuikPilot cannot make here"
43557
- };
43558
- function reasonInWords(reason) {
43559
- return REASON_WORDS[reason] ?? reason;
43560
- }
43561
- function failedAttemptRecord(n, failure) {
43562
- return {
43563
- n,
43564
- outcome: "failed",
43565
- reason: failure.reason,
43566
- ...failure.runtimeCode ? { runtimeCode: runtimeCodeWord(failure.runtimeCode) } : {},
43567
- ...failure.afterRecovery ? { afterRecovery: true } : {},
43568
- turns: failure.summary?.turns ?? 0,
43569
- toolCalls: failure.summary?.toolCalls ?? 0
43570
- };
43664
+ } catch {
43665
+ }
43666
+ return null;
43571
43667
  }
43572
- function attemptInWords(a, fallback) {
43573
- 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);
43574
- return a?.runtimeCode && a.runtimeCode !== "other" ? `${words2} (error code ${a.runtimeCode})` : words2;
43668
+ function bounded(text3, max, secrets) {
43669
+ const clean = scrubForModel(text3, secrets).text;
43670
+ return clean.length <= max ? clean : `${clean.slice(0, max - 1)}\u2026`;
43575
43671
  }
43576
- function exhaustedMessage(attempts, stop2, unreportable) {
43577
- const first = attempts[0];
43578
- const second = attempts[1];
43579
- const firstWords = attemptInWords(first, "internal_error");
43580
- const blocking = unreportable[0];
43581
- if (blocking) {
43582
- const more = unreportable.length > 1 ? `, and ${unreportable.length - 1} more like it` : "";
43583
- 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.`;
43672
+ function firstLineOf(text3) {
43673
+ return text3.split(/\r\n|\n|\r/).find((l) => l.trim() !== "")?.trim() ?? "";
43674
+ }
43675
+ var CallFunctionTool = class {
43676
+ constructor(deps) {
43677
+ this.deps = deps;
43678
+ this.maxCalls = deps.maxCalls ?? MAX_FUNCTION_CALLS;
43584
43679
  }
43585
- if (stop2 === "failed" && attempts.length === 1 && first?.reason === "test_case_disagree") {
43586
- 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.";
43680
+ deps;
43681
+ calls = 0;
43682
+ /** QUIKTR-1606 (§31.2): the last answer to each call, with the version of the change it was made on. */
43683
+ answered = /* @__PURE__ */ new Map();
43684
+ entries = [];
43685
+ maxCalls;
43686
+ /** Calls made so far. `run_scratch` (QUIKTR-1702) shares the budget, so the loop adds the two. */
43687
+ get callsMade() {
43688
+ return this.calls;
43587
43689
  }
43588
- if (stop2 === "failed") {
43589
- 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.`;
43690
+ /** `remaining.functionCalls`. */
43691
+ get callsLeft() {
43692
+ return Math.max(0, this.maxCalls - this.calls);
43590
43693
  }
43591
- const head = "QuikPilot could not write the change in the time allowed. ";
43592
- if (second?.outcome === "not_started") {
43593
- 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.`;
43694
+ record() {
43695
+ return this.entries.map((e) => ({ ...e }));
43594
43696
  }
43595
- return `${head}The first attempt ended because ${firstWords}. The second attempt ended because ${attemptInWords(second, "out_of_time")}. Nothing was written.`;
43596
- }
43597
- var CodegenAttemptsExhausted = class extends Error {
43598
- attempts;
43599
- /** `out_of_time` when the shared clock decided the end, `failed` when both attempts ended without a result for any other reason. */
43600
- stopReason;
43601
- /** QUIKTR-1823: existing tests written once for many rows that stood in the way (path, line, case), when that is why the step ended. */
43602
- unreportable;
43603
- /**
43604
- * QUIKTR-2325: `partsMissing` - the runner's own sentence naming the parts of the feature the last attempt did not build (`part_missing`).
43605
- * 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.
43606
- * Built from the design's words and the planned paths; never a file's text.
43607
- */
43608
- constructor(attempts, stopReason, unreportable = [], partsMissing) {
43609
- const message = exhaustedMessage(attempts, stopReason, unreportable);
43610
- super(partsMissing ? `${partsMissing} ${message}` : message);
43611
- this.name = "CodegenAttemptsExhausted";
43612
- this.attempts = attempts;
43613
- this.stopReason = stopReason;
43614
- this.unreportable = [...unreportable];
43697
+ answer(id, status, parts2 = {}) {
43698
+ if (parts2.counted !== false) {
43699
+ const entry = { n: this.entries.length + 1, status, ...parts2.reason ? { reason: parts2.reason } : {}, seconds: parts2.seconds ?? 0, chars: parts2.text?.length ?? 0 };
43700
+ this.entries.push(entry);
43701
+ this.deps.log?.({ event: "codegen.call_function", ...entry });
43702
+ }
43703
+ return {
43704
+ id,
43705
+ name: CALL_FUNCTION_TOOL,
43706
+ status,
43707
+ ...parts2.reason ? { reason: parts2.reason } : {},
43708
+ message: MESSAGES2[status] ?? "",
43709
+ ...parts2.text !== void 0 ? { output: { text: parts2.text } } : {}
43710
+ };
43615
43711
  }
43616
- };
43617
- var RULE_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
43618
- function count2(n) {
43619
- return typeof n === "number" && Number.isInteger(n) ? Math.min(MAX_PREVIOUS_COUNT, Math.max(0, n)) : 0;
43620
- }
43621
- function isRecord(x) {
43622
- return typeof x === "object" && x !== null && !Array.isArray(x);
43623
- }
43624
- function testRunFrom(answer) {
43625
- if (!isRecord(answer)) return void 0;
43626
- const numbers = ["passed", "failed", "total", "regressions", "newFailures", "alreadyFailing"];
43627
- if (!numbers.every((k) => typeof answer[k] === "number") || !Array.isArray(answer.failingTests)) return void 0;
43628
- 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);
43629
- const run3 = {
43630
- passed: count2(answer.passed),
43631
- failed: count2(answer.failed),
43632
- total: count2(answer.total),
43633
- regressions: count2(answer.regressions),
43634
- newFailures: count2(answer.newFailures),
43635
- alreadyFailing: count2(answer.alreadyFailing),
43636
- failingTests
43637
- };
43638
- if (isRecord(answer.messages)) {
43639
- const listed = new Set(failingTests);
43640
- const messages = {};
43641
- let total = 0;
43642
- for (const [name2, text3] of Object.entries(answer.messages)) {
43643
- const key = name2.slice(0, MAX_PREVIOUS_NAME_CHARS);
43644
- if (typeof text3 !== "string" || !listed.has(key) || Object.keys(messages).length >= MAX_PREVIOUS_TESTS) continue;
43645
- const cut2 = text3.slice(0, Math.min(MAX_PREVIOUS_WHOLE_MESSAGE_CHARS, MAX_PREVIOUS_MESSAGES_TOTAL_CHARS - total));
43646
- if (cut2.length > 0) {
43647
- messages[key] = cut2;
43648
- total += cut2.length;
43649
- }
43712
+ /** The arguments, checked; `null` when they are not what the tool takes (then nothing runs). */
43713
+ parseArgs(args2) {
43714
+ if (typeof args2 !== "object" || args2 === null || Array.isArray(args2)) return null;
43715
+ const a = args2;
43716
+ if (Object.keys(a).some((k) => k !== "path" && k !== "export" && k !== "callArgs")) return null;
43717
+ const { path, export: exportName, callArgs } = a;
43718
+ if (typeof path !== "string" || path.length === 0 || path.length > 300) return null;
43719
+ if (typeof exportName !== "string" || exportName.length > MAX_EXPORT_CHARS || !EXPORT_NAME.test(exportName)) return null;
43720
+ if (typeof callArgs !== "string" || callArgs.length > MAX_CALL_ARGS_CHARS) return null;
43721
+ let parsed;
43722
+ try {
43723
+ parsed = JSON.parse(callArgs);
43724
+ } catch {
43725
+ return null;
43650
43726
  }
43651
- if (Object.keys(messages).length > 0) run3.messages = messages;
43727
+ if (!Array.isArray(parsed)) return null;
43728
+ return { path, exportName, callArgs: parsed };
43652
43729
  }
43653
- return run3;
43654
- }
43655
- function rulesFrom(rows) {
43656
- if (!Array.isArray(rows) || rows.length === 0) return void 0;
43657
- const counts = /* @__PURE__ */ new Map();
43658
- for (const row of rows) {
43659
- for (const raw of row.rules) {
43660
- const word = recordRuleWord(raw);
43661
- counts.set(word, (counts.get(word) ?? 0) + 1);
43730
+ async execute(callId, args2) {
43731
+ const d = this.deps;
43732
+ const now = d.now ?? Date.now;
43733
+ if (this.calls >= this.maxCalls) return this.answer(callId, "budget_exhausted", { reason: "function_calls", counted: false });
43734
+ const parsed = this.parseArgs(args2);
43735
+ if (!parsed) return this.answer(callId, "bad_args", { counted: false });
43736
+ const files = d.overlayFiles();
43737
+ const known = d.listing.includes(parsed.path) || files.some((f) => f.path === parsed.path);
43738
+ if (!known || matchesDeniedPath(parsed.path, d.deniedPaths) !== null) return this.answer(callId, "bad_args", { counted: false });
43739
+ if (!JS_FILE.test(parsed.path) || testRule(d.discoveredTests)(parsed.path) || d.protectedTestPaths.includes(parsed.path)) {
43740
+ return this.answer(callId, "call_unavailable", { reason: "unsupported_file", counted: false });
43741
+ }
43742
+ const key = JSON.stringify([parsed.path, parsed.exportName, parsed.callArgs]);
43743
+ const version2 = versionOfFiles(files);
43744
+ const before = this.answered.get(key);
43745
+ if (before && before.version === version2) {
43746
+ return {
43747
+ id: callId,
43748
+ name: CALL_FUNCTION_TOOL,
43749
+ status: "duplicate",
43750
+ reason: before.id,
43751
+ message: `Same call as ${before.id}: this is its answer again; nothing was run or changed again.`,
43752
+ ...before.result.output !== void 0 ? { output: before.result.output } : {}
43753
+ };
43662
43754
  }
43755
+ const result = await this.runOnce(callId, parsed, files);
43756
+ const done = result.status === "ok" || result.status === "call_threw" || result.status === "call_unavailable" && (result.reason === "not_found" || result.reason === "not_a_function" || result.reason === "timed_out");
43757
+ if (done) this.answered.set(key, { id: callId, version: version2, result });
43758
+ return result;
43663
43759
  }
43664
- 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);
43665
- return ordered.length > 0 ? ordered.slice(0, MAX_PREVIOUS_RULES) : void 0;
43666
- }
43667
- function previousAttemptFrom(failure, attempt2) {
43668
- const told = typeof failure.told === "string" ? failure.told.slice(0, MAX_PREVIOUS_DETAIL_CHARS) : "";
43669
- const lastTestRun = testRunFrom(failure.lastTestAnswer);
43670
- const rules = rulesFrom(failure.summary?.refusedTurns);
43671
- return {
43672
- attempt: attempt2,
43673
- endedWith: RULE_SHAPE.test(failure.reason) ? failure.reason : "other",
43674
- ...told.length > 0 ? { detail: told } : {},
43675
- ...lastTestRun ? { lastTestRun } : {},
43676
- ...rules ? { rules } : {}
43677
- };
43760
+ async runOnce(callId, parsed, files) {
43761
+ const d = this.deps;
43762
+ const now = d.now ?? Date.now;
43763
+ const helper = {
43764
+ path: `.quikpilot-call-${(0, import_node_crypto4.randomBytes)(6).toString("hex")}.mjs`,
43765
+ content: helperSource({ target: (0, import_node_path19.join)(d.root, parsed.path), exportName: parsed.exportName, args: parsed.callArgs })
43766
+ };
43767
+ const run3 = d.run ?? runCapturedCommand;
43768
+ this.calls += 1;
43769
+ const startedAt = now();
43770
+ let captured;
43771
+ try {
43772
+ captured = await withOverlayOnDisk(
43773
+ d.root,
43774
+ [...files, helper],
43775
+ () => run3([d.nodePath ?? process.execPath, (0, import_node_path19.join)(d.root, helper.path)], { cwd: d.root, timeoutMs: d.timeoutMs ?? CALL_TIMEOUT_MS, maxStdoutBytes: MAX_STDOUT_BYTES }),
43776
+ { ...d.tree }
43777
+ );
43778
+ } catch (err2) {
43779
+ if (err2 instanceof TreeNotRestoredError) throw err2;
43780
+ this.calls -= 1;
43781
+ if (err2 instanceof TreeUnverifiableError) return this.answer(callId, "call_unavailable", { reason: "checkout_unverifiable" });
43782
+ if (err2 instanceof DiskWriteRefused) return this.answer(callId, "call_unavailable", { reason: "write_refused" });
43783
+ throw err2;
43784
+ }
43785
+ const seconds = Math.round((now() - startedAt) / 1e3);
43786
+ const secrets = d.secrets ?? [];
43787
+ if (!captured.started) {
43788
+ this.calls -= 1;
43789
+ return this.answer(callId, "call_unavailable", { reason: "could_not_start", seconds });
43790
+ }
43791
+ if (captured.timedOut) return this.answer(callId, "call_unavailable", { reason: "timed_out", seconds });
43792
+ const out2 = readHelperOutput(captured.stdout);
43793
+ if (!out2) return this.answer(callId, "call_unavailable", { reason: "could_not_start", seconds });
43794
+ if (out2.kind === "not_found" || out2.kind === "not_a_function") return this.answer(callId, "call_unavailable", { reason: out2.kind, seconds });
43795
+ if (out2.kind === "threw") {
43796
+ return this.answer(callId, "call_threw", { seconds, text: bounded(`${out2.name}: ${firstLineOf(out2.message)}`, MAX_THREW_CHARS, secrets) });
43797
+ }
43798
+ return this.answer(callId, "ok", { seconds, text: bounded(out2.text, MAX_CALL_TEXT_CHARS, secrets) });
43799
+ }
43800
+ };
43801
+ async function executeCallFunctionCall(call, tool, ledger, limits) {
43802
+ if (ledger.toolCalls >= limits.maxToolCalls) {
43803
+ const result2 = { id: call.id, name: call.name, ...budgetResult("tool_calls") };
43804
+ ledger.resultChars += JSON.stringify(result2).length;
43805
+ return result2;
43806
+ }
43807
+ ledger.toolCalls += 1;
43808
+ const result = await tool.execute(call.id, call.args);
43809
+ ledger.resultChars += JSON.stringify(result).length;
43810
+ return result;
43678
43811
  }
43679
43812
 
43680
43813
  // src/anchorPlaces.ts
@@ -50017,6 +50150,8 @@ async function runCodegenLoop(args2, deps) {
50017
50150
  isRunnableTestFile: (path) => matchesDeniedPath(path, args2.deniedPaths) === null && (looksLikeTest(path) || args2.protectedTestPaths.includes(path)) && (args2.listing.includes(path) || overlay.changedPaths().includes(path)),
50018
50151
  overlayFiles: filesOnDisk,
50019
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 } : {},
50020
50155
  log,
50021
50156
  now
50022
50157
  }) : null;
@@ -52360,7 +52495,7 @@ async function runCodegenStep(p) {
52360
52495
  );
52361
52496
  const now = p.deps?.now ?? Date.now;
52362
52497
  const log = p.deps?.log ?? ((e) => console.log(JSON.stringify(e)));
52363
- 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 });
52364
52499
  let args2;
52365
52500
  const loopDeps = {
52366
52501
  post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
@@ -53865,17 +54000,18 @@ async function verifyChange(ctx, results, undoable) {
53865
54000
  const timing = (phase, since, command) => {
53866
54001
  if (command) console.log(JSON.stringify({ event: "timing", phase, seconds: Math.round((now() - since) / 1e3) }));
53867
54002
  };
54003
+ const checkLimit = (at2) => commandLimitMs("check", { now: at2, stopAtMs: ctx.jobStopAtMs ?? Number.NaN, reserveMs: finalChecksReserveMs({ baselineMs: ctx.baselineMs }) });
53868
54004
  stage = "format";
53869
54005
  const formatStartedAt = now();
53870
54006
  try {
53871
- runCommand(packet.commands.format, "Format");
54007
+ await runLimitedCommand(packet.commands.format, "Format", checkLimit(formatStartedAt));
53872
54008
  } catch (err2) {
53873
54009
  console.error(`Format failed (not blocking): ${err2 instanceof Error ? err2.message : String(err2)}`);
53874
54010
  }
53875
54011
  timing("format", formatStartedAt, packet.commands.format);
53876
54012
  stage = "lint";
53877
54013
  const lintStartedAt = now();
53878
- runCommand(packet.commands.lint, "Lint");
54014
+ await runLimitedCommand(packet.commands.lint, "Lint", checkLimit(lintStartedAt));
53879
54015
  timing("lint", lintStartedAt, packet.commands.lint);
53880
54016
  stage = "gate";
53881
54017
  if (!packet.commands.test || packet.commands.test.trim() === "") return fail(new Error(unverifiedMessage("no_command")));
@@ -54526,6 +54662,50 @@ async function fetchPacket(packetUrl, runToken, githubRunId) {
54526
54662
  return body2.data;
54527
54663
  }
54528
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
+
54529
54709
  // src/phase0.ts
54530
54710
  var import_node_fs25 = require("node:fs");
54531
54711
  function writePhase0Marker(runId) {
@@ -54542,7 +54722,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
54542
54722
  var REPORT_COPY = "final-test-report.xml";
54543
54723
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
54544
54724
  var MAX_FILES = 200;
54545
- var RUNNER_VERSION = true ? "9.3.0-rc.88" : "dev";
54725
+ var RUNNER_VERSION = true ? "9.3.0-rc.89" : "dev";
54546
54726
  function safeDestination(base, repoPath) {
54547
54727
  if (!repoPath || (0, import_node_path29.isAbsolute)(repoPath)) return null;
54548
54728
  const destination = (0, import_node_path29.resolve)(base, repoPath);
@@ -55467,7 +55647,6 @@ async function exchangeForRunToken(tokenUrl, oidcToken) {
55467
55647
  }
55468
55648
 
55469
55649
  // src/run.ts
55470
- var JOB_RESERVE_MS = 7 * 6e4;
55471
55650
  var HUNK_CHECK_MAX_MS = 6 * 6e4;
55472
55651
  var HUNK_CHECK_MIN_BUDGET_MS = 3 * 6e4;
55473
55652
  var HUNK_CHECK_END_BEFORE_STOP_MS = 2 * 6e4;
@@ -55486,8 +55665,18 @@ function deletionsLeftOutNote(out2) {
55486
55665
  const one = out2.count === 1;
55487
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}.`;
55488
55667
  }
55489
- async function run2(env2) {
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) {
55490
55677
  const runStartedAt = Date.now();
55678
+ let jobStopAtMs = Number.NaN;
55679
+ let baselineDurationMs;
55491
55680
  let hardFailure = false;
55492
55681
  let packet;
55493
55682
  let branch;
@@ -55525,9 +55714,55 @@ async function run2(env2) {
55525
55714
  } catch {
55526
55715
  }
55527
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
+ };
55528
55757
  try {
55529
55758
  runToken = await exchangeForRunToken(env2.tokenUrl, await fetchGithubOidcToken());
55530
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 });
55531
55766
  checkoutTargetBranch(packet.targetBranch);
55532
55767
  const writeRoot = normaliseWorkspaceRoot(packet.workspaceRoot);
55533
55768
  scopeRoot = writeRoot;
@@ -55572,15 +55807,14 @@ async function run2(env2) {
55572
55807
  if (partsOn) console.log(JSON.stringify({ event: "parts_check.on", parts: designParts.length, ...designRead.cut > 0 ? { cut: designRead.cut } : {} }));
55573
55808
  const featureSwitch = featureTestUpdatesOn();
55574
55809
  const setupStartedAt = Date.now();
55575
- runCommand(packet.commands.setup, "Setup");
55810
+ await runLimitedCommand(packet.commands.setup, "Setup", commandLimitMs("setup", { now: setupStartedAt, stopAtMs: jobStopAtMs }));
55576
55811
  if (packet.commands.setup) console.log(JSON.stringify({ event: "timing", phase: "setup", seconds: Math.round((Date.now() - setupStartedAt) / 1e3) }));
55577
55812
  const baselineStartedAt = Date.now();
55578
- const jobStopAtMs = runStartedAt + packet.guardrails.maxWallClockMinutes * 6e4 - JOB_RESERVE_MS;
55579
55813
  const baselineLimit = testLimitsOff() ? null : baselineLimitMs(jobStopAtMs - baselineStartedAt);
55580
- const baselineRun = (baselineLimit === null ? captureBaselineSnapshot(packet.commands.test) : captureBaselineSnapshot(packet.commands.test, process.cwd(), { limitMs: baselineLimit })).then((snapshot) => ({
55581
- snapshot,
55582
- durationMs: Date.now() - baselineStartedAt
55583
- }));
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
+ });
55584
55818
  pendingBaseline = baselineRun;
55585
55819
  const discovery = await resolveTestDiscovery({
55586
55820
  command: packet.commands.test,
@@ -55766,7 +56000,7 @@ async function run2(env2) {
55766
56000
  mode: codegenMode,
55767
56001
  ...keepOnGiveUp ? { keepOnGiveUp: true } : {},
55768
56002
  ...conflictsOn ? { conflicts: { decided, titles: approved?.titles ?? [], approvedTests: approved?.approvedTests ?? [] } } : {},
55769
- // 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.
55770
56004
  ...conflictsOn && packet.fixFirst === true && process.env.QUIKPILOT_FIX_FIRST?.trim().toLowerCase() !== "off" ? { fixFirst: true } : {},
55771
56005
  // QUIKTR-2442: a feature run may propose add-only set-up for an existing test its change breaks.
55772
56006
  ...featureUpdates ? { featureTestUpdates: true } : {},
@@ -55817,6 +56051,14 @@ async function run2(env2) {
55817
56051
  out: codegenOut
55818
56052
  };
55819
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
+ }
55820
56062
  const [timedBaseline, results] = await Promise.all([baselineRun, runCodegenStep(stepParams)]);
55821
56063
  const lastAttemptMs = Date.now() - writeStartedAt;
55822
56064
  console.log(JSON.stringify({ event: "timing", phase: "baseline", seconds: Math.round(timedBaseline.durationMs / 1e3), reportInTime: discovery.result.source === "live" }));
@@ -56116,33 +56358,8 @@ async function run2(env2) {
56116
56358
  console.warn(`::warning::Could not keep the failed run's files: ${err2 instanceof Error ? err2.message : String(err2)}`);
56117
56359
  }
56118
56360
  }
56119
- const targetingRecord = targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0;
56120
- const targetingUsage = clampTotals(spendOf("targeting"));
56121
- if (targetingRecord?.loop && targetingUsage) targetingRecord.loop = { ...targetingRecord.loop, usage: targetingUsage };
56122
- const codegenUsage = clampTotals(spendOf("codegen"));
56123
- const codegenRecord = codegenOut.loop && codegenUsage ? { ...codegenOut.loop, usage: codegenUsage } : codegenOut.loop;
56124
- await reportBack({
56125
- callbackUrl: env2.callbackUrl,
56126
- runToken,
56127
- status: hardFailure ? "failed" : conflictStop ? "blocked" : "completed",
56128
- branch,
56129
- warnings,
56130
- // Omitted when targeting itself never produced a result (nothing exists to record).
56131
- targeting: targetingRecord,
56132
- baselineFindings,
56133
- vanishedTests,
56134
- unsuppliedInputs,
56135
- changesNoTestDependsOn,
56136
- testsCorrected,
56137
- codegenLoop: codegenRecord,
56138
- unresolved: failureReasons.length > 0 ? failureReasons : void 0,
56139
- aiCostUsd: spendSoFar().costUsd,
56140
- ...testConflicts && !hardFailure ? { testConflicts } : {},
56141
- // Only for a run that is going to a pull request: a stop or a failure delivers none, so nothing is claimed as applied.
56142
- ...approvedApplied && !hardFailure && !conflictStop ? { approvedTestsApplied: approvedApplied } : {},
56143
- // 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.
56144
- ...databaseChange && !hardFailure && !conflictStop && branch ? { databaseChange } : {}
56145
- });
56361
+ if (!guard.claim()) return { hardFailure: true };
56362
+ await reportBack({ callbackUrl: env2.callbackUrl, runToken, ...finalReportBody() });
56146
56363
  return { hardFailure };
56147
56364
  }
56148
56365