@quikit/quikpilot-runner 9.3.0-rc.83 → 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);
@@ -48280,218 +48284,627 @@ var TargetingHttpError = class extends Error {
48280
48284
  }
48281
48285
  };
48282
48286
 
48283
- // src/turnTimeout.ts
48284
- var FIRST_TURN_TIMEOUT_MS = 42e4;
48285
- var INVESTIGATE_FIRST_TURN_TIMEOUT_MS = 42e4;
48286
- function turnTimeoutFor(turn, perTurnMs, setByCaller, firstTurnMs = FIRST_TURN_TIMEOUT_MS) {
48287
- if (setByCaller || turn > 1) return perTurnMs;
48288
- 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("; ");
48289
48358
  }
48290
48359
 
48291
- // src/targetingLoop.ts
48292
- var LOOP_CONTRACT_VERSION = "targeting-loop-1";
48293
- var MAP_LOOP_CONTRACT_VERSION = "targeting-loop-2";
48294
- var TOOLS2_LOOP_CONTRACT_VERSION = "targeting-loop-3";
48295
- var TOOLS2_LOOP_TOOLS = ["list_files", "read_file", "grep", "find_definition"];
48296
- var NOTES_LOOP_CONTRACT_VERSION = "targeting-loop-4";
48297
- var LoopFailure = class extends Error {
48298
- reason;
48299
- runtimeCode;
48300
- /** What the loop had done when it failed, so reads made before the failure are not lost. */
48301
- summary;
48302
- constructor(reason, runtimeCode, cause) {
48303
- super(`pilot.targeting loop failed: ${reason}${runtimeCode ? ` (${runtimeCode})` : ""}`);
48304
- this.name = "LoopFailure";
48305
- this.reason = reason;
48306
- this.runtimeCode = runtimeCode;
48307
- 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("/")}`;
48308
48385
  }
48309
- };
48310
- var SafetyRefusalError = class extends RuntimeReplyError {
48311
- constructor(message, summary) {
48312
- super(message, summary);
48313
- 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("/")}`;
48314
48391
  }
48315
- };
48316
- var NO_FALLBACK_CODES = /* @__PURE__ */ new Set(["RUN_BUDGET_EXCEEDED", "RUN_CREDENTIAL_SCOPE"]);
48317
- var OUTPUT_TOO_LARGE_CODES = /* @__PURE__ */ new Set(["CODEGEN_OUTPUT_TOO_LARGE", "OUTPUT_TRUNCATED"]);
48318
- var TOOL_NAMES = /* @__PURE__ */ new Set(["list_files", "read_file", "grep", "find_definition"]);
48319
- var MAX_ID_CHARS = 64;
48320
- var MAX_CALLS_IN_A_REPLY = 50;
48321
- var MAX_ARGS_JSON_CHARS = 1e3;
48322
- function isPlainObject2(x) {
48323
- return typeof x === "object" && x !== null && !Array.isArray(x);
48392
+ return null;
48324
48393
  }
48325
- 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) => {
48326
48434
  try {
48327
- 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 });
48328
48436
  } catch {
48329
- return { _omitted: "unreadable" };
48437
+ return "";
48330
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?$/, "");
48331
48445
  }
