@quikit/quikpilot-runner 9.3.0-rc.14 → 9.3.0-rc.16

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
@@ -845,7 +845,7 @@ async function describeQuikTrackFailure(res) {
845
845
 
846
846
  // src/callback.ts
847
847
  async function reportBack(params) {
848
- const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, codegenLoop, unresolved } = params;
848
+ const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, codegenLoop, unresolved } = params;
849
849
  const body = { status };
850
850
  if (branch) body.branch = branch;
851
851
  if (warnings && warnings.length > 0) body.warnings = warnings;
@@ -854,6 +854,7 @@ async function reportBack(params) {
854
854
  if (baselineFindings) body.baselineFindings = baselineFindings;
855
855
  if (vanishedTests) body.vanishedTests = vanishedTests;
856
856
  if (unsuppliedInputs && unsuppliedInputs.length > 0) body.unsuppliedInputs = unsuppliedInputs;
857
+ if (changesNoTestDependsOn && changesNoTestDependsOn.hunks.length > 0) body.changesNoTestDependsOn = changesNoTestDependsOn;
857
858
  if (codegenLoop) body.codegenLoop = codegenLoop;
858
859
  const res = await fetch(callbackUrl, {
859
860
  method: "POST",
@@ -1579,8 +1580,8 @@ var TS_SIBLINGS = { ".js": [".ts", ".tsx"], ".jsx": [".tsx"], ".mjs": [".mts"],
1579
1580
  function resolveImport(fromPath, specifier, listing) {
1580
1581
  if (/^(?:@\/|~\/|#|\$|\/)/.test(specifier)) return { kind: "unresolved", reason: "alias" };
1581
1582
  const clean = specifier.replace(/[?#].*$/, "");
1582
- const relative8 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
1583
- if (!relative8) return { kind: "external" };
1583
+ const relative10 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
1584
+ if (!relative10) return { kind: "external" };
1584
1585
  const base = import_node_path.posix.normalize(import_node_path.posix.join(import_node_path.posix.dirname(fromPath), clean));
1585
1586
  if (base === ".." || base.startsWith("../") || import_node_path.posix.isAbsolute(base)) return { kind: "unresolved", reason: "not found" };
1586
1587
  const ext = import_node_path.posix.extname(base);
@@ -2311,6 +2312,24 @@ var MAX_RECORD_ATTEMPTS = 3;
2311
2312
  var MAX_ATTEMPT_COUNT = 1e3;
2312
2313
  var MAX_STATUS_KEYS = 20;
2313
2314
  var MAX_STATUS_KEY_CHARS = 40;
2315
+ var MAX_GATE_COUNT = 1e5;
2316
+ var HEAL_STOPS = /* @__PURE__ */ new Set(["passed", "no_progress", "limit", "out_of_time", "off", "not_eligible", "tree_not_restored", "heal_failed", "refused"]);
2317
+ var STARTED_BY = /* @__PURE__ */ new Set(["retry", "heal"]);
2318
+ var CHECKS = /* @__PURE__ */ new Set(["passed", "tests_failed", "failed_check"]);
2319
+ function gateCount(n) {
2320
+ return typeof n === "number" && Number.isInteger(n) && n >= 0 ? Math.min(MAX_GATE_COUNT, n) : 0;
2321
+ }
2322
+ function gateOf(g) {
2323
+ if (typeof g !== "object" || g === null || Array.isArray(g)) return void 0;
2324
+ const x = g;
2325
+ return {
2326
+ passed: gateCount(x.passed),
2327
+ failed: gateCount(x.failed),
2328
+ regressions: gateCount(x.regressions),
2329
+ newFailures: gateCount(x.newFailures),
2330
+ alreadyFailing: gateCount(x.alreadyFailing)
2331
+ };
2332
+ }
2314
2333
  function whole(n) {
2315
2334
  return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
2316
2335
  }
@@ -2395,14 +2414,26 @@ function buildCodegenLoopRecord(loop) {
2395
2414
  continue;
2396
2415
  }
2397
2416
  const reason = typeof a.reason === "string" ? a.reason.slice(0, MAX_STATUS_KEY_CHARS) : "";
2417
+ const gate = gateOf(a.gate);
2398
2418
  attempts.push({
2399
2419
  n: a.n,
2400
2420
  outcome: a.outcome.slice(0, MAX_STATUS_KEY_CHARS),
2401
2421
  ...reason.length > 0 ? { reason } : {},
2402
2422
  turns: small(a.turns),
2403
- toolCalls: small(a.toolCalls)
2423
+ toolCalls: small(a.toolCalls),
2424
+ ...a.startedBy && STARTED_BY.has(a.startedBy) ? { startedBy: a.startedBy } : {},
2425
+ ...a.checks && CHECKS.has(a.checks) ? { checks: a.checks } : {},
2426
+ ...gate ? { gate } : {}
2404
2427
  });
2405
2428
  }
2429
+ const healIn = loop.heal;
2430
+ const healed = healIn && typeof healIn.stop === "string" && HEAL_STOPS.has(healIn.stop) ? {
2431
+ stop: healIn.stop,
2432
+ allowed: Math.min(3, whole(healIn.allowed)),
2433
+ made: Math.min(3, whole(healIn.made)),
2434
+ ...gateOf(healIn.startedFrom) ? { startedFrom: gateOf(healIn.startedFrom) } : {},
2435
+ ...typeof healIn.failureReason === "string" && healIn.failureReason.length > 0 ? { failureReason: healIn.failureReason.slice(0, MAX_STATUS_KEY_CHARS) } : {}
2436
+ } : void 0;
2406
2437
  return {
2407
2438
  turns: whole(loop.turns),
2408
2439
  toolCalls: whole(loop.toolCalls),
@@ -2419,6 +2450,7 @@ function buildCodegenLoopRecord(loop) {
2419
2450
  ...testRuns.length > 0 ? { testRuns } : {},
2420
2451
  ...refused2.rows.length > 0 ? { refusedTurns: refused2.rows } : {},
2421
2452
  ...attempts.length > 0 ? { attempts } : {},
2453
+ ...healed ? { heal: healed } : {},
2422
2454
  reasoning,
2423
2455
  ...cut ? { truncated: true } : {}
2424
2456
  };
@@ -11743,6 +11775,12 @@ var CODEGEN_LIMITS = {
11743
11775
  function newCodegenLedger() {
11744
11776
  return { ...newLedger(), writeChars: 0 };
11745
11777
  }
11778
+ var SeedRefused = class extends Error {
11779
+ constructor() {
11780
+ super("The change kept from the earlier attempt could not be carried into this one.");
11781
+ this.name = "SeedRefused";
11782
+ }
11783
+ };
11746
11784
  function bad2(message) {
11747
11785
  return { fail: { status: "bad_args", message } };
11748
11786
  }
@@ -11787,6 +11825,19 @@ function createCodegenWorkspace(args) {
11787
11825
  if (key.startsWith("read_file:") || key.startsWith("grep:") || key.startsWith("list_files:")) ledger.seen.delete(key);
11788
11826
  }
11789
11827
  };
11828
+ for (const kept of args.seed ?? []) {
11829
+ const n = normaliseToolPath(kept.targetPath);
11830
+ if (!n.ok || matchesDeniedPath(n.path, args.deniedPaths)) throw new SeedRefused();
11831
+ if (baseFs.exists(n.path)) {
11832
+ const loaded = loadTextForEdit(baseFs, n.path, limits.fileBytesMax);
11833
+ if (!loaded.ok) throw new SeedRefused();
11834
+ const text = kept.newContent.charCodeAt(0) === 65279 ? kept.newContent.slice(1) : kept.newContent;
11835
+ overlay.setEdited(n.path, toLf(text), { ending: loaded.ending, bom: loaded.bom, originalLf: loaded.lf });
11836
+ } else {
11837
+ overlay.setCreated(n.path, toLf(kept.newContent));
11838
+ noteCreated(n.path);
11839
+ }
11840
+ }
11790
11841
  const gate = (raw, deniedPaths) => {
11791
11842
  const n = normaliseToolPath(raw);
11792
11843
  if (!n.ok) return { ok: false, fail: { status: "refused", reason: n.reason, message: "That path is not allowed." } };
@@ -12200,6 +12251,77 @@ function assertTreeUnchanged(root, before, watch, options = {}) {
12200
12251
  const differences = treeDifferences(before, now);
12201
12252
  if (differences.length > 0) throw new TreeNotRestoredError(differences);
12202
12253
  }
12254
+ function undoableFlush(root, results, flush, options = {}) {
12255
+ const ignore = new Set(options.ignore ?? []);
12256
+ const rels = results.map((r) => r.targetPath).filter((p) => safeRelativePath(p) !== null);
12257
+ const watch = [.../* @__PURE__ */ new Set([...rels, ...ignore])];
12258
+ const before = captureTree(root, watch, options);
12259
+ const beforePaths = new Set((before?.status ?? []).filter(isStatusEntry).map(entryPath));
12260
+ for (const p of ignore) beforePaths.add(p);
12261
+ const originals = rels.map((rel) => {
12262
+ const abs = (0, import_node_path7.resolve)(root, rel);
12263
+ let original = null;
12264
+ try {
12265
+ const st = (0, import_node_fs6.lstatSync)(abs);
12266
+ if (st.isFile() && !st.isSymbolicLink()) original = (0, import_node_fs6.readFileSync)(abs);
12267
+ } catch {
12268
+ original = null;
12269
+ }
12270
+ const createdDirs = [];
12271
+ if (original === null) {
12272
+ const missing = [];
12273
+ for (let d = (0, import_node_path7.dirname)(abs); !(0, import_node_fs6.existsSync)(d) && isInside(root, d); d = (0, import_node_path7.dirname)(d)) missing.push(d);
12274
+ createdDirs.push(...missing.reverse());
12275
+ }
12276
+ return { rel, abs, original, createdDirs };
12277
+ });
12278
+ const putFilesBack = () => {
12279
+ const failed = [];
12280
+ for (const o of [...originals].reverse()) {
12281
+ try {
12282
+ if (o.original !== null) (0, import_node_fs6.writeFileSync)(o.abs, o.original);
12283
+ else (0, import_node_fs6.rmSync)(o.abs, { force: true });
12284
+ for (const d of [...o.createdDirs].reverse()) {
12285
+ try {
12286
+ (0, import_node_fs6.rmdirSync)(d);
12287
+ } catch {
12288
+ }
12289
+ }
12290
+ } catch {
12291
+ failed.push(o.rel);
12292
+ }
12293
+ }
12294
+ return failed;
12295
+ };
12296
+ try {
12297
+ flush(results);
12298
+ } catch (err) {
12299
+ putFilesBack();
12300
+ throw err;
12301
+ }
12302
+ let done = false;
12303
+ return {
12304
+ undo() {
12305
+ if (done) return;
12306
+ if (before === null) throw new TreeUnverifiableError();
12307
+ const failed = putFilesBack();
12308
+ const differences = () => {
12309
+ const after = captureTree(root, watch, options);
12310
+ if (after === null) return ["(git could not report the checkout)"];
12311
+ return treeDifferences(before, after).filter((p) => !ignore.has(p));
12312
+ };
12313
+ let remaining = differences();
12314
+ if (remaining.length > 0) {
12315
+ const after = captureTree(root, watch, options);
12316
+ if (after !== null) cleanUpAfterRun(root, beforePaths, after.status);
12317
+ remaining = differences();
12318
+ }
12319
+ const bad3 = [.../* @__PURE__ */ new Set([...failed, ...remaining])].sort();
12320
+ if (bad3.length > 0) throw new TreeNotRestoredError(bad3);
12321
+ done = true;
12322
+ }
12323
+ };
12324
+ }
12203
12325
 
12204
12326
  // src/runTestsTool.ts
12205
12327
  var import_node_crypto2 = require("node:crypto");
@@ -12312,8 +12434,8 @@ async function reportToQuikTest(params) {
12312
12434
  try {
12313
12435
  console.log(`reporting ${report}`);
12314
12436
  const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
12315
- const { readFileSync: readFileSync12 } = await import("node:fs");
12316
- const body = readFileSync12(report);
12437
+ const { readFileSync: readFileSync13 } = await import("node:fs");
12438
+ const body = readFileSync13(report);
12317
12439
  let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
12318
12440
  if (generatedFiles) {
12319
12441
  url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
@@ -12578,6 +12700,56 @@ function versionOfFiles(files) {
12578
12700
  }
12579
12701
  return h.digest("hex");
12580
12702
  }
12703
+ function failingKeyOf(ordered, messages, failed) {
12704
+ const messageKey = Object.keys(messages).sort().map((k) => `${k}${messages[k]}`).join("");
12705
+ return failed > 0 ? sha(`${[...ordered].sort().join("\0")}${messageKey}`) : null;
12706
+ }
12707
+ function testAnswerFrom(args) {
12708
+ const after = args.after;
12709
+ let passed = 0;
12710
+ let failed = 0;
12711
+ for (const ok of after.results.values()) ok ? passed++ : failed++;
12712
+ let regressions;
12713
+ let newFailures;
12714
+ let alreadyFailing;
12715
+ let own = /* @__PURE__ */ new Set();
12716
+ let failureText = /* @__PURE__ */ new Map();
12717
+ if (args.baseline?.results) {
12718
+ const check = checkForRegressions(args.baseline, after);
12719
+ regressions = check.regressions;
12720
+ newFailures = check.newFailures;
12721
+ alreadyFailing = check.preExisting;
12722
+ own = ownFailureIds(newFailures, [...args.changedPaths], args.requiredIds);
12723
+ failureText = check.failureText;
12724
+ } else {
12725
+ regressions = [];
12726
+ newFailures = [...after.results.entries()].filter(([, ok]) => !ok).map(([id]) => id);
12727
+ alreadyFailing = [];
12728
+ }
12729
+ const ordered = [...regressions, ...newFailures, ...alreadyFailing];
12730
+ const listed = ordered.slice(0, MAX_LISTED_TESTS);
12731
+ const names = listed.map((n) => scrubSecrets(n).slice(0, MAX_TEST_NAME_CHARS));
12732
+ const messages = {};
12733
+ listed.forEach((id, i2) => {
12734
+ if (!own.has(id)) return;
12735
+ const line = firstLine(failureText.get(id) ?? "");
12736
+ if (line) messages[names[i2]] = line;
12737
+ });
12738
+ const messageCount = Object.keys(messages).length;
12739
+ const output = {
12740
+ passed,
12741
+ failed,
12742
+ total: passed + failed,
12743
+ regressions: regressions.length,
12744
+ newFailures: newFailures.length,
12745
+ alreadyFailing: alreadyFailing.length,
12746
+ failingTests: names,
12747
+ ...messageCount > 0 ? { messages } : {},
12748
+ timedOut: false,
12749
+ truncated: ordered.length > names.length
12750
+ };
12751
+ return { output, failingKey: failingKeyOf(ordered, messages, failed), messageCount };
12752
+ }
12581
12753
  var RunTestsTool = class {
12582
12754
  constructor(deps) {
12583
12755
  this.deps = deps;
@@ -12590,6 +12762,13 @@ var RunTestsTool = class {
12590
12762
  lastFailingKey = null;
12591
12763
  entries = [];
12592
12764
  maxRuns;
12765
+ /**
12766
+ * QUIKTR-1527: the overlay already holds a change the final checks were run on (a fix attempt's kept change), so a run before the AI has
12767
+ * changed anything would only repeat that result. Marks that version as seen; the first run waits for a real edit. Spends no run.
12768
+ */
12769
+ markSeen(version2) {
12770
+ this.lastVersion = version2;
12771
+ }
12593
12772
  /** What the runtime is told is left (`remaining.testRuns`): zero once the runs are used up or a no-progress stop has happened. */
12594
12773
  get runsLeft() {
12595
12774
  return this.locked ? 0 : Math.max(0, this.maxRuns - this.runs);
@@ -12704,53 +12883,15 @@ var RunTestsTool = class {
12704
12883
  this.lastFailingKey = null;
12705
12884
  return this.answer(callId, "no_report", { seconds });
12706
12885
  }
12707
- const after = ran.snapshot;
12708
- let passed = 0;
12709
- let failed = 0;
12710
- for (const ok of after.results.values()) ok ? passed++ : failed++;
12711
- let regressions;
12712
- let newFailures;
12713
- let alreadyFailing;
12714
- let own = /* @__PURE__ */ new Set();
12715
- let failureText = /* @__PURE__ */ new Map();
12716
- if (baseline?.snapshot.results) {
12717
- const check = checkForRegressions(baseline.snapshot, after);
12718
- regressions = check.regressions;
12719
- newFailures = check.newFailures;
12720
- alreadyFailing = check.preExisting;
12721
- own = ownFailureIds(newFailures, files.map((f) => f.path), d.requiredAutomationIds ?? []);
12722
- failureText = check.failureText;
12723
- } else {
12724
- regressions = [];
12725
- newFailures = [...after.results.entries()].filter(([, ok]) => !ok).map(([id]) => id);
12726
- alreadyFailing = [];
12727
- }
12728
- const ordered = [...regressions, ...newFailures, ...alreadyFailing];
12729
- const listed = ordered.slice(0, MAX_LISTED_TESTS);
12730
- const names = listed.map((n) => scrubSecrets(n).slice(0, MAX_TEST_NAME_CHARS));
12731
- const messages = {};
12732
- listed.forEach((id, i2) => {
12733
- if (!own.has(id)) return;
12734
- const line = firstLine(failureText.get(id) ?? "");
12735
- if (line) messages[names[i2]] = line;
12886
+ const { output, failingKey, messageCount } = testAnswerFrom({
12887
+ baseline: baseline?.snapshot ?? null,
12888
+ after: ran.snapshot,
12889
+ changedPaths: files.map((f) => f.path),
12890
+ requiredIds: d.requiredAutomationIds ?? []
12736
12891
  });
12737
- const messageCount = Object.keys(messages).length;
12738
- const output = {
12739
- passed,
12740
- failed,
12741
- total: passed + failed,
12742
- regressions: regressions.length,
12743
- newFailures: newFailures.length,
12744
- alreadyFailing: alreadyFailing.length,
12745
- failingTests: names,
12746
- ...messageCount > 0 ? { messages } : {},
12747
- timedOut: false,
12748
- truncated: ordered.length > names.length
12749
- };
12750
- const counts = { passed, failed, regressions: regressions.length, newFailures: newFailures.length, alreadyFailing: alreadyFailing.length };
12892
+ const { passed, failed } = output;
12893
+ const counts = { passed, failed, regressions: output.regressions, newFailures: output.newFailures, alreadyFailing: output.alreadyFailing };
12751
12894
  const green = failed === 0 && ran.run.outcome === "success";
12752
- const messageKey = Object.keys(messages).sort().map((k) => `${k}${messages[k]}`).join("");
12753
- const failingKey = failed > 0 ? sha(`${[...ordered].sort().join("\0")}${messageKey}`) : null;
12754
12895
  if (!green && failingKey !== null && failingKey === this.lastFailingKey) {
12755
12896
  this.locked = true;
12756
12897
  return this.answer(callId, "no_progress", { output, counts, seconds, messageCount });
@@ -13136,9 +13277,11 @@ async function runCodegenLoop(args, deps) {
13136
13277
  protectedTestPaths: args.protectedTestPaths,
13137
13278
  fs: deps.fs,
13138
13279
  limits: deps.limits,
13139
- syntaxSeed: args.syntaxSeed
13280
+ syntaxSeed: args.syntaxSeed,
13281
+ seed: args.seed
13140
13282
  });
13141
13283
  const { env: env2, ledger, overlay, limits } = ws;
13284
+ const seededText = new Map(overlay.changedPaths().map((p) => [p, overlay.get(p)?.lf]));
13142
13285
  const now = deps.now ?? Date.now;
13143
13286
  const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
13144
13287
  const filesOnDisk = () => overlay.results().map((r) => ({ path: r.targetPath, content: r.newContent }));
@@ -13151,6 +13294,7 @@ async function runCodegenLoop(args, deps) {
13151
13294
  log,
13152
13295
  now
13153
13296
  }) : null;
13297
+ if (tests && args.seed && args.seed.length > 0) tests.markSeen(versionOfFiles(filesOnDisk()));
13154
13298
  let testMs = 0;
13155
13299
  let lastTestAnswer;
13156
13300
  const pastHardStop = () => deps.hardStopAtMs !== void 0 && now() >= deps.hardStopAtMs;
@@ -13304,7 +13448,9 @@ async function runCodegenLoop(args, deps) {
13304
13448
  if (body.outcome === "DONE") {
13305
13449
  log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
13306
13450
  const changed = overlay.changedPaths();
13307
- if (changed.length === 0) throw new CodegenLoopFailure("no_writes");
13451
+ if (changed.length === 0 || changed.length === seededText.size && changed.every((p) => seededText.get(p) === overlay.get(p)?.lf)) {
13452
+ throw new CodegenLoopFailure("no_writes");
13453
+ }
13308
13454
  const texts = changed.map((p) => overlay.get(p)?.lf ?? "");
13309
13455
  const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
13310
13456
  if (missing.length > 0) {
@@ -13431,6 +13577,12 @@ function protectedTestFiles(listing, testDiscovery) {
13431
13577
  }
13432
13578
  return [...found].sort();
13433
13579
  }
13580
+ function claimedAutomationIds(p) {
13581
+ const skipped = new Set(p.skippedCases.map((s) => s.automationId));
13582
+ const claimed = /* @__PURE__ */ new Set();
13583
+ for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);
13584
+ return p.requiredTests.filter((tc) => claimed.has(tc.automationId)).map((tc) => tc.automationId);
13585
+ }
13434
13586
  function buildCodegenLoopArgs(p, context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} })) {
13435
13587
  const skipped = new Set(p.skippedCases.map((s) => s.automationId));
13436
13588
  const claimed = /* @__PURE__ */ new Set();
@@ -13602,267 +13754,542 @@ async function runCodegenStep(p) {
13602
13754
  throw lose(p, f2.summary, [firstRecord, failedAttempt(2, f2)], f2.reason === "out_of_time" ? "out_of_time" : "failed");
13603
13755
  }
13604
13756
 
13605
- // src/dependencyCheck.ts
13757
+ // src/codegenHeal.ts
13606
13758
  var import_node_fs10 = require("node:fs");
13607
- var import_node_path10 = require("node:path");
13608
- var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
13609
- var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
13610
- var NODE_BUILTINS = /* @__PURE__ */ new Set([
13611
- "assert",
13612
- "buffer",
13613
- "child_process",
13614
- "cluster",
13615
- "crypto",
13616
- "dgram",
13617
- "dns",
13618
- "domain",
13619
- "events",
13620
- "fs",
13621
- "http",
13622
- "http2",
13623
- "https",
13624
- "net",
13625
- "os",
13626
- "path",
13627
- "perf_hooks",
13628
- "process",
13629
- "punycode",
13630
- "querystring",
13631
- "readline",
13632
- "repl",
13633
- "stream",
13634
- "string_decoder",
13635
- "sys",
13636
- "timers",
13637
- "tls",
13638
- "tty",
13639
- "url",
13640
- "util",
13641
- "v8",
13642
- "vm",
13643
- "worker_threads",
13644
- "zlib",
13645
- "inspector",
13646
- "async_hooks"
13647
- ]);
13648
- var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
13649
- function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
13650
- if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
13651
- if (specifier.startsWith("node:")) return null;
13652
- if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
13653
- const segments = specifier.split("/");
13654
- const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
13655
- if (NODE_BUILTINS.has(name)) return null;
13656
- return name;
13657
- }
13658
- function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
13659
- const found = /* @__PURE__ */ new Set();
13660
- let match;
13661
- IMPORT_RE.lastIndex = 0;
13662
- while (match = IMPORT_RE.exec(source)) {
13663
- const name = packageNameFromSpecifier(match[2], aliasPrefixes);
13664
- if (name) found.add(name);
13665
- }
13666
- return [...found];
13759
+
13760
+ // src/heal.ts
13761
+ var MAX_ATTEMPTS_IN_ALL = 3;
13762
+ var MIN_HEAL_MS = 3 * 6e4;
13763
+ function healAllowance(setting, attemptsRun, healsRun, mode) {
13764
+ if (mode !== "loop-tests") return 0;
13765
+ if (typeof setting !== "number" || !Number.isFinite(setting) || setting <= 0) return 0;
13766
+ return Math.max(0, Math.min(Math.floor(setting) - healsRun, MAX_ATTEMPTS_IN_ALL - attemptsRun));
13767
+ }
13768
+ function isHealable(stage, check, bothSnapshotsReadable) {
13769
+ if (stage !== "gate" || !check || !bothSnapshotsReadable) return false;
13770
+ return check.blocked && check.regressions.length + check.newFailures.length > 0;
13771
+ }
13772
+ function decideHeal(i2) {
13773
+ if (i2.mode !== "loop-tests" || !(typeof i2.setting === "number" && Number.isFinite(i2.setting) && i2.setting > 0)) return { heal: false, stop: "off" };
13774
+ if (healAllowance(i2.setting, i2.attemptsRun, i2.healsRun, i2.mode) <= 0) return { heal: false, stop: "limit" };
13775
+ if (!isHealable(i2.stage, i2.check, i2.bothSnapshotsReadable)) return { heal: false, stop: "not_eligible" };
13776
+ if (i2.failingKey !== null && i2.failingKey === i2.lastFailingKey) return { heal: false, stop: "no_progress" };
13777
+ if (i2.leftMs < i2.neededMs) return { heal: false, stop: "out_of_time" };
13778
+ return { heal: true };
13779
+ }
13780
+ function healNeededMs(a) {
13781
+ return Math.max(a.attemptMs + a.gateMs, MIN_HEAL_MS);
13782
+ }
13783
+ function healPreviousAttempt(attempt2, answer) {
13784
+ const lastTestRun = testRunFrom(answer);
13785
+ return {
13786
+ attempt: attempt2,
13787
+ endedWith: "tests_failed",
13788
+ changesKept: true,
13789
+ ...lastTestRun ? { lastTestRun } : {}
13790
+ };
13667
13791
  }
13668
- function checkImportDependencies(results, declaredDependencies, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
13669
- if (!declaredDependencies) return { blocked: false, violations: [] };
13670
- const violations = [];
13671
- for (const { targetPath, newContent } of results) {
13672
- if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
13673
- const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
13674
- if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
13792
+
13793
+ // src/codegenHeal.ts
13794
+ async function runHealAttempt(i2) {
13795
+ const p = i2.step;
13796
+ const keptText = new Map(i2.results.map((r) => [r.targetPath, r.newContent]));
13797
+ const listed = new Set(p.workspaceListing);
13798
+ const created = i2.results.map((r) => r.targetPath).filter((path) => !listed.has(path));
13799
+ const workspaceListing = [...p.workspaceListing, ...created];
13800
+ const targets = p.targets.map((t) => t.kind === "NEW_FILE" && keptText.has(t.path) ? { ...t, kind: "EXISTING" } : t);
13801
+ const disk = p.readFile ?? ((path) => (0, import_node_fs10.readFileSync)(path, "utf8"));
13802
+ const readFile = (path) => keptText.get(path) ?? disk(path);
13803
+ const context = collectLoopContext({ targets, listing: workspaceListing, deniedPaths: p.deniedPaths, readFile });
13804
+ const original = buildCodegenLoopArgs(p, collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, readFile: disk }));
13805
+ const args = buildCodegenLoopArgs({ ...p, targets, workspaceListing }, context);
13806
+ args.protectedTestPaths = original.protectedTestPaths;
13807
+ if (original.baseContext.protectedTestPaths !== void 0) args.baseContext.protectedTestPaths = original.baseContext.protectedTestPaths;
13808
+ else delete args.baseContext.protectedTestPaths;
13809
+ const now = p.deps?.now ?? Date.now;
13810
+ try {
13811
+ const done = await runCodegenLoop(
13812
+ { ...args, seed: i2.results, previousAttempt: healPreviousAttempt(i2.attempt, i2.answer) },
13813
+ {
13814
+ post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
13815
+ ...p.deps,
13816
+ now,
13817
+ hardStopAtMs: i2.hardStopAtMs
13818
+ }
13819
+ );
13820
+ i2.out.summary = done.summary;
13821
+ return done.results;
13822
+ } catch (err) {
13823
+ if (err instanceof CodegenLoopFailure) {
13824
+ i2.out.failure = err;
13825
+ i2.out.summary = err.summary;
13826
+ }
13827
+ throw err;
13675
13828
  }
13676
- return { blocked: violations.length > 0, violations };
13677
13829
  }
13678
- function dependencyNames(pkg) {
13679
- return /* @__PURE__ */ new Set([
13680
- ...Object.keys(pkg.dependencies ?? {}),
13681
- ...Object.keys(pkg.devDependencies ?? {}),
13682
- ...Object.keys(pkg.peerDependencies ?? {})
13683
- ]);
13830
+
13831
+ // src/healLoop.ts
13832
+ function countsOf(answer) {
13833
+ return {
13834
+ passed: answer.passed,
13835
+ failed: answer.failed,
13836
+ regressions: answer.regressions,
13837
+ newFailures: answer.newFailures,
13838
+ alreadyFailing: answer.alreadyFailing
13839
+ };
13684
13840
  }
13685
- function readDeclaredDependencies(results, workspaceRoot) {
13686
- const packageJsonPath = (0, import_node_path10.join)((0, import_node_path10.resolve)(workspaceRoot ?? "."), "package.json");
13687
- const generated = results.find((r) => (0, import_node_path10.resolve)(r.targetPath) === packageJsonPath);
13688
- let raw;
13689
- if (generated) {
13690
- raw = generated.newContent;
13691
- } else {
13692
- try {
13693
- raw = (0, import_node_fs10.readFileSync)(packageJsonPath, "utf8");
13694
- } catch {
13695
- raw = null;
13841
+ async function runVerifyAndFix(p) {
13842
+ let results = p.firstResults;
13843
+ let attemptsRun = p.attemptsRun;
13844
+ let healsRun = 0;
13845
+ let lastFailingKey = null;
13846
+ let lastAttemptMs = p.lastAttemptMs;
13847
+ const attempts = [];
13848
+ const allowed = healAllowance(p.setting, attemptsRun, 0, p.mode);
13849
+ let startedFrom;
13850
+ const record = (stop, extra = {}) => ({
13851
+ stop,
13852
+ allowed,
13853
+ made: healsRun,
13854
+ attempts,
13855
+ ...startedFrom ? { startedFrom } : {},
13856
+ ...extra
13857
+ });
13858
+ for (; ; ) {
13859
+ const undoable = healAllowance(p.setting, attemptsRun, healsRun, p.mode) > 0;
13860
+ const v = await p.verify(results, undoable);
13861
+ if (healsRun > 0) {
13862
+ attempts.push({
13863
+ n: attemptsRun,
13864
+ startedBy: "heal",
13865
+ checks: v.ok ? "passed" : v.stage === "gate" ? "tests_failed" : "failed_check",
13866
+ ...!v.ok && v.answer ? { gate: countsOf(v.answer) } : {}
13867
+ });
13696
13868
  }
13697
- }
13698
- if (raw === null) return null;
13699
- try {
13700
- return dependencyNames(JSON.parse(raw));
13701
- } catch {
13702
- return null;
13703
- }
13704
- }
13705
- function stripJsonComments(text) {
13706
- let out = "";
13707
- let inString = false;
13708
- let inLineComment = false;
13709
- let inBlockComment = false;
13710
- for (let i2 = 0; i2 < text.length; i2++) {
13711
- const c = text[i2];
13712
- const next = text[i2 + 1];
13713
- if (inLineComment) {
13714
- if (c === "\n") {
13715
- inLineComment = false;
13716
- out += c;
13717
- }
13718
- continue;
13869
+ if (v.ok) return { outcome: v, results, ...healsRun > 0 ? { heal: record("passed") } : {} };
13870
+ const decision = decideHeal({
13871
+ mode: p.mode,
13872
+ setting: p.setting,
13873
+ attemptsRun,
13874
+ healsRun,
13875
+ stage: v.stage,
13876
+ check: v.check,
13877
+ bothSnapshotsReadable: v.bothSnapshotsReadable,
13878
+ failingKey: v.failingKey,
13879
+ lastFailingKey,
13880
+ leftMs: p.jobStopAtMs - p.now(),
13881
+ neededMs: healNeededMs({ attemptMs: lastAttemptMs, gateMs: v.gateMs })
13882
+ });
13883
+ if (!decision.heal) {
13884
+ p.log({ event: "heal.stop", stop: decision.stop, attemptsRun, healsRun });
13885
+ return { outcome: v, results, heal: record(decision.stop) };
13719
13886
  }
13720
- if (inBlockComment) {
13721
- if (c === "*" && next === "/") {
13722
- inBlockComment = false;
13723
- i2++;
13887
+ if (!v.answer) return { outcome: v, results, heal: record("not_eligible") };
13888
+ try {
13889
+ v.undo();
13890
+ } catch (err) {
13891
+ if (err instanceof TreeNotRestoredError || err instanceof TreeUnverifiableError) {
13892
+ p.onStop?.("tree_not_restored");
13724
13893
  }
13725
- continue;
13894
+ throw err;
13726
13895
  }
13727
- if (inString) {
13728
- out += c;
13729
- if (c === "\\") {
13730
- out += next;
13731
- i2++;
13732
- continue;
13896
+ if (healsRun === 0) startedFrom = countsOf(v.answer);
13897
+ lastFailingKey = v.failingKey;
13898
+ healsRun += 1;
13899
+ attemptsRun += 1;
13900
+ p.log({ event: "heal.start", attempt: attemptsRun, healsRun, ...countsOf(v.answer) });
13901
+ const startedAt = p.now();
13902
+ try {
13903
+ results = await p.heal({ results, answer: v.answer, attempt: attemptsRun - 1, hardStopAtMs: p.jobStopAtMs - v.gateMs });
13904
+ } catch (err) {
13905
+ if (err instanceof SafetyRefusalError) {
13906
+ p.onStop?.("refused");
13907
+ throw err;
13733
13908
  }
13734
- if (c === '"') inString = false;
13735
- continue;
13736
- }
13737
- if (c === '"') {
13738
- inString = true;
13739
- out += c;
13740
- continue;
13741
- }
13742
- if (c === "/" && next === "/") {
13743
- inLineComment = true;
13744
- i2++;
13745
- continue;
13746
- }
13747
- if (c === "/" && next === "*") {
13748
- inBlockComment = true;
13749
- i2++;
13750
- continue;
13909
+ if (err instanceof TreeNotRestoredError || err instanceof TreeUnverifiableError) {
13910
+ p.onStop?.("tree_not_restored");
13911
+ throw err;
13912
+ }
13913
+ if (err instanceof CodegenLoopFailure) {
13914
+ p.log({ event: "heal.failed", attempt: attemptsRun, reason: err.reason });
13915
+ return { outcome: v, results, heal: record("heal_failed", { failureReason: err.reason }) };
13916
+ }
13917
+ if (err instanceof SeedRefused) {
13918
+ p.log({ event: "heal.failed", attempt: attemptsRun, reason: "seed_refused" });
13919
+ return { outcome: v, results, heal: record("heal_failed", { failureReason: "seed_refused" }) };
13920
+ }
13921
+ throw err;
13751
13922
  }
13752
- out += c;
13923
+ lastAttemptMs = p.now() - startedAt;
13753
13924
  }
13754
- return out.replace(/,(\s*[}\]])/g, "$1");
13755
13925
  }
13756
- function resolveAliasPrefixes(results, workspaceRoot) {
13757
- const root = (0, import_node_path10.resolve)(workspaceRoot ?? ".");
13758
- for (const filename of ["tsconfig.json", "jsconfig.json"]) {
13759
- const configPath = (0, import_node_path10.join)(root, filename);
13760
- const generated = results.find((r) => (0, import_node_path10.resolve)(r.targetPath) === configPath);
13761
- let raw;
13762
- if (generated) {
13763
- raw = generated.newContent;
13926
+
13927
+ // src/hunkCheck.ts
13928
+ var import_node_child_process5 = require("node:child_process");
13929
+ var import_node_fs12 = require("node:fs");
13930
+ var import_node_path10 = require("node:path");
13931
+
13932
+ // src/lineDiff.ts
13933
+ var DEFAULT_MAX_LINES = 4e3;
13934
+ var DEFAULT_MAX_CELLS = 4e6;
13935
+ function diffHunks(oldLf, newLf, limits = {}) {
13936
+ const maxLines = limits.maxLines ?? DEFAULT_MAX_LINES;
13937
+ const maxCells = limits.maxCells ?? DEFAULT_MAX_CELLS;
13938
+ const a = oldLf.split("\n");
13939
+ const b = newLf.split("\n");
13940
+ if (a.length > maxLines || b.length > maxLines) return null;
13941
+ let prefix = 0;
13942
+ while (prefix < a.length && prefix < b.length && a[prefix] === b[prefix]) prefix++;
13943
+ let suffix = 0;
13944
+ while (suffix < a.length - prefix && suffix < b.length - prefix && a[a.length - 1 - suffix] === b[b.length - 1 - suffix]) suffix++;
13945
+ const am = a.slice(prefix, a.length - suffix);
13946
+ const bm = b.slice(prefix, b.length - suffix);
13947
+ if (am.length === 0 && bm.length === 0) return [];
13948
+ if ((am.length + 1) * (bm.length + 1) > maxCells) return null;
13949
+ const n = am.length;
13950
+ const m = bm.length;
13951
+ const width = m + 1;
13952
+ const table = new Uint32Array((n + 1) * width);
13953
+ for (let i3 = n - 1; i3 >= 0; i3--) {
13954
+ for (let j2 = m - 1; j2 >= 0; j2--) {
13955
+ table[i3 * width + j2] = am[i3] === bm[j2] ? table[(i3 + 1) * width + j2 + 1] + 1 : Math.max(table[(i3 + 1) * width + j2], table[i3 * width + j2 + 1]);
13956
+ }
13957
+ }
13958
+ const raw = [];
13959
+ let i2 = 0;
13960
+ let j = 0;
13961
+ let open = null;
13962
+ const close = () => {
13963
+ if (!open) return;
13964
+ raw.push({ oldStart: prefix + open.oi + 1, oldLen: i2 - open.oi, newStart: prefix + open.nj + 1, newLen: j - open.nj });
13965
+ open = null;
13966
+ };
13967
+ while (i2 < n && j < m) {
13968
+ if (am[i2] === bm[j]) {
13969
+ close();
13970
+ i2++;
13971
+ j++;
13764
13972
  } else {
13765
- try {
13766
- raw = (0, import_node_fs10.readFileSync)(configPath, "utf8");
13767
- } catch {
13768
- raw = null;
13769
- }
13770
- }
13771
- if (raw === null) continue;
13772
- try {
13773
- const parsed = JSON.parse(stripJsonComments(raw));
13774
- const paths = parsed.compilerOptions?.paths;
13775
- const fromConfig = paths && typeof paths === "object" ? Object.keys(paths).map((k) => k.endsWith("*") ? k.slice(0, -1) : k) : [];
13776
- return [.../* @__PURE__ */ new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];
13777
- } catch {
13778
- continue;
13973
+ open ??= { oi: i2, nj: j };
13974
+ if (table[(i2 + 1) * width + j] >= table[i2 * width + j + 1]) i2++;
13975
+ else j++;
13976
+ }
13977
+ }
13978
+ if (i2 < n || j < m) {
13979
+ open ??= { oi: i2, nj: j };
13980
+ i2 = n;
13981
+ j = m;
13982
+ }
13983
+ close();
13984
+ const merged = [];
13985
+ for (const h of raw) {
13986
+ const last = merged[merged.length - 1];
13987
+ if (last && h.oldStart - (last.oldStart + last.oldLen) <= 1) {
13988
+ last.oldLen = h.oldStart + h.oldLen - last.oldStart;
13989
+ last.newLen = h.newStart + h.newLen - last.newStart;
13990
+ } else {
13991
+ merged.push({ ...h });
13779
13992
  }
13780
13993
  }
13781
- return DEFAULT_ALIAS_PREFIXES;
13994
+ return merged;
13782
13995
  }
13783
- function describeDependencyViolations(check) {
13784
- return check.violations.map((v) => `${v.file} imports ${v.packages.join(", ")}, not a dependency of this repository`).join("; ");
13996
+ function revertHunk(oldLf, newLf, hunk) {
13997
+ const a = oldLf.split("\n");
13998
+ const b = newLf.split("\n");
13999
+ b.splice(hunk.newStart - 1, hunk.newLen, ...a.slice(hunk.oldStart - 1, hunk.oldStart - 1 + hunk.oldLen));
14000
+ return b.join("\n");
14001
+ }
14002
+ function lineCount(lf) {
14003
+ if (lf === "") return 0;
14004
+ const n = lf.split("\n").length;
14005
+ return lf.endsWith("\n") ? n - 1 : n;
14006
+ }
14007
+ function hunkLines(hunk, totalLines) {
14008
+ const last = Math.max(1, totalLines);
14009
+ const startLine = Math.min(last, Math.max(1, hunk.newStart));
14010
+ const endLine = hunk.newLen > 0 ? Math.min(last, Math.max(startLine, hunk.newStart + hunk.newLen - 1)) : startLine;
14011
+ return { startLine, endLine };
14012
+ }
14013
+ function isWhitespaceOnly(oldLf, newLf, hunk) {
14014
+ const strip = (lines) => lines.join("").replace(/\s+/g, "");
14015
+ const before = strip(oldLf.split("\n").slice(hunk.oldStart - 1, hunk.oldStart - 1 + hunk.oldLen));
14016
+ const after = strip(newLf.split("\n").slice(hunk.newStart - 1, hunk.newStart - 1 + hunk.newLen));
14017
+ return before === after;
13785
14018
  }
13786
14019
 
13787
- // src/guardrail.ts
13788
- function checkGuardrail(deniedPaths) {
13789
- addAll();
13790
- const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
13791
- if (violations.length > 0) {
13792
- throw new Error(`QuikPilot touched denied paths:
13793
- ${violations.join("\n")}`);
14020
+ // src/scopeCheck.ts
14021
+ var import_node_fs11 = require("node:fs");
14022
+ var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
14023
+ var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
14024
+ var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
14025
+ var NO_PATH = "(this file's route)";
14026
+ function detectMentions(text) {
14027
+ const found = [];
14028
+ for (const line of text.split("\n")) {
14029
+ const methodMatch = ROUTE_METHOD_RE.exec(line);
14030
+ const pathMatch = ROUTE_PATH_RE.exec(line);
14031
+ if (methodMatch && pathMatch) {
14032
+ found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0] });
14033
+ }
14034
+ const exportMatch = ROUTE_EXPORT_RE.exec(line);
14035
+ if (exportMatch) {
14036
+ found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
14037
+ }
13794
14038
  }
14039
+ return found;
13795
14040
  }
13796
-
13797
- // src/installationToken.ts
13798
- async function exchangeForInstallationToken(installationTokenUrl, runToken) {
13799
- const res = await fetch(installationTokenUrl, {
13800
- method: "POST",
13801
- headers: { Authorization: `Bearer ${runToken}` }
13802
- });
13803
- if (!res.ok) {
13804
- throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
13805
- }
13806
- const body = await res.json();
13807
- if (body.success !== true) {
13808
- throw new Error("Exchange installation token failed: response did not carry success:true");
14041
+ function normalizePath(path) {
14042
+ return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
14043
+ }
14044
+ function surfaceCovers(surface, mention) {
14045
+ if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
14046
+ if (mention.path === NO_PATH) return true;
14047
+ const declaredPath = normalizePath(surface);
14048
+ const mentionPath = normalizePath(mention.path);
14049
+ return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
14050
+ }
14051
+ function addedLines(before, after) {
14052
+ const beforeLines = new Set(before.split("\n"));
14053
+ return after.split("\n").filter((line) => !beforeLines.has(line)).join("\n");
14054
+ }
14055
+ var TEST_FILE_RES = [
14056
+ /(^|\/)(__tests__|__mocks__|tests?|specs?)\//i,
14057
+ /\.(test|spec)\.[^/.]+$/i,
14058
+ /(^|\/)test_[^/]+\.py$/i,
14059
+ /_test\.(py|go)$/i,
14060
+ /Tests?\.(java|kt|cs)$/
14061
+ ];
14062
+ function isTestFile(path) {
14063
+ return TEST_FILE_RES.some((re) => re.test(path));
14064
+ }
14065
+ function checkApiScope(results, targets, apiChanges) {
14066
+ const targetsByPath = new Map(targets.map((t) => [t.path, t]));
14067
+ const violations = [];
14068
+ for (const { targetPath, newContent } of results) {
14069
+ if (isTestFile(targetPath)) continue;
14070
+ const target = targetsByPath.get(targetPath);
14071
+ const isNewFile = target?.kind === "NEW_FILE";
14072
+ let scanned;
14073
+ if (isNewFile) {
14074
+ scanned = newContent;
14075
+ } else {
14076
+ let currentContent;
14077
+ try {
14078
+ currentContent = (0, import_node_fs11.readFileSync)(targetPath, "utf8");
14079
+ } catch {
14080
+ currentContent = "";
14081
+ }
14082
+ scanned = addedLines(currentContent, newContent);
14083
+ }
14084
+ for (const mention of detectMentions(scanned)) {
14085
+ if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
14086
+ violations.push({ file: targetPath, method: mention.method, path: mention.path });
14087
+ }
14088
+ }
13809
14089
  }
13810
- return body.data.token;
14090
+ return { blocked: violations.length > 0, violations };
14091
+ }
14092
+ function describeScopeViolations(check) {
14093
+ return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
13811
14094
  }
13812
14095
 
13813
- // src/oidc.ts
13814
- var QUIKPILOT_OIDC_AUDIENCE = "quiktrack-quikpilot";
13815
- async function fetchGithubOidcToken(env2 = process.env) {
13816
- const requestUrl = required(
13817
- "ACTIONS_ID_TOKEN_REQUEST_URL",
13818
- env2.ACTIONS_ID_TOKEN_REQUEST_URL
13819
- );
13820
- const requestToken = required(
13821
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
13822
- env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
13823
- );
13824
- const separator = requestUrl.includes("?") ? "&" : "?";
13825
- const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
13826
- const res = await fetch(url, {
13827
- headers: { Authorization: `Bearer ${requestToken}` }
13828
- });
13829
- if (!res.ok) {
13830
- throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
14096
+ // src/hunkCheck.ts
14097
+ var MAX_REPORTED_HUNKS = 20;
14098
+ function toFinding(r) {
14099
+ if (r.unnecessary.length === 0) return void 0;
14100
+ return { hunks: r.unnecessary.slice(0, MAX_REPORTED_HUNKS), total: r.unnecessary.length, checked: r.checked };
14101
+ }
14102
+ var DEFAULT_MAX_HUNKS = 8;
14103
+ var MAX_FILE_BYTES = 1e6;
14104
+ var FRESH_SLACK_MS2 = 2e3;
14105
+ var SAFETY_MS = 6e4;
14106
+ var CODE_EXTENSIONS = /\.(?:[cm]?[jt]sx?|py|go|java|rb|rs|cs|php|kt)$/i;
14107
+ function eligibleForHunkCheck(path) {
14108
+ return CODE_EXTENSIONS.test(path) && !isTestFile(path);
14109
+ }
14110
+ function collectHunkCheckFiles(results, root, readHead = readCommittedText) {
14111
+ const files = [];
14112
+ for (const r of results) {
14113
+ if (safeRelativePath(r.targetPath) === null || !eligibleForHunkCheck(r.targetPath)) continue;
14114
+ const raw = readHead(root, r.targetPath);
14115
+ if (raw === null) continue;
14116
+ files.push({ path: r.targetPath, originalLf: toLf(raw.charCodeAt(0) === 65279 ? raw.slice(1) : raw) });
13831
14117
  }
13832
- const body = await res.json();
13833
- if (!body.value) {
13834
- throw new Error("GitHub OIDC token response carried no value");
14118
+ return files;
14119
+ }
14120
+ function readCommittedText(root, path) {
14121
+ try {
14122
+ return (0, import_node_child_process5.execFileSync)("git", ["show", `HEAD:${path}`], { cwd: root, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 8 * 1024 * 1024 });
14123
+ } catch {
14124
+ return null;
13835
14125
  }
13836
- return body.value;
13837
14126
  }
13838
-
13839
- // src/packet.ts
13840
- async function fetchPacket(packetUrl, runToken, githubRunId) {
13841
- const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
13842
- const res = await fetch(url, {
13843
- headers: { Authorization: `Bearer ${runToken}` }
14127
+ async function runHunkCheck(input) {
14128
+ const now = input.now ?? Date.now;
14129
+ const log = input.log ?? (() => {
13844
14130
  });
13845
- if (!res.ok) {
13846
- throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
14131
+ const result = { unnecessary: [], checked: 0, total: 0, skipped: { whitespace: 0, tooBig: 0, cap: 0, time: 0, unknown: 0, files: 0 } };
14132
+ if (!input.baseline.results || input.baseline.results.size === 0) return { ...result, stopped: "no_baseline" };
14133
+ const limit = testTimeLimitMs(input.baselineMs);
14134
+ if (limit === "too_slow") return { ...result, stopped: "too_slow" };
14135
+ const perRunMs = input.baselineMs === null ? limit : Math.min(limit, Math.max(3e4, 2 * input.baselineMs));
14136
+ const fs = createNodeWriteFs(input.root);
14137
+ const candidates = [];
14138
+ for (const f of input.files) {
14139
+ const loaded = loadTextForEdit(fs, f.path, MAX_FILE_BYTES);
14140
+ if (!loaded.ok) {
14141
+ result.skipped.files += 1;
14142
+ continue;
14143
+ }
14144
+ const hunks = diffHunks(f.originalLf, loaded.lf, input.maxLines !== void 0 ? { maxLines: input.maxLines } : {});
14145
+ if (hunks === null) {
14146
+ result.skipped.tooBig += 1;
14147
+ continue;
14148
+ }
14149
+ const totalLines = lineCount(loaded.lf);
14150
+ for (const hunk of hunks) {
14151
+ if (isWhitespaceOnly(f.originalLf, loaded.lf, hunk)) {
14152
+ result.skipped.whitespace += 1;
14153
+ continue;
14154
+ }
14155
+ candidates.push({ file: f.path, ending: loaded.ending, bom: loaded.bom, originalLf: f.originalLf, currentLf: loaded.lf, hunk, totalLines });
14156
+ }
13847
14157
  }
13848
- const body = await res.json();
13849
- if (body.success !== true) {
13850
- throw new Error("Fetch work packet failed: response did not carry success:true");
14158
+ result.total = candidates.length;
14159
+ const findReport = input.findReport ?? findJUnitReport;
14160
+ const readSnapshot = input.readSnapshot ?? readTestSnapshot;
14161
+ const runCommand2 = input.runCommand ?? runTestCommandWithLimit;
14162
+ let slowestRunMs = input.baselineMs ?? 3e4;
14163
+ const runOnce = async (c) => {
14164
+ const reportBefore = findReport(input.root);
14165
+ const preserve = reportBefore ? [(0, import_node_path10.relative)(input.root, reportBefore).split("\\").join("/")] : [];
14166
+ const content = `${c.bom ? "\uFEFF" : ""}${fromLf(revertHunk(c.originalLf, c.currentLf, c.hunk), c.ending)}`;
14167
+ const startedWall = Date.now();
14168
+ const startedAt = now();
14169
+ try {
14170
+ const verdict = await withOverlayOnDisk(
14171
+ input.root,
14172
+ [{ path: c.file, content }],
14173
+ async () => {
14174
+ if (reportBefore) (0, import_node_fs12.rmSync)(reportBefore, { force: true });
14175
+ const run2 = await runCommand2(input.command, perRunMs, input.root);
14176
+ if (!run2.started || run2.timedOut) return "unknown";
14177
+ const report = findReport(input.root);
14178
+ if (!report) return "unknown";
14179
+ try {
14180
+ if ((0, import_node_fs12.statSync)(report).mtimeMs < startedWall - FRESH_SLACK_MS2) return "unknown";
14181
+ } catch {
14182
+ return "unknown";
14183
+ }
14184
+ const after = readSnapshot(run2.outcome, input.root);
14185
+ if (!after.results || after.results.size === 0) return "unknown";
14186
+ if (after.results.size < input.finalTestCount) return "needed";
14187
+ return checkForRegressions(input.baseline, after).blocked ? "needed" : "unneeded";
14188
+ },
14189
+ { ...input.tree, preserve }
14190
+ );
14191
+ slowestRunMs = Math.max(slowestRunMs, now() - startedAt);
14192
+ return verdict;
14193
+ } catch (err) {
14194
+ if (err instanceof DiskWriteRefused) return "unknown";
14195
+ throw err;
14196
+ }
14197
+ };
14198
+ const queue = candidates.slice(0, input.maxHunks ?? DEFAULT_MAX_HUNKS);
14199
+ result.skipped.cap = candidates.length - queue.length;
14200
+ let handled = 0;
14201
+ try {
14202
+ for (const c of queue) {
14203
+ if (now() + slowestRunMs + SAFETY_MS > input.deadlineAtMs) {
14204
+ result.stopped = "out_of_time";
14205
+ break;
14206
+ }
14207
+ handled += 1;
14208
+ result.checked += 1;
14209
+ let verdict = await runOnce(c);
14210
+ if (verdict === "unneeded") verdict = await runOnce(c);
14211
+ log({ event: "hunk_check.block", verdict });
14212
+ if (verdict === "unknown") result.skipped.unknown += 1;
14213
+ else if (verdict === "unneeded") {
14214
+ const { startLine, endLine } = hunkLines(c.hunk, c.totalLines);
14215
+ result.unnecessary.push({ file: c.file, startLine, endLine });
14216
+ }
14217
+ }
14218
+ } catch (err) {
14219
+ if (err instanceof TreeUnverifiableError) {
14220
+ result.checked -= 1;
14221
+ return { ...result, stopped: "tree_unverifiable" };
14222
+ }
14223
+ throw err;
13851
14224
  }
13852
- return body.data;
14225
+ result.skipped.time = queue.length - handled;
14226
+ result.unnecessary.sort((a, b) => a.file.localeCompare(b.file) || a.startLine - b.startLine);
14227
+ return result;
14228
+ }
14229
+ function describeHunkCheck(r) {
14230
+ const n = r.unnecessary.length;
14231
+ return `${n} ${n === 1 ? "change" : "changes"} QuikPilot made ${n === 1 ? "has" : "have"} no test that depends on ${n === 1 ? "it" : "them"} (checked ${r.checked} of ${r.total}). See "What QuikPilot noticed".`;
13853
14232
  }
13854
14233
 
13855
- // src/phase0.ts
13856
- var import_node_fs11 = require("node:fs");
13857
- function writePhase0Marker(runId) {
13858
- (0, import_node_fs11.mkdirSync)(".quikpilot", { recursive: true });
13859
- (0, import_node_fs11.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
13860
- `);
14234
+ // src/healRecord.ts
14235
+ var ZERO = {
14236
+ turns: 0,
14237
+ toolCalls: 0,
14238
+ refused: 0,
14239
+ stopReason: "model_done",
14240
+ reads: [],
14241
+ edits: [],
14242
+ created: [],
14243
+ statusCounts: {},
14244
+ syntaxWarnings: 0,
14245
+ reasoning: []
14246
+ };
14247
+ function mergeHealRecord(existing, heal, calls) {
14248
+ const last = [...calls].reverse().find((c) => c.summary)?.summary;
14249
+ const base = last ? buildCodegenLoopRecord(last) : existing ?? buildCodegenLoopRecord(ZERO);
14250
+ const before = existing ? existing.attempts ?? [{ n: 1, outcome: "finished", turns: existing.turns, toolCalls: existing.toolCalls }] : [];
14251
+ const attempts = before.map((a) => ({ ...a }));
14252
+ if (heal.made > 0 && attempts.length > 0) {
14253
+ const finalOne = attempts[attempts.length - 1];
14254
+ finalOne.checks = "tests_failed";
14255
+ if (heal.startedFrom) finalOne.gate = heal.startedFrom;
14256
+ }
14257
+ calls.forEach((call, i2) => {
14258
+ const n = before.length + i2 + 1;
14259
+ const counted = heal.attempts.find((a) => a.n === n);
14260
+ attempts.push({
14261
+ n,
14262
+ outcome: call.failureReason && !counted ? "failed" : "finished",
14263
+ ...call.failureReason && !counted ? { reason: call.failureReason } : {},
14264
+ turns: call.summary?.turns ?? 0,
14265
+ toolCalls: call.summary?.toolCalls ?? 0,
14266
+ startedBy: "heal",
14267
+ ...counted ? { checks: counted.checks, ...counted.gate ? { gate: counted.gate } : {} } : {}
14268
+ });
14269
+ });
14270
+ const extra = buildCodegenLoopRecord({ ...ZERO, ...attempts.length > 0 && heal.made > 0 ? { attempts } : {}, heal });
14271
+ const merged = { ...base };
14272
+ if (extra.attempts) merged.attempts = extra.attempts;
14273
+ else if (heal.made === 0) delete merged.attempts;
14274
+ if (extra.heal) merged.heal = extra.heal;
14275
+ return merged;
14276
+ }
14277
+ var STOP_WORDS = {
14278
+ no_progress: "the same tests kept failing in the same way",
14279
+ limit: "the limit of fix attempts was reached",
14280
+ out_of_time: "there was not enough time left for another attempt",
14281
+ heal_failed: "the fix attempt could not finish"
14282
+ };
14283
+ function healFailureSuffix(heal) {
14284
+ if (!heal || heal.made <= 0) return "";
14285
+ const times = heal.made === 1 ? "1 time" : `${heal.made} times`;
14286
+ const why = STOP_WORDS[heal.stop];
14287
+ return `; QuikPilot tried to fix it ${times}${why ? ` (stopped: ${why})` : ""}`;
13861
14288
  }
13862
14289
 
13863
14290
  // src/baselineCheck.ts
13864
- var import_node_child_process5 = require("node:child_process");
13865
- var import_node_fs12 = require("node:fs");
14291
+ var import_node_child_process6 = require("node:child_process");
14292
+ var import_node_fs13 = require("node:fs");
13866
14293
  var import_node_path11 = require("node:path");
13867
14294
  var BASELINE_CHECK_TIMEOUT_MS = 12e4;
13868
14295
  function shellQuote(value) {
@@ -13887,27 +14314,27 @@ function insideCheckout(cwd, path) {
13887
14314
  return rel === "" || rel.startsWith("..") || (0, import_node_path11.isAbsolute)(rel) ? null : abs;
13888
14315
  }
13889
14316
  function writeForCheck(abs, content) {
13890
- const original = (0, import_node_fs12.existsSync)(abs) ? (0, import_node_fs12.readFileSync)(abs) : null;
14317
+ const original = (0, import_node_fs13.existsSync)(abs) ? (0, import_node_fs13.readFileSync)(abs) : null;
13891
14318
  const createdDirs = [];
13892
14319
  if (original === null) {
13893
14320
  const missing = [];
13894
- for (let d = (0, import_node_path11.dirname)(abs); !(0, import_node_fs12.existsSync)(d); d = (0, import_node_path11.dirname)(d)) missing.push(d);
14321
+ for (let d = (0, import_node_path11.dirname)(abs); !(0, import_node_fs13.existsSync)(d); d = (0, import_node_path11.dirname)(d)) missing.push(d);
13895
14322
  for (const d of missing.reverse()) {
13896
- (0, import_node_fs12.mkdirSync)(d);
14323
+ (0, import_node_fs13.mkdirSync)(d);
13897
14324
  createdDirs.push(d);
13898
14325
  }
13899
14326
  }
13900
- (0, import_node_fs12.writeFileSync)(abs, content);
14327
+ (0, import_node_fs13.writeFileSync)(abs, content);
13901
14328
  return { abs, original, createdDirs };
13902
14329
  }
13903
14330
  function restore(written) {
13904
14331
  for (const file of [...written].reverse()) {
13905
14332
  try {
13906
- if (file.original !== null) (0, import_node_fs12.writeFileSync)(file.abs, file.original);
13907
- else (0, import_node_fs12.rmSync)(file.abs, { force: true });
14333
+ if (file.original !== null) (0, import_node_fs13.writeFileSync)(file.abs, file.original);
14334
+ else (0, import_node_fs13.rmSync)(file.abs, { force: true });
13908
14335
  for (const d of [...file.createdDirs].reverse()) {
13909
14336
  try {
13910
- (0, import_node_fs12.rmdirSync)(d);
14337
+ (0, import_node_fs13.rmdirSync)(d);
13911
14338
  } catch {
13912
14339
  }
13913
14340
  }
@@ -13918,7 +14345,7 @@ function restore(written) {
13918
14345
  }
13919
14346
  function untrackedFiles(cwd) {
13920
14347
  try {
13921
- const out = (0, import_node_child_process5.execFileSync)("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
14348
+ const out = (0, import_node_child_process6.execFileSync)("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
13922
14349
  cwd,
13923
14350
  encoding: "utf8",
13924
14351
  stdio: ["ignore", "pipe", "ignore"],
@@ -13931,7 +14358,7 @@ function untrackedFiles(cwd) {
13931
14358
  }
13932
14359
  var mtimeOf = (path) => {
13933
14360
  try {
13934
- return (0, import_node_fs12.statSync)(path).mtimeMs;
14361
+ return (0, import_node_fs13.statSync)(path).mtimeMs;
13935
14362
  } catch {
13936
14363
  return null;
13937
14364
  }
@@ -13945,7 +14372,7 @@ function decideCause(targets, results, cwd) {
13945
14372
  const abs = insideCheckout(cwd, t.path);
13946
14373
  if (next === void 0 || abs === null) return "ALREADY_TRUE";
13947
14374
  try {
13948
- if ((0, import_node_fs12.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
14375
+ if ((0, import_node_fs13.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
13949
14376
  } catch {
13950
14377
  return "ALREADY_TRUE";
13951
14378
  }
@@ -14021,7 +14448,7 @@ async function runBaselineCheck(params) {
14021
14448
  for (const file of untrackedAfter) {
14022
14449
  if (untrackedBefore.has(file)) continue;
14023
14450
  const abs = insideCheckout(cwd, file);
14024
- if (abs) (0, import_node_fs12.rmSync)(abs, { force: true });
14451
+ if (abs) (0, import_node_fs13.rmSync)(abs, { force: true });
14025
14452
  }
14026
14453
  }
14027
14454
  }
@@ -14041,791 +14468,1093 @@ async function runBaselineCheck(params) {
14041
14468
  }
14042
14469
  }
14043
14470
 
14044
- // src/failureArtifact.ts
14045
- var import_node_fs13 = require("node:fs");
14471
+ // src/dependencyCheck.ts
14472
+ var import_node_fs14 = require("node:fs");
14046
14473
  var import_node_path12 = require("node:path");
14047
- var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
14048
- var REPORT_COPY = "final-test-report.xml";
14049
- var MAX_REPORT_BYTES = 5 * 1024 * 1024;
14050
- var MAX_FILES = 200;
14051
- var RUNNER_VERSION = true ? "9.3.0-rc.14" : "dev";
14052
- function safeDestination(base, repoPath) {
14053
- if (!repoPath || (0, import_node_path12.isAbsolute)(repoPath)) return null;
14054
- const destination = (0, import_node_path12.resolve)(base, repoPath);
14055
- const rel = (0, import_node_path12.relative)(base, destination);
14056
- if (!rel || rel.startsWith("..") || (0, import_node_path12.isAbsolute)(rel)) return null;
14057
- return destination;
14474
+ var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
14475
+ var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
14476
+ var NODE_BUILTINS = /* @__PURE__ */ new Set([
14477
+ "assert",
14478
+ "buffer",
14479
+ "child_process",
14480
+ "cluster",
14481
+ "crypto",
14482
+ "dgram",
14483
+ "dns",
14484
+ "domain",
14485
+ "events",
14486
+ "fs",
14487
+ "http",
14488
+ "http2",
14489
+ "https",
14490
+ "net",
14491
+ "os",
14492
+ "path",
14493
+ "perf_hooks",
14494
+ "process",
14495
+ "punycode",
14496
+ "querystring",
14497
+ "readline",
14498
+ "repl",
14499
+ "stream",
14500
+ "string_decoder",
14501
+ "sys",
14502
+ "timers",
14503
+ "tls",
14504
+ "tty",
14505
+ "url",
14506
+ "util",
14507
+ "v8",
14508
+ "vm",
14509
+ "worker_threads",
14510
+ "zlib",
14511
+ "inspector",
14512
+ "async_hooks"
14513
+ ]);
14514
+ var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
14515
+ function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
14516
+ if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
14517
+ if (specifier.startsWith("node:")) return null;
14518
+ if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
14519
+ const segments = specifier.split("/");
14520
+ const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
14521
+ if (NODE_BUILTINS.has(name)) return null;
14522
+ return name;
14058
14523
  }
14059
- function writeFailureArtifact(input) {
14060
- if (input.results.length === 0) return { written: false };
14061
- try {
14062
- const base = (0, import_node_path12.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
14063
- (0, import_node_fs13.rmSync)(base, { recursive: true, force: true });
14064
- (0, import_node_fs13.mkdirSync)(base, { recursive: true });
14065
- const files = [];
14066
- const skipped = [];
14067
- for (const result of input.results) {
14068
- const destination = files.length < MAX_FILES ? safeDestination(base, result.targetPath) : null;
14069
- if (!destination) {
14070
- skipped.push(result.targetPath);
14071
- continue;
14072
- }
14073
- (0, import_node_fs13.mkdirSync)((0, import_node_path12.dirname)(destination), { recursive: true });
14074
- (0, import_node_fs13.writeFileSync)(destination, result.newContent);
14075
- files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
14076
- }
14077
- let testReport = "none";
14078
- if (input.testReport) {
14079
- if (input.testReport.byteLength > MAX_REPORT_BYTES) {
14080
- testReport = "too-large";
14081
- } else {
14082
- (0, import_node_fs13.writeFileSync)((0, import_node_path12.join)(base, REPORT_COPY), input.testReport);
14083
- testReport = "included";
14084
- }
14085
- }
14086
- const manifest = {
14087
- runId: input.runId,
14088
- issueKey: input.issueKey,
14089
- runnerVersion: RUNNER_VERSION,
14090
- generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
14091
- targets: input.targets.map((t) => ({
14092
- path: t.path,
14093
- kind: t.kind,
14094
- ...t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}
14095
- })),
14096
- files,
14097
- skipped,
14098
- testReport,
14099
- failureReasons: input.failureReasons
14100
- };
14101
- const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
14102
- (0, import_node_fs13.writeFileSync)((0, import_node_path12.join)(base, "manifest.json"), text);
14103
- return { written: (0, import_node_fs13.existsSync)((0, import_node_path12.join)(base, "manifest.json")) };
14104
- } catch (err) {
14105
- console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
14106
- return { written: false };
14524
+ function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
14525
+ const found = /* @__PURE__ */ new Set();
14526
+ let match;
14527
+ IMPORT_RE.lastIndex = 0;
14528
+ while (match = IMPORT_RE.exec(source)) {
14529
+ const name = packageNameFromSpecifier(match[2], aliasPrefixes);
14530
+ if (name) found.add(name);
14107
14531
  }
14532
+ return [...found];
14108
14533
  }
14109
-
14110
- // src/scopeCheck.ts
14111
- var import_node_fs14 = require("node:fs");
14112
- var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
14113
- var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
14114
- var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
14115
- var NO_PATH = "(this file's route)";
14116
- function detectMentions(text) {
14117
- const found = [];
14118
- for (const line of text.split("\n")) {
14119
- const methodMatch = ROUTE_METHOD_RE.exec(line);
14120
- const pathMatch = ROUTE_PATH_RE.exec(line);
14121
- if (methodMatch && pathMatch) {
14122
- found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0] });
14123
- }
14124
- const exportMatch = ROUTE_EXPORT_RE.exec(line);
14125
- if (exportMatch) {
14126
- found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
14127
- }
14534
+ function checkImportDependencies(results, declaredDependencies, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
14535
+ if (!declaredDependencies) return { blocked: false, violations: [] };
14536
+ const violations = [];
14537
+ for (const { targetPath, newContent } of results) {
14538
+ if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
14539
+ const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
14540
+ if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
14128
14541
  }
14129
- return found;
14130
- }
14131
- function normalizePath(path) {
14132
- return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
14542
+ return { blocked: violations.length > 0, violations };
14133
14543
  }
14134
- function surfaceCovers(surface, mention) {
14135
- if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
14136
- if (mention.path === NO_PATH) return true;
14137
- const declaredPath = normalizePath(surface);
14138
- const mentionPath = normalizePath(mention.path);
14139
- return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
14544
+ function dependencyNames(pkg) {
14545
+ return /* @__PURE__ */ new Set([
14546
+ ...Object.keys(pkg.dependencies ?? {}),
14547
+ ...Object.keys(pkg.devDependencies ?? {}),
14548
+ ...Object.keys(pkg.peerDependencies ?? {})
14549
+ ]);
14140
14550
  }
14141
- function addedLines(before, after) {
14142
- const beforeLines = new Set(before.split("\n"));
14143
- return after.split("\n").filter((line) => !beforeLines.has(line)).join("\n");
14551
+ function readDeclaredDependencies(results, workspaceRoot) {
14552
+ const packageJsonPath = (0, import_node_path12.join)((0, import_node_path12.resolve)(workspaceRoot ?? "."), "package.json");
14553
+ const generated = results.find((r) => (0, import_node_path12.resolve)(r.targetPath) === packageJsonPath);
14554
+ let raw;
14555
+ if (generated) {
14556
+ raw = generated.newContent;
14557
+ } else {
14558
+ try {
14559
+ raw = (0, import_node_fs14.readFileSync)(packageJsonPath, "utf8");
14560
+ } catch {
14561
+ raw = null;
14562
+ }
14563
+ }
14564
+ if (raw === null) return null;
14565
+ try {
14566
+ return dependencyNames(JSON.parse(raw));
14567
+ } catch {
14568
+ return null;
14569
+ }
14144
14570
  }
14145
- var TEST_FILE_RES = [
14146
- /(^|\/)(__tests__|__mocks__|tests?|specs?)\//i,
14147
- /\.(test|spec)\.[^/.]+$/i,
14148
- /(^|\/)test_[^/]+\.py$/i,
14149
- /_test\.(py|go)$/i,
14150
- /Tests?\.(java|kt|cs)$/
14151
- ];
14152
- function isTestFile(path) {
14153
- return TEST_FILE_RES.some((re) => re.test(path));
14571
+ function stripJsonComments(text) {
14572
+ let out = "";
14573
+ let inString = false;
14574
+ let inLineComment = false;
14575
+ let inBlockComment = false;
14576
+ for (let i2 = 0; i2 < text.length; i2++) {
14577
+ const c = text[i2];
14578
+ const next = text[i2 + 1];
14579
+ if (inLineComment) {
14580
+ if (c === "\n") {
14581
+ inLineComment = false;
14582
+ out += c;
14583
+ }
14584
+ continue;
14585
+ }
14586
+ if (inBlockComment) {
14587
+ if (c === "*" && next === "/") {
14588
+ inBlockComment = false;
14589
+ i2++;
14590
+ }
14591
+ continue;
14592
+ }
14593
+ if (inString) {
14594
+ out += c;
14595
+ if (c === "\\") {
14596
+ out += next;
14597
+ i2++;
14598
+ continue;
14599
+ }
14600
+ if (c === '"') inString = false;
14601
+ continue;
14602
+ }
14603
+ if (c === '"') {
14604
+ inString = true;
14605
+ out += c;
14606
+ continue;
14607
+ }
14608
+ if (c === "/" && next === "/") {
14609
+ inLineComment = true;
14610
+ i2++;
14611
+ continue;
14612
+ }
14613
+ if (c === "/" && next === "*") {
14614
+ inBlockComment = true;
14615
+ i2++;
14616
+ continue;
14617
+ }
14618
+ out += c;
14619
+ }
14620
+ return out.replace(/,(\s*[}\]])/g, "$1");
14154
14621
  }
14155
- function checkApiScope(results, targets, apiChanges) {
14156
- const targetsByPath = new Map(targets.map((t) => [t.path, t]));
14157
- const violations = [];
14158
- for (const { targetPath, newContent } of results) {
14159
- if (isTestFile(targetPath)) continue;
14160
- const target = targetsByPath.get(targetPath);
14161
- const isNewFile = target?.kind === "NEW_FILE";
14162
- let scanned;
14163
- if (isNewFile) {
14164
- scanned = newContent;
14622
+ function resolveAliasPrefixes(results, workspaceRoot) {
14623
+ const root = (0, import_node_path12.resolve)(workspaceRoot ?? ".");
14624
+ for (const filename of ["tsconfig.json", "jsconfig.json"]) {
14625
+ const configPath = (0, import_node_path12.join)(root, filename);
14626
+ const generated = results.find((r) => (0, import_node_path12.resolve)(r.targetPath) === configPath);
14627
+ let raw;
14628
+ if (generated) {
14629
+ raw = generated.newContent;
14165
14630
  } else {
14166
- let currentContent;
14167
14631
  try {
14168
- currentContent = (0, import_node_fs14.readFileSync)(targetPath, "utf8");
14632
+ raw = (0, import_node_fs14.readFileSync)(configPath, "utf8");
14169
14633
  } catch {
14170
- currentContent = "";
14634
+ raw = null;
14171
14635
  }
14172
- scanned = addedLines(currentContent, newContent);
14173
14636
  }
14174
- for (const mention of detectMentions(scanned)) {
14175
- if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
14176
- violations.push({ file: targetPath, method: mention.method, path: mention.path });
14177
- }
14637
+ if (raw === null) continue;
14638
+ try {
14639
+ const parsed = JSON.parse(stripJsonComments(raw));
14640
+ const paths = parsed.compilerOptions?.paths;
14641
+ const fromConfig = paths && typeof paths === "object" ? Object.keys(paths).map((k) => k.endsWith("*") ? k.slice(0, -1) : k) : [];
14642
+ return [.../* @__PURE__ */ new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];
14643
+ } catch {
14644
+ continue;
14178
14645
  }
14179
14646
  }
14180
- return { blocked: violations.length > 0, violations };
14181
- }
14182
- function describeScopeViolations(check) {
14183
- return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
14647
+ return DEFAULT_ALIAS_PREFIXES;
14184
14648
  }
14185
-
14186
- // src/targeting.ts
14187
- var import_node_path13 = require("node:path");
14188
-
14189
- // src/targetingFindings.ts
14190
- var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
14191
- function prepareTargetingFindings(raw, listing, deniedPaths) {
14192
- if (!isRecord2(raw)) return void 0;
14193
- const { verdict, files, callPath, evidence, searches } = raw;
14194
- if (typeof verdict !== "string" || !Array.isArray(files) || !Array.isArray(callPath) || !Array.isArray(evidence)) return void 0;
14195
- const keep = (entry) => isRecord2(entry) && typeof entry.path === "string" && listing.has(entry.path) && matchesDeniedPath(entry.path, deniedPaths) === null;
14196
- const kept = {
14197
- files: files.filter(keep),
14198
- callPath: callPath.filter(keep),
14199
- evidence: evidence.filter(keep)
14200
- };
14201
- if (kept.files.length === 0 && kept.callPath.length === 0 && kept.evidence.length === 0) return void 0;
14202
- return {
14203
- verdict,
14204
- ...kept,
14205
- searches: Array.isArray(searches) ? searches.filter((s) => typeof s === "string") : [],
14206
- openQuestions: []
14207
- };
14649
+ function describeDependencyViolations(check) {
14650
+ return check.violations.map((v) => `${v.file} imports ${v.packages.join(", ")}, not a dependency of this repository`).join("; ");
14208
14651
  }
14209
14652
 
14210
- // src/targetingMode.ts
14211
- var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
14212
- function parse5(value) {
14213
- if (typeof value !== "string") return null;
14214
- const v = value.trim().toLowerCase();
14215
- if (v === "loop") return "loop";
14216
- if (v === "single") return "single";
14217
- return null;
14653
+ // src/testPlacementCheck.ts
14654
+ function isDiscovered(targetPath, discoveredFiles) {
14655
+ const normalized = targetPath.replace(/\\/g, "/");
14656
+ for (const candidate of discoveredFiles) {
14657
+ if (candidate === normalized) return true;
14658
+ if (candidate.endsWith(normalized) || normalized.endsWith(candidate)) return true;
14659
+ }
14660
+ return false;
14218
14661
  }
14219
- function resolveTargetingMode(env2 = process.env, packetSetting) {
14220
- const fromSetting = parse5(packetSetting);
14221
- if (fromSetting) return fromSetting;
14222
- return parse5(env2[TARGETING_MODE_ENV]) ?? "single";
14662
+ function checkTestPlacement(targets, discoveredFiles) {
14663
+ if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };
14664
+ const violations = [];
14665
+ for (const target of targets) {
14666
+ if (target.kind !== "EXISTING") continue;
14667
+ if (!target.automationIds || target.automationIds.length === 0) continue;
14668
+ if (!isDiscovered(target.path, discoveredFiles)) {
14669
+ violations.push({ file: target.path, automationIds: target.automationIds });
14670
+ }
14671
+ }
14672
+ return { blocked: violations.length > 0, violations };
14223
14673
  }
14224
-
14225
- // src/targeting.ts
14226
- var CONTRACT_VERSION2 = "test-targets-1";
14227
- function listWorkspaceFiles(workspaceRoot) {
14228
- return listFiles(workspaceRoot ?? ".");
14674
+ function describeTestPlacementViolations(check) {
14675
+ return check.violations.map(
14676
+ (v) => `${v.file} claims test case(s) ${v.automationIds.join(", ")} but the repository's own test runner never discovered this file`
14677
+ ).join("; ");
14229
14678
  }
14230
- function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
14231
- const denied = matchesDeniedPath(target.path, deniedPaths);
14232
- if (denied) {
14233
- throw new DeniedPathError(
14234
- `pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`
14235
- );
14236
- }
14237
- const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);
14238
- if (deniedContext) {
14239
- throw new DeniedPathError(
14240
- `pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`
14241
- );
14242
- }
14243
- if (target.kind !== "EXISTING" && target.kind !== "NEW_FILE") {
14244
- throw new Error(`pilot.targeting returned an unknown kind "${target.kind}" for ${target.path}`);
14245
- }
14246
- if (target.kind === "EXISTING") {
14247
- if (!workspaceListing.has(target.path)) {
14248
- throw new Error(
14249
- `pilot.targeting named an EXISTING file not found in the checkout: ${target.path}`
14250
- );
14251
- }
14252
- return;
14679
+ function checkAutomationIdCoverage(targets, discoveredAutomationIds) {
14680
+ if (discoveredAutomationIds === null || discoveredAutomationIds === void 0) {
14681
+ return { blocked: false, missing: [] };
14253
14682
  }
14254
- const root = (0, import_node_path13.resolve)(workspaceRoot ?? ".");
14255
- const rel = (0, import_node_path13.relative)(root, (0, import_node_path13.resolve)(target.path));
14256
- if (rel.startsWith("..") || (0, import_node_path13.isAbsolute)(rel)) {
14257
- throw new Error(
14258
- `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
14259
- );
14683
+ const claimed = /* @__PURE__ */ new Set();
14684
+ for (const target of targets) {
14685
+ for (const id of target.automationIds ?? []) claimed.add(id);
14260
14686
  }
14687
+ const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));
14688
+ return { blocked: missing.length > 0, missing };
14261
14689
  }
14262
- function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings) {
14263
- const contextData = {
14264
- // NESTED, NOT FLATTENED — a second vocabulary for the design shape is exactly what
14265
- // QUIKTR-1034 cost.
14266
- workspaceListing,
14267
- design,
14268
- // QUIKTR-1065/1083 — requiredTests carried through so targeting can propose a test-file
14269
- // target naming which cases it covers (§15.1's Case shape, unchanged).
14270
- requiredTests,
14271
- // QUIKTR-1083 (§15.6) — required on the versioned path.
14272
- contractVersion: CONTRACT_VERSION2
14273
- };
14274
- if (deniedPaths.length > 0) {
14275
- contextData.deniedPaths = deniedPaths;
14276
- }
14277
- if (outOfScope.length > 0) {
14278
- contextData.outOfScope = outOfScope;
14279
- }
14280
- contextData.testDiscovery = testDiscovery;
14281
- if (findings) {
14282
- contextData.findings = findings;
14283
- }
14284
- return contextData;
14690
+ function describeAutomationCoverageViolations(check) {
14691
+ return `test case(s) ${check.missing.join(", ")} have no matching test discovered in the test run \u2014 generated, but never executed`;
14285
14692
  }
14286
- async function postTargeting(gateway, contextData, signal) {
14287
- const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
14288
- method: "POST",
14289
- headers: { "content-type": "application/json", "x-run-token": gateway.token },
14290
- body: JSON.stringify({
14291
- appId: "quiktrack",
14292
- useCase: "pilot.targeting",
14293
- expectedOutputType: "json",
14294
- userPrompt: "",
14295
- contextData
14296
- }),
14297
- ...signal ? { signal } : {}
14693
+
14694
+ // src/unsuppliedInputs.ts
14695
+ var estraverse5 = __toESM(require_estraverse());
14696
+ var MAX_UNSUPPLIED_ENTRIES = 10;
14697
+ var MAX_UNSUPPLIED_NAMES = 5;
14698
+ var MAX_NAME_CHARS = 80;
14699
+ var MAX_FUNCTION_CHARS = 120;
14700
+ var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
14701
+ var IDENTIFIER_NAME = /^[A-Za-z_$][\w$]*$/;
14702
+ function isFunction(node) {
14703
+ return FUNCTION_TYPES.has(node.type);
14704
+ }
14705
+ function collectFunctions(ast) {
14706
+ const out = [];
14707
+ estraverse5.traverse(ast, {
14708
+ fallback: "iteration",
14709
+ enter(node, parent) {
14710
+ if (isFunction(node)) out.push({ node, parent: parent ?? null });
14711
+ }
14298
14712
  });
14299
- if (!res.ok) {
14300
- throw new TargetingHttpError(res.status, res.statusText);
14301
- }
14302
- return res.json();
14713
+ return out;
14303
14714
  }
14304
- function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
14305
- if (body.outcome === "NO_TARGET") {
14306
- return { outcome: "NO_TARGET", reason: body.noTargetReason ?? null };
14715
+ function keyName(key, computed) {
14716
+ if (!key) return null;
14717
+ if (key.type === "Literal" && typeof key.value === "string") return key.value;
14718
+ if (key.type === "Identifier" && !computed) return key.name;
14719
+ return null;
14720
+ }
14721
+ function nameOf({ node, parent }) {
14722
+ if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {
14723
+ const id = node.id;
14724
+ if (id?.name) return id.name;
14307
14725
  }
14308
- if (body.outcome !== "TARGETED" || !Array.isArray(body.targets)) {
14309
- throw new RuntimeReplyError(
14310
- `pilot.targeting returned an unexpected shape: ${JSON.stringify(body)}`,
14311
- "pilot.targeting returned an unexpected shape"
14312
- );
14726
+ if (!parent) return "(anonymous)";
14727
+ if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
14728
+ if (parent.type === "AssignmentExpression") {
14729
+ const left = parent.left;
14730
+ if (left.type === "Identifier") return left.name;
14731
+ if (left.type === "MemberExpression") return keyName(left.property, left.computed) ?? "(anonymous)";
14313
14732
  }
14314
- const listing = new Set(workspaceListing);
14315
- for (const target of body.targets) {
14316
- validateTarget(target, workspaceRoot, listing, deniedPaths);
14733
+ if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
14734
+ return keyName(parent.key, parent.computed) ?? "(anonymous)";
14317
14735
  }
14318
- const correctedKinds = [];
14319
- const targets = body.targets.map((target) => {
14320
- if (target.kind === "NEW_FILE" && listing.has(target.path)) {
14321
- correctedKinds.push(target.path);
14322
- return { ...target, kind: "EXISTING" };
14736
+ return "(anonymous)";
14737
+ }
14738
+ function isCallback({ node, parent }) {
14739
+ if (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
14740
+ return (parent.arguments ?? []).includes(node);
14741
+ }
14742
+ function suppliedNames(ast, into) {
14743
+ estraverse5.traverse(ast, {
14744
+ fallback: "iteration",
14745
+ enter(node) {
14746
+ const n = node;
14747
+ if (n.type === "ObjectExpression") {
14748
+ for (const prop of n.properties ?? []) {
14749
+ if (prop.type !== "Property") continue;
14750
+ const name = keyName(prop.key, prop.computed);
14751
+ if (name) into.add(name);
14752
+ }
14753
+ } else if (n.type === "AssignmentExpression" && n.left.type === "MemberExpression") {
14754
+ const left = n.left;
14755
+ const name = keyName(left.property, left.computed);
14756
+ if (name) into.add(name);
14757
+ }
14323
14758
  }
14324
- return target;
14325
14759
  });
14326
- return {
14327
- outcome: "TARGETED",
14328
- targets,
14329
- skippedCases: body.skippedCases ?? [],
14330
- ...correctedKinds.length > 0 ? { correctedKinds } : {}
14760
+ }
14761
+ function parameters(fn) {
14762
+ const names = /* @__PURE__ */ new Set();
14763
+ const destructured = [];
14764
+ const visit = (p, topLevel) => {
14765
+ if (!p) return;
14766
+ if (p.type === "Identifier") names.add(p.name);
14767
+ else if (p.type === "AssignmentPattern") visit(p.left, topLevel);
14768
+ else if (p.type === "RestElement") visit(p.argument, topLevel);
14769
+ else if (p.type === "ObjectPattern") {
14770
+ for (const prop of p.properties ?? []) {
14771
+ if (prop.type === "RestElement") continue;
14772
+ const name = keyName(prop.key, prop.computed);
14773
+ const range = prop.range;
14774
+ if (name && topLevel) destructured.push({ name, at: range ? range[0] : 0 });
14775
+ }
14776
+ }
14331
14777
  };
14778
+ for (const p of fn.params ?? []) visit(p, true);
14779
+ return { names, destructured };
14332
14780
  }
14333
- async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], findings) {
14334
- const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
14335
- let envelope = await postTargeting(gateway, contextData);
14336
- let warnings;
14337
- if (findings && envelope?.errorCode === "CONTRACT_REJECTED") {
14338
- envelope = await postTargeting(
14339
- gateway,
14340
- buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope)
14341
- );
14342
- warnings = ["QuikPilot's targeting ran without the early look's findings (the AI service did not accept them)."];
14343
- }
14344
- checkHardFailure(envelope, "pilot.targeting");
14345
- const body = unwrapExecute(envelope, "pilot.targeting");
14346
- const result = finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);
14347
- return warnings ? { ...result, warnings } : result;
14781
+ function readsOf(site) {
14782
+ const fn = site.node;
14783
+ const { names: params, destructured } = parameters(fn);
14784
+ const reads = [...destructured];
14785
+ estraverse5.traverse(fn.body, {
14786
+ fallback: "iteration",
14787
+ enter(node, parent) {
14788
+ const n = node;
14789
+ if (isFunction(n)) {
14790
+ const own = parameters(n).names;
14791
+ const shadows = [...own].some((name) => params.has(name));
14792
+ if (!isCallback({ node: n, parent }) || shadows) return estraverse5.VisitorOption.Skip;
14793
+ }
14794
+ const range = n.range;
14795
+ const at2 = range ? range[0] : 0;
14796
+ if (n.type === "MemberExpression") {
14797
+ const object = n.object;
14798
+ if (object.type !== "Identifier" || !params.has(object.name)) return;
14799
+ const name = keyName(n.property, n.computed);
14800
+ if (name) reads.push({ name, at: at2 });
14801
+ } else if (n.type === "VariableDeclarator" && n.id.type === "ObjectPattern" && n.init) {
14802
+ const init = n.init;
14803
+ if (init.type !== "Identifier" || !params.has(init.name)) return;
14804
+ for (const prop of n.id.properties ?? []) {
14805
+ if (prop.type === "RestElement") continue;
14806
+ const name = keyName(prop.key, prop.computed);
14807
+ if (name) reads.push({ name, at: at2 });
14808
+ }
14809
+ }
14810
+ }
14811
+ });
14812
+ reads.sort((a, b) => a.at - b.at);
14813
+ return reads;
14348
14814
  }
14349
- var CODE_LIKE = /^[A-Z0-9_]{1,40}$/;
14350
- async function runTargeting(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], options = {}) {
14351
- const mode = options.mode ?? resolveTargetingMode();
14352
- const findings = prepareTargetingFindings(options.findings, new Set(workspaceListing), deniedPaths);
14353
- if (mode !== "loop") {
14354
- return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
14355
- }
14356
- const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
14357
- let summary;
14358
- let runtimeCode;
14359
- let reason;
14815
+ function wordsOf(text, into) {
14816
+ for (const m of text.matchAll(/[\w$]+/g)) into.add(m[0]);
14817
+ }
14818
+ function findUnsuppliedInputs(input) {
14360
14819
  try {
14361
- const looped = await runTargetingLoop(
14362
- { baseContext, listing: workspaceListing, deniedPaths },
14363
- { ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
14364
- );
14365
- summary = looped.summary;
14366
- const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
14367
- return { ...result, loop: summary };
14368
- } catch (err) {
14369
- if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;
14370
- if (err instanceof LoopFailure) {
14371
- reason = err.reason;
14372
- runtimeCode = err.runtimeCode;
14373
- summary = err.summary ?? summary;
14374
- } else {
14375
- reason = "final_invalid";
14820
+ const known = /* @__PURE__ */ new Set();
14821
+ for (const file of input.corpus) {
14822
+ if (!isTestFile(file.path)) wordsOf(file.text, known);
14376
14823
  }
14377
- }
14378
- const fellBack = {
14379
- turns: summary?.turns ?? 0,
14380
- toolCalls: summary?.toolCalls ?? 0,
14381
- readChars: summary?.readChars ?? 0,
14382
- refused: summary?.refused ?? 0,
14383
- reads: summary?.reads ?? [],
14384
- stopReason: "fallback",
14385
- fellBack: true,
14386
- fallbackReason: reason
14387
- };
14388
- const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
14389
- log({
14390
- event: "targeting.loop_fallback",
14391
- reason,
14392
- turn: fellBack.turns,
14393
- toolCalls: fellBack.toolCalls,
14394
- ...runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}
14395
- });
14396
- const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
14397
- return {
14398
- ...single,
14399
- loop: fellBack,
14400
- warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`, ...single.warnings ?? []]
14401
- };
14402
- }
14403
-
14404
- // src/targetingRecord.ts
14405
- var MAX_TARGETS = 25;
14406
- var MAX_IDS_PER_TARGET = 50;
14407
- var MAX_CONTEXT_PATHS = 20;
14408
- var MAX_ADDED_PATHS = 20;
14409
- var MAX_SKIPPED_CONTEXT = 20;
14410
- var MAX_SKIPPED_CASES = 200;
14411
- var MAX_CONTEXT_RECORDS = 25;
14412
- var MAX_PATH_CHARS2 = 300;
14413
- var MAX_ID_CHARS3 = 100;
14414
- var MAX_REASON_CHARS = 300;
14415
- var MAX_LOOP_READS = 50;
14416
- var MAX_FALLBACK_REASON_CHARS = 40;
14417
- function clampList(values, max, maxChars) {
14418
- let cut = false;
14419
- const kept = [];
14420
- for (const raw of values ?? []) {
14421
- const v = typeof raw === "string" ? raw.trim() : "";
14422
- if (v.length === 0) continue;
14423
- if (v.length > maxChars || kept.length >= max) {
14424
- cut = true;
14425
- continue;
14824
+ const judged = [];
14825
+ const supplied = /* @__PURE__ */ new Set();
14826
+ for (const file of input.changed) {
14827
+ if (isTestFile(file.path) || !isCheckablePath(file.path)) continue;
14828
+ const after = parseProgram(file.path, file.newContent);
14829
+ if (!after) continue;
14830
+ suppliedNames(after.ast, supplied);
14831
+ judged.push({ file, ast: after.ast });
14426
14832
  }
14427
- kept.push(v);
14833
+ const found = [];
14834
+ for (const { file, ast } of judged) {
14835
+ for (const site of collectFunctions(ast)) {
14836
+ if (isCallback(site)) continue;
14837
+ const names = [];
14838
+ for (const { name } of readsOf(site)) {
14839
+ if (!IDENTIFIER_NAME.test(name) || name.length > MAX_NAME_CHARS) continue;
14840
+ if (known.has(name) || supplied.has(name) || names.includes(name)) continue;
14841
+ names.push(name);
14842
+ }
14843
+ if (names.length === 0) continue;
14844
+ found.push({ file: file.path, function: nameOf(site).slice(0, MAX_FUNCTION_CHARS), names: names.slice(0, MAX_UNSUPPLIED_NAMES) });
14845
+ if (found.length >= MAX_UNSUPPLIED_ENTRIES) return found;
14846
+ }
14847
+ }
14848
+ return found;
14849
+ } catch {
14850
+ return [];
14428
14851
  }
14429
- return { kept, cut };
14430
14852
  }
14431
- function wholeNumber2(n) {
14432
- return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
14433
- }
14434
- function clampLoop(loop) {
14435
- let cut = false;
14436
- const reads = [];
14437
- for (const r of loop.reads ?? []) {
14438
- if (reads.length >= MAX_LOOP_READS) {
14439
- cut = true;
14440
- break;
14853
+ var MAX_CORPUS_CHARS = 64e6;
14854
+ function checkRunForUnsuppliedInputs(input) {
14855
+ try {
14856
+ const listed = new Set(input.listing);
14857
+ const corpus = [];
14858
+ let chars = 0;
14859
+ for (const path of listed) {
14860
+ const text = input.readText(path);
14861
+ if (text === null) continue;
14862
+ chars += text.length;
14863
+ if (chars > MAX_CORPUS_CHARS) return [];
14864
+ corpus.push({ path, text });
14441
14865
  }
14442
- const path = typeof r.path === "string" ? r.path.trim() : "";
14443
- if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
14444
- cut = true;
14445
- continue;
14866
+ const changed = [];
14867
+ for (const { targetPath, newContent } of input.results) {
14868
+ if (listed.has(targetPath) && input.readText(targetPath) === null) continue;
14869
+ changed.push({ path: targetPath, newContent });
14446
14870
  }
14447
- reads.push({
14448
- path,
14449
- ...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
14450
- ...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
14451
- chars: wholeNumber2(r.chars),
14452
- ...r.refused ? { refused: true } : {}
14453
- });
14871
+ return findUnsuppliedInputs({ changed, corpus });
14872
+ } catch {
14873
+ return [];
14454
14874
  }
14455
- const refusedTurns = clampRefusedTurns(loop.refusedTurns);
14456
- if (refusedTurns.cut) cut = true;
14457
- return {
14458
- turns: wholeNumber2(loop.turns),
14459
- toolCalls: wholeNumber2(loop.toolCalls),
14460
- refused: wholeNumber2(loop.refused),
14461
- stopReason: loop.stopReason,
14462
- ...loop.fellBack ? { fellBack: true } : {},
14463
- ...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {},
14464
- reads,
14465
- ...refusedTurns.rows.length > 0 ? { refusedTurns: refusedTurns.rows } : {},
14466
- ...cut ? { truncated: true } : {}
14467
- };
14468
14875
  }
14469
- function buildTargetingRecord(targeting, contextLog) {
14470
- let truncated = false;
14471
- const note = (cut) => {
14472
- if (cut) truncated = true;
14876
+ function describeUnsuppliedInputs(found) {
14877
+ const many = found.length !== 1;
14878
+ 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.`;
14879
+ }
14880
+
14881
+ // src/unsuppliedInputsDisk.ts
14882
+ var import_node_fs15 = require("node:fs");
14883
+ var MAX_READ_BYTES = 1e6;
14884
+ function readCheckoutText(path) {
14885
+ try {
14886
+ const info = (0, import_node_fs15.statSync)(path);
14887
+ if (!info.isFile() || info.size > MAX_READ_BYTES) return null;
14888
+ const bytes = (0, import_node_fs15.readFileSync)(path);
14889
+ if (bytes.includes(0)) return null;
14890
+ return bytes.toString("utf8");
14891
+ } catch {
14892
+ return null;
14893
+ }
14894
+ }
14895
+ function checkGeneratedCode(results) {
14896
+ try {
14897
+ return checkRunForUnsuppliedInputs({ results, listing: listFiles("."), readText: readCheckoutText });
14898
+ } catch {
14899
+ return [];
14900
+ }
14901
+ }
14902
+
14903
+ // src/vanishedTests.ts
14904
+ var MAX_VANISHED_NAMES = 50;
14905
+ function findVanishedTests(baseline, after) {
14906
+ if (!baseline.results || !after.results) return null;
14907
+ const missing = [...baseline.results.keys()].filter((id) => !after.results.has(id));
14908
+ if (missing.length === 0) return null;
14909
+ return { names: missing.slice(0, MAX_VANISHED_NAMES), total: missing.length };
14910
+ }
14911
+ function describeVanishedTests(vanished) {
14912
+ const noun = vanished.total === 1 ? "1 test" : `${vanished.total} tests`;
14913
+ 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"}.`;
14914
+ }
14915
+
14916
+ // src/verifyChange.ts
14917
+ var import_node_path13 = require("node:path");
14918
+ async function verifyChange(ctx, results, undoable) {
14919
+ const cwd = ctx.cwd ?? process.cwd();
14920
+ const now = ctx.now ?? Date.now;
14921
+ const { packet, targets, baseline } = ctx;
14922
+ const warnings = [];
14923
+ const outputs = { generatedFilePaths: [], finalTestReport: null };
14924
+ let stage = "other";
14925
+ let undo = () => {
14473
14926
  };
14474
- if (targeting.outcome === "NO_TARGET") {
14475
- const record2 = { outcome: "NO_TARGET", targets: [], skippedCaseIds: [], codegenContext: [] };
14476
- const reason = (targeting.reason ?? "").trim();
14477
- if (reason.length > 0) {
14478
- record2.noTargetReason = reason.slice(0, MAX_REASON_CHARS);
14479
- if (reason.length > MAX_REASON_CHARS) record2.noTargetReasonTruncated = true;
14927
+ let flushedAt = null;
14928
+ const fail = (error, extra = {}) => ({
14929
+ ok: false,
14930
+ stage,
14931
+ error,
14932
+ warnings,
14933
+ bothSnapshotsReadable: false,
14934
+ failingKey: null,
14935
+ gateMs: flushedAt === null ? 0 : now() - flushedAt,
14936
+ undo,
14937
+ outputs,
14938
+ ...extra
14939
+ });
14940
+ try {
14941
+ stage = "dependency";
14942
+ const depCheck = checkImportDependencies(results, readDeclaredDependencies(results, packet.workspaceRoot), resolveAliasPrefixes(results, packet.workspaceRoot));
14943
+ if (depCheck.blocked) {
14944
+ return fail(new Error(`QuikPilot's generated code imports packages this repository doesn't have \u2014 ${describeDependencyViolations(depCheck)}`));
14945
+ }
14946
+ stage = "scope";
14947
+ const scopeCheck = checkApiScope(results, targets, packet.design?.apiChanges ?? []);
14948
+ if (scopeCheck.blocked) {
14949
+ return fail(new Error(`QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`));
14950
+ }
14951
+ stage = "placement";
14952
+ const placementCheck = checkTestPlacement(targets, baseline.discoveredFiles);
14953
+ if (placementCheck.blocked) {
14954
+ return fail(new Error(`QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`));
14955
+ }
14956
+ stage = "other";
14957
+ try {
14958
+ const baselineCheck = await runBaselineCheck({
14959
+ targets,
14960
+ results,
14961
+ testFileCmd: packet.commands.testFile,
14962
+ requiredTestTypes: packet.requiredTestTypes
14963
+ });
14964
+ warnings.push(...baselineCheck.warnings);
14965
+ outputs.baselineFindings = baselineCheck.findings ?? void 0;
14966
+ } catch (err) {
14967
+ const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;
14968
+ console.error(message);
14969
+ warnings.push(message);
14480
14970
  }
14481
- if (targeting.loop) record2.loop = clampLoop(targeting.loop);
14482
- return record2;
14483
- }
14484
- const targets = [];
14485
- for (const t of targeting.targets) {
14486
- if (targets.length >= MAX_TARGETS) {
14487
- truncated = true;
14488
- break;
14971
+ try {
14972
+ const unsupplied = checkGeneratedCode(results);
14973
+ if (unsupplied.length > 0) {
14974
+ outputs.unsuppliedInputs = unsupplied;
14975
+ const w = describeUnsuppliedInputs(unsupplied);
14976
+ warnings.push(w);
14977
+ console.warn(`QuikPilot code warning (not blocking): ${w}`);
14978
+ }
14979
+ } catch (err) {
14980
+ console.error(`Unsupplied-input check could not run (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14981
+ }
14982
+ outputs.generatedFilePaths = results.map((r) => r.targetPath);
14983
+ flushedAt = now();
14984
+ if (undoable) {
14985
+ const report = findJUnitReport(cwd);
14986
+ const ignore = report ? [(0, import_node_path13.relative)(cwd, report).split("\\").join("/")] : [];
14987
+ const flush = undoableFlush(cwd, results, flushCodegenResults, { ignore });
14988
+ undo = () => flush.undo();
14989
+ } else {
14990
+ flushCodegenResults(results);
14489
14991
  }
14490
- const path = typeof t.path === "string" ? t.path.trim() : "";
14491
- if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
14492
- truncated = true;
14493
- continue;
14992
+ stage = "format";
14993
+ try {
14994
+ runCommand(packet.commands.format, "Format");
14995
+ } catch (err) {
14996
+ console.error(`Format failed (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14997
+ }
14998
+ stage = "lint";
14999
+ runCommand(packet.commands.lint, "Lint");
15000
+ stage = "gate";
15001
+ const after = captureTestSnapshot(packet.commands.test);
15002
+ outputs.finalTestReport = readTestReportBytes();
15003
+ outputs.testCount = after.results?.size;
15004
+ outputs.vanishedTests = findVanishedTests(baseline, after) ?? void 0;
15005
+ if (outputs.vanishedTests) {
15006
+ const w = describeVanishedTests(outputs.vanishedTests);
15007
+ warnings.push(w);
15008
+ console.warn(`QuikPilot test warning (not blocking): ${w}`);
15009
+ }
15010
+ const check = checkForRegressions(baseline, after);
15011
+ if (check.blocked) {
15012
+ const readable = Boolean(baseline.results && after.results);
15013
+ const answered = readable ? testAnswerFrom({ baseline, after, changedPaths: results.map((r) => r.targetPath), requiredIds: ctx.requiredAutomationIds }) : null;
15014
+ return fail(new Error(`QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`), {
15015
+ check,
15016
+ bothSnapshotsReadable: readable,
15017
+ ...answered ? { answer: answered.output, failingKey: answered.failingKey } : {}
15018
+ });
14494
15019
  }
14495
- const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
14496
- const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
14497
- note(contextPaths.cut);
14498
- note(automationIds.cut);
14499
- targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });
15020
+ stage = "coverage";
15021
+ const coverageCheck = checkAutomationIdCoverage(targets, after.discoveredAutomationIds);
15022
+ if (coverageCheck.blocked) {
15023
+ return fail(new Error(`QuikPilot's generated tests were not executed \u2014 ${describeAutomationCoverageViolations(coverageCheck)}`));
15024
+ }
15025
+ } catch (err) {
15026
+ return fail(err instanceof Error ? err : new Error(String(err)));
14500
15027
  }
14501
- const skipped = clampList(
14502
- (targeting.skippedCases ?? []).map((c) => c.automationId),
14503
- MAX_SKIPPED_CASES,
14504
- MAX_ID_CHARS3
15028
+ return { ok: true, warnings, gateMs: flushedAt === null ? 0 : now() - flushedAt, undo, outputs };
15029
+ }
15030
+
15031
+ // src/guardrail.ts
15032
+ function checkGuardrail(deniedPaths) {
15033
+ addAll();
15034
+ const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
15035
+ if (violations.length > 0) {
15036
+ throw new Error(`QuikPilot touched denied paths:
15037
+ ${violations.join("\n")}`);
15038
+ }
15039
+ }
15040
+
15041
+ // src/installationToken.ts
15042
+ async function exchangeForInstallationToken(installationTokenUrl, runToken) {
15043
+ const res = await fetch(installationTokenUrl, {
15044
+ method: "POST",
15045
+ headers: { Authorization: `Bearer ${runToken}` }
15046
+ });
15047
+ if (!res.ok) {
15048
+ throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
15049
+ }
15050
+ const body = await res.json();
15051
+ if (body.success !== true) {
15052
+ throw new Error("Exchange installation token failed: response did not carry success:true");
15053
+ }
15054
+ return body.data.token;
15055
+ }
15056
+
15057
+ // src/oidc.ts
15058
+ var QUIKPILOT_OIDC_AUDIENCE = "quiktrack-quikpilot";
15059
+ async function fetchGithubOidcToken(env2 = process.env) {
15060
+ const requestUrl = required(
15061
+ "ACTIONS_ID_TOKEN_REQUEST_URL",
15062
+ env2.ACTIONS_ID_TOKEN_REQUEST_URL
14505
15063
  );
14506
- note(skipped.cut);
14507
- const codegenContext = [];
14508
- for (const entry of contextLog) {
14509
- if (codegenContext.length >= MAX_CONTEXT_RECORDS) {
14510
- truncated = true;
14511
- break;
15064
+ const requestToken = required(
15065
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
15066
+ env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
15067
+ );
15068
+ const separator = requestUrl.includes("?") ? "&" : "?";
15069
+ const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
15070
+ const res = await fetch(url, {
15071
+ headers: { Authorization: `Bearer ${requestToken}` }
15072
+ });
15073
+ if (!res.ok) {
15074
+ throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
15075
+ }
15076
+ const body = await res.json();
15077
+ if (!body.value) {
15078
+ throw new Error("GitHub OIDC token response carried no value");
15079
+ }
15080
+ return body.value;
15081
+ }
15082
+
15083
+ // src/packet.ts
15084
+ async function fetchPacket(packetUrl, runToken, githubRunId) {
15085
+ const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
15086
+ const res = await fetch(url, {
15087
+ headers: { Authorization: `Bearer ${runToken}` }
15088
+ });
15089
+ if (!res.ok) {
15090
+ throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
15091
+ }
15092
+ const body = await res.json();
15093
+ if (body.success !== true) {
15094
+ throw new Error("Fetch work packet failed: response did not carry success:true");
15095
+ }
15096
+ return body.data;
15097
+ }
15098
+
15099
+ // src/phase0.ts
15100
+ var import_node_fs16 = require("node:fs");
15101
+ function writePhase0Marker(runId) {
15102
+ (0, import_node_fs16.mkdirSync)(".quikpilot", { recursive: true });
15103
+ (0, import_node_fs16.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
15104
+ `);
15105
+ }
15106
+
15107
+ // src/failureArtifact.ts
15108
+ var import_node_fs17 = require("node:fs");
15109
+ var import_node_path14 = require("node:path");
15110
+ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
15111
+ var REPORT_COPY = "final-test-report.xml";
15112
+ var MAX_REPORT_BYTES = 5 * 1024 * 1024;
15113
+ var MAX_FILES = 200;
15114
+ var RUNNER_VERSION = true ? "9.3.0-rc.16" : "dev";
15115
+ function safeDestination(base, repoPath) {
15116
+ if (!repoPath || (0, import_node_path14.isAbsolute)(repoPath)) return null;
15117
+ const destination = (0, import_node_path14.resolve)(base, repoPath);
15118
+ const rel = (0, import_node_path14.relative)(base, destination);
15119
+ if (!rel || rel.startsWith("..") || (0, import_node_path14.isAbsolute)(rel)) return null;
15120
+ return destination;
15121
+ }
15122
+ function writeFailureArtifact(input) {
15123
+ if (input.results.length === 0) return { written: false };
15124
+ try {
15125
+ const base = (0, import_node_path14.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
15126
+ (0, import_node_fs17.rmSync)(base, { recursive: true, force: true });
15127
+ (0, import_node_fs17.mkdirSync)(base, { recursive: true });
15128
+ const files = [];
15129
+ const skipped = [];
15130
+ for (const result of input.results) {
15131
+ const destination = files.length < MAX_FILES ? safeDestination(base, result.targetPath) : null;
15132
+ if (!destination) {
15133
+ skipped.push(result.targetPath);
15134
+ continue;
15135
+ }
15136
+ (0, import_node_fs17.mkdirSync)((0, import_node_path14.dirname)(destination), { recursive: true });
15137
+ (0, import_node_fs17.writeFileSync)(destination, result.newContent);
15138
+ files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
14512
15139
  }
14513
- const targetPath = typeof entry.targetPath === "string" ? entry.targetPath.trim() : "";
14514
- if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS2) {
14515
- truncated = true;
14516
- continue;
15140
+ let testReport = "none";
15141
+ if (input.testReport) {
15142
+ if (input.testReport.byteLength > MAX_REPORT_BYTES) {
15143
+ testReport = "too-large";
15144
+ } else {
15145
+ (0, import_node_fs17.writeFileSync)((0, import_node_path14.join)(base, REPORT_COPY), input.testReport);
15146
+ testReport = "included";
15147
+ }
14517
15148
  }
14518
- const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
14519
- const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS2);
14520
- const skippedPaths = clampList(
14521
- (entry.skipped ?? []).map((s) => s.path),
14522
- MAX_SKIPPED_CONTEXT,
14523
- MAX_PATH_CHARS2
14524
- );
14525
- note(contextPaths.cut);
14526
- note(addedPaths.cut);
14527
- note(skippedPaths.cut);
14528
- const reasonByPath = new Map((entry.skipped ?? []).map((s) => [s.path.trim(), s.reason]));
14529
- codegenContext.push({
14530
- targetPath,
14531
- contextPaths: contextPaths.kept,
14532
- addedPaths: addedPaths.kept,
14533
- skipped: skippedPaths.kept.map((path) => ({ path, reason: String(reasonByPath.get(path) ?? "skipped").slice(0, 40) })),
14534
- ...entry.retriedWithoutAdded ? { retriedWithoutAdded: true } : {}
14535
- });
15149
+ const manifest = {
15150
+ runId: input.runId,
15151
+ issueKey: input.issueKey,
15152
+ runnerVersion: RUNNER_VERSION,
15153
+ generatedAt: (/* @__PURE__ */ new Date()).toISOString(),
15154
+ targets: input.targets.map((t) => ({
15155
+ path: t.path,
15156
+ kind: t.kind,
15157
+ ...t.automationIds && t.automationIds.length > 0 ? { automationIds: t.automationIds } : {}
15158
+ })),
15159
+ files,
15160
+ skipped,
15161
+ testReport,
15162
+ failureReasons: input.failureReasons
15163
+ };
15164
+ const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
15165
+ (0, import_node_fs17.writeFileSync)((0, import_node_path14.join)(base, "manifest.json"), text);
15166
+ return { written: (0, import_node_fs17.existsSync)((0, import_node_path14.join)(base, "manifest.json")) };
15167
+ } catch (err) {
15168
+ console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
15169
+ return { written: false };
14536
15170
  }
14537
- const record = {
14538
- outcome: "TARGETED",
14539
- targets,
14540
- skippedCaseIds: skipped.kept,
14541
- codegenContext
15171
+ }
15172
+
15173
+ // src/targeting.ts
15174
+ var import_node_path15 = require("node:path");
15175
+
15176
+ // src/targetingFindings.ts
15177
+ var isRecord2 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
15178
+ function prepareTargetingFindings(raw, listing, deniedPaths) {
15179
+ if (!isRecord2(raw)) return void 0;
15180
+ const { verdict, files, callPath, evidence, searches } = raw;
15181
+ if (typeof verdict !== "string" || !Array.isArray(files) || !Array.isArray(callPath) || !Array.isArray(evidence)) return void 0;
15182
+ const keep = (entry) => isRecord2(entry) && typeof entry.path === "string" && listing.has(entry.path) && matchesDeniedPath(entry.path, deniedPaths) === null;
15183
+ const kept = {
15184
+ files: files.filter(keep),
15185
+ callPath: callPath.filter(keep),
15186
+ evidence: evidence.filter(keep)
15187
+ };
15188
+ if (kept.files.length === 0 && kept.callPath.length === 0 && kept.evidence.length === 0) return void 0;
15189
+ return {
15190
+ verdict,
15191
+ ...kept,
15192
+ searches: Array.isArray(searches) ? searches.filter((s) => typeof s === "string") : [],
15193
+ openQuestions: []
14542
15194
  };
14543
- if (truncated) record.truncated = true;
14544
- if (targeting.loop) record.loop = clampLoop(targeting.loop);
14545
- return record;
14546
15195
  }
14547
15196
 
14548
- // src/testPlacementCheck.ts
14549
- function isDiscovered(targetPath, discoveredFiles) {
14550
- const normalized = targetPath.replace(/\\/g, "/");
14551
- for (const candidate of discoveredFiles) {
14552
- if (candidate === normalized) return true;
14553
- if (candidate.endsWith(normalized) || normalized.endsWith(candidate)) return true;
14554
- }
14555
- return false;
15197
+ // src/targetingMode.ts
15198
+ var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
15199
+ function parse5(value) {
15200
+ if (typeof value !== "string") return null;
15201
+ const v = value.trim().toLowerCase();
15202
+ if (v === "loop") return "loop";
15203
+ if (v === "single") return "single";
15204
+ return null;
14556
15205
  }
14557
- function checkTestPlacement(targets, discoveredFiles) {
14558
- if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };
14559
- const violations = [];
14560
- for (const target of targets) {
14561
- if (target.kind !== "EXISTING") continue;
14562
- if (!target.automationIds || target.automationIds.length === 0) continue;
14563
- if (!isDiscovered(target.path, discoveredFiles)) {
14564
- violations.push({ file: target.path, automationIds: target.automationIds });
15206
+ function resolveTargetingMode(env2 = process.env, packetSetting) {
15207
+ const fromSetting = parse5(packetSetting);
15208
+ if (fromSetting) return fromSetting;
15209
+ return parse5(env2[TARGETING_MODE_ENV]) ?? "single";
15210
+ }
15211
+
15212
+ // src/targeting.ts
15213
+ var CONTRACT_VERSION2 = "test-targets-1";
15214
+ function listWorkspaceFiles(workspaceRoot) {
15215
+ return listFiles(workspaceRoot ?? ".");
15216
+ }
15217
+ function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
15218
+ const denied = matchesDeniedPath(target.path, deniedPaths);
15219
+ if (denied) {
15220
+ throw new DeniedPathError(
15221
+ `pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`
15222
+ );
15223
+ }
15224
+ const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);
15225
+ if (deniedContext) {
15226
+ throw new DeniedPathError(
15227
+ `pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`
15228
+ );
15229
+ }
15230
+ if (target.kind !== "EXISTING" && target.kind !== "NEW_FILE") {
15231
+ throw new Error(`pilot.targeting returned an unknown kind "${target.kind}" for ${target.path}`);
15232
+ }
15233
+ if (target.kind === "EXISTING") {
15234
+ if (!workspaceListing.has(target.path)) {
15235
+ throw new Error(
15236
+ `pilot.targeting named an EXISTING file not found in the checkout: ${target.path}`
15237
+ );
14565
15238
  }
15239
+ return;
15240
+ }
15241
+ const root = (0, import_node_path15.resolve)(workspaceRoot ?? ".");
15242
+ const rel = (0, import_node_path15.relative)(root, (0, import_node_path15.resolve)(target.path));
15243
+ if (rel.startsWith("..") || (0, import_node_path15.isAbsolute)(rel)) {
15244
+ throw new Error(
15245
+ `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
15246
+ );
14566
15247
  }
14567
- return { blocked: violations.length > 0, violations };
14568
- }
14569
- function describeTestPlacementViolations(check) {
14570
- return check.violations.map(
14571
- (v) => `${v.file} claims test case(s) ${v.automationIds.join(", ")} but the repository's own test runner never discovered this file`
14572
- ).join("; ");
14573
15248
  }
14574
- function checkAutomationIdCoverage(targets, discoveredAutomationIds) {
14575
- if (discoveredAutomationIds === null || discoveredAutomationIds === void 0) {
14576
- return { blocked: false, missing: [] };
15249
+ function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings) {
15250
+ const contextData = {
15251
+ // NESTED, NOT FLATTENED — a second vocabulary for the design shape is exactly what
15252
+ // QUIKTR-1034 cost.
15253
+ workspaceListing,
15254
+ design,
15255
+ // QUIKTR-1065/1083 — requiredTests carried through so targeting can propose a test-file
15256
+ // target naming which cases it covers (§15.1's Case shape, unchanged).
15257
+ requiredTests,
15258
+ // QUIKTR-1083 (§15.6) — required on the versioned path.
15259
+ contractVersion: CONTRACT_VERSION2
15260
+ };
15261
+ if (deniedPaths.length > 0) {
15262
+ contextData.deniedPaths = deniedPaths;
15263
+ }
15264
+ if (outOfScope.length > 0) {
15265
+ contextData.outOfScope = outOfScope;
14577
15266
  }
14578
- const claimed = /* @__PURE__ */ new Set();
14579
- for (const target of targets) {
14580
- for (const id of target.automationIds ?? []) claimed.add(id);
15267
+ contextData.testDiscovery = testDiscovery;
15268
+ if (findings) {
15269
+ contextData.findings = findings;
14581
15270
  }
14582
- const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));
14583
- return { blocked: missing.length > 0, missing };
14584
- }
14585
- function describeAutomationCoverageViolations(check) {
14586
- return `test case(s) ${check.missing.join(", ")} have no matching test discovered in the test run \u2014 generated, but never executed`;
15271
+ return contextData;
14587
15272
  }
14588
-
14589
- // src/tokenExchange.ts
14590
- async function exchangeForRunToken(tokenUrl, oidcToken) {
14591
- const res = await fetch(tokenUrl, {
15273
+ async function postTargeting(gateway, contextData, signal) {
15274
+ const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
14592
15275
  method: "POST",
14593
- headers: { Authorization: `Bearer ${oidcToken}` }
15276
+ headers: { "content-type": "application/json", "x-run-token": gateway.token },
15277
+ body: JSON.stringify({
15278
+ appId: "quiktrack",
15279
+ useCase: "pilot.targeting",
15280
+ expectedOutputType: "json",
15281
+ userPrompt: "",
15282
+ contextData
15283
+ }),
15284
+ ...signal ? { signal } : {}
14594
15285
  });
14595
15286
  if (!res.ok) {
14596
- throw new Error(`Exchange run token failed: ${await describeQuikTrackFailure(res)}`);
14597
- }
14598
- const body = await res.json();
14599
- if (body.success !== true) {
14600
- throw new Error("Exchange run token failed: response did not carry success:true");
15287
+ throw new TargetingHttpError(res.status, res.statusText);
14601
15288
  }
14602
- return body.data.runToken;
14603
- }
14604
-
14605
- // src/vanishedTests.ts
14606
- var MAX_VANISHED_NAMES = 50;
14607
- function findVanishedTests(baseline, after) {
14608
- if (!baseline.results || !after.results) return null;
14609
- const missing = [...baseline.results.keys()].filter((id) => !after.results.has(id));
14610
- if (missing.length === 0) return null;
14611
- return { names: missing.slice(0, MAX_VANISHED_NAMES), total: missing.length };
14612
- }
14613
- function describeVanishedTests(vanished) {
14614
- const noun = vanished.total === 1 ? "1 test" : `${vanished.total} tests`;
14615
- 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"}.`;
14616
- }
14617
-
14618
- // src/unsuppliedInputs.ts
14619
- var estraverse5 = __toESM(require_estraverse());
14620
- var MAX_UNSUPPLIED_ENTRIES = 10;
14621
- var MAX_UNSUPPLIED_NAMES = 5;
14622
- var MAX_NAME_CHARS = 80;
14623
- var MAX_FUNCTION_CHARS = 120;
14624
- var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
14625
- var IDENTIFIER_NAME = /^[A-Za-z_$][\w$]*$/;
14626
- function isFunction(node) {
14627
- return FUNCTION_TYPES.has(node.type);
14628
- }
14629
- function collectFunctions(ast) {
14630
- const out = [];
14631
- estraverse5.traverse(ast, {
14632
- fallback: "iteration",
14633
- enter(node, parent) {
14634
- if (isFunction(node)) out.push({ node, parent: parent ?? null });
14635
- }
14636
- });
14637
- return out;
14638
- }
14639
- function keyName(key, computed) {
14640
- if (!key) return null;
14641
- if (key.type === "Literal" && typeof key.value === "string") return key.value;
14642
- if (key.type === "Identifier" && !computed) return key.name;
14643
- return null;
15289
+ return res.json();
14644
15290
  }
14645
- function nameOf({ node, parent }) {
14646
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {
14647
- const id = node.id;
14648
- if (id?.name) return id.name;
15291
+ function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
15292
+ if (body.outcome === "NO_TARGET") {
15293
+ return { outcome: "NO_TARGET", reason: body.noTargetReason ?? null };
14649
15294
  }
14650
- if (!parent) return "(anonymous)";
14651
- if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
14652
- if (parent.type === "AssignmentExpression") {
14653
- const left = parent.left;
14654
- if (left.type === "Identifier") return left.name;
14655
- if (left.type === "MemberExpression") return keyName(left.property, left.computed) ?? "(anonymous)";
15295
+ if (body.outcome !== "TARGETED" || !Array.isArray(body.targets)) {
15296
+ throw new RuntimeReplyError(
15297
+ `pilot.targeting returned an unexpected shape: ${JSON.stringify(body)}`,
15298
+ "pilot.targeting returned an unexpected shape"
15299
+ );
14656
15300
  }
14657
- if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
14658
- return keyName(parent.key, parent.computed) ?? "(anonymous)";
15301
+ const listing = new Set(workspaceListing);
15302
+ for (const target of body.targets) {
15303
+ validateTarget(target, workspaceRoot, listing, deniedPaths);
14659
15304
  }
14660
- return "(anonymous)";
14661
- }
14662
- function isCallback({ node, parent }) {
14663
- if (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
14664
- return (parent.arguments ?? []).includes(node);
14665
- }
14666
- function suppliedNames(ast, into) {
14667
- estraverse5.traverse(ast, {
14668
- fallback: "iteration",
14669
- enter(node) {
14670
- const n = node;
14671
- if (n.type === "ObjectExpression") {
14672
- for (const prop of n.properties ?? []) {
14673
- if (prop.type !== "Property") continue;
14674
- const name = keyName(prop.key, prop.computed);
14675
- if (name) into.add(name);
14676
- }
14677
- } else if (n.type === "AssignmentExpression" && n.left.type === "MemberExpression") {
14678
- const left = n.left;
14679
- const name = keyName(left.property, left.computed);
14680
- if (name) into.add(name);
14681
- }
15305
+ const correctedKinds = [];
15306
+ const targets = body.targets.map((target) => {
15307
+ if (target.kind === "NEW_FILE" && listing.has(target.path)) {
15308
+ correctedKinds.push(target.path);
15309
+ return { ...target, kind: "EXISTING" };
14682
15310
  }
15311
+ return target;
14683
15312
  });
15313
+ return {
15314
+ outcome: "TARGETED",
15315
+ targets,
15316
+ skippedCases: body.skippedCases ?? [],
15317
+ ...correctedKinds.length > 0 ? { correctedKinds } : {}
15318
+ };
14684
15319
  }
14685
- function parameters(fn) {
14686
- const names = /* @__PURE__ */ new Set();
14687
- const destructured = [];
14688
- const visit = (p, topLevel) => {
14689
- if (!p) return;
14690
- if (p.type === "Identifier") names.add(p.name);
14691
- else if (p.type === "AssignmentPattern") visit(p.left, topLevel);
14692
- else if (p.type === "RestElement") visit(p.argument, topLevel);
14693
- else if (p.type === "ObjectPattern") {
14694
- for (const prop of p.properties ?? []) {
14695
- if (prop.type === "RestElement") continue;
14696
- const name = keyName(prop.key, prop.computed);
14697
- const range = prop.range;
14698
- if (name && topLevel) destructured.push({ name, at: range ? range[0] : 0 });
14699
- }
15320
+ async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], findings) {
15321
+ const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
15322
+ let envelope = await postTargeting(gateway, contextData);
15323
+ let warnings;
15324
+ if (findings && envelope?.errorCode === "CONTRACT_REJECTED") {
15325
+ envelope = await postTargeting(
15326
+ gateway,
15327
+ buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope)
15328
+ );
15329
+ warnings = ["QuikPilot's targeting ran without the early look's findings (the AI service did not accept them)."];
15330
+ }
15331
+ checkHardFailure(envelope, "pilot.targeting");
15332
+ const body = unwrapExecute(envelope, "pilot.targeting");
15333
+ const result = finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);
15334
+ return warnings ? { ...result, warnings } : result;
15335
+ }
15336
+ var CODE_LIKE = /^[A-Z0-9_]{1,40}$/;
15337
+ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], options = {}) {
15338
+ const mode = options.mode ?? resolveTargetingMode();
15339
+ const findings = prepareTargetingFindings(options.findings, new Set(workspaceListing), deniedPaths);
15340
+ if (mode !== "loop") {
15341
+ return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
15342
+ }
15343
+ const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
15344
+ let summary;
15345
+ let runtimeCode;
15346
+ let reason;
15347
+ try {
15348
+ const looped = await runTargetingLoop(
15349
+ { baseContext, listing: workspaceListing, deniedPaths },
15350
+ { ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
15351
+ );
15352
+ summary = looped.summary;
15353
+ const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
15354
+ return { ...result, loop: summary };
15355
+ } catch (err) {
15356
+ if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;
15357
+ if (err instanceof LoopFailure) {
15358
+ reason = err.reason;
15359
+ runtimeCode = err.runtimeCode;
15360
+ summary = err.summary ?? summary;
15361
+ } else {
15362
+ reason = "final_invalid";
14700
15363
  }
15364
+ }
15365
+ const fellBack = {
15366
+ turns: summary?.turns ?? 0,
15367
+ toolCalls: summary?.toolCalls ?? 0,
15368
+ readChars: summary?.readChars ?? 0,
15369
+ refused: summary?.refused ?? 0,
15370
+ reads: summary?.reads ?? [],
15371
+ stopReason: "fallback",
15372
+ fellBack: true,
15373
+ fallbackReason: reason
15374
+ };
15375
+ const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
15376
+ log({
15377
+ event: "targeting.loop_fallback",
15378
+ reason,
15379
+ turn: fellBack.turns,
15380
+ toolCalls: fellBack.toolCalls,
15381
+ ...runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}
15382
+ });
15383
+ const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
15384
+ return {
15385
+ ...single,
15386
+ loop: fellBack,
15387
+ warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`, ...single.warnings ?? []]
14701
15388
  };
14702
- for (const p of fn.params ?? []) visit(p, true);
14703
- return { names, destructured };
14704
15389
  }
14705
- function readsOf(site) {
14706
- const fn = site.node;
14707
- const { names: params, destructured } = parameters(fn);
14708
- const reads = [...destructured];
14709
- estraverse5.traverse(fn.body, {
14710
- fallback: "iteration",
14711
- enter(node, parent) {
14712
- const n = node;
14713
- if (isFunction(n)) {
14714
- const own = parameters(n).names;
14715
- const shadows = [...own].some((name) => params.has(name));
14716
- if (!isCallback({ node: n, parent }) || shadows) return estraverse5.VisitorOption.Skip;
14717
- }
14718
- const range = n.range;
14719
- const at2 = range ? range[0] : 0;
14720
- if (n.type === "MemberExpression") {
14721
- const object = n.object;
14722
- if (object.type !== "Identifier" || !params.has(object.name)) return;
14723
- const name = keyName(n.property, n.computed);
14724
- if (name) reads.push({ name, at: at2 });
14725
- } else if (n.type === "VariableDeclarator" && n.id.type === "ObjectPattern" && n.init) {
14726
- const init = n.init;
14727
- if (init.type !== "Identifier" || !params.has(init.name)) return;
14728
- for (const prop of n.id.properties ?? []) {
14729
- if (prop.type === "RestElement") continue;
14730
- const name = keyName(prop.key, prop.computed);
14731
- if (name) reads.push({ name, at: at2 });
14732
- }
14733
- }
15390
+
15391
+ // src/targetingRecord.ts
15392
+ var MAX_TARGETS = 25;
15393
+ var MAX_IDS_PER_TARGET = 50;
15394
+ var MAX_CONTEXT_PATHS = 20;
15395
+ var MAX_ADDED_PATHS = 20;
15396
+ var MAX_SKIPPED_CONTEXT = 20;
15397
+ var MAX_SKIPPED_CASES = 200;
15398
+ var MAX_CONTEXT_RECORDS = 25;
15399
+ var MAX_PATH_CHARS2 = 300;
15400
+ var MAX_ID_CHARS3 = 100;
15401
+ var MAX_REASON_CHARS = 300;
15402
+ var MAX_LOOP_READS = 50;
15403
+ var MAX_FALLBACK_REASON_CHARS = 40;
15404
+ function clampList(values, max, maxChars) {
15405
+ let cut = false;
15406
+ const kept = [];
15407
+ for (const raw of values ?? []) {
15408
+ const v = typeof raw === "string" ? raw.trim() : "";
15409
+ if (v.length === 0) continue;
15410
+ if (v.length > maxChars || kept.length >= max) {
15411
+ cut = true;
15412
+ continue;
14734
15413
  }
14735
- });
14736
- reads.sort((a, b) => a.at - b.at);
14737
- return reads;
15414
+ kept.push(v);
15415
+ }
15416
+ return { kept, cut };
14738
15417
  }
14739
- function wordsOf(text, into) {
14740
- for (const m of text.matchAll(/[\w$]+/g)) into.add(m[0]);
15418
+ function wholeNumber2(n) {
15419
+ return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
14741
15420
  }
14742
- function findUnsuppliedInputs(input) {
14743
- try {
14744
- const known = /* @__PURE__ */ new Set();
14745
- for (const file of input.corpus) {
14746
- if (!isTestFile(file.path)) wordsOf(file.text, known);
14747
- }
14748
- const judged = [];
14749
- const supplied = /* @__PURE__ */ new Set();
14750
- for (const file of input.changed) {
14751
- if (isTestFile(file.path) || !isCheckablePath(file.path)) continue;
14752
- const after = parseProgram(file.path, file.newContent);
14753
- if (!after) continue;
14754
- suppliedNames(after.ast, supplied);
14755
- judged.push({ file, ast: after.ast });
15421
+ function clampLoop(loop) {
15422
+ let cut = false;
15423
+ const reads = [];
15424
+ for (const r of loop.reads ?? []) {
15425
+ if (reads.length >= MAX_LOOP_READS) {
15426
+ cut = true;
15427
+ break;
14756
15428
  }
14757
- const found = [];
14758
- for (const { file, ast } of judged) {
14759
- for (const site of collectFunctions(ast)) {
14760
- if (isCallback(site)) continue;
14761
- const names = [];
14762
- for (const { name } of readsOf(site)) {
14763
- if (!IDENTIFIER_NAME.test(name) || name.length > MAX_NAME_CHARS) continue;
14764
- if (known.has(name) || supplied.has(name) || names.includes(name)) continue;
14765
- names.push(name);
14766
- }
14767
- if (names.length === 0) continue;
14768
- found.push({ file: file.path, function: nameOf(site).slice(0, MAX_FUNCTION_CHARS), names: names.slice(0, MAX_UNSUPPLIED_NAMES) });
14769
- if (found.length >= MAX_UNSUPPLIED_ENTRIES) return found;
14770
- }
15429
+ const path = typeof r.path === "string" ? r.path.trim() : "";
15430
+ if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
15431
+ cut = true;
15432
+ continue;
14771
15433
  }
14772
- return found;
14773
- } catch {
14774
- return [];
15434
+ reads.push({
15435
+ path,
15436
+ ...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
15437
+ ...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
15438
+ chars: wholeNumber2(r.chars),
15439
+ ...r.refused ? { refused: true } : {}
15440
+ });
14775
15441
  }
15442
+ const refusedTurns = clampRefusedTurns(loop.refusedTurns);
15443
+ if (refusedTurns.cut) cut = true;
15444
+ return {
15445
+ turns: wholeNumber2(loop.turns),
15446
+ toolCalls: wholeNumber2(loop.toolCalls),
15447
+ refused: wholeNumber2(loop.refused),
15448
+ stopReason: loop.stopReason,
15449
+ ...loop.fellBack ? { fellBack: true } : {},
15450
+ ...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {},
15451
+ reads,
15452
+ ...refusedTurns.rows.length > 0 ? { refusedTurns: refusedTurns.rows } : {},
15453
+ ...cut ? { truncated: true } : {}
15454
+ };
14776
15455
  }
14777
- var MAX_CORPUS_CHARS = 64e6;
14778
- function checkRunForUnsuppliedInputs(input) {
14779
- try {
14780
- const listed = new Set(input.listing);
14781
- const corpus = [];
14782
- let chars = 0;
14783
- for (const path of listed) {
14784
- const text = input.readText(path);
14785
- if (text === null) continue;
14786
- chars += text.length;
14787
- if (chars > MAX_CORPUS_CHARS) return [];
14788
- corpus.push({ path, text });
15456
+ function buildTargetingRecord(targeting, contextLog) {
15457
+ let truncated = false;
15458
+ const note = (cut) => {
15459
+ if (cut) truncated = true;
15460
+ };
15461
+ if (targeting.outcome === "NO_TARGET") {
15462
+ const record2 = { outcome: "NO_TARGET", targets: [], skippedCaseIds: [], codegenContext: [] };
15463
+ const reason = (targeting.reason ?? "").trim();
15464
+ if (reason.length > 0) {
15465
+ record2.noTargetReason = reason.slice(0, MAX_REASON_CHARS);
15466
+ if (reason.length > MAX_REASON_CHARS) record2.noTargetReasonTruncated = true;
14789
15467
  }
14790
- const changed = [];
14791
- for (const { targetPath, newContent } of input.results) {
14792
- if (listed.has(targetPath) && input.readText(targetPath) === null) continue;
14793
- changed.push({ path: targetPath, newContent });
15468
+ if (targeting.loop) record2.loop = clampLoop(targeting.loop);
15469
+ return record2;
15470
+ }
15471
+ const targets = [];
15472
+ for (const t of targeting.targets) {
15473
+ if (targets.length >= MAX_TARGETS) {
15474
+ truncated = true;
15475
+ break;
14794
15476
  }
14795
- return findUnsuppliedInputs({ changed, corpus });
14796
- } catch {
14797
- return [];
15477
+ const path = typeof t.path === "string" ? t.path.trim() : "";
15478
+ if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
15479
+ truncated = true;
15480
+ continue;
15481
+ }
15482
+ const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
15483
+ const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
15484
+ note(contextPaths.cut);
15485
+ note(automationIds.cut);
15486
+ targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });
14798
15487
  }
14799
- }
14800
- function describeUnsuppliedInputs(found) {
14801
- const many = found.length !== 1;
14802
- 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.`;
15488
+ const skipped = clampList(
15489
+ (targeting.skippedCases ?? []).map((c) => c.automationId),
15490
+ MAX_SKIPPED_CASES,
15491
+ MAX_ID_CHARS3
15492
+ );
15493
+ note(skipped.cut);
15494
+ const codegenContext = [];
15495
+ for (const entry of contextLog) {
15496
+ if (codegenContext.length >= MAX_CONTEXT_RECORDS) {
15497
+ truncated = true;
15498
+ break;
15499
+ }
15500
+ const targetPath = typeof entry.targetPath === "string" ? entry.targetPath.trim() : "";
15501
+ if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS2) {
15502
+ truncated = true;
15503
+ continue;
15504
+ }
15505
+ const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
15506
+ const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS2);
15507
+ const skippedPaths = clampList(
15508
+ (entry.skipped ?? []).map((s) => s.path),
15509
+ MAX_SKIPPED_CONTEXT,
15510
+ MAX_PATH_CHARS2
15511
+ );
15512
+ note(contextPaths.cut);
15513
+ note(addedPaths.cut);
15514
+ note(skippedPaths.cut);
15515
+ const reasonByPath = new Map((entry.skipped ?? []).map((s) => [s.path.trim(), s.reason]));
15516
+ codegenContext.push({
15517
+ targetPath,
15518
+ contextPaths: contextPaths.kept,
15519
+ addedPaths: addedPaths.kept,
15520
+ skipped: skippedPaths.kept.map((path) => ({ path, reason: String(reasonByPath.get(path) ?? "skipped").slice(0, 40) })),
15521
+ ...entry.retriedWithoutAdded ? { retriedWithoutAdded: true } : {}
15522
+ });
15523
+ }
15524
+ const record = {
15525
+ outcome: "TARGETED",
15526
+ targets,
15527
+ skippedCaseIds: skipped.kept,
15528
+ codegenContext
15529
+ };
15530
+ if (truncated) record.truncated = true;
15531
+ if (targeting.loop) record.loop = clampLoop(targeting.loop);
15532
+ return record;
14803
15533
  }
14804
15534
 
14805
- // src/unsuppliedInputsDisk.ts
14806
- var import_node_fs15 = require("node:fs");
14807
- var MAX_READ_BYTES = 1e6;
14808
- function readCheckoutText(path) {
14809
- try {
14810
- const info = (0, import_node_fs15.statSync)(path);
14811
- if (!info.isFile() || info.size > MAX_READ_BYTES) return null;
14812
- const bytes = (0, import_node_fs15.readFileSync)(path);
14813
- if (bytes.includes(0)) return null;
14814
- return bytes.toString("utf8");
14815
- } catch {
14816
- return null;
15535
+ // src/tokenExchange.ts
15536
+ async function exchangeForRunToken(tokenUrl, oidcToken) {
15537
+ const res = await fetch(tokenUrl, {
15538
+ method: "POST",
15539
+ headers: { Authorization: `Bearer ${oidcToken}` }
15540
+ });
15541
+ if (!res.ok) {
15542
+ throw new Error(`Exchange run token failed: ${await describeQuikTrackFailure(res)}`);
14817
15543
  }
14818
- }
14819
- function checkGeneratedCode(results) {
14820
- try {
14821
- return checkRunForUnsuppliedInputs({ results, listing: listFiles("."), readText: readCheckoutText });
14822
- } catch {
14823
- return [];
15544
+ const body = await res.json();
15545
+ if (body.success !== true) {
15546
+ throw new Error("Exchange run token failed: response did not carry success:true");
14824
15547
  }
15548
+ return body.data.runToken;
14825
15549
  }
14826
15550
 
14827
15551
  // src/run.ts
15552
+ var JOB_RESERVE_MS = 7 * 6e4;
15553
+ var HUNK_CHECK_MAX_MS = 6 * 6e4;
15554
+ var HUNK_CHECK_MIN_BUDGET_MS = 3 * 6e4;
15555
+ var HUNK_CHECK_END_BEFORE_STOP_MS = 2 * 6e4;
14828
15556
  async function run(env2) {
15557
+ const runStartedAt = Date.now();
14829
15558
  let hardFailure = false;
14830
15559
  let packet;
14831
15560
  let branch;
@@ -14846,6 +15575,7 @@ async function run(env2) {
14846
15575
  let baselineFindings;
14847
15576
  let vanishedTests;
14848
15577
  let unsuppliedInputs;
15578
+ let changesNoTestDependsOn;
14849
15579
  const contextLog = [];
14850
15580
  const codegenOut = {};
14851
15581
  try {
@@ -14921,105 +15651,113 @@ async function run(env2) {
14921
15651
  snapshot,
14922
15652
  durationMs: Date.now() - baselineStartedAt
14923
15653
  }));
14924
- const [timedBaseline, results] = await Promise.all([
14925
- baselineRun,
14926
- runCodegenStep({
14927
- mode: resolveCodegenMode(),
14928
- tests: {
14929
- root: process.cwd(),
14930
- command: packet.commands.test,
14931
- baseline: () => baselineRun.catch(() => null)
14932
- },
14933
- gateway: packet.gateway,
14934
- targets: targeting.targets,
14935
- workspaceListing,
14936
- requiredTests: packet.requiredTests,
14937
- deniedPaths: packet.guardrails.deniedPaths,
14938
- judgedByPool,
14939
- warnings,
14940
- contextLog,
14941
- outOfScope,
14942
- testDiscovery: packet.testDiscovery,
14943
- skippedCases: targeting.skippedCases ?? [],
14944
- out: codegenOut
14945
- })
14946
- ]);
15654
+ const codegenMode = resolveCodegenMode();
15655
+ const stepParams = {
15656
+ mode: codegenMode,
15657
+ tests: {
15658
+ root: process.cwd(),
15659
+ command: packet.commands.test,
15660
+ baseline: () => baselineRun.catch(() => null)
15661
+ },
15662
+ gateway: packet.gateway,
15663
+ targets: targeting.targets,
15664
+ workspaceListing,
15665
+ requiredTests: packet.requiredTests,
15666
+ deniedPaths: packet.guardrails.deniedPaths,
15667
+ judgedByPool,
15668
+ warnings,
15669
+ contextLog,
15670
+ outOfScope,
15671
+ testDiscovery: packet.testDiscovery,
15672
+ skippedCases: targeting.skippedCases ?? [],
15673
+ out: codegenOut
15674
+ };
15675
+ const writeStartedAt = Date.now();
15676
+ const [timedBaseline, results] = await Promise.all([baselineRun, runCodegenStep(stepParams)]);
15677
+ const lastAttemptMs = Date.now() - writeStartedAt;
14947
15678
  const baseline = timedBaseline.snapshot;
14948
15679
  generatedResults = results;
14949
- const depCheck = checkImportDependencies(
14950
- results,
14951
- readDeclaredDependencies(results, packet.workspaceRoot),
14952
- resolveAliasPrefixes(results, packet.workspaceRoot)
14953
- );
14954
- if (depCheck.blocked) {
14955
- throw new Error(
14956
- `QuikPilot's generated code imports packages this repository doesn't have \u2014 ${describeDependencyViolations(depCheck)}`
14957
- );
14958
- }
14959
- const scopeCheck = checkApiScope(results, targeting.targets, packet.design?.apiChanges ?? []);
14960
- if (scopeCheck.blocked) {
14961
- throw new Error(
14962
- `QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`
14963
- );
14964
- }
14965
- const placementCheck = checkTestPlacement(targeting.targets, baseline.discoveredFiles);
14966
- if (placementCheck.blocked) {
14967
- throw new Error(
14968
- `QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`
14969
- );
14970
- }
15680
+ const verifyCtx = {
15681
+ packet,
15682
+ targets: targeting.targets,
15683
+ baseline,
15684
+ requiredAutomationIds: claimedAutomationIds(stepParams)
15685
+ };
15686
+ const jobStopAtMs = runStartedAt + packet.guardrails.maxWallClockMinutes * 6e4 - JOB_RESERVE_MS;
15687
+ const healCalls = [];
15688
+ let healStop;
15689
+ let fixed;
14971
15690
  try {
14972
- const baselineCheck = await runBaselineCheck({
14973
- targets: targeting.targets,
14974
- results,
14975
- testFileCmd: packet.commands.testFile,
14976
- requiredTestTypes: packet.requiredTestTypes
15691
+ fixed = await runVerifyAndFix({
15692
+ firstResults: results,
15693
+ attemptsRun: codegenOut.loop?.attempts?.length ?? 1,
15694
+ mode: codegenMode,
15695
+ setting: packet.guardrails.maxHealIterations,
15696
+ now: Date.now,
15697
+ jobStopAtMs,
15698
+ lastAttemptMs,
15699
+ verify: (r, undoable) => verifyChange(verifyCtx, r, undoable),
15700
+ heal: async ({ results: kept, answer, attempt: attempt2, hardStopAtMs }) => {
15701
+ const out = {};
15702
+ try {
15703
+ return await runHealAttempt({ step: stepParams, results: kept, answer, attempt: attempt2, hardStopAtMs, out });
15704
+ } finally {
15705
+ healCalls.push({ ...out.summary ? { summary: out.summary } : {}, ...out.failure ? { failureReason: out.failure.reason } : {} });
15706
+ }
15707
+ },
15708
+ log: (e) => console.log(JSON.stringify(e)),
15709
+ onStop: (stop) => {
15710
+ healStop = stop;
15711
+ }
14977
15712
  });
14978
- warnings.push(...baselineCheck.warnings);
14979
- baselineFindings = baselineCheck.findings ?? void 0;
14980
15713
  } catch (err) {
14981
- const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;
14982
- console.error(message);
14983
- warnings.push(message);
14984
- }
14985
- try {
14986
- const unsupplied = checkGeneratedCode(results);
14987
- if (unsupplied.length > 0) {
14988
- unsuppliedInputs = unsupplied;
14989
- const w = describeUnsuppliedInputs(unsupplied);
14990
- warnings.push(w);
14991
- console.warn(`QuikPilot code warning (not blocking): ${w}`);
15714
+ if (healStop && codegenOut.loop) codegenOut.loop = mergeHealRecord(codegenOut.loop, { stop: healStop, allowed: 0, made: healCalls.length, attempts: [] }, healCalls);
15715
+ throw err;
15716
+ }
15717
+ generatedResults = fixed.results;
15718
+ const final = fixed.outcome;
15719
+ warnings.push(...final.warnings);
15720
+ baselineFindings = final.outputs.baselineFindings;
15721
+ unsuppliedInputs = final.outputs.unsuppliedInputs;
15722
+ generatedFilePaths = final.outputs.generatedFilePaths;
15723
+ finalTestReport = final.outputs.finalTestReport;
15724
+ vanishedTests = final.outputs.vanishedTests;
15725
+ if (fixed.heal && codegenMode === "loop-tests") codegenOut.loop = mergeHealRecord(codegenOut.loop, fixed.heal, healCalls);
15726
+ if (!final.ok) {
15727
+ const suffix = healFailureSuffix(fixed.heal);
15728
+ throw suffix ? new Error(`${final.error.message}${suffix}`) : final.error;
15729
+ }
15730
+ if (codegenMode === "loop-tests" && process.env.QUIKPILOT_HUNK_CHECK?.trim().toLowerCase() !== "off") {
15731
+ const deadlineAtMs = Math.min(jobStopAtMs - HUNK_CHECK_END_BEFORE_STOP_MS, Date.now() + HUNK_CHECK_MAX_MS);
15732
+ if (deadlineAtMs - Date.now() >= HUNK_CHECK_MIN_BUDGET_MS) {
15733
+ try {
15734
+ const files = collectHunkCheckFiles(fixed.results, process.cwd());
15735
+ if (files.length > 0) {
15736
+ const checked = await runHunkCheck({
15737
+ root: process.cwd(),
15738
+ command: packet.commands.test,
15739
+ baseline,
15740
+ baselineMs: timedBaseline.durationMs,
15741
+ finalTestCount: final.outputs.testCount ?? 0,
15742
+ files,
15743
+ deadlineAtMs,
15744
+ log: (e) => console.log(JSON.stringify(e))
15745
+ });
15746
+ console.log(JSON.stringify({ event: "hunk_check", checked: checked.checked, total: checked.total, flagged: checked.unnecessary.length, skipped: checked.skipped, stopped: checked.stopped ?? null }));
15747
+ changesNoTestDependsOn = toFinding(checked);
15748
+ if (checked.unnecessary.length > 0) {
15749
+ const w = describeHunkCheck(checked);
15750
+ warnings.push(w);
15751
+ console.warn(`QuikPilot change warning (not blocking): ${w}`);
15752
+ }
15753
+ }
15754
+ } catch (err) {
15755
+ if (err instanceof TreeNotRestoredError) throw err;
15756
+ const message = `The check for changes no test depends on could not run: ${err instanceof Error ? err.message : String(err)}`;
15757
+ console.error(message);
15758
+ warnings.push(message);
15759
+ }
14992
15760
  }
14993
- } catch (err) {
14994
- console.error(`Unsupplied-input check could not run (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14995
- }
14996
- generatedFilePaths = results.map((r) => r.targetPath);
14997
- flushCodegenResults(results);
14998
- try {
14999
- runCommand(packet.commands.format, "Format");
15000
- } catch (err) {
15001
- console.error(`Format failed (not blocking): ${err instanceof Error ? err.message : String(err)}`);
15002
- }
15003
- runCommand(packet.commands.lint, "Lint");
15004
- const after = captureTestSnapshot(packet.commands.test);
15005
- finalTestReport = readTestReportBytes();
15006
- vanishedTests = findVanishedTests(baseline, after) ?? void 0;
15007
- if (vanishedTests) {
15008
- const w = describeVanishedTests(vanishedTests);
15009
- warnings.push(w);
15010
- console.warn(`QuikPilot test warning (not blocking): ${w}`);
15011
- }
15012
- const check = checkForRegressions(baseline, after);
15013
- if (check.blocked) {
15014
- throw new Error(
15015
- `QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`
15016
- );
15017
- }
15018
- const coverageCheck = checkAutomationIdCoverage(targeting.targets, after.discoveredAutomationIds);
15019
- if (coverageCheck.blocked) {
15020
- throw new Error(
15021
- `QuikPilot's generated tests were not executed \u2014 ${describeAutomationCoverageViolations(coverageCheck)}`
15022
- );
15023
15761
  }
15024
15762
  }
15025
15763
  } catch (err) {
@@ -15091,6 +15829,7 @@ async function run(env2) {
15091
15829
  baselineFindings,
15092
15830
  vanishedTests,
15093
15831
  unsuppliedInputs,
15832
+ changesNoTestDependsOn,
15094
15833
  codegenLoop: codegenOut.loop,
15095
15834
  unresolved: failureReasons.length > 0 ? failureReasons : void 0
15096
15835
  });