@quikit/quikpilot-runner 9.3.0-rc.13 → 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.13" : "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,615 +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/targetingMode.ts
14190
- var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
14191
- function parse5(value) {
14192
- if (typeof value !== "string") return null;
14193
- const v = value.trim().toLowerCase();
14194
- if (v === "loop") return "loop";
14195
- if (v === "single") return "single";
14196
- return null;
14197
- }
14198
- function resolveTargetingMode(env2 = process.env, packetSetting) {
14199
- const fromSetting = parse5(packetSetting);
14200
- if (fromSetting) return fromSetting;
14201
- return parse5(env2[TARGETING_MODE_ENV]) ?? "single";
14202
- }
14203
-
14204
- // src/targeting.ts
14205
- var CONTRACT_VERSION2 = "test-targets-1";
14206
- function listWorkspaceFiles(workspaceRoot) {
14207
- return listFiles(workspaceRoot ?? ".");
14208
- }
14209
- function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
14210
- const denied = matchesDeniedPath(target.path, deniedPaths);
14211
- if (denied) {
14212
- throw new DeniedPathError(
14213
- `pilot.targeting proposed a target matching a denied path (${denied}): ${target.path}`
14214
- );
14215
- }
14216
- const deniedContext = findDeniedContextPath(target.contextPaths ?? [], deniedPaths);
14217
- if (deniedContext) {
14218
- throw new DeniedPathError(
14219
- `pilot.targeting cited a denied path as context (${deniedContext.pattern}): ${deniedContext.path} (target ${target.path})`
14220
- );
14221
- }
14222
- if (target.kind !== "EXISTING" && target.kind !== "NEW_FILE") {
14223
- throw new Error(`pilot.targeting returned an unknown kind "${target.kind}" for ${target.path}`);
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;
14224
14427
  }
14225
- if (target.kind === "EXISTING") {
14226
- if (!workspaceListing.has(target.path)) {
14227
- throw new Error(
14228
- `pilot.targeting named an EXISTING file not found in the checkout: ${target.path}`
14229
- );
14428
+ return false;
14429
+ }
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 });
14230
14438
  }
14231
- return;
14232
- }
14233
- const root = (0, import_node_path13.resolve)(workspaceRoot ?? ".");
14234
- const rel = (0, import_node_path13.relative)(root, (0, import_node_path13.resolve)(target.path));
14235
- if (rel.startsWith("..") || (0, import_node_path13.isAbsolute)(rel)) {
14236
- throw new Error(
14237
- `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
14238
- );
14239
14439
  }
14440
+ return { blocked: violations.length > 0, violations };
14240
14441
  }
14241
- function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope) {
14242
- const contextData = {
14243
- // NESTED, NOT FLATTENED — a second vocabulary for the design shape is exactly what
14244
- // QUIKTR-1034 cost.
14245
- workspaceListing,
14246
- design,
14247
- // QUIKTR-1065/1083 — requiredTests carried through so targeting can propose a test-file
14248
- // target naming which cases it covers (§15.1's Case shape, unchanged).
14249
- requiredTests,
14250
- // QUIKTR-1083 (§15.6) — required on the versioned path.
14251
- contractVersion: CONTRACT_VERSION2
14252
- };
14253
- if (deniedPaths.length > 0) {
14254
- contextData.deniedPaths = deniedPaths;
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: [] };
14255
14450
  }
14256
- if (outOfScope.length > 0) {
14257
- contextData.outOfScope = outOfScope;
14451
+ const claimed = /* @__PURE__ */ new Set();
14452
+ for (const target of targets) {
14453
+ for (const id of target.automationIds ?? []) claimed.add(id);
14258
14454
  }
14259
- contextData.testDiscovery = testDiscovery;
14260
- return contextData;
14455
+ const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));
14456
+ return { blocked: missing.length > 0, missing };
14261
14457
  }
14262
- async function postTargeting(gateway, contextData, signal) {
14263
- const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
14264
- method: "POST",
14265
- headers: { "content-type": "application/json", "x-run-token": gateway.token },
14266
- body: JSON.stringify({
14267
- appId: "quiktrack",
14268
- useCase: "pilot.targeting",
14269
- expectedOutputType: "json",
14270
- userPrompt: "",
14271
- contextData
14272
- }),
14273
- ...signal ? { signal } : {}
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`;
14460
+ }
14461
+
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);
14472
+ }
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
+ }
14274
14480
  });
14275
- if (!res.ok) {
14276
- throw new TargetingHttpError(res.status, res.statusText);
14277
- }
14278
- return res.json();
14481
+ return out;
14279
14482
  }
14280
- function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
14281
- if (body.outcome === "NO_TARGET") {
14282
- return { outcome: "NO_TARGET", reason: body.noTargetReason ?? null };
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;
14283
14493
  }
