@quikit/quikpilot-runner 9.3.0-rc.34 → 9.3.0-rc.36

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
@@ -144,8 +144,8 @@ var require_types = __commonJS({
144
144
  TokenType4[TokenType4["IS_POSTFIX"] = IS_POSTFIX] = "IS_POSTFIX";
145
145
  const IS_EXPRESSION_START = 1 << 9;
146
146
  TokenType4[TokenType4["IS_EXPRESSION_START"] = IS_EXPRESSION_START] = "IS_EXPRESSION_START";
147
- const num = 512;
148
- TokenType4[TokenType4["num"] = num] = "num";
147
+ const num2 = 512;
148
+ TokenType4[TokenType4["num"] = num2] = "num";
149
149
  const bigint = 1536;
150
150
  TokenType4[TokenType4["bigint"] = bigint] = "bigint";
151
151
  const decimal = 2560;
@@ -12785,8 +12785,8 @@ var require_sourcemap_codec_umd = __commonJS({
12785
12785
  }
12786
12786
  return relative10 + value;
12787
12787
  }
12788
- function encodeInteger(builder, num, relative10) {
12789
- let delta = num - relative10;
12788
+ function encodeInteger(builder, num2, relative10) {
12789
+ let delta = num2 - relative10;
12790
12790
  delta = delta < 0 ? -delta << 1 | 1 : delta << 1;
12791
12791
  do {
12792
12792
  let clamped = delta & 31;
@@ -12794,7 +12794,7 @@ var require_sourcemap_codec_umd = __commonJS({
12794
12794
  if (delta > 0) clamped |= 32;
12795
12795
  builder.write(intToChar[clamped]);
12796
12796
  } while (delta > 0);
12797
- return num;
12797
+ return num2;
12798
12798
  }
12799
12799
  function hasMoreVlq(reader, max) {
12800
12800
  if (reader.pos >= max) return false;
@@ -12851,7 +12851,7 @@ var require_sourcemap_codec_umd = __commonJS({
12851
12851
  return idx === -1 ? buffer.length : idx;
12852
12852
  }
12853
12853
  };
12854
- var EMPTY = [];
12854
+ var EMPTY2 = [];
12855
12855
  function decodeOriginalScopes(input) {
12856
12856
  const { length } = input;
12857
12857
  const reader = new StringReader(input);
@@ -12871,7 +12871,7 @@ var require_sourcemap_codec_umd = __commonJS({
12871
12871
  const fields = decodeInteger(reader, 0);
12872
12872
  const hasName = fields & 1;
12873
12873
  const scope = hasName ? [line, column, 0, 0, kind, decodeInteger(reader, 0)] : [line, column, 0, 0, kind];
12874
- let vars = EMPTY;
12874
+ let vars = EMPTY2;
12875
12875
  if (hasMoreVlq(reader, length)) {
12876
12876
  vars = [];
12877
12877
  do {
@@ -12947,7 +12947,7 @@ var require_sourcemap_codec_umd = __commonJS({
12947
12947
  const hasCallsite = fields & 2;
12948
12948
  const hasScope = fields & 4;
12949
12949
  let callsite = null;
12950
- let bindings = EMPTY;
12950
+ let bindings = EMPTY2;
12951
12951
  let range;
12952
12952
  if (hasDefinition) {
12953
12953
  const defSourcesIndex = decodeInteger(reader, definitionSourcesIndex);
@@ -24436,7 +24436,7 @@ async function describeQuikTrackFailure(res) {
24436
24436
 
24437
24437
  // src/callback.ts
24438
24438
  async function reportBack(params) {
24439
- const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, testsCorrected, codegenLoop, unresolved } = params;
24439
+ const { callbackUrl, runToken, status, branch, warnings, targeting, baselineFindings, vanishedTests, unsuppliedInputs, changesNoTestDependsOn, testsCorrected, codegenLoop, unresolved, aiCostUsd } = params;
24440
24440
  const body = { status };
24441
24441
  if (branch) body.branch = branch;
24442
24442
  if (warnings && warnings.length > 0) body.warnings = warnings;
@@ -24448,6 +24448,7 @@ async function reportBack(params) {
24448
24448
  if (changesNoTestDependsOn && changesNoTestDependsOn.hunks.length > 0) body.changesNoTestDependsOn = changesNoTestDependsOn;
24449
24449
  if (testsCorrected && testsCorrected.files.length > 0) body.testsCorrected = testsCorrected;
24450
24450
  if (codegenLoop) body.codegenLoop = codegenLoop;
24451
+ if (typeof aiCostUsd === "number" && Number.isFinite(aiCostUsd) && aiCostUsd > 0) body.aiCostUsd = Math.round(aiCostUsd * 1e6) / 1e6;
24451
24452
  const res = await fetch(callbackUrl, {
24452
24453
  method: "POST",
24453
24454
  headers: { Authorization: `Bearer ${runToken}`, "Content-Type": "application/json" },
@@ -26348,6 +26349,144 @@ function commitAndPush(branch, runId, installationToken, targeted, issueKey, iss
26348
26349
  return { changed: true, branch };
26349
26350
  }
26350
26351
 
26352
+ // src/tokenEstimate.ts
26353
+ var TOKENS_PER_ALPHA_CHAR = 0.3;
26354
+ var TOKENS_PER_DIGIT_CHAR = 0.18;
26355
+ var TOKENS_PER_SPACE_CHAR = 0.05;
26356
+ var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
26357
+ var TOKENS_PER_NON_ASCII_CHAR = 1;
26358
+ var PROMPT_OVERHEAD_TOKENS = 5e3;
26359
+ function estimateTokens(text) {
26360
+ let alpha = 0;
26361
+ let digit = 0;
26362
+ let space = 0;
26363
+ let punct = 0;
26364
+ let nonAscii = 0;
26365
+ for (const ch of text) {
26366
+ const code = ch.codePointAt(0);
26367
+ if (code >= 128) nonAscii++;
26368
+ else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
26369
+ else if (code >= 48 && code <= 57) digit++;
26370
+ else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
26371
+ else punct++;
26372
+ }
26373
+ return Math.ceil(
26374
+ alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
26375
+ );
26376
+ }
26377
+ function estimateRequestTokens(contextData) {
26378
+ return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
26379
+ }
26380
+
26381
+ // src/turnUsage.ts
26382
+ var MAX_TURN_ROWS = 30;
26383
+ var num = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0 ? v : void 0;
26384
+ function usageOf(envelope) {
26385
+ if (typeof envelope !== "object" || envelope === null) return {};
26386
+ const e = envelope;
26387
+ const tokensIn = num(e.tokensInput);
26388
+ const tokensOut = num(e.tokensOutput);
26389
+ const costUsd = num(e.costEstimateUsd);
26390
+ const ms = num(e.latencyMs);
26391
+ return {
26392
+ ...tokensIn !== void 0 ? { tokensIn: Math.round(tokensIn) } : {},
26393
+ ...tokensOut !== void 0 ? { tokensOut: Math.round(tokensOut) } : {},
26394
+ ...costUsd !== void 0 ? { costUsd } : {},
26395
+ ...ms !== void 0 ? { ms: Math.round(ms) } : {}
26396
+ };
26397
+ }
26398
+ var sizeOf = (value) => value === void 0 ? 0 : estimateTokens(JSON.stringify(value, null, 2));
26399
+ var RESULT_KEYS = /* @__PURE__ */ new Set(["transcript", "toolResults", "previousAttempt"]);
26400
+ function requestParts(contextData) {
26401
+ const parts = { fixed: PROMPT_OVERHEAD_TOKENS, map: 0, cases: 0, task: 0, results: 0, notes: 0, other: 0 };
26402
+ for (const [key, value] of Object.entries(contextData)) {
26403
+ if (key === "repoMap" || key === "workspaceListing") parts.map += sizeOf(value);
26404
+ else if (key === "requiredTests") parts.cases += sizeOf(value);
26405
+ else if (key === "loop" && typeof value === "object" && value !== null && !Array.isArray(value)) {
26406
+ for (const [loopKey, loopValue] of Object.entries(value)) {
26407
+ if (RESULT_KEYS.has(loopKey)) parts.results += sizeOf(loopValue);
26408
+ else if (loopKey === "recap") parts.notes += sizeOf(loopValue);
26409
+ else parts.other += sizeOf(loopValue);
26410
+ }
26411
+ } else parts.task += sizeOf(value);
26412
+ }
26413
+ return parts;
26414
+ }
26415
+ var TurnUsage = class {
26416
+ rows = [];
26417
+ rowsCut = false;
26418
+ totals = { calls: 0, tokensIn: 0, tokensOut: 0, costUsd: 0 };
26419
+ record(turn, contextData, estTokens, envelope, elapsedMs) {
26420
+ const used = usageOf(envelope);
26421
+ this.totals.calls += 1;
26422
+ this.totals.tokensIn += used.tokensIn ?? 0;
26423
+ this.totals.tokensOut += used.tokensOut ?? 0;
26424
+ this.totals.costUsd += used.costUsd ?? 0;
26425
+ if (this.rows.length >= MAX_TURN_ROWS) {
26426
+ this.rowsCut = true;
26427
+ return;
26428
+ }
26429
+ this.rows.push({
26430
+ turn,
26431
+ estTokens,
26432
+ parts: requestParts(contextData),
26433
+ ...used.tokensIn !== void 0 ? { tokensIn: used.tokensIn } : {},
26434
+ ...used.tokensOut !== void 0 ? { tokensOut: used.tokensOut } : {},
26435
+ ...used.costUsd !== void 0 ? { costUsd: used.costUsd } : {},
26436
+ seconds: Math.max(0, Math.round(elapsedMs / 1e3))
26437
+ });
26438
+ }
26439
+ };
26440
+ function addTotals(a, b) {
26441
+ return {
26442
+ calls: (a?.calls ?? 0) + (b?.calls ?? 0),
26443
+ tokensIn: (a?.tokensIn ?? 0) + (b?.tokensIn ?? 0),
26444
+ tokensOut: (a?.tokensOut ?? 0) + (b?.tokensOut ?? 0),
26445
+ costUsd: (a?.costUsd ?? 0) + (b?.costUsd ?? 0)
26446
+ };
26447
+ }
26448
+ var whole = (n, max) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n), max) : 0;
26449
+ var money = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.min(Math.round(n * 1e6) / 1e6, 1e3) : 0;
26450
+ function clampTurnRows(rows) {
26451
+ if (!rows || rows.length === 0) return void 0;
26452
+ return rows.slice(0, MAX_TURN_ROWS).map((r) => ({
26453
+ turn: whole(r.turn, 1e3),
26454
+ estTokens: whole(r.estTokens, 1e7),
26455
+ parts: {
26456
+ fixed: whole(r.parts.fixed, 1e7),
26457
+ map: whole(r.parts.map, 1e7),
26458
+ cases: whole(r.parts.cases, 1e7),
26459
+ task: whole(r.parts.task, 1e7),
26460
+ results: whole(r.parts.results, 1e7),
26461
+ notes: whole(r.parts.notes, 1e7),
26462
+ other: whole(r.parts.other, 1e7)
26463
+ },
26464
+ ...r.tokensIn !== void 0 ? { tokensIn: whole(r.tokensIn, 1e7) } : {},
26465
+ ...r.tokensOut !== void 0 ? { tokensOut: whole(r.tokensOut, 1e7) } : {},
26466
+ ...r.costUsd !== void 0 ? { costUsd: money(r.costUsd) } : {},
26467
+ seconds: whole(r.seconds, 1e5)
26468
+ }));
26469
+ }
26470
+ function clampTotals(t) {
26471
+ if (!t || t.calls <= 0) return void 0;
26472
+ return { calls: whole(t.calls, 1e4), tokensIn: whole(t.tokensIn, 1e8), tokensOut: whole(t.tokensOut, 1e8), costUsd: money(t.costUsd) };
26473
+ }
26474
+
26475
+ // src/aiSpend.ts
26476
+ var EMPTY = { calls: 0, tokensIn: 0, tokensOut: 0, costUsd: 0 };
26477
+ var byStep = { targeting: { ...EMPTY }, codegen: { ...EMPTY }, investigate: { ...EMPTY } };
26478
+ function noteSpend(envelope, step) {
26479
+ const used = usageOf(envelope);
26480
+ byStep[step] = addTotals(byStep[step], { calls: 1, tokensIn: used.tokensIn ?? 0, tokensOut: used.tokensOut ?? 0, costUsd: used.costUsd ?? 0 });
26481
+ return envelope;
26482
+ }
26483
+ function spendOf(step) {
26484
+ return { ...byStep[step] };
26485
+ }
26486
+ function spendSoFar() {
26487
+ return addTotals(addTotals(byStep.targeting, byStep.codegen), byStep.investigate);
26488
+ }
26489
+
26351
26490
  // src/codegen.ts
26352
26491
  var import_node_fs7 = require("node:fs");
26353
26492
  var import_node_path9 = require("node:path");
@@ -26884,7 +27023,7 @@ async function runCodegen(gateway, targets, workspaceListing, requiredTests, den
26884
27023
  if (!res.ok) {
26885
27024
  throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);
26886
27025
  }
26887
- let envelope = await res.json();
27026
+ let envelope = noteSpend(await res.json(), "codegen");
26888
27027
  checkHardFailure(envelope, "pilot.codegen", target.path);
26889
27028
  if (envelope?.errorCode === JUDGED_BY_TOO_LARGE_CODE && contextData.judgedBy) {
26890
27029
  const before = contextData.judgedBy.length;
@@ -26899,7 +27038,7 @@ async function runCodegen(gateway, targets, workspaceListing, requiredTests, den
26899
27038
  if (!res.ok) {
26900
27039
  throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);
26901
27040
  }
26902
- envelope = await res.json();
27041
+ envelope = noteSpend(await res.json(), "codegen");
26903
27042
  checkHardFailure(envelope, "pilot.codegen", target.path);
26904
27043
  }
26905
27044
  if (envelope?.errorCode === CONTEXT_TOO_LARGE_CODE && added.entries.length > 0) {
@@ -26912,7 +27051,7 @@ async function runCodegen(gateway, targets, workspaceListing, requiredTests, den
26912
27051
  if (!res.ok) {
26913
27052
  throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);
26914
27053
  }
26915
- envelope = await res.json();
27054
+ envelope = noteSpend(await res.json(), "codegen");
26916
27055
  checkHardFailure(envelope, "pilot.codegen", target.path);
26917
27056
  }
26918
27057
  throwOnTerminalRefusal(envelope, target.path);
@@ -26964,14 +27103,14 @@ async function runCodegen(gateway, targets, workspaceListing, requiredTests, den
26964
27103
  if (!res.ok) {
26965
27104
  throw new Error(`Codegen call failed for ${target.path}: ${res.status} ${res.statusText}`);
26966
27105
  }
26967
- envelope = await res.json();
27106
+ envelope = noteSpend(await res.json(), "codegen");
26968
27107
  checkHardFailure(envelope, "pilot.codegen", target.path);
26969
27108
  throwOnTerminalRefusal(envelope, target.path);
26970
- const whole3 = unwrapExecute(envelope, "pilot.codegen");
26971
- if (whole3.outcome !== "GENERATED" || typeof whole3.newContent !== "string") {
26972
- throw codegenRefusedError(target.path, whole3);
27109
+ const whole4 = unwrapExecute(envelope, "pilot.codegen");
27110
+ if (whole4.outcome !== "GENERATED" || typeof whole4.newContent !== "string") {
27111
+ throw codegenRefusedError(target.path, whole4);
26973
27112
  }
26974
- newContent = whole3.newContent;
27113
+ newContent = whole4.newContent;
26975
27114
  } catch (error) {
26976
27115
  if (error instanceof RuntimeReplyError) {
26977
27116
  throw new RuntimeReplyError(
@@ -34418,6 +34557,7 @@ function executeToolCall(call, env2, ledger) {
34418
34557
  return finish({ status: "duplicate", reason: earlier, message: "Identical call already made; see its result." });
34419
34558
  }
34420
34559
  ledger.seen.set(dupKey, call.id);
34560
+ (ledger.keys ??= /* @__PURE__ */ new Map()).set(call.id, dupKey);
34421
34561
  let executed;
34422
34562
  try {
34423
34563
  executed = prepared.exec();
@@ -34425,6 +34565,10 @@ function executeToolCall(call, env2, ledger) {
34425
34565
  executed = { result: { status: "unreadable", reason: "io", message: "That could not be read." } };
34426
34566
  }
34427
34567
  if (env2.scrub) executed = { ...executed, result: scrubAnswer(call.name, executed.result, env2.scrub) };
34568
+ if (env2.guidance && call.name === "read_file" && executed.result.status === "ok" && executed.read && isPlainObject(executed.result.output)) {
34569
+ const guidance = env2.guidance.forRead(executed.read.path);
34570
+ if (guidance) executed = { ...executed, result: { ...executed.result, output: { ...executed.result.output, guidance } } };
34571
+ }
34428
34572
  if ((call.name === "edit_file" || call.name === "write_file" || call.name === "revert_file") && executed.result.status !== "ok") ledger.seen.delete(dupKey);
34429
34573
  if (env2.serveRepeats === true && ledger.seen.has(dupKey)) (ledger.answers ??= /* @__PURE__ */ new Map()).set(call.id, executed.result);
34430
34574
  return finish(executed.result, executed.read);
@@ -35361,6 +35505,152 @@ function ambiguousPlacesMessage(lf, starts, total) {
35361
35505
  return `${header}${parts.join(", ")}. ${TAIL}`;
35362
35506
  }
35363
35507
 
35508
+ // src/loopNotes.ts
35509
+ var NOTES_KEPT_CHARS = 1500;
35510
+ var KEEP_TURNS = 3;
35511
+ var MAX_STUB_NOTE_CHARS = 200;
35512
+ var MAX_RECAP_CASES = 50;
35513
+ var MAX_RECAP_ID_CHARS = 40;
35514
+ var MAX_RECAP_TITLE_CHARS = 200;
35515
+ var MAX_RECAP_ROOTS = 20;
35516
+ var MAX_RECAP_ROOT_CHARS = 300;
35517
+ var GUIDANCE_NAMES = ["AGENTS.md", "CLAUDE.md", "README.md"];
35518
+ var GUIDANCE_TEXT_CHARS = 2e3;
35519
+ var GUIDANCE_PER_RUN = 6;
35520
+ var LOOK_TOOLS = /* @__PURE__ */ new Set(["list_files", "read_file", "grep", "find_definition"]);
35521
+ function cutText(text, max) {
35522
+ if (text.length <= max) return text;
35523
+ let out = text.slice(0, max);
35524
+ const last = out.charCodeAt(out.length - 1);
35525
+ if (last >= 55296 && last <= 56319) out = out.slice(0, -1);
35526
+ return out;
35527
+ }
35528
+ function keepNotes(kept, reply, scrub) {
35529
+ if (typeof reply !== "string") return kept;
35530
+ const cleaned = (scrub ? scrub(reply) : reply).trim();
35531
+ return cutText(cleaned, NOTES_KEPT_CHARS).trim();
35532
+ }
35533
+ function buildRecap(i2) {
35534
+ const cases = [];
35535
+ const required2 = i2.baseContext.requiredTests;
35536
+ if (Array.isArray(required2)) {
35537
+ for (const entry of required2) {
35538
+ if (cases.length >= MAX_RECAP_CASES) break;
35539
+ if (typeof entry !== "object" || entry === null) continue;
35540
+ const { automationId, title } = entry;
35541
+ if (typeof automationId !== "string" || automationId.length === 0) continue;
35542
+ cases.push({
35543
+ automationId: cutText(automationId, MAX_RECAP_ID_CHARS),
35544
+ title: typeof title === "string" ? cutText(title, MAX_RECAP_TITLE_CHARS) : ""
35545
+ });
35546
+ }
35547
+ }
35548
+ const writeRoots = i2.writeRoots.filter((r) => r.length > 0 && r.length <= MAX_RECAP_ROOT_CHARS).slice(0, MAX_RECAP_ROOTS);
35549
+ return { cases, writeRoots, ...i2.notes.length > 0 ? { notes: i2.notes } : {} };
35550
+ }
35551
+ function argOf(args, key) {
35552
+ return typeof args === "object" && args !== null ? args[key] : void 0;
35553
+ }
35554
+ function textArg(args, key, max) {
35555
+ const v = argOf(args, key);
35556
+ return typeof v === "string" ? cutText(v.replace(/\s+/g, " ").trim(), max) : "";
35557
+ }
35558
+ function stubNoteFor(call) {
35559
+ let note;
35560
+ if (call.name === "read_file") {
35561
+ const path = textArg(call.args, "path", 120);
35562
+ const start = argOf(call.args, "startLine");
35563
+ const end = argOf(call.args, "endLine");
35564
+ note = argOf(call.args, "mode") === "outline" ? `outline of ${path}` : typeof start === "number" && typeof end === "number" ? `read ${path} lines ${start}-${end}` : typeof start === "number" ? `read ${path} from line ${start}` : `read the start of ${path}`;
35565
+ } else if (call.name === "list_files") {
35566
+ const path = textArg(call.args, "path", 80) || "the repository";
35567
+ const pattern = textArg(call.args, "pattern", 60);
35568
+ note = pattern ? `found files named ${pattern} under ${path}` : `listed ${path}`;
35569
+ } else if (call.name === "grep") {
35570
+ const path = textArg(call.args, "path", 60);
35571
+ const lines = argOf(call.args, "mode") === "lines" ? " (lines)" : "";
35572
+ note = `searched for ${JSON.stringify(textArg(call.args, "pattern", 60))}${path ? ` in ${path}` : ""}${lines}`;
35573
+ } else if (call.name === "find_definition") {
35574
+ note = `looked up ${textArg(call.args, "name", 80)}`;
35575
+ } else {
35576
+ note = call.name;
35577
+ }
35578
+ return cutText(note, MAX_STUB_NOTE_CHARS);
35579
+ }
35580
+ function isStubbed(output) {
35581
+ return typeof output === "object" && output !== null && output.dropped === true;
35582
+ }
35583
+ function stubOldLooks(i2) {
35584
+ let shrunk = 0;
35585
+ for (let index = 0; index < i2.results.length; index++) {
35586
+ const r = i2.results[index];
35587
+ if (!LOOK_TOOLS.has(r.name) || r.status !== "ok" || r.output === void 0 || isStubbed(r.output)) continue;
35588
+ const turn = i2.turnOf(r.id);
35589
+ if (turn === void 0 || turn > i2.currentTurn - KEEP_TURNS) continue;
35590
+ const call = i2.callOf(r.id);
35591
+ if (!call) continue;
35592
+ i2.results[index] = { ...r, output: { dropped: true, note: stubNoteFor(call) } };
35593
+ const key = i2.ledger.keys?.get(r.id);
35594
+ if (key !== void 0 && i2.ledger.seen.get(key) === r.id) i2.ledger.seen.delete(key);
35595
+ i2.ledger.answers?.delete(r.id);
35596
+ shrunk += 1;
35597
+ }
35598
+ return shrunk;
35599
+ }
35600
+ function foldersAbove(path) {
35601
+ const parts = path.split("/");
35602
+ parts.pop();
35603
+ const out = [];
35604
+ while (parts.length > 0) {
35605
+ out.push(parts.join("/"));
35606
+ parts.pop();
35607
+ }
35608
+ return out;
35609
+ }
35610
+ function makeGuidanceFinder(i2) {
35611
+ const given = new Set(i2.alreadyShown ?? []);
35612
+ const done = new Set([...given].map((p) => p.slice(0, Math.max(0, p.lastIndexOf("/")))));
35613
+ let count3 = 0;
35614
+ return {
35615
+ shown: () => count3,
35616
+ forRead(path) {
35617
+ if (count3 >= GUIDANCE_PER_RUN) return void 0;
35618
+ for (const folder of foldersAbove(path)) {
35619
+ if (done.has(folder)) continue;
35620
+ for (const name of GUIDANCE_NAMES) {
35621
+ const candidate = `${folder}/${name}`;
35622
+ if (given.has(candidate) || !i2.listing.has(candidate) || i2.isDenied(candidate)) continue;
35623
+ const raw = i2.readText(candidate);
35624
+ given.add(candidate);
35625
+ if (raw === null) continue;
35626
+ const text = cutText((i2.scrub ? i2.scrub(raw) : raw).trim(), GUIDANCE_TEXT_CHARS);
35627
+ if (text.length === 0) continue;
35628
+ done.add(folder);
35629
+ count3 += 1;
35630
+ return { path: candidate, text };
35631
+ }
35632
+ }
35633
+ return void 0;
35634
+ }
35635
+ };
35636
+ }
35637
+ function readFileText(fs, path) {
35638
+ try {
35639
+ const st = fs.lstat(path);
35640
+ if (!st || st.isSymlink || !st.isFile || st.size > 2e5 || !fs.realpathInside(path)) return null;
35641
+ const bytes = fs.readBytes(path);
35642
+ return bytes ? new TextDecoder("utf-8").decode(bytes) : null;
35643
+ } catch {
35644
+ return null;
35645
+ }
35646
+ }
35647
+ function clampNotesRecord(n) {
35648
+ if (typeof n !== "object" || n === null) return void 0;
35649
+ const { chars, stubbed, guidance } = n;
35650
+ const whole4 = (v, max) => typeof v === "number" && Number.isInteger(v) && v >= 0 ? Math.min(v, max) : 0;
35651
+ return { chars: whole4(chars, NOTES_KEPT_CHARS), stubbed: whole4(stubbed, 1e5), guidance: whole4(guidance, GUIDANCE_PER_RUN) };
35652
+ }
35653
+
35364
35654
  // ../../../../quikit1926/node_modules/eslint-scope/lib/index.js
35365
35655
  var import_assert4 = __toESM(require("assert"), 1);
35366
35656
 
@@ -36773,9 +37063,9 @@ function placementWhy(find, k, added) {
36773
37063
  if (!DECLARES_TEST.test(added)) return "not_a_test_or_import";
36774
37064
  return bracketsBalance(added) ? null : "unbalanced_block";
36775
37065
  }
36776
- function isSubsequence(part, whole3) {
37066
+ function isSubsequence(part, whole4) {
36777
37067
  let i2 = 0;
36778
- for (let j = 0; j < whole3.length && i2 < part.length; j++) if (whole3.charCodeAt(j) === part.charCodeAt(i2)) i2++;
37068
+ for (let j = 0; j < whole4.length && i2 < part.length; j++) if (whole4.charCodeAt(j) === part.charCodeAt(i2)) i2++;
36779
37069
  return i2 === part.length;
36780
37070
  }
36781
37071
  function lostTextWhy(find, replace) {
@@ -38990,6 +39280,16 @@ function createCodegenWorkspace(args) {
38990
39280
  ...args.scrub ? { scrub: args.scrub } : {},
38991
39281
  ...args.readRoots ? { readRoots: args.readRoots } : {},
38992
39282
  ...args.tools2 ? { tools2: args.tools2 } : {},
39283
+ // Section 37: the first read under a folder that has its own guidance file carries it, once (read from disk: a guidance file is not edited here).
39284
+ ...args.tools2?.notes === true ? {
39285
+ guidance: makeGuidanceFinder({
39286
+ listing,
39287
+ readText: (p) => readFileText(baseFs, p),
39288
+ isDenied: (p) => matchesDeniedPath(p, readDenied(args.deniedPaths)) !== null,
39289
+ ...args.scrub ? { scrub: args.scrub } : {},
39290
+ alreadyShown: args.shownGuidance ?? []
39291
+ })
39292
+ } : {},
38993
39293
  extraTools: {
38994
39294
  edit_file: prepareEdit,
38995
39295
  write_file: prepareWrite,
@@ -39224,40 +39524,12 @@ var TargetingHttpError = class extends Error {
39224
39524
  }
39225
39525
  };
39226
39526
 
39227
- // src/tokenEstimate.ts
39228
- var TOKENS_PER_ALPHA_CHAR = 0.3;
39229
- var TOKENS_PER_DIGIT_CHAR = 0.18;
39230
- var TOKENS_PER_SPACE_CHAR = 0.05;
39231
- var TOKENS_PER_PUNCTUATION_CHAR = 1.05;
39232
- var TOKENS_PER_NON_ASCII_CHAR = 1;
39233
- var PROMPT_OVERHEAD_TOKENS = 5e3;
39234
- function estimateTokens(text) {
39235
- let alpha = 0;
39236
- let digit = 0;
39237
- let space = 0;
39238
- let punct = 0;
39239
- let nonAscii = 0;
39240
- for (const ch of text) {
39241
- const code = ch.codePointAt(0);
39242
- if (code >= 128) nonAscii++;
39243
- else if (code >= 65 && code <= 90 || code >= 97 && code <= 122) alpha++;
39244
- else if (code >= 48 && code <= 57) digit++;
39245
- else if (code === 32 || code === 9 || code === 13 || code === 10) space++;
39246
- else punct++;
39247
- }
39248
- return Math.ceil(
39249
- alpha * TOKENS_PER_ALPHA_CHAR + digit * TOKENS_PER_DIGIT_CHAR + space * TOKENS_PER_SPACE_CHAR + punct * TOKENS_PER_PUNCTUATION_CHAR + nonAscii * TOKENS_PER_NON_ASCII_CHAR
39250
- );
39251
- }
39252
- function estimateRequestTokens(contextData) {
39253
- return PROMPT_OVERHEAD_TOKENS + estimateTokens(JSON.stringify(contextData ?? {}, null, 2));
39254
- }
39255
-
39256
39527
  // src/turnTimeout.ts
39257
39528
  var FIRST_TURN_TIMEOUT_MS = 42e4;
39258
- function turnTimeoutFor(turn, perTurnMs, setByCaller) {
39529
+ var INVESTIGATE_FIRST_TURN_TIMEOUT_MS = 15e4;
39530
+ function turnTimeoutFor(turn, perTurnMs, setByCaller, firstTurnMs = FIRST_TURN_TIMEOUT_MS) {
39259
39531
  if (setByCaller || turn > 1) return perTurnMs;
39260
- return Math.max(perTurnMs, FIRST_TURN_TIMEOUT_MS);
39532
+ return Math.max(perTurnMs, firstTurnMs);
39261
39533
  }
39262
39534
 
39263
39535
  // src/targetingLoop.ts
@@ -39265,6 +39537,7 @@ var LOOP_CONTRACT_VERSION = "targeting-loop-1";
39265
39537
  var MAP_LOOP_CONTRACT_VERSION = "targeting-loop-2";
39266
39538
  var TOOLS2_LOOP_CONTRACT_VERSION = "targeting-loop-3";
39267
39539
  var TOOLS2_LOOP_TOOLS = ["list_files", "read_file", "grep", "find_definition"];
39540
+ var NOTES_LOOP_CONTRACT_VERSION = "targeting-loop-4";
39268
39541
  var LoopFailure = class extends Error {
39269
39542
  reason;
39270
39543
  runtimeCode;
@@ -39322,6 +39595,22 @@ async function runTargetingLoop(args, deps) {
39322
39595
  ...args.readRoots ? { readRoots: args.readRoots } : {},
39323
39596
  ...args.tools2 ? { tools2: args.tools2 } : {}
39324
39597
  };
39598
+ const notesOn = args.tools2?.notes === true;
39599
+ if (notesOn) {
39600
+ const denied = readDenied(args.deniedPaths);
39601
+ const shownInMap = args.baseContext.repoMap?.guidance;
39602
+ env2.guidance = makeGuidanceFinder({
39603
+ listing: env2.listing,
39604
+ readText: (path) => readFileText(env2.fs, path),
39605
+ isDenied: (path) => matchesDeniedPath(path, denied) !== null,
39606
+ ...env2.scrub ? { scrub: env2.scrub } : {},
39607
+ alreadyShown: (Array.isArray(shownInMap) ? shownInMap : []).map((g) => g.path).filter((p) => typeof p === "string")
39608
+ });
39609
+ }
39610
+ let notes = "";
39611
+ let stubbed = 0;
39612
+ const turnOfId = /* @__PURE__ */ new Map();
39613
+ const callOfId = /* @__PURE__ */ new Map();
39325
39614
  const ledger = newLedger();
39326
39615
  const reads = [];
39327
39616
  const transcript = [];
@@ -39330,6 +39619,7 @@ async function runTargetingLoop(args, deps) {
39330
39619
  const refusedTurns = [];
39331
39620
  let refusedStreak = 0;
39332
39621
  let peakRequestTokens = 0;
39622
+ const usage = new TurnUsage();
39333
39623
  let turns = 0;
39334
39624
  let noProgressStreak = 0;
39335
39625
  let forced = null;
@@ -39350,7 +39640,9 @@ async function runTargetingLoop(args, deps) {
39350
39640
  },
39351
39641
  transcript,
39352
39642
  toolResults,
39353
- ...args.tools2 ? { tools: [...TOOLS2_LOOP_TOOLS] } : {}
39643
+ ...args.tools2 ? { tools: [...TOOLS2_LOOP_TOOLS] } : {},
39644
+ // Section 37: LAST in `loop`, so the end of the request repeats the cases, the folders the AI may change and its own notes.
39645
+ ...notesOn ? { recap: buildRecap({ baseContext: args.baseContext, writeRoots: args.tools2?.writeRoots ?? [], notes }) } : {}
39354
39646
  }
39355
39647
  });
39356
39648
  const snapshot = (stopReason) => ({
@@ -39362,7 +39654,10 @@ async function runTargetingLoop(args, deps) {
39362
39654
  reads: [...reads],
39363
39655
  ...refusedTurns.length > 0 ? { refusedTurns: refusedTurns.map((t) => ({ turn: t.turn, rules: [...t.rules] })) } : {},
39364
39656
  ...peakRequestTokens > 0 ? { peakRequestTokens } : {},
39365
- ...args.tools2 ? { contractVersion: args.contractVersion ?? TOOLS2_LOOP_CONTRACT_VERSION } : {}
39657
+ ...args.tools2 ? { contractVersion: args.contractVersion ?? TOOLS2_LOOP_CONTRACT_VERSION } : {},
39658
+ ...notesOn ? { notes: { chars: notes.length, stubbed, guidance: env2.guidance?.shown() ?? 0 } } : {},
39659
+ ...usage.totals.calls > 0 ? { turnUsage: usage.rows.map((r) => ({ ...r, parts: { ...r.parts } })), usage: { ...usage.totals } } : {},
39660
+ ...usage.rowsCut ? { turnUsageCut: true } : {}
39366
39661
  });
39367
39662
  log({ event: "targeting.loop_start", mode: "loop", maxTurns: limits.maxTurns, maxToolCalls: limits.maxToolCalls, listingFiles: args.listing.length });
39368
39663
  try {
@@ -39386,6 +39681,7 @@ async function runTargetingLoop(args, deps) {
39386
39681
  } catch (err) {
39387
39682
  throw classifyTransport(err);
39388
39683
  }
39684
+ usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
39389
39685
  const code = envelope?.errorCode;
39390
39686
  try {
39391
39687
  checkHardFailure(envelope, "pilot.targeting");
@@ -39483,6 +39779,14 @@ async function runTargetingLoop(args, deps) {
39483
39779
  });
39484
39780
  toolResults.push(...results);
39485
39781
  refusedStreak = 0;
39782
+ if (notesOn) {
39783
+ for (const c of calls) {
39784
+ turnOfId.set(c.id, turn);
39785
+ callOfId.set(c.id, { name: c.name, args: c.args });
39786
+ }
39787
+ notes = keepNotes(notes, body.notes, env2.scrub);
39788
+ stubbed += stubOldLooks({ results: toolResults, turnOf: (id) => turnOfId.get(id), callOf: (id) => callOfId.get(id), currentTurn: turn, ledger });
39789
+ }
39486
39790
  noProgressStreak = results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
39487
39791
  if (noProgressStreak >= 2) forced = "no_progress";
39488
39792
  else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
@@ -39539,6 +39843,7 @@ var CODEGEN_LOOP_2_CONTRACT_VERSION = "codegen-loop-2";
39539
39843
  var CODEGEN_LOOP_3_CONTRACT_VERSION = "codegen-loop-3";
39540
39844
  var CODEGEN_LOOP_4_CONTRACT_VERSION = "codegen-loop-4";
39541
39845
  var CODEGEN_LOOP_5_CONTRACT_VERSION = "codegen-loop-5";
39846
+ var CODEGEN_LOOP_6_CONTRACT_VERSION = "codegen-loop-6";
39542
39847
  var MAP_SOFT_REQUEST_TOKENS = 4e4;
39543
39848
  var CodegenLoopFailure = class extends Error {
39544
39849
  reason;
@@ -39608,13 +39913,18 @@ function isTestAnswer(x) {
39608
39913
  return isPlainObject3(x) && typeof x.passed === "number" && Array.isArray(x.failingTests);
39609
39914
  }
39610
39915
  var DROPPED_OUTPUT = { dropped: true, note: "Dropped to keep the request small. Read the file again if you need it." };
39916
+ function repoMapGuidancePaths(baseContext) {
39917
+ const map = baseContext.repoMap;
39918
+ return (Array.isArray(map?.guidance) ? map.guidance : []).map((g) => g.path).filter((p) => typeof p === "string");
39919
+ }
39611
39920
  async function runCodegenLoop(args, deps) {
39921
+ const scrub = makeCodeScrubber(deps.secrets ?? [], (c) => (deps.log ?? ((e) => console.log(JSON.stringify(e))))({ event: "loop.scrubbed", ...nonZero(c) }));
39612
39922
  const ws = createCodegenWorkspace({
39613
- // S2b: credentials in what a tool answers are hidden (the AI's own writes are not touched).
39614
- scrub: makeCodeScrubber(deps.secrets ?? [], (c) => (deps.log ?? ((e) => console.log(JSON.stringify(e))))({ event: "loop.scrubbed", ...nonZero(c) })),
39923
+ scrub,
39615
39924
  listing: args.readListing ?? args.listing,
39616
39925
  ...args.readRoots ? { readRoots: args.readRoots } : {},
39617
39926
  ...args.tools2 && args.tests !== void 0 && args.harness === true ? { tools2: args.tools2 } : {},
39927
+ ...args.tools2?.notes === true && args.tests !== void 0 && args.harness === true ? { shownGuidance: repoMapGuidancePaths(args.baseContext) } : {},
39618
39928
  deniedPaths: args.deniedPaths,
39619
39929
  protectedTestPaths: args.protectedTestPaths,
39620
39930
  ...args.discoveredTests ? { discoveredTests: args.discoveredTests } : {},
@@ -39656,8 +39966,14 @@ async function runCodegenLoop(args, deps) {
39656
39966
  log,
39657
39967
  now
39658
39968
  }) : null;
39659
- const contractVersion = harness ? args.tools2 ? CODEGEN_LOOP_5_CONTRACT_VERSION : args.readRoots ? CODEGEN_LOOP_4_CONTRACT_VERSION : CODEGEN_LOOP_3_CONTRACT_VERSION : tests ? CODEGEN_LOOP_2_CONTRACT_VERSION : CODEGEN_LOOP_CONTRACT_VERSION;
39969
+ const notesOn = harness && args.tools2?.notes === true;
39970
+ const contractVersion = harness ? args.tools2 ? notesOn ? CODEGEN_LOOP_6_CONTRACT_VERSION : CODEGEN_LOOP_5_CONTRACT_VERSION : args.readRoots ? CODEGEN_LOOP_4_CONTRACT_VERSION : CODEGEN_LOOP_3_CONTRACT_VERSION : tests ? CODEGEN_LOOP_2_CONTRACT_VERSION : CODEGEN_LOOP_CONTRACT_VERSION;
39660
39971
  let peakRequestTokens = 0;
39972
+ const usage = new TurnUsage();
39973
+ let notes = "";
39974
+ let stubbed = 0;
39975
+ const turnOfId = /* @__PURE__ */ new Map();
39976
+ const callOfId = /* @__PURE__ */ new Map();
39661
39977
  const previousAttempt = args.previousAttempt && !harness ? previousForLoop2(args.previousAttempt) : args.previousAttempt;
39662
39978
  if (tests && args.seed && args.seed.length > 0) tests.markSeen(versionOfFiles(filesOnDisk()));
39663
39979
  let testMs = 0;
@@ -39742,7 +40058,9 @@ async function runCodegenLoop(args, deps) {
39742
40058
  transcript,
39743
40059
  toolResults,
39744
40060
  // QUIKTR-1581 (§36): the tools this run offers, in the order the AI Runtime lists them. `call_function` only where it is on.
39745
- ...args.tools2 && harness ? { tools: ["list_files", "read_file", "grep", "find_definition", "edit_file", "write_file", "run_tests", ...fn ? ["call_function"] : [], "show_changes", "revert_file"] } : {}
40061
+ ...args.tools2 && harness ? { tools: ["list_files", "read_file", "grep", "find_definition", "edit_file", "write_file", "run_tests", ...fn ? ["call_function"] : [], "show_changes", "revert_file"] } : {},
40062
+ // Section 37: LAST in `loop`, so the end of the request repeats the cases, the folders the AI may change and its own notes.
40063
+ ...notesOn ? { recap: buildRecap({ baseContext: args.baseContext, writeRoots: args.tools2?.writeRoots ?? [], notes }) } : {}
39746
40064
  }
39747
40065
  });
39748
40066
  const snapshot = (stopReason) => ({
@@ -39758,7 +40076,10 @@ async function runCodegenLoop(args, deps) {
39758
40076
  ...tests ? { contractVersion, testRuns: tests.record() } : {},
39759
40077
  ...refusedTurns.length > 0 ? { refusedTurns: refusedTurns.map((t) => ({ turn: t.turn, rules: [...t.rules] })) } : {},
39760
40078
  reasoning: [...reasoning],
39761
- ...args.repoView ? { repoView: args.repoView, peakRequestTokens } : {}
40079
+ ...args.repoView ? { repoView: args.repoView, peakRequestTokens } : {},
40080
+ ...notesOn ? { notes: { chars: notes.length, stubbed, guidance: env2.guidance?.shown() ?? 0 } } : {},
40081
+ ...usage.totals.calls > 0 ? { turnUsage: usage.rows.map((r) => ({ ...r, parts: { ...r.parts } })), usage: { ...usage.totals } } : {},
40082
+ ...usage.rowsCut ? { turnUsageCut: true } : {}
39762
40083
  });
39763
40084
  const makeRoom = (nextTurn, nextFinal, finalReason) => {
39764
40085
  const under = (limit) => estimateRequestTokens(buildContext(nextTurn, nextFinal, finalReason)) <= limit;
@@ -39856,6 +40177,7 @@ async function runCodegenLoop(args, deps) {
39856
40177
  } catch (err) {
39857
40178
  throw classifyTransport2(err);
39858
40179
  }
40180
+ usage.record(turn, contextData, requestTokens, envelope, now() - turnStarted);
39859
40181
  const code = envelope?.errorCode;
39860
40182
  try {
39861
40183
  checkHardFailure(envelope, "pilot.codegen");
@@ -40059,6 +40381,14 @@ async function runCodegenLoop(args, deps) {
40059
40381
  transcript.push({ turn, ...reasonText ? { reasoning: reasonText } : {}, toolCalls: calls.map((c) => ({ id: c.id, name: c.name, args: c.args })) });
40060
40382
  toolResults.push(...results);
40061
40383
  refusedStreak = 0;
40384
+ if (notesOn) {
40385
+ for (const c of calls) {
40386
+ turnOfId.set(c.id, turn);
40387
+ callOfId.set(c.id, { name: c.name, args: c.args });
40388
+ }
40389
+ notes = keepNotes(notes, body.notes, scrub);
40390
+ stubbed += stubOldLooks({ results: toolResults, turnOf: (id) => turnOfId.get(id), callOf: (id) => callOfId.get(id), currentTurn: turn, ledger });
40391
+ }
40062
40392
  noProgressStreak = harness ? results.every((r) => NOTHING_NEW.has(r.status)) ? noProgressStreak + 1 : 0 : results.every((r) => r.status === "duplicate") ? noProgressStreak + 1 : 0;
40063
40393
  if (noProgressStreak >= (harness ? HARNESS_NO_PROGRESS_TURNS : 2)) forced = "no_progress";
40064
40394
  else if (ledger.toolCalls >= limits.maxToolCalls) forced = "tool_budget";
@@ -40285,8 +40615,11 @@ function mergePhaseSummaries(parts, phases) {
40285
40615
  for (const [k, v] of Object.entries(summary.statusCounts)) statusCounts[k] = (statusCounts[k] ?? 0) + v;
40286
40616
  }
40287
40617
  let n = 0;
40288
- const testRuns = parts.flatMap(({ phase, summary }) => (summary.testRuns ?? []).map((t) => ({ ...t, n: ++n, phase })));
40618
+ const testRuns = parts.flatMap(({ phase, summary }) => (summary.testRuns ?? []).map((t2) => ({ ...t2, n: ++n, phase })));
40289
40619
  const refusedTurns = parts.flatMap(({ summary }) => summary.refusedTurns ?? []);
40620
+ let t = 0;
40621
+ const turnUsage = parts.flatMap(({ summary }) => (summary.turnUsage ?? []).map((r) => ({ ...r, turn: ++t })));
40622
+ const turnUsageCut = parts.some(({ summary }) => summary.turnUsageCut) || turnUsage.length > MAX_TURN_ROWS;
40290
40623
  return {
40291
40624
  ...last,
40292
40625
  turns: parts.reduce((s, p) => s + p.summary.turns, 0),
@@ -40300,7 +40633,9 @@ function mergePhaseSummaries(parts, phases) {
40300
40633
  ...testRuns.length > 0 ? { testRuns } : {},
40301
40634
  ...refusedTurns.length > 0 ? { refusedTurns } : {},
40302
40635
  reasoning: parts.flatMap((p) => p.summary.reasoning),
40303
- phases
40636
+ phases,
40637
+ ...turnUsage.length > 0 ? { turnUsage: turnUsage.slice(0, MAX_TURN_ROWS) } : {},
40638
+ ...turnUsageCut ? { turnUsageCut: true } : {}
40304
40639
  };
40305
40640
  }
40306
40641
 
@@ -40308,19 +40643,23 @@ function mergePhaseSummaries(parts, phases) {
40308
40643
  var MAX_ROOTS = 8;
40309
40644
  var MAX_ROOT_CHARS = 300;
40310
40645
  var MAX_REASON_CHARS2 = 40;
40311
- var whole = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
40646
+ var whole2 = (n) => typeof n === "number" && Number.isFinite(n) && n >= 0 ? Math.floor(n) : 0;
40312
40647
  function repoViewOf(scope) {
40313
- if (!scope || scope.view !== "map") return void 0;
40314
- return { view: "map", fileCount: scope.readListing.length, readRoots: [...scope.readRoots], mapTokens: scope.mapTokens ?? 0 };
40648
+ if (!scope) return void 0;
40649
+ if (scope.view !== "map") {
40650
+ return { view: "listing", writeRoot: scope.writeRoot, fileCount: scope.writeListing.length, readRoots: [scope.writeRoot] };
40651
+ }
40652
+ return { view: "map", writeRoot: scope.writeRoot, fileCount: scope.readListing.length, readRoots: [...scope.readRoots], mapTokens: scope.mapTokens ?? 0 };
40315
40653
  }
40316
40654
  function clampRepoView(facts, peakRequestTokens) {
40317
40655
  if (!facts) return {};
40318
40656
  return {
40319
- view: "map",
40320
- fileCount: whole(facts.fileCount),
40657
+ view: facts.view === "map" ? "map" : "listing",
40658
+ ...facts.writeRoot.length <= MAX_ROOT_CHARS ? { writeRoot: facts.writeRoot } : {},
40659
+ fileCount: whole2(facts.fileCount),
40321
40660
  readRoots: facts.readRoots.filter((r) => r.length <= MAX_ROOT_CHARS).slice(0, MAX_ROOTS),
40322
- mapTokens: whole(facts.mapTokens),
40323
- ...peakRequestTokens && peakRequestTokens > 0 ? { peakRequestTokens: whole(peakRequestTokens) } : {},
40661
+ ...facts.view === "map" ? { mapTokens: whole2(facts.mapTokens) } : {},
40662
+ ...peakRequestTokens && peakRequestTokens > 0 ? { peakRequestTokens: whole2(peakRequestTokens) } : {},
40324
40663
  ...facts.failReason ? { failReason: facts.failReason.slice(0, MAX_REASON_CHARS2) } : {}
40325
40664
  };
40326
40665
  }
@@ -40356,11 +40695,11 @@ function gateOf(g) {
40356
40695
  alreadyFailing: gateCount(x.alreadyFailing)
40357
40696
  };
40358
40697
  }
40359
- function whole2(n) {
40698
+ function whole3(n) {
40360
40699
  return typeof n === "number" && Number.isInteger(n) && n >= 0 ? n : 0;
40361
40700
  }
40362
40701
  function small(n) {
40363
- return Math.min(MAX_ATTEMPT_COUNT, whole2(n));
40702
+ return Math.min(MAX_ATTEMPT_COUNT, whole3(n));
40364
40703
  }
40365
40704
  function pathOk(p) {
40366
40705
  return typeof p === "string" && p.length > 0 && p.length <= MAX_RECORD_PATH_CHARS;
@@ -40386,14 +40725,14 @@ function buildCodegenLoopRecord(loop) {
40386
40725
  path: r.path.trim(),
40387
40726
  ...Number.isInteger(r.startLine) ? { startLine: r.startLine } : {},
40388
40727
  ...Number.isInteger(r.endLine) ? { endLine: r.endLine } : {},
40389
- chars: whole2(r.chars),
40728
+ chars: whole3(r.chars),
40390
40729
  ...r.refused ? { refused: true } : {}
40391
40730
  }));
40392
- const edits = room(loop.edits).map((e) => ({ path: e.path, count: whole2(e.count) }));
40393
- const created = room(loop.created).map((c) => ({ path: c.path, chars: whole2(c.chars) }));
40731
+ const edits = room(loop.edits).map((e) => ({ path: e.path, count: whole3(e.count) }));
40732
+ const created = room(loop.created).map((c) => ({ path: c.path, chars: whole3(c.chars) }));
40394
40733
  const statusCounts = {};
40395
40734
  for (const [k, v] of Object.entries(loop.statusCounts).slice(0, MAX_STATUS_KEYS)) {
40396
- if (k.length > 0 && k.length <= MAX_STATUS_KEY_CHARS) statusCounts[k] = whole2(v);
40735
+ if (k.length > 0 && k.length <= MAX_STATUS_KEY_CHARS) statusCounts[k] = whole3(v);
40397
40736
  else cut = true;
40398
40737
  }
40399
40738
  if (Object.keys(loop.statusCounts).length > MAX_STATUS_KEYS) cut = true;
@@ -40406,7 +40745,7 @@ function buildCodegenLoopRecord(loop) {
40406
40745
  const text = typeof r.text === "string" ? r.text.trim() : "";
40407
40746
  if (text.length === 0) continue;
40408
40747
  const over = text.length > MAX_RECORD_REASONING_CHARS;
40409
- reasoning.push({ turn: whole2(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...over ? { truncated: true } : {} });
40748
+ reasoning.push({ turn: whole3(r.turn), text: over ? text.slice(0, MAX_RECORD_REASONING_CHARS) : text, ...over ? { truncated: true } : {} });
40410
40749
  }
40411
40750
  const testRuns = [];
40412
40751
  for (const t of loop.testRuns ?? []) {
@@ -40415,16 +40754,16 @@ function buildCodegenLoopRecord(loop) {
40415
40754
  break;
40416
40755
  }
40417
40756
  testRuns.push({
40418
- n: whole2(t.n),
40757
+ n: whole3(t.n),
40419
40758
  status: String(t.status).slice(0, MAX_STATUS_KEY_CHARS),
40420
40759
  ...t.reason ? { reason: String(t.reason).slice(0, MAX_STATUS_KEY_CHARS) } : {},
40421
- passed: whole2(t.passed),
40422
- failed: whole2(t.failed),
40423
- regressions: whole2(t.regressions),
40424
- newFailures: whole2(t.newFailures),
40425
- alreadyFailing: whole2(t.alreadyFailing),
40760
+ passed: whole3(t.passed),
40761
+ failed: whole3(t.failed),
40762
+ regressions: whole3(t.regressions),
40763
+ newFailures: whole3(t.newFailures),
40764
+ alreadyFailing: whole3(t.alreadyFailing),
40426
40765
  timedOut: t.timedOut === true,
40427
- seconds: whole2(t.seconds),
40766
+ seconds: whole3(t.seconds),
40428
40767
  ...t.scope === "file" ? { scope: "file" } : {},
40429
40768
  ...t.phase && PHASES.has(t.phase) ? { phase: t.phase } : {}
40430
40769
  });
@@ -40441,7 +40780,7 @@ function buildCodegenLoopRecord(loop) {
40441
40780
  outcome: ph.outcome.slice(0, MAX_STATUS_KEY_CHARS),
40442
40781
  turns: small(ph.turns),
40443
40782
  toolCalls: small(ph.toolCalls),
40444
- ...whole2(ph.redUnproven) > 0 ? { redUnproven: small(ph.redUnproven) } : {}
40783
+ ...whole3(ph.redUnproven) > 0 ? { redUnproven: small(ph.redUnproven) } : {}
40445
40784
  });
40446
40785
  }
40447
40786
  const refused2 = clampRefusedTurns(loop.refusedTurns);
@@ -40472,15 +40811,15 @@ function buildCodegenLoopRecord(loop) {
40472
40811
  const healIn = loop.heal;
40473
40812
  const healed = healIn && typeof healIn.stop === "string" && HEAL_STOPS.has(healIn.stop) ? {
40474
40813
  stop: healIn.stop,
40475
- allowed: Math.min(3, whole2(healIn.allowed)),
40476
- made: Math.min(3, whole2(healIn.made)),
40814
+ allowed: Math.min(3, whole3(healIn.allowed)),
40815
+ made: Math.min(3, whole3(healIn.made)),
40477
40816
  ...gateOf(healIn.startedFrom) ? { startedFrom: gateOf(healIn.startedFrom) } : {},
40478
40817
  ...typeof healIn.failureReason === "string" && healIn.failureReason.length > 0 ? { failureReason: healIn.failureReason.slice(0, MAX_STATUS_KEY_CHARS) } : {}
40479
40818
  } : void 0;
40480
40819
  return {
40481
- turns: whole2(loop.turns),
40482
- toolCalls: whole2(loop.toolCalls),
40483
- refused: whole2(loop.refused),
40820
+ turns: whole3(loop.turns),
40821
+ toolCalls: whole3(loop.toolCalls),
40822
+ refused: whole3(loop.refused),
40484
40823
  stopReason: loop.stopReason,
40485
40824
  ...loop.fellBack ? { fellBack: true } : {},
40486
40825
  ...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_RECORD_FALLBACK_REASON_CHARS) } : {},
@@ -40488,9 +40827,13 @@ function buildCodegenLoopRecord(loop) {
40488
40827
  edits,
40489
40828
  created,
40490
40829
  statusCounts,
40491
- ...whole2(loop.syntaxWarnings) > 0 ? { syntaxWarnings: whole2(loop.syntaxWarnings) } : {},
40830
+ ...whole3(loop.syntaxWarnings) > 0 ? { syntaxWarnings: whole3(loop.syntaxWarnings) } : {},
40492
40831
  ...typeof loop.contractVersion === "string" && loop.contractVersion.length > 0 ? { contractVersion: loop.contractVersion.slice(0, 40) } : {},
40832
+ ...clampNotesRecord(loop.notes) ? { notes: clampNotesRecord(loop.notes) } : {},
40493
40833
  ...clampRepoView(loop.repoView, loop.peakRequestTokens),
40834
+ ...clampTurnRows(loop.turnUsage) ? { turnUsage: clampTurnRows(loop.turnUsage) } : {},
40835
+ ...loop.turnUsageCut ? { turnUsageCut: true } : {},
40836
+ ...clampTotals(loop.usage) ? { usage: clampTotals(loop.usage) } : {},
40494
40837
  ...testRuns.length > 0 ? { testRuns } : {},
40495
40838
  ...refused2.rows.length > 0 ? { refusedTurns: refused2.rows } : {},
40496
40839
  ...attempts.length > 0 ? { attempts } : {},
@@ -40721,7 +41064,7 @@ async function postCodegenTurn(gateway, contextData, signal) {
40721
41064
  ...signal ? { signal } : {}
40722
41065
  });
40723
41066
  if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
40724
- return res.json();
41067
+ return noteSpend(await res.json(), "codegen");
40725
41068
  }
40726
41069
  function protectedTestFiles(listing, testDiscovery) {
40727
41070
  const inListing2 = new Set(listing);
@@ -40799,7 +41142,9 @@ function buildCodegenLoopArgs(p, context = collectLoopContext({
40799
41142
  targets: p.targets,
40800
41143
  requiredAutomationIds: requiredTests.map((tc) => tc.automationId),
40801
41144
  listing: p.workspaceListing,
40802
- ...map ? { readRoots: map.readRoots, readListing: map.readListing, repoView: repoViewOf(map) } : {},
41145
+ ...map ? { readRoots: map.readRoots, readListing: map.readListing } : {},
41146
+ // QUIKTR-1582: how the run saw the repository, in both views (the record says which folder it could change).
41147
+ ...p.scope ? { repoView: repoViewOf(p.scope) } : {},
40803
41148
  deniedPaths: p.deniedPaths,
40804
41149
  protectedTestPaths,
40805
41150
  ...discoveredTests ? { discoveredTests } : {},
@@ -40961,6 +41306,12 @@ async function runCodegenStep(p) {
40961
41306
  log({ event: "codegen.attempt_start", attempt: 1 });
40962
41307
  const firstStarted = now();
40963
41308
  let first = await attempt2();
41309
+ if ("failure" in first && first.failure.reason === "contract_rejected" && p.tools2?.notes === true && args?.harness === true) {
41310
+ log({ event: "codegen.version_fallback", from: "codegen-loop-6", to: "codegen-loop-5" });
41311
+ p.tools2 = { ...p.tools2, notes: false };
41312
+ args = buildCodegenLoopArgs(p, context);
41313
+ first = await attempt2();
41314
+ }
40964
41315
  if ("failure" in first && first.failure.reason === "contract_rejected" && p.tools2 && args?.harness === true) {
40965
41316
  log({ event: "codegen.version_fallback", from: "codegen-loop-5", to: p.scope?.view === "map" ? "codegen-loop-4" : "codegen-loop-3" });
40966
41317
  p.tools2 = void 0;
@@ -42280,12 +42631,45 @@ function startMapMode(i2) {
42280
42631
  return { event: "map.mode", ...overrode ? { overrode: { targeting: i2.targetingMode, codegen: i2.codegenMode } } : {} };
42281
42632
  }
42282
42633
 
42634
+ // src/toolsMode.ts
42635
+ var TOOLS2_ENV = "QUIKPILOT_TOOLS2";
42636
+ var TOOLS_MIN_TOKENS_ENV = "QUIKPILOT_TOOLS_MIN_TOKENS";
42637
+ var NOTES_ENV = "QUIKPILOT_NOTES";
42638
+ var DEFAULT_TOOLS_MIN_TOKENS = 8e3;
42639
+ function resolveToolsSetting(env2 = process.env) {
42640
+ const v = env2[TOOLS2_ENV]?.trim().toLowerCase();
42641
+ return v === "off" ? "off" : v === "on" ? "on" : "auto";
42642
+ }
42643
+ function resolveToolsMinTokens(env2 = process.env) {
42644
+ const n = Number(env2[TOOLS_MIN_TOKENS_ENV]);
42645
+ return Number.isFinite(n) && n >= 0 ? Math.floor(n) : DEFAULT_TOOLS_MIN_TOKENS;
42646
+ }
42647
+ function notesEnabled(env2 = process.env) {
42648
+ return env2[NOTES_ENV]?.trim().toLowerCase() !== "off";
42649
+ }
42650
+ function decideTools(setting, scope, minTokens) {
42651
+ const base = { setting, listingTokens: scope.listingTokens, threshold: minTokens };
42652
+ if (setting === "off") return { ...base, on: false, why: "off" };
42653
+ if (setting === "on") return { ...base, on: true, why: "on" };
42654
+ if (scope.view === "map") return { ...base, on: true, why: "map_view" };
42655
+ return scope.listingTokens >= minTokens ? { ...base, on: true, why: "big_listing" } : { ...base, on: false, why: "small_listing" };
42656
+ }
42657
+ function buildToolsV2Env(i2) {
42658
+ const packageFolders = new Map(i2.scope.packages.map((p) => [p.name, p.folder]));
42659
+ return {
42660
+ writeRoots: [i2.scope.writeRoot],
42661
+ mapSpecifier: createAliasMapper({ readText: i2.readText, writeRoot: i2.scope.writeRoot }),
42662
+ ...packageFolders.size > 0 ? { packageFolders } : {},
42663
+ ...i2.notes ? { notes: true } : {}
42664
+ };
42665
+ }
42666
+
42283
42667
  // src/repoMap.ts
42284
42668
  var import_node_path19 = require("node:path");
42285
42669
  var MAP_BUDGET_TOKENS = 4e3;
42286
42670
  var MAX_FOLDERS = 200;
42287
42671
  var MAX_LANGUAGES = 12;
42288
- var GUIDANCE_NAMES = ["AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", "README.md"];
42672
+ var GUIDANCE_NAMES2 = ["AGENTS.md", "CLAUDE.md", "CONTRIBUTING.md", "README.md"];
42289
42673
  var GUIDANCE_FILE_CHARS = 2e3;
42290
42674
  var GUIDANCE_TOTAL_CHARS = 6e3;
42291
42675
  var MAX_GUIDANCE_FILES = 8;
@@ -42306,7 +42690,7 @@ function guidanceFiles(i2, perFile2, total) {
42306
42690
  const out = [];
42307
42691
  let left = total;
42308
42692
  for (let d = i2.writeRoot; ; d = parentOf2(d)) {
42309
- for (const name of GUIDANCE_NAMES) {
42693
+ for (const name of GUIDANCE_NAMES2) {
42310
42694
  const path = d === "" ? name : `${d}/${name}`;
42311
42695
  if (out.length >= MAX_GUIDANCE_FILES || left < MIN_GUIDANCE_CHARS) break;
42312
42696
  if (!tracked.has(path) || matchesDeniedPath(path, denied)) continue;
@@ -42609,20 +42993,6 @@ function buildRepoScope(i2) {
42609
42993
  };
42610
42994
  }
42611
42995
 
42612
- // src/toolsMode.ts
42613
- var TOOLS2_ENV = "QUIKPILOT_TOOLS2";
42614
- function resolveToolsSetting(env2 = process.env) {
42615
- return env2[TOOLS2_ENV]?.trim().toLowerCase() === "off" ? "off" : "on";
42616
- }
42617
- function buildToolsV2Env(i2) {
42618
- const packageFolders = new Map(i2.scope.packages.map((p) => [p.name, p.folder]));
42619
- return {
42620
- writeRoots: [i2.scope.writeRoot],
42621
- mapSpecifier: createAliasMapper({ readText: i2.readText, writeRoot: i2.scope.writeRoot }),
42622
- ...packageFolders.size > 0 ? { packageFolders } : {}
42623
- };
42624
- }
42625
-
42626
42996
  // src/targetingMode.ts
42627
42997
  var TARGETING_MODE_ENV = "QUIKPILOT_TARGETING_MODE";
42628
42998
  function parse5(value) {
@@ -42809,7 +43179,7 @@ var FAILURE_ARTIFACT_DIR = "quikpilot-failure";
42809
43179
  var REPORT_COPY = "final-test-report.xml";
42810
43180
  var MAX_REPORT_BYTES = 5 * 1024 * 1024;
42811
43181
  var MAX_FILES = 200;
42812
- var RUNNER_VERSION = true ? "9.3.0-rc.34" : "dev";
43182
+ var RUNNER_VERSION = true ? "9.3.0-rc.36" : "dev";
42813
43183
  function safeDestination(base, repoPath) {
42814
43184
  if (!repoPath || (0, import_node_path21.isAbsolute)(repoPath)) return null;
42815
43185
  const destination = (0, import_node_path21.resolve)(base, repoPath);
@@ -43066,7 +43436,7 @@ async function postTargeting(gateway, contextData, signal) {
43066
43436
  if (!res.ok) {
43067
43437
  throw new TargetingHttpError(res.status, res.statusText);
43068
43438
  }
43069
- return res.json();
43439
+ return noteSpend(await res.json(), "targeting");
43070
43440
  }
43071
43441
  function finalizeTargeting(body, workspaceRoot, workspaceListing, deniedPaths) {
43072
43442
  if (body.outcome === "NO_TARGET") {
@@ -43115,11 +43485,22 @@ async function runSingleShot(gateway, design, workspaceRoot, workspaceListing, r
43115
43485
  }
43116
43486
  async function loopWithTools2(args, tools2, deps) {
43117
43487
  if (!tools2) return runTargetingLoop(args, deps);
43488
+ const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
43489
+ let level = tools2;
43490
+ if (tools2.notes === true) {
43491
+ try {
43492
+ return await runTargetingLoop({ ...args, tools2, contractVersion: NOTES_LOOP_CONTRACT_VERSION }, deps);
43493
+ } catch (err) {
43494
+ if (!(err instanceof LoopFailure) || err.reason !== "contract_rejected") throw err;
43495
+ log({ event: "targeting.version_fallback", from: NOTES_LOOP_CONTRACT_VERSION, to: TOOLS2_LOOP_CONTRACT_VERSION });
43496
+ level = { ...tools2, notes: false };
43497
+ }
43498
+ }
43118
43499
  try {
43119
- return await runTargetingLoop({ ...args, tools2, contractVersion: TOOLS2_LOOP_CONTRACT_VERSION }, deps);
43500
+ return await runTargetingLoop({ ...args, tools2: level, contractVersion: TOOLS2_LOOP_CONTRACT_VERSION }, deps);
43120
43501
  } catch (err) {
43121
43502
  if (!(err instanceof LoopFailure) || err.reason !== "contract_rejected") throw err;
43122
- (deps.log ?? ((e) => console.log(JSON.stringify(e))))({
43503
+ log({
43123
43504
  event: "targeting.version_fallback",
43124
43505
  from: TOOLS2_LOOP_CONTRACT_VERSION,
43125
43506
  to: args.contractVersion ?? "targeting-loop-1"
@@ -43138,6 +43519,7 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
43138
43519
  return runSingleShot(gateway, design, workspaceRoot, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
43139
43520
  }
43140
43521
  const baseContext = buildContextData(design, workspaceListing, requiredTests, deniedPaths, testDiscovery, outOfScope, findings);
43522
+ const listingView = repoViewOf(options.scope);
43141
43523
  let summary;
43142
43524
  let runtimeCode;
43143
43525
  let reason;
@@ -43149,7 +43531,7 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
43149
43531
  );
43150
43532
  summary = looped.summary;
43151
43533
  const result = finalizeTargeting(looped.body, workspaceRoot, workspaceListing, deniedPaths);
43152
- return { ...result, loop: summary };
43534
+ return { ...result, loop: { ...summary, ...listingView ? { repoView: listingView } : {} } };
43153
43535
  } catch (err) {
43154
43536
  if (err instanceof DeniedPathError || err instanceof SafetyRefusalError) throw err;
43155
43537
  if (err instanceof LoopFailure) {
@@ -43168,7 +43550,12 @@ async function runTargeting(gateway, design, workspaceRoot, workspaceListing, re
43168
43550
  reads: summary?.reads ?? [],
43169
43551
  stopReason: "fallback",
43170
43552
  fellBack: true,
43171
- fallbackReason: reason
43553
+ fallbackReason: reason,
43554
+ // QUIKTR-1582: what the loop cost and saw before it gave up is kept, so the card still shows it.
43555
+ ...summary?.peakRequestTokens ? { peakRequestTokens: summary.peakRequestTokens } : {},
43556
+ ...summary?.turnUsage ? { turnUsage: summary.turnUsage } : {},
43557
+ ...summary?.turnUsageCut ? { turnUsageCut: true } : {},
43558
+ ...listingView ? { repoView: listingView } : {}
43172
43559
  };
43173
43560
  const log = options.loopDeps?.log ?? ((e) => console.log(JSON.stringify(e)));
43174
43561
  log({
@@ -43286,7 +43673,11 @@ function clampLoop(loop) {
43286
43673
  ...loop.fellBack ? { fellBack: true } : {},
43287
43674
  ...loop.fallbackReason ? { fallbackReason: String(loop.fallbackReason).slice(0, MAX_FALLBACK_REASON_CHARS) } : {},
43288
43675
  ...typeof loop.contractVersion === "string" && loop.contractVersion.length > 0 ? { contractVersion: loop.contractVersion.slice(0, 40) } : {},
43676
+ ...clampNotesRecord(loop.notes) ? { notes: clampNotesRecord(loop.notes) } : {},
43289
43677
  ...clampRepoView(loop.repoView, loop.peakRequestTokens),
43678
+ ...clampTurnRows(loop.turnUsage) ? { turnUsage: clampTurnRows(loop.turnUsage) } : {},
43679
+ ...loop.turnUsageCut ? { turnUsageCut: true } : {},
43680
+ ...clampTotals(loop.usage) ? { usage: clampTotals(loop.usage) } : {},
43290
43681
  reads,
43291
43682
  ...refusedTurns.rows.length > 0 ? { refusedTurns: refusedTurns.rows } : {},
43292
43683
  ...cut ? { truncated: true } : {}
@@ -43451,7 +43842,9 @@ async function run(env2) {
43451
43842
  log: (e) => console.log(JSON.stringify(e))
43452
43843
  });
43453
43844
  const mapMode = scope.view === "map";
43454
- const tools2 = resolveToolsSetting() === "on" ? buildToolsV2Env({ scope, readText: readCheckoutText2 }) : void 0;
43845
+ const toolsDecision = decideTools(resolveToolsSetting(), scope, resolveToolsMinTokens());
43846
+ console.log(JSON.stringify({ event: "tools.decided", ...toolsDecision }));
43847
+ const tools2 = toolsDecision.on ? buildToolsV2Env({ scope, readText: readCheckoutText2, notes: notesEnabled() }) : void 0;
43455
43848
  if (mapMode) {
43456
43849
  console.log(JSON.stringify(startMapMode({ testCommand: packet.commands.test, targetingMode: resolveTargetingMode(), codegenMode: resolveCodegenMode() })));
43457
43850
  }
@@ -43491,7 +43884,11 @@ async function run(env2) {
43491
43884
  packet.guardrails.deniedPaths,
43492
43885
  discovery.result.value,
43493
43886
  outOfScope,
43494
- ...packet.findings || mapMode || tools2 ? [{ ...packet.findings ? { findings: packet.findings } : {}, ...mapMode ? { scope } : {}, ...tools2 ? { tools2 } : {} }] : []
43887
+ // QUIKTR-1561 - the early look's findings, filtered to this checkout inside runTargeting. Passed ONLY when there are some, so a run
43888
+ // without a completed look calls it exactly as before.
43889
+ // QUIKTR-1580 - and the scope: in map mode it is how targeting sees the repository; since QUIKTR-1582 it is also handed over in listing
43890
+ // mode, only so the record can say which folder the run could change (listing-mode targeting reads nothing else from it).
43891
+ { ...packet.findings ? { findings: packet.findings } : {}, scope, ...tools2 ? { tools2 } : {} }
43495
43892
  );
43496
43893
  targetingResult = targeting;
43497
43894
  for (const w of targeting.warnings ?? []) {
@@ -43581,7 +43978,8 @@ async function run(env2) {
43581
43978
  gateway: packet.gateway,
43582
43979
  targets: targeting.targets,
43583
43980
  workspaceListing,
43584
- ...mapMode ? { scope } : {},
43981
+ // In both views (QUIKTR-1582): map mode reads the repository through it; listing mode only records the folder it could change.
43982
+ scope,
43585
43983
  ...tools2 ? { tools2 } : {},
43586
43984
  ...writeRoot ? { writeRoot } : {},
43587
43985
  requiredTests: packet.requiredTests,
@@ -43778,6 +44176,11 @@ async function run(env2) {
43778
44176
  console.warn(`::warning::Could not keep the failed run's files: ${err instanceof Error ? err.message : String(err)}`);
43779
44177
  }
43780
44178
  }
44179
+ const targetingRecord = targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0;
44180
+ const targetingUsage = clampTotals(spendOf("targeting"));
44181
+ if (targetingRecord?.loop && targetingUsage) targetingRecord.loop = { ...targetingRecord.loop, usage: targetingUsage };
44182
+ const codegenUsage = clampTotals(spendOf("codegen"));
44183
+ const codegenRecord = codegenOut.loop && codegenUsage ? { ...codegenOut.loop, usage: codegenUsage } : codegenOut.loop;
43781
44184
  await reportBack({
43782
44185
  callbackUrl: env2.callbackUrl,
43783
44186
  runToken,
@@ -43785,14 +44188,15 @@ async function run(env2) {
43785
44188
  branch,
43786
44189
  warnings,
43787
44190
  // Omitted when targeting itself never produced a result (nothing exists to record).
43788
- targeting: targetingResult ? buildTargetingRecord(targetingResult, contextLog) : void 0,
44191
+ targeting: targetingRecord,
43789
44192
  baselineFindings,
43790
44193
  vanishedTests,
43791
44194
  unsuppliedInputs,
43792
44195
  changesNoTestDependsOn,
43793
44196
  testsCorrected,
43794
- codegenLoop: codegenOut.loop,
43795
- unresolved: failureReasons.length > 0 ? failureReasons : void 0
44197
+ codegenLoop: codegenRecord,
44198
+ unresolved: failureReasons.length > 0 ? failureReasons : void 0,
44199
+ aiCostUsd: spendSoFar().costUsd
43796
44200
  });
43797
44201
  return { hardFailure };
43798
44202
  }
@@ -43905,6 +44309,26 @@ function emptyFindings() {
43905
44309
  function isLine(n) {
43906
44310
  return typeof n === "number" && Number.isInteger(n) && n >= 1;
43907
44311
  }
44312
+ var MAX_FINDINGS_CHARS = 6e3;
44313
+ function capFindingsSize(findings, max = MAX_FINDINGS_CHARS) {
44314
+ const size = (f2) => JSON.stringify(f2).length;
44315
+ if (size(findings) <= max) return { findings, trimmed: false };
44316
+ let f = { ...findings, files: [...findings.files], callPath: [...findings.callPath], evidence: [...findings.evidence], openQuestions: [...findings.openQuestions] };
44317
+ const stages = [
44318
+ (x) => ({ ...x, openQuestions: [] }),
44319
+ (x) => ({ ...x, callPath: x.callPath.slice(0, 5) }),
44320
+ (x) => ({ ...x, files: x.files.map((y) => ({ ...y, symbols: y.symbols.slice(0, 2) })), evidence: x.evidence.map((y) => ({ ...y, symbols: y.symbols.slice(0, 2) })) }),
44321
+ (x) => ({ ...x, files: x.files.slice(0, 6) }),
44322
+ (x) => ({ ...x, callPath: [] }),
44323
+ (x) => ({ ...x, evidence: x.evidence.slice(0, 3) }),
44324
+ (x) => ({ ...x, files: x.files.slice(0, 3), evidence: x.evidence.slice(0, 1) })
44325
+ ];
44326
+ for (const stage of stages) {
44327
+ f = stage(f);
44328
+ if (size(f) <= max) break;
44329
+ }
44330
+ return { findings: f, trimmed: true };
44331
+ }
43908
44332
  function verifyFindings(raw, ledger, ctx) {
43909
44333
  const dropped = emptyDropped();
43910
44334
  const redactions = emptyRedactionCounts();
@@ -44073,7 +44497,7 @@ async function runInvestigateLoop(args, deps) {
44073
44497
  const now = deps.now ?? Date.now;
44074
44498
  const log = deps.log ?? ((e) => console.log(JSON.stringify(e)));
44075
44499
  const turnTimeoutMs = deps.turnTimeoutMs ?? 6e4;
44076
- const deadlineMs = deps.deadlineMs ?? 12e4;
44500
+ const deadlineMs = deps.deadlineMs ?? 21e4;
44077
44501
  const secrets = deps.secrets ?? [];
44078
44502
  const env2 = {
44079
44503
  listing: new Set(args.listing),
@@ -44136,7 +44560,10 @@ async function runInvestigateLoop(args, deps) {
44136
44560
  const turnStarted = now();
44137
44561
  let envelope;
44138
44562
  try {
44139
- envelope = await deps.post(contextData, AbortSignal.timeout(turnTimeoutMs));
44563
+ envelope = await deps.post(
44564
+ contextData,
44565
+ AbortSignal.timeout(turnTimeoutFor(turn, turnTimeoutMs, deps.turnTimeoutMs !== void 0, INVESTIGATE_FIRST_TURN_TIMEOUT_MS))
44566
+ );
44140
44567
  } catch (err) {
44141
44568
  throw classifyTransport3(err);
44142
44569
  }
@@ -44269,7 +44696,7 @@ async function postInvestigate(gateway, contextData, signal) {
44269
44696
  signal
44270
44697
  });
44271
44698
  if (!res.ok) throw new TargetingHttpError(res.status, res.statusText);
44272
- return res.json();
44699
+ return noteSpend(await res.json(), "investigate");
44273
44700
  }
44274
44701
  async function reportInvestigation(callbackUrl, runToken, body) {
44275
44702
  const res = await fetch(callbackUrl, {
@@ -44348,7 +44775,8 @@ async function investigate(env2, runToken, deps, log) {
44348
44775
  const commit2 = deps.headCommit();
44349
44776
  const redactions = { ...summary.redactions };
44350
44777
  addRedactionCounts(redactions, verified.redactions);
44351
- const { findings } = verified;
44778
+ const capped = capFindingsSize(verified.findings);
44779
+ const { findings } = capped;
44352
44780
  log({
44353
44781
  event: "investigate.done",
44354
44782
  verdict: findings.verdict,
@@ -44357,6 +44785,7 @@ async function investigate(env2, runToken, deps, log) {
44357
44785
  openQuestions: findings.openQuestions.length,
44358
44786
  downgraded: verified.downgraded,
44359
44787
  dropped: verified.dropped,
44788
+ ...capped.trimmed ? { capped: true } : {},
44360
44789
  redactions
44361
44790
  });
44362
44791
  return {