48332
- function classifyTransport(err2) {
48333
- if (err2 instanceof TargetingHttpError) return new LoopFailure("http_error", void 0, err2);
48334
- const name2 = err2?.name;
48335
- if (name2 === "TimeoutError" || name2 === "AbortError") return new LoopFailure("turn_timeout", void 0, err2);
48336
- return new LoopFailure("transport", void 0, err2);
48446
+ function baseOf(path) {
48447
+ return lastSegment(path);
48337
48448
  }
48338
- async function runTargetingLoop(args2, deps) {
48339
- const limits = { ...DEFAULT_LIMITS, ...deps.limits };
48340
- const now = deps.now ?? Date.now;
48341
- const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
48342
- const turnTimeoutMs = deps.turnTimeoutMs ?? 18e4;
48343
- const deadlineMs = deps.deadlineMs ?? 9e5;
48344
- const env2 = {
48345
- listing: new Set(args2.listing),
48346
- visible: buildVisibleListing(args2.listing, readDenied(args2.deniedPaths)),
48347
- deniedPaths: writeDenied(args2.deniedPaths),
48348
- readDenied: readDenied(args2.deniedPaths),
48349
- fs: deps.fs ?? createNodeToolFs(),
48350
- limits,
48351
- scrub: makeCodeScrubber(deps.secrets ?? [], (c) => log({ event: "loop.scrubbed", ...nonZero(c) })),
48352
- ...args2.readRoots ? { readRoots: args2.readRoots } : {},
48353
- ...args2.tools2 ? { tools2: args2.tools2 } : {}
48354
- };
48355
- const notesOn = args2.tools2?.notes === true;
48356
- if (notesOn) {
48357
- const denied = readDenied(args2.deniedPaths);
48358
- const shownInMap = args2.baseContext.repoMap?.guidance;
48359
- env2.guidance = makeGuidanceFinder({
48360
- listing: env2.listing,
48361
- readText: (path) => readFileText(env2.fs, path),
48362
- isDenied: (path) => matchesDeniedPath(path, denied) !== null,
48363
- ...env2.scrub ? { scrub: env2.scrub } : {},
48364
- alreadyShown: (Array.isArray(shownInMap) ? shownInMap : []).map((g) => g.path).filter((p) => typeof p === "string")
48365
- });
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
+ }
48366
48462
  }
48367
- let notes = "";
48368
- let stubbed = 0;
48369
- const turnOfId = /* @__PURE__ */ new Map();
48370
- const callOfId = /* @__PURE__ */ new Map();
48371
- const ledger = newLedger();
48372
- const reads = [];
48373
- const transcript = [];
48374
- const toolResults = [];
48375
- const usedIds = /* @__PURE__ */ new Set();
48376
- const refusedTurns = [];
48377
- let refusedStreak = 0;
48378
- let unreadableStreak = 0;
48379
- let peakRequestTokens = 0;
48380
- const usage = new TurnUsage();
48381
- let turns = 0;
48382
- let noProgressStreak = 0;
48383
- let forced = null;
48384
- const started = now();
48385
- const buildContext = (turn, isFinal, finalReason) => ({
48386
- ...args2.baseContext,
48387
- contractVersion: args2.contractVersion ?? LOOP_CONTRACT_VERSION,
48388
- loop: {
48389
- turn,
48390
- maxTurns: limits.maxTurns,
48391
- final: isFinal,
48392
- ...isFinal ? { finalReason } : {},
48393
- // Says this runner can carry a REFUSED answer (contract 23.14). Without it the runtime fails the request, as it always did.
48394
- acceptsRefused: true,
48395
- remaining: {
48396
- toolCalls: Math.max(0, limits.maxToolCalls - ledger.toolCalls),
48397
- readChars: Math.max(0, limits.readCharsTotal - ledger.readChars)
48398
- },
48399
- transcript,
48400
- toolResults,
48401
- ...args2.tools2 ? { tools: [...TOOLS2_LOOP_TOOLS] } : {},
48402
- // Section 37: LAST in `loop`, so the end of the request repeats the cases, the folders the AI may change and its own notes.
48403
- ...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;
48404
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;
48405
48585
  });
48406
- const snapshot = (stopReason) => ({
48407
- turns,
48408
- toolCalls: ledger.toolCalls,
48409
- readChars: ledger.readChars,
48410
- refused: ledger.refused,
48411
- stopReason,
48412
- reads: [...reads],
48413
- ...refusedTurns.length > 0 ? { refusedTurns: refusedTurns.map((t) => ({ turn: t.turn, rules: [...t.rules] })) } : {},
48414
- ...peakRequestTokens > 0 ? { peakRequestTokens } : {},
48415
- ...args2.tools2 ? { contractVersion: args2.contractVersion ?? TOOLS2_LOOP_CONTRACT_VERSION } : {},
48416
- ...notesOn ? { notes: { chars: notes.length, stubbed, guidance: env2.guidance?.shown() ?? 0 } } : {},
48417
- ...usage.totals.calls > 0 ? { turnUsage: usage.rows.map((r) => ({ ...r, parts: { ...r.parts } })), usage: { ...usage.totals } } : {},
48418
- ...usage.rowsCut ? { turnUsageCut: true } : {}
48419
- });
48420
- 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 };
48421
48617
  try {
48422
- for (let turn = 1; turn <= limits.maxTurns; turn++) {
48423
- turns = turn;
48424
- if (now() - started > deadlineMs) throw new LoopFailure("loop_deadline");
48425
- const isFinal = forced !== null || turn === limits.maxTurns;
48426
- const finalReason = forced ?? "max_turns";
48427
- const contextData = buildContext(turn, isFinal, finalReason);
48428
- const requestChars = JSON.stringify(contextData).length;
48429
- const requestTokens = estimateRequestTokens(contextData);
48430
- peakRequestTokens = Math.max(peakRequestTokens, requestTokens);
48431
- if (requestTokens > limits.maxRequestTokens) {
48432
- log({ event: "targeting.loop_ceiling", turn, action: "not_sent", projectedTokens: requestTokens, ceiling: limits.maxRequestTokens });
48433
- throw new LoopFailure("token_ceiling");
48434
- }
48435
- const turnStarted = now();
48436
- let envelope;
48437
- try {
48438
- envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutFor(turn, turnTimeoutMs, deps.turnTimeoutMs !== void 0)));
48439
- } catch (err2) {
48440
- throw classifyTransport(err2);
48441
- }
48442
- usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
48443
- const code = envelope?.errorCode;
48444
- try {
48445
- checkHardFailure(envelope, "pilot.targeting");
48446
- } catch (err2) {
48447
- throw new LoopFailure(code === "CONTRACT_REJECTED" ? "contract_rejected" : "semantic_mismatch", String(code), err2);
48448
- }
48449
- if (envelope?.success === false) {
48450
- const runtimeCode = typeof code === "string" ? code : void 0;
48451
- if (runtimeCode && NO_FALLBACK_CODES.has(runtimeCode)) {
48452
- let inner;
48453
- try {
48454
- unwrapExecute(envelope, "pilot.targeting");
48455
- } catch (e) {
48456
- inner = e instanceof RuntimeReplyError ? e : void 0;
48457
- }
48458
- const fallbackText = `pilot.targeting failed: ${runtimeCode}`;
48459
- throw new SafetyRefusalError(inner?.message ?? fallbackText, inner?.summary ?? fallbackText);
48460
- }
48461
- if (runtimeCode === MALFORMED_REPLY_CODE && shouldRecover({ isFinal, consecutive: unreadableStreak })) {
48462
- unreadableStreak += 1;
48463
- refusedTurns.push({ turn, rules: [RECOVERY_RULE] });
48464
- transcript.push({ turn, toolCalls: [], refused: recoveryAnswer("malformed") });
48465
- log({ event: "targeting.loop_recovered", turn, reason: "schema_mismatch", runtimeCode, elapsedMs: now() - turnStarted });
48466
- continue;
48467
- }
48468
- throw new LoopFailure(runtimeCode && OUTPUT_TOO_LARGE_CODES.has(runtimeCode) ? "output_too_large" : "runtime_failed", runtimeCode);
48469
- }
48470
- 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;
48471
48662
  try {
48472
- body2 = unwrapExecute(envelope, "pilot.targeting");
48473
- } catch (err2) {
48474
- throw new LoopFailure("bad_reply", void 0, err2);
48475
- }
48476
- unreadableStreak = 0;
48477
- if (body2.outcome === REFUSED_OUTCOME) {
48478
- const answer = readRefusedAnswer(body2);
48479
- if (!answer) throw new LoopFailure("bad_reply");
48480
- refusedStreak += 1;
48481
- refusedTurns.push({ turn, rules: answer.rules });
48482
- log({ event: "targeting.loop_turn", turn, outcome: "refused", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [], rules: answer.rules.map(recordRuleWord), streak: refusedStreak });
48483
- if (isFinal) throw new LoopFailure("final_not_produced");
48484
- transcript.push({ turn, toolCalls: [], refused: answer });
48485
- if (refusedStreak >= REFUSED_STREAK_LIMIT) forced = "refused_repeatedly";
48486
- continue;
48487
- }
48488
- if (body2.outcome === "TARGETED" || body2.outcome === "NO_TARGET") {
48489
- log({ event: "targeting.loop_turn", turn, outcome: "final", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: [] });
48490
- const stopReason = isFinal ? `forced_${finalReason}` : "model_final";
48491
- log({ event: "targeting.loop_done", turns, toolCalls: ledger.toolCalls, readChars: ledger.readChars, refused: ledger.refused, stopReason });
48492
- return { body: body2, summary: snapshot(stopReason) };
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;
48493
48678
  }
48494
- if (body2.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
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 });
48905
+ return { body: body2, summary: snapshot(stopReason) };
48906
+ }
48907
+ if (body2.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
48495
48908
  if (isFinal) throw new LoopFailure("final_not_produced");
48496
48909
  const rawCalls = body2.toolCalls;
48497
48910
  if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
@@ -48589,482 +49002,170 @@ async function runTargetingLoop(args2, deps) {
48589
49002
  projectedTokens: projected,
48590
49003
  ceiling: limits.maxRequestTokens
48591
49004
  });
