@quikit/quikpilot-runner 9.3.0-rc.83 → 9.3.0-rc.85

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,791 +48284,888 @@ 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 }) } : {}
48404
- }
48405
- });
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 });
48421
- 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;
48471
- 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) };
48493
- }
48494
- if (body2.outcome !== "TOOL_CALLS") throw new LoopFailure("bad_reply");
48495
- if (isFinal) throw new LoopFailure("final_not_produced");
48496
- const rawCalls = body2.toolCalls;
48497
- if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
48498
- throw new LoopFailure("bad_reply");
48499
- }
48500
- const calls = [];
48501
- for (const c of rawCalls) {
48502
- if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
48503
- throw new LoopFailure("bad_reply");
48504
- }
48505
- if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
48506
- calls.push({ id: c.id, name: c.name, args: c.args });
48507
- }
48508
- for (const c of calls) usedIds.add(c.id);
48509
- const results = [];
48510
- const logged = [];
48511
- const turnReads = [];
48512
- calls.forEach((call, index) => {
48513
- let result;
48514
- let read;
48515
- if (index >= limits.maxCallsPerTurn) {
48516
- result = {
48517
- id: call.id,
48518
- name: call.name,
48519
- status: "budget_exhausted",
48520
- reason: "too_many_calls",
48521
- message: "Too many calls in one turn; this one was not run."
48522
- };
48523
- } else {
48524
- try {
48525
- ({ result, read } = executeToolCall(call, env2, ledger));
48526
- } catch (err2) {
48527
- throw new LoopFailure("executor_error", void 0, err2);
48528
- }
48529
- }
48530
- results.push(result);
48531
- turnReads[index] = read;
48532
- if (read) reads.push(read);
48533
- const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
48534
- const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
48535
- logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
48536
- if (result.status === "refused") {
48537
- log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
48538
- }
48539
- });
48540
- const reasoning = typeof body2.reasoning === "string" ? body2.reasoning.slice(0, limits.maxReasoningChars) : void 0;
48541
- transcript.push({
48542
- turn,
48543
- ...reasoning ? { reasoning } : {},
48544
- toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
48545
- });
48546
- toolResults.push(...results);
48547
- refusedStreak = 0;
48548
- if (notesOn) {
48549
- for (const c of calls) {
48550
- turnOfId.set(c.id, turn);
48551
- callOfId.set(c.id, { name: c.name, args: c.args });
48552
- }
48553
- notes = keepNotes(notes, body2.notes, env2.scrub);
48554
- stubbed += stubOldLooks({ results: toolResults, turnOf: (id) => turnOfId.get(id), callOf: (id) => callOfId.get(id), currentTurn: turn, ledger });
48555
- }
48556
- noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
48557
- if (noProgressStreak >= 2) forced = "no_progress";
48558
- else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
48559
- else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
48560
- const nextTurn = turn + 1;
48561
- if (nextTurn <= limits.maxTurns) {
48562
- const nextFinal = forced !== null || nextTurn === limits.maxTurns;
48563
- const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
48564
- if (projected > limits.maxRequestTokens) {
48565
- results.forEach((r, idx) => {
48566
- if (r.status !== "ok") return;
48567
- toolResults[toolResults.indexOf(r)] = {
48568
- id: r.id,
48569
- name: r.name,
48570
- status: "budget_exhausted",
48571
- reason: "token_ceiling",
48572
- message: "Too large to include; answer from what you have."
48573
- };
48574
- const dropped = turnReads[idx];
48575
- if (dropped) {
48576
- const at2 = reads.indexOf(dropped);
48577
- if (at2 >= 0) reads.splice(at2, 1);
48578
- }
48579
- logged[idx].status = "budget_exhausted";
48580
- logged[idx].reason = "token_ceiling";
48581
- });
48582
- forced = "read_budget";
48583
- const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
48584
- const fits = trimmed <= limits.maxRequestTokens;
48585
- log({
48586
- event: "targeting.loop_ceiling",
48587
- turn,
48588
- action: fits ? "dropped_results" : "fallback",
48589
- projectedTokens: projected,
48590
- ceiling: limits.maxRequestTokens
48591
- });
48592
- if (!fits) throw new LoopFailure("token_ceiling");
48593
- }
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);
48594
48484
  }
48595
- log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48485
+ return out2;
48596
48486
  }
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
- }
48487
+ };
48604
48488
  }
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";
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;
48612
48501
  }
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;
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
+ }
48620
48517
  return out2;
48621
48518
  }
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";
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
+ };
48630
48529
  }
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";
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));
48637
48534
  }
48638
- function rangeKey(r) {
48639
- return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
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)));
48640
48542
  }
48641
- function sizeOf2(output) {
48642
- try {
48643
- return JSON.stringify(output)?.length ?? 0;
48644
- } catch {
48645
- return Number.POSITIVE_INFINITY;
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 });
48646
48554
  }
48555
+ input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
48556
+ return calls;
48647
48557
  }
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";
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 };
48728
48568
  }
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;
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;
48743
48583
  }
48584
+ return true;
48585
+ });
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;
48744
48599
  }
48745
- return null;
48600
+ return build((p) => endOf(tail(p, 1), 22), (a) => endOf(a, 22)).slice(0, limit);
48746
48601
  }
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;
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
+ );
48753
48607
  }
48754
- function reviewAnswer(lines) {
48755
- return { rules: ["done_rule"], violations: [...lines.slice(0, MAX_REVIEW_CASES), REVIEW_CLOSING], message: REVIEW_MESSAGE };
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 };
48617
+ try {
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
+ }
48756
48623
  }
48757
48624
 
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 });
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;
48662
+ try {
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;
48678
+ }
48679
+ deps.onTrace?.({ outcome: note ? "note" : "silent", entries: note?.shownBy.length ?? 0, ms: now() - started });
48680
+ return note;
48781
48681
  }
