@quikit/quikpilot-runner 9.3.0-rc.82 → 9.3.0-rc.84

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
@@ -38590,6 +38590,10 @@ function executeToolCall(call, env2, ledger) {
38590
38590
  const guidance = env2.guidance.forRead(executed.read.path);
38591
38591
  if (guidance) executed = { ...executed, result: { ...executed.result, output: { ...executed.result.output, guidance } } };
38592
38592
  }
38593
+ if (env2.screenTrace && call.name === "read_file" && executed.result.status === "ok" && executed.read && isPlainObject(executed.result.output)) {
38594
+ const note = env2.screenTrace.forRead(executed.read.path);
38595
+ if (note) executed = { ...executed, result: { ...executed.result, output: { ...executed.result.output, ...note } } };
38596
+ }
38593
38597
  if ((call.name === "edit_file" || call.name === "write_file" || call.name === "revert_file") && executed.result.status !== "ok") ledger.seen.delete(dupKey);
38594
38598
  if (env2.serveRepeats === true && ledger.seen.has(dupKey)) (ledger.answers ??= /* @__PURE__ */ new Map()).set(call.id, executed.result);
38595
38599
  return finish(executed.result, executed.read);
@@ -38768,7 +38772,7 @@ var REJECT_MESSAGES = {
38768
38772
  unsupported_language: "Only JavaScript, TypeScript, Python, Go and Java test files can be reported.",
38769
38773
  title_not_found: "No test with that title was found in that file. Copy the title exactly as the file writes it. For a test written once for each row of a table, that is the title in the file with its $name or %s placeholders as they are, not the name of one row.",
38770
38774
  title_not_unique: "More than one test in that file has that title, so it cannot be told which one you mean.",
38771
- no_match: "find was not found in that file. Copy it exactly as read_file shows it.",
38775
+ no_match: "find was not found in that file. Copy it exactly as read_file shows it, with its tabs and spaces.",
38772
38776
  ambiguous: "find matches more than once in that file. Make it longer so it matches once, with lines of this test just before or just after it.",
38773
38777
  find_outside_test: "find is not inside that test. It must be lines of that test.",
38774
38778
  beyond_expectations: "replace changes more than the test's expected values. Only the expect(...) statements (and the title) may differ from find; the set-up and the call the test makes must stay as they are.",
@@ -38813,6 +38817,56 @@ function ambiguityHint(lf, find, test) {
38813
38817
  }
38814
38818
  return `${head} Add lines of this test around it until it matches once.`;
38815
38819
  }
38820
+ function indentOf2(line2) {
38821
+ const lead = /^[ \t]*/.exec(line2)[0];
38822
+ let tabs = 0;
38823
+ for (const c of lead) if (c === " ") tabs++;
38824
+ return { tabs, spaces: lead.length - tabs };
38825
+ }
38826
+ function indentWords(i3) {
38827
+ const parts2 = [];
38828
+ if (i3.tabs > 0) parts2.push(`${i3.tabs} tab(s)`);
38829
+ if (i3.spaces > 0) parts2.push(`${i3.spaces} space(s)`);
38830
+ return parts2.length > 0 ? parts2.join(" and ") : "no indent";
38831
+ }
38832
+ function mismatchHint(lf, find, test) {
38833
+ const want = find.split(/\r?\n/);
38834
+ const have = lf.split("\n");
38835
+ const first = want[0].trim();
38836
+ let at2 = -1;
38837
+ let k = 0;
38838
+ let inTest = false;
38839
+ if (first !== "") {
38840
+ for (let s = 0; s < have.length; s++) {
38841
+ if (have[s].trim() !== first) continue;
38842
+ let n = 1;
38843
+ while (n < want.length && s + n < have.length && have[s + n].trim() === want[n].trim()) n++;
38844
+ const inside3 = test !== void 0 && s + 1 >= test.startLine && s + n <= test.endLine;
38845
+ if (n > k || n === k && inside3 && !inTest) {
38846
+ at2 = s;
38847
+ k = n;
38848
+ inTest = inside3;
38849
+ }
38850
+ }
38851
+ }
38852
+ if (at2 < 0) return "No line of that file equals the first line of find, even ignoring spaces and tabs. Copy whole lines as read_file shows them.";
38853
+ if (k < want.length) {
38854
+ const ends = at2 + k >= have.length;
38855
+ return `The first line of find is at line ${at2 + 1} of the file; lines 1 to ${k} of find agree there, but line ${k + 1} of find does not match ${ends ? "anything: the file ends" : `line ${at2 + k + 1} of the file`}, even ignoring spaces and tabs. Check line ${k + 1} of find against the file.`;
38856
+ }
38857
+ const head = `It matches lines ${at2 + 1} to ${at2 + k} of the file when spaces and tabs are ignored, so only whitespace differs.`;
38858
+ const tail2 = "Copy the lines exactly as read_file shows them, with their tabs and spaces.";
38859
+ for (let j = 0; j < want.length; j++) {
38860
+ const a = want[j];
38861
+ const b = have[at2 + j];
38862
+ if (a === b) continue;
38863
+ const ai = indentOf2(a);
38864
+ const bi = indentOf2(b);
38865
+ if (ai.tabs !== bi.tabs || ai.spaces !== bi.spaces) return `${head} Line ${j + 1} of find starts with ${indentWords(ai)}; line ${at2 + j + 1} of the file starts with ${indentWords(bi)}. ${tail2}`;
38866
+ return `${head} Line ${j + 1} of find differs from line ${at2 + j + 1} of the file only after its indent (spaces at the end of the line, or line endings). ${tail2}`;
38867
+ }
38868
+ return `${head} ${find.includes("\r") ? "find has Windows line endings; the file is read with plain ones. " : ""}${tail2}`;
38869
+ }
38816
38870
  var NOT_FOUND_LEAD = "The tests in that file are: ";
38817
38871
  var NOT_FOUND_TAIL = ". The title is the name of the test function.";
