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

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
  }
@@ -5557,7 +5574,7 @@ pp$8.parseClassElement = function(constructorAllowsSuper) {
5557
5574
  }
5558
5575
  var ecmaVersion2 = this.options.ecmaVersion;
5559
5576
  var node = this.startNode();
5560
- var keyName = "";
5577
+ var keyName2 = "";
5561
5578
  var isGenerator = false;
5562
5579
  var isAsync = false;
5563
5580
  var kind = "method";
@@ -5570,34 +5587,34 @@ pp$8.parseClassElement = function(constructorAllowsSuper) {
5570
5587
  if (this.isClassElementNameStart() || this.type === types$1.star) {
5571
5588
  isStatic = true;
5572
5589
  } else {
5573
- keyName = "static";
5590
+ keyName2 = "static";
5574
5591
  }
5575
5592
  }
5576
5593
  node.static = isStatic;
5577
- if (!keyName && ecmaVersion2 >= 8 && this.eatContextual("async")) {
5594
+ if (!keyName2 && ecmaVersion2 >= 8 && this.eatContextual("async")) {
5578
5595
  if ((this.isClassElementNameStart() || this.type === types$1.star) && !this.canInsertSemicolon()) {
5579
5596
  isAsync = true;
5580
5597
  } else {
5581
- keyName = "async";
5598
+ keyName2 = "async";
5582
5599
  }
5583
5600
  }
5584
- if (!keyName && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {
5601
+ if (!keyName2 && (ecmaVersion2 >= 9 || !isAsync) && this.eat(types$1.star)) {
5585
5602
  isGenerator = true;
5586
5603
  }
5587
- if (!keyName && !isAsync && !isGenerator) {
5604
+ if (!keyName2 && !isAsync && !isGenerator) {
5588
5605
  var lastValue = this.value;
5589
5606
  if (this.eatContextual("get") || this.eatContextual("set")) {
5590
5607
  if (this.isClassElementNameStart()) {
5591
5608
  kind = lastValue;
5592
5609
  } else {
5593
- keyName = lastValue;
5610
+ keyName2 = lastValue;
5594
5611
  }
5595
5612
  }
5596
5613
  }
5597
- if (keyName) {
5614
+ if (keyName2) {
5598
5615
  node.computed = false;
5599
5616
  node.key = this.startNodeAt(this.lastTokStart, this.lastTokStartLoc);
5600
- node.key.name = keyName;
5617
+ node.key.name = keyName2;
5601
5618
  this.finishNode(node.key, "Identifier");
5602
5619
  } else {
5603
5620
  this.parseClassElementName(node);
@@ -5999,11 +6016,11 @@ pp$8.parseWithClause = function() {
5999
6016
  first = false;
6000
6017
  }
6001
6018
  var attr = this.parseImportAttribute();
6002
- var keyName = attr.key.type === "Identifier" ? attr.key.name : attr.key.value;
6003
- if (hasOwn(attributeKeys, keyName)) {
6004
- 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 + "'");
6005
6022
  }
6006
- attributeKeys[keyName] = true;
6023
+ attributeKeys[keyName2] = true;
6007
6024
  nodes.push(attr);
6008
6025
  }
6009
6026
  return nodes;
@@ -12295,8 +12312,8 @@ async function reportToQuikTest(params) {
12295
12312
  try {
12296
12313
  console.log(`reporting ${report}`);
12297
12314
  const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
12298
- const { readFileSync: readFileSync11 } = await import("node:fs");
12299
- const body = readFileSync11(report);
12315
+ const { readFileSync: readFileSync12 } = await import("node:fs");
12316
+ const body = readFileSync12(report);
12300
12317
  let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
12301
12318
  if (generatedFiles) {
12302
12319
  url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
@@ -14031,7 +14048,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
14031
14048
  var REPORT_COPY = "final-test-report.xml";
14032
14049
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
14033
14050
  var MAX_FILES = 200;
14034
- var RUNNER_VERSION = true ? "9.3.0-rc.11" : "dev";
14051
+ var RUNNER_VERSION = true ? "9.3.0-rc.13" : "dev";
14035
14052
  function safeDestination(base, repoPath) {
14036
14053
  if (!repoPath || (0, import_node_path12.isAbsolute)(repoPath)) return null;
14037
14054
  const destination = (0, import_node_path12.resolve)(base, repoPath);
@@ -14564,6 +14581,215 @@ function describeVanishedTests(vanished) {
14564
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"}.`;
14565
14582
  }
14566
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
+
14567
14793
  // src/run.ts
14568
14794
  async function run(env2) {
14569
14795
  let hardFailure = false;
@@ -14585,6 +14811,7 @@ async function run(env2) {
14585
14811
  let targetingResult;
14586
14812
  let baselineFindings;
14587
14813
  let vanishedTests;
14814
+ let unsuppliedInputs;
14588
14815
  const contextLog = [];
14589
14816
  const codegenOut = {};
14590
14817
  try {
@@ -14617,6 +14844,9 @@ async function run(env2) {
14617
14844
  }
14618
14845
  }
14619
14846
  if (targeting.outcome === "NO_TARGET") {
14847
+ if (packet.issueKey !== null) {
14848
+ throw new Error(`QuikPilot found no file to change for this request \u2014 ${targeting.reason?.trim() || "no reason was given."}`);
14849
+ }
14620
14850
  writePhase0Marker(env2.runId);
14621
14851
  runCommand(packet.commands.setup, "Setup");
14622
14852
  runCommand(packet.commands.lint, "Lint");
@@ -14717,6 +14947,17 @@ async function run(env2) {
14717
14947
  console.error(message);
14718
14948
  warnings.push(message);
14719
14949
  }
14950
+ try {
14951
+ const unsupplied = checkGeneratedCode(results);
14952
+ if (unsupplied.length > 0) {
14953
+ unsuppliedInputs = unsupplied;
14954
+ const w = describeUnsuppliedInputs(unsupplied);
14955
+ warnings.push(w);
14956
+ console.warn(`QuikPilot code warning (not blocking): ${w}`);
14957
+ }
14958
+ } catch (err) {
14959
+ console.error(`Unsupplied-input check could not run (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14960
+ }
14720
14961
  generatedFilePaths = results.map((r) => r.targetPath);
14721
14962
  flushCodegenResults(results);
14722
14963
  try {
@@ -14814,6 +15055,7 @@ async function run(env2) {
14814
15055
  targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0,
14815
15056
  baselineFindings,
14816
15057
  vanishedTests,
15058
+ unsuppliedInputs,
14817
15059
  codegenLoop: codegenOut.loop,
14818
15060
  unresolved: failureReasons.length > 0 ? failureReasons : void 0
14819
15061
  });
@@ -14854,9 +15096,592 @@ async function runReadinessCheck(env2) {
14854
15096
  }
14855
15097
  }
14856
15098
 
15099
+ // src/scrubForModel.ts
15100
+ var REDACTION_WORDS = ["credential", "private_key", "cloud_key", "url_credentials", "assigned_secret"];
15101
+ function emptyRedactionCounts() {
15102
+ return { credential: 0, private_key: 0, cloud_key: 0, url_credentials: 0, assigned_secret: 0 };
15103
+ }
15104
+ function addRedactionCounts(into, more) {
15105
+ for (const word of REDACTION_WORDS) into[word] += more[word];
15106
+ }
15107
+ var NAMES = "password|passwd|pwd|secret|token|api[_-]?key|access_key|private_key|credential";
15108
+ var PRIVATE_KEY = /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/g;
15109
+ var CLOUD_KEYS = [
15110
+ /\b(?:AKIA|ASIA)[A-Z0-9]{16}\b/g,
15111
+ /\bxox[abeprs]-[A-Za-z0-9-]{10,}/g,
15112
+ /\b[sr]k_(?:live|test)_[A-Za-z0-9]{16,}/g,
15113
+ /\bAIza[0-9A-Za-z_-]{35}/g
15114
+ ];
15115
+ var URL_CREDENTIALS = /\b([a-z][a-z0-9+.-]*:\/\/)[^/\s:@]+:[^/\s@]+@/gi;
15116
+ var ASSIGNED_QUOTED = new RegExp(`((?<![\\w.-])[\\w.-]{0,40}(?:${NAMES})[\\w.-]{0,40}["']?\\s*[:=]\\s*)(["'])[^"'\\s]{8,}\\2`, "gi");
15117
+ var ASSIGNED_ENV = new RegExp(
15118
+ `^(\\s*(?:export\\s+)?[A-Z0-9_]*(?:${NAMES.toUpperCase().replace(/\[_-\]\?/g, "_?")})[A-Z0-9_]*[ \\t]*=[ \\t]*)(?!["'])\\S{8,}`,
15119
+ "gm"
15120
+ );
15121
+ function replaceCounting(text, pattern, replacement, onHit) {
15122
+ return text.replace(pattern, (...args) => {
15123
+ onHit();
15124
+ return typeof replacement === "function" ? replacement(...args) : replacement;
15125
+ });
15126
+ }
15127
+ function scrubForModel(input, secrets = []) {
15128
+ const counts = emptyRedactionCounts();
15129
+ let text = input;
15130
+ text = replaceCounting(text, PRIVATE_KEY, "***", () => counts.private_key += 1);
15131
+ for (const secret of secrets) {
15132
+ if (secret.length < MIN_SECRET_LENGTH) continue;
15133
+ const parts = text.split(secret);
15134
+ if (parts.length > 1) {
15135
+ counts.credential += parts.length - 1;
15136
+ text = parts.join("***");
15137
+ }
15138
+ }
15139
+ for (const pattern of CREDENTIAL_PATTERNS) text = replaceCounting(text, pattern, "***", () => counts.credential += 1);
15140
+ for (const pattern of CLOUD_KEYS) text = replaceCounting(text, pattern, "***", () => counts.cloud_key += 1);
15141
+ text = replaceCounting(text, URL_CREDENTIALS, (_all, scheme) => `${scheme}***@`, () => counts.url_credentials += 1);
15142
+ text = replaceCounting(text, ASSIGNED_QUOTED, (_all, name, quote) => `${name}${quote}***${quote}`, () => counts.assigned_secret += 1);
15143
+ text = replaceCounting(text, ASSIGNED_ENV, (_all, name) => `${name}***`, () => counts.assigned_secret += 1);
15144
+ return { text, counts };
15145
+ }
15146
+
15147
+ // src/investigateFindings.ts
15148
+ var VERDICTS = ["PRESENT", "NOT_PRESENT", "CANNOT_TELL", "NEW_BEHAVIOUR"];
15149
+ var ROLES = ["entry_point", "faulty_function", "caller", "helper", "test", "other"];
15150
+ var MAX_FILES2 = 12;
15151
+ var MAX_CALL_PATH = 10;
15152
+ var MAX_EVIDENCE = 8;
15153
+ var MAX_SEARCHES = 5;
15154
+ var MAX_OPEN_QUESTIONS = 3;
15155
+ var MAX_QUESTION_CHARS = 150;
15156
+ var MAX_SYMBOLS = 5;
15157
+ var MAX_SYMBOL_CHARS = 120;
15158
+ var MAX_SEARCH_CHARS = 60;
15159
+ var MAX_EVIDENCE_LINES = 200;
15160
+ var LINE = /^(\d+)\t(.*)$/;
15161
+ var EvidenceLedger = class {
15162
+ lines = /* @__PURE__ */ new Map();
15163
+ searchHit = /* @__PURE__ */ new Map();
15164
+ /** `content` is read_file's output: `<line number>\t<text>` per line, plus possibly a truncation notice (ignored). */
15165
+ recordRead(path, _startLine, content) {
15166
+ const seen = this.linesOf(path);
15167
+ for (const raw of content.split("\n")) {
15168
+ const m = LINE.exec(raw);
15169
+ if (m) seen.set(Number(m[1]), m[2]);
15170
+ }
15171
+ }
15172
+ recordHits(path, hits) {
15173
+ const seen = this.linesOf(path);
15174
+ for (const hit of hits) {
15175
+ if (Number.isInteger(hit.line) && hit.line >= 1 && !seen.has(hit.line)) seen.set(hit.line, hit.text);
15176
+ }
15177
+ }
15178
+ /** `zeroHit`: the search ran completely and found nothing. A search that EVER found something is never zero-hit. */
15179
+ recordSearch(pattern, zeroHit) {
15180
+ this.searchHit.set(pattern, (this.searchHit.get(pattern) ?? false) || !zeroHit);
15181
+ }
15182
+ hasLines(path, start, end) {
15183
+ const seen = this.lines.get(path);
15184
+ if (!seen) return false;
15185
+ for (let n = start; n <= end; n++) if (!seen.has(n)) return false;
15186
+ return true;
15187
+ }
15188
+ textContains(path, symbol) {
15189
+ const seen = this.lines.get(path);
15190
+ if (!seen) return false;
15191
+ for (const text of seen.values()) if (text.includes(symbol)) return true;
15192
+ return false;
15193
+ }
15194
+ zeroHit(pattern) {
15195
+ return this.searchHit.get(pattern) === false;
15196
+ }
15197
+ linesOf(path) {
15198
+ let seen = this.lines.get(path);
15199
+ if (!seen) {
15200
+ seen = /* @__PURE__ */ new Map();
15201
+ this.lines.set(path, seen);
15202
+ }
15203
+ return seen;
15204
+ }
15205
+ };
15206
+ function isRecord2(x) {
15207
+ return typeof x === "object" && x !== null && !Array.isArray(x);
15208
+ }
15209
+ function arrayOf(x) {
15210
+ return Array.isArray(x) ? x : [];
15211
+ }
15212
+ function emptyDropped() {
15213
+ return { files: 0, callPath: 0, evidence: 0, symbols: 0, searches: 0, questions: 0 };
15214
+ }
15215
+ function emptyFindings() {
15216
+ return { verdict: "CANNOT_TELL", files: [], callPath: [], evidence: [], searches: [], openQuestions: [] };
15217
+ }
15218
+ function isLine(n) {
15219
+ return typeof n === "number" && Number.isInteger(n) && n >= 1;
15220
+ }
15221
+ function verifyFindings(raw, ledger, ctx) {
15222
+ const dropped = emptyDropped();
15223
+ const redactions = emptyRedactionCounts();
15224
+ if (!isRecord2(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
15225
+ const pathOk2 = (p) => typeof p === "string" && ctx.listing.has(p) && matchesDeniedPath(p, ctx.deniedPaths) === null;
15226
+ const symbolsOf = (path, list2) => {
15227
+ const out = [];
15228
+ for (const s of arrayOf(list2)) {
15229
+ if (typeof s !== "string" || s.length === 0 || s.length > MAX_SYMBOL_CHARS || !ledger.textContains(path, s)) {
15230
+ dropped.symbols += 1;
15231
+ continue;
15232
+ }
15233
+ if (!out.includes(s) && out.length < MAX_SYMBOLS) out.push(s);
15234
+ }
15235
+ return out;
15236
+ };
15237
+ const files = [];
15238
+ for (const f of arrayOf(raw.files)) {
15239
+ if (!isRecord2(f) || !pathOk2(f.path)) {
15240
+ dropped.files += 1;
15241
+ continue;
15242
+ }
15243
+ if (files.length >= MAX_FILES2) continue;
15244
+ const role = ROLES.includes(f.role) ? f.role : "other";
15245
+ files.push({ path: f.path, role, symbols: symbolsOf(f.path, f.symbols) });
15246
+ }
15247
+ const callPath = [];
15248
+ for (const s of arrayOf(raw.callPath)) {
15249
+ 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);
15250
+ if (!ok) {
15251
+ dropped.callPath += 1;
15252
+ continue;
15253
+ }
15254
+ if (callPath.length < MAX_CALL_PATH) callPath.push({ path: s.path, symbol: s.symbol, line: s.line });
15255
+ }
15256
+ const evidence = [];
15257
+ for (const e of arrayOf(raw.evidence)) {
15258
+ 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);
15259
+ if (!ok) {
15260
+ dropped.evidence += 1;
15261
+ continue;
15262
+ }
15263
+ if (evidence.length < MAX_EVIDENCE) {
15264
+ evidence.push({ path: e.path, startLine: e.startLine, endLine: e.endLine, symbols: symbolsOf(e.path, e.symbols) });
15265
+ }
15266
+ }
15267
+ const searches = [];
15268
+ for (const s of arrayOf(raw.searches)) {
15269
+ if (typeof s !== "string" || s.length === 0 || s.length > MAX_SEARCH_CHARS || !ledger.zeroHit(s)) {
15270
+ dropped.searches += 1;
15271
+ continue;
15272
+ }
15273
+ if (!searches.includes(s) && searches.length < MAX_SEARCHES) searches.push(s);
15274
+ }
15275
+ const openQuestions = [];
15276
+ for (const q of arrayOf(raw.openQuestions)) {
15277
+ if (typeof q !== "string" || q.trim().length === 0) {
15278
+ dropped.questions += 1;
15279
+ continue;
15280
+ }
15281
+ if (openQuestions.length >= MAX_OPEN_QUESTIONS) continue;
15282
+ const scrubbed = scrubForModel(q.trim());
15283
+ addRedactionCounts(redactions, scrubbed.counts);
15284
+ openQuestions.push(scrubbed.text.slice(0, MAX_QUESTION_CHARS));
15285
+ }
15286
+ let verdict = VERDICTS.includes(raw.verdict) ? raw.verdict : "CANNOT_TELL";
15287
+ let downgraded = false;
15288
+ const supported = verdict === "PRESENT" ? evidence.length > 0 : verdict === "NOT_PRESENT" ? searches.length > 0 : verdict === "NEW_BEHAVIOUR" ? files.length > 0 || evidence.length > 0 : true;
15289
+ if (!supported) {
15290
+ verdict = "CANNOT_TELL";
15291
+ downgraded = true;
15292
+ }
15293
+ return { findings: { verdict, files, callPath, evidence, searches, openQuestions }, downgraded, dropped, redactions };
15294
+ }
15295
+
15296
+ // src/investigateLoop.ts
15297
+ var INVESTIGATE_CONTRACT_VERSION = "investigate-loop-1";
15298
+ var INVESTIGATE_LIMITS = {
15299
+ ...DEFAULT_LIMITS,
15300
+ maxTurns: 8,
15301
+ maxToolCalls: 20,
15302
+ readCharsPerRead: 12e3,
15303
+ readCharsTotal: 6e4,
15304
+ resultCharsTotal: 8e4
15305
+ };
15306
+ var InvestigateFailure = class extends Error {
15307
+ reason;
15308
+ /** What the loop had done when it failed. */
15309
+ summary;
15310
+ constructor(reason, cause) {
15311
+ super(`pilot.investigate failed: ${reason}`);
15312
+ this.name = "InvestigateFailure";
15313
+ this.reason = reason;
15314
+ if (cause !== void 0) this.cause = cause;
15315
+ }
15316
+ };
15317
+ var TOOL_NAMES3 = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
15318
+ var MAX_ID_CHARS4 = 64;
15319
+ var MAX_CALLS_IN_A_REPLY3 = 50;
15320
+ var MAX_ARGS_JSON_CHARS2 = 1e3;
15321
+ var SWITCH_OFF_SENTENCE = "is not enabled on this runtime";
15322
+ function isPlainObject4(x) {
15323
+ return typeof x === "object" && x !== null && !Array.isArray(x);
15324
+ }
15325
+ function safeArgs2(args) {
15326
+ try {
15327
+ return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS2 ? args : { _omitted: "too large" };
15328
+ } catch {
15329
+ return { _omitted: "unreadable" };
15330
+ }
15331
+ }
15332
+ function classifyTransport3(err) {
15333
+ if (err instanceof TargetingHttpError) return new InvestigateFailure("http_error", err);
15334
+ const name = err?.name;
15335
+ if (name === "TimeoutError" || name === "AbortError") return new InvestigateFailure("turn_timeout", err);
15336
+ return new InvestigateFailure("transport", err);
15337
+ }
15338
+ function classifyEnvelope(envelope) {
15339
+ const e = envelope;
15340
+ const code = typeof e?.errorCode === "string" ? e.errorCode : void 0;
15341
+ if (code === "RUN_BUDGET_EXCEEDED") return new InvestigateFailure("budget_exceeded");
15342
+ if (code === "RUN_CREDENTIAL_SCOPE") return new InvestigateFailure("credential_scope");
15343
+ if (code === "SEMANTIC_MISMATCH") return new InvestigateFailure("semantic_mismatch");
15344
+ if (code === "CONTRACT_REJECTED") {
15345
+ const text = `${typeof e?.error === "string" ? e.error : ""} ${typeof e?.normalizedText === "string" ? e.normalizedText : ""}`;
15346
+ return new InvestigateFailure(text.includes(SWITCH_OFF_SENTENCE) ? "switch_off" : "contract_rejected");
15347
+ }
15348
+ if (e?.success === false) return new InvestigateFailure("runtime_failed");
15349
+ return null;
15350
+ }
15351
+ function scrubResult(call, result, secrets, counts, ledger) {
15352
+ if (result.status !== "ok" || !isPlainObject4(result.output)) return null;
15353
+ const output = result.output;
15354
+ const args = isPlainObject4(call.args) ? call.args : {};
15355
+ if (call.name === "read_file" && typeof output.content === "string" && typeof output.path === "string") {
15356
+ const scrubbed = scrubForModel(output.content, secrets);
15357
+ addRedactionCounts(counts, scrubbed.counts);
15358
+ output.content = scrubbed.text;
15359
+ const path = output.path;
15360
+ const start = typeof output.startLine === "number" ? output.startLine : 1;
15361
+ return () => ledger.recordRead(path, start, scrubbed.text);
15362
+ }
15363
+ if (call.name === "grep" && Array.isArray(output.matches)) {
15364
+ const hitsByPath = /* @__PURE__ */ new Map();
15365
+ for (const m of output.matches) {
15366
+ if (typeof m.text !== "string" || typeof m.path !== "string" || typeof m.line !== "number") continue;
15367
+ const scrubbed = scrubForModel(m.text, secrets);
15368
+ addRedactionCounts(counts, scrubbed.counts);
15369
+ m.text = scrubbed.text;
15370
+ const list2 = hitsByPath.get(m.path) ?? [];
15371
+ list2.push({ line: m.line, text: scrubbed.text });
15372
+ hitsByPath.set(m.path, list2);
15373
+ }
15374
+ const complete = args.pathPrefix === void 0 && args.wholeWord !== true && output.scanCapped !== true;
15375
+ const pattern = typeof args.pattern === "string" ? args.pattern : null;
15376
+ const zero = output.matches.length === 0;
15377
+ return () => {
15378
+ for (const [path, hits] of hitsByPath) ledger.recordHits(path, hits);
15379
+ if (pattern !== null && complete) ledger.recordSearch(pattern, zero);
15380
+ };
15381
+ }
15382
+ return null;
15383
+ }
15384
+ async function runInvestigateLoop(args, deps) {
15385
+ const limits = { ...INVESTIGATE_LIMITS, ...deps.limits };
15386
+ const now = deps.now ?? Date.now;
15387
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
15388
+ const turnTimeoutMs = deps.turnTimeoutMs ?? 6e4;
15389
+ const deadlineMs = deps.deadlineMs ?? 12e4;
15390
+ const secrets = deps.secrets ?? [];
15391
+ const env2 = {
15392
+ listing: new Set(args.listing),
15393
+ visible: buildVisibleListing(args.listing, args.deniedPaths),
15394
+ deniedPaths: args.deniedPaths,
15395
+ fs: deps.fs ?? createNodeToolFs(),
15396
+ limits
15397
+ };
15398
+ const ledger = newLedger();
15399
+ const evidence = new EvidenceLedger();
15400
+ const reads = [];
15401
+ const transcript = [];
15402
+ const toolResults = [];
15403
+ const usedIds = /* @__PURE__ */ new Set();
15404
+ const redactions = emptyRedactionCounts();
15405
+ let turns = 0;
15406
+ let noProgressStreak = 0;
15407
+ let forced = null;
15408
+ const started = now();
15409
+ const buildContext = (turn, isFinal, finalReason) => ({
15410
+ contractVersion: INVESTIGATE_CONTRACT_VERSION,
15411
+ report: args.report,
15412
+ deniedPaths: args.deniedPaths,
15413
+ fileCount: args.listing.length,
15414
+ loop: {
15415
+ turn,
15416
+ maxTurns: limits.maxTurns,
15417
+ final: isFinal,
15418
+ ...isFinal ? { finalReason } : {},
15419
+ remaining: {
15420
+ toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
15421
+ readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
15422
+ },
15423
+ transcript,
15424
+ toolResults
15425
+ }
15426
+ });
15427
+ const snapshot = (stopReason) => ({
15428
+ turns,
15429
+ toolCalls: ledger.toolCalls,
15430
+ readChars: ledger.readChars,
15431
+ stopReason,
15432
+ redactions: { ...redactions },
15433
+ reads: [...reads]
15434
+ });
15435
+ log({ event: "investigate.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, files: args.listing.length });
15436
+ try {
15437
+ for (let turn = 1; turn <= limits.maxTurns; turn++) {
15438
+ turns = turn;
15439
+ if (now() - started > deadlineMs) throw new InvestigateFailure("loop_deadline");
15440
+ const isFinal = forced !== null || turn === limits.maxTurns;
15441
+ const finalReason = forced ?? "max_turns";
15442
+ const contextData = buildContext(turn, isFinal, finalReason);
15443
+ const requestTokens = estimateRequestTokens(contextData);
15444
+ if (requestTokens > limits.maxRequestTokens) {
15445
+ log({ event: "investigate.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
15446
+ throw new InvestigateFailure("token_ceiling");
15447
+ }
15448
+ const turnStarted = now();
15449
+ let envelope;
15450
+ try {
15451
+ envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
15452
+ } catch (err) {
15453
+ throw classifyTransport3(err);
15454
+ }
15455
+ const failed = classifyEnvelope(envelope);
15456
+ if (failed) throw failed;
15457
+ const body = envelope?.structuredJson;
15458
+ if (!isPlainObject4(body)) throw new InvestigateFailure("bad_reply");
15459
+ if (body.outcome === "FINDINGS") {
15460
+ log({ event: "investigate.loop_turn", turn, outcome: "final", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
15461
+ const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
15462
+ log({ event: "investigate.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, stopReason, redactions });
15463
+ return { raw: body, ledger: evidence, summary: snapshot(stopReason) };
15464
+ }
15465
+ if (body.outcome !== "TOOL_CALLS") throw new InvestigateFailure("bad_reply");
15466
+ if (isFinal) throw new InvestigateFailure("final_not_produced");
15467
+ const rawCalls = body.toolCalls;
15468
+ if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY3) throw new InvestigateFailure("bad_reply");
15469
+ const calls = [];
15470
+ for (const c of rawCalls) {
15471
+ if (!isPlainObject4(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS4 || typeof c.name !== "string") {
15472
+ throw new InvestigateFailure("bad_reply");
15473
+ }
15474
+ if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new InvestigateFailure("duplicate_call_ids");
15475
+ calls.push({ id: c.id, name: c.name, args: c.args });
15476
+ }
15477
+ for (const c of calls) usedIds.add(c.id);
15478
+ const results = [];
15479
+ const logged = [];
15480
+ const turnReads = [];
15481
+ const turnCounts = emptyRedactionCounts();
15482
+ const remember = [];
15483
+ const rememberAt = [];
15484
+ calls.forEach((call, index) => {
15485
+ let result;
15486
+ let read;
15487
+ if (index >= limits.maxCallsPerTurn) {
15488
+ 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." };
15489
+ } else {
15490
+ try {
15491
+ ({ result, read } = executeToolCall(call, env2, ledger));
15492
+ } catch (err) {
15493
+ throw new InvestigateFailure("executor_error", err);
15494
+ }
15495
+ }
15496
+ const keep = scrubResult(call, result, secrets, turnCounts, evidence);
15497
+ if (keep) {
15498
+ rememberAt[index] = remember.length;
15499
+ remember.push(keep);
15500
+ }
15501
+ results.push(result);
15502
+ turnReads[index] = read;
15503
+ if (read) reads.push(read);
15504
+ const tool = TOOL_NAMES3.has(call.name) ? call.name : "unknown";
15505
+ logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {} });
15506
+ });
15507
+ const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
15508
+ transcript.push({ turn, ...reasoning ? { reasoning } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs2(c.args) })) });
15509
+ toolResults.push(...results);
15510
+ noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
15511
+ if (noProgressStreak >= 2) forced = "no_progress";
15512
+ else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
15513
+ else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
15514
+ let delivered = true;
15515
+ const nextTurn = turn + 1;
15516
+ if (nextTurn <= limits.maxTurns) {
15517
+ const nextFinal = forced !== null || nextTurn === limits.maxTurns;
15518
+ const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
15519
+ if (projected > limits.maxRequestTokens) {
15520
+ delivered = false;
15521
+ results.forEach((r, idx) => {
15522
+ if (r.status !== "ok") return;
15523
+ 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." };
15524
+ const dropped = turnReads[idx];
15525
+ if (dropped) {
15526
+ const at2 = reads.indexOf(dropped);
15527
+ if (at2 >= 0) reads.splice(at2, 1);
15528
+ }
15529
+ logged[idx].status = "budget_exhausted";
15530
+ logged[idx].reason = "token_ceiling";
15531
+ });
15532
+ forced = "read_budget";
15533
+ const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
15534
+ const fits = trimmed <= limits.maxRequestTokens;
15535
+ log({ event: "investigate.loop_ceiling", turn, action: fits ? "dropped_results" : "ended", projectedTokens: projected, ceiling: limits.maxRequestTokens });
15536
+ if (!fits) throw new InvestigateFailure("token_ceiling");
15537
+ }
15538
+ }
15539
+ if (delivered) {
15540
+ for (const keep of remember) keep();
15541
+ addRedactionCounts(redactions, turnCounts);
15542
+ }
15543
+ log({ event: "investigate.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
15544
+ }
15545
+ throw new InvestigateFailure("final_not_produced");
15546
+ } catch (err) {
15547
+ const failure = err instanceof InvestigateFailure ? err : new InvestigateFailure("internal_error", err);
15548
+ failure.summary ??= snapshot("failed");
15549
+ log({ event: "investigate.loop_failed", reason: failure.reason, turns, toolCalls: ledger.toolCalls });
15550
+ throw failure;
15551
+ }
15552
+ }
15553
+
15554
+ // src/investigate.ts
15555
+ var INVESTIGATE_EXTRA_DENIES = ["**/.npmrc", "**/*.pem", "**/*.key", "**/*.tfvars", "**/*credentials*.json", "**/docker-compose*"];
15556
+ function isStringList(x) {
15557
+ return Array.isArray(x) && x.every((s) => typeof s === "string");
15558
+ }
15559
+ async function fetchInvestigatePacket(packetUrl, runToken, githubRunId) {
15560
+ const res = await fetch(`${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`, { headers: { Authorization: `Bearer ${runToken}` } });
15561
+ if (!res.ok) throw new Error(`Fetch investigate packet failed: ${await describeQuikTrackFailure(res)}`);
15562
+ const body = await res.json();
15563
+ const data2 = body?.data;
15564
+ if (body?.success !== true || !data2) throw new Error("Fetch investigate packet failed: response did not carry success:true");
15565
+ const gateway = data2.gateway;
15566
+ if (typeof data2.report !== "string" || data2.report.length === 0 || !isStringList(data2.deniedPaths) || typeof gateway?.baseUrl !== "string" || typeof gateway?.token !== "string") {
15567
+ throw new Error("Fetch investigate packet failed: the packet is not the shape the runner expects");
15568
+ }
15569
+ return {
15570
+ report: data2.report,
15571
+ deniedPaths: data2.deniedPaths,
15572
+ workspaceRoot: typeof data2.workspaceRoot === "string" ? data2.workspaceRoot : null,
15573
+ gateway: { baseUrl: gateway.baseUrl, token: gateway.token }
15574
+ };
15575
+ }
15576
+ async function postInvestigate(gateway, contextData, signal) {
15577
+ const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
15578
+ method: "POST",
15579
+ headers: { "content-type": "application/json", "x-run-token": gateway.token },
15580
+ body: JSON.stringify({ appId: "quiktrack", useCase: "pilot.investigate", expectedOutputType: "json", userPrompt: "", contextData }),
15581
+ signal
15582
+ });
15583
+ if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
15584
+ return res.json();
15585
+ }
15586
+ async function reportInvestigation(callbackUrl, runToken, body) {
15587
+ const res = await fetch(callbackUrl, {
15588
+ method: "POST",
15589
+ headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
15590
+ body: JSON.stringify(body)
15591
+ });
15592
+ if (!res.ok) throw new Error(`Investigation callback failed: ${await describeQuikTrackFailure(res)}`);
15593
+ }
15594
+ function realDeps() {
15595
+ return {
15596
+ exchangeToken: async (tokenUrl) => exchangeForRunToken(tokenUrl, await fetchGithubOidcToken()),
15597
+ fetchPacket: fetchInvestigatePacket,
15598
+ listFiles: listWorkspaceFiles,
15599
+ runLoop: (args, deps) => runInvestigateLoop(args, deps),
15600
+ headCommit,
15601
+ report: reportInvestigation
15602
+ };
15603
+ }
15604
+ var StepFailure = class extends Error {
15605
+ constructor(reason) {
15606
+ super(reason);
15607
+ this.reason = reason;
15608
+ }
15609
+ reason;
15610
+ };
15611
+ function statsOf(summary) {
15612
+ return { turns: summary.turns, toolCalls: summary.toolCalls, readChars: summary.readChars, stopReason: summary.stopReason, redactions: { ...summary.redactions } };
15613
+ }
15614
+ async function runInvestigate(env2, deps = realDeps()) {
15615
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
15616
+ let runToken;
15617
+ try {
15618
+ runToken = await deps.exchangeToken(env2.tokenUrl);
15619
+ } catch {
15620
+ log({ event: "investigate.failed", reason: "token_failed" });
15621
+ return { hardFailure: true };
15622
+ }
15623
+ let body;
15624
+ try {
15625
+ body = await investigate(env2, runToken, deps, log);
15626
+ } catch (err) {
15627
+ const reason = err instanceof InvestigateFailure ? err.reason : err instanceof StepFailure ? err.reason : "internal_error";
15628
+ const stats = err instanceof InvestigateFailure && err.summary ? statsOf(err.summary) : void 0;
15629
+ log({ event: "investigate.failed", reason });
15630
+ body = { status: "failed", reason, ...stats ? { stats } : {} };
15631
+ }
15632
+ try {
15633
+ await deps.report(env2.callbackUrl, runToken, body);
15634
+ return { hardFailure: false };
15635
+ } catch {
15636
+ log({ event: "investigate.failed", reason: "report_failed" });
15637
+ return { hardFailure: true };
15638
+ }
15639
+ }
15640
+ async function investigate(env2, runToken, deps, log) {
15641
+ let packet;
15642
+ try {
15643
+ packet = await deps.fetchPacket(env2.packetUrl, runToken, env2.githubRunId);
15644
+ } catch {
15645
+ throw new StepFailure("packet_failed");
15646
+ }
15647
+ const listing = deps.listFiles(packet.workspaceRoot);
15648
+ if (listing.length === 0) throw new StepFailure("no_files");
15649
+ const deniedPaths = [...packet.deniedPaths, ...INVESTIGATE_EXTRA_DENIES];
15650
+ log({ event: "investigate.start", files: listing.length });
15651
+ const { raw, ledger, summary } = await deps.runLoop(
15652
+ { report: packet.report, deniedPaths, listing },
15653
+ {
15654
+ post: (contextData, signal) => postInvestigate(packet.gateway, contextData, signal),
15655
+ secrets: [runToken, packet.gateway.token],
15656
+ log
15657
+ }
15658
+ );
15659
+ const verified = verifyFindings(raw, ledger, { listing: new Set(listing), deniedPaths });
15660
+ const commit2 = deps.headCommit();
15661
+ const redactions = { ...summary.redactions };
15662
+ addRedactionCounts(redactions, verified.redactions);
15663
+ const { findings } = verified;
15664
+ log({
15665
+ event: "investigate.done",
15666
+ verdict: findings.verdict,
15667
+ files: findings.files.length,
15668
+ evidence: findings.evidence.length,
15669
+ openQuestions: findings.openQuestions.length,
15670
+ downgraded: verified.downgraded,
15671
+ dropped: verified.dropped,
15672
+ redactions
15673
+ });
15674
+ return {
15675
+ status: "completed",
15676
+ findings,
15677
+ commit: commit2,
15678
+ stats: { ...statsOf(summary), redactions, dropped: verified.dropped, downgraded: verified.downgraded }
15679
+ };
15680
+ }
15681
+
14857
15682
  // src/index.ts
14858
15683
  var env = readRunnerEnv();
14859
- var task = env.mode === "readiness_check" ? runReadinessCheck(env).then(() => ({ hardFailure: false })) : run(env);
15684
+ var task = env.mode === "readiness_check" ? runReadinessCheck(env).then(() => ({ hardFailure: false })) : env.mode === "investigate" ? runInvestigate(env) : run(env);
14860
15685
  task.then(({ hardFailure }) => {
14861
15686
  process.exitCode = hardFailure ? 1 : 0;
14862
15687
  }).catch((err) => {