48592
- if (!fits) throw new LoopFailure("token_ceiling");
48593
- }
48594
- }
48595
- log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48596
- }
48597
- throw new LoopFailure("final_not_produced");
48598
- } catch (err2) {
48599
- if (err2 instanceof SafetyRefusalError) throw err2;
48600
- const failure = err2 instanceof LoopFailure ? err2 : new LoopFailure("internal_error", void 0, err2);
48601
- failure.summary ??= snapshot("fallback");
48602
- throw failure;
48603
- }
48604
- }
48605
-
48606
- // src/workingFiles.ts
48607
- var KEEP_WORKING_FILES_ENV = "QUIKPILOT_KEEP_WORKING_FILES";
48608
- var MAX_WORKING_PATHS = 3;
48609
- var MAX_KEPT_CHARS = 4e4;
48610
- function keepWorkingFilesOn(env2 = process.env) {
48611
- return env2[KEEP_WORKING_FILES_ENV]?.trim().toLowerCase() === "on";
48612
- }
48613
- function rangeOf(args2) {
48614
- if (typeof args2 !== "object" || args2 === null) return {};
48615
- const a = args2;
48616
- if (a.mode === "outline") return { mode: "outline" };
48617
- const out2 = {};
48618
- if (typeof a.startLine === "number" && Number.isInteger(a.startLine)) out2.startLine = a.startLine;
48619
- if (typeof a.endLine === "number" && Number.isInteger(a.endLine)) out2.endLine = a.endLine;
48620
- return out2;
48621
- }
48622
- function overlapOf(a, b) {
48623
- if (a.mode === "outline" || b.mode === "outline") return a.mode === b.mode ? "same" : "disjoint";
48624
- const aStart = a.startLine ?? 1;
48625
- const bStart = b.startLine ?? 1;
48626
- const aEnd = a.endLine ?? Number.POSITIVE_INFINITY;
48627
- const bEnd = b.endLine ?? Number.POSITIVE_INFINITY;
48628
- if (aStart === bStart && aEnd === bEnd) return "same";
48629
- return aStart <= bEnd && bStart <= aEnd ? "overlapping" : "disjoint";
48630
- }
48631
- function stateOf(output, writtenSince, dropNotes) {
48632
- if (writtenSince) return "after_write";
48633
- if (output === void 0) return "stubbed";
48634
- if (!isStubbed(output)) return "whole";
48635
- const note = output.note;
48636
- return typeof note === "string" && dropNotes.has(note) ? "dropped" : "stubbed";
48637
- }
48638
- function rangeKey(r) {
48639
- return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
48640
- }
48641
- function sizeOf2(output) {
48642
- try {
48643
- return JSON.stringify(output)?.length ?? 0;
48644
- } catch {
48645
- return Number.POSITIVE_INFINITY;
48646
- }
48647
- }
48648
- var ReadTracker = class {
48649
- reads = [];
48650
- writes = [];
48651
- seq = 0;
48652
- noteRead(entry) {
48653
- this.reads.push({ ...entry, seq: this.seq++ });
48654
- }
48655
- noteWrite(path, turn) {
48656
- this.writes.push({ path, turn, seq: this.seq++ });
48657
- }
48658
- lastWriteSeq(path) {
48659
- let last = -1;
48660
- for (const w of this.writes) if (w.path === path) last = w.seq;
48661
- return last;
48662
- }
48663
- /**
48664
- * 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
48665
- * earlier answer is now; `duplicate` is whether this read was answered as a repeat.
48666
- */
48667
- reread(entry, duplicate, outputOf, dropNotes) {
48668
- let prev;
48669
- for (const r of this.reads) if (r.path === entry.path) prev = r;
48670
- if (!prev) return null;
48671
- const writtenSince = this.writes.some((w) => w.path === entry.path && w.seq > prev.seq);
48672
- const range = { startLine: entry.startLine, endLine: entry.endLine, mode: entry.mode };
48673
- const prevRange = { startLine: prev.startLine, endLine: prev.endLine, mode: prev.mode };
48674
- return {
48675
- turn: entry.turn,
48676
- path: entry.path,
48677
- ...entry.mode ? { mode: entry.mode } : {},
48678
- ...entry.startLine !== void 0 ? { startLine: entry.startLine } : {},
48679
- ...entry.endLine !== void 0 ? { endLine: entry.endLine } : {},
48680
- prevTurn: prev.turn,
48681
- ...prev.mode ? { prevMode: prev.mode } : {},
48682
- ...prev.startLine !== void 0 ? { prevStartLine: prev.startLine } : {},
48683
- ...prev.endLine !== void 0 ? { prevEndLine: prev.endLine } : {},
48684
- overlap: overlapOf(range, prevRange),
48685
- prevState: stateOf(outputOf(prev.id), writtenSince, dropNotes),
48686
- duplicate
48687
- };
48688
- }
48689
- /**
48690
- * 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
48691
- * 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.
48692
- */
48693
- keep(outputOf) {
48694
- const lastUse = /* @__PURE__ */ new Map();
48695
- const turnsRead = /* @__PURE__ */ new Map();
48696
- for (const r of this.reads) {
48697
- lastUse.set(r.path, Math.max(lastUse.get(r.path) ?? -1, r.seq));
48698
- turnsRead.set(r.path, (turnsRead.get(r.path) ?? /* @__PURE__ */ new Set()).add(r.turn));
48699
- }
48700
- for (const w of this.writes) lastUse.set(w.path, Math.max(lastUse.get(w.path) ?? -1, w.seq));
48701
- 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);
48702
- const candidates = [];
48703
- for (const path of working) {
48704
- const after = this.lastWriteSeq(path);
48705
- const newestPerRange = /* @__PURE__ */ new Map();
48706
- for (const r of this.reads) if (r.path === path && r.seq > after) newestPerRange.set(rangeKey(r), r);
48707
- candidates.push(...newestPerRange.values());
48708
- }
48709
- candidates.sort((a, b) => b.seq - a.seq);
48710
- const kept = /* @__PURE__ */ new Set();
48711
- let chars = 0;
48712
- for (const c of candidates) {
48713
- const output = outputOf(c.id);
48714
- if (output === void 0 || isStubbed(output)) continue;
48715
- const size = sizeOf2(output);
48716
- if (chars + size > MAX_KEPT_CHARS) continue;
48717
- chars += size;
48718
- kept.add(c.id);
48719
- }
48720
- return kept;
48721
- }
48722
- };
48723
-
48724
- // src/redReview.ts
48725
- var RED_REVIEW_ENV = "QUIKPILOT_RED_REVIEW";
48726
- function redReviewOn(env2 = process.env) {
48727
- return env2[RED_REVIEW_ENV]?.trim().toLowerCase() === "on";
48728
- }
48729
- var MAX_REVIEW_CASES = MAX_REFUSED_SENTENCES - 1;
48730
- 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.";
48731
- 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.";
48732
- var MAX_QUOTE_CHARS = 200;
48733
- var MIN_QUOTE_CHARS = 20;
48734
- function failureFor(id, runs, covers) {
48735
- for (let i3 = runs.length - 1; i3 >= 0; i3 -= 1) {
48736
- const run3 = runs[i3];
48737
- const messages = run3.answer?.messages;
48738
- if (!messages) continue;
48739
- for (const name2 of run3.failing) {
48740
- if (!covers(name2, id)) continue;
48741
- const text3 = messages[name2];
48742
- if (typeof text3 === "string" && text3.trim().length > 0) return text3;
48743
- }
48744
- }
48745
- return null;
48746
- }
48747
- function reviewLine(id, text3) {
48748
- const prefix = `[${id}] fails on the code as it is with: `;
48749
- const room = Math.min(MAX_QUOTE_CHARS, MAX_REFUSED_SENTENCE_CHARS - prefix.length);
48750
- if (room < MIN_QUOTE_CHARS) return null;
48751
- const line2 = firstLine(text3, void 0, room);
48752
- return line2.length > 0 ? `${prefix}${line2}` : null;
48753
- }
48754
- function reviewAnswer(lines) {
48755
- return { rules: ["done_rule"], violations: [...lines.slice(0, MAX_REVIEW_CASES), REVIEW_CLOSING], message: REVIEW_MESSAGE };
48756
- }
48757
-
48758
- // src/dataPathCheck.ts
48759
- var import_node_child_process9 = require("node:child_process");
48760
- var import_node_fs17 = require("node:fs");
48761
- var import_node_path20 = require("node:path");
48762
-
48763
- // src/scopeCheck.ts
48764
- var import_node_fs16 = require("node:fs");
48765
- var ROUTE_METHOD_RE = /\b(GET|POST|PUT|PATCH|DELETE)\b/i;
48766
- var ROUTE_PATH_RE = /\/[A-Za-z0-9_\-{}[\]]+(?:\/[A-Za-z0-9_\-:{}[\]]+)+/;
48767
- var ROUTE_EXPORT_RE = /\bexport\s+(?:async\s+)?function\s+(GET|POST|PUT|PATCH|DELETE)\s*\(/;
48768
- 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;
48769
- var NO_PATH = "(this file's route)";
48770
- function detectMentions(text3) {
48771
- const found = [];
48772
- for (const line2 of text3.split("\n")) {
48773
- const methodMatch = ROUTE_METHOD_RE.exec(line2);
48774
- const pathMatch = ROUTE_PATH_RE.exec(line2);
48775
- if (methodMatch && pathMatch && !CALL_LINE_RE.test(line2)) {
48776
- found.push({ method: methodMatch[1].toUpperCase(), path: pathMatch[0].replace(/:+$/, "") });
48777
- }
48778
- const exportMatch = ROUTE_EXPORT_RE.exec(line2);
48779
- if (exportMatch) {
48780
- found.push({ method: exportMatch[1].toUpperCase(), path: NO_PATH });
48781
- }
48782
- }
48783
- return found;
48784
- }
48785
- function normalizePath(path) {
48786
- return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
48787
- }
48788
- function surfaceCovers(surface, mention) {
48789
- if (!new RegExp(`\\b${mention.method}\\b`, "i").test(surface)) return false;
48790
- if (mention.path === NO_PATH) return true;
48791
- const declaredPath = normalizePath(surface);
48792
- const mentionPath = normalizePath(mention.path);
48793
- return declaredPath.includes(mentionPath) || mentionPath.includes(declaredPath);
48794
- }
48795
- function addedLines(before, after) {
48796
- const beforeLines = new Set(before.split("\n"));
48797
- return after.split("\n").filter((line2) => !beforeLines.has(line2)).join("\n");
48798
- }
48799
- function checkApiScope(results, targets, apiChanges, existing) {
48800
- const targetsByPath = new Map(targets.map((t) => [t.path, t]));
48801
- const violations = [];
48802
- for (const { targetPath, newContent } of results) {
48803
- if (isTestFile(targetPath)) continue;
48804
- const target = targetsByPath.get(targetPath);
48805
- const isNewFile = target?.kind === "NEW_FILE";
48806
- let scanned;
48807
- if (isNewFile) {
48808
- scanned = newContent;
48809
- } else {
48810
- let currentContent;
48811
- try {
48812
- currentContent = (0, import_node_fs16.readFileSync)(targetPath, "utf8");
48813
- } catch {
48814
- currentContent = "";
48815
- }
48816
- scanned = addedLines(currentContent, newContent);
48817
- }
48818
- for (const mention of detectMentions(scanned)) {
48819
- if (!apiChanges.some((c) => surfaceCovers(c.surface, mention))) {
48820
- if (existing && mention.path !== NO_PATH && existing.has(mention)) continue;
48821
- violations.push({ file: targetPath, method: mention.method, path: mention.path });
48822
- }
48823
- }
48824
- }
48825
- return { blocked: violations.length > 0, violations };
48826
- }
48827
- function describeScopeViolations(check) {
48828
- return check.violations.map((v) => `${v.file} adds ${v.method} ${v.path}, not declared in the design's API changes`).join("; ");
48829
- }
48830
-
48831
- // src/dataPathCheck.ts
48832
- var SOURCE_PATHSPECS = ["*.ts", "*.tsx", "*.js", "*.jsx", "*.mjs", "*.cjs", "*.mts", "*.cts"];
48833
- var SOURCE_FILE = /\.(?:[cm]?[jt]sx?)$/i;
48834
- var UI_FILE = /\.(?:tsx|jsx|vue|svelte|html?)$/i;
48835
- var MAX_CANDIDATES = 80;
48836
- var MAX_LOADING_FILES = 60;
48837
- var MAX_SECOND_HOP = 12;
48838
- var SCAN_BUDGET_MS = 8e3;
48839
- var MAX_FILE_CHARS2 = 3e5;
48840
- var MAX_LISTING = 3e4;
48841
- var GIT_TIMEOUT_MS2 = 1e4;
48842
- var GIT_MAX_BUFFER3 = 2e7;
48843
- function routeSegment(seg) {
48844
- if (/^\(.*\)$/.test(seg) || seg.startsWith("@")) return null;
48845
- if (/^\[\[?\.\.\..*\]\]?$/.test(seg)) return "**";
48846
- if (/^\[.*\]$/.test(seg)) return "*";
48847
- return seg;
48848
- }
48849
- function routeAddressOf(file) {
48850
- const segs = file.replace(/\\/g, "/").split("/");
48851
- const last = segs[segs.length - 1] ?? "";
48852
- const appAt = segs.indexOf("app");
48853
- if (appAt >= 0 && /^route\.[cm]?[jt]sx?$/.test(last)) {
48854
- const parts2 = segs.slice(appAt + 1, -1).map(routeSegment).filter((s) => s !== null);
48855
- return `/${parts2.join("/")}`;
48856
- }
48857
- const pagesAt = segs.indexOf("pages");
48858
- if (pagesAt >= 0 && segs[pagesAt + 1] === "api" && SOURCE_FILE.test(last)) {
48859
- const name2 = last.replace(/\.[cm]?[jt]sx?$/, "");
48860
- const parts2 = [...segs.slice(pagesAt + 1, -1), ...name2 === "index" ? [] : [name2]].map(routeSegment).filter((s) => s !== null);
48861
- return `/${parts2.join("/")}`;
48862
- }
48863
- return null;
48864
- }
48865
- var LITERAL_RE = /[`'"]((?:\$\{[^}]*\})?\/[^`'"\s?#]*)/g;
48866
- var API_LITERAL = /^(?:\$\{[^}]*\})?\/api\//;
48867
- function literalsOf(line2) {
48868
- return [...line2.matchAll(LITERAL_RE)].map((m) => m[1]);
48869
- }
48870
- function toAddress(raw) {
48871
- const address = normalizePath(raw.replace(/\$\{[^}]*\}/g, "*")).replace(/\/+$/, "");
48872
- if (address.startsWith("//")) return null;
48873
- const segs = address.split("/").filter((s) => s !== "");
48874
- return segs.some((s) => s !== "*") ? address : null;
48875
- }
48876
- function callAddressesIn(text3) {
48877
- const lines = text3.split("\n");
48878
- const found = [];
48879
- const add2 = (raw) => {
48880
- const a = raw === void 0 ? null : toAddress(raw);
48881
- if (a !== null && !found.includes(a)) found.push(a);
48882
- };
48883
- for (let i3 = 0; i3 < lines.length; i3++) {
48884
- const lits = literalsOf(lines[i3]);
48885
- if (CALL_LINE_RE.test(lines[i3])) {
48886
- let first = lits[0];
48887
- for (let j = i3 + 1; first === void 0 && j <= i3 + 2 && j < lines.length; j++) first = literalsOf(lines[j])[0];
48888
- add2(first);
48889
- }
48890
- for (const lit of lits) if (API_LITERAL.test(lit)) add2(lit);
48891
- }
48892
- return found;
48893
- }
48894
- function addressMatches(route, call) {
48895
- const r = route.split("/").filter((s) => s !== "");
48896
- const c = call.split("/").filter((s) => s !== "");
48897
- const same = (a, b) => a === b || a === "*" || b === "*";
48898
- const wide = r.indexOf("**");
48899
- if (wide >= 0) return c.length >= wide && r.slice(0, wide).every((s, i3) => same(s, c[i3]));
48900
- if (c.length > r.length) return false;
48901
- const tail2 = r.slice(r.length - c.length);
48902
- return c.every((s, i3) => same(tail2[i3], s));
48903
- }
48904
- var git3 = (cwd, args2) => {
48905
- try {
48906
- return (0, import_node_child_process9.execFileSync)("git", args2, { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], timeout: GIT_TIMEOUT_MS2, maxBuffer: GIT_MAX_BUFFER3 });
48907
- } catch {
48908
- return "";
48909
- }
48910
- };
48911
- function lastSegment(spec) {
48912
- const segs = spec.split("/").filter((s) => s !== "" && s !== "." && s !== "..");
48913
- let name2 = segs.pop() ?? "";
48914
- if (/^index(?:\.[cm]?[jt]sx?)?$/.test(name2)) name2 = segs.pop() ?? "";
48915
- return name2.replace(/\.[cm]?[jt]sx?$/, "");
48916
- }
48917
- function baseOf(path) {
48918
- return lastSegment(path);
48919
- }
48920
- var GENERIC_BASES = /* @__PURE__ */ new Set(["index", "page", "layout", "route", "main", "app", "utils", "util", "types", "type", "constants", "config", "client", "server", "loading", "error", "default"]);
48921
- var escapeRegex = (s) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
48922
- function graph(cwd, read, skip, expired) {
48923
- const listing = git3(cwd, ["ls-files"]).split("\n").filter((p) => SOURCE_FILE.test(p));
48924
- const byBase = /* @__PURE__ */ new Map();
48925
- if (listing.length <= MAX_LISTING) {
48926
- for (const p of listing) {
48927
- const base = baseOf(p);
48928
- if (base === "") continue;
48929
- const held = byBase.get(base);
48930
- if (held) held.push(p);
48931
- else byBase.set(base, [p]);
48932
- }
48933
- }
48934
- const text3 = (p) => {
48935
- const t = read(p);
48936
- return t !== null && t.length <= MAX_FILE_CHARS2 ? t : null;
48937
- };
48938
- const specifiers = (p) => {
48939
- const t = supportsImportScan(p) ? text3(p) : null;
48940
- return t === null ? [] : extractImportSpecifiers(t);
48941
- };
48942
- return {
48943
- importersOf(file) {
48944
- const base = baseOf(file);
48945
- if (base.length < 3 || GENERIC_BASES.has(base) || expired()) return [];
48946
- const pattern = `['"/]${escapeRegex(base)}(/index)?(\\.[cm]?[jt]sx?)?['"]`;
48947
- const hits = git3(cwd, ["grep", "-l", "-I", "-E", "-e", pattern, "--", ...SOURCE_PATHSPECS]).split("\n").filter((p) => p !== "" && p !== file && !skip(p));
48948
- return hits.slice(0, MAX_CANDIDATES).filter((p) => !expired() && specifiers(p).some((s) => lastSegment(s) === base));
48949
- },
48950
- importsOf(file) {
48951
- const out2 = [];
48952
- for (const s of specifiers(file)) {
48953
- if (!s.startsWith(".") && !s.startsWith("@/") && !s.startsWith("~/")) continue;
48954
- 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
+ }
48955
49007
  }
48956
- return out2;
49008
+ log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48957
49009
  }
48958
- };
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
+ }
48959
49017
  }
