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

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