14284
- if (body.outcome !== "TARGETED" || !Array.isArray(body.targets)) {
14285
- throw new RuntimeReplyError(
14286
- `pilot.targeting returned an unexpected shape: ${JSON.stringify(body)}`,
14287
- "pilot.targeting returned an unexpected shape"
14288
- );
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)";
14289
14500
  }
14290
- const listing = new Set(workspaceListing);
14291
- for (const target of body.targets) {
14292
- validateTarget(target, workspaceRoot, listing, deniedPaths);
14501
+ if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
14502
+ return keyName(parent.key, parent.computed) ?? "(anonymous)";
14293
14503
  }
14294
- const correctedKinds = [];
14295
- const targets = body.targets.map((target) => {
14296
- if (target.kind === "NEW_FILE" && listing.has(target.path)) {
14297
- correctedKinds.push(target.path);
14298
- return { ...target, kind: "EXISTING" };
14299
- }
14300
- return target;
14301
- });
14302
- return {
14303
- outcome: "TARGETED",
14304
- targets,
14305
- skippedCases: body.skippedCases ?? [],
14306
- ...correctedKinds.length > 0 ? { correctedKinds } : {}
14307
- };
14504
+ return "(anonymous)";
14308
14505
  }
14309
- async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = []) {
14310
- const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
14311
- const envelope = await postTargeting(gateway, contextData);
14312
- checkHardFailure(envelope, "pilot.targeting");
14313
- const body = unwrapExecute(envelope, "pilot.targeting");
14314
- return finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths);
14506
+ function isCallback({ node, parent }) {
14507
+ if (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
14508
+ return (parent.arguments ?? []).includes(node);
14315
14509
  }
14316
- var CODE_LIKE = /^[A-Z0-9_]{1,40}$/;
14317
- async function runTargeting(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], options = {}) {
14318
- const mode = options.mode ?? resolveTargetingMode();
14319
- if (mode !== "loop") {
14320
- return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
14321
- }
14322
- const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
14323
- let summary;
14324
- let runtimeCode;
14325
- let reason;
14326
- try {
14327
- const looped = await runTargetingLoop(
14328
- { baseContext, listing: workspaceListing, deniedPaths },
14329
- { ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
14330
- );
14331
- summary = looped.summary;
14332
- const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
14333
- return { ...result, loop: summary };
14334
- } catch (err) {
14335
- if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;
14336
- if (err instanceof LoopFailure) {
14337
- reason = err.reason;
14338
- runtimeCode = err.runtimeCode;
14339
- summary = err.summary ?? summary;
14340
- } else {
14341
- reason = "final_invalid";
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
+ }
14342
14526
  }
14343
- }
14344
- const fellBack = {
14345
- turns: summary?.turns ?? 0,
14346
- toolCalls: summary?.toolCalls ?? 0,
14347
- readChars: summary?.readChars ?? 0,
14348
- refused: summary?.refused ?? 0,
14349
- reads: summary?.reads ?? [],
14350
- stopReason: "fallback",
14351
- fellBack: true,
14352
- fallbackReason: reason
14353
- };
14354
- const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
14355
- log({
14356
- event: "targeting.loop_fallback",
14357
- reason,
14358
- turn: fellBack.turns,
14359
- toolCalls: fellBack.toolCalls,
14360
- ...runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}
14361
14527
  });
14362
- const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope);
14363
- return {
14364
- ...single,
14365
- loop: fellBack,
14366
- warnings: [`QuikPilot's read-only targeting could not complete (${reason}); standard targeting was used instead.`]
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
+ }
14367
14545
  };
14546
+ for (const p of fn.params ?? []) visit(p, true);
14547
+ return { names, destructured };
14368
14548
  }
14369
-
14370
- // src/targetingRecord.ts
14371
- var MAX_TARGETS = 25;
14372
- var MAX_IDS_PER_TARGET = 50;
14373
- var MAX_CONTEXT_PATHS = 20;
14374
- var MAX_ADDED_PATHS = 20;
14375
- var MAX_SKIPPED_CONTEXT = 20;
14376
- var MAX_SKIPPED_CASES = 200;
14377
- var MAX_CONTEXT_RECORDS = 25;
14378
- var MAX_PATH_CHARS2 = 300;
14379
- var MAX_ID_CHARS3 = 100;
14380
- var MAX_REASON_CHARS = 300;
14381
- var MAX_LOOP_READS = 50;
14382
- var MAX_FALLBACK_REASON_CHARS = 40;
14383
- function clampList(values, max, maxChars) {
14384
- let cut = false;
14385
- const kept = [];
14386
- for (const raw of values ?? []) {
14387
- const v = typeof raw === "string" ? raw.trim() : "";
14388
- if (v.length === 0) continue;
14389
- if (v.length > maxChars || kept.length >= max) {
14390
- cut = true;
14391
- continue;
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
+ }
14392
14578
  }
14393
- kept.push(v);
14394
- }
14395
- return { kept, cut };
14579
+ });
14580
+ reads.sort((a, b) => a.at - b.at);
14581
+ return reads;
14396
14582
  }