48782
- }
48783
- return found;
48682
+ };
48784
48683
  }
48785
- function normalizePath(path) {
48786
- return path.replace(/:[A-Za-z0-9_]+|\{[^}]+\}|\[[^\]]+\]/g, "*");
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);
48787
48691
  }
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);
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);
48794
48726
  }
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");
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
+ }
48798
48733
  }
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;
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;
48811
48850
  try {
48812
- currentContent = (0, import_node_fs16.readFileSync)(targetPath, "utf8");
48813
- } catch {
48814
- currentContent = "";
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");
48908
+ if (isFinal) throw new LoopFailure("final_not_produced");
48909
+ const rawCalls = body2.toolCalls;
48910
+ if (!Array.isArray(rawCalls) || rawCalls.length === 0 || rawCalls.length > MAX_CALLS_IN_A_REPLY) {
48911
+ throw new LoopFailure("bad_reply");
48912
+ }
48913
+ const calls = [];
48914
+ for (const c of rawCalls) {
48915
+ if (!isPlainObject2(c) || typeof c.id !== "string" || c.id.length === 0 || c.id.length > MAX_ID_CHARS || typeof c.name !== "string") {
48916
+ throw new LoopFailure("bad_reply");
48917
+ }
48918
+ if (usedIds.has(c.id) || calls.some((x) => x.id === c.id)) throw new LoopFailure("duplicate_call_ids");
48919
+ calls.push({ id: c.id, name: c.name, args: c.args });
48815
48920
  }
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 });
48921
+ for (const c of calls) usedIds.add(c.id);
48922
+ const results = [];
48923
+ const logged = [];
48924
+ const turnReads = [];
48925
+ calls.forEach((call, index) => {
48926
+ let result;
48927
+ let read;
48928
+ if (index >= limits.maxCallsPerTurn) {
48929
+ result = {
48930
+ id: call.id,
48931
+ name: call.name,
48932
+ status: "budget_exhausted",
48933
+ reason: "too_many_calls",
48934
+ message: "Too many calls in one turn; this one was not run."
48935
+ };
48936
+ } else {
48937
+ try {
48938
+ ({ result, read } = executeToolCall(call, env2, ledger));
48939
+ } catch (err2) {
48940
+ throw new LoopFailure("executor_error", void 0, err2);
48941
+ }
48942
+ }
48943
+ results.push(result);
48944
+ turnReads[index] = read;
48945
+ if (read) reads.push(read);
48946
+ const tool = TOOL_NAMES.has(call.name) ? call.name : "unknown";
48947
+ const path = read && read.path !== "(invalid path)" ? { path: read.path } : {};
48948
+ logged.push({ tool, status: result.status, ...result.reason && result.status !== "duplicate" ? { reason: result.reason } : {}, ...path });
48949
+ if (result.status === "refused") {
48950
+ log({ event: "targeting.loop_refused", turn, tool, reason: result.reason, ...path });
48951
+ }
48952
+ });
48953
+ const reasoning = typeof body2.reasoning === "string" ? body2.reasoning.slice(0, limits.maxReasoningChars) : void 0;
48954
+ transcript.push({
48955
+ turn,
48956
+ ...reasoning ? { reasoning } : {},
48957
+ toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: safeArgs(c.args) }))
48958
+ });
48959
+ toolResults.push(...results);
48960
+ refusedStreak = 0;
48961
+ if (notesOn) {
48962
+ for (const c of calls) {
48963
+ turnOfId.set(c.id, turn);
48964
+ callOfId.set(c.id, { name: c.name, args: c.args });
48965
+ }
48966
+ notes = keepNotes(notes, body2.notes, env2.scrub);
48967
+ stubbed += stubOldLooks({ results: toolResults, turnOf: (id) => turnOfId.get(id), callOf: (id) => callOfId.get(id), currentTurn: turn, ledger });
48968
+ }
48969
+ noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
48970
+ if (noProgressStreak >= 2) forced = "no_progress";
48971
+ else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
48972
+ else if (ledger.readChars >= limits.readCharsTotal || ledger.resultChars >= limits.resultCharsTotal) forced = "read_budget";
48973
+ const nextTurn = turn + 1;
48974
+ if (nextTurn <= limits.maxTurns) {
48975
+ const nextFinal = forced !== null || nextTurn === limits.maxTurns;
48976
+ const projected = estimateRequestTokens(buildContext(nextTurn, nextFinal, forced ?? "max_turns"));
48977
+ if (projected > limits.maxRequestTokens) {
48978
+ results.forEach((r, idx) => {
48979
+ if (r.status !== "ok") return;
48980
+ toolResults[toolResults.indexOf(r)] = {
48981
+ id: r.id,
48982
+ name: r.name,
48983
+ status: "budget_exhausted",
48984
+ reason: "token_ceiling",
48985
+ message: "Too large to include; answer from what you have."
48986
+ };
48987
+ const dropped = turnReads[idx];
48988
+ if (dropped) {
48989
+ const at2 = reads.indexOf(dropped);
48990
+ if (at2 >= 0) reads.splice(at2, 1);
48991
+ }
48992
+ logged[idx].status = "budget_exhausted";
48993
+ logged[idx].reason = "token_ceiling";
48994
+ });
48995
+ forced = "read_budget";
48996
+ const trimmed = estimateRequestTokens(buildContext(nextTurn, true, "read_budget"));
48997
+ const fits = trimmed <= limits.maxRequestTokens;
48998
+ log({
48999
+ event: "targeting.loop_ceiling",
49000
+ turn,
49001
+ action: fits ? "dropped_results" : "fallback",
49002
+ projectedTokens: projected,
49003
+ ceiling: limits.maxRequestTokens
49004
+ });
49005
+ if (!fits) throw new LoopFailure("token_ceiling");
49006
+ }
48822
49007
  }
