@quikit/quikpilot-runner 9.2.0-rc.8 → 9.3.0-rc.2

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
@@ -1011,20 +1011,20 @@ function runTestCommand(command) {
1011
1011
  }
1012
1012
  function runTestCommandAsync(command) {
1013
1013
  if (!command) return Promise.resolve("success");
1014
- return new Promise((resolve5) => {
1014
+ return new Promise((resolve6) => {
1015
1015
  const child = (0, import_node_child_process.spawn)(command, { shell: "/bin/bash", stdio: "inherit", env: repositoryCommandEnv() });
1016
- child.on("exit", (code) => resolve5(code === 0 ? "success" : "failure"));
1017
- child.on("error", () => resolve5("failure"));
1016
+ child.on("exit", (code) => resolve6(code === 0 ? "success" : "failure"));
1017
+ child.on("error", () => resolve6("failure"));
1018
1018
  });
1019
1019
  }
1020
1020
  function runCommandWithTimeout(command, timeoutMs) {
1021
- return new Promise((resolve5) => {
1021
+ return new Promise((resolve6) => {
1022
1022
  let settled = false;
1023
1023
  const finish = (outcome) => {
1024
1024
  if (settled) return;
1025
1025
  settled = true;
1026
1026
  clearTimeout(timer);
1027
- resolve5(outcome);
1027
+ resolve6(outcome);
1028
1028
  };
1029
1029
  const child = (0, import_node_child_process.spawn)(command, {
1030
1030
  shell: "/bin/bash",
@@ -1033,21 +1033,53 @@ function runCommandWithTimeout(command, timeoutMs) {
1033
1033
  env: repositoryCommandEnv()
1034
1034
  });
1035
1035
  const timer = setTimeout(() => {
1036
- try {
1037
- if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
1038
- else child.kill("SIGKILL");
1039
- } catch {
1040
- try {
1041
- child.kill("SIGKILL");
1042
- } catch {
1043
- }
1044
- }
1036
+ killProcessGroup(child);
1045
1037
  finish("timeout");
1046
1038
  }, timeoutMs);
1047
1039
  child.on("exit", () => finish("exited"));
1048
1040
  child.on("error", () => finish("error"));
1049
1041
  });
1050
1042
  }
1043
+ function killProcessGroup(child) {
1044
+ try {
1045
+ if (child.pid !== void 0) process.kill(-child.pid, "SIGKILL");
1046
+ else child.kill("SIGKILL");
1047
+ } catch {
1048
+ try {
1049
+ child.kill("SIGKILL");
1050
+ } catch {
1051
+ }
1052
+ }
1053
+ }
1054
+ var KILL_GRACE_MS = 2e3;
1055
+ function runTestCommandWithLimit(command, timeoutMs, cwd) {
1056
+ return new Promise((resolve6) => {
1057
+ let settled = false;
1058
+ let timedOut = false;
1059
+ let graceTimer;
1060
+ const finish = (run2) => {
1061
+ if (settled) return;
1062
+ settled = true;
1063
+ clearTimeout(timer);
1064
+ if (graceTimer) clearTimeout(graceTimer);
1065
+ resolve6(run2);
1066
+ };
1067
+ const child = (0, import_node_child_process.spawn)(command, {
1068
+ shell: "/bin/bash",
1069
+ stdio: "inherit",
1070
+ detached: true,
1071
+ env: repositoryCommandEnv(),
1072
+ ...cwd ? { cwd } : {}
1073
+ });
1074
+ const timer = setTimeout(() => {
1075
+ timedOut = true;
1076
+ killProcessGroup(child);
1077
+ graceTimer = setTimeout(() => finish({ outcome: "failure", timedOut: true, started: true }), KILL_GRACE_MS);
1078
+ }, timeoutMs);
1079
+ child.on("exit", (code) => finish({ outcome: timedOut || code !== 0 ? "failure" : "success", timedOut, started: true }));
1080
+ child.on("error", () => finish({ outcome: "failure", timedOut, started: false }));
1081
+ });
1082
+ }
1051
1083
 
1052
1084
  // src/git.ts
1053
1085
  var import_node_child_process2 = require("node:child_process");
@@ -1528,8 +1560,8 @@ var TS_SIBLINGS = { ".js": [".ts", ".tsx"], ".jsx": [".tsx"], ".mjs": [".mts"],
1528
1560
  function resolveImport(fromPath, specifier, listing) {
1529
1561
  if (/^(?:@\/|~\/|#|\$|\/)/.test(specifier)) return { kind: "unresolved", reason: "alias" };
1530
1562
  const clean = specifier.replace(/[?#].*$/, "");
1531
- const relative6 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
1532
- if (!relative6) return { kind: "external" };
1563
+ const relative8 = clean === "." || clean === ".." || clean.startsWith("./") || clean.startsWith("../");
1564
+ if (!relative8) return { kind: "external" };
1533
1565
  const base = import_node_path.posix.normalize(import_node_path.posix.join(import_node_path.posix.dirname(fromPath), clean));
1534
1566
  if (base === ".." || base.startsWith("../") || import_node_path.posix.isAbsolute(base)) return { kind: "unresolved", reason: "not found" };
1535
1567
  const ext = import_node_path.posix.extname(base);
@@ -2041,6 +2073,7 @@ function parse(value) {
2041
2073
  if (typeof value !== "string") return null;
2042
2074
  const v = value.trim().toLowerCase();
2043
2075
  if (v === "loop") return "loop";
2076
+ if (v === "loop-tests") return "loop-tests";
2044
2077
  if (v === "single") return "single";
2045
2078
  return null;
2046
2079
  }
@@ -2054,6 +2087,7 @@ var MAX_RECORD_PATH_CHARS = 300;
2054
2087
  var MAX_RECORD_REASONING_TURNS = 30;
2055
2088
  var MAX_RECORD_REASONING_CHARS = 500;
2056
2089
  var MAX_RECORD_FALLBACK_REASON_CHARS = 40;
2090
+ var MAX_RECORD_TEST_RUNS = 3;
2057
2091
  var MAX_STATUS_KEYS = 20;
2058
2092
  var MAX_STATUS_KEY_CHARS = 40;
2059
2093
  function whole(n) {
@@ -2105,6 +2139,25 @@ function buildCodegenLoopRecord(loop) {
2105
2139
  const over = text.length > MAX_RECORD_REASONING_CHARS;
2106
2140
  reasoning.push({ turn: whole(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...over ? { truncated: true } : {} });
2107
2141
  }
2142
+ const testRuns = [];
2143
+ for (const t of loop.testRuns ?? []) {
2144
+ if (testRuns.length >= MAX_RECORD_TEST_RUNS) {
2145
+ cut = true;
2146
+ break;
2147
+ }
2148
+ testRuns.push({
2149
+ n: whole(t.n),
2150
+ status: String(t.status).slice(0, MAX_STATUS_KEY_CHARS),
2151
+ ...t.reason ? { reason: String(t.reason).slice(0, MAX_STATUS_KEY_CHARS) } : {},
2152
+ passed: whole(t.passed),
2153
+ failed: whole(t.failed),
2154
+ regressions: whole(t.regressions),
2155
+ newFailures: whole(t.newFailures),
2156
+ alreadyFailing: whole(t.alreadyFailing),
2157
+ timedOut: t.timedOut === true,
2158
+ seconds: whole(t.seconds)
2159
+ });
2160
+ }
2108
2161
  return {
2109
2162
  turns: whole(loop.turns),
2110
2163
  toolCalls: whole(loop.toolCalls),
@@ -2117,6 +2170,8 @@ function buildCodegenLoopRecord(loop) {
2117
2170
  created,
2118
2171
  statusCounts,
2119
2172
  ...whole(loop.syntaxWarnings) > 0 ? { syntaxWarnings: whole(loop.syntaxWarnings) } : {},
2173
+ ...typeof loop.contractVersion === "string" && loop.contractVersion.length > 0 ? { contractVersion: loop.contractVersion.slice(0, 40) } : {},
2174
+ ...testRuns.length > 0 ? { testRuns } : {},
2120
2175
  reasoning,
2121
2176
  ...cut ? { truncated: true } : {}
2122
2177
  };
@@ -2247,8 +2302,8 @@ function pairedTestPaths(codePath, listing) {
2247
2302
  const stem = m[1].toLowerCase();
2248
2303
  const dir = dirOf(codePath);
2249
2304
  const parent = parentOf(dir);
2250
- const join6 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
2251
- const homes = /* @__PURE__ */ new Set([dir, join6(dir, "__tests__"), join6(parent, "__tests__"), join6(parent, "tests"), join6(parent, "test")]);
2305
+ const join8 = (d, leaf) => d === "" ? leaf : `${d}/${leaf}`;
2306
+ const homes = /* @__PURE__ */ new Set([dir, join8(dir, "__tests__"), join8(parent, "__tests__"), join8(parent, "tests"), join8(parent, "test")]);
2252
2307
  const found = [];
2253
2308
  for (const path of listing) {
2254
2309
  if (!homes.has(dirOf(path))) continue;
@@ -11316,1207 +11371,1779 @@ function createCodegenWorkspace(args) {
11316
11371
  };
11317
11372
  }
11318
11373
 
11319
- // src/targetingErrors.ts
11320
- var DeniedPathError = class extends Error {
11321
- constructor(message) {
11322
- super(message);
11323
- this.name = "DeniedPathError";
11374
+ // src/overlayOnDisk.ts
11375
+ var import_node_child_process4 = require("node:child_process");
11376
+ var import_node_fs6 = require("node:fs");
11377
+ var import_node_path7 = require("node:path");
11378
+
11379
+ // src/treeFingerprint.ts
11380
+ var import_node_crypto = require("node:crypto");
11381
+ var import_node_child_process3 = require("node:child_process");
11382
+ var import_node_fs5 = require("node:fs");
11383
+ var import_node_path6 = require("node:path");
11384
+ var MAX_HASHED_BYTES = 8 * 1024 * 1024;
11385
+ function defaultGitStatus(root) {
11386
+ try {
11387
+ return (0, import_node_child_process3.execFileSync)("git", ["status", "--porcelain=v1", "-z", "--untracked-files=all"], {
11388
+ cwd: root,
11389
+ encoding: "utf8",
11390
+ stdio: ["ignore", "pipe", "ignore"],
11391
+ maxBuffer: 64 * 1024 * 1024
11392
+ });
11393
+ } catch {
11394
+ return null;
11324
11395
  }
11325
- };
11326
- var TargetingHttpError = class extends Error {
11327
- status;
11328
- constructor(status, statusText) {
11329
- super(`Targeting call failed: ${status} ${statusText}`);
11330
- this.name = "TargetingHttpError";
11331
- this.status = status;
11396
+ }
11397
+ var STATUS_ENTRY = /^[ MADRCUT?!]{2} /;
11398
+ function isStatusEntry(token) {
11399
+ return STATUS_ENTRY.test(token);
11400
+ }
11401
+ function entryPath(token) {
11402
+ return token.slice(3);
11403
+ }
11404
+ function entryCode(token) {
11405
+ return token.slice(0, 2);
11406
+ }
11407
+ function parseStatus(raw) {
11408
+ return raw.split("\0").filter((t) => t.length > 0).sort();
11409
+ }
11410
+ function hashOf(root, rel) {
11411
+ const abs = (0, import_node_path6.join)(root, rel);
11412
+ let st;
11413
+ try {
11414
+ st = (0, import_node_fs5.lstatSync)(abs);
11415
+ } catch {
11416
+ return null;
11332
11417
  }
11333
- };
11334
-
11335
- // src/tokenEstimate.ts
11336
- var TOKENS_PER_ALPHA_CHAR = 0.3;
11337
- var TOKENS_PER_DIGIT_CHAR = 0.18;
11338
- var TOKENS_PER_SPACE_CHAR = 0.05;
11339
- var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
11340
- var TOKENS_PER_NON_ASCII_CHAR = 1;
11341
- var PROMPT_OVERHEAD_TOKENS = 5e3;
11342
- function estimateTokens(text) {
11343
- let alpha = 0;
11344
- let digit = 0;
11345
- let space = 0;
11346
- let punct = 0;
11347
- let nonAscii = 0;
11348
- for (const ch of text) {
11349
- const code = ch.codePointAt(0);
11350
- if (code >= 128) nonAscii++;
11351
- else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
11352
- else if (code >= 48 && code <= 57) digit++;
11353
- else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
11354
- else punct++;
11418
+ try {
11419
+ if (st.isSymbolicLink()) return `link:${(0, import_node_fs5.readlinkSync)(abs)}`;
11420
+ if (st.isDirectory()) return "dir";
11421
+ if (st.size > MAX_HASHED_BYTES) return `big:${st.size}:${Math.trunc(st.mtimeMs)}`;
11422
+ return (0, import_node_crypto.createHash)("sha256").update((0, import_node_fs5.readFileSync)(abs)).digest("hex");
11423
+ } catch {
11424
+ return `unreadable`;
11355
11425
  }
11356
- return Math.ceil(
11357
- alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
11358
- );
11359
11426
  }
11360
- function estimateRequestTokens(contextData) {
11361
- return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
11427
+ function captureTree(root, watch, deps = {}) {
11428
+ const raw = (deps.gitStatus ?? defaultGitStatus)(root);
11429
+ if (raw === null) return null;
11430
+ const status = parseStatus(raw);
11431
+ const paths = new Set(watch);
11432
+ for (const token of status) if (isStatusEntry(token)) paths.add(entryPath(token));
11433
+ const hashes = {};
11434
+ for (const p of [...paths].sort()) hashes[p] = hashOf(root, p);
11435
+ const digest = (0, import_node_crypto.createHash)("sha256").update(JSON.stringify([status, hashes])).digest("hex");
11436
+ return { status, hashes, digest };
11437
+ }
11438
+ function treeDifferences(before, after) {
11439
+ const out = /* @__PURE__ */ new Set();
11440
+ for (const p of /* @__PURE__ */ new Set([...Object.keys(before.hashes), ...Object.keys(after.hashes)])) {
11441
+ if ((before.hashes[p] ?? null) !== (after.hashes[p] ?? null)) out.add(p);
11442
+ }
11443
+ const codes = (s) => new Map(s.status.filter(isStatusEntry).map((t) => [entryPath(t), entryCode(t)]));
11444
+ const b = codes(before);
11445
+ const a = codes(after);
11446
+ for (const p of /* @__PURE__ */ new Set([...b.keys(), ...a.keys()])) if (b.get(p) !== a.get(p)) out.add(p);
11447
+ return [...out].sort();
11362
11448
  }
11363
11449
 
11364
- // src/targetingLoop.ts
11365
- var LOOP_CONTRACT_VERSION = "targeting-loop-1";
11366
- var LoopFailure = class extends Error {
11367
- reason;
11368
- runtimeCode;
11369
- /** What the loop had done when it failed, so reads made before the failure are not lost. */
11370
- summary;
11371
- constructor(reason, runtimeCode, cause) {
11372
- super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
11373
- this.name = "LoopFailure";
11374
- this.reason = reason;
11375
- this.runtimeCode = runtimeCode;
11450
+ // src/overlayOnDisk.ts
11451
+ var TreeNotRestoredError = class extends Error {
11452
+ paths;
11453
+ constructor(paths, cause) {
11454
+ super("The checkout could not be restored after a test run.");
11455
+ this.name = "TreeNotRestoredError";
11456
+ this.paths = paths;
11376
11457
  if (cause !== void 0) this.cause = cause;
11377
11458
  }
11378
11459
  };
11379
- var SafetyRefusalError = class extends RuntimeReplyError {
11380
- constructor(message, summary) {
11381
- super(message, summary);
11382
- this.name = "SafetyRefusalError";
11460
+ var TreeUnverifiableError = class extends Error {
11461
+ constructor() {
11462
+ super("The checkout could not be verified, so no test run was started.");
11463
+ this.name = "TreeUnverifiableError";
11383
11464
  }
11384
11465
  };
11385
- var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
11386
- var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
11387
- var MAX_ID_CHARS = 64;
11388
- var MAX_CALLS_IN_A_REPLY = 50;
11389
- var MAX_ARGS_JSON_CHARS = 1e3;
11390
- function isPlainObject2(x) {
11391
- return typeof x === "object" && x !== null && !Array.isArray(x);
11392
- }
11393
- function safeArgs(args) {
11394
- try {
11395
- return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS ? args : { _omitted: "too large" };
11396
- } catch {
11397
- return { _omitted: "unreadable" };
11466
+ var DiskWriteRefused = class extends Error {
11467
+ reason;
11468
+ constructor(reason) {
11469
+ super(`A change could not be put on disk (${reason}).`);
11470
+ this.name = "DiskWriteRefused";
11471
+ this.reason = reason;
11398
11472
  }
11473
+ };
11474
+ function safeRelativePath(rel) {
11475
+ if (typeof rel !== "string" || rel.length === 0 || rel.length > 400 || rel.includes("\0") || rel.includes("\\")) return null;
11476
+ if ((0, import_node_path7.isAbsolute)(rel) || /^[A-Za-z]:/.test(rel)) return null;
11477
+ const parts = rel.split("/");
11478
+ if (parts.some((p) => p === "" || p === "." || p === "..")) return null;
11479
+ return rel;
11399
11480
  }
11400
- function classifyTransport(err) {
11401
- if (err instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err);
11402
- const name = err?.name;
11403
- if (name === "TimeoutError" || name === "AbortError") return new LoopFailure("turn_timeout", void 0, err);
11404
- return new LoopFailure("transport", void 0, err);
11481
+ function isInside(root, abs) {
11482
+ const r = (0, import_node_path7.relative)(root, abs);
11483
+ return r !== "" && !r.startsWith("..") && !(0, import_node_path7.isAbsolute)(r);
11405
11484
  }
11406
- async function runTargetingLoop(args, deps) {
11407
- const limits = { ...DEFAULT_LIMITS, ...deps.limits };
11408
- const now = deps.now ?? Date.now;
11409
- const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
11410
- const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
11411
- const deadlineMs = deps.deadlineMs ?? 6e5;
11412
- const env2 = {
11413
- listing: new Set(args.listing),
11414
- visible: buildVisibleListing(args.listing, args.deniedPaths),
11415
- deniedPaths: args.deniedPaths,
11416
- fs: deps.fs ?? createNodeToolFs(),
11417
- limits
11418
- };
11419
- const ledger = newLedger();
11420
- const reads = [];
11421
- const transcript = [];
11422
- const toolResults = [];
11423
- const usedIds = /* @__PURE__ */ new Set();
11424
- let turns = 0;
11425
- let noProgressStreak = 0;
11426
- let forced = null;
11427
- const started = now();
11428
- const buildContext = (turn, isFinal, finalReason) => ({
11429
- ...args.baseContext,
11430
- contractVersion: LOOP_CONTRACT_VERSION,
11431
- loop: {
11432
- turn,
11433
- maxTurns: limits.maxTurns,
11434
- final: isFinal,
11435
- ...isFinal ? { finalReason } : {},
11436
- remaining: {
11437
- toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
11438
- readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
11439
- },
11440
- transcript,
11441
- toolResults
11485
+ function ancestorInside(realRoot, abs) {
11486
+ let dir = (0, import_node_path7.dirname)(abs);
11487
+ for (; ; ) {
11488
+ try {
11489
+ const real = (0, import_node_fs6.realpathSync)(dir);
11490
+ const r = (0, import_node_path7.relative)(realRoot, real);
11491
+ return r === "" || !r.startsWith("..") && !(0, import_node_path7.isAbsolute)(r);
11492
+ } catch {
11493
+ const up = (0, import_node_path7.dirname)(dir);
11494
+ if (up === dir) return false;
11495
+ dir = up;
11442
11496
  }
11443
- });
11444
- const snapshot = (stopReason) => ({
11445
- turns,
11446
- toolCalls: ledger.toolCalls,
11447
- readChars: ledger.readChars,
11448
- refused: ledger.refused,
11449
- stopReason,
11450
- reads: [...reads]
11451
- });
11452
- log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
11453
- try {
11454
- for (let turn = 1; turn <= limits.maxTurns; turn++) {
11455
- turns = turn;
11456
- if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
11457
- const isFinal = forced !== null || turn === limits.maxTurns;
11458
- const finalReason = forced ?? "max_turns";
11459
- const contextData = buildContext(turn, isFinal, finalReason);
11460
- const requestChars = JSON.stringify(contextData).length;
11461
- const requestTokens = estimateRequestTokens(contextData);
11462
- if (requestTokens > limits.maxRequestTokens) {
11463
- log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
11464
- throw new LoopFailure("token_ceiling");
11465
- }
11466
- const turnStarted = now();
11467
- let envelope;
11468
- try {
11469
- envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
11470
- } catch (err) {
11471
- throw classifyTransport(err);
11472
- }
11473
- const code = envelope?.errorCode;
11497
+ }
11498
+ }
11499
+ function applyOverlay(root, files) {
11500
+ const realRoot = (0, import_node_fs6.realpathSync)(root);
11501
+ const written = [];
11502
+ const seen = /* @__PURE__ */ new Set();
11503
+ const restore2 = () => {
11504
+ const failed = [];
11505
+ for (const w of [...written].reverse()) {
11506
+ const rel = (0, import_node_path7.relative)(root, w.abs).split("\\").join("/");
11474
11507
  try {
11475
- checkHardFailure(envelope, "pilot.targeting");
11476
- } catch (err) {
11477
- throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
11478
- }
11479
- if (envelope?.success === false) {
11480
- const runtimeCode = typeof code === "string" ? code : void 0;
11481
- if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
11482
- let inner;
11508
+ if (w.original !== null) (0, import_node_fs6.writeFileSync)(w.abs, w.original);
11509
+ else (0, import_node_fs6.rmSync)(w.abs, { force: true });
11510
+ for (const d of [...w.createdDirs].reverse()) {
11483
11511
  try {
11484
- unwrapExecute(envelope, "pilot.targeting");
11485
- } catch (e) {
11486
- inner = e instanceof RuntimeReplyError ? e : void 0;
11512
+ (0, import_node_fs6.rmdirSync)(d);
11513
+ } catch {
11487
11514
  }
11488
- const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
11489
- throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
11490
11515
  }
11491
- throw new LoopFailure("runtime_failed", runtimeCode);
11516
+ } catch {
11517
+ failed.push(rel);
11492
11518
  }
11493
- let body;
11519
+ }
11520
+ written.length = 0;
11521
+ return { failed: failed.sort() };
11522
+ };
11523
+ try {
11524
+ for (const f of files) {
11525
+ const rel = safeRelativePath(f.path);
11526
+ if (rel === null) throw new DiskWriteRefused("bad_path");
11527
+ if (seen.has(rel)) throw new DiskWriteRefused("duplicate");
11528
+ seen.add(rel);
11529
+ const abs = (0, import_node_path7.resolve)(root, rel);
11530
+ if (!isInside(root, abs) || !ancestorInside(realRoot, abs)) throw new DiskWriteRefused("outside_checkout");
11531
+ let original = null;
11494
11532
  try {
11495
- body = unwrapExecute(envelope, "pilot.targeting");
11533
+ const st = (0, import_node_fs6.lstatSync)(abs);
11534
+ if (st.isSymbolicLink() || !st.isFile()) throw new DiskWriteRefused("not_a_file");
11535
+ original = (0, import_node_fs6.readFileSync)(abs);
11496
11536
  } catch (err) {
11497
- throw new LoopFailure("bad_reply", void 0, err);
11498
- }
11499
- if (body.outcome === "TARGETED" || body.outcome === "NO_TARGET") {
11500
- log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
11501
- const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
11502
- log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
11503
- return { body, summary: snapshot(stopReason) };
11537
+ if (err instanceof DiskWriteRefused) throw err;
11538
+ original = null;
11504
11539
  }
11505
- if (body.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
11506
- if (isFinal) throw new LoopFailure("final_not_produced");
11507
- const rawCalls = body.toolCalls;
11508
- if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
11509
- throw new LoopFailure("bad_reply");
11540
+ const createdDirs = [];
11541
+ if (original === null) {
11542
+ const missing = [];
11543
+ for (let d = (0, import_node_path7.dirname)(abs); !(0, import_node_fs6.existsSync)(d); d = (0, import_node_path7.dirname)(d)) missing.push(d);
11544
+ for (const d of missing.reverse()) {
11545
+ (0, import_node_fs6.mkdirSync)(d);
11546
+ createdDirs.push(d);
11547
+ }
11510
11548
  }
11511
- const calls = [];
11512
- for (const c of rawCalls) {
11513
- if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
11514
- throw new LoopFailure("bad_reply");
11549
+ const w = { abs, original, createdDirs };
11550
+ written.push(w);
11551
+ (0, import_node_fs6.writeFileSync)(abs, f.content);
11552
+ }
11553
+ } catch (err) {
11554
+ restore2();
11555
+ throw err;
11556
+ }
11557
+ return { restore: restore2 };
11558
+ }
11559
+ function git2(root, args) {
11560
+ (0, import_node_child_process4.execFileSync)("git", args, { cwd: root, stdio: ["ignore", "ignore", "ignore"] });
11561
+ }
11562
+ function cleanUpAfterRun(root, beforePaths, afterStatus) {
11563
+ for (const token of afterStatus) {
11564
+ if (!isStatusEntry(token)) continue;
11565
+ const p = entryPath(token);
11566
+ if (beforePaths.has(p) || safeRelativePath(p) === null) continue;
11567
+ const code = entryCode(token);
11568
+ try {
11569
+ if (code === "??") {
11570
+ (0, import_node_fs6.rmSync)((0, import_node_path7.join)(root, p), { recursive: true, force: true });
11571
+ for (let d = (0, import_node_path7.dirname)((0, import_node_path7.join)(root, p)); d !== root && isInside(root, d); d = (0, import_node_path7.dirname)(d)) {
11572
+ try {
11573
+ (0, import_node_fs6.rmdirSync)(d);
11574
+ } catch {
11575
+ break;
11576
+ }
11515
11577
  }
11516
- if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
11517
- calls.push({ id: c.id, name: c.name, args: c.args });
11578
+ } else if (code[0] === "A") {
11579
+ git2(root, ["rm", "-f", "--", p]);
11580
+ } else {
11581
+ git2(root, ["checkout", "HEAD", "--", p]);
11518
11582
  }
11519
- for (const c of calls) usedIds.add(c.id);
11520
- const results = [];
11521
- const logged = [];
11522
- const turnReads = [];
11523
- calls.forEach((call, index) => {
11524
- let result;
11525
- let read;
11526
- if (index >= limits.maxCallsPerTurn) {
11527
- result = {
11528
- id: call.id,
11529
- name: call.name,
11530
- status: "budget_exhausted",
11531
- reason: "too_many_calls",
11532
- message: "Too many calls in one turn; this one was not run."
11533
- };
11534
- } else {
11535
- try {
11536
- ({ result, read } = executeToolCall(call, env2, ledger));
11537
- } catch (err) {
11538
- throw new LoopFailure("executor_error", void 0, err);
11539
- }
11540
- }
11541
- results.push(result);
11542
- turnReads[index] = read;
11543
- if (read) reads.push(read);
11544
- const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
11545
- const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
11546
- logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
11547
- if (result.status === "refused") {
11548
- log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
11549
- }
11550
- });
11551
- const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
11552
- transcript.push({
11553
- turn,
11554
- ...reasoning ? { reasoning } : {},
11555
- toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
11556
- });
11557
- toolResults.push(...results);
11558
- noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
11559
- if (noProgressStreak >= 2) forced = "no_progress";
11560
- else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
11561
- else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
11562
- const nextTurn = turn + 1;
11563
- if (nextTurn <= limits.maxTurns) {
11564
- const nextFinal = forced !== null || nextTurn === limits.maxTurns;
11565
- const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
11566
- if (projected > limits.maxRequestTokens) {
11567
- results.forEach((r, idx) => {
11568
- if (r.status !== "ok") return;
11569
- toolResults[toolResults.indexOf(r)] = {
11570
- id: r.id,
11571
- name: r.name,
11572
- status: "budget_exhausted",
11573
- reason: "token_ceiling",
11574
- message: "Too large to include; answer from what you have."
11575
- };
11576
- const dropped = turnReads[idx];
11577
- if (dropped) {
11578
- const at2 = reads.indexOf(dropped);
11579
- if (at2 >= 0) reads.splice(at2, 1);
11580
- }
11581
- logged[idx].status = "budget_exhausted";
11582
- logged[idx].reason = "token_ceiling";
11583
- });
11584
- forced = "read_budget";
11585
- const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
11586
- const fits = trimmed <= limits.maxRequestTokens;
11587
- log({
11588
- event: "targeting.loop_ceiling",
11589
- turn,
11590
- action: fits ? "dropped_results" : "fallback",
11591
- projectedTokens: projected,
11592
- ceiling: limits.maxRequestTokens
11593
- });
11594
- if (!fits) throw new LoopFailure("token_ceiling");
11595
- }
11596
- }
11597
- log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
11583
+ } catch {
11598
11584
  }
11599
- throw new LoopFailure("final_not_produced");
11585
+ }
11586
+ }
11587
+ function snapshotPreserved(root, paths) {
11588
+ const out = [];
11589
+ for (const rel of paths ?? []) {
11590
+ if (safeRelativePath(rel) === null) continue;
11591
+ const abs = (0, import_node_path7.resolve)(root, rel);
11592
+ try {
11593
+ const st = (0, import_node_fs6.lstatSync)(abs);
11594
+ if (st.isSymbolicLink() || !st.isFile()) continue;
11595
+ out.push({ rel, abs, bytes: (0, import_node_fs6.readFileSync)(abs) });
11596
+ } catch {
11597
+ }
11598
+ }
11599
+ return out;
11600
+ }
11601
+ function restorePreserved(kept) {
11602
+ for (const k of kept) {
11603
+ try {
11604
+ (0, import_node_fs6.writeFileSync)(k.abs, k.bytes);
11605
+ } catch {
11606
+ }
11607
+ }
11608
+ }
11609
+ async function withOverlayOnDisk(root, files, run2, options = {}) {
11610
+ const kept = snapshotPreserved(root, options.preserve);
11611
+ const watch = [...files.map((f) => f.path), ...kept.map((k) => k.rel)];
11612
+ const before = captureTree(root, watch, options);
11613
+ if (before === null) throw new TreeUnverifiableError();
11614
+ const beforePaths = new Set(before.status.filter(isStatusEntry).map(entryPath));
11615
+ const session = applyOverlay(root, files);
11616
+ let value;
11617
+ let runError;
11618
+ let failedRun = false;
11619
+ try {
11620
+ value = await run2();
11600
11621
  } catch (err) {
11601
- if (err instanceof SafetyRefusalError) throw err;
11602
- const failure = err instanceof LoopFailure ? err : new LoopFailure("internal_error", void 0, err);
11603
- failure.summary ??= snapshot("fallback");
11604
- throw failure;
11622
+ failedRun = true;
11623
+ runError = err;
11624
+ }
11625
+ const { failed } = session.restore();
11626
+ restorePreserved(kept);
11627
+ let remaining = [];
11628
+ const after = captureTree(root, watch, options);
11629
+ if (after === null) {
11630
+ remaining = ["(git could not report the checkout)"];
11631
+ } else {
11632
+ remaining = treeDifferences(before, after);
11633
+ if (remaining.length > 0) {
11634
+ cleanUpAfterRun(root, beforePaths, after.status);
11635
+ const again = captureTree(root, watch, options);
11636
+ remaining = again === null ? ["(git could not report the checkout)"] : treeDifferences(before, again);
11637
+ }
11605
11638
  }
11639
+ const bad3 = [.../* @__PURE__ */ new Set([...failed, ...remaining])].sort();
11640
+ if (bad3.length > 0) throw new TreeNotRestoredError(bad3, failedRun ? runError : void 0);
11641
+ if (failedRun) throw runError;
11642
+ return value;
11643
+ }
11644
+ function assertTreeUnchanged(root, before, watch, options = {}) {
11645
+ if (before === null) throw new TreeUnverifiableError();
11646
+ const now = captureTree(root, watch, options);
11647
+ if (now === null) throw new TreeUnverifiableError();
11648
+ const differences = treeDifferences(before, now);
11649
+ if (differences.length > 0) throw new TreeNotRestoredError(differences);
11606
11650
  }
11607
11651
 
11608
- // src/codegenLoop.ts
11609
- var CODEGEN_LOOP_CONTRACT_VERSION = "codegen-loop-1";
11610
- var CodegenLoopFailure = class extends Error {
11611
- reason;
11612
- runtimeCode;
11613
- /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */
11614
- detail;
11615
- summary;
11616
- constructor(reason, runtimeCode, cause, detail) {
11617
- super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
11618
- this.name = "CodegenLoopFailure";
11619
- this.reason = reason;
11620
- this.runtimeCode = runtimeCode;
11621
- this.detail = detail;
11622
- if (cause !== void 0) this.cause = cause;
11652
+ // src/runTestsTool.ts
11653
+ var import_node_crypto2 = require("node:crypto");
11654
+ var import_node_fs9 = require("node:fs");
11655
+ var import_node_path9 = require("node:path");
11656
+
11657
+ // src/failureReason.ts
11658
+ var MAX_FAILURE_REASON = 1e3;
11659
+ var MIN_SECRET_LENGTH = 8;
11660
+ var CREDENTIAL_PATTERNS = [
11661
+ /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
11662
+ /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
11663
+ /x-access-token:[^@\s'"]+/gi,
11664
+ // Only the header form ("Authorization: basic <token>"), or a bearer value that contains a digit: a bare
11665
+ // "basic authentication" or "bearer of the news" is prose, not a credential.
11666
+ /\bauthorization:\s*(?:basic|bearer|token)\s+[^\s'"]{8,}/gi,
11667
+ /\bbearer\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{12,}/gi,
11668
+ // A signed JWT is three dot-separated segments; QuikPilot's own run token is an encrypted JWT (alg dir) of five, the
11669
+ // second one empty. The run token is also matched by exact value, but one that has expired or rotated is not the
11670
+ // current value, so its shape has to catch it.
11671
+ /\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]*){2,4}/g
11672
+ ];
11673
+ function failureSummary(err) {
11674
+ if (err instanceof RuntimeReplyError) return err.summary;
11675
+ return err instanceof Error ? err.message : String(err);
11676
+ }
11677
+ function scrubSecrets(message, secrets = []) {
11678
+ let text = message;
11679
+ for (const secret of secrets) {
11680
+ if (secret.length >= MIN_SECRET_LENGTH) text = text.split(secret).join("***");
11623
11681
  }
11624
- };
11625
- var MAX_ID_CHARS2 = 64;
11626
- var MAX_CALLS_IN_A_REPLY2 = 50;
11627
- var MAX_SUMMARY_CHARS = 300;
11628
- var READ_TOOLS = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
11629
- var WRITE_TOOLS = /* @__PURE__ */ new Set(["edit_file", "write_file"]);
11630
- var TOOL_NAMES2 = /* @__PURE__ */ new Set([...READ_TOOLS, ...WRITE_TOOLS]);
11631
- function isPlainObject3(x) {
11632
- return typeof x === "object" && x !== null && !Array.isArray(x);
11682
+ for (const pattern of CREDENTIAL_PATTERNS) text = text.replace(pattern, "***");
11683
+ return text;
11633
11684
  }
11634
- function classifyTransport2(err) {
11635
- if (err instanceof TargetingHttpError) return new CodegenLoopFailure("http_error", void 0, err);
11636
- const name = err?.name;
11637
- if (name === "TimeoutError" || name === "AbortError") return new CodegenLoopFailure("turn_timeout", void 0, err);
11638
- return new CodegenLoopFailure("transport", void 0, err);
11685
+ function describeFailureReason(message, secrets = []) {
11686
+ let text = scrubSecrets(message, secrets);
11687
+ text = text.replace(/\s*\n\s*/g, " | ").trim();
11688
+ return text.length > MAX_FAILURE_REASON ? `${text.slice(0, MAX_FAILURE_REASON)}\u2026` : text;
11639
11689
  }
11640
- var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
11641
- async function runCodegenLoop(args, deps) {
11642
- const ws = createCodegenWorkspace({
11643
- listing: args.listing,
11644
- deniedPaths: args.deniedPaths,
11645
- protectedTestPaths: args.protectedTestPaths,
11646
- fs: deps.fs,
11647
- limits: deps.limits,
11648
- syntaxSeed: args.syntaxSeed
11649
- });
11650
- const { env: env2, ledger, overlay, limits } = ws;
11651
- const now = deps.now ?? Date.now;
11652
- const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
11653
- const turnTimeoutMs = deps.turnTimeoutMs ?? 3e5;
11654
- const deadlineMs = deps.deadlineMs ?? 15e5;
11655
- const reads = [];
11656
- const reasoning = [];
11657
- const statusCounts = {};
11658
- const transcript = [];
11659
- const toolResults = [];
11660
- const usedIds = /* @__PURE__ */ new Set();
11661
- let turns = 0;
11662
- let noProgressStreak = 0;
11663
- let forced = null;
11664
- const started = now();
11665
- const buildContext = (turn, isFinal, finalReason) => ({
11666
- ...args.baseContext,
11667
- contractVersion: CODEGEN_LOOP_CONTRACT_VERSION,
11668
- loop: {
11669
- turn,
11670
- maxTurns: limits.maxTurns,
11671
- final: isFinal,
11672
- ...isFinal ? { finalReason } : {},
11673
- remaining: {
11674
- toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
11675
- readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),
11676
- writeChars: Math.max(0, limits.writeCharsTotal - ledger.writeChars)
11677
- },
11678
- transcript,
11679
- toolResults
11680
- }
11681
- });
11682
- const snapshot = (stopReason) => ({
11683
- turns,
11684
- toolCalls: ledger.toolCalls,
11685
- refused: ledger.refused,
11686
- stopReason,
11687
- reads: [...reads],
11688
- edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),
11689
- created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),
11690
- statusCounts: { ...statusCounts },
11691
- syntaxWarnings: ws.syntaxWarnings,
11692
- reasoning: [...reasoning]
11693
- });
11694
- const makeRoom = (nextTurn, nextFinal, finalReason) => {
11695
- const fits = () => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limits.maxRequestTokens;
11696
- if (fits()) return true;
11697
- for (let i2 = 0; i2 < toolResults.length && !fits(); i2++) {
11698
- const r = toolResults[i2];
11699
- if (READ_TOOLS.has(r.name) && r.status === "ok" && r.output !== DROPPED_OUTPUT) toolResults[i2] = { ...r, output: DROPPED_OUTPUT };
11700
- }
11701
- for (const key of [...ledger.seen.keys()]) {
11702
- if (key.startsWith("read_file:") || key.startsWith("grep:") || key.startsWith("list_files:")) ledger.seen.delete(key);
11690
+
11691
+ // src/quiktest.ts
11692
+ var import_node_fs7 = require("node:fs");
11693
+ var import_node_path8 = require("node:path");
11694
+ var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
11695
+ function walkForJUnitByName(dir) {
11696
+ let entries;
11697
+ try {
11698
+ entries = (0, import_node_fs7.readdirSync)(dir);
11699
+ } catch {
11700
+ return null;
11701
+ }
11702
+ for (const entry of entries) {
11703
+ if (SKIP_DIRS.has(entry)) continue;
11704
+ const full = (0, import_node_path8.join)(dir, entry);
11705
+ let stat;
11706
+ try {
11707
+ stat = (0, import_node_fs7.statSync)(full);
11708
+ } catch {
11709
+ continue;
11703
11710
  }
11704
- for (const entry of transcript) {
11705
- if (fits()) break;
11706
- entry.toolCalls = entry.toolCalls.map((c) => {
11707
- if (!WRITE_TOOLS.has(c.name) || !isPlainObject3(c.args) || "_omitted" in c.args) return c;
11708
- const path = typeof c.args.path === "string" ? { path: c.args.path } : {};
11709
- return { ...c, args: { ...path, _omitted: "written earlier; read the file to see it" } };
11710
- });
11711
+ if (stat.isDirectory()) {
11712
+ const found = walkForJUnitByName(full);
11713
+ if (found) return found;
11714
+ } else if (/^junit.*\.xml$/.test(entry)) {
11715
+ return full;
11711
11716
  }
11712
- return fits();
11713
- };
11714
- log({ event: "codegen.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
11717
+ }
11718
+ return null;
11719
+ }
11720
+ function firstXmlIn(dir, namePattern) {
11721
+ let entries;
11715
11722
  try {
11716
- for (let turn = 1; turn <= limits.maxTurns; turn++) {
11717
- turns = turn;
11718
- if (now() - started > deadlineMs) throw new CodegenLoopFailure("loop_deadline");
11719
- const isFinal = forced !== null || turn === limits.maxTurns;
11720
- const finalReason = forced ?? "max_turns";
11721
- const contextData = buildContext(turn, isFinal, finalReason);
11722
- const requestTokens = estimateRequestTokens(contextData);
11723
- if (requestTokens > limits.maxRequestTokens) {
11724
- log({ event: "codegen.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
11725
- throw new CodegenLoopFailure("token_ceiling");
11726
- }
11727
- const turnStarted = now();
11728
- let envelope;
11729
- try {
11730
- envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
11731
- } catch (err) {
11732
- throw classifyTransport2(err);
11733
- }
11734
- const code = envelope?.errorCode;
11735
- try {
11736
- checkHardFailure(envelope, "pilot.codegen");
11737
- } catch (err) {
11738
- throw new CodegenLoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
11739
- }
11740
- if (envelope?.success === false) {
11741
- const runtimeCode = typeof code === "string" ? code : void 0;
11742
- if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
11743
- let inner;
11744
- try {
11745
- unwrapExecute(envelope, "pilot.codegen");
11746
- } catch (e) {
11747
- inner = e instanceof RuntimeReplyError ? e : void 0;
11748
- }
11749
- const fallbackText = `pilot.codegen failed: ${runtimeCode}`;
11750
- throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
11751
- }
11752
- throw new CodegenLoopFailure("runtime_failed", runtimeCode);
11753
- }
11754
- let body;
11755
- try {
11756
- body = unwrapExecute(envelope, "pilot.codegen");
11757
- } catch (err) {
11758
- throw new CodegenLoopFailure("bad_reply", void 0, err);
11759
- }
11760
- const reasonText = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
11761
- if (body.outcome === "CANNOT_COMPLETE") {
11762
- log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
11763
- const said = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
11764
- throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said);
11765
- }
11766
- if (body.outcome === "DONE") {
11767
- log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
11768
- const changed = overlay.changedPaths();
11769
- if (changed.length === 0) throw new CodegenLoopFailure("no_writes");
11770
- const texts = changed.map((p) => overlay.get(p)?.lf ?? "");
11771
- const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
11772
- if (missing.length > 0) {
11773
- log({ event: "codegen.loop_refused", turn, reason: "coverage_missing", missing: missing.length });
11774
- throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`);
11775
- }
11776
- const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);
11777
- for (const path of changed) {
11778
- const entry = overlay.get(path);
11779
- if (!entry || entry.created || entry.originalLf === null) continue;
11780
- const pseudo = { path, kind: "EXISTING", planStepsImplemented: planSteps };
11781
- const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);
11782
- if (suspect) {
11783
- log({ event: "codegen.loop_refused", turn, reason: "truncation_guard", path });
11784
- throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`);
11785
- }
11786
- }
11787
- const broken = ws.syntaxProblems()[0];
11788
- if (broken) {
11789
- log({ event: "codegen.loop_refused", turn, reason: "syntax_error", path: broken.path, kind: broken.problem.kind, line: broken.problem.line });
11790
- throw new CodegenLoopFailure("syntax_error", void 0, void 0, `${broken.path}: ${describeSyntaxProblem(broken.problem)}`);
11791
- }
11792
- const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
11793
- const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
11794
- log({ event: "codegen.loop_done", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });
11795
- return { results: overlay.results(), summary: snapshot(stopReason), doneSummary };
11796
- }
11797
- if (body.outcome !== "TOOL_CALLS") throw new CodegenLoopFailure("bad_reply");
11798
- if (isFinal) throw new CodegenLoopFailure("final_not_produced");
11799
- const rawCalls = body.toolCalls;
11800
- if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY2) throw new CodegenLoopFailure("bad_reply");
11801
- const calls = [];
11802
- for (const c of rawCalls) {
11803
- if (!isPlainObject3(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS2 || typeof c.name !== "string") {
11804
- throw new CodegenLoopFailure("bad_reply");
11805
- }
11806
- if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new CodegenLoopFailure("duplicate_call_ids");
11807
- calls.push({ id: c.id, name: c.name, args: c.args });
11808
- }
11809
- for (const c of calls) usedIds.add(c.id);
11810
- const results = [];
11811
- const logged = [];
11812
- calls.forEach((call, index) => {
11813
- let result;
11814
- let read;
11815
- if (index >= limits.maxCallsPerTurn) {
11816
- result = { id: call.id, name: call.name, status: "budget_exhausted", reason: "too_many_calls", message: "Too many calls in one turn; this one was not run." };
11817
- } else {
11818
- try {
11819
- ({ result, read } = executeToolCall(call, env2, ledger));
11820
- } catch (err) {
11821
- throw new CodegenLoopFailure("executor_error", void 0, err);
11822
- }
11823
- }
11824
- results.push(result);
11825
- if (read) reads.push(read);
11826
- statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;
11827
- const tool = TOOL_NAMES2.has(call.name) ? call.name : "unknown";
11828
- const pathArg = isPlainObject3(call.args) && typeof call.args.path === "string" && result.status !== "refused" ? { path: call.args.path } : {};
11829
- logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...pathArg });
11830
- if (result.status === "refused" || result.status === "protected") {
11831
- log({ event: "codegen.loop_refused", turn, tool, status: result.status, reason: result.reason });
11832
- }
11833
- });
11834
- if (reasonText) reasoning.push({ turn, text: reasonText });
11835
- transcript.push({ turn, ...reasonText ? { reasoning: reasonText } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });
11836
- toolResults.push(...results);
11837
- noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
11838
- if (noProgressStreak >= 2) forced = "no_progress";
11839
- else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
11840
- else if (ledger.writeChars >= limits.writeCharsTotal) forced = "write_budget";
11841
- else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
11842
- const nextTurn = turn + 1;
11843
- if (nextTurn <= limits.maxTurns) {
11844
- const nextFinal = forced !== null || nextTurn === limits.maxTurns;
11845
- if (!makeRoom(nextTurn, nextFinal, forced ?? "max_turns")) {
11846
- forced = forced ?? "read_budget";
11847
- const fits = makeRoom(nextTurn, true, forced);
11848
- log({ event: "codegen.loop_ceiling", turn, action: fits ? "forced_final" : "fallback", ceiling: limits.maxRequestTokens });
11849
- if (!fits) throw new CodegenLoopFailure("token_ceiling");
11850
- }
11851
- }
11852
- log({ event: "codegen.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
11723
+ entries = (0, import_node_fs7.readdirSync)(dir);
11724
+ } catch {
11725
+ return null;
11726
+ }
11727
+ const match = entries.find((e) => namePattern.test(e));
11728
+ return match ? (0, import_node_path8.join)(dir, match) : null;
11729
+ }
11730
+ function readTestReportBytes(cwd = process.cwd()) {
11731
+ try {
11732
+ const report = findJUnitReport(cwd);
11733
+ return report ? (0, import_node_fs7.readFileSync)(report) : null;
11734
+ } catch {
11735
+ return null;
11736
+ }
11737
+ }
11738
+ function findJUnitReport(cwd = process.cwd()) {
11739
+ return walkForJUnitByName(cwd) ?? firstXmlIn((0, import_node_path8.join)(cwd, "test-results"), /\.xml$/) ?? firstXmlIn((0, import_node_path8.join)(cwd, "reports"), /^junit.*\.xml$/) ?? firstXmlIn((0, import_node_path8.join)(cwd, "target", "surefire-reports"), /\.xml$/);
11740
+ }
11741
+ function buildCiUrl(serverUrl, repository, githubRunId) {
11742
+ return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;
11743
+ }
11744
+ function describeUnmatchedAutomationIds(unmatched) {
11745
+ if (unmatched.length === 0) return null;
11746
+ const named = unmatched.map((u) => `${u.automationId} (\xD7${u.count})`).join(", ");
11747
+ return `${unmatched.length} generated test result(s) did not match any test case: ${named} \u2014 check the automationId format.`;
11748
+ }
11749
+ async function reportToQuikTest(params) {
11750
+ const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;
11751
+ if (!resultsUrl) {
11752
+ console.log("packet.quikTest is null \u2014 this run has no QuikTest run to report into.");
11753
+ return null;
11754
+ }
11755
+ const report = findJUnitReport(cwd);
11756
+ if (!report) {
11757
+ console.warn("::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.");
11758
+ return null;
11759
+ }
11760
+ try {
11761
+ console.log(`reporting ${report}`);
11762
+ const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
11763
+ const { readFileSync: readFileSync11 } = await import("node:fs");
11764
+ const body = readFileSync11(report);
11765
+ let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
11766
+ if (generatedFiles) {
11767
+ url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
11853
11768
  }
11854
- throw new CodegenLoopFailure("final_not_produced");
11769
+ const res = await fetch(url, {
11770
+ method: "POST",
11771
+ headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "text/xml" },
11772
+ body
11773
+ });
11774
+ if (!res.ok) {
11775
+ throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);
11776
+ }
11777
+ (0, import_node_fs7.rmSync)(report, { force: true });
11778
+ let unmatched = [];
11779
+ try {
11780
+ const json = await res.json();
11781
+ unmatched = json.data?.unmatched ?? [];
11782
+ } catch {
11783
+ }
11784
+ return { unmatched };
11855
11785
  } catch (err) {
11856
- if (err instanceof SafetyRefusalError) throw err;
11857
- const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
11858
- failure.summary ??= snapshot("fallback");
11859
- throw failure;
11786
+ console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);
11787
+ return null;
11860
11788
  }
11861
11789
  }
11862
11790
 
11863
- // src/codegenStep.ts
11864
- var MAX_PROTECTED_PATHS_ON_WIRE = 300;
11865
- async function postCodegenTurn(gateway, contextData, signal) {
11866
- const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
11867
- method: "POST",
11868
- headers: { "content-type": "application/json", "x-run-token": gateway.token },
11869
- body: JSON.stringify({
11870
- appId: "quiktrack",
11871
- useCase: "pilot.codegen",
11872
- expectedOutputType: "json",
11873
- userPrompt: "",
11874
- contextData
11875
- }),
11876
- ...signal ? { signal } : {}
11877
- });
11878
- if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
11879
- return res.json();
11791
+ // src/regressionCheck.ts
11792
+ var import_node_fs8 = require("node:fs");
11793
+ var TESTCASE_RE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
11794
+ var NAME_ATTR_RE = /\bname="([^"]*)"/;
11795
+ var CLASSNAME_ATTR_RE = /\bclassname="([^"]*)"/;
11796
+ var FAILURE_CHILD_RE = /<failure\b|<error\b/;
11797
+ var SKIPPED_CHILD_RE = /<skipped\b/;
11798
+ var TESTSUITE_OPEN_RE = /<testsuite\b([^>]*?)>/g;
11799
+ var FILE_ATTR_RE = /\bfile="([^"]*)"/;
11800
+ var QP_TOKEN_BRACKET_RE = /\[(QP-[A-Z][A-Z0-9]*-\d+-\d+)\]/;
11801
+ function normalizeSlashes(path) {
11802
+ return path.replace(/\\/g, "/");
11880
11803
  }
11881
- function protectedTestFiles(listing, testDiscovery) {
11882
- const inListing = new Set(listing);
11883
- const found = new Set(listing.filter((p) => isTestTarget(p)));
11884
- if (testDiscovery.report === "PRESENT") {
11885
- for (const p of testDiscovery.discoveredTestFiles) if (inListing.has(p)) found.add(p);
11886
- }
11887
- return [...found].sort();
11804
+ var FAILURE_TAG_RE = /<(?:failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:failure|error)>)/;
11805
+ var FAILURE_MESSAGE_ATTR_RE = /\bmessage="([^"]*)"/;
11806
+ var MAX_FAILURE_TEXT = 500;
11807
+ function unescapeXmlEntities(s) {
11808
+ return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
11888
11809
  }
11889
- function buildCodegenLoopArgs(p, context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} })) {
11890
- const skipped = new Set(p.skippedCases.map((s) => s.automationId));
11891
- const claimed = /* @__PURE__ */ new Set();
11892
- for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);
11893
- const requiredTests = p.requiredTests.filter((tc) => claimed.has(tc.automationId));
11894
- const protectedTestPaths = protectedTestFiles(p.workspaceListing, p.testDiscovery);
11895
- const baseContext = {
11896
- targets: p.targets.map((t) => ({
11897
- path: t.path,
11898
- kind: t.kind,
11899
- role: (t.automationIds?.length ?? 0) > 0 || isTestTarget(t.path) ? "test" : "code",
11900
- planSteps: t.planStepsImplemented,
11901
- automationIds: t.automationIds ?? []
11902
- })),
11903
- requiredTests,
11904
- workspaceListing: p.workspaceListing
11905
- };
11906
- if (context.entries.length > 0) baseContext.contextContents = context.entries;
11907
- if (p.deniedPaths.length > 0) baseContext.deniedPaths = p.deniedPaths;
11908
- if (protectedTestPaths.length > 0) baseContext.protectedTestPaths = protectedTestPaths.slice(0, MAX_PROTECTED_PATHS_ON_WIRE);
11909
- if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;
11910
- return {
11911
- baseContext,
11912
- targets: p.targets,
11913
- requiredAutomationIds: requiredTests.map((tc) => tc.automationId),
11914
- listing: p.workspaceListing,
11915
- deniedPaths: p.deniedPaths,
11916
- protectedTestPaths,
11917
- // The files already shown are evidence for the parse check that the project parses (`syntaxCheck.ts`).
11918
- syntaxSeed: context.entries.map((e) => ({ path: e.path, text: e.content }))
11919
- };
11810
+ var FAILURE_FILE_LINE_RE = /^[ \t]*File:[ \t]*(\S[^\r\n]*?:\d+(?::\d+)?)[ \t]*$/m;
11811
+ var MAX_FAILURE_LOCATION = 300;
11812
+ function parseFailureLocation(body) {
11813
+ const found = FAILURE_FILE_LINE_RE.exec(unescapeXmlEntities(body));
11814
+ if (!found) return null;
11815
+ const path = normalizeSlashes(found[1]);
11816
+ const root = `${normalizeSlashes(process.cwd()).replace(/\/+$/, "")}/`;
11817
+ const shown = path.startsWith(root) ? path.slice(root.length) : path;
11818
+ return shown.length > MAX_FAILURE_LOCATION ? `${shown.slice(0, MAX_FAILURE_LOCATION)}\u2026` : shown;
11920
11819
  }
11921
- var NO_SUMMARY = {
11922
- turns: 0,
11923
- toolCalls: 0,
11924
- refused: 0,
11925
- stopReason: "fallback",
11926
- reads: [],
11927
- edits: [],
11928
- created: [],
11929
- statusCounts: {},
11930
- syntaxWarnings: 0,
11931
- reasoning: []
11932
- };
11933
- function perFile(p) {
11934
- return runCodegen(
11935
- p.gateway,
11936
- p.targets,
11937
- p.workspaceListing,
11938
- p.requiredTests,
11939
- p.deniedPaths,
11940
- p.judgedByPool,
11941
- p.warnings,
11942
- p.contextLog,
11943
- p.outOfScope
11944
- );
11820
+ function extractFailureText(testcaseBody) {
11821
+ const tag = FAILURE_TAG_RE.exec(testcaseBody);
11822
+ if (!tag) return null;
11823
+ const [, attrs = "", inner = ""] = tag;
11824
+ const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];
11825
+ const raw = (messageAttr ?? inner).trim();
11826
+ if (!raw) return null;
11827
+ const text = unescapeXmlEntities(raw);
11828
+ const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;
11829
+ const location = messageAttr === void 0 ? null : parseFailureLocation(inner);
11830
+ return location ? `${shortened} [at ${location}]` : shortened;
11945
11831
  }
11946
- async function runCodegenStep(p) {
11947
- if (p.mode !== "loop") return perFile(p);
11948
- const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} });
11949
- p.contextLog.push(...context.records);
11950
- console.log(
11951
- JSON.stringify({
11952
- event: "codegen.loop_context",
11953
- files: context.entries.length,
11954
- chars: context.entries.reduce((n, e) => n + e.content.length, 0),
11955
- paths: context.entries.map((e) => e.path),
11956
- existingTests: context.testPaths
11957
- })
11958
- );
11959
- try {
11960
- const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p, context), {
11961
- post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
11962
- ...p.deps
11963
- });
11964
- p.out.loop = buildCodegenLoopRecord(summary);
11965
- const planned = new Set(p.targets.map((t) => t.path));
11966
- for (const r of results) {
11967
- if (!planned.has(r.targetPath)) {
11968
- const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;
11969
- p.warnings.push(w);
11970
- console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
11971
- }
11972
- }
11973
- return results;
11974
- } catch (err) {
11975
- if (err instanceof SafetyRefusalError) throw err;
11976
- const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
11977
- p.out.loop = buildCodegenLoopRecord({
11978
- ...failure.summary ?? NO_SUMMARY,
11979
- stopReason: "fallback",
11980
- fellBack: true,
11981
- fallbackReason: failure.reason
11982
- });
11983
- const said = failure.detail ? `: ${failure.detail}` : "";
11984
- const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;
11985
- p.warnings.push(w);
11986
- console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
11987
- return perFile(p);
11832
+ var RESULT_RANK = { pass: 0, skipped: 1, fail: 2 };
11833
+ function parseJUnitOutcomes(xml) {
11834
+ const outcomes = /* @__PURE__ */ new Map();
11835
+ const automationIdResults = /* @__PURE__ */ new Map();
11836
+ const failureText = /* @__PURE__ */ new Map();
11837
+ const discoveredFiles = /* @__PURE__ */ new Set();
11838
+ const discoveredAutomationIds = /* @__PURE__ */ new Set();
11839
+ TESTSUITE_OPEN_RE.lastIndex = 0;
11840
+ let suiteMatch;
11841
+ while (suiteMatch = TESTSUITE_OPEN_RE.exec(xml)) {
11842
+ const file = FILE_ATTR_RE.exec(suiteMatch[1])?.[1];
11843
+ if (file) discoveredFiles.add(normalizeSlashes(file));
11988
11844
  }
11989
- }
11990
-
11991
- // src/dependencyCheck.ts
11992
- var import_node_fs5 = require("node:fs");
11993
- var import_node_path6 = require("node:path");
11994
- var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
11995
- var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
11996
- var NODE_BUILTINS = /* @__PURE__ */ new Set([
11997
- "assert",
11998
- "buffer",
11999
- "child_process",
12000
- "cluster",
12001
- "crypto",
12002
- "dgram",
12003
- "dns",
12004
- "domain",
12005
- "events",
12006
- "fs",
12007
- "http",
12008
- "http2",
12009
- "https",
12010
- "net",
12011
- "os",
12012
- "path",
12013
- "perf_hooks",
12014
- "process",
12015
- "punycode",
12016
- "querystring",
12017
- "readline",
12018
- "repl",
12019
- "stream",
12020
- "string_decoder",
12021
- "sys",
12022
- "timers",
12023
- "tls",
12024
- "tty",
12025
- "url",
12026
- "util",
12027
- "v8",
12028
- "vm",
12029
- "worker_threads",
12030
- "zlib",
12031
- "inspector",
12032
- "async_hooks"
12033
- ]);
12034
- var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
12035
- function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12036
- if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
12037
- if (specifier.startsWith("node:")) return null;
12038
- if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
12039
- const segments = specifier.split("/");
12040
- const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
12041
- if (NODE_BUILTINS.has(name)) return null;
12042
- return name;
12043
- }
12044
- function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12045
- const found = /* @__PURE__ */ new Set();
12046
11845
  let match;
12047
- IMPORT_RE.lastIndex = 0;
12048
- while (match = IMPORT_RE.exec(source)) {
12049
- const name = packageNameFromSpecifier(match[2], aliasPrefixes);
12050
- if (name) found.add(name);
12051
- }
12052
- return [...found];
12053
- }
12054
- function checkImportDependencies(results, declaredDependencies, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12055
- if (!declaredDependencies) return { blocked: false, violations: [] };
12056
- const violations = [];
12057
- for (const { targetPath, newContent } of results) {
12058
- if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
12059
- const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
12060
- if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
12061
- }
12062
- return { blocked: violations.length > 0, violations };
12063
- }
12064
- function dependencyNames(pkg) {
12065
- return /* @__PURE__ */ new Set([
12066
- ...Object.keys(pkg.dependencies ?? {}),
12067
- ...Object.keys(pkg.devDependencies ?? {}),
12068
- ...Object.keys(pkg.peerDependencies ?? {})
12069
- ]);
12070
- }
12071
- function readDeclaredDependencies(results, workspaceRoot) {
12072
- const packageJsonPath = (0, import_node_path6.join)((0, import_node_path6.resolve)(workspaceRoot ?? "."), "package.json");
12073
- const generated = results.find((r) => (0, import_node_path6.resolve)(r.targetPath) === packageJsonPath);
12074
- let raw;
12075
- if (generated) {
12076
- raw = generated.newContent;
12077
- } else {
12078
- try {
12079
- raw = (0, import_node_fs5.readFileSync)(packageJsonPath, "utf8");
12080
- } catch {
12081
- raw = null;
11846
+ TESTCASE_RE.lastIndex = 0;
11847
+ while (match = TESTCASE_RE.exec(xml)) {
11848
+ const [, attrs, body = ""] = match;
11849
+ const rawName = NAME_ATTR_RE.exec(attrs)?.[1];
11850
+ if (!rawName) continue;
11851
+ const name = unescapeXmlEntities(rawName);
11852
+ const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];
11853
+ const classname = rawClassname === void 0 ? void 0 : unescapeXmlEntities(rawClassname);
11854
+ const id = classname ? `${classname}::${name}` : name;
11855
+ const failed = FAILURE_CHILD_RE.test(body);
11856
+ outcomes.set(id, !failed);
11857
+ if (failed) {
11858
+ const text = extractFailureText(body);
11859
+ if (text) failureText.set(id, text);
11860
+ }
11861
+ const file = FILE_ATTR_RE.exec(attrs)?.[1];
11862
+ if (file) discoveredFiles.add(normalizeSlashes(file));
11863
+ if (classname) discoveredFiles.add(normalizeSlashes(classname));
11864
+ const bracket = QP_TOKEN_BRACKET_RE.exec(name)?.[1];
11865
+ if (bracket) {
11866
+ discoveredAutomationIds.add(bracket);
11867
+ const result = failed ? "fail" : SKIPPED_CHILD_RE.test(body) ? "skipped" : "pass";
11868
+ const seen = automationIdResults.get(bracket);
11869
+ if (!seen || RESULT_RANK[result] > RESULT_RANK[seen]) automationIdResults.set(bracket, result);
12082
11870
  }
12083
11871
  }
12084
- if (raw === null) return null;
11872
+ return { outcomes, automationIdResults, failureText, discoveredFiles, discoveredAutomationIds };
11873
+ }
11874
+ function readJUnitOutcomes(cwd) {
11875
+ const report = findJUnitReport(cwd);
11876
+ if (!report) return null;
12085
11877
  try {
12086
- return dependencyNames(JSON.parse(raw));
11878
+ return parseJUnitOutcomes((0, import_node_fs8.readFileSync)(report, "utf8"));
12087
11879
  } catch {
12088
11880
  return null;
12089
11881
  }
12090
11882
  }
12091
- function stripJsonComments(text) {
12092
- let out = "";
12093
- let inString = false;
12094
- let inLineComment = false;
12095
- let inBlockComment = false;
12096
- for (let i2 = 0; i2 < text.length; i2++) {
12097
- const c = text[i2];
12098
- const next = text[i2 + 1];
12099
- if (inLineComment) {
12100
- if (c === "\n") {
12101
- inLineComment = false;
12102
- out += c;
12103
- }
12104
- continue;
12105
- }
12106
- if (inBlockComment) {
12107
- if (c === "*" && next === "/") {
12108
- inBlockComment = false;
12109
- i2++;
11883
+ function readAutomationIdResults(cwd = process.cwd()) {
11884
+ return readJUnitOutcomes(cwd)?.automationIdResults ?? null;
11885
+ }
11886
+ function captureTestSnapshot(command, cwd = process.cwd()) {
11887
+ const outcome = runTestCommand(command);
11888
+ const parsed = readJUnitOutcomes(cwd);
11889
+ return {
11890
+ outcome,
11891
+ results: parsed?.outcomes ?? null,
11892
+ failureText: parsed?.failureText,
11893
+ discoveredFiles: parsed?.discoveredFiles ?? null,
11894
+ discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
11895
+ };
11896
+ }
11897
+ function readTestSnapshot(outcome, cwd = process.cwd()) {
11898
+ const parsed = readJUnitOutcomes(cwd);
11899
+ return {
11900
+ outcome,
11901
+ results: parsed?.outcomes ?? null,
11902
+ failureText: parsed?.failureText,
11903
+ discoveredFiles: parsed?.discoveredFiles ?? null,
11904
+ discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
11905
+ };
11906
+ }
11907
+ async function captureBaselineSnapshot(command, cwd = process.cwd()) {
11908
+ const outcome = await runTestCommandAsync(command);
11909
+ const parsed = readJUnitOutcomes(cwd);
11910
+ return {
11911
+ outcome,
11912
+ results: parsed?.outcomes ?? null,
11913
+ failureText: parsed?.failureText,
11914
+ discoveredFiles: parsed?.discoveredFiles ?? null,
11915
+ discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
11916
+ };
11917
+ }
11918
+ function checkForRegressions(baseline, after) {
11919
+ if (!baseline.results || !after.results) {
11920
+ return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: /* @__PURE__ */ new Map() };
11921
+ }
11922
+ const regressions = [];
11923
+ const newFailures = [];
11924
+ const preExisting = [];
11925
+ const failureText = /* @__PURE__ */ new Map();
11926
+ const afterFailureText = after.failureText;
11927
+ for (const [testId, passed] of after.results) {
11928
+ if (passed) continue;
11929
+ const before = baseline.results.get(testId);
11930
+ if (before === true) {
11931
+ regressions.push(testId);
11932
+ const text = afterFailureText?.get(testId);
11933
+ if (text) failureText.set(testId, text);
11934
+ } else if (before === false) {
11935
+ preExisting.push(testId);
11936
+ } else {
11937
+ newFailures.push(testId);
11938
+ const text = afterFailureText?.get(testId);
11939
+ if (text) failureText.set(testId, text);
11940
+ }
11941
+ }
11942
+ return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };
11943
+ }
11944
+ function describeRegressions(check) {
11945
+ const withText = (id) => {
11946
+ const text = check.failureText.get(id);
11947
+ return text ? `${id} (${text})` : id;
11948
+ };
11949
+ const parts = [];
11950
+ if (check.regressions.length > 0) {
11951
+ parts.push(
11952
+ `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(", ")}`
11953
+ );
11954
+ }
11955
+ if (check.newFailures.length > 0) {
11956
+ parts.push(
11957
+ `${check.newFailures.length} new failure(s) (did not exist before): ${check.newFailures.map(withText).join(", ")}`
11958
+ );
11959
+ }
11960
+ if (check.preExisting.length > 0) {
11961
+ parts.push(`${check.preExisting.length} pre-existing failure(s), unrelated to this change, not blocking`);
11962
+ }
11963
+ return parts.join("; ");
11964
+ }
11965
+
11966
+ // src/runTestsTool.ts
11967
+ var RUN_TESTS_TOOL = "run_tests";
11968
+ var MAX_TEST_RUNS = 3;
11969
+ var MIN_TEST_LIMIT_MS = 12e4;
11970
+ var MAX_TEST_LIMIT_MS = 6e5;
11971
+ var DEFAULT_TEST_LIMIT_MS = 3e5;
11972
+ var MAX_LISTED_TESTS = 20;
11973
+ var MAX_TEST_NAME_CHARS = 200;
11974
+ var FRESH_SLACK_MS = 2e3;
11975
+ function testTimeLimitMs(baselineMs) {
11976
+ if (baselineMs === null) return DEFAULT_TEST_LIMIT_MS;
11977
+ if (baselineMs > MAX_TEST_LIMIT_MS) return "too_slow";
11978
+ return Math.min(MAX_TEST_LIMIT_MS, Math.max(MIN_TEST_LIMIT_MS, baselineMs * 3));
11979
+ }
11980
+ var MESSAGES = {
11981
+ tests_passed: "The tests passed.",
11982
+ tests_failed: "Some tests failed. output lists their names, regressions first: a regression passed before your change.",
11983
+ timed_out: "The tests did not finish within the time limit and were stopped.",
11984
+ no_report: "The test run produced no readable report, so there is nothing to tell you about the tests.",
11985
+ no_change_since_last_run: "Nothing has been changed since the last test run; change something first.",
11986
+ tests_exhausted: "No test runs are left. Finish with what you have, or say you cannot complete it.",
11987
+ no_progress: "The same tests failed as in the last run. Another run would not help; say you cannot complete it if you cannot fix it.",
11988
+ tests_unavailable: "The tests could not be run here.",
11989
+ tests_too_slow: "This project's test suite is too slow to run inside this loop."
11990
+ };
11991
+ var sha = (s) => (0, import_node_crypto2.createHash)("sha256").update(s).digest("hex");
11992
+ function versionOfFiles(files) {
11993
+ const h = (0, import_node_crypto2.createHash)("sha256");
11994
+ for (const f of [...files].sort((a, b) => a.path.localeCompare(b.path))) {
11995
+ h.update(f.path);
11996
+ h.update("\0");
11997
+ h.update(typeof f.content === "string" ? f.content : f.content.toString("utf8"));
11998
+ h.update("\0");
11999
+ }
12000
+ return h.digest("hex");
12001
+ }
12002
+ var RunTestsTool = class {
12003
+ constructor(deps) {
12004
+ this.deps = deps;
12005
+ this.maxRuns = deps.maxRuns ?? MAX_TEST_RUNS;
12006
+ }
12007
+ deps;
12008
+ runs = 0;
12009
+ locked = false;
12010
+ lastVersion = null;
12011
+ lastFailingKey = null;
12012
+ entries = [];
12013
+ maxRuns;
12014
+ /** What the runtime is told is left (`remaining.testRuns`): zero once the runs are used up or a no-progress stop has happened. */
12015
+ get runsLeft() {
12016
+ return this.locked ? 0 : Math.max(0, this.maxRuns - this.runs);
12017
+ }
12018
+ record() {
12019
+ return this.entries.map((e) => ({ ...e }));
12020
+ }
12021
+ answer(id, status, parts = {}) {
12022
+ const result = {
12023
+ id,
12024
+ name: RUN_TESTS_TOOL,
12025
+ status,
12026
+ ...parts.reason ? { reason: parts.reason } : {},
12027
+ message: MESSAGES[status] ?? "",
12028
+ ...parts.output !== void 0 ? { output: parts.output } : {}
12029
+ };
12030
+ if (status !== "no_change_since_last_run" && status !== "tests_exhausted") {
12031
+ const entry = {
12032
+ n: this.entries.length + 1,
12033
+ status,
12034
+ ...parts.reason ? { reason: parts.reason } : {},
12035
+ passed: 0,
12036
+ failed: 0,
12037
+ regressions: 0,
12038
+ newFailures: 0,
12039
+ alreadyFailing: 0,
12040
+ timedOut: false,
12041
+ seconds: parts.seconds ?? 0,
12042
+ ...parts.counts
12043
+ };
12044
+ this.entries.push(entry);
12045
+ this.deps.log?.({
12046
+ event: "codegen.run_tests",
12047
+ n: this.entries.length,
12048
+ status,
12049
+ ...parts.reason ? { reason: parts.reason } : {},
12050
+ passed: entry.passed,
12051
+ failed: entry.failed,
12052
+ regressions: entry.regressions,
12053
+ newFailures: entry.newFailures,
12054
+ timedOut: entry.timedOut,
12055
+ seconds: entry.seconds
12056
+ });
12057
+ }
12058
+ return result;
12059
+ }
12060
+ async execute(callId) {
12061
+ const d = this.deps;
12062
+ const now = d.now ?? Date.now;
12063
+ if (this.locked || this.runs >= this.maxRuns) return this.answer(callId, "tests_exhausted");
12064
+ const files = d.overlayFiles();
12065
+ if (files.length === 0) return this.answer(callId, "no_change_since_last_run", { reason: "nothing_written" });
12066
+ const version2 = d.overlayVersion();
12067
+ if (version2 === this.lastVersion) return this.answer(callId, "no_change_since_last_run");
12068
+ if (!d.command) return this.answer(callId, "tests_unavailable", { reason: "no_test_command" });
12069
+ const baseline = await d.baseline();
12070
+ const limit = testTimeLimitMs(baseline?.durationMs ?? null);
12071
+ if (limit === "too_slow") return this.answer(callId, "tests_too_slow", { reason: "baseline_over_ten_minutes" });
12072
+ const findReport = d.findReport ?? findJUnitReport;
12073
+ const runCommand2 = d.runCommand ?? runTestCommandWithLimit;
12074
+ const readSnapshot = d.readSnapshot ?? readTestSnapshot;
12075
+ const reportBefore = findReport(d.root);
12076
+ const preserve = reportBefore ? [(0, import_node_path9.relative)(d.root, reportBefore).split("\\").join("/")] : [];
12077
+ this.runs += 1;
12078
+ const startedAt = now();
12079
+ let ran;
12080
+ try {
12081
+ ran = await withOverlayOnDisk(
12082
+ d.root,
12083
+ files,
12084
+ async () => {
12085
+ const run2 = await runCommand2(d.command, limit, d.root);
12086
+ if (!run2.started || run2.timedOut) return { run: run2, snapshot: null };
12087
+ const report = findReport(d.root);
12088
+ let fresh = false;
12089
+ if (report) {
12090
+ try {
12091
+ fresh = (0, import_node_fs9.statSync)(report).mtimeMs >= startedAt - FRESH_SLACK_MS;
12092
+ } catch {
12093
+ fresh = false;
12094
+ }
12095
+ }
12096
+ const snapshot = fresh ? readSnapshot(run2.outcome, d.root) : null;
12097
+ return { run: run2, snapshot: snapshot && snapshot.results ? snapshot : null };
12098
+ },
12099
+ { ...d.tree, preserve }
12100
+ );
12101
+ } catch (err) {
12102
+ if (err instanceof TreeNotRestoredError) throw err;
12103
+ this.runs -= 1;
12104
+ if (err instanceof TreeUnverifiableError) return this.answer(callId, "tests_unavailable", { reason: "checkout_unverifiable" });
12105
+ if (err instanceof DiskWriteRefused) return this.answer(callId, "tests_unavailable", { reason: "write_refused" });
12106
+ throw err;
12107
+ }
12108
+ const seconds = Math.round((now() - startedAt) / 1e3);
12109
+ if (!ran.run.started) {
12110
+ this.runs -= 1;
12111
+ return this.answer(callId, "tests_unavailable", { reason: "could_not_start", seconds });
12112
+ }
12113
+ this.lastVersion = version2;
12114
+ if (ran.run.timedOut) {
12115
+ this.lastFailingKey = null;
12116
+ return this.answer(callId, "timed_out", {
12117
+ seconds,
12118
+ counts: { timedOut: true },
12119
+ output: { passed: 0, failed: 0, total: 0, regressions: 0, newFailures: 0, alreadyFailing: 0, failingTests: [], timedOut: true, truncated: false }
12120
+ });
12121
+ }
12122
+ if (!ran.snapshot || !ran.snapshot.results || ran.snapshot.results.size === 0) {
12123
+ this.lastFailingKey = null;
12124
+ return this.answer(callId, "no_report", { seconds });
12125
+ }
12126
+ const after = ran.snapshot;
12127
+ let passed = 0;
12128
+ let failed = 0;
12129
+ for (const ok of after.results.values()) ok ? passed++ : failed++;
12130
+ let regressions;
12131
+ let newFailures;
12132
+ let alreadyFailing;
12133
+ if (baseline?.snapshot.results) {
12134
+ const check = checkForRegressions(baseline.snapshot, after);
12135
+ regressions = check.regressions;
12136
+ newFailures = check.newFailures;
12137
+ alreadyFailing = check.preExisting;
12138
+ } else {
12139
+ regressions = [];
12140
+ newFailures = [...after.results.entries()].filter(([, ok]) => !ok).map(([id]) => id);
12141
+ alreadyFailing = [];
12142
+ }
12143
+ const ordered = [...regressions, ...newFailures, ...alreadyFailing];
12144
+ const names = ordered.slice(0, MAX_LISTED_TESTS).map((n) => scrubSecrets(n).slice(0, MAX_TEST_NAME_CHARS));
12145
+ const output = {
12146
+ passed,
12147
+ failed,
12148
+ total: passed + failed,
12149
+ regressions: regressions.length,
12150
+ newFailures: newFailures.length,
12151
+ alreadyFailing: alreadyFailing.length,
12152
+ failingTests: names,
12153
+ timedOut: false,
12154
+ truncated: ordered.length > names.length
12155
+ };
12156
+ const counts = { passed, failed, regressions: regressions.length, newFailures: newFailures.length, alreadyFailing: alreadyFailing.length };
12157
+ const green = failed === 0 && ran.run.outcome === "success";
12158
+ const failingKey = failed > 0 ? sha([...ordered].sort().join("\0")) : null;
12159
+ if (!green && failingKey !== null && failingKey === this.lastFailingKey) {
12160
+ this.locked = true;
12161
+ return this.answer(callId, "no_progress", { output, counts, seconds });
12162
+ }
12163
+ this.lastFailingKey = failingKey;
12164
+ return this.answer(callId, green ? "tests_passed" : "tests_failed", { output, counts, seconds });
12165
+ }
12166
+ };
12167
+ async function executeRunTestsCall(call, tool, ledger, limits) {
12168
+ const finish = (r) => {
12169
+ const result2 = { id: call.id, name: call.name, ...r };
12170
+ ledger.resultChars += JSON.stringify(result2).length;
12171
+ if (result2.status === "refused") ledger.refused += 1;
12172
+ return result2;
12173
+ };
12174
+ if (ledger.toolCalls >= limits.maxToolCalls) return finish(budgetResult("tool_calls"));
12175
+ ledger.toolCalls += 1;
12176
+ const args = call.args;
12177
+ if (typeof args !== "object" || args === null || Array.isArray(args) || Object.keys(args).length > 0) {
12178
+ return finish({ status: "bad_args", message: "run_tests takes no arguments." });
12179
+ }
12180
+ const result = await tool.execute(call.id);
12181
+ ledger.resultChars += JSON.stringify(result).length;
12182
+ return result;
12183
+ }
12184
+
12185
+ // src/targetingErrors.ts
12186
+ var DeniedPathError = class extends Error {
12187
+ constructor(message) {
12188
+ super(message);
12189
+ this.name = "DeniedPathError";
12190
+ }
12191
+ };
12192
+ var TargetingHttpError = class extends Error {
12193
+ status;
12194
+ constructor(status, statusText) {
12195
+ super(`Targeting call failed: ${status} ${statusText}`);
12196
+ this.name = "TargetingHttpError";
12197
+ this.status = status;
12198
+ }
12199
+ };
12200
+
12201
+ // src/tokenEstimate.ts
12202
+ var TOKENS_PER_ALPHA_CHAR = 0.3;
12203
+ var TOKENS_PER_DIGIT_CHAR = 0.18;
12204
+ var TOKENS_PER_SPACE_CHAR = 0.05;
12205
+ var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
12206
+ var TOKENS_PER_NON_ASCII_CHAR = 1;
12207
+ var PROMPT_OVERHEAD_TOKENS = 5e3;
12208
+ function estimateTokens(text) {
12209
+ let alpha = 0;
12210
+ let digit = 0;
12211
+ let space = 0;
12212
+ let punct = 0;
12213
+ let nonAscii = 0;
12214
+ for (const ch of text) {
12215
+ const code = ch.codePointAt(0);
12216
+ if (code >= 128) nonAscii++;
12217
+ else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
12218
+ else if (code >= 48 && code <= 57) digit++;
12219
+ else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
12220
+ else punct++;
12221
+ }
12222
+ return Math.ceil(
12223
+ alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
12224
+ );
12225
+ }
12226
+ function estimateRequestTokens(contextData) {
12227
+ return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
12228
+ }
12229
+
12230
+ // src/targetingLoop.ts
12231
+ var LOOP_CONTRACT_VERSION = "targeting-loop-1";
12232
+ var LoopFailure = class extends Error {
12233
+ reason;
12234
+ runtimeCode;
12235
+ /** What the loop had done when it failed, so reads made before the failure are not lost. */
12236
+ summary;
12237
+ constructor(reason, runtimeCode, cause) {
12238
+ super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
12239
+ this.name = "LoopFailure";
12240
+ this.reason = reason;
12241
+ this.runtimeCode = runtimeCode;
12242
+ if (cause !== void 0) this.cause = cause;
12243
+ }
12244
+ };
12245
+ var SafetyRefusalError = class extends RuntimeReplyError {
12246
+ constructor(message, summary) {
12247
+ super(message, summary);
12248
+ this.name = "SafetyRefusalError";
12249
+ }
12250
+ };
12251
+ var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
12252
+ var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
12253
+ var MAX_ID_CHARS = 64;
12254
+ var MAX_CALLS_IN_A_REPLY = 50;
12255
+ var MAX_ARGS_JSON_CHARS = 1e3;
12256
+ function isPlainObject2(x) {
12257
+ return typeof x === "object" && x !== null && !Array.isArray(x);
12258
+ }
12259
+ function safeArgs(args) {
12260
+ try {
12261
+ return JSON.stringify(args).length <= MAX_ARGS_JSON_CHARS ? args : { _omitted: "too large" };
12262
+ } catch {
12263
+ return { _omitted: "unreadable" };
12264
+ }
12265
+ }
12266
+ function classifyTransport(err) {
12267
+ if (err instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err);
12268
+ const name = err?.name;
12269
+ if (name === "TimeoutError" || name === "AbortError") return new LoopFailure("turn_timeout", void 0, err);
12270
+ return new LoopFailure("transport", void 0, err);
12271
+ }
12272
+ async function runTargetingLoop(args, deps) {
12273
+ const limits = { ...DEFAULT_LIMITS, ...deps.limits };
12274
+ const now = deps.now ?? Date.now;
12275
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
12276
+ const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
12277
+ const deadlineMs = deps.deadlineMs ?? 6e5;
12278
+ const env2 = {
12279
+ listing: new Set(args.listing),
12280
+ visible: buildVisibleListing(args.listing, args.deniedPaths),
12281
+ deniedPaths: args.deniedPaths,
12282
+ fs: deps.fs ?? createNodeToolFs(),
12283
+ limits
12284
+ };
12285
+ const ledger = newLedger();
12286
+ const reads = [];
12287
+ const transcript = [];
12288
+ const toolResults = [];
12289
+ const usedIds = /* @__PURE__ */ new Set();
12290
+ let turns = 0;
12291
+ let noProgressStreak = 0;
12292
+ let forced = null;
12293
+ const started = now();
12294
+ const buildContext = (turn, isFinal, finalReason) => ({
12295
+ ...args.baseContext,
12296
+ contractVersion: LOOP_CONTRACT_VERSION,
12297
+ loop: {
12298
+ turn,
12299
+ maxTurns: limits.maxTurns,
12300
+ final: isFinal,
12301
+ ...isFinal ? { finalReason } : {},
12302
+ remaining: {
12303
+ toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
12304
+ readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
12305
+ },
12306
+ transcript,
12307
+ toolResults
12308
+ }
12309
+ });
12310
+ const snapshot = (stopReason) => ({
12311
+ turns,
12312
+ toolCalls: ledger.toolCalls,
12313
+ readChars: ledger.readChars,
12314
+ refused: ledger.refused,
12315
+ stopReason,
12316
+ reads: [...reads]
12317
+ });
12318
+ log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
12319
+ try {
12320
+ for (let turn = 1; turn <= limits.maxTurns; turn++) {
12321
+ turns = turn;
12322
+ if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
12323
+ const isFinal = forced !== null || turn === limits.maxTurns;
12324
+ const finalReason = forced ?? "max_turns";
12325
+ const contextData = buildContext(turn, isFinal, finalReason);
12326
+ const requestChars = JSON.stringify(contextData).length;
12327
+ const requestTokens = estimateRequestTokens(contextData);
12328
+ if (requestTokens > limits.maxRequestTokens) {
12329
+ log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
12330
+ throw new LoopFailure("token_ceiling");
12331
+ }
12332
+ const turnStarted = now();
12333
+ let envelope;
12334
+ try {
12335
+ envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
12336
+ } catch (err) {
12337
+ throw classifyTransport(err);
12338
+ }
12339
+ const code = envelope?.errorCode;
12340
+ try {
12341
+ checkHardFailure(envelope, "pilot.targeting");
12342
+ } catch (err) {
12343
+ throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
12344
+ }
12345
+ if (envelope?.success === false) {
12346
+ const runtimeCode = typeof code === "string" ? code : void 0;
12347
+ if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
12348
+ let inner;
12349
+ try {
12350
+ unwrapExecute(envelope, "pilot.targeting");
12351
+ } catch (e) {
12352
+ inner = e instanceof RuntimeReplyError ? e : void 0;
12353
+ }
12354
+ const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
12355
+ throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
12356
+ }
12357
+ throw new LoopFailure("runtime_failed", runtimeCode);
12358
+ }
12359
+ let body;
12360
+ try {
12361
+ body = unwrapExecute(envelope, "pilot.targeting");
12362
+ } catch (err) {
12363
+ throw new LoopFailure("bad_reply", void 0, err);
12364
+ }
12365
+ if (body.outcome === "TARGETED" || body.outcome === "NO_TARGET") {
12366
+ log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
12367
+ const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
12368
+ log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
12369
+ return { body, summary: snapshot(stopReason) };
12370
+ }
12371
+ if (body.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
12372
+ if (isFinal) throw new LoopFailure("final_not_produced");
12373
+ const rawCalls = body.toolCalls;
12374
+ if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
12375
+ throw new LoopFailure("bad_reply");
12376
+ }
12377
+ const calls = [];
12378
+ for (const c of rawCalls) {
12379
+ if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
12380
+ throw new LoopFailure("bad_reply");
12381
+ }
12382
+ if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
12383
+ calls.push({ id: c.id, name: c.name, args: c.args });
12384
+ }
12385
+ for (const c of calls) usedIds.add(c.id);
12386
+ const results = [];
12387
+ const logged = [];
12388
+ const turnReads = [];
12389
+ calls.forEach((call, index) => {
12390
+ let result;
12391
+ let read;
12392
+ if (index >= limits.maxCallsPerTurn) {
12393
+ result = {
12394
+ id: call.id,
12395
+ name: call.name,
12396
+ status: "budget_exhausted",
12397
+ reason: "too_many_calls",
12398
+ message: "Too many calls in one turn; this one was not run."
12399
+ };
12400
+ } else {
12401
+ try {
12402
+ ({ result, read } = executeToolCall(call, env2, ledger));
12403
+ } catch (err) {
12404
+ throw new LoopFailure("executor_error", void 0, err);
12405
+ }
12406
+ }
12407
+ results.push(result);
12408
+ turnReads[index] = read;
12409
+ if (read) reads.push(read);
12410
+ const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
12411
+ const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
12412
+ logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
12413
+ if (result.status === "refused") {
12414
+ log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
12415
+ }
12416
+ });
12417
+ const reasoning = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
12418
+ transcript.push({
12419
+ turn,
12420
+ ...reasoning ? { reasoning } : {},
12421
+ toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
12422
+ });
12423
+ toolResults.push(...results);
12424
+ noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
12425
+ if (noProgressStreak >= 2) forced = "no_progress";
12426
+ else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
12427
+ else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
12428
+ const nextTurn = turn + 1;
12429
+ if (nextTurn <= limits.maxTurns) {
12430
+ const nextFinal = forced !== null || nextTurn === limits.maxTurns;
12431
+ const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
12432
+ if (projected > limits.maxRequestTokens) {
12433
+ results.forEach((r, idx) => {
12434
+ if (r.status !== "ok") return;
12435
+ toolResults[toolResults.indexOf(r)] = {
12436
+ id: r.id,
12437
+ name: r.name,
12438
+ status: "budget_exhausted",
12439
+ reason: "token_ceiling",
12440
+ message: "Too large to include; answer from what you have."
12441
+ };
12442
+ const dropped = turnReads[idx];
12443
+ if (dropped) {
12444
+ const at2 = reads.indexOf(dropped);
12445
+ if (at2 >= 0) reads.splice(at2, 1);
12446
+ }
12447
+ logged[idx].status = "budget_exhausted";
12448
+ logged[idx].reason = "token_ceiling";
12449
+ });
12450
+ forced = "read_budget";
12451
+ const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
12452
+ const fits = trimmed <= limits.maxRequestTokens;
12453
+ log({
12454
+ event: "targeting.loop_ceiling",
12455
+ turn,
12456
+ action: fits ? "dropped_results" : "fallback",
12457
+ projectedTokens: projected,
12458
+ ceiling: limits.maxRequestTokens
12459
+ });
12460
+ if (!fits) throw new LoopFailure("token_ceiling");
12461
+ }
12110
12462
  }
12111
- continue;
12463
+ log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
12112
12464
  }
12113
- if (inString) {
12114
- out += c;
12115
- if (c === "\\") {
12116
- out += next;
12117
- i2++;
12118
- continue;
12465
+ throw new LoopFailure("final_not_produced");
12466
+ } catch (err) {
12467
+ if (err instanceof SafetyRefusalError) throw err;
12468
+ const failure = err instanceof LoopFailure ? err : new LoopFailure("internal_error", void 0, err);
12469
+ failure.summary ??= snapshot("fallback");
12470
+ throw failure;
12471
+ }
12472
+ }
12473
+
12474
+ // src/codegenLoop.ts
12475
+ var CODEGEN_LOOP_CONTRACT_VERSION = "codegen-loop-1";
12476
+ var CODEGEN_LOOP_2_CONTRACT_VERSION = "codegen-loop-2";
12477
+ var CodegenLoopFailure = class extends Error {
12478
+ reason;
12479
+ runtimeCode;
12480
+ /** Short, runner-written (or, for CANNOT_COMPLETE, the AI's own summary cut to 300 characters). Never file content. */
12481
+ detail;
12482
+ summary;
12483
+ constructor(reason, runtimeCode, cause, detail) {
12484
+ super(`pilot.codegen loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
12485
+ this.name = "CodegenLoopFailure";
12486
+ this.reason = reason;
12487
+ this.runtimeCode = runtimeCode;
12488
+ this.detail = detail;
12489
+ if (cause !== void 0) this.cause = cause;
12490
+ }
12491
+ };
12492
+ var MAX_ID_CHARS2 = 64;
12493
+ var MAX_CALLS_IN_A_REPLY2 = 50;
12494
+ var MAX_SUMMARY_CHARS = 300;
12495
+ var READ_TOOLS = /* @__PURE__ */ new Set(["list_files", "read_file", "grep"]);
12496
+ var WRITE_TOOLS = /* @__PURE__ */ new Set(["edit_file", "write_file"]);
12497
+ var TOOL_NAMES2 = /* @__PURE__ */ new Set([...READ_TOOLS, ...WRITE_TOOLS, RUN_TESTS_TOOL]);
12498
+ function isPlainObject3(x) {
12499
+ return typeof x === "object" && x !== null && !Array.isArray(x);
12500
+ }
12501
+ function classifyTransport2(err) {
12502
+ if (err instanceof TargetingHttpError) return new CodegenLoopFailure("http_error", void 0, err);
12503
+ const name = err?.name;
12504
+ if (name === "TimeoutError" || name === "AbortError") return new CodegenLoopFailure("turn_timeout", void 0, err);
12505
+ return new CodegenLoopFailure("transport", void 0, err);
12506
+ }
12507
+ var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
12508
+ async function runCodegenLoop(args, deps) {
12509
+ const ws = createCodegenWorkspace({
12510
+ listing: args.listing,
12511
+ deniedPaths: args.deniedPaths,
12512
+ protectedTestPaths: args.protectedTestPaths,
12513
+ fs: deps.fs,
12514
+ limits: deps.limits,
12515
+ syntaxSeed: args.syntaxSeed
12516
+ });
12517
+ const { env: env2, ledger, overlay, limits } = ws;
12518
+ const now = deps.now ?? Date.now;
12519
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
12520
+ const filesOnDisk = () => overlay.results().map((r) => ({ path: r.targetPath, content: r.newContent }));
12521
+ const tests = args.tests ? new RunTestsTool({ ...args.tests, overlayFiles: filesOnDisk, overlayVersion: () => versionOfFiles(filesOnDisk()), log, now }) : null;
12522
+ let testMs = 0;
12523
+ const turnTimeoutMs = deps.turnTimeoutMs ?? 3e5;
12524
+ const deadlineMs = deps.deadlineMs ?? 15e5;
12525
+ const reads = [];
12526
+ const reasoning = [];
12527
+ const statusCounts = {};
12528
+ const transcript = [];
12529
+ const toolResults = [];
12530
+ const usedIds = /* @__PURE__ */ new Set();
12531
+ let turns = 0;
12532
+ let noProgressStreak = 0;
12533
+ let forced = null;
12534
+ const started = now();
12535
+ const buildContext = (turn, isFinal, finalReason) => ({
12536
+ ...args.baseContext,
12537
+ contractVersion: tests ? CODEGEN_LOOP_2_CONTRACT_VERSION : CODEGEN_LOOP_CONTRACT_VERSION,
12538
+ loop: {
12539
+ turn,
12540
+ maxTurns: limits.maxTurns,
12541
+ final: isFinal,
12542
+ ...isFinal ? { finalReason } : {},
12543
+ remaining: {
12544
+ toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
12545
+ readChars: Math.max(0, limits.readCharsTotal - ledger.readChars),
12546
+ writeChars: Math.max(0, limits.writeCharsTotal - ledger.writeChars),
12547
+ ...tests ? { testRuns: tests.runsLeft } : {}
12548
+ },
12549
+ transcript,
12550
+ toolResults
12551
+ }
12552
+ });
12553
+ const snapshot = (stopReason) => ({
12554
+ turns,
12555
+ toolCalls: ledger.toolCalls,
12556
+ refused: ledger.refused,
12557
+ stopReason,
12558
+ reads: [...reads],
12559
+ edits: [...ws.edits.entries()].map(([path, count]) => ({ path, count })),
12560
+ created: [...ws.created.entries()].map(([path, chars]) => ({ path, chars })),
12561
+ statusCounts: { ...statusCounts },
12562
+ syntaxWarnings: ws.syntaxWarnings,
12563
+ ...tests ? { contractVersion: CODEGEN_LOOP_2_CONTRACT_VERSION, testRuns: tests.record() } : {},
12564
+ reasoning: [...reasoning]
12565
+ });
12566
+ const makeRoom = (nextTurn, nextFinal, finalReason) => {
12567
+ const fits = () => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limits.maxRequestTokens;
12568
+ if (fits()) return true;
12569
+ const lastTestRun = toolResults.map((r) => r.name).lastIndexOf(RUN_TESTS_TOOL);
12570
+ for (let i2 = 0; i2 < toolResults.length && !fits(); i2++) {
12571
+ const r = toolResults[i2];
12572
+ if (READ_TOOLS.has(r.name) && r.status === "ok" && r.output !== DROPPED_OUTPUT) toolResults[i2] = { ...r, output: DROPPED_OUTPUT };
12573
+ if (r.name === RUN_TESTS_TOOL && i2 !== lastTestRun && r.output !== void 0 && r.output !== DROPPED_OUTPUT) toolResults[i2] = { ...r, output: DROPPED_OUTPUT };
12574
+ }
12575
+ for (const key of [...ledger.seen.keys()]) {
12576
+ if (key.startsWith("read_file:") || key.startsWith("grep:") || key.startsWith("list_files:")) ledger.seen.delete(key);
12577
+ }
12578
+ for (const entry of transcript) {
12579
+ if (fits()) break;
12580
+ entry.toolCalls = entry.toolCalls.map((c) => {
12581
+ if (!WRITE_TOOLS.has(c.name) || !isPlainObject3(c.args) || "_omitted" in c.args) return c;
12582
+ const path = typeof c.args.path === "string" ? { path: c.args.path } : {};
12583
+ return { ...c, args: { ...path, _omitted: "written earlier; read the file to see it" } };
12584
+ });
12585
+ }
12586
+ return fits();
12587
+ };
12588
+ log({ event: "codegen.loop_start", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
12589
+ try {
12590
+ for (let turn = 1; turn <= limits.maxTurns; turn++) {
12591
+ turns = turn;
12592
+ if (now() - started - Math.min(testMs, MAX_TEST_RUNS * MAX_TEST_LIMIT_MS) > deadlineMs) throw new CodegenLoopFailure("loop_deadline");
12593
+ const isFinal = forced !== null || turn === limits.maxTurns;
12594
+ const finalReason = forced ?? "max_turns";
12595
+ const contextData = buildContext(turn, isFinal, finalReason);
12596
+ const requestTokens = estimateRequestTokens(contextData);
12597
+ if (requestTokens > limits.maxRequestTokens) {
12598
+ log({ event: "codegen.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
12599
+ throw new CodegenLoopFailure("token_ceiling");
12600
+ }
12601
+ const turnStarted = now();
12602
+ let envelope;
12603
+ try {
12604
+ envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
12605
+ } catch (err) {
12606
+ throw classifyTransport2(err);
12607
+ }
12608
+ const code = envelope?.errorCode;
12609
+ try {
12610
+ checkHardFailure(envelope, "pilot.codegen");
12611
+ } catch (err) {
12612
+ throw new CodegenLoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err);
12613
+ }
12614
+ if (envelope?.success === false) {
12615
+ const runtimeCode = typeof code === "string" ? code : void 0;
12616
+ if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
12617
+ let inner;
12618
+ try {
12619
+ unwrapExecute(envelope, "pilot.codegen");
12620
+ } catch (e) {
12621
+ inner = e instanceof RuntimeReplyError ? e : void 0;
12622
+ }
12623
+ const fallbackText = `pilot.codegen failed: ${runtimeCode}`;
12624
+ throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
12625
+ }
12626
+ throw new CodegenLoopFailure("runtime_failed", runtimeCode);
12627
+ }
12628
+ let body;
12629
+ try {
12630
+ body = unwrapExecute(envelope, "pilot.codegen");
12631
+ } catch (err) {
12632
+ throw new CodegenLoopFailure("bad_reply", void 0, err);
12633
+ }
12634
+ const reasonText = typeof body.reasoning === "string" ? body.reasoning.slice(0, limits.maxReasoningChars) : void 0;
12635
+ if (body.outcome === "CANNOT_COMPLETE") {
12636
+ log({ event: "codegen.loop_turn", turn, outcome: "cannot_complete", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
12637
+ const said = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : void 0;
12638
+ throw new CodegenLoopFailure("cannot_complete", void 0, void 0, said);
12639
+ }
12640
+ if (body.outcome === "DONE") {
12641
+ log({ event: "codegen.loop_turn", turn, outcome: "done", requestTokens, elapsedMs: now() - turnStarted, calls: [] });
12642
+ const changed = overlay.changedPaths();
12643
+ if (changed.length === 0) throw new CodegenLoopFailure("no_writes");
12644
+ const texts = changed.map((p) => overlay.get(p)?.lf ?? "");
12645
+ const missing = args.requiredAutomationIds.filter((id) => !texts.some((t) => t.includes(`[${id}]`)));
12646
+ if (missing.length > 0) {
12647
+ log({ event: "codegen.loop_refused", turn, reason: "coverage_missing", missing: missing.length });
12648
+ throw new CodegenLoopFailure("coverage_missing", void 0, void 0, `${missing.length} required test case(s) not written`);
12649
+ }
12650
+ const planSteps = args.targets.flatMap((t) => t.planStepsImplemented);
12651
+ for (const path of changed) {
12652
+ const entry = overlay.get(path);
12653
+ if (!entry || entry.created || entry.originalLf === null) continue;
12654
+ const pseudo = { path, kind: "EXISTING", planStepsImplemented: planSteps };
12655
+ const suspect = looksLikeTruncatedRewrite(pseudo, entry.originalLf, entry.lf);
12656
+ if (suspect) {
12657
+ log({ event: "codegen.loop_refused", turn, reason: "truncation_guard", path });
12658
+ throw new CodegenLoopFailure("truncation_guard", void 0, void 0, `${path}: ${suspect}`);
12659
+ }
12660
+ }
12661
+ const broken = ws.syntaxProblems()[0];
12662
+ if (broken) {
12663
+ log({ event: "codegen.loop_refused", turn, reason: "syntax_error", path: broken.path, kind: broken.problem.kind, line: broken.problem.line });
12664
+ throw new CodegenLoopFailure("syntax_error", void 0, void 0, `${broken.path}: ${describeSyntaxProblem(broken.problem)}`);
12665
+ }
12666
+ const stopReason = isFinal ? `forced_${finalReason}` : "model_done";
12667
+ const doneSummary = typeof body.summary === "string" ? body.summary.slice(0, MAX_SUMMARY_CHARS) : "";
12668
+ log({ event: "codegen.loop_done", turns, toolCalls: ledger.toolCalls, edits: ws.edits.size, created: ws.created.size, stopReason });
12669
+ return { results: overlay.results(), summary: snapshot(stopReason), doneSummary };
12670
+ }
12671
+ if (body.outcome !== "TOOL_CALLS") throw new CodegenLoopFailure("bad_reply");
12672
+ if (isFinal) throw new CodegenLoopFailure("final_not_produced");
12673
+ const rawCalls = body.toolCalls;
12674
+ if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY2) throw new CodegenLoopFailure("bad_reply");
12675
+ const calls = [];
12676
+ for (const c of rawCalls) {
12677
+ if (!isPlainObject3(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS2 || typeof c.name !== "string") {
12678
+ throw new CodegenLoopFailure("bad_reply");
12679
+ }
12680
+ if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new CodegenLoopFailure("duplicate_call_ids");
12681
+ calls.push({ id: c.id, name: c.name, args: c.args });
12682
+ }
12683
+ for (const c of calls) usedIds.add(c.id);
12684
+ const results = [];
12685
+ const logged = [];
12686
+ for (const [index, call] of calls.entries()) {
12687
+ let result;
12688
+ let read;
12689
+ if (index >= limits.maxCallsPerTurn) {
12690
+ result = { id: call.id, name: call.name, status: "budget_exhausted", reason: "too_many_calls", message: "Too many calls in one turn; this one was not run." };
12691
+ } else if (call.name === RUN_TESTS_TOOL && tests) {
12692
+ const testsStarted = now();
12693
+ try {
12694
+ result = await executeRunTestsCall(call, tests, ledger, limits);
12695
+ } catch (err) {
12696
+ if (err instanceof TreeNotRestoredError) throw err;
12697
+ throw new CodegenLoopFailure("executor_error", void 0, err);
12698
+ } finally {
12699
+ testMs += now() - testsStarted;
12700
+ }
12701
+ } else {
12702
+ try {
12703
+ ({ result, read } = executeToolCall(call, env2, ledger));
12704
+ } catch (err) {
12705
+ throw new CodegenLoopFailure("executor_error", void 0, err);
12706
+ }
12707
+ }
12708
+ results.push(result);
12709
+ if (read) reads.push(read);
12710
+ statusCounts[result.status] = (statusCounts[result.status] ?? 0) + 1;
12711
+ const tool = TOOL_NAMES2.has(call.name) ? call.name : "unknown";
12712
+ const pathArg = isPlainObject3(call.args) && typeof call.args.path === "string" && result.status !== "refused" ? { path: call.args.path } : {};
12713
+ logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...pathArg });
12714
+ if (result.status === "refused" || result.status === "protected") {
12715
+ log({ event: "codegen.loop_refused", turn, tool, status: result.status, reason: result.reason });
12716
+ }
12119
12717
  }
12120
- if (c === '"') inString = false;
12121
- continue;
12122
- }
12123
- if (c === '"') {
12124
- inString = true;
12125
- out += c;
12126
- continue;
12127
- }
12128
- if (c === "/" && next === "/") {
12129
- inLineComment = true;
12130
- i2++;
12131
- continue;
12132
- }
12133
- if (c === "/" && next === "*") {
12134
- inBlockComment = true;
12135
- i2++;
12136
- continue;
12137
- }
12138
- out += c;
12139
- }
12140
- return out.replace(/,(\s*[}\]])/g, "$1");
12141
- }
12142
- function resolveAliasPrefixes(results, workspaceRoot) {
12143
- const root = (0, import_node_path6.resolve)(workspaceRoot ?? ".");
12144
- for (const filename of ["tsconfig.json", "jsconfig.json"]) {
12145
- const configPath = (0, import_node_path6.join)(root, filename);
12146
- const generated = results.find((r) => (0, import_node_path6.resolve)(r.targetPath) === configPath);
12147
- let raw;
12148
- if (generated) {
12149
- raw = generated.newContent;
12150
- } else {
12151
- try {
12152
- raw = (0, import_node_fs5.readFileSync)(configPath, "utf8");
12153
- } catch {
12154
- raw = null;
12718
+ if (reasonText) reasoning.push({ turn, text: reasonText });
12719
+ transcript.push({ turn, ...reasonText ? { reasoning: reasonText } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });
12720
+ toolResults.push(...results);
12721
+ noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
12722
+ if (noProgressStreak >= 2) forced = "no_progress";
12723
+ else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
12724
+ else if (ledger.writeChars >= limits.writeCharsTotal) forced = "write_budget";
12725
+ else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
12726
+ const nextTurn = turn + 1;
12727
+ if (nextTurn <= limits.maxTurns) {
12728
+ const nextFinal = forced !== null || nextTurn === limits.maxTurns;
12729
+ if (!makeRoom(nextTurn, nextFinal, forced ?? "max_turns")) {
12730
+ forced = forced ?? "read_budget";
12731
+ const fits = makeRoom(nextTurn, true, forced);
12732
+ log({ event: "codegen.loop_ceiling", turn, action: fits ? "forced_final" : "fallback", ceiling: limits.maxRequestTokens });
12733
+ if (!fits) throw new CodegenLoopFailure("token_ceiling");
12734
+ }
12155
12735
  }
12736
+ log({ event: "codegen.loop_turn", turn, outcome: "tool_calls", requestTokens, elapsedMs: now() - turnStarted, calls: logged });
12156
12737
  }
12157
- if (raw === null) continue;
12158
- try {
12159
- const parsed = JSON.parse(stripJsonComments(raw));
12160
- const paths = parsed.compilerOptions?.paths;
12161
- const fromConfig = paths && typeof paths === "object" ? Object.keys(paths).map((k) => k.endsWith("*") ? k.slice(0, -1) : k) : [];
12162
- return [.../* @__PURE__ */ new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];
12163
- } catch {
12164
- continue;
12165
- }
12166
- }
12167
- return DEFAULT_ALIAS_PREFIXES;
12168
- }
12169
- function describeDependencyViolations(check) {
12170
- return check.violations.map((v) => `${v.file} imports ${v.packages.join(", ")}, not a dependency of this repository`).join("; ");
12171
- }
12172
-
12173
- // src/guardrail.ts
12174
- function checkGuardrail(deniedPaths) {
12175
- addAll();
12176
- const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
12177
- if (violations.length > 0) {
12178
- throw new Error(`QuikPilot touched denied paths:
12179
- ${violations.join("\n")}`);
12738
+ throw new CodegenLoopFailure("final_not_produced");
12739
+ } catch (err) {
12740
+ if (err instanceof SafetyRefusalError) throw err;
12741
+ if (err instanceof TreeNotRestoredError) throw err;
12742
+ const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
12743
+ failure.summary ??= snapshot("fallback");
12744
+ throw failure;
12180
12745
  }
12181
12746
  }
12182
12747
 
12183
- // src/installationToken.ts
12184
- async function exchangeForInstallationToken(installationTokenUrl, runToken) {
12185
- const res = await fetch(installationTokenUrl, {
12748
+ // src/codegenStep.ts
12749
+ var MAX_PROTECTED_PATHS_ON_WIRE = 300;
12750
+ async function postCodegenTurn(gateway, contextData, signal) {
12751
+ const res = await fetchWithRetry(`${gateway.baseUrl}/ai/execute`, {
12186
12752
  method: "POST",
12187
- headers: { Authorization: `Bearer ${runToken}` }
12188
- });
12189
- if (!res.ok) {
12190
- throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
12191
- }
12192
- const body = await res.json();
12193
- if (body.success !== true) {
12194
- throw new Error("Exchange installation token failed: response did not carry success:true");
12195
- }
12196
- return body.data.token;
12197
- }
12198
-
12199
- // src/oidc.ts
12200
- var QUIKPILOT_OIDC_AUDIENCE = "quiktrack-quikpilot";
12201
- async function fetchGithubOidcToken(env2 = process.env) {
12202
- const requestUrl = required(
12203
- "ACTIONS_ID_TOKEN_REQUEST_URL",
12204
- env2.ACTIONS_ID_TOKEN_REQUEST_URL
12205
- );
12206
- const requestToken = required(
12207
- "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
12208
- env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
12209
- );
12210
- const separator = requestUrl.includes("?") ? "&" : "?";
12211
- const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
12212
- const res = await fetch(url, {
12213
- headers: { Authorization: `Bearer ${requestToken}` }
12214
- });
12215
- if (!res.ok) {
12216
- throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
12217
- }
12218
- const body = await res.json();
12219
- if (!body.value) {
12220
- throw new Error("GitHub OIDC token response carried no value");
12221
- }
12222
- return body.value;
12223
- }
12224
-
12225
- // src/packet.ts
12226
- async function fetchPacket(packetUrl, runToken, githubRunId) {
12227
- const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
12228
- const res = await fetch(url, {
12229
- headers: { Authorization: `Bearer ${runToken}` }
12753
+ headers: { "content-type": "application/json", "x-run-token": gateway.token },
12754
+ body: JSON.stringify({
12755
+ appId: "quiktrack",
12756
+ useCase: "pilot.codegen",
12757
+ expectedOutputType: "json",
12758
+ userPrompt: "",
12759
+ contextData
12760
+ }),
12761
+ ...signal ? { signal } : {}
12230
12762
  });
12231
- if (!res.ok) {
12232
- throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
12233
- }
12234
- const body = await res.json();
12235
- if (body.success !== true) {
12236
- throw new Error("Fetch work packet failed: response did not carry success:true");
12237
- }
12238
- return body.data;
12239
- }
12240
-
12241
- // src/phase0.ts
12242
- var import_node_fs6 = require("node:fs");
12243
- function writePhase0Marker(runId) {
12244
- (0, import_node_fs6.mkdirSync)(".quikpilot", { recursive: true });
12245
- (0, import_node_fs6.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
12246
- `);
12247
- }
12248
-
12249
- // src/quiktest.ts
12250
- var import_node_fs7 = require("node:fs");
12251
- var import_node_path7 = require("node:path");
12252
- var SKIP_DIRS = /* @__PURE__ */ new Set(["node_modules", ".git"]);
12253
- function walkForJUnitByName(dir) {
12254
- let entries;
12255
- try {
12256
- entries = (0, import_node_fs7.readdirSync)(dir);
12257
- } catch {
12258
- return null;
12259
- }
12260
- for (const entry of entries) {
12261
- if (SKIP_DIRS.has(entry)) continue;
12262
- const full = (0, import_node_path7.join)(dir, entry);
12263
- let stat;
12264
- try {
12265
- stat = (0, import_node_fs7.statSync)(full);
12266
- } catch {
12267
- continue;
12268
- }
12269
- if (stat.isDirectory()) {
12270
- const found = walkForJUnitByName(full);
12271
- if (found) return found;
12272
- } else if (/^junit.*\.xml$/.test(entry)) {
12273
- return full;
12274
- }
12275
- }
12276
- return null;
12277
- }
12278
- function firstXmlIn(dir, namePattern) {
12279
- let entries;
12280
- try {
12281
- entries = (0, import_node_fs7.readdirSync)(dir);
12282
- } catch {
12283
- return null;
12284
- }
12285
- const match = entries.find((e) => namePattern.test(e));
12286
- return match ? (0, import_node_path7.join)(dir, match) : null;
12763
+ if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
12764
+ return res.json();
12287
12765
  }
12288
- function readTestReportBytes(cwd = process.cwd()) {
12289
- try {
12290
- const report = findJUnitReport(cwd);
12291
- return report ? (0, import_node_fs7.readFileSync)(report) : null;
12292
- } catch {
12293
- return null;
12766
+ function protectedTestFiles(listing, testDiscovery) {
12767
+ const inListing = new Set(listing);
12768
+ const found = new Set(listing.filter((p) => isTestTarget(p)));
12769
+ if (testDiscovery.report === "PRESENT") {
12770
+ for (const p of testDiscovery.discoveredTestFiles) if (inListing.has(p)) found.add(p);
12294
12771
  }
12772
+ return [...found].sort();
12295
12773
  }
12296
- function findJUnitReport(cwd = process.cwd()) {
12297
- return walkForJUnitByName(cwd) ?? firstXmlIn((0, import_node_path7.join)(cwd, "test-results"), /\.xml$/) ?? firstXmlIn((0, import_node_path7.join)(cwd, "reports"), /^junit.*\.xml$/) ?? firstXmlIn((0, import_node_path7.join)(cwd, "target", "surefire-reports"), /\.xml$/);
12298
- }
12299
- function buildCiUrl(serverUrl, repository, githubRunId) {
12300
- return `${serverUrl}/${repository}/actions/runs/${githubRunId}`;
12301
- }
12302
- function describeUnmatchedAutomationIds(unmatched) {
12303
- if (unmatched.length === 0) return null;
12304
- const named = unmatched.map((u) => `${u.automationId} (\xD7${u.count})`).join(", ");
12305
- return `${unmatched.length} generated test result(s) did not match any test case: ${named} \u2014 check the automationId format.`;
12774
+ function buildCodegenLoopArgs(p, context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} })) {
12775
+ const skipped = new Set(p.skippedCases.map((s) => s.automationId));
12776
+ const claimed = /* @__PURE__ */ new Set();
12777
+ for (const t of p.targets) for (const id of t.automationIds ?? []) if (!skipped.has(id)) claimed.add(id);
12778
+ const requiredTests = p.requiredTests.filter((tc) => claimed.has(tc.automationId));
12779
+ const protectedTestPaths = protectedTestFiles(p.workspaceListing, p.testDiscovery);
12780
+ const baseContext = {
12781
+ targets: p.targets.map((t) => ({
12782
+ path: t.path,
12783
+ kind: t.kind,
12784
+ role: (t.automationIds?.length ?? 0) > 0 || isTestTarget(t.path) ? "test" : "code",
12785
+ planSteps: t.planStepsImplemented,
12786
+ automationIds: t.automationIds ?? []
12787
+ })),
12788
+ requiredTests,
12789
+ workspaceListing: p.workspaceListing
12790
+ };
12791
+ if (context.entries.length > 0) baseContext.contextContents = context.entries;
12792
+ if (p.deniedPaths.length > 0) baseContext.deniedPaths = p.deniedPaths;
12793
+ if (protectedTestPaths.length > 0) baseContext.protectedTestPaths = protectedTestPaths.slice(0, MAX_PROTECTED_PATHS_ON_WIRE);
12794
+ if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;
12795
+ return {
12796
+ baseContext,
12797
+ targets: p.targets,
12798
+ requiredAutomationIds: requiredTests.map((tc) => tc.automationId),
12799
+ listing: p.workspaceListing,
12800
+ deniedPaths: p.deniedPaths,
12801
+ protectedTestPaths,
12802
+ // The files already shown are evidence for the parse check that the project parses (`syntaxCheck.ts`).
12803
+ syntaxSeed: context.entries.map((e) => ({ path: e.path, text: e.content })),
12804
+ ...p.mode === "loop-tests" && p.tests ? { tests: p.tests } : {}
12805
+ };
12306
12806
  }
12307
- async function reportToQuikTest(params) {
12308
- const { resultsUrl, runToken, githubServerUrl, githubRepository, githubRunId, generatedFiles, cwd } = params;
12309
- if (!resultsUrl) {
12310
- console.log("packet.quikTest is null \u2014 this run has no QuikTest run to report into.");
12311
- return null;
12312
- }
12313
- const report = findJUnitReport(cwd);
12314
- if (!report) {
12315
- console.warn("::warning::QuikPilot found no JUnit report \u2014 no results reported to QuikTest.");
12316
- return null;
12317
- }
12807
+ var NO_SUMMARY = {
12808
+ turns: 0,
12809
+ toolCalls: 0,
12810
+ refused: 0,
12811
+ stopReason: "fallback",
12812
+ reads: [],
12813
+ edits: [],
12814
+ created: [],
12815
+ statusCounts: {},
12816
+ syntaxWarnings: 0,
12817
+ reasoning: []
12818
+ };
12819
+ function perFile(p) {
12820
+ return runCodegen(
12821
+ p.gateway,
12822
+ p.targets,
12823
+ p.workspaceListing,
12824
+ p.requiredTests,
12825
+ p.deniedPaths,
12826
+ p.judgedByPool,
12827
+ p.warnings,
12828
+ p.contextLog,
12829
+ p.outOfScope
12830
+ );
12831
+ }
12832
+ async function runCodegenStep(p) {
12833
+ if (p.mode !== "loop" && p.mode !== "loop-tests") return perFile(p);
12834
+ const testSetup = p.mode === "loop-tests" ? p.tests : void 0;
12835
+ const treeAtStart = testSetup ? testSetup.baseline().then(
12836
+ () => captureTree(testSetup.root, [], testSetup.tree),
12837
+ () => captureTree(testSetup.root, [], testSetup.tree)
12838
+ ).catch(() => null) : null;
12839
+ const context = collectLoopContext({ targets: p.targets, listing: p.workspaceListing, deniedPaths: p.deniedPaths, ...p.readFile ? { readFile: p.readFile } : {} });
12840
+ p.contextLog.push(...context.records);
12841
+ console.log(
12842
+ JSON.stringify({
12843
+ event: "codegen.loop_context",
12844
+ files: context.entries.length,
12845
+ chars: context.entries.reduce((n, e) => n + e.content.length, 0),
12846
+ paths: context.entries.map((e) => e.path),
12847
+ existingTests: context.testPaths
12848
+ })
12849
+ );
12318
12850
  try {
12319
- console.log(`reporting ${report}`);
12320
- const ciUrl = buildCiUrl(githubServerUrl, githubRepository, githubRunId);
12321
- const { readFileSync: readFileSync9 } = await import("node:fs");
12322
- const body = readFileSync9(report);
12323
- let url = `${resultsUrl}?ciUrl=${encodeURIComponent(ciUrl)}&automationIdFormat=bracket`;
12324
- if (generatedFiles) {
12325
- url += `&generatedFiles=${encodeURIComponent(generatedFiles.join(","))}`;
12326
- }
12327
- const res = await fetch(url, {
12328
- method: "POST",
12329
- headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "text/xml" },
12330
- body
12851
+ const { results, summary } = await runCodegenLoop(buildCodegenLoopArgs(p, context), {
12852
+ post: (contextData, signal) => postCodegenTurn(p.gateway, contextData, signal),
12853
+ ...p.deps
12331
12854
  });
12332
- if (!res.ok) {
12333
- throw new Error(`QuikTest report POST failed: ${res.status} ${res.statusText}`);
12334
- }
12335
- (0, import_node_fs7.rmSync)(report, { force: true });
12336
- let unmatched = [];
12337
- try {
12338
- const json = await res.json();
12339
- unmatched = json.data?.unmatched ?? [];
12340
- } catch {
12855
+ p.out.loop = buildCodegenLoopRecord(summary);
12856
+ const planned = new Set(p.targets.map((t) => t.path));
12857
+ for (const r of results) {
12858
+ if (!planned.has(r.targetPath)) {
12859
+ const w = `QuikPilot changed ${r.targetPath}, which the plan did not name.`;
12860
+ p.warnings.push(w);
12861
+ console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
12862
+ }
12341
12863
  }
12342
- return { unmatched };
12864
+ return results;
12343
12865
  } catch (err) {
12344
- console.warn(`::warning::QuikPilot failed to report results to QuikTest: ${err instanceof Error ? err.message : String(err)}`);
12345
- return null;
12866
+ if (err instanceof SafetyRefusalError) throw err;
12867
+ if (err instanceof TreeNotRestoredError) throw err;
12868
+ const failure = err instanceof CodegenLoopFailure ? err : new CodegenLoopFailure("internal_error", void 0, err);
12869
+ p.out.loop = buildCodegenLoopRecord({
12870
+ ...failure.summary ?? NO_SUMMARY,
12871
+ stopReason: "fallback",
12872
+ fellBack: true,
12873
+ fallbackReason: failure.reason
12874
+ });
12875
+ const said = failure.detail ? `: ${failure.detail}` : "";
12876
+ const w = `The code-writing loop could not finish (${failure.reason}${said}), so the files were written one at a time instead.`;
12877
+ p.warnings.push(w);
12878
+ console.warn(`QuikPilot codegen warning (not blocking): ${w}`);
12879
+ const before = treeAtStart ? await treeAtStart : null;
12880
+ if (before && p.tests) assertTreeUnchanged(p.tests.root, before, [], p.tests.tree);
12881
+ return perFile(p);
12346
12882
  }
12347
12883
  }
12348
12884
 
12349
- // src/baselineCheck.ts
12350
- var import_node_child_process3 = require("node:child_process");
12351
- var import_node_fs9 = require("node:fs");
12352
- var import_node_path8 = require("node:path");
12353
-
12354
- // src/regressionCheck.ts
12355
- var import_node_fs8 = require("node:fs");
12356
- var TESTCASE_RE = /<testcase\b([^>]*?)(?:\/>|>([\s\S]*?)<\/testcase>)/g;
12357
- var NAME_ATTR_RE = /\bname="([^"]*)"/;
12358
- var CLASSNAME_ATTR_RE = /\bclassname="([^"]*)"/;
12359
- var FAILURE_CHILD_RE = /<failure\b|<error\b/;
12360
- var SKIPPED_CHILD_RE = /<skipped\b/;
12361
- var TESTSUITE_OPEN_RE = /<testsuite\b([^>]*?)>/g;
12362
- var FILE_ATTR_RE = /\bfile="([^"]*)"/;
12363
- var QP_TOKEN_BRACKET_RE = /\[(QP-[A-Z][A-Z0-9]*-\d+-\d+)\]/;
12364
- function normalizeSlashes(path) {
12365
- return path.replace(/\\/g, "/");
12885
+ // src/dependencyCheck.ts
12886
+ var import_node_fs10 = require("node:fs");
12887
+ var import_node_path10 = require("node:path");
12888
+ var SCANNABLE_EXTENSIONS = [".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", ".mts", ".cts"];
12889
+ var IMPORT_RE = /(?:\bimport\b[^'"]*?\bfrom\s*|\bimport\s*\(\s*|\bexport\b[^'"]*?\bfrom\s*|\brequire\s*\(\s*|\bimport\s+)(['"])([^'"]+)\1/g;
12890
+ var NODE_BUILTINS = /* @__PURE__ */ new Set([
12891
+ "assert",
12892
+ "buffer",
12893
+ "child_process",
12894
+ "cluster",
12895
+ "crypto",
12896
+ "dgram",
12897
+ "dns",
12898
+ "domain",
12899
+ "events",
12900
+ "fs",
12901
+ "http",
12902
+ "http2",
12903
+ "https",
12904
+ "net",
12905
+ "os",
12906
+ "path",
12907
+ "perf_hooks",
12908
+ "process",
12909
+ "punycode",
12910
+ "querystring",
12911
+ "readline",
12912
+ "repl",
12913
+ "stream",
12914
+ "string_decoder",
12915
+ "sys",
12916
+ "timers",
12917
+ "tls",
12918
+ "tty",
12919
+ "url",
12920
+ "util",
12921
+ "v8",
12922
+ "vm",
12923
+ "worker_threads",
12924
+ "zlib",
12925
+ "inspector",
12926
+ "async_hooks"
12927
+ ]);
12928
+ var DEFAULT_ALIAS_PREFIXES = ["@/", "~/"];
12929
+ function packageNameFromSpecifier(specifier, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12930
+ if (specifier.startsWith(".") || specifier.startsWith("/")) return null;
12931
+ if (specifier.startsWith("node:")) return null;
12932
+ if (aliasPrefixes.some((prefix) => specifier.startsWith(prefix))) return null;
12933
+ const segments = specifier.split("/");
12934
+ const name = specifier.startsWith("@") ? segments.slice(0, 2).join("/") : segments[0];
12935
+ if (NODE_BUILTINS.has(name)) return null;
12936
+ return name;
12366
12937
  }
12367
- var FAILURE_TAG_RE = /<(?:failure|error)\b([^>]*?)(?:\/>|>([\s\S]*?)<\/(?:failure|error)>)/;
12368
- var FAILURE_MESSAGE_ATTR_RE = /\bmessage="([^"]*)"/;
12369
- var MAX_FAILURE_TEXT = 500;
12370
- function unescapeXmlEntities(s) {
12371
- return s.replace(/&lt;/g, "<").replace(/&gt;/g, ">").replace(/&quot;/g, '"').replace(/&apos;/g, "'").replace(/&amp;/g, "&");
12938
+ function scanImports(source, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12939
+ const found = /* @__PURE__ */ new Set();
12940
+ let match;
12941
+ IMPORT_RE.lastIndex = 0;
12942
+ while (match = IMPORT_RE.exec(source)) {
12943
+ const name = packageNameFromSpecifier(match[2], aliasPrefixes);
12944
+ if (name) found.add(name);
12945
+ }
12946
+ return [...found];
12372
12947
  }
12373
- var FAILURE_FILE_LINE_RE = /^[ \t]*File:[ \t]*(\S[^\r\n]*?:\d+(?::\d+)?)[ \t]*$/m;
12374
- var MAX_FAILURE_LOCATION = 300;
12375
- function parseFailureLocation(body) {
12376
- const found = FAILURE_FILE_LINE_RE.exec(unescapeXmlEntities(body));
12377
- if (!found) return null;
12378
- const path = normalizeSlashes(found[1]);
12379
- const root = `${normalizeSlashes(process.cwd()).replace(/\/+$/, "")}/`;
12380
- const shown = path.startsWith(root) ? path.slice(root.length) : path;
12381
- return shown.length > MAX_FAILURE_LOCATION ? `${shown.slice(0, MAX_FAILURE_LOCATION)}\u2026` : shown;
12948
+ function checkImportDependencies(results, declaredDependencies, aliasPrefixes = DEFAULT_ALIAS_PREFIXES) {
12949
+ if (!declaredDependencies) return { blocked: false, violations: [] };
12950
+ const violations = [];
12951
+ for (const { targetPath, newContent } of results) {
12952
+ if (!SCANNABLE_EXTENSIONS.some((ext) => targetPath.endsWith(ext))) continue;
12953
+ const invented = scanImports(newContent, aliasPrefixes).filter((pkg) => !declaredDependencies.has(pkg));
12954
+ if (invented.length > 0) violations.push({ file: targetPath, packages: invented });
12955
+ }
12956
+ return { blocked: violations.length > 0, violations };
12382
12957
  }
12383
- function extractFailureText(testcaseBody) {
12384
- const tag = FAILURE_TAG_RE.exec(testcaseBody);
12385
- if (!tag) return null;
12386
- const [, attrs = "", inner = ""] = tag;
12387
- const messageAttr = FAILURE_MESSAGE_ATTR_RE.exec(attrs)?.[1];
12388
- const raw = (messageAttr ?? inner).trim();
12389
- if (!raw) return null;
12390
- const text = unescapeXmlEntities(raw);
12391
- const shortened = text.length > MAX_FAILURE_TEXT ? `${text.slice(0, MAX_FAILURE_TEXT)}\u2026` : text;
12392
- const location = messageAttr === void 0 ? null : parseFailureLocation(inner);
12393
- return location ? `${shortened} [at ${location}]` : shortened;
12958
+ function dependencyNames(pkg) {
12959
+ return /* @__PURE__ */ new Set([
12960
+ ...Object.keys(pkg.dependencies ?? {}),
12961
+ ...Object.keys(pkg.devDependencies ?? {}),
12962
+ ...Object.keys(pkg.peerDependencies ?? {})
12963
+ ]);
12394
12964
  }
12395
- var RESULT_RANK = { pass: 0, skipped: 1, fail: 2 };
12396
- function parseJUnitOutcomes(xml) {
12397
- const outcomes = /* @__PURE__ */ new Map();
12398
- const automationIdResults = /* @__PURE__ */ new Map();
12399
- const failureText = /* @__PURE__ */ new Map();
12400
- const discoveredFiles = /* @__PURE__ */ new Set();
12401
- const discoveredAutomationIds = /* @__PURE__ */ new Set();
12402
- TESTSUITE_OPEN_RE.lastIndex = 0;
12403
- let suiteMatch;
12404
- while (suiteMatch = TESTSUITE_OPEN_RE.exec(xml)) {
12405
- const file = FILE_ATTR_RE.exec(suiteMatch[1])?.[1];
12406
- if (file) discoveredFiles.add(normalizeSlashes(file));
12407
- }
12408
- let match;
12409
- TESTCASE_RE.lastIndex = 0;
12410
- while (match = TESTCASE_RE.exec(xml)) {
12411
- const [, attrs, body = ""] = match;
12412
- const rawName = NAME_ATTR_RE.exec(attrs)?.[1];
12413
- if (!rawName) continue;
12414
- const name = unescapeXmlEntities(rawName);
12415
- const rawClassname = CLASSNAME_ATTR_RE.exec(attrs)?.[1];
12416
- const classname = rawClassname === void 0 ? void 0 : unescapeXmlEntities(rawClassname);
12417
- const id = classname ? `${classname}::${name}` : name;
12418
- const failed = FAILURE_CHILD_RE.test(body);
12419
- outcomes.set(id, !failed);
12420
- if (failed) {
12421
- const text = extractFailureText(body);
12422
- if (text) failureText.set(id, text);
12423
- }
12424
- const file = FILE_ATTR_RE.exec(attrs)?.[1];
12425
- if (file) discoveredFiles.add(normalizeSlashes(file));
12426
- if (classname) discoveredFiles.add(normalizeSlashes(classname));
12427
- const bracket = QP_TOKEN_BRACKET_RE.exec(name)?.[1];
12428
- if (bracket) {
12429
- discoveredAutomationIds.add(bracket);
12430
- const result = failed ? "fail" : SKIPPED_CHILD_RE.test(body) ? "skipped" : "pass";
12431
- const seen = automationIdResults.get(bracket);
12432
- if (!seen || RESULT_RANK[result] > RESULT_RANK[seen]) automationIdResults.set(bracket, result);
12965
+ function readDeclaredDependencies(results, workspaceRoot) {
12966
+ const packageJsonPath = (0, import_node_path10.join)((0, import_node_path10.resolve)(workspaceRoot ?? "."), "package.json");
12967
+ const generated = results.find((r) => (0, import_node_path10.resolve)(r.targetPath) === packageJsonPath);
12968
+ let raw;
12969
+ if (generated) {
12970
+ raw = generated.newContent;
12971
+ } else {
12972
+ try {
12973
+ raw = (0, import_node_fs10.readFileSync)(packageJsonPath, "utf8");
12974
+ } catch {
12975
+ raw = null;
12433
12976
  }
12434
12977
  }
12435
- return { outcomes, automationIdResults, failureText, discoveredFiles, discoveredAutomationIds };
12436
- }
12437
- function readJUnitOutcomes(cwd) {
12438
- const report = findJUnitReport(cwd);
12439
- if (!report) return null;
12978
+ if (raw === null) return null;
12440
12979
  try {
12441
- return parseJUnitOutcomes((0, import_node_fs8.readFileSync)(report, "utf8"));
12980
+ return dependencyNames(JSON.parse(raw));
12442
12981
  } catch {
12443
12982
  return null;
12444
12983
  }
12445
12984
  }
12446
- function readAutomationIdResults(cwd = process.cwd()) {
12447
- return readJUnitOutcomes(cwd)?.automationIdResults ?? null;
12985
+ function stripJsonComments(text) {
12986
+ let out = "";
12987
+ let inString = false;
12988
+ let inLineComment = false;
12989
+ let inBlockComment = false;
12990
+ for (let i2 = 0; i2 < text.length; i2++) {
12991
+ const c = text[i2];
12992
+ const next = text[i2 + 1];
12993
+ if (inLineComment) {
12994
+ if (c === "\n") {
12995
+ inLineComment = false;
12996
+ out += c;
12997
+ }
12998
+ continue;
12999
+ }
13000
+ if (inBlockComment) {
13001
+ if (c === "*" && next === "/") {
13002
+ inBlockComment = false;
13003
+ i2++;
13004
+ }
13005
+ continue;
13006
+ }
13007
+ if (inString) {
13008
+ out += c;
13009
+ if (c === "\\") {
13010
+ out += next;
13011
+ i2++;
13012
+ continue;
13013
+ }
13014
+ if (c === '"') inString = false;
13015
+ continue;
13016
+ }
13017
+ if (c === '"') {
13018
+ inString = true;
13019
+ out += c;
13020
+ continue;
13021
+ }
13022
+ if (c === "/" && next === "/") {
13023
+ inLineComment = true;
13024
+ i2++;
13025
+ continue;
13026
+ }
13027
+ if (c === "/" && next === "*") {
13028
+ inBlockComment = true;
13029
+ i2++;
13030
+ continue;
13031
+ }
13032
+ out += c;
13033
+ }
13034
+ return out.replace(/,(\s*[}\]])/g, "$1");
12448
13035
  }
12449
- function captureTestSnapshot(command, cwd = process.cwd()) {
12450
- const outcome = runTestCommand(command);
12451
- const parsed = readJUnitOutcomes(cwd);
12452
- return {
12453
- outcome,
12454
- results: parsed?.outcomes ?? null,
12455
- failureText: parsed?.failureText,
12456
- discoveredFiles: parsed?.discoveredFiles ?? null,
12457
- discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
12458
- };
13036
+ function resolveAliasPrefixes(results, workspaceRoot) {
13037
+ const root = (0, import_node_path10.resolve)(workspaceRoot ?? ".");
13038
+ for (const filename of ["tsconfig.json", "jsconfig.json"]) {
13039
+ const configPath = (0, import_node_path10.join)(root, filename);
13040
+ const generated = results.find((r) => (0, import_node_path10.resolve)(r.targetPath) === configPath);
13041
+ let raw;
13042
+ if (generated) {
13043
+ raw = generated.newContent;
13044
+ } else {
13045
+ try {
13046
+ raw = (0, import_node_fs10.readFileSync)(configPath, "utf8");
13047
+ } catch {
13048
+ raw = null;
13049
+ }
13050
+ }
13051
+ if (raw === null) continue;
13052
+ try {
13053
+ const parsed = JSON.parse(stripJsonComments(raw));
13054
+ const paths = parsed.compilerOptions?.paths;
13055
+ const fromConfig = paths && typeof paths === "object" ? Object.keys(paths).map((k) => k.endsWith("*") ? k.slice(0, -1) : k) : [];
13056
+ return [.../* @__PURE__ */ new Set([...DEFAULT_ALIAS_PREFIXES, ...fromConfig])];
13057
+ } catch {
13058
+ continue;
13059
+ }
13060
+ }
13061
+ return DEFAULT_ALIAS_PREFIXES;
12459
13062
  }
12460
- async function captureBaselineSnapshot(command, cwd = process.cwd()) {
12461
- const outcome = await runTestCommandAsync(command);
12462
- const parsed = readJUnitOutcomes(cwd);
12463
- return {
12464
- outcome,
12465
- results: parsed?.outcomes ?? null,
12466
- failureText: parsed?.failureText,
12467
- discoveredFiles: parsed?.discoveredFiles ?? null,
12468
- discoveredAutomationIds: parsed?.discoveredAutomationIds ?? null
12469
- };
13063
+ function describeDependencyViolations(check) {
13064
+ return check.violations.map((v) => `${v.file} imports ${v.packages.join(", ")}, not a dependency of this repository`).join("; ");
12470
13065
  }
12471
- function checkForRegressions(baseline, after) {
12472
- if (!baseline.results || !after.results) {
12473
- return { blocked: false, regressions: [], newFailures: [], preExisting: [], failureText: /* @__PURE__ */ new Map() };
13066
+
13067
+ // src/guardrail.ts
13068
+ function checkGuardrail(deniedPaths) {
13069
+ addAll();
13070
+ const violations = deniedPaths.flatMap((pattern) => diffCachedNamesMatching(pattern));
13071
+ if (violations.length > 0) {
13072
+ throw new Error(`QuikPilot touched denied paths:
13073
+ ${violations.join("\n")}`);
12474
13074
  }
12475
- const regressions = [];
12476
- const newFailures = [];
12477
- const preExisting = [];
12478
- const failureText = /* @__PURE__ */ new Map();
12479
- const afterFailureText = after.failureText;
12480
- for (const [testId, passed] of after.results) {
12481
- if (passed) continue;
12482
- const before = baseline.results.get(testId);
12483
- if (before === true) {
12484
- regressions.push(testId);
12485
- const text = afterFailureText?.get(testId);
12486
- if (text) failureText.set(testId, text);
12487
- } else if (before === false) {
12488
- preExisting.push(testId);
12489
- } else {
12490
- newFailures.push(testId);
12491
- const text = afterFailureText?.get(testId);
12492
- if (text) failureText.set(testId, text);
12493
- }
13075
+ }
13076
+
13077
+ // src/installationToken.ts
13078
+ async function exchangeForInstallationToken(installationTokenUrl, runToken) {
13079
+ const res = await fetch(installationTokenUrl, {
13080
+ method: "POST",
13081
+ headers: { Authorization: `Bearer ${runToken}` }
13082
+ });
13083
+ if (!res.ok) {
13084
+ throw new Error(`Exchange installation token failed: ${await describeQuikTrackFailure(res)}`);
12494
13085
  }
12495
- return { blocked: regressions.length > 0 || newFailures.length > 0, regressions, newFailures, preExisting, failureText };
13086
+ const body = await res.json();
13087
+ if (body.success !== true) {
13088
+ throw new Error("Exchange installation token failed: response did not carry success:true");
13089
+ }
13090
+ return body.data.token;
12496
13091
  }
12497
- function describeRegressions(check) {
12498
- const withText = (id) => {
12499
- const text = check.failureText.get(id);
12500
- return text ? `${id} (${text})` : id;
12501
- };
12502
- const parts = [];
12503
- if (check.regressions.length > 0) {
12504
- parts.push(
12505
- `${check.regressions.length} regression(s) (passed before, now fail): ${check.regressions.map(withText).join(", ")}`
12506
- );
13092
+
13093
+ // src/oidc.ts
13094
+ var QUIKPILOT_OIDC_AUDIENCE = "quiktrack-quikpilot";
13095
+ async function fetchGithubOidcToken(env2 = process.env) {
13096
+ const requestUrl = required(
13097
+ "ACTIONS_ID_TOKEN_REQUEST_URL",
13098
+ env2.ACTIONS_ID_TOKEN_REQUEST_URL
13099
+ );
13100
+ const requestToken = required(
13101
+ "ACTIONS_ID_TOKEN_REQUEST_TOKEN",
13102
+ env2.ACTIONS_ID_TOKEN_REQUEST_TOKEN
13103
+ );
13104
+ const separator = requestUrl.includes("?") ? "&" : "?";
13105
+ const url = `${requestUrl}${separator}audience=${encodeURIComponent(QUIKPILOT_OIDC_AUDIENCE)}`;
13106
+ const res = await fetch(url, {
13107
+ headers: { Authorization: `Bearer ${requestToken}` }
13108
+ });
13109
+ if (!res.ok) {
13110
+ throw new Error(`Fetch GitHub OIDC token failed: ${res.status} ${res.statusText}`);
12507
13111
  }
12508
- if (check.newFailures.length > 0) {
12509
- parts.push(
12510
- `${check.newFailures.length} new failure(s) (did not exist before): ${check.newFailures.map(withText).join(", ")}`
12511
- );
13112
+ const body = await res.json();
13113
+ if (!body.value) {
13114
+ throw new Error("GitHub OIDC token response carried no value");
12512
13115
  }
12513
- if (check.preExisting.length > 0) {
12514
- parts.push(`${check.preExisting.length} pre-existing failure(s), unrelated to this change, not blocking`);
13116
+ return body.value;
13117
+ }
13118
+
13119
+ // src/packet.ts
13120
+ async function fetchPacket(packetUrl, runToken, githubRunId) {
13121
+ const url = `${packetUrl}?githubRunId=${encodeURIComponent(githubRunId)}`;
13122
+ const res = await fetch(url, {
13123
+ headers: { Authorization: `Bearer ${runToken}` }
13124
+ });
13125
+ if (!res.ok) {
13126
+ throw new Error(`Fetch work packet failed: ${await describeQuikTrackFailure(res)}`);
12515
13127
  }
12516
- return parts.join("; ");
13128
+ const body = await res.json();
13129
+ if (body.success !== true) {
13130
+ throw new Error("Fetch work packet failed: response did not carry success:true");
13131
+ }
13132
+ return body.data;
13133
+ }
13134
+
13135
+ // src/phase0.ts
13136
+ var import_node_fs11 = require("node:fs");
13137
+ function writePhase0Marker(runId) {
13138
+ (0, import_node_fs11.mkdirSync)(".quikpilot", { recursive: true });
13139
+ (0, import_node_fs11.appendFileSync)(".quikpilot/phase0-marker.txt", `QuikPilot Phase 0 skeleton marker for run ${runId}
13140
+ `);
12517
13141
  }
12518
13142
 
12519
13143
  // src/baselineCheck.ts
13144
+ var import_node_child_process5 = require("node:child_process");
13145
+ var import_node_fs12 = require("node:fs");
13146
+ var import_node_path11 = require("node:path");
12520
13147
  var BASELINE_CHECK_TIMEOUT_MS = 12e4;
12521
13148
  function shellQuote(value) {
12522
13149
  return `'${value.split("'").join("'\\''")}'`;
@@ -12535,32 +13162,32 @@ function checkableIds(ids, types2) {
12535
13162
  });
12536
13163
  }
12537
13164
  function insideCheckout(cwd, path) {
12538
- const abs = (0, import_node_path8.resolve)(cwd, path);
12539
- const rel = (0, import_node_path8.relative)(cwd, abs);
12540
- return rel === "" || rel.startsWith("..") || (0, import_node_path8.isAbsolute)(rel) ? null : abs;
13165
+ const abs = (0, import_node_path11.resolve)(cwd, path);
13166
+ const rel = (0, import_node_path11.relative)(cwd, abs);
13167
+ return rel === "" || rel.startsWith("..") || (0, import_node_path11.isAbsolute)(rel) ? null : abs;
12541
13168
  }
12542
13169
  function writeForCheck(abs, content) {
12543
- const original = (0, import_node_fs9.existsSync)(abs) ? (0, import_node_fs9.readFileSync)(abs) : null;
13170
+ const original = (0, import_node_fs12.existsSync)(abs) ? (0, import_node_fs12.readFileSync)(abs) : null;
12544
13171
  const createdDirs = [];
12545
13172
  if (original === null) {
12546
13173
  const missing = [];
12547
- for (let d = (0, import_node_path8.dirname)(abs); !(0, import_node_fs9.existsSync)(d); d = (0, import_node_path8.dirname)(d)) missing.push(d);
13174
+ 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);
12548
13175
  for (const d of missing.reverse()) {
12549
- (0, import_node_fs9.mkdirSync)(d);
13176
+ (0, import_node_fs12.mkdirSync)(d);
12550
13177
  createdDirs.push(d);
12551
13178
  }
12552
13179
  }
12553
- (0, import_node_fs9.writeFileSync)(abs, content);
13180
+ (0, import_node_fs12.writeFileSync)(abs, content);
12554
13181
  return { abs, original, createdDirs };
12555
13182
  }
12556
13183
  function restore(written) {
12557
13184
  for (const file of [...written].reverse()) {
12558
13185
  try {
12559
- if (file.original !== null) (0, import_node_fs9.writeFileSync)(file.abs, file.original);
12560
- else (0, import_node_fs9.rmSync)(file.abs, { force: true });
13186
+ if (file.original !== null) (0, import_node_fs12.writeFileSync)(file.abs, file.original);
13187
+ else (0, import_node_fs12.rmSync)(file.abs, { force: true });
12561
13188
  for (const d of [...file.createdDirs].reverse()) {
12562
13189
  try {
12563
- (0, import_node_fs9.rmdirSync)(d);
13190
+ (0, import_node_fs12.rmdirSync)(d);
12564
13191
  } catch {
12565
13192
  }
12566
13193
  }
@@ -12571,7 +13198,7 @@ function restore(written) {
12571
13198
  }
12572
13199
  function untrackedFiles(cwd) {
12573
13200
  try {
12574
- const out = (0, import_node_child_process3.execFileSync)("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
13201
+ const out = (0, import_node_child_process5.execFileSync)("git", ["ls-files", "--others", "--exclude-standard", "-z"], {
12575
13202
  cwd,
12576
13203
  encoding: "utf8",
12577
13204
  stdio: ["ignore", "pipe", "ignore"],
@@ -12584,7 +13211,7 @@ function untrackedFiles(cwd) {
12584
13211
  }
12585
13212
  var mtimeOf = (path) => {
12586
13213
  try {
12587
- return (0, import_node_fs9.statSync)(path).mtimeMs;
13214
+ return (0, import_node_fs12.statSync)(path).mtimeMs;
12588
13215
  } catch {
12589
13216
  return null;
12590
13217
  }
@@ -12598,7 +13225,7 @@ function decideCause(targets, results, cwd) {
12598
13225
  const abs = insideCheckout(cwd, t.path);
12599
13226
  if (next === void 0 || abs === null) return "ALREADY_TRUE";
12600
13227
  try {
12601
- if ((0, import_node_fs9.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
13228
+ if ((0, import_node_fs12.readFileSync)(abs, "utf8") !== next) return "ALREADY_TRUE";
12602
13229
  } catch {
12603
13230
  return "ALREADY_TRUE";
12604
13231
  }
@@ -12674,7 +13301,7 @@ async function runBaselineCheck(params) {
12674
13301
  for (const file of untrackedAfter) {
12675
13302
  if (untrackedBefore.has(file)) continue;
12676
13303
  const abs = insideCheckout(cwd, file);
12677
- if (abs) (0, import_node_fs9.rmSync)(abs, { force: true });
13304
+ if (abs) (0, import_node_fs12.rmSync)(abs, { force: true });
12678
13305
  }
12679
13306
  }
12680
13307
  }
@@ -12695,62 +13322,26 @@ async function runBaselineCheck(params) {
12695
13322
  }
12696
13323
 
12697
13324
  // src/failureArtifact.ts
12698
- var import_node_fs10 = require("node:fs");
12699
- var import_node_path9 = require("node:path");
12700
-
12701
- // src/failureReason.ts
12702
- var MAX_FAILURE_REASON = 1e3;
12703
- var MIN_SECRET_LENGTH = 8;
12704
- var CREDENTIAL_PATTERNS = [
12705
- /\b(?:ghp|gho|ghu|ghs|ghr)_[A-Za-z0-9]{20,}/g,
12706
- /\bgithub_pat_[A-Za-z0-9_]{20,}/g,
12707
- /x-access-token:[^@\s'"]+/gi,
12708
- // Only the header form ("Authorization: basic <token>"), or a bearer value that contains a digit: a bare
12709
- // "basic authentication" or "bearer of the news" is prose, not a credential.
12710
- /\bauthorization:\s*(?:basic|bearer|token)\s+[^\s'"]{8,}/gi,
12711
- /\bbearer\s+(?=[A-Za-z0-9._~+/=-]*\d)[A-Za-z0-9._~+/=-]{12,}/gi,
12712
- // A signed JWT is three dot-separated segments; QuikPilot's own run token is an encrypted JWT (alg dir) of five, the
12713
- // second one empty. The run token is also matched by exact value, but one that has expired or rotated is not the
12714
- // current value, so its shape has to catch it.
12715
- /\beyJ[A-Za-z0-9_-]{8,}(?:\.[A-Za-z0-9_-]*){2,4}/g
12716
- ];
12717
- function failureSummary(err) {
12718
- if (err instanceof RuntimeReplyError) return err.summary;
12719
- return err instanceof Error ? err.message : String(err);
12720
- }
12721
- function scrubSecrets(message, secrets = []) {
12722
- let text = message;
12723
- for (const secret of secrets) {
12724
- if (secret.length >= MIN_SECRET_LENGTH) text = text.split(secret).join("***");
12725
- }
12726
- for (const pattern of CREDENTIAL_PATTERNS) text = text.replace(pattern, "***");
12727
- return text;
12728
- }
12729
- function describeFailureReason(message, secrets = []) {
12730
- let text = scrubSecrets(message, secrets);
12731
- text = text.replace(/\s*\n\s*/g, " | ").trim();
12732
- return text.length > MAX_FAILURE_REASON ? `${text.slice(0, MAX_FAILURE_REASON)}\u2026` : text;
12733
- }
12734
-
12735
- // src/failureArtifact.ts
13325
+ var import_node_fs13 = require("node:fs");
13326
+ var import_node_path12 = require("node:path");
12736
13327
  var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
12737
13328
  var REPORT_COPY = "final-test-report.xml";
12738
13329
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
12739
13330
  var MAX_FILES = 200;
12740
- var RUNNER_VERSION = true ? "9.2.0-rc.8" : "dev";
13331
+ var RUNNER_VERSION = true ? "9.3.0-rc.2" : "dev";
12741
13332
  function safeDestination(base, repoPath) {
12742
- if (!repoPath || (0, import_node_path9.isAbsolute)(repoPath)) return null;
12743
- const destination = (0, import_node_path9.resolve)(base, repoPath);
12744
- const rel = (0, import_node_path9.relative)(base, destination);
12745
- if (!rel || rel.startsWith("..") || (0, import_node_path9.isAbsolute)(rel)) return null;
13333
+ if (!repoPath || (0, import_node_path12.isAbsolute)(repoPath)) return null;
13334
+ const destination = (0, import_node_path12.resolve)(base, repoPath);
13335
+ const rel = (0, import_node_path12.relative)(base, destination);
13336
+ if (!rel || rel.startsWith("..") || (0, import_node_path12.isAbsolute)(rel)) return null;
12746
13337
  return destination;
12747
13338
  }
12748
13339
  function writeFailureArtifact(input) {
12749
13340
  if (input.results.length === 0) return { written: false };
12750
13341
  try {
12751
- const base = (0, import_node_path9.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
12752
- (0, import_node_fs10.rmSync)(base, { recursive: true, force: true });
12753
- (0, import_node_fs10.mkdirSync)(base, { recursive: true });
13342
+ const base = (0, import_node_path12.resolve)(input.cwd, FAILURE_ARTIFACT_DIR);
13343
+ (0, import_node_fs13.rmSync)(base, { recursive: true, force: true });
13344
+ (0, import_node_fs13.mkdirSync)(base, { recursive: true });
12754
13345
  const files = [];
12755
13346
  const skipped = [];
12756
13347
  for (const result of input.results) {
@@ -12759,8 +13350,8 @@ function writeFailureArtifact(input) {
12759
13350
  skipped.push(result.targetPath);
12760
13351
  continue;
12761
13352
  }
12762
- (0, import_node_fs10.mkdirSync)((0, import_node_path9.dirname)(destination), { recursive: true });
12763
- (0, import_node_fs10.writeFileSync)(destination, result.newContent);
13353
+ (0, import_node_fs13.mkdirSync)((0, import_node_path12.dirname)(destination), { recursive: true });
13354
+ (0, import_node_fs13.writeFileSync)(destination, result.newContent);
12764
13355
  files.push({ path: result.targetPath, bytes: Buffer.byteLength(result.newContent) });
12765
13356
  }
12766
13357
  let testReport = "none";
@@ -12768,7 +13359,7 @@ function writeFailureArtifact(input) {
12768
13359
  if (input.testReport.byteLength > MAX_REPORT_BYTES) {
12769
13360
  testReport = "too-large";
12770
13361
  } else {
12771
- (0, import_node_fs10.writeFileSync)((0, import_node_path9.join)(base, REPORT_COPY), input.testReport);
13362
+ (0, import_node_fs13.writeFileSync)((0, import_node_path12.join)(base, REPORT_COPY), input.testReport);
12772
13363
  testReport = "included";
12773
13364
  }
12774
13365
  }
@@ -12788,8 +13379,8 @@ function writeFailureArtifact(input) {
12788
13379
  failureReasons: input.failureReasons
12789
13380
  };
12790
13381
  const text = JSON.stringify(manifest, (_key, value) => typeof value === "string" ? scrubSecrets(value, input.secrets) : value, 2);
12791
- (0, import_node_fs10.writeFileSync)((0, import_node_path9.join)(base, "manifest.json"), text);
12792
- return { written: (0, import_node_fs10.existsSync)((0, import_node_path9.join)(base, "manifest.json")) };
13382
+ (0, import_node_fs13.writeFileSync)((0, import_node_path12.join)(base, "manifest.json"), text);
13383
+ return { written: (0, import_node_fs13.existsSync)((0, import_node_path12.join)(base, "manifest.json")) };
12793
13384
  } catch (err) {
12794
13385
  console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
12795
13386
  return { written: false };
@@ -12797,7 +13388,7 @@ function writeFailureArtifact(input) {
12797
13388
  }
12798
13389
 
12799
13390
  // src/scopeCheck.ts
12800
- var import_node_fs11 = require("node:fs");
13391
+ var import_node_fs14 = require("node:fs");
12801
13392
  var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
12802
13393
  var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
12803
13394
  var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
@@ -12854,7 +13445,7 @@ function checkApiScope(results, targets, apiChanges) {
12854
13445
  } else {
12855
13446
  let currentContent;
12856
13447
  try {
12857
- currentContent = (0, import_node_fs11.readFileSync)(targetPath, "utf8");
13448
+ currentContent = (0, import_node_fs14.readFileSync)(targetPath, "utf8");
12858
13449
  } catch {
12859
13450
  currentContent = "";
12860
13451
  }
@@ -12873,7 +13464,7 @@ function describeScopeViolations(check) {
12873
13464
  }
12874
13465
 
12875
13466
  // src/targeting.ts
12876
- var import_node_path10 = require("node:path");
13467
+ var import_node_path13 = require("node:path");
12877
13468
 
12878
13469
  // src/targetingMode.ts
12879
13470
  var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
@@ -12919,9 +13510,9 @@ function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
12919
13510
  }
12920
13511
  return;
12921
13512
  }
12922
- const root = (0, import_node_path10.resolve)(workspaceRoot ?? ".");
12923
- const rel = (0, import_node_path10.relative)(root, (0, import_node_path10.resolve)(target.path));
12924
- if (rel.startsWith("..") || (0, import_node_path10.isAbsolute)(rel)) {
13513
+ const root = (0, import_node_path13.resolve)(workspaceRoot ?? ".");
13514
+ const rel = (0, import_node_path13.relative)(root, (0, import_node_path13.resolve)(target.path));
13515
+ if (rel.startsWith("..") || (0, import_node_path13.isAbsolute)(rel)) {
12925
13516
  throw new Error(
12926
13517
  `pilot.targeting named a NEW_FILE path that escapes the workspace root: ${target.path}`
12927
13518
  );
@@ -13354,10 +13945,20 @@ async function run(env2) {
13354
13945
  targeting.targets,
13355
13946
  targeting.skippedCases ?? []
13356
13947
  );
13357
- const [baseline, results] = await Promise.all([
13358
- captureBaselineSnapshot(packet.commands.test),
13948
+ const baselineStartedAt = Date.now();
13949
+ const baselineRun = captureBaselineSnapshot(packet.commands.test).then((snapshot) => ({
13950
+ snapshot,
13951
+ durationMs: Date.now() - baselineStartedAt
13952
+ }));
13953
+ const [timedBaseline, results] = await Promise.all([
13954
+ baselineRun,
13359
13955
  runCodegenStep({
13360
13956
  mode: resolveCodegenMode(),
13957
+ tests: {
13958
+ root: process.cwd(),
13959
+ command: packet.commands.test,
13960
+ baseline: () => baselineRun.catch(() => null)
13961
+ },
13361
13962
  gateway: packet.gateway,
13362
13963
  targets: targeting.targets,
13363
13964
  workspaceListing,
@@ -13372,6 +13973,7 @@ async function run(env2) {
13372
13973
  out: codegenOut
13373
13974
  })
13374
13975
  ]);
13976
+ const baseline = timedBaseline.snapshot;
13375
13977
  generatedResults = results;
13376
13978
  const depCheck = checkImportDependencies(
13377
13979
  results,