14397
- function wholeNumber2(n) {
14398
- return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
14583
+ function wordsOf(text, into) {
14584
+ for (const m of text.matchAll(/[\w$]+/g)) into.add(m[0]);
14399
14585
  }
14400
- function clampLoop(loop) {
14401
- let cut = false;
14402
- const reads = [];
14403
- for (const r of loop.reads ?? []) {
14404
- if (reads.length >= MAX_LOOP_READS) {
14405
- cut = true;
14406
- break;
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);
14407
14591
  }
14408
- const path = typeof r.path === "string" ? r.path.trim() : "";
14409
- if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
14410
- cut = true;
14411
- continue;
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 });
14412
14600
  }
14413
- reads.push({
14414
- path,
14415
- ...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
14416
- ...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
14417
- chars: wholeNumber2(r.chars),
14418
- ...r.refused ? { refused: true } : {}
14419
- });
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 [];
14420
14619
  }
14421
- const refusedTurns = clampRefusedTurns(loop.refusedTurns);
14422
- if (refusedTurns.cut) cut = true;
14423
- return {
14424
- turns: wholeNumber2(loop.turns),
14425
- toolCalls: wholeNumber2(loop.toolCalls),
14426
- refused: wholeNumber2(loop.refused),
14427
- stopReason: loop.stopReason,
14428
- ...loop.fellBack ? { fellBack: true } : {},
14429
- ...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {},
14430
- reads,
14431
- ...refusedTurns.rows.length > 0 ? { refusedTurns: refusedTurns.rows } : {},
14432
- ...cut ? { truncated: true } : {}
14433
- };
14434
14620
  }
14435
- function buildTargetingRecord(targeting, contextLog) {
14436
- let truncated = false;
14437
- const note = (cut) => {
14438
- if (cut) truncated = true;
14439
- };
14440
- if (targeting.outcome === "NO_TARGET") {
14441
- const record2 = { outcome: "NO_TARGET", targets: [], skippedCaseIds: [], codegenContext: [] };
14442
- const reason = (targeting.reason ?? "").trim();
14443
- if (reason.length > 0) {
14444
- record2.noTargetReason = reason.slice(0, MAX_REASON_CHARS);
14445
- if (reason.length > MAX_REASON_CHARS) record2.noTargetReasonTruncated = true;
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 });
14446
14633
  }
14447
- if (targeting.loop) record2.loop = clampLoop(targeting.loop);
14448
- return record2;
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 [];
14449
14642
  }
14450
- const targets = [];
14451
- for (const t of targeting.targets) {
14452
- if (targets.length >= MAX_TARGETS) {
14453
- truncated = true;
14454
- break;
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;
14661
+ }
14662
+ }
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
14707
+ });
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);
14455
14738
  }
14456
- const path = typeof t.path === "string" ? t.path.trim() : "";
14457
- if (path.length === 0 || path.length > MAX_PATH_CHARS2) {
14458
- truncated = true;
14459
- continue;
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);
14460
14759
  }
14461
- const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
14462
- const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
14463
- note(contextPaths.cut);
14464
- note(automationIds.cut);
14465
- targets.push({ path, kind: t.kind, contextPaths: contextPaths.kept, automationIds: automationIds.kept });
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)));
14466
14794
  }