48960
- function loadingFiles(cwd, screens, read, skip, expired) {
48961
- const g = graph(cwd, read, skip, expired);
48962
- const files = [];
48963
- const add2 = (p) => {
48964
- if (files.length < MAX_LOADING_FILES && !files.includes(p)) files.push(p);
48965
- };
48966
- const hop1 = unique2(screens.flatMap((s) => g.importersOf(s)));
48967
- for (const p of hop1) add2(p);
48968
- for (const p of hop1.slice(0, MAX_SECOND_HOP).flatMap((f) => g.importersOf(f))) add2(p);
48969
- for (const s of screens) add2(s);
48970
- for (const p of [...files].flatMap((f) => expired() ? [] : g.importsOf(f))) add2(p);
48971
- 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";
48972
49025
  }
48973
- function readFromCheckout(root) {
48974
- return (path) => {
48975
- try {
48976
- const abs = (0, import_node_path20.join)(root, path);
48977
- const st = (0, import_node_fs17.lstatSync)(abs);
48978
- return st.isSymbolicLink() || !st.isFile() || st.size > MAX_FILE_CHARS2 ? null : (0, import_node_fs17.readFileSync)(abs, "utf8");
48979
- } catch {
48980
- return null;
48981
- }
48982
- };
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;
48983
49034
  }
