@quikit/quikpilot-runner 9.3.0-rc.56 → 9.3.0-rc.58

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/README.md CHANGED
@@ -164,8 +164,14 @@ wrong (a field that arrives from a database row or a request), so it only warns
164
164
 
165
165
  **9.3.0-rc.46 — the existing tests to read first include the ones that reach the code through one file in between (QUIKTR-1845).** On the live bug-6 run (QTRIA-17) the design changed `lib/services/issueFilters.ts`, and the two tests that assert the bug import `app/api/issues/route.ts`, which imports it, so the list of existing tests the AI reads before writing (`testsToCheck`, rc.44) was empty. When fewer than 3 test files are found by name or a direct import, the runner now takes one more step: of the files the tests import (code, not a test, not under a denied path; the 150 most shared first) it keeps the ones that import a changed file, and adds the tests that import them, after the others and up to 10 in all. A file in between imported by more than 12 tests only brings the tests named after it (a route by its folder) or after the changed file. Paths only, as before. With 3 or more found the list is exactly as in rc.45. Also in rc.46: everything in rc.45. Nothing else changes.
166
166
 
167
+ **9.3.0-rc.58 - write the fix first, then ask once about every existing test it breaks, with proof (QUIKTR-1851, absorbing QUIKTR-1850; release 1).** Until now, when an existing test expected the bug, the run stopped BEFORE any code was written and a person approved a change to that test with nothing to show it could ever pass, and the tests were found one at a time: QTRIA-23 approved a change that moved the status line off 401 and left `expect(body).toEqual({ ..., error: "Unauthorized" })`, which no fix can satisfy, and spent all three stops. Now, when the project switches it on (`packet.fixFirst`; `QUIKPILOT_FIX_FIRST=off` turns it off without a rebuild) the run speaks `codegen-loop-8`: a `report_test_conflict` is a PROPOSAL that does not end the run, the AI writes the tests and the fix and reports every existing test its fix breaks, and at its DONE the runner proves the proposals (`proofCheck.ts`): it runs the project's WHOLE suite (the related-tests planner off, a fresh tool, outside the AI's run allowance) with the fix and every proposed change written over the old code. A proposal whose test still fails is sent back with its name ("change EVERY expectation of it"), and an existing test the fix broke that no proposal covers is sent back by name (never a failure message: QUIKTR-1474), at most twice; one that still fails after that is not offered to a person. Then ONE stop, as before, whose proposals carry `oldCodeChecked` (fails on the old code with the change alone), `newCode` (`passes` / `fails` / `not_checked`) and `newEndLine` (where the changed test now ends, for showing the whole test); no time, no answer or a list of failures cut to fit is `not_checked`, never proven. The tests phase hands its proposals to the code phase. An AI Runtime that refuses `codegen-loop-8` is asked again as loop-7 (nothing else changes), a fix turn stays loop-7, and a project that did not switch it on sends and receives exactly what it did. Release 2 (keeping the fix across the stop) is not in this version: the next job still writes the code again. Also in rc.58: everything in rc.57.
168
+
169
+ **9.3.0-rc.57 - rc.56 and rc.55 together.** rc.56 (QUIKTR-1701 release 2) was built and published from a source that did not yet contain rc.55's turn recovery (QUIKTR-1853: a cut-off answer or a slow turn is asked again once in a smaller step instead of ending the attempt), so a project pinned to rc.56 lost it. rc.57 is the merge of the two and nothing else: everything in rc.56 and everything in rc.55. Also in rc.57: everything in rc.54.
170
+
167
171
  **9.3.0-rc.56 - outline and find_definition for eight languages, the last test-file names, and the AI's own tests kept in Python, Go and Java (QUIKTR-1701, release 2).** (1) `definitions.ts` reads the definitions of a Python, Go, Java, Kotlin, C#, Rust, Ruby or PHP file from its tree-sitter tree - functions, classes, methods, structs, interfaces, enums, modules, with exact line ranges and nesting (a Java or C# method, a Kotlin `fun`, a Ruby `valid?` and `def self.x`, a Rust `impl`). `read_file` mode "outline" and the too-large answer use it (`engine: "treesitter"`), and `find_definition` looks a name up in the tree of every file that holds it (at most 80 files are parsed per call; the rest, a file that does not parse and any other language keep the line patterns). The name rule is widened to any language: a letter of any script, `_` or `$`, then letters, digits, `_` or `$`, optionally a Ruby-style `?` or `!` at the end (the AI service checks the same rule first: deploy it BEFORE this runner), and a regular-expression character in a name can no longer break the pattern. The grammars are loaded once at the start of a run for the languages in the repository. (2) Test-file names: Surefire's `Test*.java` and `*TestCase.java`, Failsafe's `*IT.java`, Kotest and ScalaTest `FooSpec.kt/.scala`, Django `tests.py` and every file of a C# test project (`Acme.Tests/`) are test files (same table in the AI service and QuikProjects). (3) A fix may correct a test the AI wrote in this run in a Python, Go or Java file but not remove it, skip it (`@pytest.mark.skip`, `t.Skip()`, `@Disabled`) or leave it with fewer checks (assertion statements, `t.Error`/`t.Fatal`, `pytest.raises`, `fail(...)`), as for JavaScript. `QUIKPILOT_LANG_CHECKS=js` and `QUIKPILOT_TEST_LOCATE=js` switch the readers off. Also in rc.56: everything in rc.54 (rc.55 is QUIKTR-1853, built on its own branch).
168
172
 