14467
- const skipped = clampList(
14468
- (targeting.skippedCases ?? []).map((c) => c.automationId),
14469
- MAX_SKIPPED_CASES,
14470
- MAX_ID_CHARS3
14795
+ return { ok: true, warnings, gateMs: flushedAt === null ? 0 : now() - flushedAt, undo, outputs };
14796
+ }
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")}`);
14805
+ }
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)}`);
14816
+ }
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");
14820
+ }
14821
+ return body.data.token;
14822
+ }
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
14471
14830
  );
14472
- note(skipped.cut);
14473
- const codegenContext = [];
14474
- for (const entry of contextLog) {
14475
- if (codegenContext.length >= MAX_CONTEXT_RECORDS) {
14476
- truncated = true;
14477
- break;
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}`);
14842
+ }
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;
14848
+ }
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)}`);
14858
+ }
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 };
14891
+ try {
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) });
14478
14906
  }
14479
- const targetPath = typeof entry.targetPath === "string" ? entry.targetPath.trim() : "";
14480
- if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS2) {
14481
- truncated = true;
14482
- continue;
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
+ }
14483
14915
  }
14484
- const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS2);
14485
- const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS2);
14486
- const skippedPaths = clampList(
14487
- (entry.skipped ?? []).map((s) => s.path),
14488
- MAX_SKIPPED_CONTEXT,
14489
- MAX_PATH_CHARS2
14490
- );
14491
- note(contextPaths.cut);
14492
- note(addedPaths.cut);
14493
- note(skippedPaths.cut);
14494
- const reasonByPath = new Map((entry.skipped ?? []).map((s) => [s.path.trim(), s.reason]));
14495
- codegenContext.push({
14496
- targetPath,
14497
- contextPaths: contextPaths.kept,
14498
- addedPaths: addedPaths.kept,
14499
- skipped: skippedPaths.kept.map((path) => ({ path, reason: String(reasonByPath.get(path) ?? "skipped").slice(0, 40) })),
14500
- ...entry.retriedWithoutAdded ? { retriedWithoutAdded: true } : {}
14501
- });
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 };
14502
14937
  }
14503
- const record = {
14504
- outcome: "TARGETED",
14505
- targets,
14506
- skippedCaseIds: skipped.kept,
14507
- codegenContext
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)
14954
+ };
14955
+ if (kept.files.length === 0 && kept.callPath.length === 0 && kept.evidence.length === 0) return void 0;
14956
+ return {
14957
+ verdict,
14958
+ ...kept,
14959
+ searches: Array.isArray(searches) ? searches.filter((s) => typeof s === "string") : [],
14960
+ openQuestions: []
14508
14961
  };
14509
- if (truncated) record.truncated = true;
14510
- if (targeting.loop) record.loop = clampLoop(targeting.loop);
14511
- return record;
14512
14962
  }
14513
14963
 
14514
- // src/testPlacementCheck.ts
14515
- function isDiscovered(targetPath, discoveredFiles) {
14516
- const normalized = targetPath.replace(/\\/g, "/");
14517
- for (const candidate of discoveredFiles) {
14518
- if (candidate === normalized) return true;
14519
- if (candidate.endsWith(normalized) || normalized.endsWith(candidate)) return true;
14520
- }
14521
- return false;
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;
14522
14972
  }
14523
- function checkTestPlacement(targets, discoveredFiles) {
14524
- if (!discoveredFiles || discoveredFiles.size === 0) return { blocked: false, violations: [] };
14525
- const violations = [];
14526
- for (const target of targets) {
14527
- if (target.kind !== "EXISTING") continue;
14528
- if (!target.automationIds || target.automationIds.length === 0) continue;
14529
- if (!isDiscovered(target.path, discoveredFiles)) {
14530
- violations.push({ file: target.path, automationIds: target.automationIds });
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";
14977
+ }
14978
+
14979
+ // src/targeting.ts
14980
+ var CONTRACT_VERSION2 = "test-targets-1";
14981
+ function listWorkspaceFiles(workspaceRoot) {
14982
+ return listFiles(workspaceRoot ?? ".");
14983
+ }
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
+ );
14990
+ }
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})`
14995
+ );
14996
+ }
14997
+ if (target.kind !== "EXISTING" && target.kind !== "NEW_FILE") {
14998
+ throw new Error(`pilot.targeting returned an unknown kind "${target.kind}" for ${target.path}`);
14999
+ }
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
+ );
14531
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
+ );
14532
15014
  }
14533
- return { blocked: violations.length > 0, violations };
14534
- }
14535
- function describeTestPlacementViolations(check) {
14536
- return check.violations.map(
14537
- (v) => `${v.file} claims test case(s) ${v.automationIds.join(", ")} but the repository's own test runner never discovered this file`
14538
- ).join("; ");
14539
15015
  }
