loki-mode 11.161.0 → 11.162.0

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.
Files changed (73) hide show
  1. package/SKILL.md +2 -2
  2. package/VERSION +1 -1
  3. package/autonomy/loki +24 -1
  4. package/autonomy/route.sh +12 -5
  5. package/bin/loki +1 -0
  6. package/dashboard/__init__.py +1 -1
  7. package/docs/CLI-REFERENCE.md +1 -1
  8. package/docs/INSTALLATION.md +1 -1
  9. package/docs/cost-controls.md +26 -2
  10. package/docs/dev/architecture-reference.md +1 -0
  11. package/docs/environment-variables.md +9 -1
  12. package/loki-ts/dist/loki.js +1969 -1952
  13. package/mcp/__init__.py +1 -1
  14. package/package.json +2 -2
  15. package/packages/control-plane/dist/server.js +354 -146
  16. package/plugins/loki-mode/.claude-plugin/plugin.json +1 -1
  17. package/web-app/dist/assets/{AdminPage-CuV3jwO8.js → AdminPage-BizDHgWk.js} +1 -1
  18. package/web-app/dist/assets/{Avatar-fwxJYmU0.js → Avatar-EPfQ4V79.js} +1 -1
  19. package/web-app/dist/assets/{Badge-C-16U-fv.js → Badge-BOcJREUY.js} +1 -1
  20. package/web-app/dist/assets/{Button-DFjWZzwM.js → Button-BL7oJ3SX.js} +1 -1
  21. package/web-app/dist/assets/{CockpitPage-BMe0TFba.js → CockpitPage-CCjh7fQ3.js} +1 -1
  22. package/web-app/dist/assets/{ComparePage-BGNs7d0W.js → ComparePage-D5v3QbiF.js} +1 -1
  23. package/web-app/dist/assets/{ErrorBoundary-Dg4jYVbI.js → ErrorBoundary-BPaT8HE3.js} +1 -1
  24. package/web-app/dist/assets/{EvidenceReceiptPanel-BPiK4shg.js → EvidenceReceiptPanel-DPjXfVE0.js} +1 -1
  25. package/web-app/dist/assets/{GitHubIssuesPanel-Bj73V3QA.js → GitHubIssuesPanel-TbALzECx.js} +1 -1
  26. package/web-app/dist/assets/{GitHubPRsPanel-BbmTPafH.js → GitHubPRsPanel-C-L_BSIr.js} +1 -1
  27. package/web-app/dist/assets/{HomePage-_kzSwCXX.js → HomePage-1mYJaASp.js} +2 -2
  28. package/web-app/dist/assets/{LoginPage-D3guOsi2.js → LoginPage-B6idMnV-.js} +1 -1
  29. package/web-app/dist/assets/{MagicPage-SWoVP7OY.js → MagicPage-DeNkeYa6.js} +1 -1
  30. package/web-app/dist/assets/{MetricsPage-BogKy2pu.js → MetricsPage-Dgz1xd96.js} +1 -1
  31. package/web-app/dist/assets/{NotFoundPage-CQiT_FXs.js → NotFoundPage-BcpJkVEt.js} +1 -1
  32. package/web-app/dist/assets/{ProjectPage-CZ_hFP38.js → ProjectPage-BghMVwZJ.js} +3 -3
  33. package/web-app/dist/assets/{ProjectsPage-Bq-oT_Pe.js → ProjectsPage-CYi1AWYT.js} +1 -1
  34. package/web-app/dist/assets/{SettingsPage-DSr6lHmq.js → SettingsPage-CY2F-s-3.js} +1 -1
  35. package/web-app/dist/assets/{ShowcasePage-Dqjj3rgJ.js → ShowcasePage-CnGVGvsv.js} +1 -1
  36. package/web-app/dist/assets/{SystemSettingsPage-scRs0fQ3.js → SystemSettingsPage-ZJA4D4Cr.js} +1 -1
  37. package/web-app/dist/assets/{TeamsPage-BhLTiTJf.js → TeamsPage-D-ubF63c.js} +1 -1
  38. package/web-app/dist/assets/{TemplatesPage-CfLqFEwD.js → TemplatesPage-DU5ExG6U.js} +1 -1
  39. package/web-app/dist/assets/{TerminalOutput-LEdtHTdQ.js → TerminalOutput-CxWrY53G.js} +1 -1
  40. package/web-app/dist/assets/{activity-CIE6E4sw.js → activity-B0hVt7sG.js} +1 -1
  41. package/web-app/dist/assets/{bell-CbXNt0VT.js → bell-D70EABSP.js} +1 -1
  42. package/web-app/dist/assets/{bot-DBilu5by.js → bot-D0lhJgAo.js} +1 -1
  43. package/web-app/dist/assets/{check-ByCaYntD.js → check-CvK2c4aF.js} +1 -1
  44. package/web-app/dist/assets/{chevron-left-lmByeTlW.js → chevron-left-5nepkZ1R.js} +1 -1
  45. package/web-app/dist/assets/{circle-alert-DKEPsx9y.js → circle-alert-COWxxc9Q.js} +1 -1
  46. package/web-app/dist/assets/{clock-t4QPQ9P1.js → clock-DVruSW-w.js} +1 -1
  47. package/web-app/dist/assets/{cloud-YfbBdG9Y.js → cloud-BLxWirmZ.js} +1 -1
  48. package/web-app/dist/assets/{code-xml-DUdvGh42.js → code-xml-DTR0iFkj.js} +1 -1
  49. package/web-app/dist/assets/{database-DMsUwuu7.js → database-BDk9p0n4.js} +1 -1
  50. package/web-app/dist/assets/{dollar-sign-CQj8ulH4.js → dollar-sign-BZNzvnXk.js} +1 -1
  51. package/web-app/dist/assets/{file-code-corner-Dcun8Ito.js → file-code-corner-BnUFhCvL.js} +1 -1
  52. package/web-app/dist/assets/{file-plus-BipK8vSI.js → file-plus-COXu7-j_.js} +1 -1
  53. package/web-app/dist/assets/{globe-0GE20vx4.js → globe-lyZQ67pp.js} +1 -1
  54. package/web-app/dist/assets/{hammer-BSCC-aCx.js → hammer-DCl4Kayz.js} +1 -1
  55. package/web-app/dist/assets/{index-uBPpPPl7.js → index-DPOae9m_.js} +3 -3
  56. package/web-app/dist/assets/{layers-BT6Akh8A.js → layers-jBOzzVOq.js} +1 -1
  57. package/web-app/dist/assets/{loader-circle-BSF5o6lv.js → loader-circle-BFjr0bf_.js} +1 -1
  58. package/web-app/dist/assets/{lock-DhvY9ErS.js → lock-CY4mlLs5.js} +1 -1
  59. package/web-app/dist/assets/{package-BMUewVpu.js → package-eZT5xC4c.js} +1 -1
  60. package/web-app/dist/assets/{plus-JcYGK4QC.js → plus-DuykLjQt.js} +1 -1
  61. package/web-app/dist/assets/{refresh-cw-BSMX6sVQ.js → refresh-cw-G7q9T3RR.js} +1 -1
  62. package/web-app/dist/assets/{rotate-ccw-I5qSLfsL.js → rotate-ccw-Bokg6RqC.js} +1 -1
  63. package/web-app/dist/assets/{scroll-text-DQ8wk3hX.js → scroll-text-DOds11-k.js} +1 -1
  64. package/web-app/dist/assets/{server-P6nlJ6_y.js → server-C8algKl_.js} +1 -1
  65. package/web-app/dist/assets/{shield-alert-DJXz2Y6G.js → shield-alert-BiKSiXeT.js} +1 -1
  66. package/web-app/dist/assets/{thumbs-up-BlLS0TcM.js → thumbs-up-DbgJ8_nk.js} +1 -1
  67. package/web-app/dist/assets/{trash-2-2-LU0vyX.js → trash-2-CzORwdJm.js} +1 -1
  68. package/web-app/dist/assets/{trending-down-DBVjyJy7.js → trending-down-jQ86erDF.js} +1 -1
  69. package/web-app/dist/assets/{trending-up-Dbz8-n-y.js → trending-up-C9JVhiBK.js} +1 -1
  70. package/web-app/dist/assets/{upload-CbP9Qhau.js → upload-OV-MfCE6.js} +1 -1
  71. package/web-app/dist/assets/{usePolling-Br1am1Wv.js → usePolling-C2jjhfd7.js} +1 -1
  72. package/web-app/dist/assets/{user-B43gT1q9.js → user-CNnDlDog.js} +1 -1
  73. package/web-app/dist/index.html +1 -1
@@ -14610,6 +14610,94 @@ var init_retry_class = __esm(() => {
14610
14610
  CAUSE_FIX_DEFAULT = { auth: "re-authenticate the provider CLI (see `loki doctor`)", quota_exhausted: "add credit to the provider account or wait for the plan reset" };
14611
14611
  });
14612
14612
 
14613
+ // ../../loki-ts/src/engine10/types.ts
14614
+ function armTimer(fn, ms, o = {}) {
14615
+ let t = null, done = false;
14616
+ if (!Number.isFinite(ms) && ms > 0)
14617
+ return { clear: () => {} };
14618
+ const due = Date.now() + Math.max(0, Number.isFinite(ms) ? ms : 0);
14619
+ const arm = () => {
14620
+ const left = due - Date.now();
14621
+ t = setTimeout(() => {
14622
+ if (done)
14623
+ return;
14624
+ if (due - Date.now() > 0 && left > MAX_TIMER_MS)
14625
+ arm();
14626
+ else {
14627
+ done = true;
14628
+ fn();
14629
+ }
14630
+ }, Math.min(Math.max(0, left), MAX_TIMER_MS));
14631
+ if (o.unref)
14632
+ t.unref?.();
14633
+ };
14634
+ arm();
14635
+ return { clear: () => {
14636
+ done = true;
14637
+ if (t)
14638
+ clearTimeout(t);
14639
+ } };
14640
+ }
14641
+ function warnBadCap(source, raw2) {
14642
+ const key = `${source}=${raw2}`;
14643
+ if (warnedCap.has(key))
14644
+ return;
14645
+ warnedCap.add(key);
14646
+ process.stderr.write(`loki: ignoring invalid ${source}="${raw2}" (need a number > 0); using the default cap of ${DEFAULT_CAP_S}s
14647
+ `);
14648
+ }
14649
+ function envCapS(raw2) {
14650
+ if (raw2 === undefined || raw2.trim() === "")
14651
+ return null;
14652
+ const n3 = Number(raw2);
14653
+ if (Number.isFinite(n3) && n3 > 0)
14654
+ return n3;
14655
+ warnBadCap("LOKI_E10_CAP_S", raw2);
14656
+ return null;
14657
+ }
14658
+ function backstopS(capS, graceS = BACKSTOP_GRACE_S) {
14659
+ return capS - Math.min(graceS, capS / 30);
14660
+ }
14661
+ function pushArgv(a) {
14662
+ switch (a.cmd) {
14663
+ case "push-pr":
14664
+ return ["push-pr", a.repoDir, a.branch, a.title, a.bodyFile, a.draft ? "1" : "0"];
14665
+ case "comment":
14666
+ return ["comment", a.runId, a.prUrl, a.file];
14667
+ case "status":
14668
+ return ["status", a.sha, a.state, a.description];
14669
+ case "issue-comment":
14670
+ return a.update ? ["issue-comment", "--update", a.issueRef, a.bodyFile] : ["issue-comment", a.issueRef, a.bodyFile];
14671
+ }
14672
+ }
14673
+ function taskBlock(task) {
14674
+ return ["Task (untrusted, quoted verbatim):", "<<<TASK", task, "TASK"];
14675
+ }
14676
+ var STAGE_BUDGETS, DEFAULT_CAP_S = 900, DEEP_CAP_S = 2700, defaultBudgetsOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_DEFAULT_BUDGETS"] ?? "").trim()), budgetsOn = (env = process.env) => defaultBudgetsOn(env) || (env["LOKI_E10_CAP_S"] ?? "").trim() !== "", posEnv = (raw2, dflt) => {
14677
+ const n3 = Number((raw2 ?? "").trim());
14678
+ return (raw2 ?? "").trim() !== "" && Number.isFinite(n3) && n3 > 0 ? n3 : dflt;
14679
+ }, NO_PROGRESS_ROUNDS = 2, noProgressRounds = (env = process.env) => Math.floor(posEnv(env["LOKI_E10_NO_PROGRESS_ROUNDS"], NO_PROGRESS_ROUNDS)), SILENCE_KILL_S = 1800, LOOP_KILL_S = 3600, loopKillS = (env = process.env) => posEnv(env["LOKI_E10_LOOP_KILL_S"], LOOP_KILL_S), cmdSilenceS = (env = process.env) => posEnv(env["LOKI_E10_CMD_SILENCE_S"], SILENCE_KILL_S), HANG_SILENCE_S = 1800, hangSilenceS = (env = process.env) => posEnv(env["LOKI_E10_HANG_SILENCE_S"], HANG_SILENCE_S), MAX_TIMER_MS, warnedCap, BACKSTOP_GRACE_S = 30, DEEP_IMPLEMENT_LIMIT_S = 1800, MAX_FIX_ROUNDS = 2, VERIFY_STOPPED_NOTE, ROUTER_COST_FIELDS, FINISH_LINE = "Finish with exactly one line: LOKI_DONE, or LOKI_ALREADY_DONE: <file:line evidence>, or LOKI_SPEC_CONFLICT: <reason; cite test as path:line>.", ISSUE_FINISH_LINE = "Finish with exactly one line: LOKI_DONE, or LOKI_ALREADY_DONE: <file:line evidence>, or LOKI_SPEC_CONFLICT: <reason; cite test as path:line>, or LOKI_UNFINISHED: <what is left> when something the issue requires is not delivered. An item the issue marks optional is not required: do it or skip it, say which in your reply, and still finish with LOKI_DONE. Use LOKI_SPEC_CONFLICT only when a test in the repository contradicts the task.", taskWording = (s) => s.replace(/\bThis is an issue\b/g, "This is a task").replace(/\bThis issue\b/g, "This task").replace(/\bthe issue\b/g, "the task"), TEXT_FINISH_LINE, proveByRunningOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_PROVE_BY_RUNNING"] ?? "").trim()), WORK_ROAD_ENV = "LOKI_E10_WORK_ROAD", workRoadOn = (env = process.env) => env[WORK_ROAD_ENV] === "1", issueRunBrief = (provider, source, env = process.env) => provider === "claude" && (source === "issue" || source === "text" && workRoadOn(env)) && proveByRunningOn(env);
14680
+ var init_types2 = __esm(() => {
14681
+ STAGE_BUDGETS = {
14682
+ intake: { targetS: 15, limitS: 60 },
14683
+ plan: { targetS: 45, limitS: 90 },
14684
+ wall: { targetS: 45, limitS: 90 },
14685
+ implement: { targetS: 180, limitS: 480 },
14686
+ prove: { targetS: 300, limitS: 3600 },
14687
+ verify: { targetS: 60, limitS: 120 },
14688
+ fix: { targetS: 90, limitS: 180 },
14689
+ commit: { targetS: 5, limitS: 30 },
14690
+ seal: { targetS: 15, limitS: 60 },
14691
+ pr: { targetS: 15, limitS: 60 },
14692
+ deep: { targetS: null, limitS: 2700 }
14693
+ };
14694
+ MAX_TIMER_MS = 2 ** 31 - 1;
14695
+ warnedCap = new Set;
14696
+ VERIFY_STOPPED_NOTE = { limit: "verify stopped at its time limit before all checks ran", cap: "verify stopped at the run time cap before all checks ran" };
14697
+ ROUTER_COST_FIELDS = ["requests_total", "requests_over_100k", "advisor_calls", "advisor_input_tokens", "advisor_output_tokens"];
14698
+ TEXT_FINISH_LINE = taskWording(ISSUE_FINISH_LINE);
14699
+ });
14700
+
14613
14701
  // ../../loki-ts/src/runner/worker_proc.ts
14614
14702
  import { spawn as spawn7, spawnSync as spawnSync2 } from "child_process";
14615
14703
  import { createInterface } from "readline";
@@ -14659,7 +14747,11 @@ function maxTurnsFor(limitS, env) {
14659
14747
  return Number.isInteger(user) && user > 0 ? user : Math.max(MIN_TURNS, Math.ceil(limitS / SECONDS_PER_TURN));
14660
14748
  }