48984
- var unique2 = (xs) => [...new Set(xs)];
48985
- var slashed = (p) => p.replace(/\\/g, "/");
48986
- function plannedChanged(input, changed, kind) {
48987
- 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";
48988
49043
  }
48989
- var withAddress = (files) => files.flatMap((file) => {
48990
- const address = routeAddressOf(file);
48991
- return address === null ? [] : [{ file, address }];
48992
- });
48993
- function unplannedRoutes(input, changed) {
48994
- const planned = new Set(input.parts.flatMap((p) => p.paths.map(slashed)));
48995
- 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";
48996
49050
  }
48997
- function callsLoadingScreens(input, screens) {
48998
- const started = Date.now();
48999
- const expired = () => Date.now() - started > SCAN_BUDGET_MS;
49000
- const denied = [...input.deniedPaths];
49001
- const skip = (p) => input.isTest(p) || matchesDeniedPath(p, denied) !== null || input.readable != null && !input.readable.has(p);
49002
- const calls = [];
49003
- const files = loadingFiles(input.cwd, screens, input.read, skip, expired);
49004
- for (const file of files) {
49005
- const text3 = input.read(file);
49006
- if (text3 === null || text3.length > MAX_FILE_CHARS2) continue;
49007
- for (const call of callAddressesIn(text3)) calls.push({ file, call });
49008
- }
49009
- input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
49010
- return calls;
49051
+ function rangeKey(r) {
49052
+ return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
49011
49053
  }
49012
- function dataPathGap(input) {
49013
- const changed = new Set(input.changed.map(slashed));
49014
- const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
49015
- const routes = withAddress(plannedChanged(input, changed, "data"));
49016
- if (screens.length === 0 || routes.length === 0) return null;
49017
- const calls = callsLoadingScreens(input, screens);
49018
- if (calls.length === 0) return null;
49019
- const answering = [...routes, ...unplannedRoutes(input, changed)];
49020
- if (answering.some((r) => calls.some((c) => addressMatches(r.address, c.call)))) return null;
49021
- 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
+ }
49022
49060
  }