14540
- function checkAutomationIdCoverage(targets, discoveredAutomationIds) {
14541
- if (discoveredAutomationIds === null || discoveredAutomationIds === void 0) {
14542
- 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;
14543
15030
  }
14544
- const claimed = /* @__PURE__ */ new Set();
14545
- for (const target of targets) {
14546
- for (const id of target.automationIds ?? []) claimed.add(id);
15031
+ if (outOfScope.length > 0) {
15032
+ contextData.outOfScope = outOfScope;
14547
15033
  }
14548
- const missing = [...claimed].filter((id) => !discoveredAutomationIds.has(id));
14549
- return { blocked: missing.length > 0, missing };
14550
- }
14551
- function describeAutomationCoverageViolations(check) {
14552
- 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;
14553
15039
  }
14554
-
14555
- // src/tokenExchange.ts
14556
- async function exchangeForRunToken(tokenUrl, oidcToken) {
14557
- const res = await fetch(tokenUrl, {
15040
+ async function postTargeting(gateway, contextData, signal) {
15041
+ const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
14558
15042
  method: "POST",
14559
- 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 } : {}
14560
15052
  });
14561
15053
  if (!res.ok) {
14562
- throw new Error(`Exchange run token failed: ${await describeQuikTrackFailure(res)}`);
14563
- }
14564
- const body = await res.json();
14565
- if (body.success !== true) {
14566
- throw new Error("Exchange run token failed: response did not carry success:true");
15054
+ throw new TargetingHttpError(res.status, res.statusText);
14567
15055
  }
14568
- return body.data.runToken;
14569
- }
14570
-
14571
- // src/vanishedTests.ts
14572
- var MAX_VANISHED_NAMES = 50;
14573
- function findVanishedTests(baseline, after) {
14574
- if (!baseline.results || !after.results) return null;
14575
- const missing = [...baseline.results.keys()].filter((id) => !after.results.has(id));
14576
- if (missing.length === 0) return null;
14577
- return { names: missing.slice(0, MAX_VANISHED_NAMES), total: missing.length };
14578
- }
14579
- function describeVanishedTests(vanished) {
14580
- const noun = vanished.total === 1 ? "1 test" : `${vanished.total} tests`;
14581
- return `${noun} that ran before this change ${vanished.total === 1 ? "is" : "are"} missing from the final test report; the pull request lists ${vanished.total === 1 ? "it" : "them"}.`;
14582
- }
14583
-
14584
- // src/unsuppliedInputs.ts
14585
- var estraverse5 = __toESM(require_estraverse());
14586
- var MAX_UNSUPPLIED_ENTRIES = 10;
14587
- var MAX_UNSUPPLIED_NAMES = 5;
14588
- var MAX_NAME_CHARS = 80;
14589
- var MAX_FUNCTION_CHARS = 120;
14590
- var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
14591
- var IDENTIFIER_NAME = /^[A-Za-z_$][\w$]*$/;
14592
- function isFunction(node) {
14593
- return FUNCTION_TYPES.has(node.type);
14594
- }
14595
- function collectFunctions(ast) {
14596
- const out = [];
14597
- estraverse5.traverse(ast, {
14598
- fallback: "iteration",
14599
- enter(node, parent) {
14600
- if (isFunction(node)) out.push({ node, parent: parent ?? null });
14601
- }
14602
- });
14603
- return out;
14604
- }
14605
- function keyName(key, computed) {
14606
- if (!key) return null;
14607
- if (key.type === "Literal" && typeof key.value === "string") return key.value;
14608
- if (key.type === "Identifier" && !computed) return key.name;
14609
- return null;
15056
+ return res.json();
14610
15057
  }
14611
- function nameOf({ node, parent }) {
14612
- if (node.type === "FunctionDeclaration" || node.type === "FunctionExpression") {
14613
- const id = node.id;
14614
- if (id?.name) return id.name;
15058
+ function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
15059
+ if (body.outcome === "NO_TARGET") {
15060
+ return { outcome: "NO_TARGET", reason: body.noTargetReason ?? null };
14615
15061
  }
14616
- if (!parent) return "(anonymous)";
14617
- if (parent.type === "VariableDeclarator" && parent.id.type === "Identifier") return parent.id.name;
14618
- if (parent.type === "AssignmentExpression") {
14619
- const left = parent.left;
14620
- if (left.type === "Identifier") return left.name;
14621
- if (left.type === "MemberExpression") return keyName(left.property, left.computed) ?? "(anonymous)";
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
+ );
14622
15067
  }
14623
- if (parent.type === "Property" || parent.type === "MethodDefinition" || parent.type === "PropertyDefinition") {
14624
- 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);
14625
15071
  }
14626
- return "(anonymous)";
14627
- }
14628
- function isCallback({ node, parent }) {
14629
- if (!parent || parent.type !== "CallExpression" && parent.type !== "NewExpression") return false;
14630
- return (parent.arguments ?? []).includes(node);
14631
- }
14632
- function suppliedNames(ast, into) {
14633
- estraverse5.traverse(ast, {
14634
- fallback: "iteration",
14635
- enter(node) {
14636
- const n = node;
14637
- if (n.type === "ObjectExpression") {
14638
- for (const prop of n.properties ?? []) {
14639
- if (prop.type !== "Property") continue;
14640
- const name = keyName(prop.key, prop.computed);
14641
- if (name) into.add(name);
14642
- }
14643
- } else if (n.type === "AssignmentExpression" && n.left.type === "MemberExpression") {
14644
- const left = n.left;
14645
- const name = keyName(left.property, left.computed);
14646
- if (name) into.add(name);
14647
- }
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" };
14648
15077
  }
15078
+ return target;
14649
15079
  });
15080
+ return {
15081
+ outcome: "TARGETED",
15082
+ targets,
15083
+ skippedCases: body.skippedCases ?? [],
15084
+ ...correctedKinds.length > 0 ? { correctedKinds } : {}
15085
+ };
14650
15086
  }
14651
- function parameters(fn) {
14652
- const names = /* @__PURE__ */ new Set();
14653
- const destructured = [];
14654
- const visit = (p, topLevel) => {
14655
- if (!p) return;
14656
- if (p.type === "Identifier") names.add(p.name);
14657
- else if (p.type === "AssignmentPattern") visit(p.left, topLevel);
14658
- else if (p.type === "RestElement") visit(p.argument, topLevel);
14659
- else if (p.type === "ObjectPattern") {
14660
- for (const prop of p.properties ?? []) {
14661
- if (prop.type === "RestElement") continue;
14662
- const name = keyName(prop.key, prop.computed);
14663
- const range = prop.range;
14664
- if (name && topLevel) destructured.push({ name, at: range ? range[0] : 0 });
14665
- }
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";
14666
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 ?? []]
14667
15155
  };
14668
- for (const p of fn.params ?? []) visit(p, true);
14669
- return { names, destructured };
14670
15156
  }