14661
14749
  function clampBashTimeoutEnv(env, limitS) {
14662
- env["LOKI_E10_MAX_TURNS"] = String(maxTurnsFor(limitS, env));
14750
+ const turns = maxTurnsFor(limitS, env);
14751
+ if (Number.isFinite(turns))
14752
+ env["LOKI_E10_MAX_TURNS"] = String(turns);
14753
+ else
14754
+ delete env["LOKI_E10_MAX_TURNS"];
14663
14755
  const budget = Math.max(BASH_CLAMP_FLOOR_MS, Math.floor(limitS * 1000) - BASH_CLAMP_MARGIN_MS);
14664
14756
  for (const [k, dflt] of [["BASH_DEFAULT_TIMEOUT_MS", 120000], ["BASH_MAX_TIMEOUT_MS", 600000]]) {
14665
14757
  const cur = Number(env[k]);
@@ -14689,7 +14781,15 @@ function ulimitArgv(argv, env) {
14689
14781
  const script = `${set.map(([, flag], i) => `ulimit ${flag} "$${i + 1}"`).join(" && ")} || { printf '%s\\n' '${why}' >&2; exit ${ULIMIT_REFUSED_EXIT}; }; shift ${set.length}; exec "$@"`;
14690
14782
  return [LIMIT_SHELL, "-c", script, "sh", ...values, ...argv];
14691
14783
  }
14692
- function spawnWorker(argv, env, cwd, backstopMs, escalateMs, onLine, onStopped = () => {}) {
14784
+ function hasChildProcess(pid) {
14785
+ try {
14786
+ const r = spawnSync2("pgrep", ["-P", String(pid)], { encoding: "utf8", timeout: 5000 });
14787
+ return r.status === 1 && r.stdout.trim() === "" ? false : true;
14788
+ } catch {
14789
+ return true;
14790
+ }
14791
+ }
14792
+ function spawnWorker(argv, env, cwd, backstopMs, escalateMs, onLine, hang, onStopped = () => {}) {
14693
14793
  return new Promise((resolve11) => {
14694
14794
  if (!argv[0])
14695
14795
  return resolve11({ code: null, killed: false });
@@ -14772,6 +14872,9 @@ function spawnWorker(argv, env, cwd, backstopMs, escalateMs, onLine, onStopped =
14772
14872
  globalThis[Symbol.for("loki.ownsStopSignals")] = false;
14773
14873
  for (const t of timers)
14774
14874
  clearTimeout(t);
14875
+ backstop.clear();
14876
+ if (hangBeat)
14877
+ clearInterval(hangBeat);
14775
14878
  rl.close();
14776
14879
  child.stdout?.destroy();
14777
14880
  if (fwd && child.stderr) {
@@ -14783,13 +14886,24 @@ function spawnWorker(argv, env, cwd, backstopMs, escalateMs, onLine, onStopped =
14783
14886
  }
14784
14887
  killGroup2(child.pid, "SIGKILL");
14785
14888
  onStopped(cancelled2 !== undefined);
14786
- resolve11({ code, killed, ...cancelled2 ? { cancelled: cancelled2 } : {} });
14889
+ resolve11({ code, killed, ...cancelled2 ? { cancelled: cancelled2 } : {}, ...hung ? { hung: true } : {} });
14787
14890
  };
14788
- timers.push(setTimeout(() => {
14891
+ const stopWorker = () => {
14892
+ if (killed)
14893
+ return;
14789
14894
  killed = true;
14790
14895
  killGroup2(child.pid, "SIGTERM");
14791
14896
  timers.push(setTimeout(() => killGroup2(child.pid, "SIGKILL"), escalateMs));
14792
- }, backstopMs));
14897
+ };
14898
+ const backstop = armTimer(stopWorker, backstopMs);
14899
+ let hung = false;
14900
+ const hangBeat = hang ? setInterval(() => {
14901
+ if (!killed && Date.now() - hang.lastEventMs() >= hang.silenceS * 1000 && child.pid !== undefined && !hasChildProcess(child.pid)) {
14902
+ hung = true;
14903
+ stopWorker();
14904
+ }
14905
+ }, Math.max(100, Math.min(HANG_POLL_MS, Math.floor(hang.silenceS * 500)))) : null;
14906
+ hangBeat?.unref();
14793
14907
  child.on("error", () => finish2(null));
14794
14908
  child.on("exit", (code) => {
14795
14909
  const drained = () => (child.stdout?.readableEnded ?? true) && (!fwd || (child.stderr?.readableEnded ?? true));
@@ -15022,7 +15136,7 @@ var CANCEL_GRACE_MS, DRAIN_MS = 2000, KILL_GRACE_MS2 = 2000, BASH_CLAMP_FLOOR_MS
15022
15136
  } catch {
15023
15137
  return false;
15024
15138
  }
15025
- }, SAFE_BUN_FLAGS, ULIMIT_REFUSED_EXIT = 97, LIMIT_SHELL, ULIMIT_KNOBS, forwardsWorkerStderr = (stream = process.stderr) => stream.isTTY === true && globalThis[Symbol.for("loki.consoleOwnsTerminal")] === true, EXIT_CAUSES, SCRATCH_MARKER = ".loki-scratch-owned", SCRATCH_RECORD = "scratch.json", OWNER_ENV = "LOKI_RUN_OWNER", TASK_MEMORY_SUBDIR = "task-memory", scratchSessionEnv = (s) => ({ LOKI_SCRATCH: s.dir, LOKI_SCRATCH_SINCE: String(s.since), TMPDIR: s.dir, [OWNER_ENV]: s.nonce }), psOut = (args, timeout = 4000) => spawnSync2("ps", args, { encoding: "utf8", env: { PATH: process.env["PATH"] ?? "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" }, timeout }).stdout ?? "", alive = (pid) => {
15139
+ }, SAFE_BUN_FLAGS, ULIMIT_REFUSED_EXIT = 97, LIMIT_SHELL, ULIMIT_KNOBS, forwardsWorkerStderr = (stream = process.stderr) => stream.isTTY === true && globalThis[Symbol.for("loki.consoleOwnsTerminal")] === true, HANG_POLL_MS = 30000, EXIT_CAUSES, SCRATCH_MARKER = ".loki-scratch-owned", SCRATCH_RECORD = "scratch.json", OWNER_ENV = "LOKI_RUN_OWNER", TASK_MEMORY_SUBDIR = "task-memory", scratchSessionEnv = (s) => ({ LOKI_SCRATCH: s.dir, LOKI_SCRATCH_SINCE: String(s.since), TMPDIR: s.dir, [OWNER_ENV]: s.nonce }), psOut = (args, timeout = 4000) => spawnSync2("ps", args, { encoding: "utf8", env: { PATH: process.env["PATH"] ?? "/usr/bin:/bin", LC_ALL: "C", TZ: "UTC" }, timeout }).stdout ?? "", alive = (pid) => {
15026
15140
  try {
15027
15141
  process.kill(pid, 0);
15028
15142
  return true;
@@ -15043,6 +15157,7 @@ ${r.stdout ?? ""}`);
15043
15157
  }, procName = (command) => (command.trim().split(/\s+/)[0] ?? "").split("/").pop().slice(0, 60), SCRATCH_EXIT_RECORD = "scratch-cleanup.json";
15044
15158
  var init_worker_proc = __esm(() => {
15045
15159
  init_retry_class();
15160
+ init_types2();
15046
15161
  CANCEL_GRACE_MS = Number(process.env["LOKI_E10_CANCEL_GRACE_MS"]) > 0 ? Number(process.env["LOKI_E10_CANCEL_GRACE_MS"]) : 1e4;
15047
15162
  SAFE_BUN_FLAGS = ["--no-env-file", "--config=/dev/null"];
15048
15163
  LIMIT_SHELL = existsSync17("/bin/bash") ? "/bin/bash" : "/bin/sh";
@@ -15062,65 +15177,8 @@ var init_worker_proc = __esm(() => {
15062
15177
  ].map(([code, what]) => [code, `exit ${code} (${what})`]));
15063
15178
  });
15064
15179
 
15065
- // ../../loki-ts/src/engine10/types.ts
15066
- function warnBadCap(source, raw2) {
15067
- const key = `${source}=${raw2}`;
15068
- if (warnedCap.has(key))
15069
- return;
15070
- warnedCap.add(key);
15071
- process.stderr.write(`loki: ignoring invalid ${source}="${raw2}" (need a number > 0); using the default cap of ${DEFAULT_CAP_S}s
15072
- `);
15073
- }
15074
- function envCapS(raw2) {
15075
- if (raw2 === undefined || raw2.trim() === "")
15076
- return null;
15077
- const n3 = Number(raw2);
15078
- if (Number.isFinite(n3) && n3 > 0)
15079
- return n3;
15080
- warnBadCap("LOKI_E10_CAP_S", raw2);
15081
- return null;
15082
- }
15083
- function backstopS(capS, graceS = BACKSTOP_GRACE_S) {
15084
- return capS - Math.min(graceS, capS / 30);
15085
- }
15086
- function pushArgv(a) {
15087
- switch (a.cmd) {
15088
- case "push-pr":
15089
- return ["push-pr", a.repoDir, a.branch, a.title, a.bodyFile, a.draft ? "1" : "0"];
15090
- case "comment":
15091
- return ["comment", a.runId, a.prUrl, a.file];
15092
- case "status":
15093
- return ["status", a.sha, a.state, a.description];
15094
- case "issue-comment":
15095
- return a.update ? ["issue-comment", "--update", a.issueRef, a.bodyFile] : ["issue-comment", a.issueRef, a.bodyFile];
15096
- }
15097
- }
15098
- function taskBlock(task) {
15099
- return ["Task (untrusted, quoted verbatim):", "<<<TASK", task, "TASK"];
15100
- }
15101
- var STAGE_BUDGETS, DEFAULT_CAP_S = 900, DEEP_CAP_S = 2700, warnedCap, BACKSTOP_GRACE_S = 30, DEEP_IMPLEMENT_LIMIT_S = 1800, MAX_FIX_ROUNDS = 2, VERIFY_STOPPED_NOTE, ROUTER_COST_FIELDS, FINISH_LINE = "Finish with exactly one line: LOKI_DONE, or LOKI_ALREADY_DONE: <file:line evidence>, or LOKI_SPEC_CONFLICT: <reason; cite test as path:line>.", ISSUE_FINISH_LINE = "Finish with exactly one line: LOKI_DONE, or LOKI_ALREADY_DONE: <file:line evidence>, or LOKI_SPEC_CONFLICT: <reason; cite test as path:line>, or LOKI_UNFINISHED: <what is left> when something the issue requires is not delivered. An item the issue marks optional is not required: do it or skip it, say which in your reply, and still finish with LOKI_DONE. Use LOKI_SPEC_CONFLICT only when a test in the repository contradicts the task.", taskWording = (s) => s.replace(/\bThis is an issue\b/g, "This is a task").replace(/\bThis issue\b/g, "This task").replace(/\bthe issue\b/g, "the task"), TEXT_FINISH_LINE, proveByRunningOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_PROVE_BY_RUNNING"] ?? "").trim()), WORK_ROAD_ENV = "LOKI_E10_WORK_ROAD", workRoadOn = (env = process.env) => env[WORK_ROAD_ENV] === "1", issueRunBrief = (provider, source, env = process.env) => provider === "claude" && (source === "issue" || source === "text" && workRoadOn(env)) && proveByRunningOn(env);
15102
- var init_types2 = __esm(() => {
15103
- STAGE_BUDGETS = {
15104
- intake: { targetS: 15, limitS: 60 },
15105
- plan: { targetS: 45, limitS: 90 },
15106
- wall: { targetS: 45, limitS: 90 },
15107
- implement: { targetS: 180, limitS: 480 },
15108
- prove: { targetS: 300, limitS: 3600 },
15109
- verify: { targetS: 60, limitS: 120 },
15110
- fix: { targetS: 90, limitS: 180 },
15111
- commit: { targetS: 5, limitS: 30 },
15112
- seal: { targetS: 15, limitS: 60 },
15113
- pr: { targetS: 15, limitS: 60 },
15114
- deep: { targetS: null, limitS: 2700 }
15115
- };
15116
- warnedCap = new Set;
15117
- VERIFY_STOPPED_NOTE = { limit: "verify stopped at its time limit before all checks ran", cap: "verify stopped at the run time cap before all checks ran" };
15118
- ROUTER_COST_FIELDS = ["requests_total", "requests_over_100k", "advisor_calls", "advisor_input_tokens", "advisor_output_tokens"];
15119
- TEXT_FINISH_LINE = taskWording(ISSUE_FINISH_LINE);
15120
- });
15121
-
15122
15180
  // ../../loki-ts/src/util/shell.ts
15123
- async function readStreamCapped(stream, maxBytes = MAX_STDOUT_BYTES, onFirstChunk) {
15181
+ async function readStreamCapped(stream, maxBytes = MAX_STDOUT_BYTES, onFirstChunk, onChunk) {
15124
15182
  const reader = stream.getReader();
15125
15183
  let first = onFirstChunk;
15126
15184
  const decoder = new TextDecoder;
@@ -15133,6 +15191,11 @@ async function readStreamCapped(stream, maxBytes = MAX_STDOUT_BYTES, onFirstChun
15133
15191
  break;
15134
15192
  if (!value)
15135
15193
  continue;
15194
+ if (onChunk && value.byteLength > 0) {
15195
+ try {
15196
+ onChunk();
15197
+ } catch {}
15198
+ }
15136
15199
  if (first && value.byteLength > 0) {
15137
15200
  const cb = first;
15138
15201
  first = undefined;
@@ -15186,10 +15249,22 @@ async function run(argv, opts = {}) {
15186
15249
  };
15187
15250
  let timedOut = false;
15188
15251
  if (opts.timeoutMs && opts.timeoutMs > 0)
15189
- timer = setTimeout(() => {
15252
+ timer = armTimer(() => {
15190
15253
  timedOut = true;
15191
15254
  stop();
15192
15255
  }, opts.timeoutMs);
15256
+ const silenceMs = opts.silenceMs ?? (opts.timeoutMs !== undefined && !Number.isFinite(opts.timeoutMs) ? cmdSilenceS() * 1000 : undefined);
15257
+ let lastByte = Date.now(), silent = false;
15258
+ const touch = () => {
15259
+ lastByte = Date.now();
15260
+ };
15261
+ const quiet = silenceMs !== undefined && Number.isFinite(silenceMs) && silenceMs > 0 ? setInterval(() => {
15262
+ if (Date.now() - lastByte >= silenceMs) {
15263
+ silent = true;
15264
+ timedOut = true;
15265
+ stop();
15266
+ }
15267
+ }, Math.min(30000, Math.max(50, Math.floor(silenceMs / 4)))) : undefined;
15193
15268
  if (opts.signal) {
15194
15269
  if (opts.signal.aborted)
15195
15270
  stop();
@@ -15198,14 +15273,15 @@ async function run(argv, opts = {}) {
15198
15273
  }
15199
15274
  try {
15200
15275
  const [stdout, stderr, exitCode] = await Promise.all([
15201
- readStreamCapped(proc.stdout, MAX_STDOUT_BYTES, opts.onFirstStdout),
15202
- new Response(proc.stderr).text(),
15276
+ readStreamCapped(proc.stdout, MAX_STDOUT_BYTES, opts.onFirstStdout, quiet ? touch : undefined),
15277
+ quiet ? readStreamCapped(proc.stderr, MAX_STDOUT_BYTES, undefined, touch) : new Response(proc.stderr).text(),
15203
15278
  proc.exited
15204
15279
  ]);
15205
- return { stdout, stderr, exitCode, ...timedOut ? { timedOut: true } : {} };
15280
+ return { stdout, stderr, exitCode, ...timedOut ? { timedOut: true } : {}, ...silent ? { silent: true } : {} };
15206
15281
  } finally {
15207
- if (timer)
15208
- clearTimeout(timer);
15282
+ timer?.clear();
15283
+ if (quiet)
15284
+ clearInterval(quiet);
15209
15285
  if (killTimer)
15210
15286
  clearTimeout(killTimer);
15211
15287
  opts.signal?.removeEventListener("abort", stop);
@@ -15237,6 +15313,7 @@ function shellWord(value) {
15237
15313
  var MAX_STDOUT_BYTES;
15238
15314
  var init_shell = __esm(() => {
15239
15315
  init_worker_proc();
15316
+ init_types2();
15240
15317
  MAX_STDOUT_BYTES = 16 * 1024 * 1024;
15241
15318
  });
15242
15319
 
@@ -18346,11 +18423,11 @@ function positiveEnv(name, env, dflt) {
18346
18423
  function stallThresholdS(env = process.env["LOKI_E10_STALL_S"]) {
18347
18424
  return positiveEnv("LOKI_E10_STALL_S", env, DEFAULT_STALL_S);
18348
18425
  }
18349
- function stallKillS(env = process.env["LOKI_E10_STALL_KILL_S"]) {
18350
- return positiveEnv("LOKI_E10_STALL_KILL_S", env, 0);
18426
+ function stallKillS(env = process.env["LOKI_E10_STALL_KILL_S"], dflt = 0) {
18427
+ return positiveEnv("LOKI_E10_STALL_KILL_S", env, dflt);
18351
18428
  }
18352
18429
  function createWatchdog(now2, stallS = stallThresholdS()) {
18353
- let lastBytes = 0, lastDiff = "", lastChange = now2(), loopTicks = 0, stalled = false;
18430
+ let lastBytes = 0, lastDiff = "", lastChange = now2(), lastDiffChange = now2(), loopTicks = 0, stalled = false;
18354
18431
  return {
18355
18432
  tick(bytes, diff) {
18356
18433
  const t = now2();
@@ -18360,6 +18437,7 @@ function createWatchdog(now2, stallS = stallThresholdS()) {
18360
18437
  lastDiff = diff;
18361
18438
  loopTicks = 0;
18362
18439
  lastChange = t;
18440
+ lastDiffChange = t;
18363
18441
  stalled = false;
18364
18442
  } else if (moreOutput) {
18365
18443
  loopTicks++;
@@ -18367,17 +18445,17 @@ function createWatchdog(now2, stallS = stallThresholdS()) {
18367
18445
  stalled = false;
18368
18446
  } else
18369
18447
  loopTicks = 0;
18370
- const idleS = (t - lastChange) / 1000;
18448
+ const idleS = (t - lastChange) / 1000, diffIdleS = (t - lastDiffChange) / 1000;
18371
18449
  if (idleS >= stallS) {
18372
18450
  const stalledNow = !stalled;
18373
18451
  stalled = true;
18374
- return { cls: "stalled", idleS, stalledNow };
18452
+ return { cls: "stalled", idleS, stalledNow, diffIdleS };
18375
18453
  }
18376
18454
  if (loopTicks >= LOOP_TICKS)
18377
- return { cls: "looping", idleS, stalledNow: false };
18455
+ return { cls: "looping", idleS, stalledNow: false, diffIdleS };
18378
18456
  if (!moreOutput && !diffMoved && idleS >= IDLE_S)
18379
- return { cls: "idle", idleS, stalledNow: false };
18380
- return { cls: "progressing", idleS, stalledNow: false };
18457
+ return { cls: "idle", idleS, stalledNow: false, diffIdleS };
18458
+ return { cls: "progressing", idleS, stalledNow: false, diffIdleS };
18381
18459
  }
18382
18460
  };
18383
18461
  }
@@ -23297,17 +23375,27 @@ ${r.stderr ?? ""}`), missing: r.status === 127 };
23297
23375
  stopped = true;
23298
23376
  kill();
23299
23377
  };
23300
- const timer = setTimeout(stop, timeoutMs);
23378
+ const timer = armTimer(stop, timeoutMs), open = !Number.isFinite(timeoutMs);
23379
+ let last = Date.now();
23380
+ const touch = () => {
23381
+ last = Date.now();
23382
+ };
23383
+ const quiet = open ? setInterval(() => {
23384
+ if (Date.now() - last >= cmdSilenceS() * 1000)
23385
+ stop();
23386
+ }, Math.min(30000, Math.max(50, cmdSilenceS() * 250))) : undefined;
23301
23387
  if (signal?.aborted)
23302
23388
  stop();
23303
23389
  else
23304
23390
  signal?.addEventListener("abort", stop, { once: true });
23305
23391
  try {
23306
- const [o, e, code] = await Promise.all([new Response(proc.stdout).text(), new Response(proc.stderr).text(), proc.exited]);
23392
+ const [o, e, code] = await Promise.all([open ? readStreamCapped(proc.stdout, MAX_STDOUT_BYTES, undefined, touch) : new Response(proc.stdout).text(), open ? readStreamCapped(proc.stderr, MAX_STDOUT_BYTES, undefined, touch) : new Response(proc.stderr).text(), proc.exited]);
23307
23393
  return { code: stopped ? null : code, timedOut: stopped, out: stripAnsi(`${o}
23308
23394
  ${e}`).slice(-8 * 1024 * 1024), missing: code === 127 };
23309
23395
  } finally {
23310
- clearTimeout(timer);
23396
+ timer.clear();
23397
+ if (quiet)
23398
+ clearInterval(quiet);
23311
23399
  signal?.removeEventListener("abort", stop);
23312
23400
  kill();
23313
23401
  }
@@ -23319,6 +23407,8 @@ ${e}`).slice(-8 * 1024 * 1024), missing: code === 127 };
23319
23407
  }
23320
23408
  }, SAME_RED_NOTE = "excused as red on base in the identical kind (same command, same exit code, the same unparseable output shape; no failing id could be compared)", baseRedByIdOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_BASE_RED_BY_ID"] ?? "").trim()), baseRedSuiteOff = (env = process.env) => /^(0|off|false|no)$/i.test((env["LOKI_E10_BASE_RED_BY_ID"] ?? "").trim()), touchedBaseRedOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_TOUCHED_BASE_RED"] ?? "").trim()), collateralBaselineOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_COLLATERAL_BASELINE"] ?? "").trim()), TOUCHED_RED = "edited test file red on base by every failing id with the same errors; the cases the change added or edited pass (excused, not blocking)", STATIC_DIAG, STATIC_NOISE, STATIC_SUMMARY, readinessLines = (r) => [` Readiness: ${r.score}/100 (${r.grade})`, ...r.findings.length ? [" Fix:", ...r.findings.map((f) => ` - ${f.fix}`)] : []];
23321
23409
  var init_repo_profile = __esm(() => {
23410
+ init_types2();
23411
+ init_shell();
23322
23412
  init_failures();
23323
23413
  init_check_result();
23324
23414
  init_safe_git();
@@ -23737,7 +23827,7 @@ async function runPackageSuites(repoDir, signal, opts, checks2, notProven) {
23737
23827
  continue;
23738
23828
  }
23739
23829
  if (r.timedOut && suiteTimeoutOn()) {
23740
- const why = `timed out after ${Math.round(timeoutMs / 1000)}s`;
23830
+ const why = r.silent ? `stopped after ${cmdSilenceS()}s with no output` : `timed out after ${Math.round(timeoutMs / 1000)}s`;
23741
23831
  checks2.push({ name, cmd, result: "not_run", duration_s, reason: why });
23742
23832
  notProven.add(`not run: ${name} (${why})`);
23743
23833
  continue;
@@ -23786,6 +23876,7 @@ var WORKSPACE_WIDE, scopedOutNote = (s) => `n/a: ${s.name} (\`${s.cmd}\`) not ru
23786
23876
  return w.length > 0 && w.every((c) => c.result === "pass") ? wall.map((x) => x.path) : [];
23787
23877
  }, emptySubsuiteNaOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_EMPTY_SUBSUITE_NA"] ?? "").trim()), suiteTimeoutOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_SUITE_TIMEOUT_NOT_RUN"] ?? "").trim());
23788
23878
  var init_package_suite = __esm(() => {
23879
+ init_types2();
23789
23880
  init_load_owner();
23790
23881
  init_repo_profile();
23791
23882
  init_check_result();
@@ -24506,6 +24597,13 @@ function yamlRunCapS(text4) {
24506
24597
  warnBadCap("budgets.run_cap_s", raw2);
24507
24598
  return null;
24508
24599
  }
24600
+ function parseDurationS(raw2) {
24601
+ const m = /^\s*(\d+)\s*([smh]?)\s*$/.exec(raw2 ?? "");
24602
+ if (!m)
24603
+ return null;
24604
+ const n3 = Number(m[1]) * (m[2] === "h" ? 3600 : m[2] === "m" ? 60 : 1);
24605
+ return n3 > 0 ? n3 : null;
24606
+ }
24509
24607
  function deadlineCapS(env = process.env, uptimeS = process.uptime()) {
24510
24608
  const raw2 = env.LOKI_RUN_DEADLINE_S;
24511
24609
  if (raw2 === undefined || raw2.trim() === "")
@@ -24522,6 +24620,9 @@ function resolveRunCapS(repoDir, subscription, env = process.env) {
24522
24620
  const first = texts.find((t) => yamlKey(t, "budgets", "run_cap_s") !== null);
24523
24621
  const yamlS = first !== undefined ? yamlRunCapS(first) : null;
24524
24622
  const set = fixedCapS(envCapS(env.LOKI_E10_CAP_S) ?? undefined, yamlS), dl = deadlineCapS(env), fixedS = dl === undefined ? set : Math.min(set ?? dl, dl);
24623
+ const badLimit = (env.LOKI_E10_CAP_S ?? "").trim() !== "" || first !== undefined && yamlS === null || (env.LOKI_RUN_DEADLINE_S ?? "").trim() !== "";
24624
+ if (fixedS === undefined && !badLimit && !defaultBudgetsOn(env))
24625
+ return { capS: Infinity, ceilingS: Infinity };
24525
24626
  return { capS: fixedS ?? DEFAULT_CAP_S, fixedS, ceilingS: fixedS ?? capCeilingS(subscription) };
24526
24627
  }
24527
24628
  function planOutOfRepo(runDir) {
@@ -24544,12 +24645,13 @@ var PLAN_SCOPE_FILE = "plan-scope.json", MAX_SCOPE_BYTES, CEILING_SUBSCRIPTION_S
24544
24645
  }, issueMinCapS = (env = process.env) => {
24545
24646
  const v = (env["LOKI_E10_ISSUE_MIN_CAP_S"] ?? "").trim(), n3 = Number(v);
24546
24647
  return v !== "" && Number.isFinite(n3) && n3 >= 0 ? n3 : 2400;
24547
- }, issueCapRule = (runDir, env = process.env) => existsSync39(join62(runDir, "issue.json")) || workRoadOn(env) || !!env["LOKI_E10_ISSUE_JSON"] && existsSync39(env["LOKI_E10_ISSUE_JSON"]), DEADLINE_MARGIN_S = 30, DEADLINE_MIN_CAP_S = 60, timeNoteOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_TIME_NOTE"] ?? "").trim()), timeBudgetNote = (limitS) => `Time budget: about ${Math.max(1, Math.round(limitS / 60))} minutes left for this session. Work in small steps, keep the test suite passing at every checkpoint, and leave the tree in a working state when time runs out.`, outOfRepoInstruction = (scopePath) => `If the requested change has no target in this repository (for example the code lives in a hosted service or another repo), write {"files":[],"out_of_repo":"<one sentence why>"} to ${scopePath} and do not guess files.`, localBranchNote = (runId, verdict, repoDir) => `engine10: run ${runId} sealed ${verdict}, not verified: branch loki/${runId} stays local (not pushed); inspect it in ${repoDir}
24648
+ }, issueCapRule = (runDir, env = process.env) => existsSync39(join62(runDir, "issue.json")) || workRoadOn(env) || !!env["LOKI_E10_ISSUE_JSON"] && existsSync39(env["LOKI_E10_ISSUE_JSON"]), DEADLINE_MARGIN_S = 30, DEADLINE_MIN_CAP_S = 60, TIME_FLAGS, timeNoteOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_TIME_NOTE"] ?? "").trim()), timeBudgetNote = (limitS) => `Time budget: about ${Math.max(1, Math.round(limitS / 60))} minutes left for this session. Work in small steps, keep the test suite passing at every checkpoint, and leave the tree in a working state when time runs out.`, outOfRepoInstruction = (scopePath) => `If the requested change has no target in this repository (for example the code lives in a hosted service or another repo), write {"files":[],"out_of_repo":"<one sentence why>"} to ${scopePath} and do not guess files.`, localBranchNote = (runId, verdict, repoDir) => `engine10: run ${runId} sealed ${verdict}, not verified: branch loki/${runId} stays local (not pushed); inspect it in ${repoDir}
24548
24649
  `;
24549
24650
  var init_run_cap = __esm(() => {
24550
24651
  init_types2();
24551
24652
  init_yaml_key();
24552
24653
  MAX_SCOPE_BYTES = 256 * 1024;
24654
+ TIME_FLAGS = { "--max-time": "LOKI_RUN_DEADLINE_S", "--verify-max-time": "LOKI_E10_VERIFY_MAX_S" };
24553
24655
  });
24554
24656
 
24555
24657
  // ../../loki-ts/src/engine10/closure.ts
@@ -25784,7 +25886,8 @@ function dependentTests(repoDir, map, changed, already) {
25784
25886
  if (deps.size === 0)
25785
25887
  return { ...none, truncated };
25786
25888
  const all = map.tests.filter((t) => !have.has(t.path) && importsAny(read3(repoDir, t.path), t.path, deps, js)).sort((a, b) => a.path.localeCompare(b.path));
25787
- return { tests: all.slice(0, MAX_DEPENDENT_TESTS), dropped: Math.max(0, all.length - MAX_DEPENDENT_TESTS), truncated };
25889
+ const cap = defaultBudgetsOn() ? MAX_DEPENDENT_TESTS : all.length;
25890
+ return { tests: all.slice(0, cap), dropped: Math.max(0, all.length - cap), truncated };
25788
25891
  }
25789
25892
  var MAX_DEPENDENT_TESTS = 20, SCAN_MAX_BYTES = 48000000, SCAN_MAX_MS = 4000, FILE_MAX_BYTES = 256000, JS, PY, JS_EXT, PY_FROM, PY_IMP, pyMod = (base) => [`${base}.py`, `${base}/__init__.py`], read3 = (repoDir, rel) => {
25790
25893
  try {
@@ -25794,6 +25897,7 @@ var MAX_DEPENDENT_TESTS = 20, SCAN_MAX_BYTES = 48000000, SCAN_MAX_MS = 4000, FIL
25794
25897
  }
25795
25898
  }, importsAny = (text4, rel, set, js) => importTargets(rel, text4, js).some((t) => set.has(t)), dependentNotes = (d) => [...d.truncated ? ["reverse-dependent scan hit its byte or time bound: some importers of changed files may not have been tested"] : [], ...d.dropped ? [`reverse-dependent tests dropped by the ${MAX_DEPENDENT_TESTS}-file cap: ${d.dropped}`] : []];
25796
25899
  var init_dependents = __esm(() => {
25900
+ init_types2();
25797
25901
  init_safe_git();
25798
25902
  init_test_file_text();
25799
25903
  init_js_resolve();
@@ -31571,7 +31675,7 @@ var TEST_DIR2, TEST_NAME3, isTestFile3 = (f) => isTestFile(f) || TEST_DIR2.test(
31571
31675
  return /^(0|off|false|no)$/.test(v) ? "off" : v === "always" ? "always" : "on";
31572
31676
  }, SELF_REVIEW_MAX_TURNS = 12, selfReviewMaxTurns = (env = process.env) => {
31573
31677
  const n3 = Number((env["LOKI_E10_SELF_REVIEW_MAX_TURNS"] ?? "").trim());
31574
- return Number.isInteger(n3) && n3 > 0 ? n3 : SELF_REVIEW_MAX_TURNS;
31678
+ return Number.isInteger(n3) && n3 > 0 ? n3 : defaultBudgetsOn(env) ? SELF_REVIEW_MAX_TURNS : 0;
31575
31679
  }, SRC_EXT2, STYLE_FILES, repoConventionsOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_REPO_CONVENTIONS"] ?? "").trim()), PC_TYPES, CODE_FILE, docEnumOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_DOC_ENUM"] ?? "").trim()), NAME_TOKENS = (text4) => new Set([...text4.matchAll(/['"`]([A-Za-z][\w-]{2,39})['"`]|\b([A-Za-z_][\w]{2,39})\s*:/g)].map((m) => m[1] ?? m[2]).filter((t) => !/^(?:true|false|null|undefined|this|type|name|value|string|number|default|function|return|const|let|var|import|export|from|https?)$/i.test(t))), srCoverageOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_SR_COVERAGE"] ?? "").trim()), COMMON_CALLS, RESULT_AFTER, ERROR_IN, wallCasesOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_WALL_CASES"] ?? "").trim()), WALL_CASES_FILE = "wall-required-cases.json", wallCasesHanded = (runDir) => {
31576
31680
  if (!runDir)
31577
31681
  return 0;
@@ -31582,9 +31686,10 @@ var TEST_DIR2, TEST_NAME3, isTestFile3 = (f) => isTestFile(f) || TEST_DIR2.test(
31582
31686
  }
31583
31687
  }, SIB_SKIP, S = "[[:space:]]", DEF_RE, selfReviewWanted = (items, mode) => mode === "always" || mode === "on" && items.some((i) => i.status === "flagged"), LABEL2, KEY_OF, selfReviewReceiptBlock = (implement) => implement && implement["self_review"] ? { self_review: implement["self_review"] } : {}, verifiedFinishOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_VERIFIED_FINISH"] ?? "").trim()), VERIFIED_FINISH_MAX_TURNS = 8, verifiedFinishMaxTurns = (env = process.env) => {
31584
31688
  const n3 = Number((env["LOKI_E10_VERIFIED_FINISH_MAX_TURNS"] ?? "").trim());
31585
- return Number.isInteger(n3) && n3 > 0 ? n3 : VERIFIED_FINISH_MAX_TURNS;
31689
+ return Number.isInteger(n3) && n3 > 0 ? n3 : defaultBudgetsOn(env) ? VERIFIED_FINISH_MAX_TURNS : 0;
31586
31690
  }, FINISH_DIFF_MAX = 40000, FINISH_FILE_MAX = 12000, FINISH_FILES_MAX = 36000, FINISH_LEAD = "Finish pass. The change below is already applied, uncommitted, in this checkout. Do not redo, rewrite or extend the fix itself; only bring the change up to the repository's rules.", reviewTurnGuardOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_REVIEW_TURN_GUARD"] ?? "").trim()), sameEntry = (a, b) => !a || !b ? a === b : a.kind === b.kind && a.mode === b.mode && a.symlinkTarget === b.symlinkTarget && (a.content && b.content ? a.content.equals(b.content) : a.content === b.content), turnGuardNote = (g) => g?.reverted ? [`review turn reverted: ${g.broke.join(", ")} passed before the turn and failed after it; the turn's edits to ${g.paths.join(", ")} were taken back and the pre-turn diff kept`] : [], releaseRefsReceiptBlock = (implement) => Array.isArray(implement?.["changelog_refs_removed"]) && implement["changelog_refs_removed"].length ? { changelog_refs_removed: implement["changelog_refs_removed"] } : {};
31587
31691
  var init_self_review = __esm(() => {
31692
+ init_types2();
31588
31693
  init_commit_filter();
31589
31694
  init_scope2();
31590
31695
  init_conventions();
@@ -37144,11 +37249,11 @@ function resolveCap(cli, repoDir, env = process.env) {
37144
37249
  if (raw2 !== null && !isZeroCap(raw2))
37145
37250
  return { error: `loki.yaml budgets.per_run must be a positive number of US dollars (got "${raw2}")` };
37146
37251
  }
37147
- return hasApiKey(env) ? { usd: DEFAULT_MAX_COST_USD, source: "default" } : { usd: 0, source: "subscription" };
37252
+ return { usd: 0, source: hasApiKey(env) ? "default" : "subscription" };
37148
37253
  }
37149
37254
  function capNote(usd, source) {
37150
37255
  if (usd <= 0)
37151
- return "no dollar cap (subscription)";
37256
+ return source === "default" ? NO_COST_LIMIT_NOTE : "no dollar cap (subscription)";
37152
37257
  return `cap $${usd.toFixed(2)} (${source})`;
37153
37258
  }
37154
37259
  function groupEnv(env, capUsd, repoDir) {
@@ -37323,7 +37428,7 @@ function budgetNext(spentUsd, capUsd) {
37323
37428
  function unenforceableNote(provider, capUsd) {
37324
37429
  return capUsd > 0 && capability(provider)?.cost === "none" ? `warning: ${provider} reports no cost, so the $${capUsd.toFixed(2)} cap cannot be enforced` : null;
37325
37430
  }
37326
- var DEFAULT_MAX_COST_USD, SUBSCRIPTION_NOTE = "subscription: no dollar cap; usage counts against your plan limits", isZeroCap = (raw2) => /^\$?(0+(\.0*)?|\.0+)$/.test(raw2.trim()), BUDGET_THRESHOLDS;
37431
+ var DEFAULT_MAX_COST_USD, SUBSCRIPTION_NOTE = "subscription: no dollar cap; usage counts against your plan limits", NO_COST_LIMIT_NOTE = "no cost limit is set: the run stops when it is done or makes no progress (--max-cost <usd> sets one)", isZeroCap = (raw2) => /^\$?(0+(\.0*)?|\.0+)$/.test(raw2.trim()), BUDGET_THRESHOLDS;
37327
37432
  var init_budget_cap = __esm(() => {
37328
37433
  init_yaml_key();
37329
37434
  init_budget();
@@ -38488,12 +38593,13 @@ loki_services_stop() {
38488
38593
  }
38489
38594
  `, checkKey = (text4) => text4.split(/ \| (?:status \d|exit \d|wanted )/)[0].toLowerCase().replace(/\b[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f-]{22,}\b|\b[0-9a-f]{12,}\b/g, "#").replace(/\d+/g, "#").replace(/\s+/g, " ").trim().slice(0, 200), proofChecks = (out2, token) => proofLines(out2, token).map((c) => ({ item: c.item, what: checkKey(c.text), ok: c.ok })), MAX_SCRIPT_BYTES = 200000, TAIL_CHARS = 8000, proofRerunS = (env = process.env) => {
38490
38595
  const n3 = Number(env["LOKI_E10_PROOF_RERUN_S"]);
38491
- return n3 > 0 ? n3 : 600;
38596
+ return n3 > 0 ? n3 : defaultBudgetsOn(env) ? 600 : Infinity;
38492
38597
  }, proofLoopMax = (env = process.env) => {
38493
38598
  const v = (env["LOKI_E10_PROOF_LOOP_MAX"] ?? "").trim(), n3 = Number(v);
38494
38599
  return v !== "" && Number.isInteger(n3) && n3 >= 0 ? n3 : 3;
38495
38600
  }, proofRerunOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_PROOF_RERUN"] ?? "").trim()), proofBaseOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_PROOF_BASE"] ?? "").trim()), proofBaseCapOn = (env = process.env) => /^(1|on|true|yes)$/i.test((env["LOKI_E10_PROOF_BASE_CAP"] ?? "").trim()), keepsWorkingAsk = (line2) => /\b(still|existing|remains?|unchanged|regress\w*|backwards?[- ]compatib\w*|compatib\w*|continues? to|keeps?|preserv\w*|no breaking|without breaking|(?:does|do|must|should) not break|not affect\w*|refactor\w*|clean ?up|renam\w*|upgrad\w*|bump\w*|tests? pass(?:es|ing)?|lint\w*|type ?checks?|ci (?:is |stays )?green|builds? (?:pass|succeed)\w*)\b/i.test(line2), provesNothingReason = (base, n3) => `every passing check for this line also passes on the base commit, before the change, so none of them proves the change (for example: ${base.same[String(n3)]?.first ?? ""})`.slice(0, 300), baseFacts = (asks, r, base) => provesNothing(asks, r, base).map((n3) => `Line ${n3}: every passing check for it in Loki's own run also passes when the same script runs against the base commit, before the change. Those checks do not show that the change delivered this line.`), PROVES_NOTHING_FIX = "Replace it with, or add, a check of what you built for this line: the request the new endpoint or page serves, the new output, the new row. A check that would also pass with your change removed proves nothing. If this line only asks that something keeps working, leave its check and say so in your reply", BASE_CACHE = "proof-base.json", DEPS_COPY_MS = 180000, RESULT_LOG = "loki-proof-results.log", SETUP_CHECK_S = 120, SETUP_TAIL_CHARS = 1000, NO_OWN_PROOF_NOTE = "no proof script: the session left nothing Loki could run itself, so no acceptance line is proved by Loki's own run", noOwnProofNotes = (source, listed, r, env = process.env) => source === "text" && listed > 0 && !r && proofRerunOn(env) ? [NO_OWN_PROOF_NOTE] : [];
38496
38601
  var init_proof_rerun = __esm(() => {
38602
+ init_types2();
38497
38603
  init_worker_proc();
38498
38604
  init_shell();
38499
38605
  init_safe_git();
@@ -39168,7 +39274,7 @@ Review ONLY the diff below. Do not modify files.` : "You are an independent code
39168
39274
  }
39169
39275
  var modelReviewRan = (xr) => !!xr && xr.level !== "not_run" && xr.reviewed_by !== "deterministic" && xr.reviewed_by !== "none", COMPILED_PATHS, hygieneFindings = (paths, ignored = new Set) => paths.filter((f) => !f.startsWith(".loki/") && (COMPILED_PATHS.some((re) => re.test(f)) || ignored.has(f))), RANK3, MAX_NOTES = 5, reviewRanWording = (xr) => modelReviewRan(xr) ? xr.reviewer_model ? `reviewer (${xr.reviewer_model})` : "reviewer" : xr?.reviewed_by === "deterministic" ? "deterministic check" : "none", REVIEW_TOOLS_NOTE = "Your tools are Read, Grep, Glob and a read-only shell (cat, ls, grep, rg, find, head, tail, wc). No git commands are available; the diff is in this prompt. You cannot edit files or run project code or tests, so trace behaviour by reading the code. If a tool fails or you could not inspect something, say so plainly in your reasons.", clean4 = (s) => capWhole(s.replace(/[\x00-\x1f\x7f`]+/g, " "), 600), UNMET_REASON_RE, isUnmetNote = (note2) => /^cross-review \w+ \([^)]*\):\s*\**UNMET\b/.test(note2), reviewDefaultOn = (tier, env = process.env) => tier === "high" || tier === "medium" && env["LOKI_REVIEW_DEFAULT"] === "1", reviewBoxS = (env = process.env) => {
39170
39276
  const n3 = Number(env["LOKI_E10_REVIEW_BOX_S"]);
39171
- return n3 > 0 ? n3 : 300;
39277
+ return n3 > 0 ? n3 : defaultBudgetsOn(env) ? 300 : Infinity;
39172
39278
  }, MIN_REVIEW_S = 30, roomS = (ctx) => backstopS(ctx.capS ?? Infinity) - (ctx.startedAtMs === undefined ? 0 : (ctx.clock?.now() ?? Date.now()) - ctx.startedAtMs) / 1000 - 55, boxFor = (ctx) => Math.min(reviewBoxS(), roomS(ctx)), reviewExtraLimitS = (ctx) => pickReviewer(ctx, configuredReviewer(ctx.repoDir)).p && roomS(ctx) >= MIN_REVIEW_S ? boxFor(ctx) + 30 : 0, LINE_CHECK_HEAD = "Loki acceptance line check.", LINE_CHECK_SYSTEM = "You check a code change against an issue's acceptance lines. You have no tools: read only what is below. Answer for every numbered line, one line each, nothing else.", LINE_CHECK_DIFF_MAX = 240000, CUT_FIRST, lineCheckOverride = null, lineCheckModel = (ctxModel, env = process.env) => (env["LOKI_E10_ISSUE_ACCEPTANCE_MODEL"] ?? "").trim() || (ctxModel && /^claude-/.test(ctxModel) ? ctxModel : ctxModel && /^(opus|sonnet|haiku)$/.test(ctxModel) ? `claude-${ctxModel}-5-5` : "claude-sonnet-5-5"), reviewAcceptance = (ctx) => {
39173
39279
  const o = ctx.outputs?.() ?? {}, il = issueAcceptanceCapOn() ? issueAcceptanceOf(o.intake) : [];
39174
39280
  return il.length ? il : acceptanceLines(o.plan);
@@ -39178,6 +39284,7 @@ var modelReviewRan = (xr) => !!xr && xr.level !== "not_run" && xr.reviewed_by !=
39178
39284
  return rows.length ? ["", "Checks the harness already ran on this change (name: result). Do not flag a line only because you could not run a test yourself; use these results:", ...rows] : [];
39179
39285
  }, reviewFixOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_REVIEW_FIX"] ?? "").trim());
39180
39286
  var init_xreview = __esm(() => {
39287
+ init_types2();
39181
39288
  init_role_agents();
39182
39289
  init_role_agents();
39183
39290
  init_shell();
@@ -40116,6 +40223,15 @@ ${r.session.summary}` };
40116
40223
  let reviewedEarly = false, earlyReviewCost = null;
40117
40224
  let proofFails = 0, lineTurns = 0;
40118
40225
  const LINE_TURNS_MAX = 2;
40226
+ const noBudget = !defaultBudgetsOn() && !ctx.deep;
40227
+ let proofBest = { failed: Infinity, unmet: Infinity }, proofStill = 0;
40228
+ const proofStep = (failed2, unmet) => {
40229
+ if (failed2 < proofBest.failed || unmet < proofBest.unmet) {
40230
+ proofBest = { failed: Math.min(failed2, proofBest.failed), unmet: Math.min(unmet, proofBest.unmet) };
40231
+ proofStill = 0;
40232
+ } else
40233
+ proofStill++;
40234
+ };
40119
40235
  const reviewRound = async (tree) => {
40120
40236
  if (reviewedEarly || !reviewFixOn())
40121
40237
  return false;
@@ -40140,7 +40256,7 @@ ${r.session.summary}` };
40140
40256
  ${r3.session.summary}` };
40141
40257
  return true;
40142
40258
  };
40143
- for (let round2 = 0;proofFails < proofLoopMax() && scratch && proofRerunOn() && existsSync68(join103(scratch.dir, PROOF_SCRIPT)) && !signal.aborted && !session3.killed && session3.exit === 0 && !session3.markers.specConflict && !session3.markers.alreadyDone; round2++) {
40259
+ for (let round2 = 0;(noBudget ? proofStill < noProgressRounds() : proofFails < proofLoopMax()) && scratch && proofRerunOn() && existsSync68(join103(scratch.dir, PROOF_SCRIPT)) && !signal.aborted && !session3.killed && session3.exit === 0 && !session3.markers.specConflict && !session3.markers.alreadyDone; round2++) {
40144
40260
  if (!keepProofScript(scratch.dir, ctx.runDir))
40145
40261
  break;
40146
40262
  const pr = await rerunProof(ctx.repoDir, ctx.runDir, signal);
@@ -40158,7 +40274,7 @@ ${r3.session.summary}` };
40158
40274
  const la = labelAsks(ctx.provider, prior.intake, prior.plan, ctx.repoDir);
40159
40275
  if (!la.asks.length)
40160
40276
  break;
40161
- if (lineTurns >= LINE_TURNS_MAX) {
40277
+ if (noBudget ? proofStill >= noProgressRounds() : lineTurns >= LINE_TURNS_MAX) {
40162
40278
  const t = await worktreeTree(ctx.repoDir);
40163
40279
  if (t && await reviewRound(t))
40164
40280
  continue;
@@ -40178,6 +40294,7 @@ ${r3.session.summary}` };
40178
40294
  return lc.marks && !lc.marks.met.includes(i + 1) ? [{ line: `${i + 1}. ${line2}`, reason: `it has a passing check, but a reviewer found a gap: ${lc.reasons?.[String(i + 1)] ?? "not stated"}` }] : [];
40179
40295
  });
40180
40296
  const lineUnmet = unmet.length;
40297
+ proofStep(pr.failed, lineUnmet);
40181
40298
  for (const f of await unusedNewFiles(ctx.repoDir, ctx.baseSha, tree))
40182
40299
  unmet.push({ line: `(not an acceptance line) ${f}`, reason: "no other file in the repository imports or names this new file, so a user cannot reach what it does. Mount it where it belongs (a page, a route, a registry, a menu) and prove that path, or remove it" });
40183
40300
  lineRounds.push({ met: lc.marks?.met.length ?? 0, unmet: unmet.length, usd: lc.usd });
@@ -40201,6 +40318,9 @@ ${r3.session.summary}` };
40201
40318
  ${r2.session.summary}` };
40202
40319
  continue;
40203
40320
  }
40321
+ proofStep(Math.max(1, pr.failed), Infinity);
40322
+ if (noBudget && proofStill >= noProgressRounds())
40323
+ break;
40204
40324
  const r = await resumeForProofScript(ctx, { ...unchained(), iterationId: ids[ids.length - 1] }, session3, `Loki ran your proof script ($LOKI_SCRATCH/loki-proof.sh) by itself, in a new empty directory, and it did not pass: exit ${pr.exit === null ? "none (it did not finish in time)" : pr.exit}, ${pr.proved} PROVED and ${pr.failed} FAILED line(s). This is the real end of its output:
40205
40325
 
40206
40326
  ${pr.tail.slice(-4000)}
@@ -40563,7 +40683,7 @@ async function runPass(root, dir, out2, ids, signal, o = {}) {
40563
40683
  cut = true;
40564
40684
  killGroup2(proc.pid, "SIGKILL");
40565
40685
  };
40566
- const timer = setTimeout(stop, Math.max(1, passS) * 1000);
40686
+ const timer = setTimeout(stop, Math.min(MAX_TIMER_MS, Math.max(1, passS) * 1000));
40567
40687
  if (signal.aborted)
40568
40688
  stop();
40569
40689
  else
@@ -40777,6 +40897,7 @@ printf 'done\\n' > "$OUT/driver.done"
40777
40897
  }
40778
40898
  }, proveStage, stage3, proveDisclosures = (o) => (o.prove?.notes ?? []).filter((n3) => !n3.startsWith("not proved:")).map((n3) => clean5(n3, 400));
40779
40899
  var init_prove = __esm(() => {
40900
+ init_types2();
40780
40901
  init_worker_proc();
40781
40902
  init_check_result();
40782
40903
  init_anti_loop();
@@ -43713,6 +43834,7 @@ __export(exports_machine, {
43713
43834
  hasFailures: () => hasFailures,
43714
43835
  haikuIndepFixOn: () => haikuIndepFixOn,
43715
43836
  freshBaseCheckout: () => freshBaseCheckout,
43837
+ fixProgressOf: () => fixProgressOf,
43716
43838
  attemptSignalOf: () => attemptSignalOf,
43717
43839
  VERIFY_MAX_S: () => VERIFY_MAX_S,
43718
43840
  USAGE_LIMIT_STOP: () => USAGE_LIMIT_STOP,
@@ -43759,9 +43881,13 @@ function stillFailing(groups, kept) {
43759
43881
  });
43760
43882
  }
43761
43883
  function verifyLimitFor(floorS, softS, elapsedS2, env = process.env) {
43762
- const v = Number((env["LOKI_E10_VERIFY_MAX_S"] ?? "").trim()), max = Number.isFinite(v) && v >= 1 ? Math.floor(v) : VERIFY_MAX_S;
43884
+ const v = Number((env["LOKI_E10_VERIFY_MAX_S"] ?? "").trim()), max = Number.isFinite(v) && v >= 1 ? Math.floor(v) : defaultBudgetsOn(env) ? VERIFY_MAX_S : Infinity;
43763
43885
  return Math.min(Math.max(floorS, Math.floor(softS - elapsedS2 - VERIFY_TAIL_S)), max);
43764
43886
  }
43887
+ function fixProgressOf(d) {
43888
+ const checks2 = Array.isArray(d?.checks) ? d.checks : [];
43889
+ return { failing: checks2.filter((c) => c?.result === "fail").reduce((n3, c) => n3 + Math.max(1, Array.isArray(c.ids) ? c.ids.length : 0), 0) + (Number(d?.holdout_failed) > 0 ? Number(d.holdout_failed) : 0), ran: checks2.filter((c) => c?.result !== "not_run").length };
43890
+ }
43765
43891
  function softCapS(capS) {
43766
43892
  const plain = capS * 14 / 15, budget = backstopS(capS) - ((STAGE_BUDGETS.commit.targetS ?? 0) + (STAGE_BUDGETS.seal.targetS ?? 0) + KILL_GRACE_MS3 / 1000 + 2);
43767
43893
  return Math.max(0, Math.min(plain, budget));
@@ -43781,7 +43907,8 @@ async function runMachine(ctx, opts = {}) {
43781
43907
  const timeline = ctx.timeline ??= [], intentRevs = ctx.intentRevisions ??= [];
43782
43908
  let capAtMs = startMs + softCapS(ctx.capS) * 1000;
43783
43909
  const capCtl = new AbortController;
43784
- let capTimer = setTimeout(() => capCtl.abort(), Math.max(0, capAtMs - ctx.clock.now()));
43910
+ let capTimer = armTimer(() => capCtl.abort(), Math.max(0, capAtMs - ctx.clock.now()));
43911
+ const unbounded = !defaultBudgetsOn() && !ctx.deep;
43785
43912
  let implementStartMs = null;
43786
43913
  const withTimeNote = (brief, limitS) => brief.endsWith(FINISH_LINE) ? `${brief.slice(0, -FINISH_LINE.length)}${timeBudgetNote(limitS)}
43787
43914
 
@@ -43793,10 +43920,10 @@ ${timeBudgetNote(limitS)}`;
43793
43920
  if (limited)
43794
43921
  return { exit: null, markers: { done: false, alreadyDone: null, specConflict: null }, durationS: 0, killed: true };
43795
43922
  startedIds.add(o0.iterationId);
43796
- const n0 = intentRevs.length, o = withSteer(o0, ctx.repoDir, intentRevs);
43923
+ const n0 = intentRevs.length, o = withSteer(unbounded ? { ...o0, limitS: Infinity } : o0, ctx.repoDir, intentRevs);
43797
43924
  if (intentRevs.length > n0)
43798
43925
  ctx.emit("intent.revised", o.stage, { revisions: intentRevs });
43799
- const left = implementStartMs === null ? Infinity : Math.max(1, implementBudgetS - (ctx.clock.now() - implementStartMs) / 1000), imp = o.stage === "implement" ? { ...o, limitS: Math.min(Math.max(o.limitS, implementBudgetS), left) } : o, r = await rerunOnQuota(() => ctx.sessions.run(imp.stage === "implement" && typeof imp.brief === "string" && imp.limitS > 0 && !issueRunBrief(ctx.provider, outputs.intake?.source) && timeNoteOn() ? { ...imp, brief: withTimeNote(imp.brief, imp.limitS) } : imp), sessionKind, ctx.clock, imp.signal, capAtMs, () => ctx.overCap?.() === true);
43926
+ const left = implementStartMs === null ? Infinity : Math.max(1, implementBudgetS - (ctx.clock.now() - implementStartMs) / 1000), imp = o.stage === "implement" ? { ...o, limitS: Math.min(Math.max(o.limitS, implementBudgetS), left) } : o, r = await rerunOnQuota(() => ctx.sessions.run(imp.stage === "implement" && typeof imp.brief === "string" && imp.limitS > 0 && Number.isFinite(imp.limitS) && !issueRunBrief(ctx.provider, outputs.intake?.source) && timeNoteOn() ? { ...imp, brief: withTimeNote(imp.brief, imp.limitS) } : imp), sessionKind, ctx.clock, imp.signal, Number.isFinite(capAtMs) ? capAtMs : ctx.clock.now() + hangSilenceS() * 1000, () => ctx.overCap?.() === true);
43800
43927
  const k = r.exit === 0 ? null : sessionKind(r);
43801
43928
  if (k === "auth" || k === "quota_exhausted" && !capReached())
43802
43929
  fatal ??= `fatal:${k}`;
@@ -43818,8 +43945,8 @@ ${timeBudgetNote(limitS)}`;
43818
43945
  return;
43819
43946
  ctx.capS = sctx.capS = proposedS;
43820
43947
  capAtMs = startMs + softCapS(proposedS) * 1000;
43821
- clearTimeout(capTimer);
43822
- capTimer = setTimeout(() => capCtl.abort(), Math.max(0, capAtMs - ctx.clock.now()));
43948
+ capTimer.clear();
43949
+ capTimer = armTimer(() => capCtl.abort(), Math.max(0, capAtMs - ctx.clock.now()));
43823
43950
  ctx.emit("cap.sized", null, { cap_s: proposedS });
43824
43951
  };
43825
43952
  const capReached = () => capCtl.signal.aborted || ctx.clock.now() >= capAtMs || ctx.overCap?.() === true;
@@ -43832,7 +43959,7 @@ ${timeBudgetNote(limitS)}`;
43832
43959
  const proveReserveS = () => proveScope(ctx.provider, outputs) ? proveBudgetS() : 0;
43833
43960
  let implementBudgetS = 0;
43834
43961
  const implementLimitS = (floorS) => Math.max(floorS, Math.floor(softCapS(ctx.capS) - elapsedS2() - (STAGE_BUDGETS.verify.limitS ?? 0) - proveReserveS()));
43835
- const fixLimitS = (baseS) => Math.max(baseS, Math.min(2 * baseS, Math.round(baseS * ctx.capS / DEFAULT_CAP_S)));
43962
+ const fixLimitS = (baseS) => unbounded ? Infinity : Math.max(baseS, Math.min(2 * baseS, Math.round(baseS * ctx.capS / DEFAULT_CAP_S)));
43836
43963
  const verifyLimitS = (floorS) => verifyLimitFor(floorS, softCapS(ctx.capS), elapsedS2());
43837
43964
  const runStage = async (name, underCap) => {
43838
43965
  if (limited)
@@ -43846,7 +43973,7 @@ ${timeBudgetNote(limitS)}`;
43846
43973
  markCap(name);
43847
43974
  return null;
43848
43975
  }
43849
- const limitS = name === "implement" ? ctx.deep ? DEEP_IMPLEMENT_LIMIT_S : st.limitS >= STAGE_BUDGETS.implement.limitS ? implementLimitS(st.limitS) : st.limitS : (name === "verify" && st.limitS >= STAGE_BUDGETS.verify.limitS ? verifyLimitS(st.limitS) : name === "fix" ? fixLimitS(st.limitS) : name === "prove" ? sctx.proveBudgetS ?? st.limitS : st.limitS) + (st.extraLimitS?.(sctx) ?? 0);
43976
+ const limitS0 = name === "implement" ? ctx.deep ? DEEP_IMPLEMENT_LIMIT_S : st.limitS >= STAGE_BUDGETS.implement.limitS ? implementLimitS(st.limitS) : st.limitS : (name === "verify" && st.limitS >= STAGE_BUDGETS.verify.limitS ? verifyLimitS(st.limitS) : name === "fix" ? fixLimitS(st.limitS) : name === "prove" ? sctx.proveBudgetS ?? st.limitS : st.limitS) + (st.extraLimitS?.(sctx) ?? 0), limitS = unbounded && !(name === "verify" || name === "implement" && Number.isFinite(ctx.capS)) ? Infinity : limitS0;
43850
43977
  if (name === "implement") {
43851
43978
  implementBudgetS = limitS;
43852
43979
  implementStartMs = ctx.clock.now();
@@ -43865,7 +43992,7 @@ ${timeBudgetNote(limitS)}`;
43865
43992
  ctl.abort();
43866
43993
  }
43867
43994
  };
43868
- const limitTimer = setTimeout(() => kill("limit"), limitS * 1000);
43995
+ const limitTimer = armTimer(() => kill("limit"), limitS * 1000);
43869
43996
  const onCap = () => kill("cap"), onUsage = () => kill("usage");
43870
43997
  limitCtl.signal.addEventListener("abort", onUsage);
43871
43998
  if (underCap) {
@@ -43885,7 +44012,7 @@ ${timeBudgetNote(limitS)}`;
43885
44012
  } catch (err) {
43886
44013
  r = { status: "failed", data: {}, reason: err instanceof Error ? err.message : String(err) };
43887
44014
  } finally {
43888
- clearTimeout(limitTimer);
44015
+ limitTimer.clear();
43889
44016
  capCtl.signal.removeEventListener("abort", onCap);
43890
44017
  limitCtl.signal.removeEventListener("abort", onUsage);
43891
44018
  }
@@ -43975,7 +44102,7 @@ ${timeBudgetNote(limitS)}`;
43975
44102
 
43976
44103
  ${CASCADE_LEAD}
43977
44104
  ${wallTail}` : brief0;
43978
- const room = Math.floor(softCapS(ctx.capS) - elapsedS2() - ATTEMPTS_TAIL_S), limitS = Math.min(STAGE_BUDGETS.implement.limitS, room);
44105
+ const room = Math.floor(softCapS(ctx.capS) - elapsedS2() - ATTEMPTS_TAIL_S), limitS = unbounded ? Infinity : Math.min(STAGE_BUDGETS.implement.limitS, room);
43979
44106
  if (limitS < MIN_ATTEMPT_WINDOW_S)
43980
44107
  return note2(`not enough run time left (${Math.max(room, 0)}s)`);
43981
44108
  if (capReached())
@@ -44040,7 +44167,7 @@ ${wallTail}` : brief0;
44040
44167
  };
44041
44168
  let wallJob = null;
44042
44169
  const closeWallJob = (j) => {
44043
- clearTimeout(j.timer);
44170
+ j.timer.clear();
44044
44171
  capCtl.signal.removeEventListener("abort", j.onCap);
44045
44172
  };
44046
44173
  const dropSnap = (j) => {
@@ -44073,7 +44200,7 @@ ${wallTail}` : brief0;
44073
44200
  ctl.abort();
44074
44201
  }
44075
44202
  };
44076
- const timer = setTimeout(() => kill("limit"), st.limitS * 1000), onCap = () => kill("cap");
44203
+ const timer = armTimer(() => kill("limit"), (unbounded ? Infinity : st.limitS) * 1000), onCap = () => kill("cap");
44077
44204
  if (capCtl.signal.aborted)
44078
44205
  onCap();
44079
44206
  else
@@ -44258,6 +44385,7 @@ ${wallTail}` : brief0;
44258
44385
  }
44259
44386
  }
44260
44387
  let extraRounds = 0;
44388
+ let fixBest = fixProgressOf(outputs.verify), stillRounds = 0;
44261
44389
  let noopSig = null;
44262
44390
  const suiteSkip = suiteFixSkipEnabled() && !fatal && !capHit && outputs.implement?.exit === "done" && hasFailures(outputs.verify) && suiteOnlyRed(outputs.verify);
44263
44391
  const indepSkip = !fatal && !capHit && hasFailures(outputs.verify) && fixGateOf(outputs.verify, `${String(outputs.implement?.model ?? "")} ${ctx.model}`).startsWith("closed");
@@ -44269,7 +44397,7 @@ ${wallTail}` : brief0;
44269
44397
  outputs.verify = { ...outputs.verify, not_proven: [...Array.isArray(outputs.verify?.not_proven) ? outputs.verify.not_proven : [], SUITE_FIX_SKIP_NOTE] };
44270
44398
  ctx.emit("loop.repeat", "fix", { reason: SUITE_FIX_SKIP_NOTE, round: 0, skipped: true });
44271
44399
  }
44272
- for (let round2 = 1;!indepSkip && round2 <= MAX_FIX_ROUNDS + extraRounds && !fatal && !capHit && !outputs.implement?.attempts?.error && !((round2 > 1 || suiteSkip) && onlyFullSuiteRed(outputs.verify)) && hasFailures(outputs.verify) && outputs.implement?.exit !== "spec_conflict" && outputs.implement?.exit !== "external"; round2++) {
44400
+ for (let round2 = 1;!indepSkip && (unbounded ? stillRounds < noProgressRounds() : round2 <= MAX_FIX_ROUNDS + extraRounds) && !fatal && !capHit && !outputs.implement?.attempts?.error && !((round2 > 1 || suiteSkip) && onlyFullSuiteRed(outputs.verify)) && hasFailures(outputs.verify) && outputs.implement?.exit !== "spec_conflict" && outputs.implement?.exit !== "external"; round2++) {
44273
44401
  const wallBefore = wallSignature(outputs, ctx.repoDir);
44274
44402
  const fx = await runStage("fix", true);
44275
44403
  if (!fx || mustJump("fix", fx) || fatal)
@@ -44318,6 +44446,14 @@ ${wallTail}` : brief0;
44318
44446
  noopSig = noop ? fedBy : null;
44319
44447
  const v = await runStage("verify", true);
44320
44448
  sigs.push(sigOf(outputs.verify, v));
44449
+ {
44450
+ const now2 = fixProgressOf(outputs.verify);
44451
+ if (now2.failing < fixBest.failing || now2.ran > fixBest.ran) {
44452
+ fixBest = { failing: Math.min(now2.failing, fixBest.failing), ran: Math.max(now2.ran, fixBest.ran) };
44453
+ stillRounds = 0;
44454
+ } else
44455
+ stillRounds++;
44456
+ }
44321
44457
  if (mustJump("verify", v))
44322
44458
  break;
44323
44459
  if (wallOnlyAfterFix(outputs, ctx.repoDir) && wallSignature(outputs, ctx.repoDir) === wallBefore)
@@ -44332,6 +44468,8 @@ ${wallTail}` : brief0;
44332
44468
  }
44333
44469
  if (round2 === 1 && round2 < MAX_FIX_ROUNDS + extraRounds && consultAvailable(ctx.runDir))
44334
44470
  continue;
44471
+ if (unbounded && stillRounds < noProgressRounds())
44472
+ continue;
44335
44473
  stopped = "stalled";
44336
44474
  break;
44337
44475
  }
@@ -44350,7 +44488,7 @@ ${wallTail}` : brief0;
44350
44488
  if (!fatal && !capHit && stopped === null && await deliverOverWallConflict(outputs, ctx.repoDir, () => runStage("verify", true), (path, why) => ctx.emit("wall.arbitrated", "wall", { path, discarded: why }), { runDir: ctx.runDir, restored: (v) => ctx.emit("stage.completed", "verify", { ...v, restored: true }) }) && wasConflict)
44351
44489
  ctx.emit("spec.conflict", "implement", { delivered: true, reason: outputs.implement?.spec_conflict_reason ?? null });
44352
44490
  if (outputs.prove)
44353
- outputs.prove = await recheckProve(sctx, outputs.prove, fatal || capHit ? 0 : Math.floor(softCapS(ctx.capS) - elapsedS2() - (STAGE_BUDGETS.commit.limitS + STAGE_BUDGETS.seal.limitS + STAGE_BUDGETS.pr.limitS)), capCtl.signal);
44491
+ outputs.prove = await recheckProve(sctx, outputs.prove, fatal || capHit ? 0 : unbounded ? proveBudgetS() : Math.floor(softCapS(ctx.capS) - elapsedS2() - (STAGE_BUDGETS.commit.limitS + STAGE_BUDGETS.seal.limitS + STAGE_BUDGETS.pr.limitS)), capCtl.signal);
44354
44492
  if (fatal) {
44355
44493
  stopped = fatal;
44356
44494
  jumped = true;
@@ -44366,7 +44504,7 @@ ${wallTail}` : brief0;
44366
44504
  throw err;
44367
44505
  } finally {
44368
44506
  abortWall();
44369
- clearTimeout(capTimer);
44507
+ capTimer.clear();
44370
44508
  removeHoldout(ctx.runId, ctx.repoDir);
44371
44509
  }
44372
44510
  }
@@ -44634,7 +44772,7 @@ async function runWorker(drive, opts = {}) {
44634
44772
  `));
44635
44773
  }
44636
44774
  function workerCapS(deep, env) {
44637
- return envCapS(env.LOKI_E10_CAP_S) ?? (deep ? DEEP_CAP_S : DEFAULT_CAP_S);
44775
+ return envCapS(env.LOKI_E10_CAP_S) ?? (deep ? DEEP_CAP_S : budgetsOn(env) ? DEFAULT_CAP_S : Infinity);
44638
44776
  }
44639
44777
  function costCapture(rawEmit, runId, repoDir, env = process.env) {
44640
44778
  const kept = env.LOKI_E10_RESUME === "1" ? readEvents(join112(repoDir, eventsRelPath(runId))).filter((e) => e.type === "cost") : [];
@@ -44703,7 +44841,7 @@ async function main(args) {
44703
44841
  clock: { now: () => Date.now() },
44704
44842
  outputs: () => ({})
44705
44843
  };
44706
- const resize = deep ? undefined : () => resizeCap(ctx.runDir, loadProjectApi(repoDir), !(Number(parseCapUsd(process.env.LOKI_E10_MAX_COST_USD)) > 0), Number(process.env.LOKI_E10_CAP_FIXED_S) || undefined);
44844
+ const resize = deep || !Number.isFinite(ctx.capS) ? undefined : () => resizeCap(ctx.runDir, loadProjectApi(repoDir), !(Number(parseCapUsd(process.env.LOKI_E10_MAX_COST_USD)) > 0), Number(process.env.LOKI_E10_CAP_FIXED_S) || undefined);
44707
44845
  let flow = FLOW.filter((s) => s !== "pr"), restored;
44708
44846
  if (process.env.LOKI_E10_RESUME === "1") {
44709
44847
  const p = join112(repoDir, eventsRelPath(runId)), r = (await Promise.resolve().then(() => (init_run_outputs(), exports_run_outputs))).resumeMachineOpts(ctx, readEvents(p), readFileSync102(p, "utf8"), flow);
@@ -44771,7 +44909,7 @@ import { copyFileSync as copyFileSync8, existsSync as existsSync77, mkdirSync as
44771
44909
  import { tmpdir as tmpdir21 } from "os";
44772
44910
  import { dirname as dirname46, join as join113 } from "path";
44773
44911
  async function runFullSuite(ctx, signal, opts, checks2, notProven2) {
44774
- if (await runPackageSuites(ctx.repoDir, signal, { path: opts.path, timeoutMs: opts.suiteTimeoutMs ?? opts.fullSuiteTimeoutMs ?? FULL_SUITE_TIMEOUT_MS, baseSha: ctx.baseSha, skip: installOwned(ctx.repoDir, ctx.outputs().intake?.install_created), changed: opts.changed, proofFiles: opts.proofFiles, wallBaseRed: opts.wallBaseRed, targetPassed: opts.targetPassed, ...opts.ownedOnly ? { ownedOnly: true } : {}, ...opts.scope ? { scope: true } : {}, ...opts.ensureBase ? { ensureBase: opts.ensureBase } : {} }, checks2, notProven2))
44912
+ if (await runPackageSuites(ctx.repoDir, signal, { path: opts.path, timeoutMs: opts.suiteTimeoutMs ?? opts.fullSuiteTimeoutMs ?? fullSuiteMs(), baseSha: ctx.baseSha, skip: installOwned(ctx.repoDir, ctx.outputs().intake?.install_created), changed: opts.changed, proofFiles: opts.proofFiles, wallBaseRed: opts.wallBaseRed, targetPassed: opts.targetPassed, ...opts.ownedOnly ? { ownedOnly: true } : {}, ...opts.scope ? { scope: true } : {}, ...opts.ensureBase ? { ensureBase: opts.ensureBase } : {} }, checks2, notProven2))
44775
44913
  return;
44776
44914
  const map = await ctx.tests.detect(ctx.repoDir);
44777
44915
  if (map.runners.length === 0) {
@@ -44789,7 +44927,7 @@ async function runFullSuite(ctx, signal, opts, checks2, notProven2) {
44789
44927
  const started = Date.now();
44790
44928
  const r = await run([spec.cmd, ...spec.args], {
44791
44929
  cwd: ctx.repoDir,
44792
- timeoutMs: opts.fullSuiteTimeoutMs ?? FULL_SUITE_TIMEOUT_MS,
44930
+ timeoutMs: opts.fullSuiteTimeoutMs ?? fullSuiteMs(),
44793
44931
  env: suiteEnv(opts.path),
44794
44932
  ...suiteTimeoutOn() ? { group: true, signal } : {}
44795
44933
  });
@@ -44800,7 +44938,7 @@ async function runFullSuite(ctx, signal, opts, checks2, notProven2) {
44800
44938
  continue;
44801
44939
  }
44802
44940
  if (r.timedOut && suiteTimeoutOn()) {
44803
- const why = `timed out after ${Math.round((opts.fullSuiteTimeoutMs ?? FULL_SUITE_TIMEOUT_MS) / 1000)}s`;
44941
+ const why = r.silent ? `stopped after ${cmdSilenceS()}s with no output` : `timed out after ${Math.round((opts.fullSuiteTimeoutMs ?? fullSuiteMs()) / 1000)}s`;
44804
44942
  checks2.push({ name, cmd: [spec.cmd, ...spec.args].join(" "), result: "not_run", duration_s: durationS, reason: why });
44805
44943
  notProven2.add(`not run: ${name} (${why})`);
44806
44944
  continue;
@@ -45162,7 +45300,7 @@ async function deepPost(args, deps = {}) {
45162
45300
  `);
45163
45301
  return out2.some((n3) => n3.startsWith("loki/deep-verify status not set") || n3.startsWith("push refused")) ? 1 : 0;
45164
45302
  }
45165
- var DEFAULT_SECRET_SCAN_SH, FULL_SUITE_TIMEOUT_MS, deepStage, stage5;
45303
+ var DEFAULT_SECRET_SCAN_SH, fullSuiteMs = () => defaultBudgetsOn() ? BASELINE_CMD_TIMEOUT_S * 1000 : Infinity, deepStage, stage5;
45166
45304
  var init_deep = __esm(() => {
45167
45305
  init_install();
45168
45306
  init_app_probe();
@@ -45182,7 +45320,6 @@ var init_deep = __esm(() => {
45182
45320
  init_paths();
45183
45321
  init_pr();
45184
45322
  DEFAULT_SECRET_SCAN_SH = join113(REPO_ROOT, "autonomy/lib/secret-scan.sh");
45185
- FULL_SUITE_TIMEOUT_MS = BASELINE_CMD_TIMEOUT_S * 1000;
45186
45323
  deepStage = {
45187
45324
  name: "deep",
45188
45325
  ...STAGE_BUDGETS.deep,
@@ -45284,7 +45421,7 @@ function sameFailureLines(headOut, base2, changed, symbols, headRoot, baseRoot)
45284
45421
  return ![...h].some((l) => names(l));
45285
45422
  }
45286
45423
  function suiteTimeoutFor(deadlineMs, nowMs, env = process.env) {
45287
- const v = Number((env["LOKI_E10_SUITE_TIMEOUT_S"] ?? "").trim()), max = Number.isFinite(v) && v >= 1 ? Math.floor(v * 1000) : 300000;
45424
+ const v = Number((env["LOKI_E10_SUITE_TIMEOUT_S"] ?? "").trim()), max = Number.isFinite(v) && v >= 1 ? Math.floor(v * 1000) : defaultBudgetsOn(env) ? 300000 : Infinity;
45288
45425
  if (deadlineMs === undefined)
45289
45426
  return max;
45290
45427
  const left = deadlineMs - nowMs - SUITE_MARGIN_MS;
@@ -45391,7 +45528,15 @@ function editedTestTitles(repoDir, baseSha, rel) {
45391
45528
  async function runOnce3(cmd, args, cwd, signal, opts) {
45392
45529
  if (!Bun.which(cmd, { PATH: opts.path ?? process.env["PATH"] ?? "" }))
45393
45530
  return { ok: false, missing: true, cut: false, out: "" };
45394
- const timeout = AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS);
45531
+ const tmo = opts.timeoutMs ?? checkTimeoutMs(), silence = new AbortController;
45532
+ let silent = false, lastByte = Date.now();
45533
+ const timeout = Number.isFinite(tmo) ? AbortSignal.timeout(Math.max(0, tmo)) : silence.signal;
45534
+ const quiet = Number.isFinite(tmo) ? undefined : setInterval(() => {
45535
+ if (Date.now() - lastByte >= cmdSilenceS() * 1000) {
45536
+ silent = true;
45537
+ silence.abort();
45538
+ }
45539
+ }, Math.min(30000, Math.max(50, cmdSilenceS() * 250)));
45395
45540
  const proc = Bun.spawn([cmd, ...args], {
45396
45541
  cwd,
45397
45542
  stdin: opts.stdin !== undefined ? Buffer.from(opts.stdin) : "ignore",
@@ -45434,19 +45579,22 @@ async function runOnce3(cmd, args, cwd, signal, opts) {
45434
45579
  const c = await r.read().catch(() => ({ done: true, value: undefined }));
45435
45580
  if (c.done)
45436
45581
  return;
45582
+ lastByte = Date.now();
45437
45583
  tail2 += d.decode(c.value, { stream: true });
45438
45584
  if (tail2.length > keep * 2)
45439
45585
  tail2 = tail2.slice(-keep);
45440
45586
  }
45441
45587
  });
45442
45588
  const exitCode = await proc.exited;
45589
+ if (quiet)
45590
+ clearInterval(quiet);
45443
45591
  await Promise.race([Promise.all(pumps), new Promise((r) => setTimeout(r, 300))]);
45444
45592
  rs.forEach((r) => r.cancel().catch(() => {}));
45445
45593
  if (opts.group)
45446
45594
  killGroup3();
45447
45595
  const cut = timeout.aborted || signal.aborted;
45448
45596
  const out2 = cut ? "" : stripAnsi(tail2.slice(-keep)), spawnTool = exitCode !== 0 && !cut ? spawnFailedTool(out2, exitCode) : null;
45449
- return { ok: exitCode === 0 && !cut, missing: spawnTool !== null, cut, out: out2, ...spawnTool ? { spawnTool } : {} };
45597
+ return { ok: exitCode === 0 && !cut, missing: spawnTool !== null, cut, out: out2, ...spawnTool ? { spawnTool } : {}, ...silent ? { silent } : {} };
45450
45598
  }
45451
45599
  async function runCheck(ctx, name, cmd, args, signal, checks2, opts = {}) {
45452
45600
  const started = Date.now();
@@ -45460,7 +45608,7 @@ async function runCheck(ctx, name, cmd, args, signal, checks2, opts = {}) {
45460
45608
  c2 = { result: "not_run", reason: lr, owner: "harness" };
45461
45609
  if (!lr && kind === "static" && !a.ok && !a.cut && !a.missing && opts.wall?.size && wallOwnedFailure(a.out, cwd, ctx.repoDir, opts.wall))
45462
45610
  c2 = { result: "not_run", reason: WALL_COMPILE_REASON, owner: "harness" };
45463
- const reason2 = a.missing ? a.spawnTool ? `${a.spawnTool} could not be started (not installed)${installHint(a.spawnTool)}` : `${cmd} not found on PATH${installHint(cmd)}` : a.cut ? signal.aborted ? "aborted" : `timed out after ${(opts.timeoutMs ?? CHECK_TIMEOUT_MS) / 1000}s` : c2.reason;
45611
+ const reason2 = a.missing ? a.spawnTool ? `${a.spawnTool} could not be started (not installed)${installHint(a.spawnTool)}` : `${cmd} not found on PATH${installHint(cmd)}` : a.cut ? signal.aborted ? "aborted" : a.silent ? `stopped after ${cmdSilenceS()}s with no output` : `timed out after ${(opts.timeoutMs ?? checkTimeoutMs()) / 1000}s` : c2.reason;
45464
45612
  return { ...c2, ...reason2 ? { reason: reason2 } : {} };
45465
45613
  };
45466
45614
  let attempt = await runOnce3(cmd, args, cwd, signal, opts);
@@ -45974,7 +46122,7 @@ async function tscOnBase(ctx, groupCwd, signal, opts, shared2) {
45974
46122
  return null;
45975
46123
  if (cwd !== shared2.dir)
45976
46124
  shared2.link(shared2.dir);
45977
- const r = await runOnce3("npx", ["--no-install", "tsc", "--noEmit", "-p", "."], cwd, AbortSignal.any([signal, AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS)]), { ...opts });
46125
+ const r = await runOnce3("npx", ["--no-install", "tsc", "--noEmit", "-p", "."], cwd, AbortSignal.any([signal, Number.isFinite(opts.timeoutMs ?? checkTimeoutMs()) ? AbortSignal.timeout(opts.timeoutMs ?? checkTimeoutMs()) : new AbortController().signal]), { ...opts });
45978
46126
  return r.missing || r.cut ? null : r.out;
45979
46127
  } catch {
45980
46128
  return null;
@@ -45990,7 +46138,7 @@ async function tscOnBase(ctx, groupCwd, signal, opts, shared2) {
45990
46138
  return null;
45991
46139
  if (cwd !== dir)
45992
46140
  link(dir);
45993
- const r = await runOnce3("npx", ["--no-install", "tsc", "--noEmit", "-p", "."], cwd, AbortSignal.any([signal, AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS)]), { ...opts });
46141
+ const r = await runOnce3("npx", ["--no-install", "tsc", "--noEmit", "-p", "."], cwd, AbortSignal.any([signal, Number.isFinite(opts.timeoutMs ?? checkTimeoutMs()) ? AbortSignal.timeout(opts.timeoutMs ?? checkTimeoutMs()) : new AbortController().signal]), { ...opts });
45994
46142
  return r.missing || r.cut ? null : r.out;
45995
46143
  } catch {
45996
46144
  return null;
@@ -46486,10 +46634,10 @@ var timeoutCarryOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LO
46486
46634
  for (const r of [...new Set(all)].filter((x) => x.length > 1).sort((a, b) => b.length - a.length))
46487
46635
  o = o.split(r).join("<repo>");
46488
46636
  return o;
46489
- }, SUITE_MARGIN_MS = 5000, CHECK_TIMEOUT_MS = 60000, excerpts, checkExcerpt = (c) => excerpts.get(c) ?? "", suites, failTails, tscOut, crashSigs, baseCrashEnvOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BASE_CRASH_ENV"] ?? "").trim()), BCE_REASON = "fails the same way on base, so its result cannot be read: the environment, not the change", noIdOut, headErrors, WALL_FAILURE_TAIL_CAP = 16384, wallTailOf = (out2, repoDir) => redactSecrets(stripAnsi(out2).replace(/\r/g, "").split(repoDir.replace(/\/+$/, "") + "/").join("")).slice(-WALL_FAILURE_TAIL_CAP), isHold = (c) => isHoldoutCheck(c.name), pubHold = (c) => ({ name: "holdout", cmd: "holdout", result: c.result, duration_s: c.duration_s, ...c.n !== undefined ? { n: c.n } : {}, ...c.sk !== undefined ? { sk: c.sk } : {}, ...c.owner ? { owner: c.owner, reason: "holdout infrastructure failure" } : {} }), testCheckName = (t) => `${t.runner}:${t.path}`, QUIET_RED = "excused as red on base although its error text differs from base by noise only (the same error shapes; no changed file or symbol appears in the failure)", COLLATERAL_RED = "relevant test already failing on base, still failing the same tests (it imports a file the task names; capped, not blocking)", noTestFallbackOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_NO_TEST_FALLBACK"] ?? "").trim()), ownByPathOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_OWN_BY_PATH"] ?? "").trim()), TEST_TITLE_RE, dedupeTests = (tests) => [...new Map(tests.map((t) => [`${t.runner}:${t.path}`, t])).values()], verifyBatchOn = (env = process.env) => env["LOKI_E10_VERIFY_BATCH"] !== "0", BATCH_MIN = 2, UNHANDLED_RE, batchTimeoutMs = (files) => Math.max(CHECK_TIMEOUT_MS, Math.min(300000, files * 5000)), vitestFile = (t, c) => t.runner === "vitest" && c.cmd === "npx" && c.args.length === 4 && c.args[0] === "--no-install" && c.args[1] === "vitest" && c.args[2] === "run", goBatchOn = (env = process.env) => verifyBatchOn(env) && env["LOKI_E10_GO_BATCH"] !== "0", goFileCmd = (t, c) => t.runner === "go" && c.cmd === "go" && c.args.length === 5 && c.args[0] === "test" && c.args[1] === "-json" && c.args[2] === "-run" && /^\^\([A-Za-z0-9_|]+\)\$$/.test(c.args[3]), goBatchable = (t, targets, changed, env = process.env) => goBatchOn(env) && t.runner === "go" && !targets.has(testCheckName(t)) && !changed.includes(t.path), uncausedOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_UNCAUSED_NO_FIX"] ?? "").trim()), LINT_CONFIG, INERT_FILE, OWN_LINT, OWN_TYPECHECK, haikuIndepFixOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_HAIKU_INDEP_FIX"] ?? "").trim()), ownLintOf = (c, pre, changed, symbols, excerpt2, re = OWN_LINT) => re.test(c.name) && feedsFixRound(c, pre) && !uncausedRed(c, changed, symbols, excerpt2), feedsFixRound = (c, pre) => c.result === "fail" && !pre.names.includes(c.name) && !pre.sameError.includes(c.name) && !isHoldoutCheck(c.name), baseMemoOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BASE_MEMO"] ?? "").trim()), ESLINT_CONFIGS, excuseLint = (ctx, signal, c, tool, cmd, prefix, cwd, rel, opts) => c.result !== "fail" || signal.aborted ? Promise.resolve(false) : staticPreExisting(tool, prefix, rel, { run: async (a, stdin) => {
46637
+ }, SUITE_MARGIN_MS = 5000, CHECK_TIMEOUT_MS = 60000, checkTimeoutMs = () => defaultBudgetsOn() ? CHECK_TIMEOUT_MS : Infinity, excerpts, checkExcerpt = (c) => excerpts.get(c) ?? "", suites, failTails, tscOut, crashSigs, baseCrashEnvOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BASE_CRASH_ENV"] ?? "").trim()), BCE_REASON = "fails the same way on base, so its result cannot be read: the environment, not the change", noIdOut, headErrors, WALL_FAILURE_TAIL_CAP = 16384, wallTailOf = (out2, repoDir) => redactSecrets(stripAnsi(out2).replace(/\r/g, "").split(repoDir.replace(/\/+$/, "") + "/").join("")).slice(-WALL_FAILURE_TAIL_CAP), isHold = (c) => isHoldoutCheck(c.name), pubHold = (c) => ({ name: "holdout", cmd: "holdout", result: c.result, duration_s: c.duration_s, ...c.n !== undefined ? { n: c.n } : {}, ...c.sk !== undefined ? { sk: c.sk } : {}, ...c.owner ? { owner: c.owner, reason: "holdout infrastructure failure" } : {} }), testCheckName = (t) => `${t.runner}:${t.path}`, QUIET_RED = "excused as red on base although its error text differs from base by noise only (the same error shapes; no changed file or symbol appears in the failure)", COLLATERAL_RED = "relevant test already failing on base, still failing the same tests (it imports a file the task names; capped, not blocking)", noTestFallbackOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_NO_TEST_FALLBACK"] ?? "").trim()), ownByPathOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_OWN_BY_PATH"] ?? "").trim()), TEST_TITLE_RE, dedupeTests = (tests) => [...new Map(tests.map((t) => [`${t.runner}:${t.path}`, t])).values()], verifyBatchOn = (env = process.env) => env["LOKI_E10_VERIFY_BATCH"] !== "0", BATCH_MIN = 2, UNHANDLED_RE, batchTimeoutMs = (files) => defaultBudgetsOn() ? Math.max(CHECK_TIMEOUT_MS, Math.min(300000, files * 5000)) : Infinity, vitestFile = (t, c) => t.runner === "vitest" && c.cmd === "npx" && c.args.length === 4 && c.args[0] === "--no-install" && c.args[1] === "vitest" && c.args[2] === "run", goBatchOn = (env = process.env) => verifyBatchOn(env) && env["LOKI_E10_GO_BATCH"] !== "0", goFileCmd = (t, c) => t.runner === "go" && c.cmd === "go" && c.args.length === 5 && c.args[0] === "test" && c.args[1] === "-json" && c.args[2] === "-run" && /^\^\([A-Za-z0-9_|]+\)\$$/.test(c.args[3]), goBatchable = (t, targets, changed, env = process.env) => goBatchOn(env) && t.runner === "go" && !targets.has(testCheckName(t)) && !changed.includes(t.path), uncausedOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_UNCAUSED_NO_FIX"] ?? "").trim()), LINT_CONFIG, INERT_FILE, OWN_LINT, OWN_TYPECHECK, haikuIndepFixOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_HAIKU_INDEP_FIX"] ?? "").trim()), ownLintOf = (c, pre, changed, symbols, excerpt2, re = OWN_LINT) => re.test(c.name) && feedsFixRound(c, pre) && !uncausedRed(c, changed, symbols, excerpt2), feedsFixRound = (c, pre) => c.result === "fail" && !pre.names.includes(c.name) && !pre.sameError.includes(c.name) && !isHoldoutCheck(c.name), baseMemoOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BASE_MEMO"] ?? "").trim()), ESLINT_CONFIGS, excuseLint = (ctx, signal, c, tool, cmd, prefix, cwd, rel, opts) => c.result !== "fail" || signal.aborted ? Promise.resolve(false) : staticPreExisting(tool, prefix, rel, { run: async (a, stdin) => {
46490
46638
  if (signal.aborted)
46491
46639
  return null;
46492
- const r = await runOnce3(cmd, a, cwd, AbortSignal.any([signal, AbortSignal.timeout(opts.timeoutMs ?? CHECK_TIMEOUT_MS)]), { ...opts, ...stdin !== undefined ? { stdin } : {} });
46640
+ const r = await runOnce3(cmd, a, cwd, AbortSignal.any([signal, Number.isFinite(opts.timeoutMs ?? checkTimeoutMs()) ? AbortSignal.timeout(opts.timeoutMs ?? checkTimeoutMs()) : new AbortController().signal]), { ...opts, ...stdin !== undefined ? { stdin } : {} });
46493
46641
  return r.missing || r.cut ? null : r;
46494
46642
  }, base: (f) => {
46495
46643
  try {
@@ -48136,6 +48284,7 @@ var exports_seal = {};
48136
48284
  __export(exports_seal, {
48137
48285
  wallGreenOnBaseOf: () => wallGreenOnBaseOf,
48138
48286
  verdictOf: () => verdictOf2,
48287
+ unattributedRed: () => unattributedRed,
48139
48288
  targetedBreak: () => targetedBreak,
48140
48289
  targetProofOf: () => targetProofOf,
48141
48290
  stage: () => stage8,
@@ -48348,6 +48497,10 @@ function secretPushRefusal(verify4, runId) {
48348
48497
  return null;
48349
48498
  return { check: "security scan", matches: m && m.length ? m : ["(where it matched was not recorded)"], command: `git push -u origin loki/${runId}` };
48350
48499
  }
48500
+ function unattributedRed(o, c) {
48501
+ const cut = o.verify?.stopped_at === "limit" || o.verify?.stopped_at === "cap", head = c.name.split(":")[0];
48502
+ return cut && c.provenance === "exogenous" && c.name.includes(":") && !/^(lint|typecheck|holdout|select-tests|build|patch|turn)$/.test(head);
48503
+ }
48351
48504
  function verdictOf2(o, checks2, emptyDiff, verifyNotProven, wallGreenOnBase, proof, targetProof = false, uncovered = [], leanGap = [], copyGap = [], clauseGap = []) {
48352
48505
  const exit = o.implement?.exit;
48353
48506
  if (o.commit?.failed !== true && strs2(o.commit?.not_proven).length === 0 && (o.intake?.already_satisfied === true || exit === "already_done"))
@@ -48362,7 +48515,7 @@ function verdictOf2(o, checks2, emptyDiff, verifyNotProven, wallGreenOnBase, pro
48362
48515
  return typeof o.implement?.limit_s === "number" && targetProof && uncovered.length === 0 && copyGap.length === 0 && clauseGap.length === 0 && proof && !wallGreenOnBase && !verifyNotProven && checks2.length > 0 && checks2.every((c) => c.result === "pass") ? "VERIFIED" : "PARTIAL";
48363
48516
  if (typeof o.implement?.limit_s === "number")
48364
48517
  return "PARTIAL";
48365
- if (checks2.some((c) => c.result === "fail"))
48518
+ if (checks2.some((c) => c.result === "fail" && !unattributedRed(o, c)))
48366
48519
  return "FAILED";
48367
48520
  if (exit === "external" && !(Array.isArray(o.wall?.files) && o.wall.files.length > 0))
48368
48521
  return "PARTIAL";
@@ -57403,6 +57556,8 @@ __export(exports_supervisor, {
57403
57556
  TAMPER_NOT_PROVEN: () => TAMPER_NOT_PROVEN,
57404
57557
  SupervisorLog: () => SupervisorLog,
57405
57558
  START_LINE: () => START_LINE,
57559
+ HANG_SEALED_NOTE: () => HANG_SEALED_NOTE,
57560
+ HANG_NOT_PROVEN: () => HANG_NOT_PROVEN,
57406
57561
  BACKSTOP_SEAL_MIN_MS: () => BACKSTOP_SEAL_MIN_MS,
57407
57562
  BACKSTOP_SEAL_MAX_MS: () => BACKSTOP_SEAL_MAX_MS,
57408
57563
  BACKSTOP_SEAL_MARGIN_S: () => BACKSTOP_SEAL_MARGIN_S,
@@ -57583,6 +57738,11 @@ class SupervisorLog {
57583
57738
  }
57584
57739
  }
57585
57740
  function applyCapEnv(env, capS, sized) {
57741
+ if (!Number.isFinite(capS)) {
57742
+ delete env.LOKI_E10_CAP_S;
57743
+ delete env.LOKI_E10_CAP_FIXED_S;
57744
+ return;
57745
+ }
57586
57746
  env.LOKI_E10_CAP_S = String(capS);
57587
57747
  if (sized) {
57588
57748
  if (sized.fixedS)
@@ -57641,10 +57801,12 @@ async function runSupervisor(opts) {
57641
57801
  else
57642
57802
  delete workerEnv[WORK_ROAD_ENV];
57643
57803
  workerEnv.LOKI_INTENT_TTY = env.LOKI_CONFIRM === "1" && process.stdin.isTTY === true && process.stdout.isTTY === true ? "1" : "0";
57644
- const capS = opts.capS ?? envCapS(env.LOKI_E10_CAP_S) ?? DEFAULT_CAP_S;
57804
+ const capS = opts.capS ?? envCapS(env.LOKI_E10_CAP_S) ?? (budgetsOn(env) ? DEFAULT_CAP_S : Infinity);
57645
57805
  const ceilingS = Math.max(capS, opts.capCeilingS ?? capS);
57646
57806
  const backstopMs = backstopS(ceilingS, opts.graceS ?? BACKSTOP_GRACE_S) * 1000;
57647
- const escalateMs = Math.max(0, Math.min(2000, ceilingS * 1000 - backstopMs));
57807
+ const escalateMs = Number.isFinite(ceilingS) ? Math.max(0, Math.min(2000, ceilingS * 1000 - backstopMs)) : 2000;
57808
+ let lastEventMs = Date.now();
57809
+ const hang = Number.isFinite(ceilingS) ? undefined : { silenceS: hangSilenceS(env), lastEventMs: () => lastEventMs };
57648
57810
  let spawnArgv = opts.workerArgv;
57649
57811
  try {
57650
57812
  spawnArgv = ulimitArgv(opts.workerArgv, workerEnv);
@@ -57655,6 +57817,7 @@ async function runSupervisor(opts) {
57655
57817
  const onWorkerLine = (line2) => {
57656
57818
  const e = log.ingest(line2);
57657
57819
  if (e) {
57820
+ lastEventMs = Date.now();
57658
57821
  stuck.event(String(e.stage ?? "unknown"), Date.now());
57659
57822
  quiet.event(e.stage ?? null, e.type, Date.now());
57660
57823
  }
@@ -57669,7 +57832,7 @@ async function runSupervisor(opts) {
57669
57832
  }
57670
57833
  };
57671
57834
  let workerStopped = false;
57672
- let worker = await spawnWorker(opts.workerArgv, workerEnv, opts.repoDir, backstopMs, escalateMs, onWorkerLine, (stopped) => {
57835
+ let worker = await spawnWorker(opts.workerArgv, workerEnv, opts.repoDir, backstopMs, escalateMs, onWorkerLine, hang, (stopped) => {
57673
57836
  for (const g2 of sessionGroups)
57674
57837
  killGroup2(g2, "SIGKILL");
57675
57838
  workerStopped = stopped;
@@ -57694,7 +57857,7 @@ async function runSupervisor(opts) {
57694
57857
  safeGit(opts.repoDir, ["checkout", runBr], { stdio: "ignore" });
57695
57858
  } catch {}
57696
57859
  log.sealLog();
57697
- const sealed2 = await spawnWorker(opts.workerArgv, { ...workerEnv, LOKI_E10_RESUME: "1", LOKI_E10_SEAL_ONLY: "1" }, opts.repoDir, leftMs, escalateMs, onWorkerLine, () => {
57860
+ const sealed2 = await spawnWorker(opts.workerArgv, { ...workerEnv, LOKI_E10_RESUME: "1", LOKI_E10_SEAL_ONLY: "1" }, opts.repoDir, leftMs, escalateMs, onWorkerLine, undefined, () => {
57698
57861
  for (const g2 of sessionGroups)
57699
57862
  killGroup2(g2, "SIGKILL");
57700
57863
  });
@@ -57710,7 +57873,7 @@ async function runSupervisor(opts) {
57710
57873
  const receiptVerdict = workerExit === 0 && typeof v === "string" && VERDICTS2.has(v), verdict = receiptVerdict ? v : "FAILED";
57711
57874
  const notProven2 = Array.isArray(sealedData?.not_proven) ? sealedData.not_proven.map(String) : [];
57712
57875
  if (worker.killed)
57713
- notProven2.push(sealPass && sealed ? BACKSTOP_SEALED_NOTE : BACKSTOP_NOT_PROVEN);
57876
+ notProven2.push(worker.hung ? sealPass && sealed ? HANG_SEALED_NOTE : HANG_NOT_PROVEN : sealPass && sealed ? BACKSTOP_SEALED_NOTE : BACKSTOP_NOT_PROVEN);
57714
57877
  const ev0 = readEvents(log.path), usage = worker.cancelled ? null : usageLimitOfRun(ev0);
57715
57878
  const cancelled2 = worker.cancelled ?? (ev0.some((e) => e.type === "cancel_effective") ? "request" : usage ? "usage limit" : null);
57716
57879
  if (cancelled2)
@@ -57834,7 +57997,16 @@ async function main3(args) {
57834
57997
  verbose = true;
57835
57998
  else if (a === "--quiet")
57836
57999
  quiet = true;
57837
- else if (a === "--max-cost") {
58000
+ else if (TIME_FLAGS[a.split("=")[0]]) {
58001
+ const name = a.split("=")[0], v = a.includes("=") ? a.slice(a.indexOf("=") + 1) : args[++i], s = parseDurationS(v);
58002
+ if (s === null) {
58003
+ process.stderr.write(`engine10: ${name} needs a duration (seconds, or 90m / 2h), got '${v ?? ""}'
58004
+ `);
58005
+ noteRefusal("unsupported_flag");
58006
+ return 2;
58007
+ }
58008
+ process.env[TIME_FLAGS[name]] = String(s);
58009
+ } else if (a === "--max-cost") {
57838
58010
  const v = args[i + 1];
57839
58011
  if (v === undefined || v === "" || v.startsWith("-")) {
57840
58012
  process.stderr.write(`engine10: --max-cost needs a value
@@ -57902,7 +58074,7 @@ async function main3(args) {
57902
58074
  eoo = true;
57903
58075
  else if (!eoo && /^--?[A-Za-z][\w-]*(=\S*)?$/.test(a)) {
57904
58076
  process.stderr.write(`engine10: unknown flag ${a}
57905
- usage: loki "<task>" [--no-pr] [--deep] [--verified] [--json] [--verbose] [--quiet] [--max-cost N] [--provider P] [--spec F] [--seal-existing PATCH] [--resume] [--fresh] [--base-current] [-- <task>]
58077
+ usage: loki "<task>" [--no-pr] [--deep] [--verified] [--json] [--verbose] [--quiet] [--max-cost N] [--max-time DUR] [--verify-max-time DUR] [--provider P] [--spec F] [--seal-existing PATCH] [--resume] [--fresh] [--base-current] [-- <task>]
57906
58078
  `);
57907
58079
  noteRefusal("unsupported_flag");
57908
58080
  return 2;
@@ -58420,7 +58592,7 @@ var START_LINE = "Loki 10 engine", TAMPER_NOT_PROVEN = "event log modified outsi
58420
58592
  return 120;
58421
58593
  const v = Number(raw2);
58422
58594
  return Number.isFinite(v) && v >= 0 ? v : 120;
58423
- }, deepPostOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_DEEP_POST"] ?? "").trim()), VERDICTS2, ALIVE_BEAT_MS = 15000, SESSION_EXITS, BACKSTOP_NOT_PROVEN = "worker killed by the supervisor backstop (cap minus grace)", BACKSTOP_SEALED_NOTE = "time ran out: the worker was stopped at its time limit and the current tree was sealed by a seal pass", backstopSealOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BACKSTOP_SEAL"] ?? "").trim()), BACKSTOP_SEAL_MAX_MS = 45000, BACKSTOP_SEAL_MIN_MS = 1e4, BACKSTOP_SEAL_MARGIN_S = 25, isRev = (r) => typeof r === "object" && r !== null && Number.isInteger(r.rev) && nonNegNum(r.at), nonNegNum = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0, ISSUE_RE, runSummaryCost = (events2, tampered, repoDir) => summaryCost(events2, tampered, join135(repoDir, ".loki"));
58595
+ }, deepPostOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_DEEP_POST"] ?? "").trim()), VERDICTS2, ALIVE_BEAT_MS = 15000, SESSION_EXITS, BACKSTOP_NOT_PROVEN = "worker killed by the supervisor backstop (cap minus grace)", HANG_NOT_PROVEN = "worker stopped by the supervisor: no event and no running process for the hang window (LOKI_E10_HANG_SILENCE_S)", HANG_SEALED_NOTE = "the worker made no progress (no event and no running process for the hang window) and was stopped; the current tree was sealed by a seal pass", BACKSTOP_SEALED_NOTE = "time ran out: the worker was stopped at its time limit and the current tree was sealed by a seal pass", backstopSealOn = (env = process.env) => !/^(0|off|false|no)$/i.test((env["LOKI_E10_BACKSTOP_SEAL"] ?? "").trim()), BACKSTOP_SEAL_MAX_MS = 45000, BACKSTOP_SEAL_MIN_MS = 1e4, BACKSTOP_SEAL_MARGIN_S = 25, isRev = (r) => typeof r === "object" && r !== null && Number.isInteger(r.rev) && nonNegNum(r.at), nonNegNum = (v) => typeof v === "number" && Number.isFinite(v) && v >= 0, ISSUE_RE, runSummaryCost = (events2, tampered, repoDir) => summaryCost(events2, tampered, join135(repoDir, ".loki"));
58424
58596
  var init_supervisor = __esm(() => {
58425
58597
  init_worker_proc();
58426
58598
  init_route_block();
@@ -107555,13 +107727,13 @@ function createSessionRunner(cfg) {
107555
107727
  };
107556
107728
  cfg.emit?.("session.started", opts.stage, { session_id: sessionId, provider: cfg.provider, model: opts.model ?? cfg.model ?? null, pgid: pgid ?? null });
107557
107729
  const onAbort = () => kill("aborted");
107558
- const limitTimer = setTimeout(() => kill("limit"), opts.limitS * 1000);
107730
+ const limitTimer = armTimer(() => kill("limit"), opts.limitS * 1000);
107559
107731
  const capUsd = parseCapUsd(process.env["LOKI_E10_MAX_COST_USD"]), effDir = cfg.lokiRoot ? join162(cfg.lokiRoot, "metrics", "efficiency") : null, effBase = effDir !== null && capUsd !== null ? calculateCostFromRecords(readEfficiencyDir(effDir)) : 0;
107560
107732
  const stopBudgetWatch = isGuarded(cfg.provider) && capUsd !== null ? watchBudget(() => (cfg.remaining?.() ?? 1) <= 0 || effDir !== null && calculateCostFromRecords(readEfficiencyDir(effDir)) - effBase >= capUsd, () => {
107561
107733
  cfg.emit?.("guard.budget_stop", opts.stage, { provider: cfg.provider });
107562
107734
  kill("limit");
107563
107735
  }) : () => {};
107564
- const watchdog = createWatchdog(Date.now), stallKill = stallKillS();
107736
+ const noLimit = !Number.isFinite(opts.limitS), watchdog = createWatchdog(Date.now), stallKill = stallKillS(undefined, noLimit ? SILENCE_KILL_S : 0), loopKill = noLimit ? loopKillS() : 0;
107565
107737
  const heartbeatTimer = setInterval(() => {
107566
107738
  const un2 = untrackedList(opts.cwd), diff = diffShortstat(opts.cwd, un2), w = watchdog.tick(stdout.length + errBytes, diffSignature(opts.cwd, diff, un2));
107567
107739
  const live2 = readSessionId(opts.cwd ?? process.cwd(), opts.iterationId);
@@ -107570,13 +107742,17 @@ function createSessionRunner(cfg) {
107570
107742
  cfg.emit?.("session.stalled", opts.stage, { session_id: sessionId, idle_s: w.idleS, threshold_s: stallThresholdS() });
107571
107743
  if (stallKill > 0 && w.idleS >= stallKill)
107572
107744
  kill("stalled");
107745
+ else if (loopKill > 0 && w.diffIdleS >= loopKill) {
107746
+ cfg.emit?.("session.looping", opts.stage, { session_id: sessionId, no_tree_change_s: Math.round(w.diffIdleS), threshold_s: loopKill });
107747
+ kill("stalled");
107748
+ }
107573
107749
  }, cfg.heartbeatMs ?? HEARTBEAT_MS_DEFAULT);
107574
107750
  opts.signal.addEventListener("abort", onAbort, { once: true });
107575
107751
  const untrack = trackSession(() => kill("aborted"));
107576
107752
  return new Promise((resolve46) => {
107577
107753
  child.on("exit", () => reapLiveGroup(pgid, () => cfg.emit?.("session.group_reaped", opts.stage, { session_id: sessionId, pgid })));
107578
107754
  child.on("close", (code) => {
107579
- clearTimeout(limitTimer);
107755
+ limitTimer.clear();
107580
107756
  clearInterval(heartbeatTimer);
107581
107757
  stopBudgetWatch();
107582
107758
  if (workRun) {
@@ -107685,6 +107861,7 @@ var init_session3 = __esm(() => {
107685
107861
  init_hooks();
107686
107862
  init_session_resume();
107687
107863
  init_session_route();
107864
+ init_types2();
107688
107865
  init_worker_proc();
107689
107866
  init_providers();
107690
107867
  init_model_rank();
@@ -110688,7 +110865,8 @@ function startWatchdog(pgid) {
110688
110865
  }
110689
110866
  }
110690
110867
  function spawnGroupSync(cmd2, args, o) {
110691
- const r = spawnSync30(process.execPath, [...SAFE_BUN_FLAGS, "-e", GROUP_LAUNCHER], { input: JSON.stringify([cmd2, args, o.cwd ?? "", o.timeoutMs, watchdogArgv(), o.env ?? plainTestEnv()]), env: { PATH: process.env["PATH"] ?? "" }, encoding: "utf8", timeout: o.timeoutMs + 5000, killSignal: "SIGKILL", maxBuffer: 16 * 1024 * 1024 });
110868
+ const fin = Number.isFinite(o.timeoutMs);
110869
+ const r = spawnSync30(process.execPath, [...SAFE_BUN_FLAGS, "-e", GROUP_LAUNCHER], { input: JSON.stringify([cmd2, args, o.cwd ?? "", fin ? o.timeoutMs : 0, watchdogArgv(), o.env ?? plainTestEnv(), fin ? 0 : cmdSilenceS() * 1000]), env: { PATH: process.env["PATH"] ?? "" }, encoding: "utf8", ...fin ? { timeout: o.timeoutMs + 5000 } : {}, killSignal: "SIGKILL", maxBuffer: 16 * 1024 * 1024 });
110692
110870
  try {
110693
110871
  return JSON.parse(r.stdout);
110694
110872
  } catch {
@@ -110701,10 +110879,14 @@ function spawnCollect(cmd2, args, o) {
110701
110879
  let out3 = "", err = "", error = false, done = false;
110702
110880
  const MAX = o.maxBytes ?? 1024 * 1024;
110703
110881
  const timers = [];
110882
+ let main9, quiet, lastByte = Date.now();
110704
110883
  const fin = (status2) => {
110705
110884
  if (!done) {
110706
110885
  done = true;
110707
110886
  timers.forEach(clearTimeout);
110887
+ main9?.clear();
110888
+ if (quiet)
110889
+ clearInterval(quiet);
110708
110890
  o.signal?.removeEventListener("abort", abort);
110709
110891
  killGroup2(c.pid, "SIGKILL");
110710
110892
  wd2?.kill("SIGKILL");
@@ -110721,14 +110903,22 @@ ${err}` });
110721
110903
  c.kill("SIGTERM");
110722
110904
  }
110723
110905
  };
110724
- timers.push(setTimeout(() => {
110906
+ const expire = () => {
110725
110907
  error = true;
110726
110908
  term();
110727
110909
  timers.push(setTimeout(() => {
110728
110910
  killGroup2(c.pid, "SIGKILL");
110729
110911
  fin(null);
110730
110912
  }, 1000));
110731
- }, o.timeoutMs));
110913
+ };
110914
+ main9 = armTimer(expire, o.timeoutMs);
110915
+ if (!Number.isFinite(o.timeoutMs))
110916
+ quiet = setInterval(() => {
110917
+ if (Date.now() - lastByte >= cmdSilenceS() * 1000) {
110918
+ clearInterval(quiet);
110919
+ expire();
110920
+ }
110921
+ }, Math.min(30000, Math.max(50, cmdSilenceS() * 250)));
110732
110922
  const abort = () => {
110733
110923
  error = true;
110734
110924
  term();
@@ -110748,10 +110938,12 @@ ${err}` });
110748
110938
  }
110749
110939
  };
110750
110940
  c.stdout?.on("data", (d) => {
110941
+ lastByte = Date.now();
110751
110942
  out3 += d;
110752
110943
  over2();
110753
110944
  });
110754
110945
  c.stderr?.on("data", (d) => {
110946
+ lastByte = Date.now();
110755
110947
  err += d;
110756
110948
  over2();
110757
110949
  });
@@ -111186,14 +111378,14 @@ exit $st`, wrapperOr = (repoDir, w, bare) => existsSync120(join167(repoDir, w))
111186
111378
  }, verifyJobs = () => {
111187
111379
  const n10 = Number.parseInt(process.env["LOKI_E10_VERIFY_JOBS"] ?? "", 10);
111188
111380
  return Number.isFinite(n10) && n10 >= 1 ? Math.min(n10, 8) : 1;
111189
- }, WATCHDOG = `const O = __O__, G = __G__; setInterval(() => { try { process.kill(O, 0); } catch { try { process.kill(-G, "SIGKILL"); } catch {} process.exit(0); } }, 200);`, watchdogArgv = () => [process.execPath, ...SAFE_BUN_FLAGS, "-e", WATCHDOG], GROUP_LAUNCHER = `const { spawn } = require("node:child_process"); const fs = require("node:fs"); const [cmd, args, cwd, ms, wd, env] = JSON.parse(fs.readFileSync(0, "utf8")); const MAX = 1048576; let out = "", err = "", to = false, fin = false;
111381
+ }, WATCHDOG = `const O = __O__, G = __G__; setInterval(() => { try { process.kill(O, 0); } catch { try { process.kill(-G, "SIGKILL"); } catch {} process.exit(0); } }, 200);`, watchdogArgv = () => [process.execPath, ...SAFE_BUN_FLAGS, "-e", WATCHDOG], GROUP_LAUNCHER = `const { spawn } = require("node:child_process"); const fs = require("node:fs"); const [cmd, args, cwd, ms, wd, env, sil] = JSON.parse(fs.readFileSync(0, "utf8")); const MAX = 1048576; let out = "", err = "", to = false, fin = false, last = Date.now();
111190
111382
  const c = spawn(cmd, args, { cwd: cwd || undefined, env, detached: true, stdio: ["ignore", "pipe", "pipe"] });
111191
111383
  let w; try { const a = wd.slice(1); a[a.length - 1] = a[a.length - 1].replace("__O__", String(process.pid)).replace("__G__", String(c.pid)); w = spawn(wd[0], a, { detached: true, stdio: "ignore", env: { PATH: process.env.PATH || "" } }); w.on("error", () => {}); } catch {}
111192
111384
  const kill = (s) => { try { process.kill(-c.pid, s); } catch { try { c.kill(s); } catch {} } };
111193
111385
  const done = (code, sig) => { if (fin) return; fin = true; kill("SIGKILL"); try { w.kill("SIGKILL"); } catch {} const b = Buffer.from(JSON.stringify({ status: to || sig ? null : code, output: out + "\\n" + err })); for (let i = 0; i < b.length;) { try { i += fs.writeSync(1, b, i); } catch (e) { if (e.code !== "EAGAIN") break; } } process.exit(0); };
111194
- setTimeout(() => { to = true; kill("SIGTERM"); setTimeout(() => done(null, 1), 1000); }, ms);
111386
+ const expire = () => { to = true; kill("SIGTERM"); setTimeout(() => done(null, 1), 1000); }; if (ms) setTimeout(expire, ms); if (sil) { const q = setInterval(() => { if (Date.now() - last >= sil) { clearInterval(q); expire(); } }, Math.min(30000, Math.max(50, Math.floor(sil / 4)))); }
111195
111387
  const over = () => { if (out.length > MAX || err.length > MAX) { to = true; kill("SIGKILL"); } };
111196
- c.stdout.on("data", (d) => { out += d; over(); }); c.stderr.on("data", (d) => { err += d; over(); });
111388
+ c.stdout.on("data", (d) => { last = Date.now(); out += d; over(); }); c.stderr.on("data", (d) => { last = Date.now(); err += d; over(); });
111197
111389
  c.on("error", () => done(null, 1)); c.on("close", done); c.on("exit", (a, b) => setTimeout(() => done(a, b), 500)); `, importProbe, venvSkips, venvSkipNotes = (repoDir) => [...venvSkips].filter(([k10]) => k10.startsWith(`${repoDir}\x00`)).map(([, v10]) => v10), FULL_SUITE_STATIC, BUILD_TOOL_RUNNERS, genericSuiteLine = (runner, repoDir) => {
111198
111390
  const f = discoveredSuiteCmd(runner, repoDir);
111199
111391
  return [f.cmd, ...f.args].join(" ");
@@ -111205,6 +111397,7 @@ var init_check_result = __esm(() => {
111205
111397
  init_resolve();
111206
111398
  init_guides();
111207
111399
  init_testmap();
111400
+ init_types2();
111208
111401
  init_lock_ecosystems();
111209
111402
  init_python_build_check();
111210
111403
  init_safe_git();
@@ -134748,6 +134941,8 @@ async function resumeToFinish(ctx, first, session3, o) {
134748
134941
  const missing = () => readPlanScope(ctx.runDir).filter((f) => !existsSync122(join171(ctx.repoDir, f)));
134749
134942
  let unchanged = 0;
134750
134943
  let cur = session3, outstanding = outstandingOf(session3.summary), base2 = first, ended = max === 0 ? "continue off" : "count cap", spent = null;
134944
+ const noCount = !Number.isFinite(max), saidBefore = new Set([outstanding]);
134945
+ let fewestMissing = noCount ? missing().length : 0;
134751
134946
  for (let n10 = 1;n10 <= max; n10++) {
134752
134947
  if (o.signal.aborted) {
134753
134948
  ended = "aborted";
@@ -134782,6 +134977,18 @@ async function resumeToFinish(ctx, first, session3, o) {
134782
134977
  ended = "tree unknown";
134783
134978
  break;
134784
134979
  }
134980
+ if (noCount) {
134981
+ const left = missing().length, said = outstandingOf(r.reply.summary), moved = left < fewestMissing || said !== "" && !saidBefore.has(said);
134982
+ fewestMissing = Math.min(fewestMissing, left);
134983
+ saidBefore.add(said);
134984
+ if (moved)
134985
+ unchanged = 0;
134986
+ else if (++unchanged >= noProgressRounds(env2)) {
134987
+ ended = "no progress";
134988
+ break;
134989
+ }
134990
+ continue;
134991
+ }
134785
134992
  if (before === after) {
134786
134993
  if (++unchanged >= 2) {
134787
134994
  ended = "tree unchanged";
@@ -135313,10 +135520,10 @@ var refereeModel = (ctx) => capToRunTier(wallPinModel(), ctx.model, ["LOKI_E10_W
135313
135520
  if (isOff(v10))
135314
135521
  return 0;
135315
135522
  const n10 = Number(v10);
135316
- return v10 !== "" && Number.isInteger(n10) && n10 >= 0 ? Math.min(n10, 10) : CONTINUE_MAX_DEFAULT;
135523
+ return v10 !== "" && Number.isInteger(n10) && n10 >= 0 ? Math.min(n10, 10) : defaultBudgetsOn(env2) ? CONTINUE_MAX_DEFAULT : Infinity;
135317
135524
  }, continueMaxUsd = (env2 = process.env) => {
135318
135525
  const n10 = Number((env2["LOKI_E10_CONTINUE_MAX_USD"] ?? "").trim());
135319
- return (env2["LOKI_E10_CONTINUE_MAX_USD"] ?? "").trim() !== "" && Number.isFinite(n10) && n10 >= 0 ? n10 : CONTINUE_MAX_USD_DEFAULT;
135526
+ return (env2["LOKI_E10_CONTINUE_MAX_USD"] ?? "").trim() !== "" && Number.isFinite(n10) && n10 >= 0 ? n10 : defaultBudgetsOn(env2) ? CONTINUE_MAX_USD_DEFAULT : Infinity;
135320
135527
  }, lacksFinishLine = (provider, s) => provider === "claude" && s.markers.finishLine === null, conflictNeedsTestOn = (env2 = process.env) => /^(1|on|true|yes)$/i.test((env2["LOKI_E10_CONFLICT_NEEDS_TEST"] ?? "").trim()), asUnfinishedConflict = (s) => s.markers.specConflict !== null && !citesTestFile(s.markers.specConflict) ? { ...s, markers: { ...s.markers, specConflict: null, finishLine: s.markers.finishLine === "spec_conflict" ? null : s.markers.finishLine } } : s, resumeForProofScript = (ctx, first, firstSession, brief) => (ctx.implementLeftS?.() ?? Infinity) < RESUME_MIN_LEFT_S ? Promise.resolve({ session: firstSession, iterationId: first.iterationId }) : resumeWith(ctx, first, firstSession, brief, "-pf"), resumeAfterEmptyDone = (ctx, first, firstSession, challenge = false) => resumeWith(ctx, first, firstSession, challenge ? EMPTY_DONE_CHALLENGED : EMPTY_DONE_CORRECTION, "-e"), resumeNeverStop = (ctx, first, firstSession, reason, advice) => (ctx.implementLeftS?.() ?? Infinity) < RESUME_MIN_LEFT_S ? Promise.resolve({ session: firstSession, iterationId: first.iterationId }) : resumeWith(ctx, first, firstSession, neverStopBrief(reason, advice), "-n"), runVerifiedFinish = async (ctx, first, firstSession, brief, maxTurns) => {
135321
135528
  if ((ctx.implementLeftS?.() ?? Infinity) < RESUME_MIN_LEFT_S)
135322
135529
  return null;
@@ -135336,7 +135543,7 @@ var refereeModel = (ctx) => capToRunTier(wallPinModel(), ctx.model, ["LOKI_E10_W
135336
135543
  if (isOff(v10))
135337
135544
  return;
135338
135545
  const n10 = Number(v10);
135339
- return v10 !== "" && Number.isInteger(n10) && n10 > 0 ? n10 : COVERAGE_MAX_TURNS_DEFAULT;
135546
+ return v10 !== "" && Number.isInteger(n10) && n10 > 0 ? n10 : defaultBudgetsOn(env2) ? COVERAGE_MAX_TURNS_DEFAULT : 0;
135340
135547
  }, siteHintsEnabled = (env2 = process.env) => !["0", "off", "false"].includes((env2.LOKI_E10_SITE_HINTS ?? "").toLowerCase()), claimAbsentBrief = (sites) => `You wrote SITE ... changed for these lines, but each is byte-identical to the base: ${sites.join(", ")}. Make the change at each one, or write it as unchanged with the reason. ` + FINISH_LINE, oneLine6 = (s) => s.replace(/[\u0000-\u001f\u007f]+/g, " ").trim().slice(0, 200), REFEREE_PER_CHECK = 1, REFEREE_PER_RUN = 2, wallRefereeEnabled = (env2 = process.env) => !["0", "off", "false"].includes((env2.LOKI_E10_WALL_REFEREE ?? "").toLowerCase()), defaultRunCheck = (dir, ref) => {
135341
135548
  const r = new RealBaseTestRunner(undefined, undefined, { PYTHONDONTWRITEBYTECODE: "1" }).run(dir, [ref]);
135342
135549
  return r.fail > 0 ? "fail" : r.pass > 0 && (r.not_run ?? 0) === 0 ? "pass" : "not_run";
@@ -135373,6 +135580,7 @@ ${diff.length > REMEDY_DIFF_CAP ? `${diff.slice(0, REMEDY_DIFF_CAP)}
135373
135580
  return miss && !impl ? "missing" : impl && !miss ? "implemented" : null;
135374
135581
  }, remedyResumeBrief = (remedy) => `The issue's first-choice remedy is not in your change: "${remedy}". Implement that remedy now, keep any other fix only on top of it, run the targeted tests, then finish. ` + FINISH_LINE, remedyCallOverride = null;
135375
135582
  var init_conflict_resume = __esm(() => {
135583
+ init_types2();
135376
135584
  init_role_agents();
135377
135585
  init_opus_consult();
135378
135586
  init_session_resume();