49023
- function withoutMovedData(missing, input) {
49024
- const open = missing.filter((m) => m.why === "unchanged" && m.part.kind === "data" && m.part.database === void 0);
49025
- if (open.length === 0) return [...missing];
49026
- const changed = new Set(input.changed.map(slashed));
49027
- const screens = plannedChanged(input, changed, "screen").filter((p) => UI_FILE.test(p));
49028
- if (screens.length === 0) return [...missing];
49029
- const moved = unplannedRoutes(input, changed);
49030
- if (moved.length === 0) return [...missing];
49031
- const calls = callsLoadingScreens(input, screens);
49032
- let excuses = moved.filter((r) => calls.some((c) => addressMatches(r.address, c.call))).length;
49033
- return missing.filter((m) => {
49034
- if (excuses > 0 && open.includes(m)) {
49035
- excuses -= 1;
49036
- 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));
49037
49112
  }
49038
- return true;
49039
- });
49040
- }
49041
- var tail = (path, n) => path.split("/").slice(-n).join("/");
49042
- var endOf = (s, n) => s.length <= n ? s : `\u2026${s.slice(s.length - (n - 1))}`;
49043
- function fit(limit, build) {
49044
- const whole4 = (s) => s;
49045
- const spellings = [
49046
- [whole4, whole4],
49047
- [(p) => tail(p, 2), whole4],
49048
- [(p) => tail(p, 1), whole4]
49049
- ];
49050
- for (const [file, address] of spellings) {
49051
- const s = build(file, address);
49052
- 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;
49053
49134
  }
49054
- 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";
49055
49141
  }