14671
- function readsOf(site) {
14672
- const fn = site.node;
14673
- const { names: params, destructured } = parameters(fn);
14674
- const reads = [...destructured];
14675
- estraverse5.traverse(fn.body, {
14676
- fallback: "iteration",
14677
- enter(node, parent) {
14678
- const n = node;
14679
- if (isFunction(n)) {
14680
- const own = parameters(n).names;
14681
- const shadows = [...own].some((name) => params.has(name));
14682
- if (!isCallback({ node: n, parent }) || shadows) return estraverse5.VisitorOption.Skip;
14683
- }
14684
- const range = n.range;
14685
- const at2 = range ? range[0] : 0;
14686
- if (n.type === "MemberExpression") {
14687
- const object = n.object;
14688
- if (object.type !== "Identifier" || !params.has(object.name)) return;
14689
- const name = keyName(n.property, n.computed);
14690
- if (name) reads.push({ name, at: at2 });
14691
- } else if (n.type === "VariableDeclarator" && n.id.type === "ObjectPattern" && n.init) {
14692
- const init = n.init;
14693
- if (init.type !== "Identifier" || !params.has(init.name)) return;
14694
- for (const prop of n.id.properties ?? []) {
14695
- if (prop.type === "RestElement") continue;
14696
- const name = keyName(prop.key, prop.computed);
14697
- if (name) reads.push({ name, at: at2 });
14698
- }
14699
- }
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;
14700
15180
  }
14701
- });
14702
- reads.sort((a, b) => a.at - b.at);
14703
- return reads;
15181
+ kept.push(v);
15182
+ }
15183
+ return { kept, cut };
14704
15184
  }
14705
- function wordsOf(text, into) {
14706
- 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;
14707
15187
  }
14708
- function findUnsuppliedInputs(input) {
14709
- try {
14710
- const known = /* @__PURE__ */ new Set();
14711
- for (const file of input.corpus) {
14712
- if (!isTestFile(file.path)) wordsOf(file.text, known);
14713
- }
14714
- const judged = [];
14715
- const supplied = /* @__PURE__ */ new Set();
14716
- for (const file of input.changed) {
14717
- if (isTestFile(file.path) || !isCheckablePath(file.path)) continue;
14718
- const after = parseProgram(file.path, file.newContent);
14719
- if (!after) continue;
14720
- suppliedNames(after.ast, supplied);
14721
- judged.push({ file, ast: after.ast });
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;
14722
15195
  }
14723
- const found = [];
14724
- for (const { file, ast } of judged) {
14725
- for (const site of collectFunctions(ast)) {
14726
- if (isCallback(site)) continue;
14727
- const names = [];
14728
- for (const { name } of readsOf(site)) {
14729
- if (!IDENTIFIER_NAME.test(name) || name.length > MAX_NAME_CHARS) continue;
14730
- if (known.has(name) || supplied.has(name) || names.includes(name)) continue;
14731
- names.push(name);
14732
- }
14733
- if (names.length === 0) continue;
14734
- found.push({ file: file.path, function: nameOf(site).slice(0, MAX_FUNCTION_CHARS), names: names.slice(0, MAX_UNSUPPLIED_NAMES) });
14735
- if (found.length >= MAX_UNSUPPLIED_ENTRIES) return found;
14736
- }
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;
14737
15200
  }
14738
- return found;
14739
- } catch {
14740
- 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
+ });
14741
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
+ };
14742
15222
  }
14743
- var MAX_CORPUS_CHARS = 64e6;
14744
- function checkRunForUnsuppliedInputs(input) {
14745
- try {
14746
- const listed = new Set(input.listing);
14747
- const corpus = [];
14748
- let chars = 0;
14749
- for (const path of listed) {
14750
- const text = input.readText(path);
14751
- if (text === null) continue;
14752
- chars += text.length;
14753
- if (chars > MAX_CORPUS_CHARS) return [];
14754
- corpus.push({ path, text });
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;
14755
15234
  }
14756
- const changed = [];
14757
- for (const { targetPath, newContent } of input.results) {
14758
- if (listed.has(targetPath) && input.readText(targetPath) === null) continue;
14759
- changed.push({ path: targetPath, newContent });
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;
14760
15243
  }
14761
- return findUnsuppliedInputs({ changed, corpus });
14762
- } catch {
14763
- 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 });
14764
15254
  }
14765
- }
14766
- function describeUnsuppliedInputs(found) {
14767
- const many = found.length !== 1;
14768
- return `${found.length} changed function${many ? "s" : ""} ${many ? "read" : "reads"} a field that nothing else in the project supplies; the new tests may be the only thing feeding ${many ? "them" : "it"}. See "What QuikPilot noticed" on the run.`;
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;
14769
15300
  }
14770
15301
 