38818
38872
  function titlesHint(tests, room = Number.POSITIVE_INFINITY) {
@@ -39076,7 +39130,7 @@ var TestConflictTool = class {
39076
39130
  const isTable = index >= located.tests.length;
39077
39131
  const applied = applyEdits(lf, [{ find: r.find, replace: r.replace }]);
39078
39132
  if (!applied.ok) {
39079
- if (applied.refusals[0]?.kind !== "ambiguous") return this.reject("no_match");
39133
+ if (applied.refusals[0]?.kind !== "ambiguous") return this.reject("no_match", helper ? void 0 : mismatchHint(lf, r.find, test));
39080
39134
  return this.reject("ambiguous", helper ? void 0 : ambiguityHint(lf, r.find, test) || void 0);
39081
39135
  }
39082
39136
  const at2 = lf.indexOf(r.find);
@@ -48230,215 +48284,624 @@ var TargetingHttpError = class extends Error {
48230
48284
  }
48231
48285
  };
48232
48286
 
48233
- // src/turnTimeout.ts
48234
- var FIRST_TURN_TIMEOUT_MS = 42e4;
48235
- var INVESTIGATE_FIRST_TURN_TIMEOUT_MS = 42e4;
48236
- function turnTimeoutFor(turn, perTurnMs, setByCaller, firstTurnMs = FIRST_TURN_TIMEOUT_MS) {
48237
- if (setByCaller || turn > 1) return perTurnMs;
48238
- return Math.max(perTurnMs, firstTurnMs);
48287
+ // src/dataPathCheck.ts
48288
+ var import_node_child_process9 = require("node:child_process");
48289
+ var import_node_fs17 = require("node:fs");
48290
+ var import_node_path20 = require("node:path");
48291
+
48292
+ // src/scopeCheck.ts
48293
+ var import_node_fs16 = require("node:fs");
48294
+ var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
48295
+ var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
48296
+ var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
48297
+ var CALL_LINE_RE = /fetch\s*\(|\baxios\b|(?:\$|\bjQuery)\.(?:ajax|get|post|getJSON)\s*\(|\bXMLHttpRequest\b|\.open\(\s*["'`](?:GET|POST|PUT|PATCH|DELETE)["'`]|\bhttp\.(?:get|post|put|patch|delete|head|request|postform|newrequest|newrequestwithcontext)\s*\(|\b(?:requests|httpx)\.(?:get|post|put|patch|delete|head|request)\s*\(|\bHttpRequest\.newBuilder\b|\bcurl\b/i;
48298
+ var NO_PATH = "(this file's route)";
48299
+ function detectMentions(text3) {
48300
+ const found = [];
48301
+ for (const line2 of text3.split("\n")) {
48302
+ const methodMatch = ROUTE_METHOD_RE.exec(line2);
48303
+ const pathMatch = ROUTE_PATH_RE.exec(line2);
48304
+ if (methodMatch && pathMatch && !CALL_LINE_RE.test(line2)) {
48305
+ found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0].replace(/:+$/, "") });
48306
+ }
48307
+ const exportMatch = ROUTE_EXPORT_RE.exec(line2);
48308
+ if (exportMatch) {
48309
+ found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
48310
+ }
48311
+ }
48312
+ return found;
48313
+ }
48314
+ function normalizePath(path) {
48315
+ return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
48316
+ }
48317
+ function surfaceCovers(surface, mention) {
48318
+ if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
48319
+ if (mention.path === NO_PATH) return true;
48320
+ const declaredPath = normalizePath(surface);
48321
+ const mentionPath = normalizePath(mention.path);
48322
+ return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
48323
+ }
48324
+ function addedLines(before, after) {
48325
+ const beforeLines = new Set(before.split("\n"));
48326
+ return after.split("\n").filter((line2) => !beforeLines.has(line2)).join("\n");
48327
+ }
48328
+ function checkApiScope(results, targets, apiChanges, existing) {
48329
+ const targetsByPath = new Map(targets.map((t) => [t.path, t]));
48330
+ const violations = [];
48331
+ for (const { targetPath, newContent } of results) {
48332
+ if (isTestFile(targetPath)) continue;
48333
+ const target = targetsByPath.get(targetPath);
48334
+ const isNewFile = target?.kind === "NEW_FILE";
48335
+ let scanned;
48336
+ if (isNewFile) {
48337
+ scanned = newContent;
48338
+ } else {
48339
+ let currentContent;
48340
+ try {
48341
+ currentContent = (0, import_node_fs16.readFileSync)(targetPath, "utf8");
48342
+ } catch {
48343
+ currentContent = "";
48344
+ }
48345
+ scanned = addedLines(currentContent, newContent);
48346
+ }
48347
+ for (const mention of detectMentions(scanned)) {
48348
+ if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
48349
+ if (existing && mention.path !== NO_PATH && existing.has(mention)) continue;
48350
+ violations.push({ file: targetPath, method: mention.method, path: mention.path });
48351
+ }
48352
+ }
48353
+ }
48354
+ return { blocked: violations.length > 0, violations };
48355
+ }
48356
+ function describeScopeViolations(check) {
48357
+ return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
48239
48358
  }
48240
48359
 
48241
- // src/targetingLoop.ts
48242
- var LOOP_CONTRACT_VERSION = "targeting-loop-1";
48243
- var MAP_LOOP_CONTRACT_VERSION = "targeting-loop-2";
48244
- var TOOLS2_LOOP_CONTRACT_VERSION = "targeting-loop-3";
48245
- var TOOLS2_LOOP_TOOLS = ["list_files", "read_file", "grep", "find_definition"];
48246
- var NOTES_LOOP_CONTRACT_VERSION = "targeting-loop-4";
48247
- var LoopFailure = class extends Error {
48248
- reason;
48249
- runtimeCode;
48250
- /** What the loop had done when it failed, so reads made before the failure are not lost. */
48251
- summary;
48252
- constructor(reason, runtimeCode, cause) {
48253
- super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
48254
- this.name = "LoopFailure";
48255
- this.reason = reason;
48256
- this.runtimeCode = runtimeCode;
48257
- if (cause !== void 0) this.cause = cause;
48360
+ // src/dataPathCheck.ts
48361
+ var SOURCE_PATHSPECS = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
48362
+ var SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
48363
+ var UI_FILE = /\.(?:tsx|jsx|vue|svelte|html?)$/i;
48364
+ var MAX_CANDIDATES = 80;
48365
+ var MAX_LOADING_FILES = 60;
48366
+ var MAX_SECOND_HOP = 12;
48367
+ var SCAN_BUDGET_MS = 8e3;
48368
+ var MAX_FILE_CHARS2 = 3e5;
48369
+ var MAX_LISTING = 3e4;
48370
+ var GIT_TIMEOUT_MS2 = 1e4;
48371
+ var GIT_MAX_BUFFER3 = 2e7;
48372
+ function routeSegment(seg) {
48373
+ if (/^\(.*\)$/.test(seg) || seg.startsWith("@")) return null;
48374
+ if (/^\[\[?\.\.\..*\]\]?$/.test(seg)) return "**";
48375
+ if (/^\[.*\]$/.test(seg)) return "*";
48376
+ return seg;
48377
+ }
48378
+ function routeAddressOf(file) {
48379
+ const segs = file.replace(/\\/g, "/").split("/");
48380
+ const last = segs[segs.length - 1] ?? "";
48381
+ const appAt = segs.indexOf("app");
48382
+ if (appAt >= 0 && /^route\.[cm]?[jt]sx?$/.test(last)) {
48383
+ const parts2 = segs.slice(appAt + 1, -1).map(routeSegment).filter((s) => s !== null);
48384
+ return `/${parts2.join("/")}`;
48258
48385
  }
48259
- };
48260
- var SafetyRefusalError = class extends RuntimeReplyError {
48261
- constructor(message, summary) {
48262
- super(message, summary);
48263
- this.name = "SafetyRefusalError";
48386
+ const pagesAt = segs.indexOf("pages");
48387
+ if (pagesAt >= 0 && segs[pagesAt + 1] === "api" && SOURCE_FILE.test(last)) {
48388
+ const name2 = last.replace(/\.[cm]?[jt]sx?$/, "");
48389
+ const parts2 = [...segs.slice(pagesAt + 1, -1), ...name2 === "index" ? [] : [name2]].map(routeSegment).filter((s) => s !== null);
48390
+ return `/${parts2.join("/")}`;
48264
48391
  }
48265
- };
48266
- var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
48267
- var OUTPUT_TOO_LARGE_CODES = /* @__PURE__ */ new Set(["CODEGEN_OUTPUT_TOO_LARGE", "OUTPUT_TRUNCATED"]);
48268
- var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep", "find_definition"]);
48269
- var MAX_ID_CHARS = 64;
48270
- var MAX_CALLS_IN_A_REPLY = 50;
48271
- var MAX_ARGS_JSON_CHARS = 1e3;
48272
- function isPlainObject2(x) {
48273
- return typeof x === "object" && x !== null && !Array.isArray(x);
48392
+ return null;
48274
48393
  }
48275
- function safeArgs(args2) {
48394
+ var LITERAL_RE = /[`'"]((?:\$\{[^}]*\})?\/[^`'"\s?#]*)/g;
48395
+ var API_LITERAL = /^(?:\$\{[^}]*\})?\/api\//;
48396
+ function literalsOf(line2) {
48397
+ return [...line2.matchAll(LITERAL_RE)].map((m) => m[1]);
48398
+ }
48399
+ function toAddress(raw) {
48400
+ const address = normalizePath(raw.replace(/\$\{[^}]*\}/g, "*")).replace(/\/+$/, "");
48401
+ if (address.startsWith("//")) return null;
48402
+ const segs = address.split("/").filter((s) => s !== "");
48403
+ return segs.some((s) => s !== "*") ? address : null;
48404
+ }
48405
+ function callAddressesIn(text3) {
48406
+ const lines = text3.split("\n");
48407
+ const found = [];
48408
+ const add2 = (raw) => {
48409
+ const a = raw === void 0 ? null : toAddress(raw);
48410
+ if (a !== null && !found.includes(a)) found.push(a);
48411
+ };
48412
+ for (let i3 = 0; i3 < lines.length; i3++) {
48413
+ const lits = literalsOf(lines[i3]);
48414
+ if (CALL_LINE_RE.test(lines[i3])) {
48415
+ let first = lits[0];
48416
+ for (let j = i3 + 1; first === void 0 && j <= i3 + 2 && j < lines.length; j++) first = literalsOf(lines[j])[0];
48417
+ add2(first);
48418
+ }
48419
+ for (const lit of lits) if (API_LITERAL.test(lit)) add2(lit);
48420
+ }
48421
+ return found;
48422
+ }
48423
+ function addressMatches(route, call) {
48424
+ const r = route.split("/").filter((s) => s !== "");
48425
+ const c = call.split("/").filter((s) => s !== "");
48426
+ const same = (a, b) => a === b || a === "*" || b === "*";
48427
+ const wide = r.indexOf("**");
48428
+ if (wide >= 0) return c.length >= wide && r.slice(0, wide).every((s, i3) => same(s, c[i3]));
48429
+ if (c.length > r.length) return false;
48430
+ const tail2 = r.slice(r.length - c.length);
48431
+ return c.every((s, i3) => same(tail2[i3], s));
48432
+ }
48433
+ var git3 = (cwd, args2) => {
48276
48434
  try {
48277
- return JSON.stringify(args2).length <= MAX_ARGS_JSON_CHARS ? args2 : { _omitted: "too large" };
48435
+ return (0, import_node_child_process9.execFileSync)("git", args2, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48278
48436
  } catch {
48279
- return { _omitted: "unreadable" };
48437
+ return "";
48280
48438
  }
48439
+ };
48440
+ function lastSegment(spec) {
48441
+ const segs = spec.split("/").filter((s) => s !== "" && s !== "." && s !== "..");
48442
+ let name2 = segs.pop() ?? "";
48443
+ if (/^index(?:\.[cm]?[jt]sx?)?$/.test(name2)) name2 = segs.pop() ?? "";
48444
+ return name2.replace(/\.[cm]?[jt]sx?$/, "");
48281
48445
  }
48282
- function classifyTransport(err2) {
48283
- if (err2 instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err2);
48284
- const name2 = err2?.name;
48285
- if (name2 === "TimeoutError" || name2 === "AbortError") return new LoopFailure("turn_timeout", void 0, err2);
48286
- return new LoopFailure("transport", void 0, err2);
48446
+ function baseOf(path) {
48447
+ return lastSegment(path);
48287
48448
  }
48288
- async function runTargetingLoop(args2, deps) {
48289
- const limits = { ...DEFAULT_LIMITS, ...deps.limits };
48290
- const now = deps.now ?? Date.now;
48291
- const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
48292
- const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
48293
- const deadlineMs = deps.deadlineMs ?? 9e5;
48294
- const env2 = {
48295
- listing: new Set(args2.listing),
48296
- visible: buildVisibleListing(args2.listing, readDenied(args2.deniedPaths)),
48297
- deniedPaths: writeDenied(args2.deniedPaths),
48298
- readDenied: readDenied(args2.deniedPaths),
48299
- fs: deps.fs ?? createNodeToolFs(),
48300
- limits,
48301
- scrub: makeCodeScrubber(deps.secrets ?? [], (c) => log({ event: "loop.scrubbed", ...nonZero(c) })),
48302
- ...args2.readRoots ? { readRoots: args2.readRoots } : {},
48303
- ...args2.tools2 ? { tools2: args2.tools2 } : {}
48304
- };
48305
- const notesOn = args2.tools2?.notes === true;
48306
- if (notesOn) {
48307
- const denied = readDenied(args2.deniedPaths);
48308
- const shownInMap = args2.baseContext.repoMap?.guidance;
48309
- env2.guidance = makeGuidanceFinder({
48310
- listing: env2.listing,
48311
- readText: (path) => readFileText(env2.fs, path),
48312
- isDenied: (path) => matchesDeniedPath(path, denied) !== null,
48313
- ...env2.scrub ? { scrub: env2.scrub } : {},
48314
- alreadyShown: (Array.isArray(shownInMap) ? shownInMap : []).map((g) => g.path).filter((p) => typeof p === "string")
48315
- });
48449
+ var GENERIC_BASES = /* @__PURE__ */ new Set(["index", "page", "layout", "route", "main", "app", "utils", "util", "types", "type", "constants", "config", "client", "server", "loading", "error", "default"]);
48450
+ var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48451
+ function graph(cwd, read, skip, expired) {
48452
+ const listing = git3(cwd, ["ls-files"]).split("\n").filter((p) => SOURCE_FILE.test(p));
48453
+ const byBase = /* @__PURE__ */ new Map();
48454
+ if (listing.length <= MAX_LISTING) {
48455
+ for (const p of listing) {
48456
+ const base = baseOf(p);
48457
+ if (base === "") continue;
48458
+ const held = byBase.get(base);
48459
+ if (held) held.push(p);
48460
+ else byBase.set(base, [p]);
48461
+ }
48316
48462
  }
48317
- let notes = "";
48318
- let stubbed = 0;
48319
- const turnOfId = /* @__PURE__ */ new Map();
48320
- const callOfId = /* @__PURE__ */ new Map();
48321
- const ledger = newLedger();
48322
- const reads = [];
48323
- const transcript = [];
48324
- const toolResults = [];
48325
- const usedIds = /* @__PURE__ */ new Set();
48326
- const refusedTurns = [];
48327
- let refusedStreak = 0;
48328
- let unreadableStreak = 0;
48329
- let peakRequestTokens = 0;
48330
- const usage = new TurnUsage();
48331
- let turns = 0;
48332
- let noProgressStreak = 0;
48333
- let forced = null;
48334
- const started = now();
48335
- const buildContext = (turn, isFinal, finalReason) => ({
48336
- ...args2.baseContext,
48337
- contractVersion: args2.contractVersion ?? LOOP_CONTRACT_VERSION,
48338
- loop: {
48339
- turn,
48340
- maxTurns: limits.maxTurns,
48341
- final: isFinal,
48342
- ...isFinal ? { finalReason } : {},
48343
- // Says this runner can carry a REFUSED answer (contract 23.14). Without it the runtime fails the request, as it always did.
48344
- acceptsRefused: true,
48345
- remaining: {
48346
- toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
48347
- readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
48348
- },
48349
- transcript,
48350
- toolResults,
48351
- ...args2.tools2 ? { tools: [...TOOLS2_LOOP_TOOLS] } : {},
48352
- // Section 37: LAST in `loop`, so the end of the request repeats the cases, the folders the AI may change and its own notes.
48353
- ...notesOn ? { recap: buildRecap({ baseContext: args2.baseContext, writeRoots: args2.tools2?.writeRoots ?? [], notes }) } : {}
48463
+ const text3 = (p) => {
48464
+ const t = read(p);
48465
+ return t !== null && t.length <= MAX_FILE_CHARS2 ? t : null;
48466
+ };
48467
+ const specifiers = (p) => {
48468
+ const t = supportsImportScan(p) ? text3(p) : null;
48469
+ return t === null ? [] : extractImportSpecifiers(t);
48470
+ };
48471
+ return {
48472
+ importersOf(file) {
48473
+ const base = baseOf(file);
48474
+ if (base.length < 3 || GENERIC_BASES.has(base) || expired()) return [];
48475
+ const pattern = `['"/]${escapeRegex(base)}(/index)?(\\.[cm]?[jt]sx?)?['"]`;
48476
+ const hits = git3(cwd, ["grep", "-l", "-I", "-E", "-e", pattern, "--", ...SOURCE_PATHSPECS]).split("\n").filter((p) => p !== "" && p !== file && !skip(p));
48477
+ return hits.slice(0, MAX_CANDIDATES).filter((p) => !expired() && specifiers(p).some((s) => lastSegment(s) === base));
48478
+ },
48479
+ importsOf(file) {
48480
+ const out2 = [];
48481
+ for (const s of specifiers(file)) {
48482
+ if (!s.startsWith(".") && !s.startsWith("@/") && !s.startsWith("~/")) continue;
48483
+ for (const p of (byBase.get(lastSegment(s)) ?? []).slice(0, 6)) if (p !== file && !skip(p) && !out2.includes(p)) out2.push(p);
48484
+ }
48485
+ return out2;
48354
48486
  }
48487
+ };
48488
+ }
48489
+ function loadingFiles(cwd, screens, read, skip, expired) {
48490
+ const g = graph(cwd, read, skip, expired);
48491
+ const files = [];
48492
+ const add2 = (p) => {
48493
+ if (files.length < MAX_LOADING_FILES && !files.includes(p)) files.push(p);
48494
+ };
48495
+ const hop1 = unique2(screens.flatMap((s) => g.importersOf(s)));
48496
+ for (const p of hop1) add2(p);
48497
+ for (const p of hop1.slice(0, MAX_SECOND_HOP).flatMap((f) => g.importersOf(f))) add2(p);
48498
+ for (const s of screens) add2(s);
48499
+ for (const p of [...files].flatMap((f) => expired() ? [] : g.importsOf(f))) add2(p);
48500
+ return files;
48501
+ }
48502
+ function isScreenFile(path) {
48503
+ return UI_FILE.test(path);
48504
+ }
48505
+ function screenLoaders(cwd, screen, read, skip, expired) {
48506
+ const g = graph(cwd, read, skip, expired);
48507
+ const hop1 = g.importersOf(screen);
48508
+ const hop2 = hop1.slice(0, MAX_SECOND_HOP).flatMap((f) => expired() ? [] : g.importersOf(f));
48509
+ const out2 = [];
48510
+ for (const file of unique2([...hop1, ...hop2]).slice(0, MAX_LOADING_FILES)) {
48511
+ if (expired()) break;
48512
+ const text3 = read(file);
48513
+ if (text3 === null || text3.length > MAX_FILE_CHARS2) continue;
48514
+ const calls = callAddressesIn(text3);
48515
+ if (calls.length > 0) out2.push({ file, calls });
48516
+ }
48517
+ return out2;
48518
+ }
48519
+ function readFromCheckout(root) {
48520
+ return (path) => {
48521
+ try {
48522
+ const abs = (0, import_node_path20.join)(root, path);
48523
+ const st = (0, import_node_fs17.lstatSync)(abs);
48524
+ return st.isSymbolicLink() || !st.isFile() || st.size > MAX_FILE_CHARS2 ? null : (0, import_node_fs17.readFileSync)(abs, "utf8");
48525
+ } catch {
48526
+ return null;
48527
+ }
48528
+ };
48529
+ }
48530
+ var unique2 = (xs) => [...new Set(xs)];
48531
+ var slashed = (p) => p.replace(/\\/g, "/");
48532
+ function plannedChanged(input, changed, kind) {
48533
+ return unique2(input.parts.filter((p) => p.kind === kind).flatMap((p) => p.paths.map(slashed))).filter((p) => changed.has(p) && !input.isTest(p));
48534
+ }
48535
+ var withAddress = (files) => files.flatMap((file) => {
48536
+ const address = routeAddressOf(file);
48537
+ return address === null ? [] : [{ file, address }];
48538
+ });
48539
+ function unplannedRoutes(input, changed) {
48540
+ const planned = new Set(input.parts.flatMap((p) => p.paths.map(slashed)));
48541
+ return withAddress([...changed].sort().filter((f) => !planned.has(f) && !input.isTest(f)));
48542
+ }
48543
+ function callsLoadingScreens(input, screens) {
48544
+ const started = Date.now();
48545
+ const expired = () => Date.now() - started > SCAN_BUDGET_MS;
48546
+ const denied = [...input.deniedPaths];
48547
+ const skip = (p) => input.isTest(p) || matchesDeniedPath(p, denied) !== null || input.readable != null && !input.readable.has(p);
48548
+ const calls = [];
48549
+ const files = loadingFiles(input.cwd, screens, input.read, skip, expired);
48550
+ for (const file of files) {
48551
+ const text3 = input.read(file);
48552
+ if (text3 === null || text3.length > MAX_FILE_CHARS2) continue;
48553
+ for (const call of callAddressesIn(text3)) calls.push({ file, call });
48554
+ }
48555
+ input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
48556
+ return calls;
48557
+ }
48558
+ function dataPathGap(input) {
48559
+ const changed = new Set(input.changed.map(slashed));
48560
+ const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48561
+ const routes = withAddress(plannedChanged(input, changed, "data"));
48562
+ if (screens.length === 0 || routes.length === 0) return null;
48563
+ const calls = callsLoadingScreens(input, screens);
48564
+ if (calls.length === 0) return null;
48565
+ const answering = [...routes, ...unplannedRoutes(input, changed)];
48566
+ if (answering.some((r) => calls.some((c) => addressMatches(r.address, c.call)))) return null;
48567
+ return { screen: screens[0], loader: calls[0].file, call: calls[0].call, routeFile: routes[0].file, route: routes[0].address };
48568
+ }
48569
+ function withoutMovedData(missing, input) {
48570
+ const open = missing.filter((m) => m.why === "unchanged" && m.part.kind === "data" && m.part.database === void 0);
48571
+ if (open.length === 0) return [...missing];
48572
+ const changed = new Set(input.changed.map(slashed));
48573
+ const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48574
+ if (screens.length === 0) return [...missing];
48575
+ const moved = unplannedRoutes(input, changed);
48576
+ if (moved.length === 0) return [...missing];
48577
+ const calls = callsLoadingScreens(input, screens);
48578
+ let excuses = moved.filter((r) => calls.some((c) => addressMatches(r.address, c.call))).length;
48579
+ return missing.filter((m) => {
48580
+ if (excuses > 0 && open.includes(m)) {
48581
+ excuses -= 1;
48582
+ return false;
48583
+ }
48584
+ return true;
48355
48585
  });
48356
- const snapshot = (stopReason) => ({
48357
- turns,
48358
- toolCalls: ledger.toolCalls,
48359
- readChars: ledger.readChars,
48360
- refused: ledger.refused,
48361
- stopReason,
48362
- reads: [...reads],
48363
- ...refusedTurns.length > 0 ? { refusedTurns: refusedTurns.map((t) => ({ turn: t.turn, rules: [...t.rules] })) } : {},
48364
- ...peakRequestTokens > 0 ? { peakRequestTokens } : {},
48365
- ...args2.tools2 ? { contractVersion: args2.contractVersion ?? TOOLS2_LOOP_CONTRACT_VERSION } : {},
48366
- ...notesOn ? { notes: { chars: notes.length, stubbed, guidance: env2.guidance?.shown() ?? 0 } } : {},
48367
- ...usage.totals.calls > 0 ? { turnUsage: usage.rows.map((r) => ({ ...r, parts: { ...r.parts } })), usage: { ...usage.totals } } : {},
48368
- ...usage.rowsCut ? { turnUsageCut: true } : {}
48369
- });
48370
- log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args2.listing.length });
48586
+ }
48587
+ var tail = (path, n) => path.split("/").slice(-n).join("/");
48588
+ var endOf = (s, n) => s.length <= n ? s : `\u2026${s.slice(s.length - (n - 1))}`;
48589
+ function fit(limit, build) {
48590
+ const whole4 = (s) => s;
48591
+ const spellings = [
48592
+ [whole4, whole4],
48593
+ [(p) => tail(p, 2), whole4],
48594
+ [(p) => tail(p, 1), whole4]
48595
+ ];
48596
+ for (const [file, address] of spellings) {
48597
+ const s = build(file, address);
48598
+ if (s.length <= limit) return s;
48599
+ }
48600
+ return build((p) => endOf(tail(p, 1), 22), (a) => endOf(a, 22)).slice(0, limit);
48601
+ }
48602
+ function dataPathSentence(g) {
48603
+ return fit(
48604
+ MAX_REFUSED_SENTENCE_CHARS,
48605
+ (f, a) => `${f(g.screen)} is shown from ${f(g.loader)}, which loads ${a(g.call)}; the data was added in ${f(g.routeFile)} (${a(g.route)}). Add it where ${a(g.call)} is answered too and keep that change, or say why ${a(g.route)} alone is right.`
48606
+ );
48607
+ }
48608
+ var DATA_PATH_MESSAGE = "Your answer was sent back: the data this feature adds may not reach the screen that shows it. The sentence names the screen, where its data is loaded from, and the route that was changed instead. This check is made once.";
48609
+ function dataPathAnswer(g) {
48610
+ return { rules: ["done_rule"], violations: [dataPathSentence(g)], message: DATA_PATH_MESSAGE };
48611
+ }
48612
+ function dataPathWarning(g) {
48613
+ return `QuikPilot could not confirm that the new data reaches the screen: ${g.screen} is shown from ${g.loader}, which loads its data from ${g.call}, but the data was added in ${g.routeFile} (${g.route}). Check that the screen shows it.`.slice(0, 1500);
48614
+ }
48615
+ function dataPathAtTargeting(input) {
48616
+ const seen = { files: 0, calls: 0, ms: 0 };
48371
48617
  try {
48372
- for (let turn = 1; turn <= limits.maxTurns; turn++) {
48373
- turns = turn;
48374
- if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
48375
- const isFinal = forced !== null || turn === limits.maxTurns;
48376
- const finalReason = forced ?? "max_turns";
48377
- const contextData = buildContext(turn, isFinal, finalReason);
48378
- const requestChars = JSON.stringify(contextData).length;
48379
- const requestTokens = estimateRequestTokens(contextData);
48380
- peakRequestTokens = Math.max(peakRequestTokens, requestTokens);
48381
- if (requestTokens > limits.maxRequestTokens) {
48382
- log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
48383
- throw new LoopFailure("token_ceiling");
48384
- }
48385
- const turnStarted = now();
48386
- let envelope;
48387
- try {
48388
- envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutFor(turn, turnTimeoutMs, deps.turnTimeoutMs !== void 0)));
48389
- } catch (err2) {
48390
- throw classifyTransport(err2);
48391
- }
48392
- usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
48393
- const code = envelope?.errorCode;
48394
- try {
48395
- checkHardFailure(envelope, "pilot.targeting");
48396
- } catch (err2) {
48397
- throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err2);
48398
- }
48399
- if (envelope?.success === false) {
48400
- const runtimeCode = typeof code === "string" ? code : void 0;
48401
- if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
48402
- let inner;
48403
- try {
48404
- unwrapExecute(envelope, "pilot.targeting");
48405
- } catch (e) {
48406
- inner = e instanceof RuntimeReplyError ? e : void 0;
48407
- }
48408
- const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
48409
- throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
48410
- }
48411
- if (runtimeCode === MALFORMED_REPLY_CODE && shouldRecover({ isFinal, consecutive: unreadableStreak })) {
48412
- unreadableStreak += 1;
48413
- refusedTurns.push({ turn, rules: [RECOVERY_RULE] });
48414
- transcript.push({ turn, toolCalls: [], refused: recoveryAnswer("malformed") });
48415
- log({ event: "targeting.loop_recovered", turn, reason: "schema_mismatch", runtimeCode, elapsedMs: now() - turnStarted });
48416
- continue;
48417
- }
48418
- throw new LoopFailure(runtimeCode && OUTPUT_TOO_LARGE_CODES.has(runtimeCode) ? "output_too_large" : "runtime_failed", runtimeCode);
48419
- }
48420
- let body2;
48618
+ const gap = dataPathGap({ ...input, onScan: (i3) => Object.assign(seen, { files: i3.files.length, calls: i3.calls.length, ms: i3.ms }) });
48619
+ return { outcome: gap !== null ? "gap" : seen.calls > 0 ? "ok" : "silent", ...seen };
48620
+ } catch {
48621
+ return { outcome: "silent", ...seen };
48622
+ }
48623
+ }
48624
+
48625
+ // src/screenTrace.ts
48626
+ var SCREEN_TRACE_ENV = "QUIKPILOT_SCREEN_TRACE";
48627
+ function screenTraceOn(env2 = process.env) {
48628
+ return env2[SCREEN_TRACE_ENV]?.trim().toLowerCase() === "on";
48629
+ }
48630
+ var MAX_SHOWN_BY = 4;
48631
+ var MAX_LOADS_PER_FILE = 2;
48632
+ var MAX_NOTE_CHARS2 = 600;
48633
+ var SCREEN_TRACE_BUDGET_MS = 3e3;
48634
+ function makeScreenTracer(deps) {
48635
+ const visible = deps.visible instanceof Set ? deps.visible : new Set(deps.visible);
48636
+ const now = deps.now ?? Date.now;
48637
+ const budgetMs = deps.budgetMs ?? SCREEN_TRACE_BUDGET_MS;
48638
+ const done = /* @__PURE__ */ new Set();
48639
+ let routes;
48640
+ const routeFiles = () => {
48641
+ if (!routes) {
48642
+ routes = [];
48643
+ for (const file of [...visible].sort()) {
48644
+ const address = routeAddressOf(file);
48645
+ if (address !== null && !deps.isTest(file) && !deps.isDenied(file)) routes.push({ file, address });
48646
+ }
48647
+ }
48648
+ return routes;
48649
+ };
48650
+ const answeredBy = (call) => {
48651
+ const all = routeFiles().filter((r) => addressMatches(r.address, call));
48652
+ return (all.find((r) => r.address === call) ?? all[0])?.file;
48653
+ };
48654
+ return {
48655
+ forRead(path) {
48656
+ if (done.has(path)) return void 0;
48657
+ done.add(path);
48658
+ if (!isScreenFile(path) || deps.isTest(path) || deps.isDenied(path)) return void 0;
48659
+ const started = now();
48660
+ const expired = () => now() - started > budgetMs;
48661
+ let note;
48421
48662
  try {
48422
- body2 = unwrapExecute(envelope, "pilot.targeting");
48423
- } catch (err2) {
48424
- throw new LoopFailure("bad_reply", void 0, err2);
48425
- }
48426
- unreadableStreak = 0;
48427
- if (body2.outcome === REFUSED_OUTCOME) {
48428
- const answer = readRefusedAnswer(body2);
48429
- if (!answer) throw new LoopFailure("bad_reply");
48430
- refusedStreak += 1;
48431
- refusedTurns.push({ turn, rules: answer.rules });
48432
- log({ event: "targeting.loop_turn", turn, outcome: "refused", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [], rules: answer.rules.map(recordRuleWord), streak: refusedStreak });
48433
- if (isFinal) throw new LoopFailure("final_not_produced");
48434
- transcript.push({ turn, toolCalls: [], refused: answer });
48435
- if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
48436
- continue;
48663
+ const skip = (p) => deps.isTest(p) || deps.isDenied(p) || !visible.has(p);
48664
+ const shownBy = [];
48665
+ for (const loader of screenLoaders(deps.cwd, path, deps.read, skip, expired)) {
48666
+ if (shownBy.length >= MAX_SHOWN_BY) break;
48667
+ const loads = [];
48668
+ for (const call of loader.calls) {
48669
+ const route = answeredBy(call);
48670
+ if (route !== void 0 && loads.length < MAX_LOADS_PER_FILE && !loads.some((l) => l.call === call)) loads.push({ call, route });
48671
+ }
48672
+ if (loads.length > 0) shownBy.push({ file: loader.file, loads });
48673
+ }
48674
+ while (shownBy.length > 0 && JSON.stringify({ shownBy }).length > MAX_NOTE_CHARS2) shownBy.pop();
48675
+ if (shownBy.length > 0) note = { shownBy };
48676
+ } catch {
48677
+ note = void 0;
48437
48678
  }
48438
- if (body2.outcome === "TARGETED" || body2.outcome === "NO_TARGET") {
48439
- log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
48440
- const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
48441
- log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
48679
+ deps.onTrace?.({ outcome: note ? "note" : "silent", entries: note?.shownBy.length ?? 0, ms: now() - started });
48680
+ return note;
48681
+ }
48682
+ };
48683
+ }
48684
+
48685
+ // src/turnTimeout.ts
48686
+ var FIRST_TURN_TIMEOUT_MS = 42e4;
48687
+ var INVESTIGATE_FIRST_TURN_TIMEOUT_MS = 42e4;
48688
+ function turnTimeoutFor(turn, perTurnMs, setByCaller, firstTurnMs = FIRST_TURN_TIMEOUT_MS) {
48689
+ if (setByCaller || turn > 1) return perTurnMs;
48690
+ return Math.max(perTurnMs, firstTurnMs);
48691
+ }
48692
+
48693
+ // src/targetingLoop.ts
48694
+ var LOOP_CONTRACT_VERSION = "targeting-loop-1";
48695
+ var MAP_LOOP_CONTRACT_VERSION = "targeting-loop-2";
48696
+ var TOOLS2_LOOP_CONTRACT_VERSION = "targeting-loop-3";
48697
+ var TOOLS2_LOOP_TOOLS = ["list_files", "read_file", "grep", "find_definition"];
48698
+ var NOTES_LOOP_CONTRACT_VERSION = "targeting-loop-4";
48699
+ var LoopFailure = class extends Error {
48700
+ reason;
48701
+ runtimeCode;
48702
+ /** What the loop had done when it failed, so reads made before the failure are not lost. */
48703
+ summary;
48704
+ constructor(reason, runtimeCode, cause) {
48705
+ super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
48706
+ this.name = "LoopFailure";
48707
+ this.reason = reason;
48708
+ this.runtimeCode = runtimeCode;
48709
+ if (cause !== void 0) this.cause = cause;
48710
+ }
48711
+ };
48712
+ var SafetyRefusalError = class extends RuntimeReplyError {
48713
+ constructor(message, summary) {
48714
+ super(message, summary);
48715
+ this.name = "SafetyRefusalError";
48716
+ }
48717
+ };
48718
+ var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
48719
+ var OUTPUT_TOO_LARGE_CODES = /* @__PURE__ */ new Set(["CODEGEN_OUTPUT_TOO_LARGE", "OUTPUT_TRUNCATED"]);
48720
+ var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep", "find_definition"]);
48721
+ var MAX_ID_CHARS = 64;
48722
+ var MAX_CALLS_IN_A_REPLY = 50;
48723
+ var MAX_ARGS_JSON_CHARS = 1e3;
48724
+ function isPlainObject2(x) {
48725
+ return typeof x === "object" && x !== null && !Array.isArray(x);
48726
+ }
48727
+ function safeArgs(args2) {
48728
+ try {
48729
+ return JSON.stringify(args2).length <= MAX_ARGS_JSON_CHARS ? args2 : { _omitted: "too large" };
48730
+ } catch {
48731
+ return { _omitted: "unreadable" };
48732
+ }
48733
+ }
48734
+ function classifyTransport(err2) {
48735
+ if (err2 instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err2);
48736
+ const name2 = err2?.name;
48737
+ if (name2 === "TimeoutError" || name2 === "AbortError") return new LoopFailure("turn_timeout", void 0, err2);
48738
+ return new LoopFailure("transport", void 0, err2);
48739
+ }
48740
+ async function runTargetingLoop(args2, deps) {
48741
+ const limits = { ...DEFAULT_LIMITS, ...deps.limits };
48742
+ const now = deps.now ?? Date.now;
48743
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
48744
+ const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
48745
+ const deadlineMs = deps.deadlineMs ?? 9e5;
48746
+ const env2 = {
48747
+ listing: new Set(args2.listing),
48748
+ visible: buildVisibleListing(args2.listing, readDenied(args2.deniedPaths)),
48749
+ deniedPaths: writeDenied(args2.deniedPaths),
48750
+ readDenied: readDenied(args2.deniedPaths),
48751
+ fs: deps.fs ?? createNodeToolFs(),
48752
+ limits,
48753
+ scrub: makeCodeScrubber(deps.secrets ?? [], (c) => log({ event: "loop.scrubbed", ...nonZero(c) })),
48754
+ ...args2.readRoots ? { readRoots: args2.readRoots } : {},
48755
+ ...args2.tools2 ? { tools2: args2.tools2 } : {}
48756
+ };
48757
+ const notesOn = args2.tools2?.notes === true;
48758
+ if (notesOn) {
48759
+ const denied = readDenied(args2.deniedPaths);
48760
+ const shownInMap = args2.baseContext.repoMap?.guidance;
48761
+ env2.guidance = makeGuidanceFinder({
48762
+ listing: env2.listing,
48763
+ readText: (path) => readFileText(env2.fs, path),
48764
+ isDenied: (path) => matchesDeniedPath(path, denied) !== null,
48765
+ ...env2.scrub ? { scrub: env2.scrub } : {},
48766
+ alreadyShown: (Array.isArray(shownInMap) ? shownInMap : []).map((g) => g.path).filter((p) => typeof p === "string")
48767
+ });
48768
+ }
48769
+ if (args2.tools2 && (deps.screenTrace ?? screenTraceOn())) {
48770
+ const denied = readDenied(args2.deniedPaths);
48771
+ env2.screenTrace = makeScreenTracer({
48772
+ cwd: env2.fs.rootReal,
48773
+ visible: env2.visible,
48774
+ read: (path) => readFileText(env2.fs, path),
48775
+ isDenied: (path) => matchesDeniedPath(path, denied) !== null,
48776
+ isTest: isTestFile,
48777
+ onTrace: (t) => log({ event: "targeting.screen_trace", outcome: t.outcome, entries: t.entries, ms: t.ms })
48778
+ });
48779
+ }
48780
+ let notes = "";
48781
+ let stubbed = 0;
48782
+ const turnOfId = /* @__PURE__ */ new Map();
48783
+ const callOfId = /* @__PURE__ */ new Map();
48784
+ const ledger = newLedger();
48785
+ const reads = [];
48786
+ const transcript = [];
48787
+ const toolResults = [];
48788
+ const usedIds = /* @__PURE__ */ new Set();
48789
+ const refusedTurns = [];
48790
+ let refusedStreak = 0;
48791
+ let unreadableStreak = 0;
48792
+ let peakRequestTokens = 0;
48793
+ const usage = new TurnUsage();
48794
+ let turns = 0;
48795
+ let noProgressStreak = 0;
48796
+ let forced = null;
48797
+ const started = now();
48798
+ const buildContext = (turn, isFinal, finalReason) => ({
48799
+ ...args2.baseContext,
48800
+ contractVersion: args2.contractVersion ?? LOOP_CONTRACT_VERSION,
48801
+ loop: {
48802
+ turn,
48803
+ maxTurns: limits.maxTurns,
48804
+ final: isFinal,
48805
+ ...isFinal ? { finalReason } : {},
48806
+ // Says this runner can carry a REFUSED answer (contract 23.14). Without it the runtime fails the request, as it always did.
48807
+ acceptsRefused: true,
48808
+ remaining: {
48809
+ toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
48810
+ readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
48811
+ },
48812
+ transcript,
48813
+ toolResults,
48814
+ ...args2.tools2 ? { tools: [...TOOLS2_LOOP_TOOLS] } : {},
48815
+ // Section 37: LAST in `loop`, so the end of the request repeats the cases, the folders the AI may change and its own notes.
48816
+ ...notesOn ? { recap: buildRecap({ baseContext: args2.baseContext, writeRoots: args2.tools2?.writeRoots ?? [], notes }) } : {}
48817
+ }
48818
+ });
48819
+ const snapshot = (stopReason) => ({
48820
+ turns,
48821
+ toolCalls: ledger.toolCalls,
48822
+ readChars: ledger.readChars,
48823
+ refused: ledger.refused,
48824
+ stopReason,
48825
+ reads: [...reads],
48826
+ ...refusedTurns.length > 0 ? { refusedTurns: refusedTurns.map((t) => ({ turn: t.turn, rules: [...t.rules] })) } : {},
48827
+ ...peakRequestTokens > 0 ? { peakRequestTokens } : {},
48828
+ ...args2.tools2 ? { contractVersion: args2.contractVersion ?? TOOLS2_LOOP_CONTRACT_VERSION } : {},
48829
+ ...notesOn ? { notes: { chars: notes.length, stubbed, guidance: env2.guidance?.shown() ?? 0 } } : {},
48830
+ ...usage.totals.calls > 0 ? { turnUsage: usage.rows.map((r) => ({ ...r, parts: { ...r.parts } })), usage: { ...usage.totals } } : {},
48831
+ ...usage.rowsCut ? { turnUsageCut: true } : {}
48832
+ });
48833
+ log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args2.listing.length });
48834
+ try {
48835
+ for (let turn = 1; turn <= limits.maxTurns; turn++) {
48836
+ turns = turn;
48837
+ if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
48838
+ const isFinal = forced !== null || turn === limits.maxTurns;
48839
+ const finalReason = forced ?? "max_turns";
48840
+ const contextData = buildContext(turn, isFinal, finalReason);
48841
+ const requestChars = JSON.stringify(contextData).length;
48842
+ const requestTokens = estimateRequestTokens(contextData);
48843
+ peakRequestTokens = Math.max(peakRequestTokens, requestTokens);
48844
+ if (requestTokens > limits.maxRequestTokens) {
48845
+ log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
48846
+ throw new LoopFailure("token_ceiling");
48847
+ }
48848
+ const turnStarted = now();
48849
+ let envelope;
48850
+ try {
48851
+ envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutFor(turn, turnTimeoutMs, deps.turnTimeoutMs !== void 0)));
48852
+ } catch (err2) {
48853
+ throw classifyTransport(err2);
48854
+ }
48855
+ usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
48856
+ const code = envelope?.errorCode;
48857
+ try {
48858
+ checkHardFailure(envelope, "pilot.targeting");
48859
+ } catch (err2) {
48860
+ throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err2);
48861
+ }
48862
+ if (envelope?.success === false) {
48863
+ const runtimeCode = typeof code === "string" ? code : void 0;
48864
+ if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
48865
+ let inner;
48866
+ try {
48867
+ unwrapExecute(envelope, "pilot.targeting");
48868
+ } catch (e) {
48869
+ inner = e instanceof RuntimeReplyError ? e : void 0;
48870
+ }
48871
+ const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
48872
+ throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
48873
+ }
48874
+ if (runtimeCode === MALFORMED_REPLY_CODE && shouldRecover({ isFinal, consecutive: unreadableStreak })) {
48875
+ unreadableStreak += 1;
48876
+ refusedTurns.push({ turn, rules: [RECOVERY_RULE] });
48877
+ transcript.push({ turn, toolCalls: [], refused: recoveryAnswer("malformed") });
48878
+ log({ event: "targeting.loop_recovered", turn, reason: "schema_mismatch", runtimeCode, elapsedMs: now() - turnStarted });
48879
+ continue;
48880
+ }
48881
+ throw new LoopFailure(runtimeCode && OUTPUT_TOO_LARGE_CODES.has(runtimeCode) ? "output_too_large" : "runtime_failed", runtimeCode);
48882
+ }
48883
+ let body2;
48884
+ try {
48885
+ body2 = unwrapExecute(envelope, "pilot.targeting");
48886
+ } catch (err2) {
48887
+ throw new LoopFailure("bad_reply", void 0, err2);
48888
+ }
48889
+ unreadableStreak = 0;
48890
+ if (body2.outcome === REFUSED_OUTCOME) {
48891
+ const answer = readRefusedAnswer(body2);
48892
+ if (!answer) throw new LoopFailure("bad_reply");
48893
+ refusedStreak += 1;
48894
+ refusedTurns.push({ turn, rules: answer.rules });
48895
+ log({ event: "targeting.loop_turn", turn, outcome: "refused", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [], rules: answer.rules.map(recordRuleWord), streak: refusedStreak });
48896
+ if (isFinal) throw new LoopFailure("final_not_produced");
48897
+ transcript.push({ turn, toolCalls: [], refused: answer });
48898
+ if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
48899
+ continue;
48900
+ }
48901
+ if (body2.outcome === "TARGETED" || body2.outcome === "NO_TARGET") {
48902
+ log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
48903
+ const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
48904
+ log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
48442
48905
  return { body: body2, summary: snapshot(stopReason) };
48443
48906
  }
48444
48907
  if (body2.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
@@ -48539,482 +49002,170 @@ async function runTargetingLoop(args2, deps) {
48539
49002
  projectedTokens: projected,
48540
49003
  ceiling: limits.maxRequestTokens
48541
49004
  });
48542
- if (!fits) throw new LoopFailure("token_ceiling");
48543
- }
48544
- }
48545
- log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48546
- }
48547
- throw new LoopFailure("final_not_produced");
48548
- } catch (err2) {
48549
- if (err2 instanceof SafetyRefusalError) throw err2;
48550
- const failure = err2 instanceof LoopFailure ? err2 : new LoopFailure("internal_error", void 0, err2);
48551
- failure.summary ??= snapshot("fallback");
48552
- throw failure;
48553
- }
48554
- }
48555
-
48556
- // src/workingFiles.ts
48557
- var KEEP_WORKING_FILES_ENV = "QUIKPILOT_KEEP_WORKING_FILES";
48558
- var MAX_WORKING_PATHS = 3;
48559
- var MAX_KEPT_CHARS = 4e4;
48560
- function keepWorkingFilesOn(env2 = process.env) {
48561
- return env2[KEEP_WORKING_FILES_ENV]?.trim().toLowerCase() === "on";
48562
- }
48563
- function rangeOf(args2) {
48564
- if (typeof args2 !== "object" || args2 === null) return {};
48565
- const a = args2;
48566
- if (a.mode === "outline") return { mode: "outline" };
48567
- const out2 = {};
48568
- if (typeof a.startLine === "number" && Number.isInteger(a.startLine)) out2.startLine = a.startLine;
48569
- if (typeof a.endLine === "number" && Number.isInteger(a.endLine)) out2.endLine = a.endLine;
48570
- return out2;
48571
- }
48572
- function overlapOf(a, b) {
48573
- if (a.mode === "outline" || b.mode === "outline") return a.mode === b.mode ? "same" : "disjoint";
48574
- const aStart = a.startLine ?? 1;
48575
- const bStart = b.startLine ?? 1;
48576
- const aEnd = a.endLine ?? Number.POSITIVE_INFINITY;
48577
- const bEnd = b.endLine ?? Number.POSITIVE_INFINITY;
48578
- if (aStart === bStart && aEnd === bEnd) return "same";
48579
- return aStart <= bEnd && bStart <= aEnd ? "overlapping" : "disjoint";
48580
- }
48581
- function stateOf(output, writtenSince, dropNotes) {
48582
- if (writtenSince) return "after_write";
48583
- if (output === void 0) return "stubbed";
48584
- if (!isStubbed(output)) return "whole";
48585
- const note = output.note;
48586
- return typeof note === "string" && dropNotes.has(note) ? "dropped" : "stubbed";
48587
- }
48588
- function rangeKey(r) {
48589
- return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
48590
- }
48591
- function sizeOf2(output) {
48592
- try {
48593
- return JSON.stringify(output)?.length ?? 0;
48594
- } catch {
48595
- return Number.POSITIVE_INFINITY;
48596
- }
48597
- }
48598
- var ReadTracker = class {
48599
- reads = [];
48600
- writes = [];
48601
- seq = 0;
48602
- noteRead(entry) {
48603
- this.reads.push({ ...entry, seq: this.seq++ });
48604
- }
48605
- noteWrite(path, turn) {
48606
- this.writes.push({ path, turn, seq: this.seq++ });
48607
- }
48608
- lastWriteSeq(path) {
48609
- let last = -1;
48610
- for (const w of this.writes) if (w.path === path) last = w.seq;
48611
- return last;
48612
- }
48613
- /**
48614
- * The re-read report for `entry`, called BEFORE it is noted: null for a path not read before in this loop. `outputOf(id)` answers what the
48615
- * earlier answer is now; `duplicate` is whether this read was answered as a repeat.
48616
- */
48617
- reread(entry, duplicate, outputOf, dropNotes) {
48618
- let prev;
48619
- for (const r of this.reads) if (r.path === entry.path) prev = r;
48620
- if (!prev) return null;
48621
- const writtenSince = this.writes.some((w) => w.path === entry.path && w.seq > prev.seq);
48622
- const range = { startLine: entry.startLine, endLine: entry.endLine, mode: entry.mode };
48623
- const prevRange = { startLine: prev.startLine, endLine: prev.endLine, mode: prev.mode };
48624
- return {
48625
- turn: entry.turn,
48626
- path: entry.path,
48627
- ...entry.mode ? { mode: entry.mode } : {},
48628
- ...entry.startLine !== void 0 ? { startLine: entry.startLine } : {},
48629
- ...entry.endLine !== void 0 ? { endLine: entry.endLine } : {},
48630
- prevTurn: prev.turn,
48631
- ...prev.mode ? { prevMode: prev.mode } : {},
48632
- ...prev.startLine !== void 0 ? { prevStartLine: prev.startLine } : {},
48633
- ...prev.endLine !== void 0 ? { prevEndLine: prev.endLine } : {},
48634
- overlap: overlapOf(range, prevRange),
48635
- prevState: stateOf(outputOf(prev.id), writtenSince, dropNotes),
48636
- duplicate
48637
- };
48638
- }
48639
- /**
48640
- * The ids of the answers to keep whole: for each working file (written in this loop, or read in two different turns; the three most recently
48641
- * used), the newest answer per range made after the file's latest write, while it is still whole; at most 40,000 characters, newest first.
48642
- */
48643
- keep(outputOf) {
48644
- const lastUse = /* @__PURE__ */ new Map();
48645
- const turnsRead = /* @__PURE__ */ new Map();
48646
- for (const r of this.reads) {
48647
- lastUse.set(r.path, Math.max(lastUse.get(r.path) ?? -1, r.seq));
48648
- turnsRead.set(r.path, (turnsRead.get(r.path) ?? /* @__PURE__ */ new Set()).add(r.turn));
48649
- }
48650
- for (const w of this.writes) lastUse.set(w.path, Math.max(lastUse.get(w.path) ?? -1, w.seq));
48651
- const working = [...lastUse.keys()].filter((path) => this.writes.some((w) => w.path === path) || (turnsRead.get(path)?.size ?? 0) >= 2).sort((a, b) => lastUse.get(b) - lastUse.get(a)).slice(0, MAX_WORKING_PATHS);
48652
- const candidates = [];
48653
- for (const path of working) {
48654
- const after = this.lastWriteSeq(path);
48655
- const newestPerRange = /* @__PURE__ */ new Map();
48656
- for (const r of this.reads) if (r.path === path && r.seq > after) newestPerRange.set(rangeKey(r), r);
48657
- candidates.push(...newestPerRange.values());
48658
- }
48659
- candidates.sort((a, b) => b.seq - a.seq);
48660
- const kept = /* @__PURE__ */ new Set();
48661
- let chars = 0;
48662
- for (const c of candidates) {
48663
- const output = outputOf(c.id);
48664
- if (output === void 0 || isStubbed(output)) continue;
48665
- const size = sizeOf2(output);
48666
- if (chars + size > MAX_KEPT_CHARS) continue;
48667
- chars += size;
48668
- kept.add(c.id);
48669
- }
48670
- return kept;
48671
- }
48672
- };
48673
-
48674
- // src/redReview.ts
48675
- var RED_REVIEW_ENV = "QUIKPILOT_RED_REVIEW";
48676
- function redReviewOn(env2 = process.env) {
48677
- return env2[RED_REVIEW_ENV]?.trim().toLowerCase() === "on";
48678
- }
48679
- var MAX_REVIEW_CASES = MAX_REFUSED_SENTENCES - 1;
48680
- var REVIEW_MESSAGE = "Before your tests are frozen, check why each one fails on the code as it is. Each sentence but the last quotes the first line of a bug case's failure there. This check is made once.";
48681
- var REVIEW_CLOSING = "For each one, confirm the failure shows the bug its case describes and not a broken test (a missing mock or stub, an error in the test's own set-up, a crash the bug does not cause). Fix and run again any test that fails for another reason; otherwise answer DONE again.";
48682
- var MAX_QUOTE_CHARS = 200;
48683
- var MIN_QUOTE_CHARS = 20;
48684
- function failureFor(id, runs, covers) {
48685
- for (let i3 = runs.length - 1; i3 >= 0; i3 -= 1) {
48686
- const run3 = runs[i3];
48687
- const messages = run3.answer?.messages;
48688
- if (!messages) continue;
48689
- for (const name2 of run3.failing) {
48690
- if (!covers(name2, id)) continue;
48691
- const text3 = messages[name2];
48692
- if (typeof text3 === "string" && text3.trim().length > 0) return text3;
48693
- }
48694
- }
48695
- return null;
48696
- }
48697
- function reviewLine(id, text3) {
48698
- const prefix = `[${id}] fails on the code as it is with: `;
48699
- const room = Math.min(MAX_QUOTE_CHARS, MAX_REFUSED_SENTENCE_CHARS - prefix.length);
48700
- if (room < MIN_QUOTE_CHARS) return null;
48701
- const line2 = firstLine(text3, void 0, room);
48702
- return line2.length > 0 ? `${prefix}${line2}` : null;
48703
- }
48704
- function reviewAnswer(lines) {
48705
- return { rules: ["done_rule"], violations: [...lines.slice(0, MAX_REVIEW_CASES), REVIEW_CLOSING], message: REVIEW_MESSAGE };
48706
- }
48707
-
48708
- // src/dataPathCheck.ts
48709
- var import_node_child_process9 = require("node:child_process");
48710
- var import_node_fs17 = require("node:fs");
48711
- var import_node_path20 = require("node:path");
48712
-
48713
- // src/scopeCheck.ts
48714
- var import_node_fs16 = require("node:fs");
48715
- var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
48716
- var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
48717
- var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
48718
- var CALL_LINE_RE = /fetch\s*\(|\baxios\b|(?:\$|\bjQuery)\.(?:ajax|get|post|getJSON)\s*\(|\bXMLHttpRequest\b|\.open\(\s*["'`](?:GET|POST|PUT|PATCH|DELETE)["'`]|\bhttp\.(?:get|post|put|patch|delete|head|request|postform|newrequest|newrequestwithcontext)\s*\(|\b(?:requests|httpx)\.(?:get|post|put|patch|delete|head|request)\s*\(|\bHttpRequest\.newBuilder\b|\bcurl\b/i;
48719
- var NO_PATH = "(this file's route)";
48720
- function detectMentions(text3) {
48721
- const found = [];
48722
- for (const line2 of text3.split("\n")) {
48723
- const methodMatch = ROUTE_METHOD_RE.exec(line2);
48724
- const pathMatch = ROUTE_PATH_RE.exec(line2);
48725
- if (methodMatch && pathMatch && !CALL_LINE_RE.test(line2)) {
48726
- found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0].replace(/:+$/, "") });
48727
- }
48728
- const exportMatch = ROUTE_EXPORT_RE.exec(line2);
48729
- if (exportMatch) {
48730
- found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
48731
- }
48732
- }
48733
- return found;
48734
- }
48735
- function normalizePath(path) {
48736
- return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
48737
- }
48738
- function surfaceCovers(surface, mention) {
48739
- if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
48740
- if (mention.path === NO_PATH) return true;
48741
- const declaredPath = normalizePath(surface);
48742
- const mentionPath = normalizePath(mention.path);
48743
- return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
48744
- }
48745
- function addedLines(before, after) {
48746
- const beforeLines = new Set(before.split("\n"));
48747
- return after.split("\n").filter((line2) => !beforeLines.has(line2)).join("\n");
48748
- }
48749
- function checkApiScope(results, targets, apiChanges, existing) {
48750
- const targetsByPath = new Map(targets.map((t) => [t.path, t]));
48751
- const violations = [];
48752
- for (const { targetPath, newContent } of results) {
48753
- if (isTestFile(targetPath)) continue;
48754
- const target = targetsByPath.get(targetPath);
48755
- const isNewFile = target?.kind === "NEW_FILE";
48756
- let scanned;
48757
- if (isNewFile) {
48758
- scanned = newContent;
48759
- } else {
48760
- let currentContent;
48761
- try {
48762
- currentContent = (0, import_node_fs16.readFileSync)(targetPath, "utf8");
48763
- } catch {
48764
- currentContent = "";
48765
- }
48766
- scanned = addedLines(currentContent, newContent);
48767
- }
48768
- for (const mention of detectMentions(scanned)) {
48769
- if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
48770
- if (existing && mention.path !== NO_PATH && existing.has(mention)) continue;
48771
- violations.push({ file: targetPath, method: mention.method, path: mention.path });
48772
- }
48773
- }
48774
- }
48775
- return { blocked: violations.length > 0, violations };
48776
- }
48777
- function describeScopeViolations(check) {
48778
- return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
48779
- }
48780
-
48781
- // src/dataPathCheck.ts
48782
- var SOURCE_PATHSPECS = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
48783
- var SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
48784
- var UI_FILE = /\.(?:tsx|jsx|vue|svelte|html?)$/i;
48785
- var MAX_CANDIDATES = 80;
48786
- var MAX_LOADING_FILES = 60;
48787
- var MAX_SECOND_HOP = 12;
48788
- var SCAN_BUDGET_MS = 8e3;
48789
- var MAX_FILE_CHARS2 = 3e5;
48790
- var MAX_LISTING = 3e4;
48791
- var GIT_TIMEOUT_MS2 = 1e4;
48792
- var GIT_MAX_BUFFER3 = 2e7;
48793
- function routeSegment(seg) {
48794
- if (/^\(.*\)$/.test(seg) || seg.startsWith("@")) return null;
48795
- if (/^\[\[?\.\.\..*\]\]?$/.test(seg)) return "**";
48796
- if (/^\[.*\]$/.test(seg)) return "*";
48797
- return seg;
48798
- }
48799
- function routeAddressOf(file) {
48800
- const segs = file.replace(/\\/g, "/").split("/");
48801
- const last = segs[segs.length - 1] ?? "";
48802
- const appAt = segs.indexOf("app");
48803
- if (appAt >= 0 && /^route\.[cm]?[jt]sx?$/.test(last)) {
48804
- const parts2 = segs.slice(appAt + 1, -1).map(routeSegment).filter((s) => s !== null);
48805
- return `/${parts2.join("/")}`;
48806
- }
48807
- const pagesAt = segs.indexOf("pages");
48808
- if (pagesAt >= 0 && segs[pagesAt + 1] === "api" && SOURCE_FILE.test(last)) {
48809
- const name2 = last.replace(/\.[cm]?[jt]sx?$/, "");
48810
- const parts2 = [...segs.slice(pagesAt + 1, -1), ...name2 === "index" ? [] : [name2]].map(routeSegment).filter((s) => s !== null);
48811
- return `/${parts2.join("/")}`;
48812
- }
48813
- return null;
48814
- }
48815
- var LITERAL_RE = /[`'"]((?:\$\{[^}]*\})?\/[^`'"\s?#]*)/g;
48816
- var API_LITERAL = /^(?:\$\{[^}]*\})?\/api\//;
48817
- function literalsOf(line2) {
48818
- return [...line2.matchAll(LITERAL_RE)].map((m) => m[1]);
48819
- }
48820
- function toAddress(raw) {
48821
- const address = normalizePath(raw.replace(/\$\{[^}]*\}/g, "*")).replace(/\/+$/, "");
48822
- if (address.startsWith("//")) return null;
48823
- const segs = address.split("/").filter((s) => s !== "");
48824
- return segs.some((s) => s !== "*") ? address : null;
48825
- }
48826
- function callAddressesIn(text3) {
48827
- const lines = text3.split("\n");
48828
- const found = [];
48829
- const add2 = (raw) => {
48830
- const a = raw === void 0 ? null : toAddress(raw);
48831
- if (a !== null && !found.includes(a)) found.push(a);
48832
- };
48833
- for (let i3 = 0; i3 < lines.length; i3++) {
48834
- const lits = literalsOf(lines[i3]);
48835
- if (CALL_LINE_RE.test(lines[i3])) {
48836
- let first = lits[0];
48837
- for (let j = i3 + 1; first === void 0 && j <= i3 + 2 && j < lines.length; j++) first = literalsOf(lines[j])[0];
48838
- add2(first);
48839
- }
48840
- for (const lit of lits) if (API_LITERAL.test(lit)) add2(lit);
48841
- }
48842
- return found;
48843
- }
48844
- function addressMatches(route, call) {
48845
- const r = route.split("/").filter((s) => s !== "");
48846
- const c = call.split("/").filter((s) => s !== "");
48847
- const same = (a, b) => a === b || a === "*" || b === "*";
48848
- const wide = r.indexOf("**");
48849
- if (wide >= 0) return c.length >= wide && r.slice(0, wide).every((s, i3) => same(s, c[i3]));
48850
- if (c.length > r.length) return false;
48851
- const tail2 = r.slice(r.length - c.length);
48852
- return c.every((s, i3) => same(tail2[i3], s));
48853
- }
48854
- var git3 = (cwd, args2) => {
48855
- try {
48856
- return (0, import_node_child_process9.execFileSync)("git", args2, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48857
- } catch {
48858
- return "";
48859
- }
48860
- };
48861
- function lastSegment(spec) {
48862
- const segs = spec.split("/").filter((s) => s !== "" && s !== "." && s !== "..");
48863
- let name2 = segs.pop() ?? "";
48864
- if (/^index(?:\.[cm]?[jt]sx?)?$/.test(name2)) name2 = segs.pop() ?? "";
48865
- return name2.replace(/\.[cm]?[jt]sx?$/, "");
48866
- }
48867
- function baseOf(path) {
48868
- return lastSegment(path);
48869
- }
48870
- var GENERIC_BASES = /* @__PURE__ */ new Set(["index", "page", "layout", "route", "main", "app", "utils", "util", "types", "type", "constants", "config", "client", "server", "loading", "error", "default"]);
48871
- var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48872
- function graph(cwd, read, skip, expired) {
48873
- const listing = git3(cwd, ["ls-files"]).split("\n").filter((p) => SOURCE_FILE.test(p));
48874
- const byBase = /* @__PURE__ */ new Map();
48875
- if (listing.length <= MAX_LISTING) {
48876
- for (const p of listing) {
48877
- const base = baseOf(p);
48878
- if (base === "") continue;
48879
- const held = byBase.get(base);
48880
- if (held) held.push(p);
48881
- else byBase.set(base, [p]);
48882
- }
48883
- }
48884
- const text3 = (p) => {
48885
- const t = read(p);
48886
- return t !== null && t.length <= MAX_FILE_CHARS2 ? t : null;
48887
- };
48888
- const specifiers = (p) => {
48889
- const t = supportsImportScan(p) ? text3(p) : null;
48890
- return t === null ? [] : extractImportSpecifiers(t);
48891
- };
48892
- return {
48893
- importersOf(file) {
48894
- const base = baseOf(file);
48895
- if (base.length < 3 || GENERIC_BASES.has(base) || expired()) return [];
48896
- const pattern = `['"/]${escapeRegex(base)}(/index)?(\\.[cm]?[jt]sx?)?['"]`;
48897
- const hits = git3(cwd, ["grep", "-l", "-I", "-E", "-e", pattern, "--", ...SOURCE_PATHSPECS]).split("\n").filter((p) => p !== "" && p !== file && !skip(p));
48898
- return hits.slice(0, MAX_CANDIDATES).filter((p) => !expired() && specifiers(p).some((s) => lastSegment(s) === base));
48899
- },
48900
- importsOf(file) {
48901
- const out2 = [];
48902
- for (const s of specifiers(file)) {
48903
- if (!s.startsWith(".") && !s.startsWith("@/") && !s.startsWith("~/")) continue;
48904
- for (const p of (byBase.get(lastSegment(s)) ?? []).slice(0, 6)) if (p !== file && !skip(p) && !out2.includes(p)) out2.push(p);
49005
+ if (!fits) throw new LoopFailure("token_ceiling");
49006
+ }
48905
49007
  }
48906
- return out2;
49008
+ log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48907
49009
  }
48908
- };
49010
+ throw new LoopFailure("final_not_produced");
49011
+ } catch (err2) {
49012
+ if (err2 instanceof SafetyRefusalError) throw err2;
49013
+ const failure = err2 instanceof LoopFailure ? err2 : new LoopFailure("internal_error", void 0, err2);
49014
+ failure.summary ??= snapshot("fallback");
49015
+ throw failure;
49016
+ }
48909
49017
  }