49008
+ log({ event: "targeting.loop_turn", turn, outcome: "tool_calls", requestChars, requestTokens, elapsedMs: now() - turnStarted, calls: logged });
48823
49009
  }
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;
48824
49016
  }
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
49017
  }
48830
49018
 
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);
48955
- }
48956
- return out2;
48957
- }
48958
- };
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";
48959
49025
  }
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;
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;
48972
49034
  }
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
- };
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";
48983
49043
  }
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));
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";
48988
49050
  }
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)));
49051
+ function rangeKey(r) {
49052
+ return r.mode === "outline" ? "outline" : `${r.startLine ?? ""}-${r.endLine ?? ""}`;
48996
49053
  }
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 });
49054
+ function sizeOf2(output) {
49055
+ try {
49056
+ return JSON.stringify(output)?.length ?? 0;
49057
+ } catch {
49058
+ return Number.POSITIVE_INFINITY;
49008
49059
  }
49009
- input.onScan?.({ files, calls, ms: Date.now() - started, expired: expired() });
49010
- return calls;
49011
- }
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 };
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);
@@ -49520,6 +49621,92 @@ function partMissingSentence(missing, opts = {}) {
49520
49621
  return `${start3} ${missing[0] ? item(missing[0], true) : ""}`.slice(0, MAX_REFUSED_SENTENCE_CHARS);
49521
49622
  }
49522
49623
 
49624
+ // src/ticketHints.ts
49625
+ var CRITERIA_WORDING_KEY = "criteriaWording";
49626
+ var MAX_HINT_FILES = 20;
49627
+ var MAX_HINT_ROUTES = 10;
49628
+ var MAX_ROUTE_FILES = 3;
49629
+ var MAX_ADDRESS_CHARS = 200;
49630
+ var MAX_HINT_NAMES = 20;
49631
+ var MAX_NAME_CHARS4 = 120;
49632
+ var MAX_HINT_TESTS = 10;
49633
+ var MAX_TEST_CHARS = 200;
49634
+ var MAX_CRITERIA = 20;
49635
+ var MAX_CRITERION_ID_CHARS = 40;
49636
+ var MAX_STATEMENT_CHARS = 500;
49637
+ var MAX_QUOTE_CHARS2 = 200;
49638
+ var METHODS = /* @__PURE__ */ new Set(["GET", "POST", "PUT", "PATCH", "DELETE", "HEAD", "OPTIONS"]);
49639
+ var isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
49640
+ var strings = (v) => Array.isArray(v) ? v.filter((s) => typeof s === "string") : [];
49641
+ var oneLine2 = (s, max) => s.trim() !== "" && s.length <= max && !/[\r\n]/.test(s);
49642
+ var unique3 = (xs) => [...new Set(xs)];
49643
+ var MAX_PATH_CHARS5 = 300;
49644
+ function cleanPath2(p) {
49645
+ return p !== "" && p.length <= MAX_PATH_CHARS5 && !p.startsWith("/") && !p.includes("\\") && !/[\u0000-\u001f\u007f]/.test(p) && p.split("/").every((seg) => seg !== "" && seg !== "." && seg !== "..");
49646
+ }
49647
+ function cleanAddress(a) {
49648
+ return oneLine2(a, MAX_ADDRESS_CHARS) && a.startsWith("/") && !a.startsWith("//") && !/\s/.test(a);
49649
+ }
49650
+ function prepareTicketHints(raw, listing, deniedPaths) {
49651
+ const counts = { files: 0, routes: 0, routeFiles: 0, names: 0, tests: 0, dropped: 0 };
49652
+ if (!isRecord5(raw)) return { counts };
49653
+ const listed = listing instanceof Set ? listing : new Set(listing);
49654
+ const denied = [...deniedPaths];
49655
+ const usable = (p) => cleanPath2(p) && listed.has(p) && matchesDeniedPath(p, denied) === null;
49656
+ const named2 = unique3(strings(raw.paths).map((p) => p.trim()));
49657
+ const files = named2.filter(usable).slice(0, MAX_HINT_FILES);
49658
+ counts.dropped = named2.filter((p) => !usable(p)).length;
49659
+ const routeFiles = [];
49660
+ for (const file of [...listed].sort()) {
49661
+ const address = routeAddressOf(file);
49662
+ if (address !== null && usable(file)) routeFiles.push({ file, address });
49663
+ }
49664
+ const routes = [];
49665
+ const seen = /* @__PURE__ */ new Set();
49666
+ for (const r of Array.isArray(raw.routes) ? raw.routes : []) {
49667
+ if (routes.length >= MAX_HINT_ROUTES) break;
49668
+ if (!isRecord5(r) || typeof r.address !== "string") continue;
49669
+ const address = r.address.trim();
49670
+ if (!cleanAddress(address)) continue;
49671
+ const method = typeof r.method === "string" && METHODS.has(r.method.toUpperCase()) ? r.method.toUpperCase() : void 0;
49672
+ const key = `${method ?? ""} ${address}`;
49673
+ if (seen.has(key)) continue;
49674
+ seen.add(key);
49675
+ const answering = routeFiles.filter((f) => addressMatches(f.address, address));
49676
+ answering.sort((a, b) => Number(b.address === address) - Number(a.address === address) || a.file.localeCompare(b.file));
49677
+ const filesOf = answering.slice(0, MAX_ROUTE_FILES).map((f) => f.file);
49678
+ routes.push({ address, ...method ? { method } : {}, files: filesOf });
49679
+ }
49680
+ const names = unique3(strings(raw.names).map((s) => s.trim())).filter((s) => oneLine2(s, MAX_NAME_CHARS4)).slice(0, MAX_HINT_NAMES);
49681
+ const tests = unique3(strings(raw.tests).map((s) => s.trim())).filter((s) => oneLine2(s, MAX_TEST_CHARS)).slice(0, MAX_HINT_TESTS);
49682
+ counts.files = files.length;
49683
+ counts.routes = routes.length;
49684
+ counts.routeFiles = routes.reduce((n, r) => n + r.files.length, 0);
49685
+ counts.names = names.length;
49686
+ counts.tests = tests.length;
49687
+ const hints = {
49688
+ ...files.length > 0 ? { files } : {},
49689
+ ...routes.length > 0 ? { routes } : {},
49690
+ ...names.length > 0 ? { names } : {},
49691
+ ...tests.length > 0 ? { tests } : {}
49692
+ };
49693
+ return Object.keys(hints).length > 0 ? { hints, counts } : { counts };
49694
+ }
49695
+ function prepareCriteriaWording(raw) {
49696
+ if (!Array.isArray(raw)) return void 0;
49697
+ const out2 = [];
49698
+ for (const c of raw) {
49699
+ if (out2.length >= MAX_CRITERIA) break;
49700
+ if (!isRecord5(c) || typeof c.id !== "string" || typeof c.statement !== "string") continue;
49701
+ const id = c.id.trim();
49702
+ const statement = c.statement.trim().slice(0, MAX_STATEMENT_CHARS).trim();
49703
+ if (!oneLine2(id, MAX_CRITERION_ID_CHARS) || statement === "") continue;
49704
+ const quote = typeof c.quote === "string" ? c.quote.trim().slice(0, MAX_QUOTE_CHARS2).trim() : "";
49705
+ out2.push({ id, statement, ...quote !== "" ? { quote } : {} });
49706
+ }
49707
+ return out2.length > 0 ? out2 : void 0;
49708
+ }
49709
+
49523
49710
  // src/sameFailureHint.ts