173
+ **9.3.0-rc.55 - a cut-off answer or a slow turn continues in a smaller step instead of ending the attempt (QUIKTR-1853).** Until now one turn that the AI Runtime cut off for length (`output_too_large`) or that ran past the turn limit (`turn_timeout`) threw the whole code-writing attempt away, and with two attempts per job two such turns ended a job with nothing written, though the AI was making progress (QTRIA-21: one slow turn, then one cut-off answer while writing tests, nothing written, $1.70). Nothing the attempt holds changes with a lost turn (the overlay, the transcript and the counters change only after a reply comes back as an answer), so the runner now asks again, once: the AI's transcript gets one fixed sentence of the runner's own - "your last answer was too long and was cut off / your last step took too long, so none of it was run. Take a smaller step: fewer files and fewer edits in one turn, and make each edit a small find-and-replace change" - as a refused turn with the shared rule word `length`, which every AI Runtime version already accepts, so nothing is deployed on the AI Runtime (`turnRecovery.ts`). It is never counted as a refusal or as a turn that changed nothing, so it cannot force `refused_repeatedly` or `no_progress`; it uses a turn and the attempt deadline and the step clock still bound it. It never happens twice in a row: a second lost turn straight after the first, and any lost turn on the final turn, end the attempt as before, and the failure message then says "a second time in a row, even after the AI was asked to take a smaller step". The run log gets `codegen.loop_recovered` (turn, reason, the service's code) and `afterRecovery` on `codegen.attempt_end`; the recovered turn appears in the record as a refused turn with the rule `length`. The AI Runtime's own log `output.measured` names the model that was cut off. `QUIKPILOT_TURN_RECOVERY=off` returns to ending the attempt. Also in rc.55: everything in rc.54.
174
+
169
175
  **9.3.0-rc.54 - eight languages share one tree-sitter base: a syntax check and "never weaken an existing test" by structure (QUIKTR-1701, release 1).** Until now the runner's safety checks read code with a JavaScript parser and switched off for any other language: nothing noticed a broken Go or Ruby file, and an existing test in another language was protected only by the text rule, which lets any text be added in front of or behind the matched part (`t.Skip()`, an early `return`, `@pytest.mark.skip`, `@Disabled`, a shadowing `test_a = lambda: None` all passed). Now `languages.ts` is the one table of the languages read with tree-sitter - Python, Go, Java, Kotlin, C#, Rust, Ruby and PHP (JavaScript and TypeScript keep acorn and sucrase and every check they have). (1) Syntax: after each edit the code-writing loop tells the AI "the file no longer parses (a syntax error at line N)" when a file that parsed does not, and at hand-over a file that parsed before and does not now stops the run, exactly as for JavaScript; a file that was already broken, or a language whose grammar is not loaded, is never judged. (2) Existing tests (`existingTestsLang.ts`): every unit of the test file as it was before the run (a function, a class, an import, a statement - with its decorators, annotations and modifiers) must still be there, byte for byte and in order; a class, module, `impl` or RSpec `describe` is compared by what is around its body and then by its own units; an import may only gain names or a whole new import may be added; comments between units are free; a NEW unit may only declare something whose name no unit of that level has, and may not be a hook that runs around every test (`setUp`, `TestMain`, `init`, `@BeforeEach`, `[SetUp]`, a constructor, an RSpec `before`/`let`, a fixture, a static or `init` block, an inner attribute), a build constraint, a statement that declares nothing (`pytest.skip(...)` at module level), or a Rust attribute in front of an old item. The reasons are the same closed words as for JavaScript (`changed_text`, `removed_text`, `moved_block`, `affects_existing`). A file that does not parse falls back to the text rule. Size: the five new grammars are vendored brotli-compressed and embedded the same way (each decoded on first use, 2-25 ms), and the published source map no longer copies the source text, so the package is about 1.4 MB (rc.53: about 1.9 MB). `QUIKPILOT_LANG_CHECKS=js` turns both checks back to the old behaviour. Also in rc.54: everything in rc.53.
170
176
 
171
177
  **9.3.0-rc.53 - a Python, Go or Java test that pins the bug can be reported to a person (QUIKTR-1855, release 2).** Until now the stop "an existing test expects what an approved case calls wrong - may I change it?" worked only for JavaScript and TypeScript tests: the test was found, and an edit of it judged, by a JavaScript parser, so a Go, Python or Java test ended the run with `test_unsupported_language`. Now `testLocateLang.ts` finds the tests of those languages with tree-sitter (a Python `def test_*` with its decorators, a Go `func TestX` whose subtests are its rows, a Java `@Test`/`@ParameterizedTest` method with its annotations) and judges an edit by its SHAPE: the test's tokens with every literal value (text, number, true/false/None/nil/null), assertion statements (`assert ...`, `self.assertEqual`, `assert.Equal`, `assertEquals`, `assertThat(...)...`), comments and the test's own name taken out must be the same before and after - so the values of a `parametrize` list, a Go table or a `@CsvSource` may change, and the call the test makes, its loops and its set-up may not. Data a test reads from elsewhere in the file (a module-level list, a `@MethodSource`) is outside the test and an edit there is refused as outside it. The tests are found by the function's name (a Java `@DisplayName` is the title when there is one); a reply that does not find the title lists the file's test names. A later job (the approval) reads the file the same way. The tree-sitter runtime and the three grammars (`vendor/tree-sitter/`, MIT, about 1.3 MB) are embedded in the bundle as base64 and decoded only when the first Python, Go or Java test file is read, so a JavaScript run pays nothing; the package grows from about 330 KB to about 700 KB gzipped and stays one file with no dependencies. A file that does not parse cleanly, and any other language (Kotlin, C#, Ruby, PHP), is still `test_unsupported_language`. `QUIKPILOT_TEST_LOCATE=js` turns the new readers off. Also in rc.53: everything in rc.52.
package/dist/index.js CHANGED
@@ -37514,6 +37514,7 @@ function titlesHint(tests) {
37514
37514
  return shown.length === 0 ? "none" : `${shown.join(", ")}${tests.length > 12 ? ", ..." : ""}`;
37515
37515
  }
37516
37516
  var RECORDED_MESSAGE = "Recorded. This run will now stop before any code is delivered, and a person will decide about this test. Finish your answer; there is nothing more to do for this test.";
37517
+ var RECORDED_MESSAGE_FIX_FIRST = "Recorded as a proposal; nothing was changed. Carry on: write the tests and the fix, run the project's tests, and report every other existing test your fix breaks that expects what a case calls wrong. When your change is complete, answer DONE: QuikPilot then checks each proposal against your code and a person decides about them together.";
37517
37518
  var BOUNDS = { find: 8e3, replace: 2e4, title: 300, reason: 300, caseText: 1e3, value: 120, why: 300 };
37518
37519
  var ALLOWED_KEYS = /* @__PURE__ */ new Set([
37519
37520
  "path",
@@ -37638,6 +37639,22 @@ var TestConflictTool = class {
37638
37639
  recorded() {
37639
37640
  return [...this.byTest.values()];
37640
37641
  }
37642
+ /**
37643
+ * QUIKTR-1851: proposals recorded by an earlier phase of the same attempt (the tests phase), which the code phase's tool then holds as its own, so
37644
+ * the one stop at the end lists them all. They are replaced by a later report for the same test, like any other.
37645
+ */
37646
+ seed(conflicts) {
37647
+ for (const c of conflicts) this.byTest.set(`${c.path}\0${c.testTitle}`, { ...c });
37648
+ }
37649
+ /** QUIKTR-1851: the proofs of the checks at DONE, written onto the proposals they are about (by place in `recorded()`). */
37650
+ setEvidence(path, title, evidence) {
37651
+ const c = this.byTest.get(`${path}\0${title}`);
37652
+ if (c) Object.assign(c, evidence);
37653
+ }
37654
+ /** QUIKTR-1851: a proposal that could not be made to pass is taken out of the stop. */
37655
+ drop(path, title) {
37656
+ this.byTest.delete(`${path}\0${title}`);
37657
+ }
37641
37658
  /** QUIKTR-1823: the tests reported that are written once for many rows, one entry per test, in the order they were first reported. */
37642
37659
  unreportable() {
37643
37660
  return [...this.generated.values()];
@@ -37755,7 +37772,7 @@ var TestConflictTool = class {
37755
37772
  this.byTest.set(key, conflict);
37756
37773
  this.counts.recorded += 1;
37757
37774
  d.log?.({ event: "codegen.conflict_recorded", reading: r.reading, phase: d.phase ?? null, historyAvailable: history.available, ...isTable ? { rows: mine.length } : {} });
37758
- return { status: "conflict_recorded", message: RECORDED_MESSAGE, output: { history } };
37775
+ return { status: "conflict_recorded", message: d.fixFirst ? RECORDED_MESSAGE_FIX_FIRST : RECORDED_MESSAGE, output: { history } };
37759
37776
  }
37760
37777
  /** QUIKTR-1844: record a revision of an approved test change that does not fit. */
37761
37778
  recordRevision(r, revision, at2, key) {
@@ -37783,7 +37800,7 @@ var TestConflictTool = class {
37783
37800
  this.byTest.set(key, conflict);
37784
37801
  this.counts.recorded += 1;
37785
37802
  d.log?.({ event: "codegen.conflict_recorded", reading: r.reading, phase: d.phase ?? null, historyAvailable: history.available, revision: true, ...at2.isTable ? { rows: revision.rows } : {} });
37786
- return { status: "conflict_recorded", message: RECORDED_MESSAGE, output: { history } };
37803
+ return { status: "conflict_recorded", message: d.fixFirst ? RECORDED_MESSAGE_FIX_FIRST : RECORDED_MESSAGE, output: { history } };
37787
37804
  }
37788
37805
  };
37789
37806
  function fileText(lf, ending, bom) {
@@ -37875,6 +37892,8 @@ function lineOf2(c, file) {
37875
37892
  correction: c.correction,
37876
37893
  history: c.history,
37877
37894
  oldCodeChecked: c.oldCodeChecked === true,
37895
+ ...c.newCode !== void 0 ? { newCode: c.newCode } : {},
37896
+ ...c.newEndLine !== void 0 ? { newEndLine: c.newEndLine } : {},
37878
37897
  ...c.rows !== void 0 ? { rows: c.rows } : {},
37879
37898
  ...file.stale.get(c.index) ? { stale: file.stale.get(c.index) } : {},
37880
37899
  ...c.revises !== void 0 ? { revises: c.revises } : {},
@@ -37909,6 +37928,9 @@ function buildProposalMessage(input) {
37909
37928
  ...l.history.available ? [` Added ${l.history.addedAt ?? ""} in ${l.history.addedBySha?.slice(0, 10) ?? "a commit"}${l.history.subject ? `: ${oneLine(l.history.subject)}` : ""}`] : [],
37910
37929
  ...l.history.sameCommitPaths && l.history.sameCommitPaths.length > 0 ? [` The same change also touched: ${l.history.sameCommitPaths.slice(0, 5).join(", ")}${l.history.sameCommitPaths.length > 5 || l.history.sameCommitMore ? ", ..." : ""}`] : [],
37911
37930
  ...l.oldCodeChecked ? [" With this change the test fails on the code as it is today, so it shows the bug."] : [],
37931
+ ...l.newCode === "passes" ? [" With this change the test passes on the fix QuikPilot wrote."] : [],
37932
+ ...l.newCode === "fails" ? [" With this change the test still fails on the fix QuikPilot wrote."] : [],
37933
+ ...l.newCode === "not_checked" ? [" It was not checked whether this change passes on the fix QuikPilot wrote."] : [],
37912
37934
  ...l.stale ? [` ${staleNote(l.stale)}`] : [],
37913
37935
  ...l.revises ? [` ${revisionNote(l.revises, l.misfit)}`] : [],
37914
37936
  ""
@@ -37948,7 +37970,7 @@ function parseProposalMessage(message) {
37948
37970
  const o = j;
37949
37971
  const c = o.correction;
37950
37972
  const h = o.history;
37951
- if (o.v !== 1 || !isStr(o.path, 300) || !isStr(o.title, 300) || o.newTitle !== void 0 && !isStr(o.newTitle, 300) || !isStr(o.caseId, 64) || !CONFLICT_READINGS.includes(o.reading) || !isLine(o.startLine) || !isLine(o.endLine) || !isLine(o.changeLine) || !isStr(o.reason, 300) || typeof c !== "object" || c === null || !CONFLICT_CASE_FIELDS.includes(c.field) || !isStr(c.text, 1e3) || !isStr(c.why, 300) || typeof h !== "object" || h === null || typeof h.available !== "boolean" || typeof o.oldCodeChecked !== "boolean" || o.rows !== void 0 && !(typeof o.rows === "number" && Number.isInteger(o.rows) && o.rows >= 1 && o.rows <= 1e4) || o.stale !== void 0 && !isStale(o.stale) || o.revises !== void 0 && !(typeof o.revises === "string" && /^[0-9a-f]{40}$/.test(o.revises)) || o.misfit !== void 0 && (o.revises === void 0 || !isMisfit(o.misfit))) {
37973
+ if (o.v !== 1 || !isStr(o.path, 300) || !isStr(o.title, 300) || o.newTitle !== void 0 && !isStr(o.newTitle, 300) || !isStr(o.caseId, 64) || !CONFLICT_READINGS.includes(o.reading) || !isLine(o.startLine) || !isLine(o.endLine) || !isLine(o.changeLine) || !isStr(o.reason, 300) || typeof c !== "object" || c === null || !CONFLICT_CASE_FIELDS.includes(c.field) || !isStr(c.text, 1e3) || !isStr(c.why, 300) || typeof h !== "object" || h === null || typeof h.available !== "boolean" || typeof o.oldCodeChecked !== "boolean" || o.newCode !== void 0 && !["passes", "fails", "not_checked"].includes(o.newCode) || o.newEndLine !== void 0 && !isLine(o.newEndLine) || o.rows !== void 0 && !(typeof o.rows === "number" && Number.isInteger(o.rows) && o.rows >= 1 && o.rows <= 1e4) || o.stale !== void 0 && !isStale(o.stale) || o.revises !== void 0 && !(typeof o.revises === "string" && /^[0-9a-f]{40}$/.test(o.revises)) || o.misfit !== void 0 && (o.revises === void 0 || !isMisfit(o.misfit))) {
37952
37974
  continue;
37953
37975
  }
37954
37976
  out2.push(o);
@@ -37995,6 +38017,9 @@ function conflictsReport(p) {
37995
38017
  caseId: l.caseId,
37996
38018
  reading: l.reading,
37997
38019
  oldCodeChecked: l.oldCodeChecked,
38020
+ // QUIKTR-1851: only a fix-first stop carries them, so a loop-7 report is byte for byte what it was (QuikProjects reads a strict shape).
38021
+ ...l.newCode !== void 0 ? { newCode: l.newCode } : {},
38022
+ ...l.newEndLine !== void 0 ? { newEndLine: l.newEndLine } : {},
37998
38023
  ...l.rows !== void 0 ? { rows: l.rows } : {},
37999
38024
  ...l.history.available ? {
38000
38025
  history: {
@@ -41893,12 +41918,13 @@ function failedAttemptRecord(n, failure) {
41893
41918
  outcome: "failed",
41894
41919
  reason: failure.reason,
41895
41920
  ...failure.runtimeCode ? { runtimeCode: runtimeCodeWord(failure.runtimeCode) } : {},
41921
+ ...failure.afterRecovery ? { afterRecovery: true } : {},
41896
41922
  turns: failure.summary?.turns ?? 0,
41897
41923
  toolCalls: failure.summary?.toolCalls ?? 0
41898
41924
  };
41899
41925
  }
41900
41926
  function attemptInWords(a, fallback) {
41901
- const words = reasonInWords(a?.reason ?? fallback);
41927
+ const words = 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);
41902
41928
  return a?.runtimeCode && a.runtimeCode !== "other" ? `${words} (error code ${a.runtimeCode})` : words;
41903
41929
  }
41904
41930
  function exhaustedMessage(attempts, stop2, unreportable) {
@@ -46281,6 +46307,136 @@ function missingImportSentence(m) {
46281
46307
  return `${first.path} imports ${first.name} from ${first.from}, which does not export it${more}: export it there, or change the import.`.slice(0, 300);
46282
46308
  }
46283
46309
 
46310
+ // src/turnRecovery.ts
46311
+ var RECOVERY_RULE = "length";
46312
+ var COMMON = "Take a smaller step: fewer files and fewer edits in one turn, and make each edit a small find-and-replace change.";
46313
+ var SENTENCES = {
46314
+ cut_off: {
46315
+ violation: "Your last answer was cut off because it was too long, so none of it was run.",
46316
+ message: `Your last answer was too long and was cut off, so none of it was run. ${COMMON}`
46317
+ },
46318
+ slow: {
46319
+ violation: "Your last step took too long, so none of it was run.",
46320
+ message: `Your last step took too long, so none of it was run. ${COMMON}`
46321
+ }
46322
+ };
46323
+ function turnRecoveryOff(env2 = process.env) {
46324
+ return env2.QUIKPILOT_TURN_RECOVERY === "off";
46325
+ }
46326
+ function shouldRecover(input) {
46327
+ return !(input.off ?? turnRecoveryOff()) && !input.isFinal && input.consecutive < 1;
46328
+ }
46329
+ function recoveryAnswer(kind) {
46330
+ const s = SENTENCES[kind];
46331
+ return { rules: [RECOVERY_RULE], violations: [s.violation], message: s.message };
46332
+ }
46333
+ function repeatedLossDetail(kind, first) {
46334
+ const now = kind === "cut_off" ? "cut off" : "too slow";
46335
+ const before = first === "cut_off" ? "cut off" : "too slow";
46336
+ return `a turn was ${before}, and the next one, after the AI was asked for a smaller step, was ${now} too`;
46337
+ }
46338
+
46339
+ // src/conflictVerify.ts
46340
+ var CUT_AT = 190;
46341
+ function failingNameIs(id, file, conflict) {
46342
+ const { file: where, name: name2 } = splitTestId(id);
46343
+ if (where !== null && !idPlaceMatches(where, file.path)) return false;
46344
+ const title = file.newTitles.get(conflict.index) ?? conflict.testTitle;
46345
+ if (conflict.rows !== void 0) return rowPattern({ describes: conflict.describes, title }, file.path).test(name2);
46346
+ const full = [...conflict.describes, title];
46347
+ const candidates = [title, full.join(" > "), full.join(" "), full.join(" \u203A ")];
46348
+ return candidates.includes(name2) || name2.length >= CUT_AT && candidates.some((c) => c.startsWith(name2));
46349
+ }
46350
+ async function verifyOnOldCode(conflicts, run3, log = () => void 0) {
46351
+ const { files, dropped: unmergeable } = buildProposalFiles(conflicts);
46352
+ if (files.length === 0 || run3 === null) return { kept: conflicts.filter((c) => !unmergeable.includes(c)), dropped: [] };
46353
+ let answer = null;
46354
+ try {
46355
+ answer = await run3(files.map((f) => ({ targetPath: f.path, newContent: fileText(f.newLf, f.ending, f.bom) })));
46356
+ } catch (err2) {
46357
+ if (err2 instanceof TreeNotRestoredError) throw err2;
46358
+ answer = null;
46359
+ }
46360
+ const usable = answer !== null && !answer.timedOut;
46361
+ const kept = [];
46362
+ const dropped = [];
46363
+ const outcomes = { fails: 0, passes: 0, unknown: 0 };
46364
+ for (const file of files) {
46365
+ for (const c of file.conflicts) {
46366
+ const fails = usable && answer.failingTests.some((id) => failingNameIs(id, file, c));
46367
+ if (fails) {
46368
+ kept.push({ ...c, oldCodeChecked: true });
46369
+ outcomes.fails += 1;
46370
+ } else if (usable && !answer.truncated) {
46371
+ dropped.push(c);
46372
+ outcomes.passes += 1;
46373
+ } else {
46374
+ kept.push({ ...c, oldCodeChecked: false });
46375
+ outcomes.unknown += 1;
46376
+ }
46377
+ }
46378
+ }
46379
+ const order = new Map(conflicts.map((c, i3) => [`${c.path}\0${c.testTitle}`, i3]));
46380
+ kept.sort((a, b) => (order.get(`${a.path}\0${a.testTitle}`) ?? 0) - (order.get(`${b.path}\0${b.testTitle}`) ?? 0));
46381
+ log({ event: "codegen.conflict_old_code", ...outcomes, files: files.length, ran: answer !== null, timedOut: answer?.timedOut ?? false });
46382
+ return { kept, dropped };
46383
+ }
46384
+
46385
+ // src/proofCheck.ts
46386
+ var keyOf2 = (c) => `${c.path}\0${c.testTitle}`;
46387
+ function newEndLineOf(f, c) {
46388
+ const located = locateTests(f.path, f.newLf);
46389
+ return located ? allTests(located)[c.index]?.endLine : void 0;
46390
+ }
46391
+ async function proveProposals(input) {
46392
+ const evidence = /* @__PURE__ */ new Map();
46393
+ const { files, dropped } = buildProposalFiles(input.conflicts);
46394
+ for (const c of dropped) evidence.set(keyOf2(c), { newCode: "not_checked" });
46395
+ const notChecked = () => {
46396
+ for (const f of files) for (const c of f.conflicts) evidence.set(keyOf2(c), { newCode: "not_checked", ...endOf(f, c) });
46397
+ return { ran: false, evidence, stillFailing: [], unexplained: [] };
46398
+ };
46399
+ const endOf = (f, c) => {
46400
+ const line = newEndLineOf(f, c);
46401
+ return line === void 0 ? {} : { newEndLine: line };
46402
+ };
46403
+ if (files.length === 0 || input.run === null) return notChecked();
46404
+ const proposed = files.map((f) => ({ targetPath: f.path, newContent: fileText(f.newLf, f.ending, f.bom) }));
46405
+ const merged = [...input.fix.filter((r) => !proposed.some((p) => p.targetPath === r.targetPath)).map((r) => ({ targetPath: r.targetPath, newContent: r.newContent })), ...proposed];
46406
+ let answer = null;
46407
+ try {
46408
+ answer = await input.run(merged);
46409
+ } catch {
46410
+ answer = null;
46411
+ }
46412
+ if (answer === null || answer.timedOut) return notChecked();
46413
+ const stillFailing = [];
46414
+ const covered = /* @__PURE__ */ new Set();
46415
+ for (const f of files) {
46416
+ for (const c of f.conflicts) {
46417
+ const failing = answer.failingTests.filter((id) => failingNameIs(id, f, c));
46418
+ for (const id of failing) covered.add(id);
46419
+ const newCode = failing.length > 0 ? "fails" : answer.truncated ? "not_checked" : "passes";
46420
+ evidence.set(keyOf2(c), { newCode, ...endOf(f, c) });
46421
+ if (newCode === "fails") stillFailing.push(c);
46422
+ }
46423
+ }
46424
+ const broken = answer.failingTests.slice(0, answer.regressions).filter((id) => !covered.has(id));
46425
+ return { ran: true, evidence, stillFailing, unexplained: groupRegressions(broken) };
46426
+ }
46427
+ var MAX_NAMED2 = 8;
46428
+ function proofSentences(proof) {
46429
+ const out2 = [];
46430
+ if (proof.stillFailing.length > 0) {
46431
+ const named = proof.stillFailing.slice(0, MAX_NAMED2).map((c) => `${c.path}: "${c.testTitle.replace(/\s+/g, " ").slice(0, 120)}"`);
46432
+ out2.push(
46433
+ `Your proposed change to ${named.join("; ")}${proof.stillFailing.length > MAX_NAMED2 ? `; and ${proof.stillFailing.length - MAX_NAMED2} more` : ""} still fails on your fix. Another line of that test still expects the old behaviour: change EVERY expectation of it (status, body, message) and report the test again.`
46434
+ );
46435
+ }
46436
+ if (proof.unexplained.length > 0) out2.push(...giveUpSentences(proof.unexplained).slice(0, MAX_NAMED2));
46437
+ return out2.map((s) => s.length > 300 ? `${s.slice(0, 299)}\u2026` : s);
46438
+ }
46439
+
46284
46440
  // src/targetingErrors.ts
46285
46441
  var DeniedPathError = class extends Error {
46286
46442
  constructor(message) {
@@ -46619,6 +46775,7 @@ var CODEGEN_LOOP_4_CONTRACT_VERSION = "codegen-loop-4";
46619
46775
  var CODEGEN_LOOP_5_CONTRACT_VERSION = "codegen-loop-5";
46620
46776
  var CODEGEN_LOOP_6_CONTRACT_VERSION = "codegen-loop-6";
46621
46777
  var CODEGEN_LOOP_7_CONTRACT_VERSION = "codegen-loop-7";
46778
+ var CODEGEN_LOOP_8_CONTRACT_VERSION = "codegen-loop-8";
46622
46779
  var MAP_SOFT_REQUEST_TOKENS = 4e4;
46623
46780
  var MAP_SOFT_HEADROOM_TOKENS = 2e4;
46624
46781
  function mapSoftTarget(firstRequestTokens, ceiling) {
@@ -46650,6 +46807,8 @@ var CodegenLoopFailure = class extends Error {
46650
46807
  summary;
46651
46808
  /** QUIKTR-1823 (`test_conflict_unreportable` only): where each such test is and which case it contradicts. Never a title. */
46652
46809
  unreportable;
46810
+ /** QUIKTR-1853: a turn was lost straight after one that had been recovered (see `turnRecovery.ts`). */
46811
+ afterRecovery;
46653
46812
  constructor(reason, runtimeCode, cause, detail, told) {
46654
46813
  super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
46655
46814
  this.name = "CodegenLoopFailure";
@@ -46792,9 +46951,15 @@ async function runCodegenLoop(args2, deps) {
46792
46951
  baseline: args2.tests.baseline,
46793
46952
  scrub,
46794
46953
  ...args2.phase ? { phase: args2.phase } : {},
46954
+ ...args2.fixFirst === true ? { fixFirst: true } : {},
46795
46955
  log
46796
46956
  }) : null;
46797
- const contractVersion = harness ? args2.tools2 ? conflictTool ? CODEGEN_LOOP_7_CONTRACT_VERSION : notesOn ? CODEGEN_LOOP_6_CONTRACT_VERSION : CODEGEN_LOOP_5_CONTRACT_VERSION : args2.readRoots ? CODEGEN_LOOP_4_CONTRACT_VERSION : CODEGEN_LOOP_3_CONTRACT_VERSION : tests ? CODEGEN_LOOP_2_CONTRACT_VERSION : CODEGEN_LOOP_CONTRACT_VERSION;
46957
+ if (conflictTool && args2.seedProposals && args2.seedProposals.length > 0) conflictTool.seed(args2.seedProposals);
46958
+ const markNotChecked = () => {
46959
+ if (!conflictTool || args2.fixFirst !== true) return;
46960
+ for (const c of conflictTool.recorded()) if (c.newCode === void 0) conflictTool.setEvidence(c.path, c.testTitle, { newCode: "not_checked" });
46961
+ };
46962
+ const contractVersion = harness ? args2.tools2 ? conflictTool ? args2.fixFirst === true ? CODEGEN_LOOP_8_CONTRACT_VERSION : CODEGEN_LOOP_7_CONTRACT_VERSION : notesOn ? CODEGEN_LOOP_6_CONTRACT_VERSION : CODEGEN_LOOP_5_CONTRACT_VERSION : args2.readRoots ? CODEGEN_LOOP_4_CONTRACT_VERSION : CODEGEN_LOOP_3_CONTRACT_VERSION : tests ? CODEGEN_LOOP_2_CONTRACT_VERSION : CODEGEN_LOOP_CONTRACT_VERSION;
46798
46963
  let peakRequestTokens = 0;
46799
46964
  let firstRequestTokens = 0;
46800
46965
  const usage = new TurnUsage();
@@ -46821,6 +46986,7 @@ async function runCodegenLoop(args2, deps) {
46821
46986
  const redRuns = [];
46822
46987
  let redRefusals = 0;
46823
46988
  let importRefusals = 0;
46989
+ let proofSendBacks = 0;
46824
46990
  let giveUpRefusals = 0;
46825
46991
  let redUnproven;
46826
46992
  const currentRedRuns = () => {
@@ -46866,6 +47032,8 @@ async function runCodegenLoop(args2, deps) {
46866
47032
  let turns = 0;
46867
47033
  let noProgressStreak = 0;
46868
47034
  let forced = null;
47035
+ let lostLast = null;
47036
+ let lostStreak = 0;
46869
47037
  const started = now();
46870
47038
  let toCheckList = null;
46871
47039
  const toCheck = () => toCheckList ??= (args2.testsToCheck?.() ?? []).slice(0, 10);
@@ -47008,6 +47176,22 @@ async function runCodegenLoop(args2, deps) {
47008
47176
  return null;
47009
47177
  };
47010
47178
  log({ event: "codegen.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args2.listing.length });
47179
+ const loseTurn = (turn, kind, isFinalTurn, runtimeCode, elapsedMs) => {
47180
+ const reason = kind === "cut_off" ? "output_too_large" : "turn_timeout";
47181
+ if (!shouldRecover({ isFinal: isFinalTurn, consecutive: lostStreak })) {
47182
+ const again = lostLast !== null && lostStreak > 0;
47183
+ const failure = new CodegenLoopFailure(reason, runtimeCode, void 0, again ? repeatedLossDetail(kind, lostLast) : void 0);
47184
+ if (again) failure.afterRecovery = true;
47185
+ return failure;
47186
+ }
47187
+ lostStreak += 1;
47188
+ lostLast = kind;
47189
+ refusedTurns.push({ turn, rules: [RECOVERY_RULE] });
47190
+ transcript.push({ turn, toolCalls: [], refused: recoveryAnswer(kind) });
47191
+ log({ event: "codegen.loop_recovered", turn, reason, ...runtimeCode ? { runtimeCode } : {}, elapsedMs });
47192
+ forced = settleNextTurn(turn, forced);
47193
+ return true;
47194
+ };
47011
47195
  try {
47012
47196
  for (let turn = 1; turn <= limits.maxTurns; turn++) {
47013
47197
  turns = turn;
@@ -47029,7 +47213,13 @@ async function runCodegenLoop(args2, deps) {
47029
47213
  try {
47030
47214
  envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutFor(turn, turnTimeoutMs, deps.turnTimeoutMs !== void 0)));
47031
47215
  } catch (err2) {
47032
- throw classifyTransport2(err2);
47216
+ const lost = classifyTransport2(err2);
47217
+ if (lost.reason === "turn_timeout") {
47218
+ const handled = loseTurn(turn, "slow", isFinal, void 0, now() - turnStarted);
47219
+ if (handled === true) continue;
47220
+ throw handled;
47221
+ }
47222
+ throw lost;
47033
47223
  }
47034
47224
  usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
47035
47225
  const code = envelope?.errorCode;
@@ -47050,7 +47240,12 @@ async function runCodegenLoop(args2, deps) {
47050
47240
  const fallbackText = `pilot.codegen failed: ${runtimeCode}`;
47051
47241
  throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
47052
47242
  }
47053
- throw new CodegenLoopFailure(runtimeCode && OUTPUT_TOO_LARGE_CODES.has(runtimeCode) ? "output_too_large" : "runtime_failed", runtimeCode);
47243
+ if (runtimeCode && OUTPUT_TOO_LARGE_CODES.has(runtimeCode)) {
47244
+ const handled = loseTurn(turn, "cut_off", isFinal, runtimeCode, now() - turnStarted);
47245
+ if (handled === true) continue;
47246
+ throw handled;
47247
+ }
47248
+ throw new CodegenLoopFailure("runtime_failed", runtimeCode);
47054
47249
  }
47055
47250
  let body2;
47056
47251
  try {
@@ -47058,6 +47253,7 @@ async function runCodegenLoop(args2, deps) {
47058
47253
  } catch (err2) {
47059
47254
  throw new CodegenLoopFailure("bad_reply", void 0, err2);
47060
47255
  }
47256
+ lostStreak = 0;
47061
47257
  const reasonText = typeof body2.reasoning === "string" ? body2.reasoning.slice(0, limits.maxReasoningChars) : void 0;
47062
47258
  if (body2.outcome === REFUSED_OUTCOME) {
47063
47259
  const answer = readRefusedAnswer(body2);
@@ -47075,6 +47271,7 @@ async function runCodegenLoop(args2, deps) {
47075
47271
  log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
47076
47272
  const said = typeof body2.summary === "string" ? body2.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
47077
47273
  if (conflictTool && conflictTool.recorded().length > 0) {
47274
+ markNotChecked();
47078
47275
  throw new TestConflictStop(conflictTool.recorded(), new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said));
47079
47276
  }
47080
47277
  if (conflictTool && conflictTool.unreportable().length > 0) {
@@ -47119,7 +47316,35 @@ async function runCodegenLoop(args2, deps) {
47119
47316
  }
47120
47317
  if (conflictTool && conflictTool.recorded().length > 0) {
47121
47318
  const said = typeof body2.summary === "string" ? body2.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
47122
- throw new TestConflictStop(conflictTool.recorded(), new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said));
47319
+ if (args2.fixFirst !== true) throw new TestConflictStop(conflictTool.recorded(), new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said));
47320
+ if (args2.phase !== "tests") {
47321
+ const proof = await proveProposals({ conflicts: conflictTool.recorded(), fix: overlay.results(), run: pastHardStop() ? null : deps.wholeSuite ?? null });
47322
+ for (const c of conflictTool.recorded()) {
47323
+ const ev = proof.evidence.get(keyOf2(c));
47324
+ if (ev) conflictTool.setEvidence(c.path, c.testTitle, ev);
47325
+ }
47326
+ const sentences = proofSentences(proof);
47327
+ const counts = { passes: 0, fails: 0, notChecked: 0 };
47328
+ for (const ev of proof.evidence.values()) counts[ev.newCode === "passes" ? "passes" : ev.newCode === "fails" ? "fails" : "notChecked"] += 1;
47329
+ log({ event: "codegen.proof_check", turn, ran: proof.ran, proposals: proof.evidence.size, ...counts, unexplained: proof.unexplained.length, sendBacks: proofSendBacks });
47330
+ if (sentences.length > 0 && proofSendBacks < 2 && !isFinal) {
47331
+ proofSendBacks += 1;
47332
+ const answer = {
47333
+ rules: ["done_rule"],
47334
+ violations: sentences,
47335
+ message: "Your answer was sent back: QuikPilot ran the project's tests on your finished change with every proposed test change written over it, and found problems. Each sentence names them."
47336
+ };
47337
+ refusedStreak += 1;
47338
+ refusedTurns.push({ turn, rules: answer.rules });
47339
+ transcript.push({ turn, toolCalls: [], refused: answer });
47340
+ if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
47341
+ forced = settleNextTurn(turn, forced);
47342
+ continue;
47343
+ }
47344
+ for (const c of proof.stillFailing) conflictTool.drop(c.path, c.testTitle);
47345
+ const detail = proof.unexplained.length > 0 ? oldBehaviourSentence(proof.unexplained, MAX_PREVIOUS_DETAIL_CHARS) : proof.stillFailing.length > 0 ? "a proposed change to an existing test could not be made to pass on the fix" : said;
47346
+ throw new TestConflictStop(conflictTool.recorded(), new CodegenLoopFailure("cannot_complete", void 0, void 0, detail, said));
47347
+ }
47123
47348
  }
47124
47349
  const refusal = handOverRefusal(turn, false);
47125
47350
  if (refusal) throw refusal;
@@ -47197,7 +47422,16 @@ async function runCodegenLoop(args2, deps) {
47197
47422
  const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
47198
47423
  log({ event: "codegen.loop_done", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });
47199
47424
  const told = lastTestAnswer ?? (args2.phase === "tests" ? currentRedRuns().at(-1)?.answer : void 0);
47200
- return { results: overlay.results(), summary: snapshot(stopReason), doneSummary, steps: sentSteps(), ...redUnproven ? { redUnproven } : {}, ...told ? { lastTestAnswer: told } : {} };
47425
+ const proposals = args2.fixFirst === true && conflictTool ? conflictTool.recorded() : [];
47426
+ return {
47427
+ results: overlay.results(),
47428
+ summary: snapshot(stopReason),
47429
+ doneSummary,
47430
+ steps: sentSteps(),
47431
+ ...redUnproven ? { redUnproven } : {},
47432
+ ...told ? { lastTestAnswer: told } : {},
47433
+ ...proposals.length > 0 ? { proposals } : {}
47434
+ };
47201
47435
  }
47202
47436
  if (body2.outcome !== "TOOL_CALLS") throw new CodegenLoopFailure("bad_reply");
47203
47437
  if (isFinal) throw new CodegenLoopFailure("final_not_produced");
@@ -47302,6 +47536,7 @@ async function runCodegenLoop(args2, deps) {
47302
47536
  }
47303
47537
  let failure = err2 instanceof CodegenLoopFailure ? err2 : new CodegenLoopFailure("internal_error", void 0, err2);
47304
47538
  if (conflictTool && conflictTool.recorded().length > 0) {
47539
+ markNotChecked();
47305
47540
  const stop2 = new TestConflictStop(conflictTool.recorded(), failure);
47306
47541
  stop2.summary = failure.summary ?? snapshot("test_conflict");
47307
47542
  throw withUnreportable(stop2, unreportable);
@@ -47422,7 +47657,8 @@ async function runPhases(i3) {
47422
47657
  summary: d1.summary,
47423
47658
  ...d1.lastTestAnswer ? { answer: d1.lastTestAnswer } : {},
47424
47659
  ...d1.steps ? { steps: d1.steps } : {},
47425
- ...d1.redUnproven ? { redUnproven: d1.redUnproven } : {}
47660
+ ...d1.redUnproven ? { redUnproven: d1.redUnproven } : {},
47661
+ ...d1.proposals ? { proposals: d1.proposals } : {}
47426
47662
  };
47427
47663
  }
47428
47664
  i3.log({ event: "codegen.phase_start", attempt: i3.attempt, phase: "code" });
@@ -47433,6 +47669,7 @@ async function runPhases(i3) {
47433
47669
  phase: "code",
47434
47670
  lane: { kind: "code", testPaths: i3.testPaths, frozen: tests.frozen },
47435
47671
  seed: tests.results,
47672
+ ...tests.proposals ? { seedProposals: tests.proposals } : {},
47436
47673
  keepOnGiveUp: true,
47437
47674
  previousAttempt: keptChange(i3.attempt, "tests_written", tests.answer, tests.steps)
47438
47675
  });
@@ -48317,52 +48554,6 @@ function mapModeMessage(phase, reason) {
48317
48554
  return `QuikPilot could not ${what}: this project is too large to send the AI its full list of files, so it was sent a summary instead, and that did not finish (${WHY[reason] ?? reason}). There is no other way to try on a project this size, so nothing was changed.`;
48318
48555
  }
48319
48556
 
48320
- // src/conflictVerify.ts
48321
- var CUT_AT = 190;
48322
- function failingNameIs(id, file, conflict) {
48323
- const { file: where, name: name2 } = splitTestId(id);
48324
- if (where !== null && !idPlaceMatches(where, file.path)) return false;
48325
- const title = file.newTitles.get(conflict.index) ?? conflict.testTitle;
48326
- if (conflict.rows !== void 0) return rowPattern({ describes: conflict.describes, title }, file.path).test(name2);
48327
- const full = [...conflict.describes, title];
48328
- const candidates = [title, full.join(" > "), full.join(" "), full.join(" \u203A ")];
48329
- return candidates.includes(name2) || name2.length >= CUT_AT && candidates.some((c) => c.startsWith(name2));
48330
- }
48331
- async function verifyOnOldCode(conflicts, run3, log = () => void 0) {
48332
- const { files, dropped: unmergeable } = buildProposalFiles(conflicts);
48333
- if (files.length === 0 || run3 === null) return { kept: conflicts.filter((c) => !unmergeable.includes(c)), dropped: [] };
48334
- let answer = null;
48335
- try {
48336
- answer = await run3(files.map((f) => ({ targetPath: f.path, newContent: fileText(f.newLf, f.ending, f.bom) })));
48337
- } catch (err2) {
48338
- if (err2 instanceof TreeNotRestoredError) throw err2;
48339
- answer = null;
48340
- }
48341
- const usable = answer !== null && !answer.timedOut;
48342
- const kept = [];
48343
- const dropped = [];
48344
- const outcomes = { fails: 0, passes: 0, unknown: 0 };
48345
- for (const file of files) {
48346
- for (const c of file.conflicts) {
48347
- const fails = usable && answer.failingTests.some((id) => failingNameIs(id, file, c));
48348
- if (fails) {
48349
- kept.push({ ...c, oldCodeChecked: true });
48350
- outcomes.fails += 1;
48351
- } else if (usable && !answer.truncated) {
48352
- dropped.push(c);
48353
- outcomes.passes += 1;
48354
- } else {
48355
- kept.push({ ...c, oldCodeChecked: false });
48356
- outcomes.unknown += 1;
48357
- }
48358
- }
48359
- }
48360
- const order = new Map(conflicts.map((c, i3) => [`${c.path}\0${c.testTitle}`, i3]));
48361
- kept.sort((a, b) => (order.get(`${a.path}\0${a.testTitle}`) ?? 0) - (order.get(`${b.path}\0${b.testTitle}`) ?? 0));
48362
- log({ event: "codegen.conflict_old_code", ...outcomes, files: files.length, ran: answer !== null, timedOut: answer?.timedOut ?? false });
48363
- return { kept, dropped };
48364
- }
48365
-
48366
48557
  // src/testsToCheck.ts
48367
48558
  var import_node_fs16 = require("node:fs");
48368
48559
  var import_node_path19 = require("node:path");
@@ -48559,6 +48750,7 @@ function buildCodegenLoopArgs(p, context = collectLoopContext({
48559
48750
  ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2 ? { tools2: p.tools2 } : {},
48560
48751
  ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.callFunction ? { callFunction: p.callFunction } : {},
48561
48752
  ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2?.notes === true && p.conflicts ? { conflicts: p.conflicts, ...testsToCheckOf(p) } : {},
48753
+ ...p.mode === "loop-tests" && p.tests && p.harness !== false && p.tools2?.notes === true && p.conflicts && p.fixFirst === true ? { fixFirst: true } : {},
48562
48754
  // An approved test change stands whatever version the AI Runtime speaks: a person decided it.
48563
48755
  ...p.approved && p.approved.length > 0 ? { approved: p.approved.map((r) => ({ targetPath: r.targetPath, newContent: r.newContent })) } : {}
48564
48756
  };
@@ -48606,16 +48798,18 @@ function lose(p, summary, attempts, stop2, unreportable) {
48606
48798
  p.out.loop = buildCodegenLoopRecord({ ...summary ?? NO_SUMMARY, stopReason: stop2, attempts });
48607
48799
  return new CodegenAttemptsExhausted(attempts, stop2, unreportable);
48608
48800
  }
48609
- function oldCodeRunner(args2, log, now) {
48801
+ function oldCodeRunner(args2, log, now, wholeSuite = false) {
48610
48802
  return async (files) => {
48611
48803
  const disk = files.map((r) => ({ path: r.targetPath, content: r.newContent }));
48612
48804
  const tool = new RunTestsTool({
48613
48805
  ...args2.tests,
48806
+ // QUIKTR-1851: the proof of a proposal needs the WHOLE suite, never only the tests related to the change (the planner would leave a broken test out).
48807
+ ...wholeSuite ? { planner: void 0 } : {},
48614
48808
  requiredAutomationIds: args2.requiredAutomationIds,
48615
48809
  harness: true,
48616
48810
  overlayFiles: () => disk,
48617
48811
  overlayVersion: () => versionOfFiles(disk),
48618
- log: (e) => log({ ...e, event: "codegen.old_code_run" }),
48812
+ log: (e) => log({ ...e, event: wholeSuite ? "codegen.proof_run" : "codegen.old_code_run" }),
48619
48813
  now
48620
48814
  });
48621
48815
  const answer = await tool.execute("old-code");
@@ -48675,6 +48869,8 @@ async function runCodegenStep(p) {
48675
48869
  const loopDeps = {
48676
48870
  post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
48677
48871
  secrets: [p.gateway.token],
48872
+ // QUIKTR-1851: built per call, because `args` is rebuilt when a version is refused. A fresh tool per run: the AI's run allowance is not touched.
48873
+ wholeSuite: async (files) => args2?.tests && now() < hardStopAtMs ? oldCodeRunner(args2, log, now, true)(files) : null,
48678
48874
  ...p.deps,
48679
48875
  hardStopAtMs
48680
48876
  };
@@ -48738,6 +48934,12 @@ async function runCodegenStep(p) {
48738
48934
  log({ event: "codegen.attempt_start", attempt: 1 });
48739
48935
  const firstStarted = now();
48740
48936
  let first = await attempt2();
48937
+ if ("failure" in first && first.failure.reason === "contract_rejected" && p.fixFirst === true && args2?.fixFirst === true) {
48938
+ log({ event: "codegen.version_fallback", from: "codegen-loop-8", to: "codegen-loop-7" });
48939
+ p.fixFirst = false;
48940
+ args2 = buildCodegenLoopArgs(p, context);
48941
+ first = await attempt2();
48942
+ }
48741
48943
  if ("failure" in first && first.failure.reason === "contract_rejected" && p.conflicts && args2?.conflicts) {
48742
48944
  log({ event: "codegen.version_fallback", from: "codegen-loop-7", to: "codegen-loop-6" });
48743
48945
  p.conflicts = void 0;
@@ -48783,7 +48985,7 @@ async function runCodegenStep(p) {
48783
48985
  return finish(first.done);
48784
48986
  }
48785
48987
  const f1 = first.failure;
48786
- log({ event: "codegen.attempt_end", attempt: 1, outcome: "failed", reason: f1.reason, turns: f1.summary?.turns ?? 0, toolCalls: f1.summary?.toolCalls ?? 0, durationMs: firstMs });
48988
+ log({ event: "codegen.attempt_end", attempt: 1, outcome: "failed", reason: f1.reason, ...f1.afterRecovery ? { afterRecovery: true } : {}, turns: f1.summary?.turns ?? 0, toolCalls: f1.summary?.toolCalls ?? 0, durationMs: firstMs });
48787
48989
  const said = f1.detail ? `: ${f1.detail}` : "";
48788
48990
  if (f1.reason === "contract_rejected") {
48789
48991
  p.out.loop = buildCodegenLoopRecord({ ...f1.summary ?? NO_SUMMARY, stopReason: "fallback", fellBack: true, fallbackReason: f1.reason });
@@ -48825,7 +49027,7 @@ async function runCodegenStep(p) {
48825
49027
  return finish(second.done, [firstRecord, { n: 2, outcome: "finished", turns: second.done.summary.turns, toolCalls: second.done.summary.toolCalls }]);
48826
49028
  }
48827
49029
  const f2 = second.failure;
48828
- log({ event: "codegen.attempt_end", attempt: 2, outcome: "failed", reason: f2.reason, turns: f2.summary?.turns ?? 0, toolCalls: f2.summary?.toolCalls ?? 0, durationMs: secondMs });
49030
+ log({ event: "codegen.attempt_end", attempt: 2, outcome: "failed", reason: f2.reason, ...f2.afterRecovery ? { afterRecovery: true } : {}, turns: f2.summary?.turns ?? 0, toolCalls: f2.summary?.toolCalls ?? 0, durationMs: secondMs });
48829
49031
  throw lose(p, f2.summary, [firstRecord, failedAttempt(2, f2)], f2.reason === "out_of_time" ? "out_of_time" : "failed", f2.unreportable);
48830
49032
  }
48831
49033
 
@@ -48918,7 +49120,7 @@ async function runHealAttempt(i3) {
48918
49120
  p,
48919
49121
  collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, writeRoot: p.writeRoot ?? "", ...discoveredTests ? { discoveredTests } : {}, readFile: disk })
48920
49122
  );
48921
- const args2 = buildCodegenLoopArgs({ ...p, targets, workspaceListing }, context);
49123
+ const args2 = buildCodegenLoopArgs({ ...p, targets, workspaceListing, fixFirst: false }, context);
48922
49124
  if (i3.review !== void 0 || i3.answer.regressions <= 0) delete args2.conflicts;
48923
49125
  if (args2.conflicts && i3.misfits && i3.misfits.length > 0) args2.conflicts = withMisfits(args2.conflicts, i3.misfits);
48924
49126
  args2.protectedTestPaths = original.protectedTestPaths;
@@ -50807,7 +51009,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
50807
51009
  var REPORT_COPY = "final-test-report.xml";
50808
51010
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
50809
51011
  var MAX_FILES = 200;
50810
- var RUNNER_VERSION = true ? "9.3.0-rc.56" : "dev";
51012
+ var RUNNER_VERSION = true ? "9.3.0-rc.58" : "dev";
50811
51013
  function safeDestination(base, repoPath) {
50812
51014
  if (!repoPath || (0, import_node_path25.isAbsolute)(repoPath)) return null;
50813
51015
  const destination = (0, import_node_path25.resolve)(base, repoPath);
@@ -51630,6 +51832,8 @@ async function run2(env2) {
51630
51832
  mode: codegenMode,
51631
51833
  ...keepOnGiveUp ? { keepOnGiveUp: true } : {},
51632
51834
  ...conflictsOn ? { conflicts: { decided, titles: approved?.titles ?? [], approvedTests: approved?.approvedTests ?? [] } } : {},
51835
+ // 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.
51836
+ ...conflictsOn && packet.fixFirst === true && process.env.QUIKPILOT_FIX_FIRST?.trim().toLowerCase() !== "off" ? { fixFirst: true } : {},
51633
51837
  ...approved && approved.files.length > 0 ? { approved: approved.files } : {},
51634
51838
  ...callFunction ? { callFunction } : {},
51635
51839
  ...twoPhase ? { twoPhase: true, ...packet.requiredTestTypes ? { requiredTestTypes: packet.requiredTestTypes } : {} } : {},