48910
- function loadingFiles(cwd, screens, read, skip, expired) {
48911
- const g = graph(cwd, read, skip, expired);
48912
- const files = [];
48913
- const add2 = (p) => {
48914
- if (files.length < MAX_LOADING_FILES && !files.includes(p)) files.push(p);
48915
- };
48916
- const hop1 = unique2(screens.flatMap((s) => g.importersOf(s)));
48917
- for (const p of hop1) add2(p);
48918
- for (const p of hop1.slice(0, MAX_SECOND_HOP).flatMap((f) => g.importersOf(f))) add2(p);
48919
- for (const s of screens) add2(s);
48920
- for (const p of [...files].flatMap((f) => expired() ? [] : g.importsOf(f))) add2(p);
48921
- return files;
49018
+
49019
+ // src/workingFiles.ts
49020
+ var KEEP_WORKING_FILES_ENV = "QUIKPILOT_KEEP_WORKING_FILES";
49021
+ var MAX_WORKING_PATHS = 3;
49022
+ var MAX_KEPT_CHARS = 4e4;
49023
+ function keepWorkingFilesOn(env2 = process.env) {
49024
+ return env2[KEEP_WORKING_FILES_ENV]?.trim().toLowerCase() === "on";
48922
49025
  }
48923
- function readFromCheckout(root) {
48924
- return (path) => {
48925
- try {
48926
- const abs = (0, import_node_path20.join)(root, path);
48927
- const st = (0, import_node_fs17.lstatSync)(abs);
48928
- return st.isSymbolicLink() || !st.isFile() || st.size > MAX_FILE_CHARS2 ? null : (0, import_node_fs17.readFileSync)(abs, "utf8");
48929
- } catch {
48930
- return null;
48931
- }
48932
- };
49026
+ function rangeOf(args2) {
49027
+ if (typeof args2 !== "object" || args2 === null) return {};
49028
+ const a = args2;
49029
+ if (a.mode === "outline") return { mode: "outline" };
49030
+ const out2 = {};
49031
+ if (typeof a.startLine === "number" && Number.isInteger(a.startLine)) out2.startLine = a.startLine;
49032
+ if (typeof a.endLine === "number" && Number.isInteger(a.endLine)) out2.endLine = a.endLine;
49033
+ return out2;
48933
49034
  }
48934
- var unique2 = (xs) => [...new Set(xs)];
48935
- var slashed = (p) => p.replace(/\\/g, "/");
48936
- function plannedChanged(input, changed, kind) {
48937
- return unique2(input.parts.filter((p) => p.kind === kind).flatMap((p) => p.paths.map(slashed))).filter((p) => changed.has(p) && !input.isTest(p));
49035
+ function overlapOf(a, b) {
49036
+ if (a.mode === "outline" || b.mode === "outline") return a.mode === b.mode ? "same" : "disjoint";
49037
+ const aStart = a.startLine ?? 1;
49038
+ const bStart = b.startLine ?? 1;
49039
+ const aEnd = a.endLine ?? Number.POSITIVE_INFINITY;
49040
+ const bEnd = b.endLine ?? Number.POSITIVE_INFINITY;
49041
+ if (aStart === bStart && aEnd === bEnd) return "same";
49042
+ return aStart <= bEnd && bStart <= aEnd ? "overlapping" : "disjoint";
48938
49043
  }
48939
- var withAddress = (files) => files.flatMap((file) => {
48940
- const address = routeAddressOf(file);
48941
- return address === null ? [] : [{ file, address }];
48942
- });
48943
- function unplannedRoutes(input, changed) {
48944
- const planned = new Set(input.parts.flatMap((p) => p.paths.map(slashed)));
48945
- return withAddress([...changed].sort().filter((f) => !planned.has(f) && !input.isTest(f)));
49044
+ function stateOf(output, writtenSince, dropNotes) {
49045
+ if (writtenSince) return "after_write";
49046
+ if (output === void 0) return "stubbed";
49047
+ if (!isStubbed(output)) return "whole";
49048
+ const note = output.note;
49049
+ return typeof note === "string" && dropNotes.has(note) ? "dropped" : "stubbed";
48946
49050
  }
48947
- function callsLoadingScreens(input, screens) {
48948
- const started = Date.now();
48949
- const expired = () => Date.now() - started > SCAN_BUDGET_MS;
48950
- const denied = [...input.deniedPaths];
48951
- const skip = (p) => input.isTest(p) || matchesDeniedPath(p, denied) !== null || input.readable != null && !input.readable.has(p);
48952
- const calls = [];
48953
- const files = loadingFiles(input.cwd, screens, input.read, skip, expired);
48954
- for (const file of files) {
48955
- const text3 = input.read(file);
48956
- if (text3 === null || text3.length > MAX_FILE_CHARS2) continue;
48957
- for (const call of callAddressesIn(text3)) calls.push({ file, call });
48958
- }
48959
- input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
48960
- return calls;
49051
+ function rangeKey(r) {
49052
+ return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
48961
49053
  }
48962
- function dataPathGap(input) {
48963
- const changed = new Set(input.changed.map(slashed));
48964
- const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48965
- const routes = withAddress(plannedChanged(input, changed, "data"));
48966
- if (screens.length === 0 || routes.length === 0) return null;
48967
- const calls = callsLoadingScreens(input, screens);
48968
- if (calls.length === 0) return null;
48969
- const answering = [...routes, ...unplannedRoutes(input, changed)];
48970
- if (answering.some((r) => calls.some((c) => addressMatches(r.address, c.call)))) return null;
48971
- return { screen: screens[0], loader: calls[0].file, call: calls[0].call, routeFile: routes[0].file, route: routes[0].address };
49054
+ function sizeOf2(output) {
49055
+ try {
49056
+ return JSON.stringify(output)?.length ?? 0;
49057
+ } catch {
49058
+ return Number.POSITIVE_INFINITY;
49059
+ }
48972
49060
  }
48973
- function withoutMovedData(missing, input) {
48974
- const open = missing.filter((m) => m.why === "unchanged" && m.part.kind === "data" && m.part.database === void 0);
48975
- if (open.length === 0) return [...missing];
48976
- const changed = new Set(input.changed.map(slashed));
48977
- const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
48978
- if (screens.length === 0) return [...missing];
48979
- const moved = unplannedRoutes(input, changed);
48980
- if (moved.length === 0) return [...missing];
48981
- const calls = callsLoadingScreens(input, screens);
48982
- let excuses = moved.filter((r) => calls.some((c) => addressMatches(r.address, c.call))).length;
48983
- return missing.filter((m) => {
48984
- if (excuses > 0 && open.includes(m)) {
48985
- excuses -= 1;
48986
- return false;
49061
+ var ReadTracker = class {
49062
+ reads = [];
49063
+ writes = [];
49064
+ seq = 0;
49065
+ noteRead(entry) {
49066
+ this.reads.push({ ...entry, seq: this.seq++ });
49067
+ }
49068
+ noteWrite(path, turn) {
49069
+ this.writes.push({ path, turn, seq: this.seq++ });
49070
+ }
49071
+ lastWriteSeq(path) {
49072
+ let last = -1;
49073
+ for (const w of this.writes) if (w.path === path) last = w.seq;
49074
+ return last;
49075
+ }
49076
+ /**
49077
+ * The re-read report for `entry`, called BEFORE it is noted: null for a path not read before in this loop. `outputOf(id)` answers what the
49078
+ * earlier answer is now; `duplicate` is whether this read was answered as a repeat.
49079
+ */
49080
+ reread(entry, duplicate, outputOf, dropNotes) {
49081
+ let prev;
49082
+ for (const r of this.reads) if (r.path === entry.path) prev = r;
49083
+ if (!prev) return null;
49084
+ const writtenSince = this.writes.some((w) => w.path === entry.path && w.seq > prev.seq);
49085
+ const range = { startLine: entry.startLine, endLine: entry.endLine, mode: entry.mode };
49086
+ const prevRange = { startLine: prev.startLine, endLine: prev.endLine, mode: prev.mode };
49087
+ return {
49088
+ turn: entry.turn,
49089
+ path: entry.path,
49090
+ ...entry.mode ? { mode: entry.mode } : {},
49091
+ ...entry.startLine !== void 0 ? { startLine: entry.startLine } : {},
49092
+ ...entry.endLine !== void 0 ? { endLine: entry.endLine } : {},
49093
+ prevTurn: prev.turn,
49094
+ ...prev.mode ? { prevMode: prev.mode } : {},
49095
+ ...prev.startLine !== void 0 ? { prevStartLine: prev.startLine } : {},
49096
+ ...prev.endLine !== void 0 ? { prevEndLine: prev.endLine } : {},
49097
+ overlap: overlapOf(range, prevRange),
49098
+ prevState: stateOf(outputOf(prev.id), writtenSince, dropNotes),
49099
+ duplicate
49100
+ };
49101
+ }
49102
+ /**
49103
+ * The ids of the answers to keep whole: for each working file (written in this loop, or read in two different turns; the three most recently
49104
+ * used), the newest answer per range made after the file's latest write, while it is still whole; at most 40,000 characters, newest first.
49105
+ */
49106
+ keep(outputOf) {
49107
+ const lastUse = /* @__PURE__ */ new Map();
49108
+ const turnsRead = /* @__PURE__ */ new Map();
49109
+ for (const r of this.reads) {
49110
+ lastUse.set(r.path, Math.max(lastUse.get(r.path) ?? -1, r.seq));
49111
+ turnsRead.set(r.path, (turnsRead.get(r.path) ?? /* @__PURE__ */ new Set()).add(r.turn));
48987
49112
  }
48988
- return true;
48989
- });
48990
- }
48991
- var tail = (path, n) => path.split("/").slice(-n).join("/");
48992
- var endOf = (s, n) => s.length <= n ? s : `\u2026${s.slice(s.length - (n - 1))}`;
48993
- function fit(limit, build) {
48994
- const whole4 = (s) => s;
48995
- const spellings = [
48996
- [whole4, whole4],
48997
- [(p) => tail(p, 2), whole4],
48998
- [(p) => tail(p, 1), whole4]
48999
- ];
49000
- for (const [file, address] of spellings) {
49001
- const s = build(file, address);
49002
- if (s.length <= limit) return s;
49113
+ for (const w of this.writes) lastUse.set(w.path, Math.max(lastUse.get(w.path) ?? -1, w.seq));
49114
+ const working = [...lastUse.keys()].filter((path) => this.writes.some((w) => w.path === path) || (turnsRead.get(path)?.size ?? 0) >= 2).sort((a, b) => lastUse.get(b) - lastUse.get(a)).slice(0, MAX_WORKING_PATHS);
49115
+ const candidates = [];
49116
+ for (const path of working) {
49117
+ const after = this.lastWriteSeq(path);
49118
+ const newestPerRange = /* @__PURE__ */ new Map();
49119
+ for (const r of this.reads) if (r.path === path && r.seq > after) newestPerRange.set(rangeKey(r), r);
49120
+ candidates.push(...newestPerRange.values());
49121
+ }
49122
+ candidates.sort((a, b) => b.seq - a.seq);
49123
+ const kept = /* @__PURE__ */ new Set();
49124
+ let chars = 0;
49125
+ for (const c of candidates) {
49126
+ const output = outputOf(c.id);
49127
+ if (output === void 0 || isStubbed(output)) continue;
49128
+ const size = sizeOf2(output);
49129
+ if (chars + size > MAX_KEPT_CHARS) continue;
49130
+ chars += size;
49131
+ kept.add(c.id);
49132
+ }
49133
+ return kept;
49003
49134
  }
49004
- return build((p) => endOf(tail(p, 1), 22), (a) => endOf(a, 22)).slice(0, limit);
49135
+ };
49136
+
49137
+ // src/redReview.ts
49138
+ var RED_REVIEW_ENV = "QUIKPILOT_RED_REVIEW";
49139
+ function redReviewOn(env2 = process.env) {
49140
+ return env2[RED_REVIEW_ENV]?.trim().toLowerCase() === "on";
49005
49141
  }
49006
- function dataPathSentence(g) {
49007
- return fit(
49008
- MAX_REFUSED_SENTENCE_CHARS,
49009
- (f, a) => `${f(g.screen)} is shown from ${f(g.loader)}, which loads ${a(g.call)}; the data was added in ${f(g.routeFile)} (${a(g.route)}). Add it where ${a(g.call)} is answered too and keep that change, or say why ${a(g.route)} alone is right.`
49010
- );
49142
+ var MAX_REVIEW_CASES = MAX_REFUSED_SENTENCES - 1;
49143
+ var REVIEW_MESSAGE = "Before your tests are frozen, check why each one fails on the code as it is. Each sentence but the last quotes the first line of a bug case's failure there. This check is made once.";
49144
+ var REVIEW_CLOSING = "For each one, confirm the failure shows the bug its case describes and not a broken test (a missing mock or stub, an error in the test's own set-up, a crash the bug does not cause). Fix and run again any test that fails for another reason; otherwise answer DONE again.";
49145
+ var MAX_QUOTE_CHARS = 200;
49146
+ var MIN_QUOTE_CHARS = 20;
49147
+ function failureFor(id, runs, covers) {
49148
+ for (let i3 = runs.length - 1; i3 >= 0; i3 -= 1) {
49149
+ const run3 = runs[i3];
49150
+ const messages = run3.answer?.messages;
49151
+ if (!messages) continue;
49152
+ for (const name2 of run3.failing) {
49153
+ if (!covers(name2, id)) continue;
49154
+ const text3 = messages[name2];
49155
+ if (typeof text3 === "string" && text3.trim().length > 0) return text3;
49156
+ }
49157
+ }
49158
+ return null;
49011
49159
  }
49012
- var DATA_PATH_MESSAGE = "Your answer was sent back: the data this feature adds may not reach the screen that shows it. The sentence names the screen, where its data is loaded from, and the route that was changed instead. This check is made once.";
49013
- function dataPathAnswer(g) {
49014
- return { rules: ["done_rule"], violations: [dataPathSentence(g)], message: DATA_PATH_MESSAGE };
49160
+ function reviewLine(id, text3) {
49161
+ const prefix = `[${id}] fails on the code as it is with: `;
49162
+ const room = Math.min(MAX_QUOTE_CHARS, MAX_REFUSED_SENTENCE_CHARS - prefix.length);
49163
+ if (room < MIN_QUOTE_CHARS) return null;
49164
+ const line2 = firstLine(text3, void 0, room);
49165
+ return line2.length > 0 ? `${prefix}${line2}` : null;
49015
49166
  }
49016
- function dataPathWarning(g) {
49017
- return `QuikPilot could not confirm that the new data reaches the screen: ${g.screen} is shown from ${g.loader}, which loads its data from ${g.call}, but the data was added in ${g.routeFile} (${g.route}). Check that the screen shows it.`.slice(0, 1500);
49167
+ function reviewAnswer(lines) {
49168
+ return { rules: ["done_rule"], violations: [...lines.slice(0, MAX_REVIEW_CASES), REVIEW_CLOSING], message: REVIEW_MESSAGE };
49018
49169
  }
49019
49170
 
49020
49171
  // src/databaseChange.ts
@@ -49022,7 +49173,7 @@ var DATABASE_CHANGE_KEY = "databaseChange";
49022
49173
  var DATABASE_CHANGE_PATH = ".quikpilot/database-change.json";
49023
49174
  var STORED_PROPOSALS_KEY = "storedProposals";
49024
49175
  var NOTE_REASON = "database_change_note";
49025
- var MAX_NOTE_CHARS2 = 2e4;
49176
+ var MAX_NOTE_CHARS3 = 2e4;
49026
49177
  var MAX_WHY_CHARS = 300;
49027
49178
  var MAX_PATH_CHARS4 = 300;
49028
49179
  var MAX_SCHEMA_CHANGE_CHARS = 4e3;
@@ -49066,7 +49217,7 @@ function cleanPath(value) {
49066
49217
  }
49067
49218
  function readProposal(text3, partIds) {
49068
49219
  const fail = (sentence) => ({ ok: false, sentence });
49069
- if (text3.length > MAX_NOTE_CHARS2) return fail(PROPOSAL_SENTENCES.tooLong);
49220
+ if (text3.length > MAX_NOTE_CHARS3) return fail(PROPOSAL_SENTENCES.tooLong);
49070
49221
  let raw;
49071
49222
  try {
49072
49223
  raw = JSON.parse(text3);
@@ -54180,7 +54331,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
54180
54331
  var REPORT_COPY = "final-test-report.xml";
54181
54332
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
54182
54333
  var MAX_FILES = 200;
54183
- var RUNNER_VERSION = true ? "9.3.0-rc.82" : "dev";
54334
+ var RUNNER_VERSION = true ? "9.3.0-rc.84" : "dev";
54184
54335
  function safeDestination(base, repoPath) {
54185
54336
  if (!repoPath || (0, import_node_path28.isAbsolute)(repoPath)) return null;
54186
54337
  const destination = (0, import_node_path28.resolve)(base, repoPath);
@@ -55271,6 +55422,18 @@ async function run2(env2) {
55271
55422
  console.log(JSON.stringify({ event: "parts_check.stop", reason: partsStop.reason, ids: partsStop.ids }));
55272
55423
  throw new PartsStopError(partsStop);
55273
55424
  }
55425
+ if (designParts.length > 0) {
55426
+ const measure = dataPathAtTargeting({
55427
+ cwd: process.cwd(),
55428
+ parts: partsForCode(designParts, targeting.targets, proposals ? { proposals: true } : {}),
55429
+ changed: targeting.targets.map((t) => t.path),
55430
+ read: readFromCheckout(process.cwd()),
55431
+ isTest: testRule(discoveredTestsOf(codegenDiscovery)),
55432
+ deniedPaths: packet.guardrails.deniedPaths,
55433
+ readable: new Set(scope.readListing)
55434
+ });
55435
+ console.log(JSON.stringify({ event: "targeting.data_path", ...measure }));
55436
+ }
55274
55437
  const judgedByPool = buildJudgedByPool(
55275
55438
  packet.requiredTests,
55276
55439
  targeting.targets,