14771
- // src/unsuppliedInputsDisk.ts
14772
- var import_node_fs15 = require("node:fs");
14773
- var MAX_READ_BYTES = 1e6;
14774
- function readCheckoutText(path) {
14775
- try {
14776
- const info = (0, import_node_fs15.statSync)(path);
14777
- if (!info.isFile() || info.size > MAX_READ_BYTES) return null;
14778
- const bytes = (0, import_node_fs15.readFileSync)(path);
14779
- if (bytes.includes(0)) return null;
14780
- return bytes.toString("utf8");
14781
- } catch {
14782
- return null;
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)}`);
14783
15310
  }
14784
- }
14785
- function checkGeneratedCode(results) {
14786
- try {
14787
- return checkRunForUnsuppliedInputs({ results, listing: listFiles("."), readText: readCheckoutText });
14788
- } catch {
14789
- 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");
14790
15314
  }
15315
+ return body.data.runToken;
14791
15316
  }
14792
15317
 
14793
15318
  // src/run.ts
15319
+ var JOB_RESERVE_MS = 7 * 6e4;
14794
15320
  async function run(env2) {
15321
+ const runStartedAt = Date.now();
14795
15322
  let hardFailure = false;
14796
15323
  let packet;
14797
15324
  let branch;
@@ -14828,7 +15355,8 @@ async function run(env2) {
14828
15355
  packet.requiredTests,
14829
15356
  packet.guardrails.deniedPaths,
14830
15357
  packet.testDiscovery,
14831
- outOfScope
15358
+ outOfScope,
15359
+ ...packet.findings ? [{ findings: packet.findings }] : []
14832
15360
  );
14833
15361
  targetingResult = targeting;
14834
15362
  for (const w of targeting.warnings ?? []) {
@@ -14886,105 +15414,80 @@ async function run(env2) {
14886
15414
  snapshot,
14887
15415
  durationMs: Date.now() - baselineStartedAt
14888
15416
  }));
14889
- const [timedBaseline, results] = await Promise.all([
14890
- baselineRun,
14891
- runCodegenStep({
14892
- mode: resolveCodegenMode(),
14893
- tests: {
14894
- root: process.cwd(),
14895
- command: packet.commands.test,
14896
- baseline: () => baselineRun.catch(() => null)
14897
- },
14898
- gateway: packet.gateway,
14899
- targets: targeting.targets,
14900
- workspaceListing,
14901
- requiredTests: packet.requiredTests,
14902
- deniedPaths: packet.guardrails.deniedPaths,
14903
- judgedByPool,
14904
- warnings,
14905
- contextLog,
14906
- outOfScope,
14907
- testDiscovery: packet.testDiscovery,
14908
- skippedCases: targeting.skippedCases ?? [],
14909
- out: codegenOut
14910
- })
14911
- ]);
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;
14912
15441
  const baseline = timedBaseline.snapshot;
14913
15442
  generatedResults = results;
14914
- const depCheck = checkImportDependencies(
14915
- results,
14916
- readDeclaredDependencies(results, packet.workspaceRoot),
14917
- resolveAliasPrefixes(results, packet.workspaceRoot)
14918
- );
14919
- if (depCheck.blocked) {
14920
- throw new Error(
14921
- `QuikPilot's generated code imports packages this repository doesn't have \u2014 ${describeDependencyViolations(depCheck)}`
14922
- );
14923
- }
14924
- const scopeCheck = checkApiScope(results, targeting.targets, packet.design?.apiChanges ?? []);
14925
- if (scopeCheck.blocked) {
14926
- throw new Error(
14927
- `QuikPilot's generated code exceeds the approved design \u2014 ${describeScopeViolations(scopeCheck)}`
14928
- );
14929
- }
14930
- const placementCheck = checkTestPlacement(targeting.targets, baseline.discoveredFiles);
14931
- if (placementCheck.blocked) {
14932
- throw new Error(
14933
- `QuikPilot's generated tests are not where the test runner will find them \u2014 ${describeTestPlacementViolations(placementCheck)}`
14934
- );
14935
- }
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;
14936
15452
  try {
14937
- const baselineCheck = await runBaselineCheck({
14938
- targets: targeting.targets,
14939
- results,
14940
- testFileCmd: packet.commands.testFile,
14941
- 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
+ }
14942
15474
  });
