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

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
@@ -35,7 +35,7 @@ var require_estraverse = __commonJS({
35
35
  "../../node_modules/estraverse/estraverse.js"(exports2) {
36
36
  (function clone(exports3) {
37
37
  "use strict";
38
- var Syntax4, VisitorOption, VisitorKeys, BREAK, SKIP, REMOVE;
38
+ var Syntax4, VisitorOption2, VisitorKeys, BREAK, SKIP, REMOVE;
39
39
  function deepCopy(obj) {
40
40
  var ret = {}, key, val;
41
41
  for (key in obj) {
@@ -231,7 +231,7 @@ var require_estraverse = __commonJS({
231
231
  BREAK = {};
232
232
  SKIP = {};
233
233
  REMOVE = {};
234
- VisitorOption = {
234
+ VisitorOption2 = {
235
235
  Break: BREAK,
236
236
  Skip: SKIP,
237
237
  Remove: REMOVE
@@ -356,7 +356,7 @@ var require_estraverse = __commonJS({
356
356
  }
357
357
  return false;
358
358
  }
359
- Controller.prototype.traverse = function traverse3(root, visitor) {
359
+ Controller.prototype.traverse = function traverse4(root, visitor) {
360
360
  var worklist, leavelist, element, node, nodeType, ret, key, current2, current22, candidates, candidate, sentinel;
361
361
  this.__initialize(root, visitor);
362
362
  sentinel = {};
@@ -533,7 +533,7 @@ var require_estraverse = __commonJS({
533
533
  }
534
534
  return outer.root;
535
535
  };
536
- function traverse2(root, visitor) {
536
+ function traverse3(root, visitor) {
537
537
  var controller = new Controller();
538
538
  return controller.traverse(root, visitor);
539
539
  }
@@ -576,7 +576,7 @@ var require_estraverse = __commonJS({
576
576
  comments.push(extendCommentRange(deepCopy(providedComments[i2]), tokens));
577
577
  }
578
578
  cursor = 0;
579
- traverse2(tree, {
579
+ traverse3(tree, {
580
580
  enter: function(node) {
581
581
  var comment2;
582
582
  while (cursor < comments.length) {
@@ -595,15 +595,15 @@ var require_estraverse = __commonJS({
595
595
  }
596
596
  }
597
597
  if (cursor === comments.length) {
598
- return VisitorOption.Break;
598
+ return VisitorOption2.Break;
599
599
  }
600
600
  if (comments[cursor].extendedRange[0] > node.range[1]) {
601
- return VisitorOption.Skip;
601
+ return VisitorOption2.Skip;
602
602
  }
603
603
  }
604
604
  });
605
605
  cursor = 0;
606
- traverse2(tree, {
606
+ traverse3(tree, {
607
607
  leave: function(node) {
608
608
  var comment2;
609
609
  while (cursor < comments.length) {
@@ -622,21 +622,21 @@ var require_estraverse = __commonJS({
622
622
  }
623
623
  }
624
624
  if (cursor === comments.length) {
625
- return VisitorOption.Break;
625
+ return VisitorOption2.Break;
626
626
  }
627
627
  if (comments[cursor].extendedRange[0] > node.range[1]) {
628
- return VisitorOption.Skip;
628
+ return VisitorOption2.Skip;
629
629
  }
630
630
  }
631
631
  });
632
632
  return tree;
633
633
  }
634
634
  exports3.Syntax = Syntax4;
635
- exports3.traverse = traverse2;
635
+ exports3.traverse = traverse3;
636
636
  exports3.replace = replace;
637
637
  exports3.attachComments = attachComments;
638
638
  exports3.VisitorKeys = VisitorKeys;
639
- exports3.VisitorOption = VisitorOption;
639
+ exports3.VisitorOption = VisitorOption2;
640
640
  exports3.Controller = Controller;
641
641
  exports3.cloneEnvironment = function() {
642
642
  return clone({});
@@ -709,7 +709,7 @@ var require_esrecurse = __commonJS({
709
709
  "../../node_modules/esrecurse/esrecurse.js"(exports2) {
710
710
  (function() {
711
711
  "use strict";
712
- var estraverse5 = require_estraverse();
712
+ var estraverse6 = require_estraverse();
713
713
  function isNode(node) {
714
714
  if (node == null) {
715
715
  return false;
@@ -717,12 +717,12 @@ var require_esrecurse = __commonJS({
717
717
  return typeof node === "object" && typeof node.type === "string";
718
718
  }
719
719
  function isProperty(nodeType, key) {
720
- return (nodeType === estraverse5.Syntax.ObjectExpression || nodeType === estraverse5.Syntax.ObjectPattern) && key === "properties";
720
+ return (nodeType === estraverse6.Syntax.ObjectExpression || nodeType === estraverse6.Syntax.ObjectPattern) && key === "properties";
721
721
  }
722
722
  function Visitor(visitor, options) {
723
723
  options = options || {};
724
724
  this.__visitor = visitor || this;
725
- this.__childVisitorKeys = options.childVisitorKeys ? Object.assign({}, estraverse5.VisitorKeys, options.childVisitorKeys) : estraverse5.VisitorKeys;
725
+ this.__childVisitorKeys = options.childVisitorKeys ? Object.assign({}, estraverse6.VisitorKeys, options.childVisitorKeys) : estraverse6.VisitorKeys;
726
726
  if (options.fallback === "iteration") {
727
727
  this.__fallback = Object.keys;
728
728
  } else if (typeof options.fallback === "function") {
@@ -734,7 +734,7 @@ var require_esrecurse = __commonJS({
734
734
  if (node == null) {
735
735
  return;
736
736
  }
737
- type = node.type || estraverse5.Syntax.Property;
737
+ type = node.type || estraverse6.Syntax.Property;
738
738
  children = this.__childVisitorKeys[type];
739
739
  if (!children) {
740
740
  if (this.__fallback) {
@@ -765,7 +765,7 @@ var require_esrecurse = __commonJS({
765
765
  if (node == null) {
766
766
  return;
767
767
  }
768
- type = node.type || estraverse5.Syntax.Property;
768
+ type = node.type || estraverse6.Syntax.Property;
769
769
  if (this.__visitor[type]) {
770
770
  this.__visitor[type].call(this, node);
771
771
  return;
@@ -805,6 +805,19 @@ function readRunnerEnv(env2 = process.env) {
805
805
  githubRepository
806
806
  };
807
807
  }
808
+ if (env2.MODE === "investigate") {
809
+ return {
810
+ mode: "investigate",
811
+ runId: required("RUN_ID", env2.RUN_ID),
812
+ callbackUrl: required("CALLBACK_URL", env2.CALLBACK_URL),
813
+ packetUrl: required("PACKET_URL", env2.PACKET_URL),
814
+ tokenUrl: required("TOKEN_URL", env2.TOKEN_URL),
815
+ githubRunId,
816
+ githubServerUrl,
817
+ githubRepository
818
+ };
819
+ }
820
+ if (env2.MODE && env2.MODE !== "run") throw new Error(`Unknown MODE: ${env2.MODE}`);
808
821
  return {
809
822
  mode: "run",
810
823
  runId: required("RUN_ID", env2.RUN_ID),
@@ -832,7 +845,7 @@ async function describeQuikTrackFailure(res) {
832
845
 
833
846
  // src/callback.ts
834
847
  async function reportBack(params) {
835
- const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, codegenLoop, unresolved } = params;
848
+ const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, codegenLoop, unresolved } = params;
836
849
  const body = { status };
837
850
  if (branch) body.branch = branch;
838
851
  if (warnings && warnings.length > 0) body.warnings = warnings;
@@ -840,6 +853,7 @@ async function reportBack(params) {
840
853
  if (targeting) body.targeting = targeting;
841
854
  if (baselineFindings) body.baselineFindings = baselineFindings;
842
855
  if (vanishedTests) body.vanishedTests = vanishedTests;
856
+ if (unsuppliedInputs && unsuppliedInputs.length > 0) body.unsuppliedInputs = unsuppliedInputs;
843
857
  if (codegenLoop) body.codegenLoop = codegenLoop;
844
858
  const res = await fetch(callbackUrl, {
845
859
  method: "POST",
@@ -1089,6 +1103,9 @@ function git(args, extraEnv = {}) {
1089
1103
  env: { ...process.env, ...extraEnv }
1090
1104
  }).trim();
1091
1105
  }
1106
+ function headCommit() {
1107
+ return git(["rev-parse", "HEAD"]);
1108
+ }
1092
1109
  function currentBranch() {
1093
1110
  return git(["rev-parse", "--abbrev-ref", "HEAD"]);
1094
1111
  }
@@ -1705,9 +1722,9 @@ function countRemovedLines(currentContent, newContent) {
1705
1722
  }
1706
1723
  let removed = 0;
1707
1724
  for (const line of currentContent.split("\n")) {
1708
- const count = remaining.get(line) ?? 0;
1709
- if (count > 0) {
1710
- remaining.set(line, count - 1);
1725
+ const count2 = remaining.get(line) ?? 0;
1726
+ if (count2 > 0) {
1727
+ remaining.set(line, count2 - 1);
1711
1728
  } else {
1712
1729
  removed++;
1713
1730
  }
@@ -2083,6 +2100,34 @@ function resolveCodegenMode(env2 = process.env, packetSetting) {
2083
2100
  return parse(packetSetting) ?? parse(env2[CODEGEN_MODE_ENV]) ?? "single";
2084
2101
  }
2085
2102
 
2103
+ // src/attemptSentences.ts
2104
+ var MAX_PREVIOUS_DETAIL_CHARS = 300;
2105
+ var MAX_PREVIOUS_RULES = 15;
2106
+ var MAX_PREVIOUS_TESTS = 20;
2107
+ var MAX_PREVIOUS_NAME_CHARS = 200;
2108
+ var MAX_PREVIOUS_MESSAGE_CHARS = 120;
2109
+ var MAX_PREVIOUS_COUNT = 1e5;
2110
+ var COVERAGE_PREFIX = "Required test cases not written: ";
2111
+ function coverageSentence(ids) {
2112
+ const total = ids.length;
2113
+ for (let shown = total; shown >= 1; shown--) {
2114
+ const rest = total - shown;
2115
+ const text = `${COVERAGE_PREFIX}${ids.slice(0, shown).join(", ")}${rest > 0 ? `, and ${rest} more` : ""}.`;
2116
+ if (text.length <= MAX_PREVIOUS_DETAIL_CHARS) return text;
2117
+ }
2118
+ return `${COVERAGE_PREFIX}${total} of them.`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
2119
+ }
2120
+ function truncationPhrase(suspect) {
2121
+ if (/^contains placeholder text/i.test(suspect)) return "placeholder text that suggests an abbreviated rewrite";
2122
+ if (/^sharp length drop/i.test(suspect)) return "a sharp drop in length";
2123
+ if (/^removed \d+ of \d+ lines/i.test(suspect)) return "many lines removed";
2124
+ if (/^removed exported symbol/i.test(suspect)) return "some of the file's exports were removed";
2125
+ return "the file came out much shorter than the original";
2126
+ }
2127
+ function truncationSentence(path, suspect) {
2128
+ return `${path}: ${truncationPhrase(suspect)}`.slice(0, MAX_PREVIOUS_DETAIL_CHARS);
2129
+ }
2130
+
2086
2131
  // src/refusedReply.ts
2087
2132
  var REFUSED_OUTCOME = "REFUSED";
2088
2133
  var REFUSED_STREAK_LIMIT = 3;
@@ -2142,6 +2187,119 @@ function clampRefusedTurns(turns) {
2142
2187
  return { rows, cut };
2143
2188
  }
2144
2189
 
2190
+ // src/codegenAttempts.ts
2191
+ var CODEGEN_BUDGET_MS = 30 * 6e4;
2192
+ var MIN_SECOND_ATTEMPT_MS = 3 * 6e4;
2193
+ function secondAttemptFloorMs(a) {
2194
+ return Math.max(a.firstAttemptMs, a.testLimitMs ?? 0, MIN_SECOND_ATTEMPT_MS);
2195
+ }
2196
+ var REASON_WORDS = {
2197
+ contract_rejected: "the AI service did not accept the request (it may be switched off)",
2198
+ semantic_mismatch: "the AI service and the runner disagreed about the request",
2199
+ http_error: "the AI service returned an error",
2200
+ transport: "the AI service could not be reached",
2201
+ turn_timeout: "one step took too long",
2202
+ loop_deadline: "the whole change took too long",
2203
+ runtime_failed: "the AI service failed",
2204
+ bad_reply: "the AI service sent a reply that could not be used",
2205
+ duplicate_call_ids: "the AI service repeated a request",
2206
+ final_not_produced: "it never reached an answer",
2207
+ token_ceiling: "the request grew too large for one step",
2208
+ executor_error: "reading or changing the code failed",
2209
+ internal_error: "the runner hit an internal error",
2210
+ cannot_complete: "the AI said it could not make the change from what it could see",
2211
+ no_writes: "it said it was finished but had changed nothing",
2212
+ coverage_missing: "it said it was finished but had not written a test for every case",
2213
+ truncation_guard: "a file it rewrote looked cut short",
2214
+ syntax_error: "a file it changed would not run (a syntax error, or a name that is used but never defined or imported)",
2215
+ out_of_time: "the time allowed for writing the change ran out"
2216
+ };
2217
+ function reasonInWords(reason) {
2218
+ return REASON_WORDS[reason] ?? reason;
2219
+ }
2220
+ function exhaustedMessage(attempts, stop) {
2221
+ const first = attempts[0];
2222
+ const second = attempts[1];
2223
+ const firstWords = reasonInWords(first?.reason ?? "internal_error");
2224
+ if (stop === "failed") {
2225
+ 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.`;
2226
+ }
2227
+ const head = "QuikPilot could not write the change in the time allowed. ";
2228
+ if (second?.outcome === "not_started") {
2229
+ 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.`;
2230
+ }
2231
+ return `${head}The first attempt ended because ${firstWords}. The second attempt ended because ${reasonInWords(second?.reason ?? "out_of_time")}. Nothing was written.`;
2232
+ }
2233
+ var CodegenAttemptsExhausted = class extends Error {
2234
+ attempts;
2235
+ /** `out_of_time` when the shared clock decided the end, `failed` when both attempts ended without a result for any other reason. */
2236
+ stopReason;
2237
+ constructor(attempts, stopReason) {
2238
+ super(exhaustedMessage(attempts, stopReason));
2239
+ this.name = "CodegenAttemptsExhausted";
2240
+ this.attempts = attempts;
2241
+ this.stopReason = stopReason;
2242
+ }
2243
+ };
2244
+ var RULE_SHAPE = /^[a-z][a-z0-9_]{0,39}$/;
2245
+ function count(n) {
2246
+ return typeof n === "number" && Number.isInteger(n) ? Math.min(MAX_PREVIOUS_COUNT, Math.max(0, n)) : 0;
2247
+ }
2248
+ function isRecord(x) {
2249
+ return typeof x === "object" && x !== null && !Array.isArray(x);
2250
+ }
2251
+ function testRunFrom(answer) {
2252
+ if (!isRecord(answer)) return void 0;
2253
+ const numbers = ["passed", "failed", "total", "regressions", "newFailures", "alreadyFailing"];
2254
+ if (!numbers.every((k) => typeof answer[k] === "number") || !Array.isArray(answer.failingTests)) return void 0;
2255
+ 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);
2256
+ const run2 = {
2257
+ passed: count(answer.passed),
2258
+ failed: count(answer.failed),
2259
+ total: count(answer.total),
2260
+ regressions: count(answer.regressions),
2261
+ newFailures: count(answer.newFailures),
2262
+ alreadyFailing: count(answer.alreadyFailing),
2263
+ failingTests
2264
+ };
2265
+ if (isRecord(answer.messages)) {
2266
+ const listed = new Set(failingTests);
2267
+ const messages = {};
2268
+ for (const [name, text] of Object.entries(answer.messages)) {
2269
+ const key = name.slice(0, MAX_PREVIOUS_NAME_CHARS);
2270
+ if (typeof text !== "string" || !listed.has(key) || Object.keys(messages).length >= MAX_PREVIOUS_TESTS) continue;
2271
+ const cut = text.slice(0, MAX_PREVIOUS_MESSAGE_CHARS);
2272
+ if (cut.length > 0) messages[key] = cut;
2273
+ }
2274
+ if (Object.keys(messages).length > 0) run2.messages = messages;
2275
+ }
2276
+ return run2;
2277
+ }
2278
+ function rulesFrom(rows) {
2279
+ if (!Array.isArray(rows) || rows.length === 0) return void 0;
2280
+ const counts = /* @__PURE__ */ new Map();
2281
+ for (const row of rows) {
2282
+ for (const raw of row.rules) {
2283
+ const word = recordRuleWord(raw);
2284
+ counts.set(word, (counts.get(word) ?? 0) + 1);
2285
+ }
2286
+ }
2287
+ 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);
2288
+ return ordered.length > 0 ? ordered.slice(0, MAX_PREVIOUS_RULES) : void 0;
2289
+ }
2290
+ function previousAttemptFrom(failure, attempt2) {
2291
+ const told = typeof failure.told === "string" ? failure.told.slice(0, MAX_PREVIOUS_DETAIL_CHARS) : "";
2292
+ const lastTestRun = testRunFrom(failure.lastTestAnswer);
2293
+ const rules = rulesFrom(failure.summary?.refusedTurns);
2294
+ return {
2295
+ attempt: attempt2,
2296
+ endedWith: RULE_SHAPE.test(failure.reason) ? failure.reason : "other",
2297
+ ...told.length > 0 ? { detail: told } : {},
2298
+ ...lastTestRun ? { lastTestRun } : {},
2299
+ ...rules ? { rules } : {}
2300
+ };
2301
+ }
2302
+
2145
2303
  // src/codegenLoopRecord.ts
2146
2304
  var MAX_RECORD_PATHS = 50;
2147
2305
  var MAX_RECORD_PATH_CHARS = 300;
@@ -2149,11 +2307,16 @@ var MAX_RECORD_REASONING_TURNS = 30;
2149
2307
  var MAX_RECORD_REASONING_CHARS = 500;
2150
2308
  var MAX_RECORD_FALLBACK_REASON_CHARS = 40;
2151
2309
  var MAX_RECORD_TEST_RUNS = 3;
2310
+ var MAX_RECORD_ATTEMPTS = 3;
2311
+ var MAX_ATTEMPT_COUNT = 1e3;
2152
2312
  var MAX_STATUS_KEYS = 20;
2153
2313
  var MAX_STATUS_KEY_CHARS = 40;
2154
2314
  function whole(n) {
2155
2315
  return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
2156
2316
  }
2317
+ function small(n) {
2318
+ return Math.min(MAX_ATTEMPT_COUNT, whole(n));
2319
+ }
2157
2320
  function pathOk(p) {
2158
2321
  return typeof p === "string" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;
2159
2322
  }
@@ -2221,6 +2384,25 @@ function buildCodegenLoopRecord(loop) {
2221
2384
  }
2222
2385
  const refused2 = clampRefusedTurns(loop.refusedTurns);
2223
2386
  if (refused2.cut) cut = true;
2387
+ const attempts = [];
2388
+ for (const a of loop.attempts ?? []) {
2389
+ if (attempts.length >= MAX_RECORD_ATTEMPTS) {
2390
+ cut = true;
2391
+ break;
2392
+ }
2393
+ if (!Number.isInteger(a.n) || a.n < 1 || a.n > MAX_RECORD_ATTEMPTS || typeof a.outcome !== "string" || a.outcome.length === 0) {
2394
+ cut = true;
2395
+ continue;
2396
+ }
2397
+ const reason = typeof a.reason === "string" ? a.reason.slice(0, MAX_STATUS_KEY_CHARS) : "";
2398
+ attempts.push({
2399
+ n: a.n,
2400
+ outcome: a.outcome.slice(0, MAX_STATUS_KEY_CHARS),
2401
+ ...reason.length > 0 ? { reason } : {},
2402
+ turns: small(a.turns),
2403
+ toolCalls: small(a.toolCalls)
2404
+ });
2405
+ }
2224
2406
  return {
2225
2407
  turns: whole(loop.turns),
2226
2408
  toolCalls: whole(loop.toolCalls),
@@ -2236,6 +2418,7 @@ function buildCodegenLoopRecord(loop) {
2236
2418
  ...typeof loop.contractVersion === "string" && loop.contractVersion.length > 0 ? { contractVersion: loop.contractVersion.slice(0, 40) } : {},
2237
2419
  ...testRuns.length > 0 ? { testRuns } : {},
2238
2420
  ...refused2.rows.length > 0 ? { refusedTurns: refused2.rows } : {},
2421
+ ...attempts.length > 0 ? { attempts } : {},
2239
2422
  reasoning,
2240
2423
  ...cut ? { truncated: true } : {}
2241
2424
  };
@@ -5391,7 +5574,7 @@ pp$8.parseClassElement = function(constructorAllowsSuper) {
5391
5574
  }
5392
5575
  var ecmaVersion2 = this.options.ecmaVersion;
5393
5576
  var node = this.startNode();
5394
- var keyName = "";
5577
+ var keyName2 = "";
5395
5578
  var isGenerator = false;
5396
5579
  var isAsync = false;
5397
5580
  var kind = "method";
@@ -5404,34 +5587,34 @@ pp$8.parseClassElement = function(constructorAllowsSuper) {
5404
5587
  if (this.isClassElementNameStart() || this.type === types$1.star) {
5405
5588
  isStatic = true;
5406
5589
  } else {
5407
- keyName = "static";
5590
+ keyName2 = "static";
5408
5591
  }
5409
5592
  }
5410
5593
  node.static = isStatic;
5411
- if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) {
5594
+ if (!keyName2 && ecmaVersion2 >= 8 && this.eatContextual("async")) {
5412
5595
  if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
5413
5596
  isAsync = true;
5414
5597
  } else {
5415
- keyName = "async";
5598
+ keyName2 = "async";
5416
5599
  }
5417
5600
  }
5418
- if (!keyName && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {
5601
+ if (!keyName2 && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {
5419
5602
  isGenerator = true;
5420
5603
  }
5421
- if (!keyName && !isAsync && !isGenerator) {
5604
+ if (!keyName2 && !isAsync && !isGenerator) {
5422
5605
  var lastValue = this.value;
5423
5606
  if (this.eatContextual("get") || this.eatContextual("set")) {
5424
5607
  if (this.isClassElementNameStart()) {
5425
5608
  kind = lastValue;
5426
5609
  } else {
5427
- keyName = lastValue;
5610
+ keyName2 = lastValue;
5428
5611
  }
5429
5612
  }
5430
5613
  }
5431
- if (keyName) {
5614
+ if (keyName2) {
5432
5615
  node.computed = false;
5433
5616
  node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
5434
- node.key.name = keyName;
5617
+ node.key.name = keyName2;
5435
5618
  this.finishNode(node.key, "Identifier");
5436
5619
  } else {
5437
5620
  this.parseClassElementName(node);
@@ -5833,11 +6016,11 @@ pp$8.parseWithClause = function() {
5833
6016
  first = false;
5834
6017
  }
5835
6018
  var attr = this.parseImportAttribute();
5836
- var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
5837
- if (hasOwn(attributeKeys, keyName)) {
5838
- this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName + "'");
6019
+ var keyName2 = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
6020
+ if (hasOwn(attributeKeys, keyName2)) {
6021
+ this.raiseRecoverable(attr.key.start, "Duplicate attribute key '" + keyName2 + "'");
5839
6022
  }
5840
- attributeKeys[keyName] = true;
6023
+ attributeKeys[keyName2] = true;
5841
6024
  nodes.push(attr);
5842
6025
  }
5843
6026
  return nodes;
@@ -8644,11 +8827,11 @@ pp$1.regexp_classStringDisjunctionContents = function(state) {
8644
8827
  return result;
8645
8828
  };
8646
8829
  pp$1.regexp_classString = function(state) {
8647
- var count = 0;
8830
+ var count2 = 0;
8648
8831
  while (this.regexp_eatClassSetCharacter(state)) {
8649
- count++;
8832
+ count2++;
8650
8833
  }
8651
- return count === 1 ? CharSetOk : CharSetString;
8834
+ return count2 === 1 ? CharSetOk : CharSetString;
8652
8835
  };
8653
8836
  pp$1.regexp_eatClassSetCharacter = function(state) {
8654
8837
  var start = state.pos;
@@ -11278,7 +11461,7 @@ function prepareListFiles(args, env2) {
11278
11461
  const slash = rest.indexOf("/");
11279
11462
  if (slash > 0) counts.set(rest.slice(0, slash), (counts.get(rest.slice(0, slash)) ?? 0) + 1);
11280
11463
  }
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);
11464
+ 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
11465
  }
11283
11466
  return { result: { status: "ok", output } };
11284
11467
  }
@@ -12129,8 +12312,8 @@ async function reportToQuikTest(params) {
12129
12312
  try {
12130
12313
  console.log(`reporting ${report}`);
12131
12314
  const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
12132
- const { readFileSync: readFileSync11 } = await import("node:fs");
12133
- const body = readFileSync11(report);
12315
+ const { readFileSync: readFileSync12 } = await import("node:fs");
12316
+ const body = readFileSync12(report);
12134
12317
  let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
12135
12318
  if (generatedFiles) {
12136
12319
  url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
@@ -12908,13 +13091,22 @@ var CodegenLoopFailure = class extends Error {
12908
13091
  runtimeCode;
12909
13092
  /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */
12910
13093
  detail;
13094
+ /**
13095
+ * 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
13096
+ * 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
13097
+ * for one check lists names read from the original file.
13098
+ */
13099
+ told;
13100
+ /** The last `run_tests` answer the AI was shown in this attempt, kept for the next one. Wire only: never logged, never recorded. */
13101
+ lastTestAnswer;
12911
13102
  summary;
12912
- constructor(reason, runtimeCode, cause, detail) {
13103
+ constructor(reason, runtimeCode, cause, detail, told) {
12913
13104
  super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
12914
13105
  this.name = "CodegenLoopFailure";
12915
13106
  this.reason = reason;
12916
13107
  this.runtimeCode = runtimeCode;
12917
13108
  this.detail = detail;
13109
+ this.told = told;
12918
13110
  if (cause !== void 0) this.cause = cause;
12919
13111
  }
12920
13112
  };
@@ -12933,6 +13125,9 @@ function classifyTransport2(err) {
12933
13125
  if (name === "TimeoutError" || name === "AbortError") return new CodegenLoopFailure("turn_timeout", void 0, err);
12934
13126
  return new CodegenLoopFailure("transport", void 0, err);
12935
13127
  }
13128
+ function isTestAnswer(x) {
13129
+ return isPlainObject3(x) && typeof x.passed === "number" && Array.isArray(x.failingTests);
13130
+ }
12936
13131
  var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
12937
13132
  async function runCodegenLoop(args, deps) {
12938
13133
  const ws = createCodegenWorkspace({
@@ -12957,6 +13152,8 @@ async function runCodegenLoop(args, deps) {
12957
13152
  now
12958
13153
  }) : null;
12959
13154
  let testMs = 0;
13155
+ let lastTestAnswer;
13156
+ const pastHardStop = () => deps.hardStopAtMs !== void 0 && now() >= deps.hardStopAtMs;
12960
13157
  const turnTimeoutMs = deps.turnTimeoutMs ?? 3e5;
12961
13158
  const deadlineMs = deps.deadlineMs ?? 15e5;
12962
13159
  const reads = [];
@@ -12981,6 +13178,7 @@ async function runCodegenLoop(args, deps) {
12981
13178
  ...isFinal ? { finalReason } : {},
12982
13179
  // Says this runner can carry a REFUSED answer (24.12a). Without it the runtime fails the request, as it always did.
12983
13180
  acceptsRefused: true,
13181
+ ...args.previousAttempt ? { previousAttempt: args.previousAttempt } : {},
12984
13182
  remaining: {
12985
13183
  toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
12986
13184
  readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),
@@ -12997,7 +13195,7 @@ async function runCodegenLoop(args, deps) {
12997
13195
  refused: ledger.refused,
12998
13196
  stopReason,
12999
13197
  reads: [...reads],
13000
- edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),
13198
+ edits: [...ws.edits.entries()].map(([path, count2]) => ({ path, count: count2 })),
13001
13199
  created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),
13002
13200
  statusCounts: { ...statusCounts },
13003
13201
  syntaxWarnings: ws.syntaxWarnings,
@@ -13042,6 +13240,7 @@ async function runCodegenLoop(args, deps) {
13042
13240
  try {
13043
13241
  for (let turn = 1; turn <= limits.maxTurns; turn++) {
13044
13242
  turns = turn;
13243
+ if (pastHardStop()) throw new CodegenLoopFailure("out_of_time");
13045
13244
  if (now() - started - Math.min(testMs, MAX_TEST_RUNS * MAX_TEST_LIMIT_MS) > deadlineMs) throw new CodegenLoopFailure("loop_deadline");
13046
13245
  const isFinal = forced !== null || turn === limits.maxTurns;
13047
13246
  const finalReason = forced ?? "max_turns";
@@ -13100,7 +13299,7 @@ async function runCodegenLoop(args, deps) {
13100
13299
  if (body.outcome === "CANNOT_COMPLETE") {
13101
13300
  log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
13102
13301
  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);
13302
+ throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said, said);
13104
13303
  }
13105
13304
  if (body.outcome === "DONE") {
13106
13305
  log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
@@ -13110,7 +13309,7 @@ async function runCodegenLoop(args, deps) {
13110
13309
  const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
13111
13310
  if (missing.length > 0) {
13112
13311
  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`);
13312
+ throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`, coverageSentence(missing));
13114
13313
  }
13115
13314
  const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);
13116
13315
  for (const path of changed) {
@@ -13120,13 +13319,14 @@ async function runCodegenLoop(args, deps) {
13120
13319
  const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);
13121
13320
  if (suspect) {
13122
13321
  log({ event: "codegen.loop_refused", turn, reason: "truncation_guard", path });
13123
- throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`);
13322
+ throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`, truncationSentence(path, suspect));
13124
13323
  }
13125
13324
  }
13126
13325
  const broken = ws.syntaxProblems()[0];
13127
13326
  if (broken) {
13128
13327
  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)}`);
13328
+ const sentence = `${broken.path}: ${describeSyntaxProblem(broken.problem)}`;
13329
+ throw new CodegenLoopFailure("syntax_error", void 0, void 0, sentence, sentence.slice(0, MAX_PREVIOUS_DETAIL_CHARS));
13130
13330
  }
13131
13331
  const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
13132
13332
  const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
@@ -13154,6 +13354,7 @@ async function runCodegenLoop(args, deps) {
13154
13354
  if (index >= limits.maxCallsPerTurn) {
13155
13355
  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
13356
  } else if (call.name === RUN_TESTS_TOOL && tests) {
13357
+ if (pastHardStop()) throw new CodegenLoopFailure("out_of_time");
13157
13358
  const testsStarted = now();
13158
13359
  try {
13159
13360
  result = await executeRunTestsCall(call, tests, ledger, limits);
@@ -13171,6 +13372,7 @@ async function runCodegenLoop(args, deps) {
13171
13372
  }
13172
13373
  }
13173
13374
  results.push(result);
13375
+ if (call.name === RUN_TESTS_TOOL && isTestAnswer(result.output)) lastTestAnswer = result.output;
13174
13376
  if (read) reads.push(read);
13175
13377
  statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;
13176
13378
  const tool = TOOL_NAMES2.has(call.name) ? call.name : "unknown";
@@ -13198,6 +13400,7 @@ async function runCodegenLoop(args, deps) {
13198
13400
  if (err instanceof TreeNotRestoredError) throw err;
13199
13401
  const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
13200
13402
  failure.summary ??= snapshot("fallback");
13403
+ if (lastTestAnswer) failure.lastTestAnswer ??= lastTestAnswer;
13201
13404
  throw failure;
13202
13405
  }
13203
13406
  }
@@ -13286,6 +13489,22 @@ function perFile(p) {
13286
13489
  p.outOfScope
13287
13490
  );
13288
13491
  }
13492
+ function warn(p, message) {
13493
+ p.warnings.push(message);
13494
+ console.warn(`QuikPilot codegen warning (not blocking): ${message}`);
13495
+ }
13496
+ async function oneTestRunMs(tests) {
13497
+ const timed = await tests.baseline().catch(() => null);
13498
+ const limit = testTimeLimitMs(timed?.durationMs ?? null);
13499
+ return limit === "too_slow" ? MAX_TEST_LIMIT_MS : limit;
13500
+ }
13501
+ function failedAttempt(n, failure) {
13502
+ return { n, outcome: "failed", reason: failure.reason, turns: failure.summary?.turns ?? 0, toolCalls: failure.summary?.toolCalls ?? 0 };
13503
+ }
13504
+ function lose(p, summary, attempts, stop) {
13505
+ p.out.loop = buildCodegenLoopRecord({ ...summary ?? NO_SUMMARY, stopReason: stop, attempts });
13506
+ return new CodegenAttemptsExhausted(attempts, stop);
13507
+ }
13289
13508
  async function runCodegenStep(p) {
13290
13509
  if (p.mode !== "loop" && p.mode !== "loop-tests") return perFile(p);
13291
13510
  const testSetup = p.mode === "loop-tests" ? p.tests : void 0;
@@ -13293,6 +13512,10 @@ async function runCodegenStep(p) {
13293
13512
  () => captureTree(testSetup.root, [], testSetup.tree),
13294
13513
  () => captureTree(testSetup.root, [], testSetup.tree)
13295
13514
  ).catch(() => null) : null;
13515
+ const guardTree = async () => {
13516
+ const before = treeAtStart ? await treeAtStart : null;
13517
+ if (before && p.tests) assertTreeUnchanged(p.tests.root, before, [], p.tests.tree);
13518
+ };
13296
13519
  const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} });
13297
13520
  p.contextLog.push(...context.records);
13298
13521
  console.log(
@@ -13304,39 +13527,79 @@ async function runCodegenStep(p) {
13304
13527
  existingTests: context.testPaths
13305
13528
  })
13306
13529
  );
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);
13530
+ const now = p.deps?.now ?? Date.now;
13531
+ const log = p.deps?.log ?? ((e) => console.log(JSON.stringify(e)));
13532
+ const hardStopAtMs = now() + (p.budgetMs ?? CODEGEN_BUDGET_MS);
13533
+ let args;
13534
+ const attempt2 = async (previousAttempt) => {
13535
+ try {
13536
+ args ??= buildCodegenLoopArgs(p, context);
13537
+ const done = await runCodegenLoop(previousAttempt ? { ...args, previousAttempt } : args, {
13538
+ post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
13539
+ ...p.deps,
13540
+ hardStopAtMs
13541
+ });
13542
+ return { done };
13543
+ } catch (err) {
13544
+ if (err instanceof SafetyRefusalError) throw err;
13545
+ if (err instanceof TreeNotRestoredError) throw err;
13546
+ return { failure: err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err) };
13547
+ }
13548
+ };
13549
+ const finish = (done, attempts) => {
13550
+ p.out.loop = buildCodegenLoopRecord(attempts ? { ...done.summary, attempts } : done.summary);
13313
13551
  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
- }
13552
+ for (const r of done.results) {
13553
+ if (!planned.has(r.targetPath)) warn(p, `QuikPilot changed ${r.targetPath}, which the plan did not name.`);
13320
13554
  }
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);
13555
+ return done.results;
13556
+ };
13557
+ log({ event: "codegen.attempt_start", attempt: 1 });
13558
+ const firstStarted = now();
13559
+ const first = await attempt2();
13560
+ const firstMs = now() - firstStarted;
13561
+ if ("done" in first) {
13562
+ log({ event: "codegen.attempt_end", attempt: 1, outcome: "finished", turns: first.done.summary.turns, toolCalls: first.done.summary.toolCalls, durationMs: firstMs });
13563
+ return finish(first.done);
13564
+ }
13565
+ const f1 = first.failure;
13566
+ log({ event: "codegen.attempt_end", attempt: 1, outcome: "failed", reason: f1.reason, turns: f1.summary?.turns ?? 0, toolCalls: f1.summary?.toolCalls ?? 0, durationMs: firstMs });
13567
+ const said = f1.detail ? `: ${f1.detail}` : "";
13568
+ if (f1.reason === "contract_rejected") {
13569
+ p.out.loop = buildCodegenLoopRecord({ ...f1.summary ?? NO_SUMMARY, stopReason: "fallback", fellBack: true, fallbackReason: f1.reason });
13570
+ warn(p, `The code-writing loop could not finish (${f1.reason}${said}), so the files were written one at a time instead.`);
13571
+ await guardTree();
13338
13572
  return perFile(p);
13339
13573
  }
13574
+ await guardTree();
13575
+ const firstRecord = failedAttempt(1, f1);
13576
+ const testLimit = p.mode === "loop-tests" && p.tests ? await oneTestRunMs(p.tests) : null;
13577
+ const left = hardStopAtMs - now();
13578
+ const needed = secondAttemptFloorMs({ firstAttemptMs: firstMs, testLimitMs: testLimit });
13579
+ if (f1.reason === "out_of_time" || left < needed) {
13580
+ log({ event: "codegen.attempt_skipped", attempt: 2, reason: "out_of_time", leftMs: Math.max(0, left), neededMs: needed });
13581
+ throw lose(p, f1.summary, [firstRecord, { n: 2, outcome: "not_started", reason: "out_of_time", turns: 0, toolCalls: 0 }], "out_of_time");
13582
+ }
13583
+ warn(p, `The first attempt at writing the change ended (${f1.reason}${said}), so QuikPilot is trying once more.`);
13584
+ const previous = previousAttemptFrom(f1, 1);
13585
+ log({
13586
+ event: "codegen.attempt_start",
13587
+ attempt: 2,
13588
+ endedWith: previous.endedWith,
13589
+ hasDetail: previous.detail !== void 0,
13590
+ rulesCount: previous.rules?.length ?? 0,
13591
+ hasLastTestRun: previous.lastTestRun !== void 0
13592
+ });
13593
+ const secondStarted = now();
13594
+ const second = await attempt2(previous);
13595
+ const secondMs = now() - secondStarted;
13596
+ if ("done" in second) {
13597
+ log({ event: "codegen.attempt_end", attempt: 2, outcome: "finished", turns: second.done.summary.turns, toolCalls: second.done.summary.toolCalls, durationMs: secondMs });
13598
+ return finish(second.done, [firstRecord, { n: 2, outcome: "finished", turns: second.done.summary.turns, toolCalls: second.done.summary.toolCalls }]);
13599
+ }
13600
+ const f2 = second.failure;
13601
+ log({ event: "codegen.attempt_end", attempt: 2, outcome: "failed", reason: f2.reason, turns: f2.summary?.turns ?? 0, toolCalls: f2.summary?.toolCalls ?? 0, durationMs: secondMs });
13602
+ throw lose(p, f2.summary, [firstRecord, failedAttempt(2, f2)], f2.reason === "out_of_time" ? "out_of_time" : "failed");
13340
13603
  }
13341
13604
 
13342
13605
  // src/dependencyCheck.ts
@@ -13785,7 +14048,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
13785
14048
  var REPORT_COPY = "final-test-report.xml";
13786
14049
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
13787
14050
  var MAX_FILES = 200;
13788
- var RUNNER_VERSION = true ? "9.3.0-rc.10" : "dev";
14051
+ var RUNNER_VERSION = true ? "9.3.0-rc.12" : "dev";
13789
14052
  function safeDestination(base, repoPath) {
13790
14053
  if (!repoPath || (0, import_node_path12.isAbsolute)(repoPath)) return null;
13791
14054
  const destination = (0, import_node_path12.resolve)(base, repoPath);
@@ -14318,6 +14581,215 @@ function describeVanishedTests(vanished) {
14318
14581
  return `${noun} that ran before this change ${vanished.total === 1 ? "is" : "are"} missing from the final test report; the pull request lists ${vanished.total === 1 ? "it" : "them"}.`;
14319
14582
  }
14320
14583
 
14584
+ // src/unsuppliedInputs.ts
14585
+ var estraverse5 = __toESM(require_estraverse());
14586
+ var MAX_UNSUPPLIED_ENTRIES = 10;
14587
+ var MAX_UNSUPPLIED_NAMES = 5;
14588
+ var MAX_NAME_CHARS = 80;
14589
+ var MAX_FUNCTION_CHARS = 120;
14590
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
14591
+ var IDENTIFIER_NAME = /^[A-Za-z_$][\w$]*$/;
14592
+ function isFunction(node) {
14593
+ return FUNCTION_TYPES.has(node.type);
14594
+ }
14595
+ function collectFunctions(ast) {
14596
+ const out = [];
14597
+ estraverse5.traverse(ast, {
14598
+ fallback: "iteration",
14599
+ enter(node, parent) {
14600
+ if (isFunction(node)) out.push({ node, parent: parent ?? null });
14601
+ }
14602
+ });
14603
+ return out;
14604
+ }
14605
+ function keyName(key, computed) {
14606
+ if (!key) return null;
14607
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
14608
+ if (key.type === "Identifier" && !computed) return key.name;
14609
+ return null;
14610
+ }
14611
+ function nameOf({ node, parent }) {
14612
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {
14613
+ const id = node.id;
14614
+ if (id?.name) return id.name;
14615
+ }
14616
+ if (!parent) return "(anonymous)";
14617
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
14618
+ if (parent.type === "AssignmentExpression") {
14619
+ const left = parent.left;
14620
+ if (left.type === "Identifier") return left.name;
14621
+ if (left.type === "MemberExpression") return keyName(left.property, left.computed) ?? "(anonymous)";
14622
+ }
14623
+ if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
14624
+ return keyName(parent.key, parent.computed) ?? "(anonymous)";
14625
+ }
14626
+ return "(anonymous)";
14627
+ }
14628
+ function isCallback({ node, parent }) {
14629
+ if (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
14630
+ return (parent.arguments ?? []).includes(node);
14631
+ }
14632
+ function suppliedNames(ast, into) {
14633
+ estraverse5.traverse(ast, {
14634
+ fallback: "iteration",
14635
+ enter(node) {
14636
+ const n = node;
14637
+ if (n.type === "ObjectExpression") {
14638
+ for (const prop of n.properties ?? []) {
14639
+ if (prop.type !== "Property") continue;
14640
+ const name = keyName(prop.key, prop.computed);
14641
+ if (name) into.add(name);
14642
+ }
14643
+ } else if (n.type === "AssignmentExpression" && n.left.type === "MemberExpression") {
14644
+ const left = n.left;
14645
+ const name = keyName(left.property, left.computed);
14646
+ if (name) into.add(name);
14647
+ }
14648
+ }
14649
+ });
14650
+ }
14651
+ function parameters(fn) {
14652
+ const names = /* @__PURE__ */ new Set();
14653
+ const destructured = [];
14654
+ const visit = (p, topLevel) => {
14655
+ if (!p) return;
14656
+ if (p.type === "Identifier") names.add(p.name);
14657
+ else if (p.type === "AssignmentPattern") visit(p.left, topLevel);
14658
+ else if (p.type === "RestElement") visit(p.argument, topLevel);
14659
+ else if (p.type === "ObjectPattern") {
14660
+ for (const prop of p.properties ?? []) {
14661
+ if (prop.type === "RestElement") continue;
14662
+ const name = keyName(prop.key, prop.computed);
14663
+ const range = prop.range;
14664
+ if (name && topLevel) destructured.push({ name, at: range ? range[0] : 0 });
14665
+ }
14666
+ }
14667
+ };
14668
+ for (const p of fn.params ?? []) visit(p, true);
14669
+ return { names, destructured };
14670
+ }
14671
+ function readsOf(site) {
14672
+ const fn = site.node;
14673
+ const { names: params, destructured } = parameters(fn);
14674
+ const reads = [...destructured];
14675
+ estraverse5.traverse(fn.body, {
14676
+ fallback: "iteration",
14677
+ enter(node, parent) {
14678
+ const n = node;
14679
+ if (isFunction(n)) {
14680
+ const own = parameters(n).names;
14681
+ const shadows = [...own].some((name) => params.has(name));
14682
+ if (!isCallback({ node: n, parent }) || shadows) return estraverse5.VisitorOption.Skip;
14683
+ }
14684
+ const range = n.range;
14685
+ const at2 = range ? range[0] : 0;
14686
+ if (n.type === "MemberExpression") {
14687
+ const object = n.object;
14688
+ if (object.type !== "Identifier" || !params.has(object.name)) return;
14689
+ const name = keyName(n.property, n.computed);
14690
+ if (name) reads.push({ name, at: at2 });
14691
+ } else if (n.type === "VariableDeclarator" && n.id.type === "ObjectPattern" && n.init) {
14692
+ const init = n.init;
14693
+ if (init.type !== "Identifier" || !params.has(init.name)) return;
14694
+ for (const prop of n.id.properties ?? []) {
14695
+ if (prop.type === "RestElement") continue;
14696
+ const name = keyName(prop.key, prop.computed);
14697
+ if (name) reads.push({ name, at: at2 });
14698
+ }
14699
+ }
14700
+ }
14701
+ });
14702
+ reads.sort((a, b) => a.at - b.at);
14703
+ return reads;
14704
+ }
14705
+ function wordsOf(text, into) {
14706
+ for (const m of text.matchAll(/[\w$]+/g)) into.add(m[0]);
14707
+ }
14708
+ function findUnsuppliedInputs(input) {
14709
+ try {
14710
+ const known = /* @__PURE__ */ new Set();
14711
+ for (const file of input.corpus) {
14712
+ if (!isTestFile(file.path)) wordsOf(file.text, known);
14713
+ }
14714
+ const judged = [];
14715
+ const supplied = /* @__PURE__ */ new Set();
14716
+ for (const file of input.changed) {
14717
+ if (isTestFile(file.path) || !isCheckablePath(file.path)) continue;
14718
+ const after = parseProgram(file.path, file.newContent);
14719
+ if (!after) continue;
14720
+ suppliedNames(after.ast, supplied);
14721
+ judged.push({ file, ast: after.ast });
14722
+ }
14723
+ const found = [];
14724
+ for (const { file, ast } of judged) {
14725
+ for (const site of collectFunctions(ast)) {
14726
+ if (isCallback(site)) continue;
14727
+ const names = [];
14728
+ for (const { name } of readsOf(site)) {
14729
+ if (!IDENTIFIER_NAME.test(name) || name.length > MAX_NAME_CHARS) continue;
14730
+ if (known.has(name) || supplied.has(name) || names.includes(name)) continue;
14731
+ names.push(name);
14732
+ }
14733
+ if (names.length === 0) continue;
14734
+ found.push({ file: file.path, function: nameOf(site).slice(0, MAX_FUNCTION_CHARS), names: names.slice(0, MAX_UNSUPPLIED_NAMES) });
14735
+ if (found.length >= MAX_UNSUPPLIED_ENTRIES) return found;
14736
+ }
14737
+ }
14738
+ return found;
14739
+ } catch {
14740
+ return [];
14741
+ }
14742
+ }
14743
+ var MAX_CORPUS_CHARS = 64e6;
14744
+ function checkRunForUnsuppliedInputs(input) {
14745
+ try {
14746
+ const listed = new Set(input.listing);
14747
+ const corpus = [];
14748
+ let chars = 0;
14749
+ for (const path of listed) {
14750
+ const text = input.readText(path);
14751
+ if (text === null) continue;
14752
+ chars += text.length;
14753
+ if (chars > MAX_CORPUS_CHARS) return [];
14754
+ corpus.push({ path, text });
14755
+ }
14756
+ const changed = [];
14757
+ for (const { targetPath, newContent } of input.results) {
14758
+ if (listed.has(targetPath) && input.readText(targetPath) === null) continue;
14759
+ changed.push({ path: targetPath, newContent });
14760
+ }
14761
+ return findUnsuppliedInputs({ changed, corpus });
14762
+ } catch {
14763
+ return [];
14764
+ }
14765
+ }
14766
+ function describeUnsuppliedInputs(found) {
14767
+ const many = found.length !== 1;
14768
+ return `${found.length} changed function${many ? "s" : ""} ${many ? "read" : "reads"} a field that nothing else in the project supplies; the new tests may be the only thing feeding ${many ? "them" : "it"}. See "What QuikPilot noticed" on the run.`;
14769
+ }
14770
+
14771
+ // src/unsuppliedInputsDisk.ts
14772
+ var import_node_fs15 = require("node:fs");
14773
+ var MAX_READ_BYTES = 1e6;
14774
+ function readCheckoutText(path) {
14775
+ try {
14776
+ const info = (0, import_node_fs15.statSync)(path);
14777
+ if (!info.isFile() || info.size > MAX_READ_BYTES) return null;
14778
+ const bytes = (0, import_node_fs15.readFileSync)(path);
14779
+ if (bytes.includes(0)) return null;
14780
+ return bytes.toString("utf8");
14781
+ } catch {
14782
+ return null;
14783
+ }
14784
+ }
14785
+ function checkGeneratedCode(results) {
14786
+ try {
14787
+ return checkRunForUnsuppliedInputs({ results, listing: listFiles("."), readText: readCheckoutText });
14788
+ } catch {
14789
+ return [];
14790
+ }
14791
+ }
14792
+
14321
14793
  // src/run.ts
14322
14794
  async function run(env2) {
14323
14795
  let hardFailure = false;
@@ -14339,6 +14811,7 @@ async function run(env2) {
14339
14811
  let targetingResult;
14340
14812
  let baselineFindings;
14341
14813
  let vanishedTests;
14814
+ let unsuppliedInputs;
14342
14815
  const contextLog = [];
14343
14816
  const codegenOut = {};
14344
14817
  try {
@@ -14471,6 +14944,17 @@ async function run(env2) {
14471
14944
  console.error(message);
14472
14945
  warnings.push(message);
14473
14946
  }
14947
+ try {
14948
+ const unsupplied = checkGeneratedCode(results);
14949
+ if (unsupplied.length > 0) {
14950
+ unsuppliedInputs = unsupplied;
14951
+ const w = describeUnsuppliedInputs(unsupplied);
14952
+ warnings.push(w);
14953
+ console.warn(`QuikPilot code warning (not blocking): ${w}`);
14954
+ }
14955
+ } catch (err) {
14956
+ console.error(`Unsupplied-input check could not run (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14957
+ }
14474
14958
  generatedFilePaths = results.map((r) => r.targetPath);
14475
14959
  flushCodegenResults(results);
14476
14960
  try {
@@ -14568,6 +15052,7 @@ async function run(env2) {
14568
15052
  targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0,
14569
15053
  baselineFindings,
14570
15054
  vanishedTests,
15055
+ unsuppliedInputs,
14571
15056
  codegenLoop: codegenOut.loop,
14572
15057
  unresolved: failureReasons.length > 0 ? failureReasons : void 0
14573
15058
  });
@@ -14608,9 +15093,592 @@ async function runReadinessCheck(env2) {
14608
15093
  }
14609
15094
  }
14610
15095
 
15096
+ // src/scrubForModel.ts
15097
+ var REDACTION_WORDS = ["credential", "private_key", "cloud_key", "url_credentials", "assigned_secret"];
15098
+ function emptyRedactionCounts() {
15099
+ return { credential: 0, private_key: 0, cloud_key: 0, url_credentials: 0, assigned_secret: 0 };
15100
+ }
15101
+ function addRedactionCounts(into, more) {
15102
+ for (const word of REDACTION_WORDS) into[word] += more[word];
15103
+ }
15104
+ var NAMES = "password|passwd|pwd|secret|token|api[_-]?key|access_key|private_key|credential";
15105
+ var PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g;
15106
+ var CLOUD_KEYS = [
15107
+ /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
15108
+ /\bxox[abeprs]-[A-Za-z0-9-]{10,}/g,
15109
+ /\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g,
15110
+ /\bAIza[0-9A-Za-z_-]{35}/g
15111
+ ];
15112
+ var URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+:[^/\s@]+@/gi;
15113
+ var ASSIGNED_QUOTED = new RegExp(`((?<![\\w.-])[\\w.-]{0,40}(?:${NAMES})[\\w.-]{0,40}["']?\\s*[:=]\\s*)(["'])[^"'\\s]{8,}\\2`, "gi");
15114
+ var ASSIGNED_ENV = new RegExp(
15115
+ `^(\\s*(?:export\\s+)?[A-Z0-9_]*(?:${NAMES.toUpperCase().replace(/\[_-\]\?/g, "_?")})[A-Z0-9_]*[ \\t]*=[ \\t]*)(?!["'])\\S{8,}`,
15116
+ "gm"
15117
+ );
15118
+ function replaceCounting(text, pattern, replacement, onHit) {
15119
+ return text.replace(pattern, (...args) => {
15120
+ onHit();
15121
+ return typeof replacement === "function" ? replacement(...args) : replacement;
15122
+ });
15123
+ }
15124
+ function scrubForModel(input, secrets = []) {
15125
+ const counts = emptyRedactionCounts();
15126
+ let text = input;
15127
+ text = replaceCounting(text, PRIVATE_KEY, "***", () => counts.private_key += 1);
15128
+ for (const secret of secrets) {
15129
+ if (secret.length < MIN_SECRET_LENGTH) continue;
15130
+ const parts = text.split(secret);
15131
+ if (parts.length > 1) {
15132
+ counts.credential += parts.length - 1;
15133
+ text = parts.join("***");
15134
+ }
15135
+ }
15136
+ for (const pattern of CREDENTIAL_PATTERNS) text = replaceCounting(text, pattern, "***", () => counts.credential += 1);
15137
+ for (const pattern of CLOUD_KEYS) text = replaceCounting(text, pattern, "***", () => counts.cloud_key += 1);
15138
+ text = replaceCounting(text, URL_CREDENTIALS, (_all, scheme) => `${scheme}***@`, () => counts.url_credentials += 1);
15139
+ text = replaceCounting(text, ASSIGNED_QUOTED, (_all, name, quote) => `${name}${quote}***${quote}`, () => counts.assigned_secret += 1);
15140
+ text = replaceCounting(text, ASSIGNED_ENV, (_all, name) => `${name}***`, () => counts.assigned_secret += 1);
15141
+ return { text, counts };
15142
+ }
15143
+
15144
+ // src/investigateFindings.ts
15145
+ var VERDICTS = ["PRESENT", "NOT_PRESENT", "CANNOT_TELL", "NEW_BEHAVIOUR"];
15146
+ var ROLES = ["entry_point", "faulty_function", "caller", "helper", "test", "other"];
15147
+ var MAX_FILES2 = 12;
15148
+ var MAX_CALL_PATH = 10;
15149
+ var MAX_EVIDENCE = 8;
15150
+ var MAX_SEARCHES = 5;
15151
+ var MAX_OPEN_QUESTIONS = 3;
15152
+ var MAX_QUESTION_CHARS = 150;
15153
+ var MAX_SYMBOLS = 5;
15154
+ var MAX_SYMBOL_CHARS = 120;
15155
+ var MAX_SEARCH_CHARS = 60;
15156
+ var MAX_EVIDENCE_LINES = 200;
15157
+ var LINE = /^(\d+)\t(.*)$/;
15158
+ var EvidenceLedger = class {
15159
+ lines = /* @__PURE__ */ new Map();
15160
+ searchHit = /* @__PURE__ */ new Map();
15161
+ /** `content` is read_file's output: `<line number>\t<text>` per line, plus possibly a truncation notice (ignored). */
15162
+ recordRead(path, _startLine, content) {
15163
+ const seen = this.linesOf(path);
15164
+ for (const raw of content.split("\n")) {
15165
+ const m = LINE.exec(raw);
15166
+ if (m) seen.set(Number(m[1]), m[2]);
15167
+ }
15168
+ }
15169
+ recordHits(path, hits) {
15170
+ const seen = this.linesOf(path);
15171
+ for (const hit of hits) {
15172
+ if (Number.isInteger(hit.line) && hit.line >= 1 && !seen.has(hit.line)) seen.set(hit.line, hit.text);
15173
+ }
15174
+ }
15175
+ /** `zeroHit`: the search ran completely and found nothing. A search that EVER found something is never zero-hit. */
15176
+ recordSearch(pattern, zeroHit) {
15177
+ this.searchHit.set(pattern, (this.searchHit.get(pattern) ?? false) || !zeroHit);
15178
+ }
15179
+ hasLines(path, start, end) {
15180
+ const seen = this.lines.get(path);
15181
+ if (!seen) return false;
15182
+ for (let n = start; n <= end; n++) if (!seen.has(n)) return false;
15183
+ return true;
15184
+ }
15185
+ textContains(path, symbol) {
15186
+ const seen = this.lines.get(path);
15187
+ if (!seen) return false;
15188
+ for (const text of seen.values()) if (text.includes(symbol)) return true;
15189
+ return false;
15190
+ }
15191
+ zeroHit(pattern) {
15192
+ return this.searchHit.get(pattern) === false;
15193
+ }
15194
+ linesOf(path) {
15195
+ let seen = this.lines.get(path);
15196
+ if (!seen) {
15197
+ seen = /* @__PURE__ */ new Map();
15198
+ this.lines.set(path, seen);
15199
+ }
15200
+ return seen;
15201
+ }
15202
+ };
15203
+ function isRecord2(x) {
15204
+ return typeof x === "object" && x !== null && !Array.isArray(x);
15205
+ }
15206
+ function arrayOf(x) {
15207
+ return Array.isArray(x) ? x : [];
15208
+ }
15209
+ function emptyDropped() {
15210
+ return { files: 0, callPath: 0, evidence: 0, symbols: 0, searches: 0, questions: 0 };
15211
+ }
15212
+ function emptyFindings() {
15213
+ return { verdict: "CANNOT_TELL", files: [], callPath: [], evidence: [], searches: [], openQuestions: [] };
15214
+ }
15215
+ function isLine(n) {
15216
+ return typeof n === "number" && Number.isInteger(n) && n >= 1;
15217
+ }
15218
+ function verifyFindings(raw, ledger, ctx) {
15219
+ const dropped = emptyDropped();
15220
+ const redactions = emptyRedactionCounts();
15221
+ if (!isRecord2(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
15222
+ const pathOk2 = (p) => typeof p === "string" && ctx.listing.has(p) && matchesDeniedPath(p, ctx.deniedPaths) === null;
15223
+ const symbolsOf = (path, list2) => {
15224
+ const out = [];
15225
+ for (const s of arrayOf(list2)) {
15226
+ if (typeof s !== "string" || s.length === 0 || s.length > MAX_SYMBOL_CHARS || !ledger.textContains(path, s)) {
15227
+ dropped.symbols += 1;
15228
+ continue;
15229
+ }
15230
+ if (!out.includes(s) && out.length < MAX_SYMBOLS) out.push(s);
15231
+ }
15232
+ return out;
15233
+ };
15234
+ const files = [];
15235
+ for (const f of arrayOf(raw.files)) {
15236
+ if (!isRecord2(f) || !pathOk2(f.path)) {
15237
+ dropped.files += 1;
15238
+ continue;
15239
+ }
15240
+ if (files.length >= MAX_FILES2) continue;
15241
+ const role = ROLES.includes(f.role) ? f.role : "other";
15242
+ files.push({ path: f.path, role, symbols: symbolsOf(f.path, f.symbols) });
15243
+ }
15244
+ const callPath = [];
15245
+ for (const s of arrayOf(raw.callPath)) {
15246
+ const ok = isRecord2(s) && pathOk2(s.path) && typeof s.symbol === "string" && s.symbol.length > 0 && s.symbol.length <= MAX_SYMBOL_CHARS && isLine(s.line) && ledger.hasLines(s.path, s.line, s.line) && ledger.textContains(s.path, s.symbol);
15247
+ if (!ok) {
15248
+ dropped.callPath += 1;
15249
+ continue;
15250
+ }
15251
+ if (callPath.length < MAX_CALL_PATH) callPath.push({ path: s.path, symbol: s.symbol, line: s.line });
15252
+ }
15253
+ const evidence = [];
15254
+ for (const e of arrayOf(raw.evidence)) {
15255
+ const ok = isRecord2(e) && pathOk2(e.path) && isLine(e.startLine) && isLine(e.endLine) && e.startLine <= e.endLine && e.endLine - e.startLine + 1 <= MAX_EVIDENCE_LINES && ledger.hasLines(e.path, e.startLine, e.endLine);
15256
+ if (!ok) {
15257
+ dropped.evidence += 1;
15258
+ continue;
15259
+ }
15260
+ if (evidence.length < MAX_EVIDENCE) {
15261
+ evidence.push({ path: e.path, startLine: e.startLine, endLine: e.endLine, symbols: symbolsOf(e.path, e.symbols) });
15262
+ }
15263
+ }
15264
+ const searches = [];
15265
+ for (const s of arrayOf(raw.searches)) {
15266
+ if (typeof s !== "string" || s.length === 0 || s.length > MAX_SEARCH_CHARS || !ledger.zeroHit(s)) {
15267
+ dropped.searches += 1;
15268
+ continue;
15269
+ }
15270
+ if (!searches.includes(s) && searches.length < MAX_SEARCHES) searches.push(s);
15271
+ }
15272
+ const openQuestions = [];
15273
+ for (const q of arrayOf(raw.openQuestions)) {
15274
+ if (typeof q !== "string" || q.trim().length === 0) {
15275
+ dropped.questions += 1;
15276
+ continue;
15277
+ }
15278
+ if (openQuestions.length >= MAX_OPEN_QUESTIONS) continue;
15279
+ const scrubbed = scrubForModel(q.trim());
15280
+ addRedactionCounts(redactions, scrubbed.counts);
15281
+ openQuestions.push(scrubbed.text.slice(0, MAX_QUESTION_CHARS));
15282
+ }
15283
+ let verdict = VERDICTS.includes(raw.verdict) ? raw.verdict : "CANNOT_TELL";
15284
+ let downgraded = false;
15285
+ const supported = verdict === "PRESENT" ? evidence.length > 0 : verdict === "NOT_PRESENT" ? searches.length > 0 : verdict === "NEW_BEHAVIOUR" ? files.length > 0 || evidence.length > 0 : true;
15286
+ if (!supported) {
15287
+ verdict = "CANNOT_TELL";
15288
+ downgraded = true;
15289
+ }
15290
+ return { findings: { verdict, files, callPath, evidence, searches, openQuestions }, downgraded, dropped, redactions };
15291
+ }
15292
+
15293
+ // src/investigateLoop.ts
15294
+ var INVESTIGATE_CONTRACT_VERSION = "investigate-loop-1";
15295
+ var INVESTIGATE_LIMITS = {
15296
+ ...DEFAULT_LIMITS,
15297
+ maxTurns: 8,
15298
+ maxToolCalls: 20,
15299
+ readCharsPerRead: 12e3,
15300
+ readCharsTotal: 6e4,
15301
+ resultCharsTotal: 8e4
15302
+ };
15303
+ var InvestigateFailure = class extends Error {
15304
+ reason;
15305
+ /** What the loop had done when it failed. */
15306
+ summary;
15307
+ constructor(reason, cause) {
15308
+ super(`pilot.investigate failed: ${reason}`);
15309
+ this.name = "InvestigateFailure";
15310
+ this.reason = reason;
15311
+ if (cause !== void 0) this.cause = cause;
15312
+ }
15313
+ };
15314
+ var TOOL_NAMES3 = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
15315
+ var MAX_ID_CHARS4 = 64;
15316
+ var MAX_CALLS_IN_A_REPLY3 = 50;
15317
+ var MAX_ARGS_JSON_CHARS2 = 1e3;
15318
+ var SWITCH_OFF_SENTENCE = "is not enabled on this runtime";
15319
+ function isPlainObject4(x) {
15320
+ return typeof x === "object" && x !== null && !Array.isArray(x);
15321
+ }
15322
+ function safeArgs2(args) {
15323
+ try {
15324
+ return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS2 ? args : { _omitted: "too large" };
15325
+ } catch {
15326
+ return { _omitted: "unreadable" };
15327
+ }
15328
+ }
15329
+ function classifyTransport3(err) {
15330
+ if (err instanceof TargetingHttpError) return new InvestigateFailure("http_error", err);
15331
+ const name = err?.name;
15332
+ if (name === "TimeoutError" || name === "AbortError") return new InvestigateFailure("turn_timeout", err);
15333
+ return new InvestigateFailure("transport", err);
15334
+ }
15335
+ function classifyEnvelope(envelope) {
15336
+ const e = envelope;
15337
+ const code = typeof e?.errorCode === "string" ? e.errorCode : void 0;
15338
+ if (code === "RUN_BUDGET_EXCEEDED") return new InvestigateFailure("budget_exceeded");
15339
+ if (code === "RUN_CREDENTIAL_SCOPE") return new InvestigateFailure("credential_scope");
15340
+ if (code === "SEMANTIC_MISMATCH") return new InvestigateFailure("semantic_mismatch");
15341
+ if (code === "CONTRACT_REJECTED") {
15342
+ const text = `${typeof e?.error === "string" ? e.error : ""} ${typeof e?.normalizedText === "string" ? e.normalizedText : ""}`;
15343
+ return new InvestigateFailure(text.includes(SWITCH_OFF_SENTENCE) ? "switch_off" : "contract_rejected");
15344
+ }
15345
+ if (e?.success === false) return new InvestigateFailure("runtime_failed");
15346
+ return null;
15347
+ }
15348
+ function scrubResult(call, result, secrets, counts, ledger) {
15349
+ if (result.status !== "ok" || !isPlainObject4(result.output)) return null;
15350
+ const output = result.output;
15351
+ const args = isPlainObject4(call.args) ? call.args : {};
15352
+ if (call.name === "read_file" && typeof output.content === "string" && typeof output.path === "string") {
15353
+ const scrubbed = scrubForModel(output.content, secrets);
15354
+ addRedactionCounts(counts, scrubbed.counts);
15355
+ output.content = scrubbed.text;
15356
+ const path = output.path;
15357
+ const start = typeof output.startLine === "number" ? output.startLine : 1;
15358
+ return () => ledger.recordRead(path, start, scrubbed.text);
15359
+ }
15360
+ if (call.name === "grep" && Array.isArray(output.matches)) {
15361
+ const hitsByPath = /* @__PURE__ */ new Map();
15362
+ for (const m of output.matches) {
15363
+ if (typeof m.text !== "string" || typeof m.path !== "string" || typeof m.line !== "number") continue;
15364
+ const scrubbed = scrubForModel(m.text, secrets);
15365
+ addRedactionCounts(counts, scrubbed.counts);
15366
+ m.text = scrubbed.text;
15367
+ const list2 = hitsByPath.get(m.path) ?? [];
15368
+ list2.push({ line: m.line, text: scrubbed.text });
15369
+ hitsByPath.set(m.path, list2);
15370
+ }
15371
+ const complete = args.pathPrefix === void 0 && args.wholeWord !== true && output.scanCapped !== true;
15372
+ const pattern = typeof args.pattern === "string" ? args.pattern : null;
15373
+ const zero = output.matches.length === 0;
15374
+ return () => {
15375
+ for (const [path, hits] of hitsByPath) ledger.recordHits(path, hits);
15376
+ if (pattern !== null && complete) ledger.recordSearch(pattern, zero);
15377
+ };
15378
+ }
15379
+ return null;
15380
+ }
15381
+ async function runInvestigateLoop(args, deps) {
15382
+ const limits = { ...INVESTIGATE_LIMITS, ...deps.limits };
15383
+ const now = deps.now ?? Date.now;
15384
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
15385
+ const turnTimeoutMs = deps.turnTimeoutMs ?? 6e4;
15386
+ const deadlineMs = deps.deadlineMs ?? 12e4;
15387
+ const secrets = deps.secrets ?? [];
15388
+ const env2 = {
15389
+ listing: new Set(args.listing),
15390
+ visible: buildVisibleListing(args.listing, args.deniedPaths),
15391
+ deniedPaths: args.deniedPaths,
15392
+ fs: deps.fs ?? createNodeToolFs(),
15393
+ limits
15394
+ };
15395
+ const ledger = newLedger();
15396
+ const evidence = new EvidenceLedger();
15397
+ const reads = [];
15398
+ const transcript = [];
15399
+ const toolResults = [];
15400
+ const usedIds = /* @__PURE__ */ new Set();
15401
+ const redactions = emptyRedactionCounts();
15402
+ let turns = 0;
15403
+ let noProgressStreak = 0;
15404
+ let forced = null;
15405
+ const started = now();
15406
+ const buildContext = (turn, isFinal, finalReason) => ({
15407
+ contractVersion: INVESTIGATE_CONTRACT_VERSION,
15408
+ report: args.report,
15409
+ deniedPaths: args.deniedPaths,
15410
+ fileCount: args.listing.length,
15411
+ loop: {
15412
+ turn,
15413
+ maxTurns: limits.maxTurns,
15414
+ final: isFinal,
15415
+ ...isFinal ? { finalReason } : {},
15416
+ remaining: {
15417
+ toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
15418
+ readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
15419
+ },
15420
+ transcript,
15421
+ toolResults
15422
+ }
15423
+ });
15424
+ const snapshot = (stopReason) => ({
15425
+ turns,
15426
+ toolCalls: ledger.toolCalls,
15427
+ readChars: ledger.readChars,
15428
+ stopReason,
15429
+ redactions: { ...redactions },
15430
+ reads: [...reads]
15431
+ });
15432
+ log({ event: "investigate.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, files: args.listing.length });
15433
+ try {
15434
+ for (let turn = 1; turn <= limits.maxTurns; turn++) {
15435
+ turns = turn;
15436
+ if (now() - started > deadlineMs) throw new InvestigateFailure("loop_deadline");
15437
+ const isFinal = forced !== null || turn === limits.maxTurns;
15438
+ const finalReason = forced ?? "max_turns";
15439
+ const contextData = buildContext(turn, isFinal, finalReason);
15440
+ const requestTokens = estimateRequestTokens(contextData);
15441
+ if (requestTokens > limits.maxRequestTokens) {
15442
+ log({ event: "investigate.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
15443
+ throw new InvestigateFailure("token_ceiling");
15444
+ }
15445
+ const turnStarted = now();
15446
+ let envelope;
15447
+ try {
15448
+ envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
15449
+ } catch (err) {
15450
+ throw classifyTransport3(err);
15451
+ }
15452
+ const failed = classifyEnvelope(envelope);
15453
+ if (failed) throw failed;
15454
+ const body = envelope?.structuredJson;
15455
+ if (!isPlainObject4(body)) throw new InvestigateFailure("bad_reply");
15456
+ if (body.outcome === "FINDINGS") {
15457
+ log({ event: "investigate.loop_turn", turn, outcome: "final", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
15458
+ const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
15459
+ log({ event: "investigate.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, stopReason, redactions });
15460
+ return { raw: body, ledger: evidence, summary: snapshot(stopReason) };
15461
+ }
15462
+ if (body.outcome !== "TOOL_CALLS") throw new InvestigateFailure("bad_reply");
15463
+ if (isFinal) throw new InvestigateFailure("final_not_produced");
15464
+ const rawCalls = body.toolCalls;
15465
+ if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY3) throw new InvestigateFailure("bad_reply");
15466
+ const calls = [];
15467
+ for (const c of rawCalls) {
15468
+ if (!isPlainObject4(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS4 || typeof c.name !== "string") {
15469
+ throw new InvestigateFailure("bad_reply");
15470
+ }
15471
+ if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new InvestigateFailure("duplicate_call_ids");
15472
+ calls.push({ id: c.id, name: c.name, args: c.args });
15473
+ }
15474
+ for (const c of calls) usedIds.add(c.id);
15475
+ const results = [];
15476
+ const logged = [];
15477
+ const turnReads = [];
15478
+ const turnCounts = emptyRedactionCounts();
15479
+ const remember = [];
15480
+ const rememberAt = [];
15481
+ calls.forEach((call, index) => {
15482
+ let result;
15483
+ let read;
15484
+ if (index >= limits.maxCallsPerTurn) {
15485
+ 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." };
15486
+ } else {
15487
+ try {
15488
+ ({ result, read } = executeToolCall(call, env2, ledger));
15489
+ } catch (err) {
15490
+ throw new InvestigateFailure("executor_error", err);
15491
+ }
15492
+ }
15493
+ const keep = scrubResult(call, result, secrets, turnCounts, evidence);
15494
+ if (keep) {
15495
+ rememberAt[index] = remember.length;
15496
+ remember.push(keep);
15497
+ }
15498
+ results.push(result);
15499
+ turnReads[index] = read;
15500
+ if (read) reads.push(read);
15501
+ const tool = TOOL_NAMES3.has(call.name) ? call.name : "unknown";
15502
+ logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {} });
15503
+ });
15504
+ const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
15505
+ transcript.push({ turn, ...reasoning ? { reasoning } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs2(c.args) })) });
15506
+ toolResults.push(...results);
15507
+ noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
15508
+ if (noProgressStreak >= 2) forced = "no_progress";
15509
+ else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
15510
+ else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
15511
+ let delivered = true;
15512
+ const nextTurn = turn + 1;
15513
+ if (nextTurn <= limits.maxTurns) {
15514
+ const nextFinal = forced !== null || nextTurn === limits.maxTurns;
15515
+ const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
15516
+ if (projected > limits.maxRequestTokens) {
15517
+ delivered = false;
15518
+ results.forEach((r, idx) => {
15519
+ if (r.status !== "ok") return;
15520
+ toolResults[toolResults.indexOf(r)] = { id: r.id, name: r.name, status: "budget_exhausted", reason: "token_ceiling", message: "Too large to include; answer from what you have." };
15521
+ const dropped = turnReads[idx];
15522
+ if (dropped) {
15523
+ const at2 = reads.indexOf(dropped);
15524
+ if (at2 >= 0) reads.splice(at2, 1);
15525
+ }
15526
+ logged[idx].status = "budget_exhausted";
15527
+ logged[idx].reason = "token_ceiling";
15528
+ });
15529
+ forced = "read_budget";
15530
+ const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
15531
+ const fits = trimmed <= limits.maxRequestTokens;
15532
+ log({ event: "investigate.loop_ceiling", turn, action: fits ? "dropped_results" : "ended", projectedTokens: projected, ceiling: limits.maxRequestTokens });
15533
+ if (!fits) throw new InvestigateFailure("token_ceiling");
15534
+ }
15535
+ }
15536
+ if (delivered) {
15537
+ for (const keep of remember) keep();
15538
+ addRedactionCounts(redactions, turnCounts);
15539
+ }
15540
+ log({ event: "investigate.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
15541
+ }
15542
+ throw new InvestigateFailure("final_not_produced");
15543
+ } catch (err) {
15544
+ const failure = err instanceof InvestigateFailure ? err : new InvestigateFailure("internal_error", err);
15545
+ failure.summary ??= snapshot("failed");
15546
+ log({ event: "investigate.loop_failed", reason: failure.reason, turns, toolCalls: ledger.toolCalls });
15547
+ throw failure;
15548
+ }
15549
+ }
15550
+
15551
+ // src/investigate.ts
15552
+ var INVESTIGATE_EXTRA_DENIES = ["**/.npmrc", "**/*.pem", "**/*.key", "**/*.tfvars", "**/*credentials*.json", "**/docker-compose*"];
15553
+ function isStringList(x) {
15554
+ return Array.isArray(x) && x.every((s) => typeof s === "string");
15555
+ }
15556
+ async function fetchInvestigatePacket(packetUrl, runToken, githubRunId) {
15557
+ const res = await fetch(`${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`, { headers: { Authorization: `Bearer ${runToken}` } });
15558
+ if (!res.ok) throw new Error(`Fetch investigate packet failed: ${await describeQuikTrackFailure(res)}`);
15559
+ const body = await res.json();
15560
+ const data2 = body?.data;
15561
+ if (body?.success !== true || !data2) throw new Error("Fetch investigate packet failed: response did not carry success:true");
15562
+ const gateway = data2.gateway;
15563
+ if (typeof data2.report !== "string" || data2.report.length === 0 || !isStringList(data2.deniedPaths) || typeof gateway?.baseUrl !== "string" || typeof gateway?.token !== "string") {
15564
+ throw new Error("Fetch investigate packet failed: the packet is not the shape the runner expects");
15565
+ }
15566
+ return {
15567
+ report: data2.report,
15568
+ deniedPaths: data2.deniedPaths,
15569
+ workspaceRoot: typeof data2.workspaceRoot === "string" ? data2.workspaceRoot : null,
15570
+ gateway: { baseUrl: gateway.baseUrl, token: gateway.token }
15571
+ };
15572
+ }
15573
+ async function postInvestigate(gateway, contextData, signal) {
15574
+ const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
15575
+ method: "POST",
15576
+ headers: { "content-type": "application/json", "x-run-token": gateway.token },
15577
+ body: JSON.stringify({ appId: "quiktrack", useCase: "pilot.investigate", expectedOutputType: "json", userPrompt: "", contextData }),
15578
+ signal
15579
+ });
15580
+ if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
15581
+ return res.json();
15582
+ }
15583
+ async function reportInvestigation(callbackUrl, runToken, body) {
15584
+ const res = await fetch(callbackUrl, {
15585
+ method: "POST",
15586
+ headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
15587
+ body: JSON.stringify(body)
15588
+ });
15589
+ if (!res.ok) throw new Error(`Investigation callback failed: ${await describeQuikTrackFailure(res)}`);
15590
+ }
15591
+ function realDeps() {
15592
+ return {
15593
+ exchangeToken: async (tokenUrl) => exchangeForRunToken(tokenUrl, await fetchGithubOidcToken()),
15594
+ fetchPacket: fetchInvestigatePacket,
15595
+ listFiles: listWorkspaceFiles,
15596
+ runLoop: (args, deps) => runInvestigateLoop(args, deps),
15597
+ headCommit,
15598
+ report: reportInvestigation
15599
+ };
15600
+ }
15601
+ var StepFailure = class extends Error {
15602
+ constructor(reason) {
15603
+ super(reason);
15604
+ this.reason = reason;
15605
+ }
15606
+ reason;
15607
+ };
15608
+ function statsOf(summary) {
15609
+ return { turns: summary.turns, toolCalls: summary.toolCalls, readChars: summary.readChars, stopReason: summary.stopReason, redactions: { ...summary.redactions } };
15610
+ }
15611
+ async function runInvestigate(env2, deps = realDeps()) {
15612
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
15613
+ let runToken;
15614
+ try {
15615
+ runToken = await deps.exchangeToken(env2.tokenUrl);
15616
+ } catch {
15617
+ log({ event: "investigate.failed", reason: "token_failed" });
15618
+ return { hardFailure: true };
15619
+ }
15620
+ let body;
15621
+ try {
15622
+ body = await investigate(env2, runToken, deps, log);
15623
+ } catch (err) {
15624
+ const reason = err instanceof InvestigateFailure ? err.reason : err instanceof StepFailure ? err.reason : "internal_error";
15625
+ const stats = err instanceof InvestigateFailure && err.summary ? statsOf(err.summary) : void 0;
15626
+ log({ event: "investigate.failed", reason });
15627
+ body = { status: "failed", reason, ...stats ? { stats } : {} };
15628
+ }
15629
+ try {
15630
+ await deps.report(env2.callbackUrl, runToken, body);
15631
+ return { hardFailure: false };
15632
+ } catch {
15633
+ log({ event: "investigate.failed", reason: "report_failed" });
15634
+ return { hardFailure: true };
15635
+ }
15636
+ }
15637
+ async function investigate(env2, runToken, deps, log) {
15638
+ let packet;
15639
+ try {
15640
+ packet = await deps.fetchPacket(env2.packetUrl, runToken, env2.githubRunId);
15641
+ } catch {
15642
+ throw new StepFailure("packet_failed");
15643
+ }
15644
+ const listing = deps.listFiles(packet.workspaceRoot);
15645
+ if (listing.length === 0) throw new StepFailure("no_files");
15646
+ const deniedPaths = [...packet.deniedPaths, ...INVESTIGATE_EXTRA_DENIES];
15647
+ log({ event: "investigate.start", files: listing.length });
15648
+ const { raw, ledger, summary } = await deps.runLoop(
15649
+ { report: packet.report, deniedPaths, listing },
15650
+ {
15651
+ post: (contextData, signal) => postInvestigate(packet.gateway, contextData, signal),
15652
+ secrets: [runToken, packet.gateway.token],
15653
+ log
15654
+ }
15655
+ );
15656
+ const verified = verifyFindings(raw, ledger, { listing: new Set(listing), deniedPaths });
15657
+ const commit2 = deps.headCommit();
15658
+ const redactions = { ...summary.redactions };
15659
+ addRedactionCounts(redactions, verified.redactions);
15660
+ const { findings } = verified;
15661
+ log({
15662
+ event: "investigate.done",
15663
+ verdict: findings.verdict,
15664
+ files: findings.files.length,
15665
+ evidence: findings.evidence.length,
15666
+ openQuestions: findings.openQuestions.length,
15667
+ downgraded: verified.downgraded,
15668
+ dropped: verified.dropped,
15669
+ redactions
15670
+ });
15671
+ return {
15672
+ status: "completed",
15673
+ findings,
15674
+ commit: commit2,
15675
+ stats: { ...statsOf(summary), redactions, dropped: verified.dropped, downgraded: verified.downgraded }
15676
+ };
15677
+ }
15678
+
14611
15679
  // src/index.ts
14612
15680
  var env = readRunnerEnv();
14613
- var task = env.mode === "readiness_check" ? runReadinessCheck(env).then(() => ({ hardFailure: false })) : run(env);
15681
+ var task = env.mode === "readiness_check" ? runReadinessCheck(env).then(() => ({ hardFailure: false })) : env.mode === "investigate" ? runInvestigate(env) : run(env);
14614
15682
  task.then(({ hardFailure }) => {
14615
15683
  process.exitCode = hardFailure ? 1 : 0;
14616
15684
  }).catch((err) => {