49056
- function dataPathSentence(g) {
49057
- return fit(
49058
- MAX_REFUSED_SENTENCE_CHARS,
49059
- (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.`
49060
- );
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;
49061
49159
  }
49062
- 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.";
49063
- function dataPathAnswer(g) {
49064
- 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;
49065
49166
  }
49066
- function dataPathWarning(g) {
49067
- 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 };
49068
49169
  }
49069
49170
 
49070
49171
  // src/databaseChange.ts
@@ -49072,7 +49173,7 @@ var DATABASE_CHANGE_KEY = "databaseChange";
49072
49173
  var DATABASE_CHANGE_PATH = ".quikpilot/database-change.json";
49073
49174
  var STORED_PROPOSALS_KEY = "storedProposals";
49074
49175
  var NOTE_REASON = "database_change_note";
49075
- var MAX_NOTE_CHARS2 = 2e4;
49176
+ var MAX_NOTE_CHARS3 = 2e4;
49076
49177
  var MAX_WHY_CHARS = 300;
49077
49178
  var MAX_PATH_CHARS4 = 300;
49078
49179
  var MAX_SCHEMA_CHANGE_CHARS = 4e3;
@@ -49116,7 +49217,7 @@ function cleanPath(value) {
49116
49217
  }
49117
49218
  function readProposal(text3, partIds) {
49118
49219
  const fail = (sentence) => ({ ok: false, sentence });
49119
- if (text3.length > MAX_NOTE_CHARS2) return fail(PROPOSAL_SENTENCES.tooLong);
49220
+ if (text3.length > MAX_NOTE_CHARS3) return fail(PROPOSAL_SENTENCES.tooLong);
49120
49221
  let raw;
49121
49222
  try {
49122
49223
  raw = JSON.parse(text3);
@@ -54230,7 +54331,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
54230
54331
  var REPORT_COPY = "final-test-report.xml";
54231
54332
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
54232
54333
  var MAX_FILES = 200;
54233
- var RUNNER_VERSION = true ? "9.3.0-rc.83" : "dev";
54334
+ var RUNNER_VERSION = true ? "9.3.0-rc.84" : "dev";
54234
54335
  function safeDestination(base, repoPath) {
54235
54336
  if (!repoPath || (0, import_node_path28.isAbsolute)(repoPath)) return null;
54236
54337
  const destination = (0, import_node_path28.resolve)(base, repoPath);
@@ -55321,6 +55422,18 @@ async function run2(env2) {
55321
55422
  console.log(JSON.stringify({ event: "parts_check.stop", reason: partsStop.reason, ids: partsStop.ids }));
55322
55423
  throw new PartsStopError(partsStop);
55323
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
+ }
55324
55437
  const judgedByPool = buildJudgedByPool(
55325
55438
  packet.requiredTests,
55326
55439
  targeting.targets,