14943
- warnings.push(...baselineCheck.warnings);
14944
- baselineFindings = baselineCheck.findings ?? void 0;
14945
- } catch (err) {
14946
- const message = `Baseline check could not run: ${err instanceof Error ? err.message : String(err)}`;
14947
- console.error(message);
14948
- warnings.push(message);
14949
- }
14950
- try {
14951
- const unsupplied = checkGeneratedCode(results);
14952
- if (unsupplied.length > 0) {
14953
- unsuppliedInputs = unsupplied;
14954
- const w = describeUnsuppliedInputs(unsupplied);
14955
- warnings.push(w);
14956
- console.warn(`QuikPilot code warning (not blocking): ${w}`);
14957
- }
14958
- } catch (err) {
14959
- console.error(`Unsupplied-input check could not run (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14960
- }
14961
- generatedFilePaths = results.map((r) => r.targetPath);
14962
- flushCodegenResults(results);
14963
- try {
14964
- runCommand(packet.commands.format, "Format");
14965
15475
  } catch (err) {
14966
- console.error(`Format failed (not blocking): ${err instanceof Error ? err.message : String(err)}`);
14967
- }
14968
- runCommand(packet.commands.lint, "Lint");
14969
- const after = captureTestSnapshot(packet.commands.test);
14970
- finalTestReport = readTestReportBytes();
14971
- vanishedTests = findVanishedTests(baseline, after) ?? void 0;
14972
- if (vanishedTests) {
14973
- const w = describeVanishedTests(vanishedTests);
14974
- warnings.push(w);
14975
- console.warn(`QuikPilot test warning (not blocking): ${w}`);
14976
- }
14977
- const check = checkForRegressions(baseline, after);
14978
- if (check.blocked) {
14979
- throw new Error(
14980
- `QuikPilot's generated code introduced test failures \u2014 ${describeRegressions(check)}`
14981
- );
14982
- }
14983
- const coverageCheck = checkAutomationIdCoverage(targeting.targets, after.discoveredAutomationIds);
14984
- if (coverageCheck.blocked) {
14985
- throw new Error(
14986
- `QuikPilot's generated tests were not executed \u2014 ${describeAutomationCoverageViolations(coverageCheck)}`
14987
- );
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;
14988
15491
  }
14989
15492
  }
14990
15493
  } catch (err) {
@@ -15203,7 +15706,7 @@ var EvidenceLedger = class {
15203
15706
  return seen;
15204
15707
  }
15205
15708
  };
15206
- function isRecord2(x) {
15709
+ function isRecord3(x) {
15207
15710
  return typeof x === "object" && x !== null && !Array.isArray(x);
15208
15711
  }
15209
15712
  function arrayOf(x) {
@@ -15221,7 +15724,7 @@ function isLine(n) {
15221
15724
  function verifyFindings(raw, ledger, ctx) {
15222
15725
  const dropped = emptyDropped();
15223
15726
  const redactions = emptyRedactionCounts();
15224
- if (!isRecord2(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
15727
+ if (!isRecord3(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
15225
15728
  const pathOk2 = (p) => typeof p === "string" && ctx.listing.has(p) && matchesDeniedPath(p, ctx.deniedPaths) === null;
15226
15729
  const symbolsOf = (path, list2) => {
15227
15730
  const out = [];
@@ -15236,7 +15739,7 @@ function verifyFindings(raw, ledger, ctx) {
15236
15739
  };
15237
15740
  const files = [];
15238
15741
  for (const f of arrayOf(raw.files)) {
15239
- if (!isRecord2(f) || !pathOk2(f.path)) {
15742
+ if (!isRecord3(f) || !pathOk2(f.path)) {
15240
15743
  dropped.files += 1;
15241
15744
  continue;
15242
15745
  }
@@ -15246,7 +15749,7 @@ function verifyFindings(raw, ledger, ctx) {
15246
15749
  }
15247
15750
  const callPath = [];
15248
15751
  for (const s of arrayOf(raw.callPath)) {
15249
- const ok = isRecord2(s) && pathOk2(s.path) && typeof s.symbol === "string" && s.symbol.length > 0 && s.symbol.length <= MAX_SYMBOL_CHARS && isLine(s.line) && ledger.hasLines(s.path, s.line, s.line) && ledger.textContains(s.path, s.symbol);
15752
+ const ok = isRecord3(s) && pathOk2(s.path) && typeof s.symbol === "string" && s.symbol.length > 0 && s.symbol.length <= MAX_SYMBOL_CHARS && isLine(s.line) && ledger.hasLines(s.path, s.line, s.line) && ledger.textContains(s.path, s.symbol);
15250
15753
  if (!ok) {
15251
15754
  dropped.callPath += 1;
15252
15755
  continue;
@@ -15255,7 +15758,7 @@ function verifyFindings(raw, ledger, ctx) {
15255
15758
  }
15256
15759
  const evidence = [];
15257
15760
  for (const e of arrayOf(raw.evidence)) {
15258
- const ok = isRecord2(e) && pathOk2(e.path) && isLine(e.startLine) && isLine(e.endLine) && e.startLine <= e.endLine && e.endLine - e.startLine + 1 <= MAX_EVIDENCE_LINES && ledger.hasLines(e.path, e.startLine, e.endLine);
15761
+ const ok = isRecord3(e) && pathOk2(e.path) && isLine(e.startLine) && isLine(e.endLine) && e.startLine <= e.endLine && e.endLine - e.startLine + 1 <= MAX_EVIDENCE_LINES && ledger.hasLines(e.path, e.startLine, e.endLine);
15259
15762
  if (!ok) {
15260
15763
  dropped.evidence += 1;
15261
15764
  continue;