49524
49711
  var MAX_NAMES = 2;
49525
49712
  var MAX_HINT_CHARS = 300;
@@ -49625,6 +49812,8 @@ var CodegenLoopFailure = class extends Error {
49625
49812
  featureKey;
49626
49813
  /** QUIKTR-2445: the AI Runtime refused a request that carried `databaseChange` (the step then stops `needs_database_change`). */
49627
49814
  databaseKey;
49815
+ /** QUIKTR-2509: the AI Runtime refused a request that carried `criteriaWording` (the step then asks again without it). Wire only. */
49816
+ criteriaKey;
49628
49817
  /** QUIKTR-2468: the refusal came on a later turn, not the loop's first request: about that request, never the version. */
49629
49818
  late;
49630
49819
  constructor(reason, runtimeCode, cause, detail, told) {
@@ -50220,6 +50409,7 @@ async function runCodegenLoop(args2, deps) {
50220
50409
  const blames = (key) => !late || refusalText.includes(key);
50221
50410
  if (code === "CONTRACT_REJECTED" && contextData[FEATURE_TEST_UPDATES_KEY] === true && blames(FEATURE_TEST_UPDATES_KEY)) failure.featureKey = true;
50222
50411
  if (code === "CONTRACT_REJECTED" && contextData[DATABASE_CHANGE_KEY] !== void 0 && blames(DATABASE_CHANGE_KEY)) failure.databaseKey = true;
50412
+ if (code === "CONTRACT_REJECTED" && contextData[CRITERIA_WORDING_KEY] !== void 0 && blames(CRITERIA_WORDING_KEY)) failure.criteriaKey = true;
50223
50413
  throw failure;
50224
50414
  }
50225
50415
  if (envelope?.success === false) {
@@ -51922,6 +52112,7 @@ function buildCodegenLoopArgs(p, context = collectLoopContext({
51922
52112
  );
51923
52113
  }
51924
52114
  if (p.outOfScope.length > 0) baseContext.outOfScope = p.outOfScope;
52115
+ if (p.criteriaWording && p.criteriaWording.length > 0) baseContext[CRITERIA_WORDING_KEY] = p.criteriaWording;
51925
52116
  return {
51926
52117
  baseContext,
51927
52118
  targets: p.targets,
@@ -52135,6 +52326,13 @@ async function runCodegenStep(p) {
52135
52326
  log({ event: "codegen.attempt_start", attempt: 1 });
52136
52327
  const firstStarted = now();
52137
52328
  let first = await attempt2();
52329
+ if ("failure" in first && first.failure.reason === "contract_rejected" && first.failure.criteriaKey === true && p.criteriaWording) {
52330
+ log({ event: "codegen.version_fallback", from: "criteria_wording" });
52331
+ p.criteriaWording = void 0;
52332
+ const kept = "tests" in first ? first.tests : void 0;
52333
+ args2 = buildCodegenLoopArgs(p, context);
52334
+ first = await attempt2(void 0, 1, kept);
52335
+ }
52138
52336
  if ("failure" in first && first.failure.reason === "contract_rejected" && first.failure.featureKey === true && p.featureTestUpdates === true) {
52139
52337
  log({ event: "codegen.version_fallback", from: "feature_test_updates" });
52140
52338
  p.featureTestUpdates = false;
@@ -53206,7 +53404,7 @@ function describeAutomationCoverageViolations(check) {
53206
53404
  var estraverse5 = __toESM2(require_estraverse());
53207
53405
  var MAX_UNSUPPLIED_ENTRIES = 10;
53208
53406
  var MAX_UNSUPPLIED_NAMES = 5;
53209
- var MAX_NAME_CHARS4 = 80;
53407
+ var MAX_NAME_CHARS5 = 80;
53210
53408
  var MAX_FUNCTION_CHARS = 120;
53211
53409
  var FUNCTION_TYPES = /* @__PURE__ */ new Set(["FunctionDeclaration", "FunctionExpression", "ArrowFunctionExpression"]);
53212
53410
  var IDENTIFIER_NAME = /^[A-Za-z_$][\w$]*$/;
@@ -53347,7 +53545,7 @@ function findUnsuppliedInputs(input) {
53347
53545
  if (isCallback(site)) continue;
53348
53546
  const names = [];
53349
53547
  for (const { name: name2 } of readsOf(site)) {
53350
- if (!IDENTIFIER_NAME.test(name2) || name2.length > MAX_NAME_CHARS4) continue;
53548
+ if (!IDENTIFIER_NAME.test(name2) || name2.length > MAX_NAME_CHARS5) continue;
53351
53549
  if (known.has(name2) || supplied.has(name2) || names.includes(name2)) continue;
53352
53550
  names.push(name2);
53353
53551
  }
@@ -54230,7 +54428,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
54230
54428
  var REPORT_COPY = "final-test-report.xml";
54231
54429
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
54232
54430
  var MAX_FILES = 200;
54233
- var RUNNER_VERSION = true ? "9.3.0-rc.83" : "dev";
54431
+ var RUNNER_VERSION = true ? "9.3.0-rc.85" : "dev";
54234
54432
  function safeDestination(base, repoPath) {
54235
54433
  if (!repoPath || (0, import_node_path28.isAbsolute)(repoPath)) return null;
54236
54434
  const destination = (0, import_node_path28.resolve)(base, repoPath);
@@ -54639,12 +54837,12 @@ async function resolveTestDiscovery(i3) {
54639
54837
  }
54640
54838
 
54641
54839
  // src/targetingFindings.ts
54642
- var isRecord5 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
54840
+ var isRecord6 = (v) => typeof v === "object" && v !== null && !Array.isArray(v);
54643
54841
  function prepareTargetingFindings(raw, listing, deniedPaths) {
54644
- if (!isRecord5(raw)) return void 0;
54842
+ if (!isRecord6(raw)) return void 0;
54645
54843
  const { verdict, files, callPath, evidence, searches } = raw;
54646
54844
  if (typeof verdict !== "string" || !Array.isArray(files) || !Array.isArray(callPath) || !Array.isArray(evidence)) return void 0;
54647
- const keep = (entry) => isRecord5(entry) && typeof entry.path === "string" && listing.has(entry.path) && matchesDeniedPath(entry.path, deniedPaths) === null;
54845
+ const keep = (entry) => isRecord6(entry) && typeof entry.path === "string" && listing.has(entry.path) && matchesDeniedPath(entry.path, deniedPaths) === null;
54648
54846
  const kept = {
54649
54847
  files: files.filter(keep),
54650
54848
  callPath: callPath.filter(keep),
@@ -54698,7 +54896,7 @@ function validateTarget(target, workspaceRoot, workspaceListing, deniedPaths) {
54698
54896
  );
54699
54897
  }
54700
54898
  }
54701
- function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck = false, storedProposals = false) {
54899
+ function buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck = false, storedProposals = false, ticketHints) {
54702
54900
  const contextData = {
54703
54901
  // NESTED, NOT FLATTENED — a second vocabulary for the design shape is exactly what
54704
54902
  // QUIKTR-1034 cost.
@@ -54727,6 +54925,9 @@ function buildContextData(design, workspaceListing, requiredTests, deniedPaths,
54727
54925
  if (partsCheck && storedProposals) {
54728
54926
  contextData[STORED_PROPOSALS_KEY] = true;
54729
54927
  }
54928
+ if (ticketHints) {
54929
+ contextData.ticketHints = ticketHints;
54930
+ }
54730
54931
  return contextData;
54731
54932
  }
54732
54933
  async function postTargeting(gateway, contextData, signal) {
@@ -54776,16 +54977,24 @@ function finalizeTargeting(body2, workspaceRoot, workspaceListing, deniedPaths)
54776
54977
  ...correctedKinds.length > 0 ? { correctedKinds } : {}
54777
54978
  };
54778
54979
  }
54779
- async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], findings, partsCheck = false, storedProposals = false) {
54780
- const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals);
54980
+ async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope = [], findings, partsCheck = false, storedProposals = false, ticketHints) {
54981
+ const contextData = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals, ticketHints);
54781
54982
  let envelope = await postTargeting(gateway, contextData);
54782
54983
  let warnings;
54783
- if (findings && envelope?.errorCode === "CONTRACT_REJECTED") {
54984
+ const refused2 = () => envelope?.errorCode === "CONTRACT_REJECTED";
54985
+ if (ticketHints && refused2()) {
54986
+ envelope = await postTargeting(
54987
+ gateway,
54988
+ buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals)
54989
+ );
54990
+ warnings = [TICKET_HINTS_REFUSED_WARNING];
54991
+ }
54992
+ if (findings && refused2()) {
54784
54993
  envelope = await postTargeting(
54785
54994
  gateway,
54786
54995
  buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, void 0, partsCheck, storedProposals)
54787
54996
  );
54788
- warnings = ["QuikPilot's targeting ran without the early look's findings (the AI service did not accept them)."];
54997
+ warnings = [...warnings ?? [], "QuikPilot's targeting ran without the early look's findings (the AI service did not accept them)."];
54789
54998
  }
54790
54999
  checkHardFailure(envelope, "pilot.targeting");
54791
55000
  const body2 = unwrapExecute(envelope, "pilot.targeting");
@@ -54828,23 +55037,36 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
54828
55037
  }
54829
55038
  const mode = options.mode ?? resolveTargetingMode();
54830
55039
  const findings = prepareTargetingFindings(options.findings, new Set(workspaceListing), deniedPaths);
55040
+ const logEvent = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
55041
+ let ticketHints = hintsFor(options.ticketHints, workspaceListing, deniedPaths, logEvent);
54831
55042
  if (mode !== "loop") {
54832
- return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals);
55043
+ return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals, ticketHints);
54833
55044
  }
54834
- const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals);
55045
+ const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals, ticketHints);
55046
+ let hintsWarning;
54835
55047
  const listingView = repoViewOf(options.scope);
54836
55048
  let summary;
54837
55049
  let runtimeCode;
54838
55050
  let reason;
54839
55051
  try {
54840
- const looped = await loopWithTools2(
54841
- { baseContext, listing: workspaceListing, deniedPaths },
54842
- options.tools2,
54843
- { secrets: [gateway.token], ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
55052
+ const deps = { secrets: [gateway.token], ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) };
55053
+ const looped = await withoutHintsIfRefused(
55054
+ ticketHints,
55055
+ (ctx) => loopWithTools2({ baseContext: ctx, listing: workspaceListing, deniedPaths }, options.tools2, deps),
55056
+ baseContext,
55057
+ () => {
55058
+ ticketHints = void 0;
55059
+ hintsWarning = TICKET_HINTS_REFUSED_WARNING;
55060
+ logEvent({ event: "targeting.ticket_hints_refused" });
55061
+ }
54844
55062
  );
54845
55063
  summary = looped.summary;
54846
55064
  const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
54847
- return { ...result, loop: { ...summary, ...listingView ? { repoView: listingView } : {} } };
55065
+ return {
55066
+ ...result,
55067
+ loop: { ...summary, ...listingView ? { repoView: listingView } : {} },
55068
+ ...hintsWarning ? { warnings: [hintsWarning, ...result.warnings ?? []] } : {}
55069
+ };
54848
55070
  } catch (err2) {
54849
55071
  if (err2 instanceof DeniedPathError || err2 instanceof SafetyRefusalError) throw err2;
54850
55072
  if (err2 instanceof LoopFailure) {
@@ -54878,7 +55100,7 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
54878
55100
  toolCalls: fellBack.toolCalls,
54879
55101
  ...runtimeCode && CODE_LIKE.test(runtimeCode) ? { runtimeCode } : {}
54880
55102
  });
54881
- const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals);
55103
+ const single = await runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals, ticketHints);
54882
55104
  return {
54883
55105
  ...single,
54884
55106
  loop: fellBack,
@@ -54891,7 +55113,7 @@ function mapTestDiscovery(testDiscovery) {
54891
55113
  if (estimateTokens(JSON.stringify(testDiscovery.discoveredTestFiles, null, 2)) <= MAP_DISCOVERY_MAX_TOKENS) return testDiscovery;
54892
55114
  return { report: "PRESENT", discoveredTestFiles: [], unmappedEntries: Math.max(1, testDiscovery.unmappedEntries + testDiscovery.discoveredTestFiles.length) };
54893
55115
  }
54894
- function buildMapContextData(repoMap, design, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck = false, storedProposals = false) {
55116
+ function buildMapContextData(repoMap, design, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck = false, storedProposals = false, ticketHints) {
54895
55117
  return {
54896
55118
  repoMap,
54897
55119
  design,
@@ -54902,23 +55124,35 @@ function buildMapContextData(repoMap, design, requiredTests, deniedPaths, testDi
54902
55124
  testDiscovery: mapTestDiscovery(testDiscovery),
54903
55125
  ...findings ? { findings } : {},
54904
55126
  ...partsCheck ? { partsCheck: true } : {},
54905
- ...partsCheck && storedProposals ? { [STORED_PROPOSALS_KEY]: true } : {}
55127
+ ...partsCheck && storedProposals ? { [STORED_PROPOSALS_KEY]: true } : {},
55128
+ ...ticketHints ? { ticketHints } : {}
54906
55129
  };
54907
55130
  }
54908
55131
  async function runMapTargeting(gateway, design, workspaceRoot, scope, requiredTests, deniedPaths, testDiscovery, outOfScope, options, partsCheck, storedProposals = false) {
54909
55132
  const findings = prepareTargetingFindings(options.findings, new Set(scope.readListing), deniedPaths);
54910
- const baseContext = buildMapContextData(scope.repoMap, design, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals);
54911
- const repoView = repoViewOf(scope);
54912
55133
  const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
55134
+ const ticketHints = hintsFor(options.ticketHints, scope.readListing, deniedPaths, log);
55135
+ const baseContext = buildMapContextData(scope.repoMap, design, requiredTests, deniedPaths, testDiscovery, outOfScope, findings, partsCheck, storedProposals, ticketHints);
55136
+ const repoView = repoViewOf(scope);
54913
55137
  let reason;
55138
+ let hintsWarning;
54914
55139
  try {
54915
- const looped = await loopWithTools2(
54916
- { baseContext, listing: scope.readListing, deniedPaths, readRoots: scope.readRoots, contractVersion: MAP_LOOP_CONTRACT_VERSION },
54917
- options.tools2,
54918
- { secrets: [gateway.token], ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) }
55140
+ const deps = { secrets: [gateway.token], ...options.loopDeps, post: (contextData, signal) => postTargeting(gateway, contextData, signal) };
55141
+ const looped = await withoutHintsIfRefused(
55142
+ ticketHints,
55143
+ (ctx) => loopWithTools2({ baseContext: ctx, listing: scope.readListing, deniedPaths, readRoots: scope.readRoots, contractVersion: MAP_LOOP_CONTRACT_VERSION }, options.tools2, deps),
55144
+ baseContext,
55145
+ () => {
55146
+ hintsWarning = TICKET_HINTS_REFUSED_WARNING;
55147
+ log({ event: "targeting.ticket_hints_refused" });
55148
+ }
54919
55149
  );
54920
55150
  const result = finalizeTargeting(looped.body, workspaceRoot, scope.writeListing, deniedPaths);
54921
- return { ...result, loop: { ...looped.summary, ...repoView ? { repoView } : {} } };
55151
+ return {
55152
+ ...result,
55153
+ loop: { ...looped.summary, ...repoView ? { repoView } : {} },
55154
+ ...hintsWarning ? { warnings: [hintsWarning, ...result.warnings ?? []] } : {}
55155
+ };
54922
55156
  } catch (err2) {
54923
55157
  if (err2 instanceof DeniedPathError || err2 instanceof SafetyRefusalError) throw err2;
54924
55158
  reason = err2 instanceof LoopFailure ? err2.reason : "final_invalid";
@@ -54926,6 +55160,24 @@ async function runMapTargeting(gateway, design, workspaceRoot, scope, requiredTe
54926
55160
  log({ event: "targeting.map_failed", reason });
54927
55161
  throw new MapModeError("targeting", reason);
54928
55162
  }
55163
+ var TICKET_HINTS_REFUSED_WARNING = "QuikPilot's targeting ran without the files and routes the request names (the AI service did not accept them).";
55164
+ function hintsFor(raw, listing, deniedPaths, log) {
55165
+ if (raw === void 0 || raw === null) return void 0;
55166
+ const { hints, counts } = prepareTicketHints(raw, listing, deniedPaths);
55167
+ log({ event: "targeting.ticket_hints", ...counts, sent: hints !== void 0 });
55168
+ return hints;
55169
+ }
55170
+ async function withoutHintsIfRefused(hints, run3, baseContext, onRefused) {
55171
+ try {
55172
+ return await run3(baseContext);
55173
+ } catch (err2) {
55174
+ if (!hints || !(err2 instanceof LoopFailure) || err2.reason !== "contract_rejected") throw err2;
55175
+ onRefused();
55176
+ const without = { ...baseContext };
55177
+ delete without.ticketHints;
55178
+ return run3(without);
55179
+ }
55180
+ }
54929
55181
 
54930
55182
  // src/targetingRecord.ts
54931
55183
  var MAX_TARGETS = 25;
@@ -54935,7 +55187,7 @@ var MAX_ADDED_PATHS = 20;
54935
55187
  var MAX_SKIPPED_CONTEXT = 20;
54936
55188
  var MAX_SKIPPED_CASES = 200;
54937
55189
  var MAX_CONTEXT_RECORDS = 25;
54938
- var MAX_PATH_CHARS5 = 300;
55190
+ var MAX_PATH_CHARS6 = 300;
54939
55191
  var MAX_ID_CHARS3 = 100;
54940
55192
  var MAX_REASON_CHARS3 = 300;
54941
55193
  var MAX_LOOP_READS = 50;
@@ -54966,7 +55218,7 @@ function clampLoop(loop) {
54966
55218
  break;
54967
55219
  }
54968
55220
  const path = typeof r.path === "string" ? r.path.trim() : "";
54969
- if (path.length === 0 || path.length > MAX_PATH_CHARS5) {
55221
+ if (path.length === 0 || path.length > MAX_PATH_CHARS6) {
54970
55222
  cut2 = true;
54971
55223
  continue;
54972
55224
  }
@@ -55020,11 +55272,11 @@ function buildTargetingRecord(targeting, contextLog) {
55020
55272
  break;
55021
55273
  }
55022
55274
  const path = typeof t.path === "string" ? t.path.trim() : "";
55023
- if (path.length === 0 || path.length > MAX_PATH_CHARS5) {
55275
+ if (path.length === 0 || path.length > MAX_PATH_CHARS6) {
55024
55276
  truncated = true;
55025
55277
  continue;
55026
55278
  }
55027
- const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS5);
55279
+ const contextPaths = clampList(t.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS6);
55028
55280
  const automationIds = clampList(t.automationIds, MAX_IDS_PER_TARGET, MAX_ID_CHARS3);
55029
55281
  note(contextPaths.cut);
55030
55282
  note(automationIds.cut);
@@ -55043,16 +55295,16 @@ function buildTargetingRecord(targeting, contextLog) {
55043
55295
  break;
55044
55296
  }
55045
55297
  const targetPath = typeof entry.targetPath === "string" ? entry.targetPath.trim() : "";
55046
- if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS5) {
55298
+ if (targetPath.length === 0 || targetPath.length > MAX_PATH_CHARS6) {
55047
55299
  truncated = true;
55048
55300
  continue;
55049
55301
  }
55050
- const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS5);
55051
- const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS5);
55302
+ const contextPaths = clampList(entry.contextPaths, MAX_CONTEXT_PATHS, MAX_PATH_CHARS6);
55303
+ const addedPaths = clampList(entry.addedPaths, MAX_ADDED_PATHS, MAX_PATH_CHARS6);
55052
55304
  const skippedPaths = clampList(
55053
55305
  (entry.skipped ?? []).map((s) => s.path),
55054
55306
  MAX_SKIPPED_CONTEXT,
55055
- MAX_PATH_CHARS5
55307
+ MAX_PATH_CHARS6
55056
55308
  );
55057
55309
  note(contextPaths.cut);
55058
55310
  note(addedPaths.cut);
@@ -55245,6 +55497,8 @@ async function run2(env2) {
55245
55497
  // QUIKTR-2325 - and `partsCheck` only when the switch is on and the design has parts.
55246
55498
  {
55247
55499
  ...packet.findings ? { findings: packet.findings } : {},
55500
+ // QUIKTR-2509 - what the person's request names; fitted to this checkout inside runTargeting. Absent: called exactly as before.
55501
+ ...packet.ticketHints ? { ticketHints: packet.ticketHints } : {},
55248
55502
  scope,
55249
55503
  ...tools2 ? { tools2 } : {},
55250
55504
  mode: resolveTargetingMode(process.env, packet.targetingMode),
@@ -55321,6 +55575,18 @@ async function run2(env2) {
55321
55575
  console.log(JSON.stringify({ event: "parts_check.stop", reason: partsStop.reason, ids: partsStop.ids }));
55322
55576
  throw new PartsStopError(partsStop);
55323
55577
  }
55578
+ if (designParts.length > 0) {
55579
+ const measure = dataPathAtTargeting({
55580
+ cwd: process.cwd(),
55581
+ parts: partsForCode(designParts, targeting.targets, proposals ? { proposals: true } : {}),
55582
+ changed: targeting.targets.map((t) => t.path),
55583
+ read: readFromCheckout(process.cwd()),
55584
+ isTest: testRule(discoveredTestsOf(codegenDiscovery)),
55585
+ deniedPaths: packet.guardrails.deniedPaths,
55586
+ readable: new Set(scope.readListing)
55587
+ });
55588
+ console.log(JSON.stringify({ event: "targeting.data_path", ...measure }));
55589
+ }
55324
55590
  const judgedByPool = buildJudgedByPool(
55325
55591
  packet.requiredTests,
55326
55592
  targeting.targets,
@@ -55367,6 +55633,7 @@ async function run2(env2) {
55367
55633
  if (approved && approved.proposals.length > 0) approvedApplied = approved.proposals;
55368
55634
  }
55369
55635
  const decided = approved?.decided ?? [];
55636
+ const criteriaWording = prepareCriteriaWording(packet.criteriaWording);
55370
55637
  const stepParams = {
55371
55638
  mode: codegenMode,
55372
55639
  ...keepOnGiveUp ? { keepOnGiveUp: true } : {},
@@ -55375,6 +55642,8 @@ async function run2(env2) {
55375
55642
  ...conflictsOn && packet.fixFirst === true && process.env.QUIKPILOT_FIX_FIRST?.trim().toLowerCase() !== "off" ? { fixFirst: true } : {},
55376
55643
  // QUIKTR-2442: a feature run may propose add-only set-up for an existing test its change breaks.
55377
55644
  ...featureUpdates ? { featureTestUpdates: true } : {},
55645
+ // QUIKTR-2509: the approved criteria in the person's words, when QuikProjects sent them (its switch QUIKPILOT_TICKET_HINTS).
55646
+ ...criteriaWording ? { criteriaWording } : {},
55378
55647
  ...approved && approved.files.length > 0 ? { approved: approved.files } : {},
55379
55648
  ...callFunction ? { callFunction } : {},
55380
55649
  ...runScratch ? { runScratch } : {},
@@ -55834,7 +56103,7 @@ var EvidenceLedger = class {
55834
56103
  return seen;
55835
56104
  }
55836
56105
  };
55837
- function isRecord6(x) {
56106
+ function isRecord7(x) {
55838
56107
  return typeof x === "object" && x !== null && !Array.isArray(x);
55839
56108
  }
55840
56109
  function arrayOf(x) {
@@ -55872,7 +56141,7 @@ function capFindingsSize(findings, max = MAX_FINDINGS_CHARS) {
55872
56141
  function verifyFindings(raw, ledger, ctx) {
55873
56142
  const dropped = emptyDropped();
55874
56143
  const redactions = emptyRedactionCounts();
55875
- if (!isRecord6(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
56144
+ if (!isRecord7(raw)) return { findings: emptyFindings(), downgraded: false, dropped, redactions };
55876
56145
  const pathOk2 = (p) => typeof p === "string" && ctx.listing.has(p) && matchesDeniedPath(p, ctx.deniedPaths) === null;
55877
56146
  const symbolsOf = (path, list2) => {
55878
56147
  const out2 = [];
@@ -55887,7 +56156,7 @@ function verifyFindings(raw, ledger, ctx) {
55887
56156
  };
55888
56157
  const files = [];
55889
56158
  for (const f of arrayOf(raw.files)) {
55890
- if (!isRecord6(f) || !pathOk2(f.path)) {
56159
+ if (!isRecord7(f) || !pathOk2(f.path)) {
55891
56160
  dropped.files += 1;
55892
56161
  continue;
55893
56162
  }
@@ -55897,7 +56166,7 @@ function verifyFindings(raw, ledger, ctx) {
55897
56166
  }
55898
56167
  const callPath = [];
55899
56168
  for (const s of arrayOf(raw.callPath)) {
55900
- const ok = isRecord6(s) && pathOk2(s.path) && typeof s.symbol === "string" && s.symbol.length > 0 && s.symbol.length <= MAX_SYMBOL_CHARS && isLine2(s.line) && ledger.hasLines(s.path, s.line, s.line) && ledger.textContains(s.path, s.symbol);
56169
+ const ok = isRecord7(s) && pathOk2(s.path) && typeof s.symbol === "string" && s.symbol.length > 0 && s.symbol.length <= MAX_SYMBOL_CHARS && isLine2(s.line) && ledger.hasLines(s.path, s.line, s.line) && ledger.textContains(s.path, s.symbol);
55901
56170
  if (!ok) {
55902
56171
  dropped.callPath += 1;
55903
56172
  continue;
@@ -55906,7 +56175,7 @@ function verifyFindings(raw, ledger, ctx) {
55906
56175
  }
55907
56176
  const evidence = [];
55908
56177
  for (const e of arrayOf(raw.evidence)) {
55909
- const ok = isRecord6(e) && pathOk2(e.path) && isLine2(e.startLine) && isLine2(e.endLine) && e.startLine <= e.endLine && e.endLine - e.startLine + 1 <= MAX_EVIDENCE_LINES && ledger.hasLines(e.path, e.startLine, e.endLine);
56178
+ const ok = isRecord7(e) && pathOk2(e.path) && isLine2(e.startLine) && isLine2(e.endLine) && e.startLine <= e.endLine && e.endLine - e.startLine + 1 <= MAX_EVIDENCE_LINES && ledger.hasLines(e.path, e.startLine, e.endLine);
55910
56179
  if (!ok) {
55911
56180
  dropped.evidence += 1;
55912
56181
  continue;