@quikit/quikpilot-runner 9.3.0-rc.10 → 9.3.0-rc.11

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
@@ -1705,9 +1705,9 @@ function countRemovedLines(currentContent, newContent) {
1705
1705
  }
1706
1706
  let removed = 0;
1707
1707
  for (const line of currentContent.split("\n")) {
1708
- const count = remaining.get(line) ?? 0;
1709
- if (count > 0) {
1710
- remaining.set(line, count - 1);
1708
+ const count2 = remaining.get(line) ?? 0;
1709
+ if (count2 > 0) {
1710
+ remaining.set(line, count2 - 1);
1711
1711
  } else {
1712
1712
  removed++;
1713
1713
  }
@@ -2083,6 +2083,34 @@ function resolveCodegenMode(env2 = process.env, packetSetting) {
2083
2083
  return parse(packetSetting) ?? parse(env2[CODEGEN_MODE_ENV]) ?? "single";
2084
2084
  }
2085
2085
 
2086
+ // src/attemptSentences.ts
2087
+ var MAX_PREVIOUS_DETAIL_CHARS = 300;
2088
+ var MAX_PREVIOUS_RULES = 15;
2089
+ var MAX_PREVIOUS_TESTS = 20;
2090
+ var MAX_PREVIOUS_NAME_CHARS = 200;
2091
+ var MAX_PREVIOUS_MESSAGE_CHARS = 120;
2092
+ var MAX_PREVIOUS_COUNT = 1e5;
2093
+ var COVERAGE_PREFIX = "Required test cases not written: ";
2094
+ function coverageSentence(ids) {
2095
+ const total = ids.length;
2096
+ for (let shown = total; shown >= 1; shown--) {
2097
+ const rest = total - shown;
2098
+ const text = `${COVERAGE_PREFIX}${ids.slice(0, shown).join(", ")}${rest > 0 ? `, and ${rest} more` : ""}.`;
2099
+ if (text.length <= MAX_PREVIOUS_DETAIL_CHARS) return text;
2100
+ }
2101
+ return `${COVERAGE_PREFIX}${total} of them.`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
2102
+ }
2103
+ function truncationPhrase(suspect) {
2104
+ if (/^contains placeholder text/i.test(suspect)) return "placeholder text that suggests an abbreviated rewrite";
2105
+ if (/^sharp length drop/i.test(suspect)) return "a sharp drop in length";
2106
+ if (/^removed \d+ of \d+ lines/i.test(suspect)) return "many lines removed";
2107
+ if (/^removed exported symbol/i.test(suspect)) return "some of the file's exports were removed";
2108
+ return "the file came out much shorter than the original";
2109
+ }
2110
+ function truncationSentence(path, suspect) {
2111
+ return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
2112
+ }
2113
+
2086
2114
  // src/refusedReply.ts
2087
2115
  var REFUSED_OUTCOME = "REFUSED";
2088
2116
  var REFUSED_STREAK_LIMIT = 3;
@@ -2142,6 +2170,119 @@ function clampRefusedTurns(turns) {
2142
2170
  return { rows, cut };
2143
2171
  }
2144
2172
 
2173
+ // src/codegenAttempts.ts
2174
+ var CODEGEN_BUDGET_MS = 30 * 6e4;
2175
+ var MIN_SECOND_ATTEMPT_MS = 3 * 6e4;
2176
+ function secondAttemptFloorMs(a) {
2177
+ return Math.max(a.firstAttemptMs, a.testLimitMs ?? 0, MIN_SECOND_ATTEMPT_MS);
2178
+ }
2179
+ var REASON_WORDS = {
2180
+ contract_rejected: "the AI service did not accept the request (it may be switched off)",
2181
+ semantic_mismatch: "the AI service and the runner disagreed about the request",
2182
+ http_error: "the AI service returned an error",
2183
+ transport: "the AI service could not be reached",
2184
+ turn_timeout: "one step took too long",
2185
+ loop_deadline: "the whole change took too long",
2186
+ runtime_failed: "the AI service failed",
2187
+ bad_reply: "the AI service sent a reply that could not be used",
2188
+ duplicate_call_ids: "the AI service repeated a request",
2189
+ final_not_produced: "it never reached an answer",
2190
+ token_ceiling: "the request grew too large for one step",
2191
+ executor_error: "reading or changing the code failed",
2192
+ internal_error: "the runner hit an internal error",
2193
+ cannot_complete: "the AI said it could not make the change from what it could see",
2194
+ no_writes: "it said it was finished but had changed nothing",
2195
+ coverage_missing: "it said it was finished but had not written a test for every case",
2196
+ truncation_guard: "a file it rewrote looked cut short",
2197
+ syntax_error: "a file it changed would not run (a syntax error, or a name that is used but never defined or imported)",
2198
+ out_of_time: "the time allowed for writing the change ran out"
2199
+ };
2200
+ function reasonInWords(reason) {
2201
+ return REASON_WORDS[reason] ?? reason;
2202
+ }
2203
+ function exhaustedMessage(attempts, stop) {
2204
+ const first = attempts[0];
2205
+ const second = attempts[1];
2206
+ const firstWords = reasonInWords(first?.reason ?? "internal_error");
2207
+ if (stop === "failed") {
2208
+ return `QuikPilot could not write the change: neither attempt reached a result. The first attempt ended because ${firstWords}. The second attempt ended because ${reasonInWords(second?.reason ?? "internal_error")}. Nothing was written.`;
2209
+ }
2210
+ const head = "QuikPilot could not write the change in the time allowed. ";
2211
+ if (second?.outcome === "not_started") {
2212
+ 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.`;
2213
+ }
2214
+ return `${head}The first attempt ended because ${firstWords}. The second attempt ended because ${reasonInWords(second?.reason ?? "out_of_time")}. Nothing was written.`;
2215
+ }
2216
+ var CodegenAttemptsExhausted = class extends Error {
2217
+ attempts;
2218
+ /** `out_of_time` when the shared clock decided the end, `failed` when both attempts ended without a result for any other reason. */
2219
+ stopReason;
2220
+ constructor(attempts, stopReason) {
2221
+ super(exhaustedMessage(attempts, stopReason));
2222
+ this.name = "CodegenAttemptsExhausted";
2223
+ this.attempts = attempts;
2224
+ this.stopReason = stopReason;
2225
+ }
2226
+ };
2227
+ var RULE_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
2228
+ function count(n) {
2229
+ return typeof n === "number" && Number.isInteger(n) ? Math.min(MAX_PREVIOUS_COUNT, Math.max(0, n)) : 0;
2230
+ }
2231
+ function isRecord(x) {
2232
+ return typeof x === "object" && x !== null && !Array.isArray(x);
2233
+ }
2234
+ function testRunFrom(answer) {
2235
+ if (!isRecord(answer)) return void 0;
2236
+ const numbers = ["passed", "failed", "total", "regressions", "newFailures", "alreadyFailing"];
2237
+ if (!numbers.every((k) => typeof answer[k] === "number") || !Array.isArray(answer.failingTests)) return void 0;
2238
+ 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);
2239
+ const run2 = {
2240
+ passed: count(answer.passed),
2241
+ failed: count(answer.failed),
2242
+ total: count(answer.total),
2243
+ regressions: count(answer.regressions),
2244
+ newFailures: count(answer.newFailures),
2245
+ alreadyFailing: count(answer.alreadyFailing),
2246
+ failingTests
2247
+ };
2248
+ if (isRecord(answer.messages)) {
2249
+ const listed = new Set(failingTests);
2250
+ const messages = {};
2251
+ for (const [name, text] of Object.entries(answer.messages)) {
2252
+ const key = name.slice(0, MAX_PREVIOUS_NAME_CHARS);
2253
+ if (typeof text !== "string" || !listed.has(key) || Object.keys(messages).length >= MAX_PREVIOUS_TESTS) continue;
2254
+ const cut = text.slice(0, MAX_PREVIOUS_MESSAGE_CHARS);
2255
+ if (cut.length > 0) messages[key] = cut;
2256
+ }
2257
+ if (Object.keys(messages).length > 0) run2.messages = messages;
2258
+ }
2259
+ return run2;
2260
+ }
2261
+ function rulesFrom(rows) {
2262
+ if (!Array.isArray(rows) || rows.length === 0) return void 0;
2263
+ const counts = /* @__PURE__ */ new Map();
2264
+ for (const row of rows) {
2265
+ for (const raw of row.rules) {
2266
+ const word = recordRuleWord(raw);
2267
+ counts.set(word, (counts.get(word) ?? 0) + 1);
2268
+ }
2269
+ }
2270
+ 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);
2271
+ return ordered.length > 0 ? ordered.slice(0, MAX_PREVIOUS_RULES) : void 0;
2272
+ }
2273
+ function previousAttemptFrom(failure, attempt2) {
2274
+ const told = typeof failure.told === "string" ? failure.told.slice(0, MAX_PREVIOUS_DETAIL_CHARS) : "";
2275
+ const lastTestRun = testRunFrom(failure.lastTestAnswer);
2276
+ const rules = rulesFrom(failure.summary?.refusedTurns);
2277
+ return {
2278
+ attempt: attempt2,
2279
+ endedWith: RULE_SHAPE.test(failure.reason) ? failure.reason : "other",
2280
+ ...told.length > 0 ? { detail: told } : {},
2281
+ ...lastTestRun ? { lastTestRun } : {},
2282
+ ...rules ? { rules } : {}
2283
+ };
2284
+ }
2285
+
2145
2286
  // src/codegenLoopRecord.ts
2146
2287
  var MAX_RECORD_PATHS = 50;
2147
2288
  var MAX_RECORD_PATH_CHARS = 300;
@@ -2149,11 +2290,16 @@ var MAX_RECORD_REASONING_TURNS = 30;
2149
2290
  var MAX_RECORD_REASONING_CHARS = 500;
2150
2291
  var MAX_RECORD_FALLBACK_REASON_CHARS = 40;
2151
2292
  var MAX_RECORD_TEST_RUNS = 3;
2293
+ var MAX_RECORD_ATTEMPTS = 3;
2294
+ var MAX_ATTEMPT_COUNT = 1e3;
2152
2295
  var MAX_STATUS_KEYS = 20;
2153
2296
  var MAX_STATUS_KEY_CHARS = 40;
2154
2297
  function whole(n) {
2155
2298
  return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
2156
2299
  }
2300
+ function small(n) {
2301
+ return Math.min(MAX_ATTEMPT_COUNT, whole(n));
2302
+ }
2157
2303
  function pathOk(p) {
2158
2304
  return typeof p === "string" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;
2159
2305
  }
@@ -2221,6 +2367,25 @@ function buildCodegenLoopRecord(loop) {
2221
2367
  }
2222
2368
  const refused2 = clampRefusedTurns(loop.refusedTurns);
2223
2369
  if (refused2.cut) cut = true;
2370
+ const attempts = [];
2371
+ for (const a of loop.attempts ?? []) {
2372
+ if (attempts.length >= MAX_RECORD_ATTEMPTS) {
2373
+ cut = true;
2374
+ break;
2375
+ }
2376
+ if (!Number.isInteger(a.n) || a.n < 1 || a.n > MAX_RECORD_ATTEMPTS || typeof a.outcome !== "string" || a.outcome.length === 0) {
2377
+ cut = true;
2378
+ continue;
2379
+ }
2380
+ const reason = typeof a.reason === "string" ? a.reason.slice(0, MAX_STATUS_KEY_CHARS) : "";
2381
+ attempts.push({
2382
+ n: a.n,
2383
+ outcome: a.outcome.slice(0, MAX_STATUS_KEY_CHARS),
2384
+ ...reason.length > 0 ? { reason } : {},
2385
+ turns: small(a.turns),
2386
+ toolCalls: small(a.toolCalls)
2387
+ });
2388
+ }
2224
2389
  return {
2225
2390
  turns: whole(loop.turns),
2226
2391
  toolCalls: whole(loop.toolCalls),
@@ -2236,6 +2401,7 @@ function buildCodegenLoopRecord(loop) {
2236
2401
  ...typeof loop.contractVersion === "string" && loop.contractVersion.length > 0 ? { contractVersion: loop.contractVersion.slice(0, 40) } : {},
2237
2402
  ...testRuns.length > 0 ? { testRuns } : {},
2238
2403
  ...refused2.rows.length > 0 ? { refusedTurns: refused2.rows } : {},
2404
+ ...attempts.length > 0 ? { attempts } : {},
2239
2405
  reasoning,
2240
2406
  ...cut ? { truncated: true } : {}
2241
2407
  };
@@ -8644,11 +8810,11 @@ pp$1.regexp_classStringDisjunctionContents = function(state) {
8644
8810
  return result;
8645
8811
  };
8646
8812
  pp$1.regexp_classString = function(state) {
8647
- var count = 0;
8813
+ var count2 = 0;
8648
8814
  while (this.regexp_eatClassSetCharacter(state)) {
8649
- count++;
8815
+ count2++;
8650
8816
  }
8651
- return count === 1 ? CharSetOk : CharSetString;
8817
+ return count2 === 1 ? CharSetOk : CharSetString;
8652
8818
  };
8653
8819
  pp$1.regexp_eatClassSetCharacter = function(state) {
8654
8820
  var start = state.pos;
@@ -11278,7 +11444,7 @@ function prepareListFiles(args, env2) {
11278
11444
  const slash = rest.indexOf("/");
11279
11445
  if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);
11280
11446
  }
11281
- output.subdirs = [...counts.entries()].map(([name, count]) => ({ name, count })).sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1)).slice(0, 50);
11447
+ output.subdirs = [...counts.entries()].map(([name, count2]) => ({ name, count: count2 })).sort((a, b) => b.count - a.count || (a.name < b.name ? -1 : 1)).slice(0, 50);
11282
11448
  }
11283
11449
  return { result: { status: "ok", output } };
11284
11450
  }
@@ -12908,13 +13074,22 @@ var CodegenLoopFailure = class extends Error {
12908
13074
  runtimeCode;
12909
13075
  /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */
12910
13076
  detail;
13077
+ /**
13078
+ * QUIKTR-1544 (24.12c): what the NEXT attempt is told, built from closed vocabularies: the ids of the cases not written, a file the AI
13079
+ * itself broke with a fixed phrase and a line number, the AI's own summary when it said it could not complete. Never `detail`, which
13080
+ * for one check lists names read from the original file.
13081
+ */
13082
+ told;
13083
+ /** The last `run_tests` answer the AI was shown in this attempt, kept for the next one. Wire only: never logged, never recorded. */
13084
+ lastTestAnswer;
12911
13085
  summary;
12912
- constructor(reason, runtimeCode, cause, detail) {
13086
+ constructor(reason, runtimeCode, cause, detail, told) {
12913
13087
  super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
12914
13088
  this.name = "CodegenLoopFailure";
12915
13089
  this.reason = reason;
12916
13090
  this.runtimeCode = runtimeCode;
12917
13091
  this.detail = detail;
13092
+ this.told = told;
12918
13093
  if (cause !== void 0) this.cause = cause;
12919
13094
  }
12920
13095
  };
@@ -12933,6 +13108,9 @@ function classifyTransport2(err) {
12933
13108
  if (name === "TimeoutError" || name === "AbortError") return new CodegenLoopFailure("turn_timeout", void 0, err);
12934
13109
  return new CodegenLoopFailure("transport", void 0, err);
12935
13110
  }
13111
+ function isTestAnswer(x) {
13112
+ return isPlainObject3(x) && typeof x.passed === "number" && Array.isArray(x.failingTests);
13113
+ }
12936
13114
  var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
12937
13115
  async function runCodegenLoop(args, deps) {
12938
13116
  const ws = createCodegenWorkspace({
@@ -12957,6 +13135,8 @@ async function runCodegenLoop(args, deps) {
12957
13135
  now
12958
13136
  }) : null;
12959
13137
  let testMs = 0;
13138
+ let lastTestAnswer;
13139
+ const pastHardStop = () => deps.hardStopAtMs !== void 0 && now() >= deps.hardStopAtMs;
12960
13140
  const turnTimeoutMs = deps.turnTimeoutMs ?? 3e5;
12961
13141
  const deadlineMs = deps.deadlineMs ?? 15e5;
12962
13142
  const reads = [];
@@ -12981,6 +13161,7 @@ async function runCodegenLoop(args, deps) {
12981
13161
  ...isFinal ? { finalReason } : {},
12982
13162
  // Says this runner can carry a REFUSED answer (24.12a). Without it the runtime fails the request, as it always did.
12983
13163
  acceptsRefused: true,
13164
+ ...args.previousAttempt ? { previousAttempt: args.previousAttempt } : {},
12984
13165
  remaining: {
12985
13166
  toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
12986
13167
  readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),
@@ -12997,7 +13178,7 @@ async function runCodegenLoop(args, deps) {
12997
13178
  refused: ledger.refused,
12998
13179
  stopReason,
12999
13180
  reads: [...reads],
13000
- edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),
13181
+ edits: [...ws.edits.entries()].map(([path, count2]) => ({ path, count: count2 })),
13001
13182
  created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),
13002
13183
  statusCounts: { ...statusCounts },
13003
13184
  syntaxWarnings: ws.syntaxWarnings,
@@ -13042,6 +13223,7 @@ async function runCodegenLoop(args, deps) {
13042
13223
  try {
13043
13224
  for (let turn = 1; turn <= limits.maxTurns; turn++) {
13044
13225
  turns = turn;
13226
+ if (pastHardStop()) throw new CodegenLoopFailure("out_of_time");
13045
13227
  if (now() - started - Math.min(testMs, MAX_TEST_RUNS * MAX_TEST_LIMIT_MS) > deadlineMs) throw new CodegenLoopFailure("loop_deadline");
13046
13228
  const isFinal = forced !== null || turn === limits.maxTurns;
13047
13229
  const finalReason = forced ?? "max_turns";
@@ -13100,7 +13282,7 @@ async function runCodegenLoop(args, deps) {
13100
13282
  if (body.outcome === "CANNOT_COMPLETE") {
13101
13283
  log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
13102
13284
  const said = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
13103
- throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said);
13285
+ throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said);
13104
13286
  }
13105
13287
  if (body.outcome === "DONE") {
13106
13288
  log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
@@ -13110,7 +13292,7 @@ async function runCodegenLoop(args, deps) {
13110
13292
  const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
13111
13293
  if (missing.length > 0) {
13112
13294
  log({ event: "codegen.loop_refused", turn, reason: "coverage_missing", missing: missing.length });
13113
- throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`);
13295
+ throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`, coverageSentence(missing));
13114
13296
  }
13115
13297
  const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);
13116
13298
  for (const path of changed) {
@@ -13120,13 +13302,14 @@ async function runCodegenLoop(args, deps) {
13120
13302
  const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);
13121
13303
  if (suspect) {
13122
13304
  log({ event: "codegen.loop_refused", turn, reason: "truncation_guard", path });
13123
- throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`);
13305
+ throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`, truncationSentence(path, suspect));
13124
13306
  }
13125
13307
  }
13126
13308
  const broken = ws.syntaxProblems()[0];
13127
13309
  if (broken) {
13128
13310
  log({ event: "codegen.loop_refused", turn, reason: "syntax_error", path: broken.path, kind: broken.problem.kind, line: broken.problem.line });
13129
- throw new CodegenLoopFailure("syntax_error", void 0, void 0, `${broken.path}: ${describeSyntaxProblem(broken.problem)}`);
13311
+ const sentence = `${broken.path}: ${describeSyntaxProblem(broken.problem)}`;
13312
+ throw new CodegenLoopFailure("syntax_error", void 0, void 0, sentence, sentence.slice(0, MAX_PREVIOUS_DETAIL_CHARS));
13130
13313
  }
13131
13314
  const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
13132
13315
  const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
@@ -13154,6 +13337,7 @@ async function runCodegenLoop(args, deps) {
13154
13337
  if (index >= limits.maxCallsPerTurn) {
13155
13338
  result = { id: call.id, name: call.name, status: "budget_exhausted", reason: "too_many_calls", message: "Too many calls in one turn; this one was not run." };
13156
13339
  } else if (call.name === RUN_TESTS_TOOL && tests) {
13340
+ if (pastHardStop()) throw new CodegenLoopFailure("out_of_time");
13157
13341
  const testsStarted = now();
13158
13342
  try {
13159
13343
  result = await executeRunTestsCall(call, tests, ledger, limits);
@@ -13171,6 +13355,7 @@ async function runCodegenLoop(args, deps) {
13171
13355
  }
13172
13356
  }
13173
13357
  results.push(result);
13358
+ if (call.name === RUN_TESTS_TOOL && isTestAnswer(result.output)) lastTestAnswer = result.output;
13174
13359
  if (read) reads.push(read);
13175
13360
  statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;
13176
13361
  const tool = TOOL_NAMES2.has(call.name) ? call.name : "unknown";
@@ -13198,6 +13383,7 @@ async function runCodegenLoop(args, deps) {
13198
13383
  if (err instanceof TreeNotRestoredError) throw err;
13199
13384
  const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
13200
13385
  failure.summary ??= snapshot("fallback");
13386
+ if (lastTestAnswer) failure.lastTestAnswer ??= lastTestAnswer;
13201
13387
  throw failure;
13202
13388
  }
13203
13389
  }
@@ -13286,6 +13472,22 @@ function perFile(p) {
13286
13472
  p.outOfScope
13287
13473
  );
13288
13474
  }
13475
+ function warn(p, message) {
13476
+ p.warnings.push(message);
13477
+ console.warn(`QuikPilot codegen warning (not blocking): ${message}`);
13478
+ }
13479
+ async function oneTestRunMs(tests) {
13480
+ const timed = await tests.baseline().catch(() => null);
13481
+ const limit = testTimeLimitMs(timed?.durationMs ?? null);
13482
+ return limit === "too_slow" ? MAX_TEST_LIMIT_MS : limit;
13483
+ }
13484
+ function failedAttempt(n, failure) {
13485
+ return { n, outcome: "failed", reason: failure.reason, turns: failure.summary?.turns ?? 0, toolCalls: failure.summary?.toolCalls ?? 0 };
13486
+ }
13487
+ function lose(p, summary, attempts, stop) {
13488
+ p.out.loop = buildCodegenLoopRecord({ ...summary ?? NO_SUMMARY, stopReason: stop, attempts });
13489
+ return new CodegenAttemptsExhausted(attempts, stop);
13490
+ }
13289
13491
  async function runCodegenStep(p) {
13290
13492
  if (p.mode !== "loop" && p.mode !== "loop-tests") return perFile(p);
13291
13493
  const testSetup = p.mode === "loop-tests" ? p.tests : void 0;
@@ -13293,6 +13495,10 @@ async function runCodegenStep(p) {
13293
13495
  () => captureTree(testSetup.root, [], testSetup.tree),
13294
13496
  () => captureTree(testSetup.root, [], testSetup.tree)
13295
13497
  ).catch(() => null) : null;
13498
+ const guardTree = async () => {
13499
+ const before = treeAtStart ? await treeAtStart : null;
13500
+ if (before && p.tests) assertTreeUnchanged(p.tests.root, before, [], p.tests.tree);
13501
+ };
13296
13502
  const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} });
13297
13503
  p.contextLog.push(...context.records);
13298
13504
  console.log(
@@ -13304,39 +13510,79 @@ async function runCodegenStep(p) {
13304
13510
  existingTests: context.testPaths
13305
13511
  })
13306
13512
  );
13307
- try {
13308
- const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p, context), {
13309
- post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
13310
- ...p.deps
13311
- });
13312
- p.out.loop = buildCodegenLoopRecord(summary);
13513
+ const now = p.deps?.now ?? Date.now;
13514
+ const log = p.deps?.log ?? ((e) => console.log(JSON.stringify(e)));
13515
+ const hardStopAtMs = now() + (p.budgetMs ?? CODEGEN_BUDGET_MS);
13516
+ let args;
13517
+ const attempt2 = async (previousAttempt) => {
13518
+ try {
13519
+ args ??= buildCodegenLoopArgs(p, context);
13520
+ const done = await runCodegenLoop(previousAttempt ? { ...args, previousAttempt } : args, {
13521
+ post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
13522
+ ...p.deps,
13523
+ hardStopAtMs
13524
+ });
13525
+ return { done };
13526
+ } catch (err) {
13527
+ if (err instanceof SafetyRefusalError) throw err;
13528
+ if (err instanceof TreeNotRestoredError) throw err;
13529
+ return { failure: err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err) };
13530
+ }
13531
+ };
13532
+ const finish = (done, attempts) => {
13533
+ p.out.loop = buildCodegenLoopRecord(attempts ? { ...done.summary, attempts } : done.summary);
13313
13534
  const planned = new Set(p.targets.map((t) => t.path));
13314
- for (const r of results) {
13315
- if (!planned.has(r.targetPath)) {
13316
- const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;
13317
- p.warnings.push(w);
13318
- console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
13319
- }
13535
+ for (const r of done.results) {
13536
+ if (!planned.has(r.targetPath)) warn(p, `QuikPilot changed ${r.targetPath}, which the plan did not name.`);
13320
13537
  }
13321
- return results;
13322
- } catch (err) {
13323
- if (err instanceof SafetyRefusalError) throw err;
13324
- if (err instanceof TreeNotRestoredError) throw err;
13325
- const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
13326
- p.out.loop = buildCodegenLoopRecord({
13327
- ...failure.summary ?? NO_SUMMARY,
13328
- stopReason: "fallback",
13329
- fellBack: true,
13330
- fallbackReason: failure.reason
13331
- });
13332
- const said = failure.detail ? `: ${failure.detail}` : "";
13333
- const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;
13334
- p.warnings.push(w);
13335
- console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
13336
- const before = treeAtStart ? await treeAtStart : null;
13337
- if (before && p.tests) assertTreeUnchanged(p.tests.root, before, [], p.tests.tree);
13538
+ return done.results;
13539
+ };
13540
+ log({ event: "codegen.attempt_start", attempt: 1 });
13541
+ const firstStarted = now();
13542
+ const first = await attempt2();
13543
+ const firstMs = now() - firstStarted;
13544
+ if ("done" in first) {
13545
+ log({ event: "codegen.attempt_end", attempt: 1, outcome: "finished", turns: first.done.summary.turns, toolCalls: first.done.summary.toolCalls, durationMs: firstMs });
13546
+ return finish(first.done);
13547
+ }
13548
+ const f1 = first.failure;
13549
+ log({ event: "codegen.attempt_end", attempt: 1, outcome: "failed", reason: f1.reason, turns: f1.summary?.turns ?? 0, toolCalls: f1.summary?.toolCalls ?? 0, durationMs: firstMs });
13550
+ const said = f1.detail ? `: ${f1.detail}` : "";
13551
+ if (f1.reason === "contract_rejected") {
13552
+ p.out.loop = buildCodegenLoopRecord({ ...f1.summary ?? NO_SUMMARY, stopReason: "fallback", fellBack: true, fallbackReason: f1.reason });
13553
+ warn(p, `The code-writing loop could not finish (${f1.reason}${said}), so the files were written one at a time instead.`);
13554
+ await guardTree();
13338
13555
  return perFile(p);
13339
13556
  }
13557
+ await guardTree();
13558
+ const firstRecord = failedAttempt(1, f1);
13559
+ const testLimit = p.mode === "loop-tests" && p.tests ? await oneTestRunMs(p.tests) : null;
13560
+ const left = hardStopAtMs - now();
13561
+ const needed = secondAttemptFloorMs({ firstAttemptMs: firstMs, testLimitMs: testLimit });
13562
+ if (f1.reason === "out_of_time" || left < needed) {
13563
+ log({ event: "codegen.attempt_skipped", attempt: 2, reason: "out_of_time", leftMs: Math.max(0, left), neededMs: needed });
13564
+ throw lose(p, f1.summary, [firstRecord, { n: 2, outcome: "not_started", reason: "out_of_time", turns: 0, toolCalls: 0 }], "out_of_time");
13565
+ }
13566
+ warn(p, `The first attempt at writing the change ended (${f1.reason}${said}), so QuikPilot is trying once more.`);
13567
+ const previous = previousAttemptFrom(f1, 1);
13568
+ log({
13569
+ event: "codegen.attempt_start",
13570
+ attempt: 2,
13571
+ endedWith: previous.endedWith,
13572
+ hasDetail: previous.detail !== void 0,
13573
+ rulesCount: previous.rules?.length ?? 0,
13574
+ hasLastTestRun: previous.lastTestRun !== void 0
13575
+ });
13576
+ const secondStarted = now();
13577
+ const second = await attempt2(previous);
13578
+ const secondMs = now() - secondStarted;
13579
+ if ("done" in second) {
13580
+ log({ event: "codegen.attempt_end", attempt: 2, outcome: "finished", turns: second.done.summary.turns, toolCalls: second.done.summary.toolCalls, durationMs: secondMs });
13581
+ return finish(second.done, [firstRecord, { n: 2, outcome: "finished", turns: second.done.summary.turns, toolCalls: second.done.summary.toolCalls }]);
13582
+ }
13583
+ const f2 = second.failure;
13584
+ log({ event: "codegen.attempt_end", attempt: 2, outcome: "failed", reason: f2.reason, turns: f2.summary?.turns ?? 0, toolCalls: f2.summary?.toolCalls ?? 0, durationMs: secondMs });
13585
+ throw lose(p, f2.summary, [firstRecord, failedAttempt(2, f2)], f2.reason === "out_of_time" ? "out_of_time" : "failed");
13340
13586
  }
13341
13587
 
13342
13588
  // src/dependencyCheck.ts
@@ -13785,7 +14031,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
13785
14031
  var REPORT_COPY = "final-test-report.xml";
13786
14032
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
13787
14033
  var MAX_FILES = 200;
13788
- var RUNNER_VERSION = true ? "9.3.0-rc.10" : "dev";
14034
+ var RUNNER_VERSION = true ? "9.3.0-rc.11" : "dev";
13789
14035
  function safeDestination(base, repoPath) {
13790
14036
  if (!repoPath || (0, import_node_path12.isAbsolute)(repoPath)) return null;
13791
14037
  const destination = (0, import_node_path12.resolve)(base, repoPath);