@0perator/operator 0.1.352 → 0.1.354

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 (92) hide show
  1. package/dist/acp/agent.js +4 -2
  2. package/dist/acp/tool-map.js +5 -4
  3. package/dist/autonomy/delegate.js +55 -2
  4. package/dist/autonomy/headless.js +4 -1
  5. package/dist/autonomy/session-factory.js +1 -0
  6. package/dist/background/index.js +86 -10
  7. package/dist/background/notices.js +16 -4
  8. package/dist/cli.js +1072 -178
  9. package/dist/config/home.js +6 -0
  10. package/dist/config/memory-sections.js +92 -0
  11. package/dist/config/persona.js +144 -26
  12. package/dist/config/settings.js +15 -4
  13. package/dist/consolidation/scheduler.js +9 -2
  14. package/dist/consolidation/sleep.js +39 -278
  15. package/dist/engine/agent.js +547 -92
  16. package/dist/engine/anthropic-chat.js +13 -2
  17. package/dist/engine/aurora.js +135 -30
  18. package/dist/engine/batch-scheduler.js +27 -3
  19. package/dist/engine/compaction.js +12 -5
  20. package/dist/engine/continuation.js +51 -22
  21. package/dist/engine/contract.js +1 -1
  22. package/dist/engine/decision-points.js +7 -1
  23. package/dist/engine/front-door.js +59 -0
  24. package/dist/engine/grandmaster.js +13 -1
  25. package/dist/engine/loop-guard.js +694 -0
  26. package/dist/engine/net-error.js +2 -1
  27. package/dist/engine/owner-act.js +52 -0
  28. package/dist/engine/selfheal.js +48 -0
  29. package/dist/engine/verify-gate.js +52 -0
  30. package/dist/flywheel/processor.js +3 -1
  31. package/dist/flywheel/srft.js +8 -4
  32. package/dist/hooks/index.js +12 -8
  33. package/dist/mcp/index.js +9 -4
  34. package/dist/permissions/index.js +32 -11
  35. package/dist/permissions/modes.js +42 -0
  36. package/dist/permissions/plan-review.js +100 -0
  37. package/dist/permissions/policy.js +16 -5
  38. package/dist/permissions/signature.js +8 -3
  39. package/dist/remote/safe-commands.js +1 -1
  40. package/dist/router/read-rates.js +152 -0
  41. package/dist/selfimprove/backfill.js +174 -0
  42. package/dist/selfimprove/index.js +146 -57
  43. package/dist/selfimprove/lessons.js +429 -0
  44. package/dist/selfimprove/sync.js +58 -0
  45. package/dist/session.js +375 -31
  46. package/dist/skills/finder.js +219 -0
  47. package/dist/tools/deferred.js +28 -18
  48. package/dist/tools/executor.js +7 -3
  49. package/dist/tools/registry.js +34 -4
  50. package/dist/ui/ActivitySpinner.js +21 -12
  51. package/dist/ui/App.js +107 -30
  52. package/dist/ui/ApprovalPrompt.js +5 -3
  53. package/dist/ui/ArtifactPicker.js +3 -3
  54. package/dist/ui/BgPanel.js +105 -5
  55. package/dist/ui/Composer.js +85 -9
  56. package/dist/ui/PlanPane.js +72 -8
  57. package/dist/ui/QuestionPrompt.js +6 -4
  58. package/dist/ui/SecretPrompt.js +8 -3
  59. package/dist/ui/SessionPicker.js +2 -2
  60. package/dist/ui/SkillFinder.js +153 -0
  61. package/dist/ui/StatusRule.js +5 -2
  62. package/dist/ui/SummaryCard.js +3 -1
  63. package/dist/ui/ThinkingSpinner.js +11 -2
  64. package/dist/ui/ToolBatch.js +11 -2
  65. package/dist/ui/ToolStep.js +36 -13
  66. package/dist/ui/Transcript.js +13 -2
  67. package/dist/ui/actNow.js +61 -0
  68. package/dist/ui/batchLine.js +165 -0
  69. package/dist/ui/conversations.js +154 -0
  70. package/dist/ui/decodeHealth.js +77 -0
  71. package/dist/ui/expand.js +17 -0
  72. package/dist/ui/fit.js +40 -0
  73. package/dist/ui/fitTail.js +14 -0
  74. package/dist/ui/fold.js +149 -0
  75. package/dist/ui/format.js +46 -2
  76. package/dist/ui/liveTools.js +163 -13
  77. package/dist/ui/modelPicker.js +78 -6
  78. package/dist/ui/nextStep.js +103 -0
  79. package/dist/ui/pending.js +57 -0
  80. package/dist/ui/phase.js +105 -0
  81. package/dist/ui/planExit.js +0 -5
  82. package/dist/ui/progressbar.js +4 -26
  83. package/dist/ui/readForecast.js +44 -0
  84. package/dist/ui/readProgress.js +119 -0
  85. package/dist/ui/reportLine.js +62 -0
  86. package/dist/ui/slashCommands.js +1 -1
  87. package/dist/ui/theme.js +1 -0
  88. package/dist/ui/turnFlow.js +72 -0
  89. package/dist/ui/turnLedger.js +121 -0
  90. package/dist/ui/turnScope.js +11 -0
  91. package/dist/util/slash.js +18 -0
  92. package/package.json +1 -1
@@ -39,6 +39,8 @@ export function resolveLoopGuardConfig(raw, ctx) {
39
39
  stopInvestigateLoop: intAtLeast(s.hardStopAfter?.investigateLoop, d.stopInvestigateLoop, 1),
40
40
  maxWebSearches: intAtLeast(s.caps?.webSearches, d.maxWebSearches, 0),
41
41
  maxSubagents: intAtLeast(s.caps?.subagents, d.maxSubagents, 0),
42
+ compactAfterNudges: intAtLeast(s.compactAfterNudges, 2, 0),
43
+ maxLoopCompactions: Math.min(5, intAtLeast(s.maxLoopCompactions, 2, 0)),
42
44
  };
43
45
  }
44
46
  /** Read-only tools: the same call returning the same result again is no new information. */
@@ -155,6 +157,16 @@ export class LoopGuard {
155
157
  trip(message, code = "repeated_action") { this.stop(code, "tool batch", 0, message); }
156
158
  /** Clear the pending stop only. Evidence, refusal counters and resource caps remain intact. */
157
159
  resume() { this.haltDecision = null; }
160
+ /** A loop reset replaced this turn's tool results with a digest (agent.ts resetLoop): forget the results this guard
161
+ * compares against — the streak, the cycle history, the read-only repeat counts — so the re-read the digest allows
162
+ * comes back whole, not as a stub pointing at a result that is gone. Failure counts and the per-turn caps stay:
163
+ * they count what happened, not what the model can still see. */
164
+ forgetResults() {
165
+ this.noProgress.clear();
166
+ this.history = [];
167
+ this.streak = { sig: "", hash: "", count: 0, firstId: "" };
168
+ this.lastHash.clear();
169
+ }
158
170
  stop(code, tool, count, message) {
159
171
  const d = { action: "halt", code, message, tool, count };
160
172
  this.haltDecision ??= d;
@@ -535,6 +547,11 @@ export class LoopRecovery {
535
547
  this.maxAttempts = maxAttempts;
536
548
  }
537
549
  get attempts() { return this.used; }
550
+ get max() { return this.maxAttempts; }
551
+ /** One attempt for a dead round (agent.ts recoverDeadRound), from the same budget; undefined once it is spent. That
552
+ * recovery puts the repeated calls' results in front of the model, so unlike next() a re-worded repeat of a COMPLETED
553
+ * action is recoverable there. */
554
+ spend() { return this.used < this.maxAttempts ? ++this.used : undefined; }
538
555
  next(d) {
539
556
  // Caps are budgets, and a re-worded repeat of a COMPLETED action has nothing left to recover: both stay terminal.
540
557
  if (d.code === "web_search_cap" || d.code === "subagent_cap" || d.code === "completed_action" || this.used >= this.maxAttempts)
@@ -550,3 +567,680 @@ export class LoopRecovery {
550
567
  `Continue within the existing time, token, round and resource limits.`;
551
568
  }
552
569
  }
570
+ export const noEditNudge = (n) => `You've run ${n} rounds of tools without changing a file. If you've found the root cause, ` +
571
+ `make the change now and verify it. If you're still gathering context that's fine — but if you're ` +
572
+ `going in circles, say so and switch to a genuinely different approach.`;
573
+ export const repeatedStepNudge = (n) => `You've repeated the same step ${n}× with the same result — that approach is not working. Do NOT ` +
574
+ `end the turn or ask the owner how to proceed. STOP repeating it and try a genuinely DIFFERENT approach: a ` +
575
+ `different command, tool, path, or angle; if a tool seems broken, work around it. If you already ` +
576
+ `know the fix (you often do — you just described one), do it now.`;
577
+ export const repeatedStepRedirect = (n) => `You have repeated the SAME step ${n}× and it is STILL not working — repeating it again will not ` +
578
+ `help. Stop and do this explicitly, in order:\n` +
579
+ `1. In ONE line, state exactly WHAT you keep doing and WHY it isn't making progress (what you ` +
580
+ `expected vs what actually happened).\n` +
581
+ `2. Then pick ONE and do it immediately:\n` +
582
+ ` (a) BREAK IT DOWN — split the stuck step into a smaller, concrete sub-action and do just that ` +
583
+ `one thing now; or\n` +
584
+ ` (b) SWITCH APPROACH — a genuinely different tool, command, path, or order of operations; if a ` +
585
+ `tool or command seems broken, work around it.\n` +
586
+ `Do NOT reproduce your previous output, do NOT end the turn, and do NOT ask me how to proceed — ` +
587
+ `decide and act on the smallest next concrete step.`;
588
+ export const reasoningLoopNudge = (n) => `You've spent ${n} rounds thinking at length while only polling/reading — no file ` +
589
+ `changed and no answer given. That is a reasoning loop. Stop deliberating: if you know the next ` +
590
+ `concrete action, take it now with a tool; if you have enough to answer, answer directly and ` +
591
+ `concisely. Extended thinking is now off for the rest of this turn.`;
592
+ export const SELF_LOOP_NUDGE = `You just said you're stuck or looping — that is the moment to CHANGE something concrete, not run the ` +
593
+ `same investigation again. If you understand the root cause, apply the fix NOW with file_edit/file_write ` +
594
+ `and verify it. If a tool, path, or approach isn't working, switch to a genuinely different one. If you ` +
595
+ `are truly blocked, STOP and give the owner one line naming exactly what is blocking you and what you would try next.`;
596
+ /** The re-read warning: `reads` = the files re-read unchanged since the last landed write, with how often. */
597
+ export const staleRereadNudge = (reads, home) => `You re-read ${describeReads(reads, 200, home)} since your last change, and each time got back exactly what you already ` +
598
+ `had — those files have not changed and their content is above. Do not read them (or the same line ranges) again. ` +
599
+ `If you said you would fix something, make that edit now; if the task is a review or a question, write the answer now.`;
600
+ /** One stable phrase per loop-family nudge above. The backfill classifies the notes recorded in old flywheel rows by
601
+ * these, so a nudge may be reworded only if its phrase survives (test/loop-compaction.test.mts pins it). */
602
+ export const LOOP_NUDGE_PHRASES = [
603
+ ["no_write_progress", "You have made no write-progress in the last"],
604
+ ["reasoning_loop", "That is a reasoning loop."],
605
+ ["no_edit_streak", "rounds of tools without changing a file."],
606
+ ["repeated_step", "with the same result — that approach is not working."],
607
+ ["repeated_step", "and it is STILL not working"],
608
+ ["self_loop", "You just said you're stuck or looping"],
609
+ ["stale_reread", "each time got back exactly what you already had"],
610
+ ];
611
+ export function loopNudgeKind(text) {
612
+ return LOOP_NUDGE_PHRASES.find(([, phrase]) => text.includes(phrase))?.[0];
613
+ }
614
+ /** Words of a shell command, quote-aware; unquoted &&, ||, |, ; and & are tokens of their own (`2>&1` stays a word). */
615
+ function shellWords(cmd) {
616
+ const out = [];
617
+ let cur = "", has = false, q = "";
618
+ const flush = () => { if (has)
619
+ out.push(cur); cur = ""; has = false; };
620
+ for (let i = 0; i < cmd.length; i++) {
621
+ const c = cmd[i];
622
+ if (q) {
623
+ if (c === q)
624
+ q = "";
625
+ else if (q === '"' && c === "\\" && i + 1 < cmd.length)
626
+ cur += cmd[++i];
627
+ else
628
+ cur += c;
629
+ continue;
630
+ }
631
+ if (c === "'" || c === '"') {
632
+ q = c;
633
+ has = true;
634
+ continue;
635
+ }
636
+ if (c === "\\" && i + 1 < cmd.length) {
637
+ cur += cmd[++i];
638
+ has = true;
639
+ continue;
640
+ }
641
+ if (/\s/.test(c)) {
642
+ flush();
643
+ continue;
644
+ }
645
+ if ((c === "&" || c === "|" || c === ";") && !(c === "&" && (cur.endsWith(">") || cmd[i + 1] === ">"))) {
646
+ flush();
647
+ const two = cmd.slice(i, i + 2);
648
+ if (two === "&&" || two === "||") {
649
+ out.push(two);
650
+ i++;
651
+ }
652
+ else
653
+ out.push(c);
654
+ continue;
655
+ }
656
+ cur += c;
657
+ has = true;
658
+ }
659
+ flush();
660
+ return out;
661
+ }
662
+ function segments(words) {
663
+ const segs = [[]];
664
+ for (const w of words) {
665
+ if (w === "&&" || w === "||" || w === "|" || w === ";" || w === "&")
666
+ segs.push([]);
667
+ else
668
+ segs[segs.length - 1].push(w);
669
+ }
670
+ return segs.filter((s) => s.length > 0);
671
+ }
672
+ /** POSIX join + normalize, node-free (the engine bundle has no node:path). `~` paths are left as written. */
673
+ export function joinPath(base, p) {
674
+ const full = p.startsWith("/") || p.startsWith("~") || !base ? p : `${base.replace(/\/+$/, "")}/${p}`;
675
+ const abs = full.startsWith("/");
676
+ const parts = [];
677
+ for (const seg of full.split("/")) {
678
+ if (!seg || seg === ".")
679
+ continue;
680
+ if (seg === ".." && parts.length && parts[parts.length - 1] !== "..")
681
+ parts.pop();
682
+ else
683
+ parts.push(seg);
684
+ }
685
+ return (abs ? "/" : "") + parts.join("/");
686
+ }
687
+ const READERS = new Set(["cat", "head", "tail", "sed", "awk", "grep", "egrep", "fgrep", "rg", "nl", "less", "more", "bat", "wc", "cut", "sort", "uniq", "diff", "jq", "strings"]);
688
+ const PATTERN_FIRST = new Set(["sed", "awk", "grep", "egrep", "fgrep", "rg"]); // first operand is the script/pattern, not a file
689
+ const PATTERN_OPTS = new Set(["-e", "-f", "--regexp", "--file", "--expression"]);
690
+ const VALUE_OPTS = {
691
+ grep: new Set(["-A", "-B", "-C", "-m", "--max-count"]), egrep: new Set(["-A", "-B", "-C", "-m"]), fgrep: new Set(["-A", "-B", "-C", "-m"]),
692
+ rg: new Set(["-A", "-B", "-C", "-m", "-g", "-t", "--glob", "--type"]), awk: new Set(["-v", "-F"]),
693
+ };
694
+ const REDIRECT_RE = /^\d*(?:>>?|<|&>)/;
695
+ const PATHISH_RE = /^(?:[\w.~@+-]*\/[\w./@+-]*|[\w.~@+-]*[\w@+-]\.[A-Za-z0-9]{1,8})$/;
696
+ const SHELL_WRITE_VERBS = new Set(["mv", "cp", "rm", "touch", "mkdir", "tee", "patch", "truncate", "ln"]);
697
+ const GIT_WRITE_RE = /^(?:checkout|switch|restore|apply|reset|merge|rebase|stash|pull|cherry-pick|am)$/;
698
+ /** The files a shell command reads, the directory it runs in (a leading `cd`), and whether it changes the tree. */
699
+ function shellReads(command, cwd) {
700
+ let base = cwd;
701
+ const files = [];
702
+ let mutates = false;
703
+ for (const seg of segments(shellWords(command))) {
704
+ const [verb, ...rest] = seg;
705
+ if (verb === "cd") {
706
+ base = rest[0] ? joinPath(base, rest[0]) : base;
707
+ continue;
708
+ }
709
+ if (SHELL_WRITE_VERBS.has(verb) || (verb === "sed" && rest.some((w) => /^-i/.test(w))) || (verb === "git" && GIT_WRITE_RE.test(rest[0] ?? "")))
710
+ mutates = true;
711
+ for (let i = 0; i < seg.length; i++) {
712
+ if (/^\d*>>?$/.test(seg[i]) && seg[i + 1] && seg[i + 1] !== "/dev/null")
713
+ mutates = true;
714
+ else if (/^\d*>>?[^&>]/.test(seg[i]) && !seg[i].endsWith("/dev/null"))
715
+ mutates = true;
716
+ }
717
+ if (!READERS.has(verb) || (verb === "tail" && rest.some((w) => w === "-f" || w === "-F" || w === "--follow")))
718
+ continue;
719
+ let pattern = !PATTERN_FIRST.has(verb);
720
+ for (let i = 0; i < rest.length; i++) {
721
+ const w = rest[i];
722
+ if (REDIRECT_RE.test(w)) {
723
+ if (/^\d*(?:>>?|<)$/.test(w))
724
+ i++;
725
+ continue;
726
+ }
727
+ if (w.startsWith("-") && w.length > 1) {
728
+ if (PATTERN_OPTS.has(w)) {
729
+ pattern = true;
730
+ i++;
731
+ }
732
+ else if (VALUE_OPTS[verb]?.has(w))
733
+ i++;
734
+ continue;
735
+ }
736
+ if (!pattern) {
737
+ pattern = true;
738
+ continue;
739
+ }
740
+ if (w !== "/dev/null" && !/^https?:/.test(w) && !/^[\d.,]+$/.test(w) && PATHISH_RE.test(w))
741
+ files.push(joinPath(base, w));
742
+ }
743
+ }
744
+ const display = command.replace(/^\s*cd\s+\S+\s*&&\s*/, "").replace(/\s+/g, " ").trim();
745
+ return { files, display: display.length > 100 ? display.slice(0, 100) + "…" : display, mutates };
746
+ }
747
+ const FILE_READ_TOOLS = new Set(["file_read", "read_file", "image_inspect"]);
748
+ const WRITE_TOOLS = new Set(["file_write", "file_edit", "file_create", "file_delete"]);
749
+ /** What one tool call READ: files, or — for a read-only call with no file in it — the call itself; `mutates` when a shell
750
+ * command changes the tree. Pollers, writes and everything that is not a read return nothing. Pure and node-free;
751
+ * shared by the engine and the backfill. */
752
+ export function readTargets(name, args, cwd) {
753
+ if (FILE_READ_TOOLS.has(name) && typeof args.path === "string")
754
+ return { files: [joinPath(cwd, args.path)] };
755
+ if (name === "read_files" && Array.isArray(args.paths)) { // paths, or {path, offset, limit} objects
756
+ const paths = args.paths.map((p) => (typeof p === "string" ? p : p?.path)).filter((p) => typeof p === "string");
757
+ return { files: paths.map((p) => joinPath(cwd, p)) };
758
+ }
759
+ if (SHELL_TOOLS.has(name) && typeof args.command === "string") {
760
+ const r = shellReads(args.command, typeof args.cwd === "string" ? args.cwd : cwd);
761
+ if (r.files.length)
762
+ return { files: r.files, mutates: r.mutates };
763
+ return r.mutates || isRepeatable(name, args) || !r.display ? { files: [], mutates: r.mutates } : { files: [], call: `$ ${r.display}` };
764
+ }
765
+ if (IDEMPOTENT_TOOLS.has(name)) {
766
+ const c = canonical(args);
767
+ return { files: [], call: `${name} ${c.length > 100 ? c.slice(0, 100) + "…" : c}` };
768
+ }
769
+ return { files: [] };
770
+ }
771
+ /** Stale re-reads that, with at least one loop warning, mark a turn as looped even when no warning was ignored — a
772
+ * continuation that re-reads the same files after the previous turn's loop. Measured over all 36 flywheel days to
773
+ * 11/02, a stale re-read being the same output again: every such row at 7+ is a loop on inspection (11/02's sh17
774
+ * continuation 10, "use codestack" 7, 10/25's metadata re-query 8), no healthy row with a warning passes 4. (12 was
775
+ * the bar when any second read of a file counted, healthy paging included.) */
776
+ export const LOOPED_STALE_REREADS = 7;
777
+ /** Stale FILE re-reads since the last landed write that earn the re-read warning (staleRereadNudge), at the round that
778
+ * reaches them; the next round that re-reads an unchanged file again is that warning ignored. Measured over the 1,462
779
+ * flywheel rows with steps to 11/02: no row the loop tag leaves clean has more than 4 (the Nova wake turn re-read
780
+ * Demo.tsx 4 times before it wrote), the review loop reached 5 at round 12 (its second warning came at 17) and ARM B
781
+ * of the 11/02 replay re-ran the same five `sed -n` ranges of api.ts at once — 5 in one round. The other warnings say
782
+ * nothing was written; they arrive after 8-15 rounds, 30+ minutes at Aurora's 1-5 minutes a round on a big context. */
783
+ export const STALE_REREAD_NUDGE = 5;
784
+ /** The tag the self-improvement loop puts on a turn: kept out of training, written up as a lesson. */
785
+ export function isLooped(e) {
786
+ return !!e && (e.compactions > 0 || (e.recoveries ?? 0) > 0 || e.ignored > 0 || (e.nudges > 0 && e.stale >= LOOPED_STALE_REREADS));
787
+ }
788
+ // The nudges that are themselves evidence of repetition. No write-progress and no-edit only say nothing was written —
789
+ // a long survey of DIFFERENT files trips them too — so they count as ignored only beside a stale re-read. These three
790
+ // are also the engine's reaction to a reply it just received (agent.ts), so one of them means the model has answered.
791
+ const REPETITION_KINDS = new Set(["reasoning_loop", "repeated_step", "self_loop"]);
792
+ // A call the engine or the executor refused without running it (a guard, a re-worded repeat, a cap, a denial): no read.
793
+ const REFUSED_RE = /^(?:loop guard|repeated action|blocked |permission denied|cancelled|\[interrupted)/i;
794
+ /** A result that says the call never ran (REFUSED_RE). */
795
+ export const refusedResult = (result) => REFUSED_RE.test(result.trimStart());
796
+ // The result guard's own marks (LoopGuard.afterCall): a byte-identical duplicate swapped for a stub, short notes appended.
797
+ const STUB_RE = /^\[note: this result is byte-identical to the /;
798
+ const GUARD_NOTES_RE = /\n\n\[note: [^\n]*\](?:\n\[note: [^\n]*\])*\s*$/;
799
+ /** How a call is named in the loop reset's digest and the dead-round note: `$ sed -n '1,80p' src/a.ts`,
800
+ * `file_read {"path":"src/a.ts"}`. */
801
+ export function callLabel(name, args) {
802
+ if (SHELL_TOOLS.has(name) && typeof args.command === "string")
803
+ return `$ ${shellReads(args.command).display}`;
804
+ const c = canonical(args);
805
+ return `${name} ${c.length > 100 ? c.slice(0, 100) + "…" : c}`;
806
+ }
807
+ /** Per-turn loop evidence, fed in the order things happened: every nudge, every model reply, every settled tool call.
808
+ * Side-effect free. */
809
+ export class LoopEvidenceTracker {
810
+ cwd;
811
+ nudgeCount = 0;
812
+ unheeded = 0;
813
+ answered = false;
814
+ staleSinceWrite = 0;
815
+ repeatSinceWrite = false;
816
+ ignoredCount = 0;
817
+ compactionCount = 0;
818
+ recoveryCount = 0;
819
+ staleCount = 0;
820
+ kinds = {};
821
+ fileReads = new Map();
822
+ callReads = new Map();
823
+ seenFiles = new Map(); // file → hashes of what reading it gave since it last changed
824
+ seenCalls = new Map();
825
+ lastRead = new Map();
826
+ written = new Set();
827
+ staleFiles = new Map(); // file → stale re-reads of it since the last landed write
828
+ staleFileReads = 0;
829
+ staleFresh = false; // a stale file re-read since the last staleRereadDue()
830
+ staleWarned = 0;
831
+ constructor(cwd) {
832
+ this.cwd = cwd;
833
+ }
834
+ /** A loop-family nudge fired. `unheeded`: the warnings since the last landed file write that the model has seen and
835
+ * answered, this one included — one that arrives before any reply to the previous one (no write-progress after a
836
+ * batch, then the no-edit nudge at the top of the next round) joins it, since the model had no chance to heed
837
+ * either; `repeating`: the turn has re-read something unchanged or been told it repeats a step since that write. */
838
+ nudge(kind) {
839
+ this.nudgeCount++;
840
+ this.kinds[kind] = (this.kinds[kind] ?? 0) + 1;
841
+ if (REPETITION_KINDS.has(kind))
842
+ this.repeatSinceWrite = true;
843
+ const repeating = this.repeatSinceWrite || this.staleSinceWrite > 0;
844
+ if (this.unheeded === 0 || this.answered || REPETITION_KINDS.has(kind)) {
845
+ if (++this.unheeded >= 2 && repeating)
846
+ this.ignoredCount++;
847
+ }
848
+ this.answered = false;
849
+ return { unheeded: this.unheeded, repeating };
850
+ }
851
+ /** A model reply arrived: the warnings injected before its request have been seen. */
852
+ responded() { this.answered = true; }
853
+ /** The engine answered the ignored warnings: the turn's rounds were replaced (`ok`) or at least the recovery note went
854
+ * in. The next reset needs fresh evidence; the files already read stay known, so reading one again still counts. */
855
+ recovered(ok) {
856
+ if (ok)
857
+ this.compactionCount++;
858
+ this.unheeded = 0;
859
+ this.staleSinceWrite = 0;
860
+ this.repeatSinceWrite = false;
861
+ this.forgetStale();
862
+ }
863
+ /** A dead round was recovered (agent.ts recoverDeadRound): its looping rounds became one note of what those calls
864
+ * returned. The turn looped (isLooped), and like a reset that note answers the warnings before it. */
865
+ recoveredDeadRound() {
866
+ this.recoveryCount++;
867
+ this.unheeded = 0;
868
+ this.staleSinceWrite = 0;
869
+ this.repeatSinceWrite = false;
870
+ this.forgetStale();
871
+ }
872
+ forgetStale() { this.staleFiles.clear(); this.staleFileReads = 0; this.staleFresh = false; this.staleWarned = 0; }
873
+ /** After a settled round: the files to name in the re-read warning (staleRereadNudge) when this round re-read an
874
+ * unchanged file and the stale file re-reads since the last landed write have reached STALE_REREAD_NUDGE — at most
875
+ * twice between writes: the second time, a round after the first, is that warning ignored. */
876
+ staleRereadDue() {
877
+ const fresh = this.staleFresh;
878
+ this.staleFresh = false;
879
+ if (!fresh || this.staleFileReads < STALE_REREAD_NUDGE || this.staleWarned >= 2)
880
+ return undefined;
881
+ this.staleWarned++;
882
+ return [...this.staleFiles].map(([target, count]) => ({ target, count })).sort((a, b) => b.count - a.count);
883
+ }
884
+ observe(name, args, result = "") {
885
+ const head = result.trimStart();
886
+ if (REFUSED_RE.test(head))
887
+ return; // the call never ran
888
+ if (WRITE_TOOLS.has(name)) {
889
+ if (FAILURE_PREFIX_RE.test(head))
890
+ return;
891
+ this.unheeded = 0;
892
+ this.staleSinceWrite = 0;
893
+ this.repeatSinceWrite = false;
894
+ this.forgetStale();
895
+ if (typeof args.path === "string") {
896
+ const p = joinPath(this.cwd, args.path);
897
+ this.seenFiles.delete(p);
898
+ this.lastRead.delete(p);
899
+ this.written.add(p);
900
+ } // its last output is stale now
901
+ this.seenCalls.clear();
902
+ return;
903
+ }
904
+ const t = readTargets(name, args, this.cwd);
905
+ if (t.mutates) {
906
+ this.seenFiles.clear();
907
+ this.seenCalls.clear();
908
+ }
909
+ if (!t.files.length && !t.call)
910
+ return;
911
+ // The same target giving back something new is no loop (the next page of a file, a different grep over a dir) —
912
+ // the loop guard's own rule. The guard's stub is, by definition, what the previous identical call gave.
913
+ const same = STUB_RE.test(head);
914
+ const body = same ? "" : result.replace(GUARD_NOTES_RE, "");
915
+ const h = same ? "" : hash(body);
916
+ const label = t.files.length && !same ? callLabel(name, args) : "";
917
+ for (const f of new Set(t.files)) {
918
+ if (this.read(f, h, this.fileReads, this.seenFiles)) {
919
+ this.staleFiles.set(f, (this.staleFiles.get(f) ?? 0) + 1);
920
+ this.staleFileReads++;
921
+ this.staleFresh = true;
922
+ }
923
+ if (label)
924
+ this.lastRead.set(f, { call: label, body });
925
+ }
926
+ if (t.call)
927
+ this.read(t.call, h, this.callReads, this.seenCalls);
928
+ }
929
+ /** Count one read of `key`; true when it gave back what `key` already gave since it last changed (stale). */
930
+ read(key, h, counts, seen) {
931
+ counts.set(key, (counts.get(key) ?? 0) + 1);
932
+ const got = seen.get(key);
933
+ const stale = !!got && (h === "" || got.has(h));
934
+ if (stale) {
935
+ this.staleCount++;
936
+ this.staleSinceWrite++;
937
+ }
938
+ if (!got)
939
+ seen.set(key, new Set(h ? [h] : []));
940
+ else if (h)
941
+ got.add(h);
942
+ return stale;
943
+ }
944
+ /** Every file read this turn, most-read first. */
945
+ filesRead() {
946
+ return [...this.fileReads].map(([target, count]) => ({ target, count })).sort((a, b) => b.count - a.count);
947
+ }
948
+ digest() {
949
+ return {
950
+ files: this.filesRead().map((f) => ({ ...f, ...this.lastRead.get(f.target) })),
951
+ written: [...this.written],
952
+ calls: [...this.callReads].filter(([, count]) => count >= 2).map(([target, count]) => ({ target, count })).sort((a, b) => b.count - a.count),
953
+ };
954
+ }
955
+ evidence(top = 5) {
956
+ const rereads = [...this.fileReads, ...this.callReads]
957
+ .filter(([, count]) => count >= 2)
958
+ .map(([target, count]) => ({ target, count }))
959
+ .sort((a, b) => b.count - a.count)
960
+ .slice(0, top);
961
+ return {
962
+ nudges: this.nudgeCount, kinds: { ...this.kinds }, ignored: this.ignoredCount, compactions: this.compactionCount, stale: this.staleCount, rereads,
963
+ ...(this.recoveryCount ? { recoveries: this.recoveryCount } : {}),
964
+ };
965
+ }
966
+ }
967
+ /** Replay a recorded turn's messages (a flywheel row's `steps`) through the tracker: loop-family notes are matched by
968
+ * their phrases, replies by the assistant messages, tool calls by their results. For rows written before the engine
969
+ * reported loop evidence itself. */
970
+ export function loopEvidenceFromSteps(steps, cwd) {
971
+ const t = new LoopEvidenceTracker(cwd);
972
+ const calls = new Map();
973
+ (steps ?? []).forEach((s, i) => {
974
+ if (s.role === "user" && i > 0) {
975
+ const kind = loopNudgeKind(String(s.content ?? ""));
976
+ if (kind)
977
+ t.nudge(kind);
978
+ }
979
+ else if (s.role === "assistant") {
980
+ t.responded();
981
+ for (const c of s.tool_calls ?? []) {
982
+ let args = {};
983
+ try {
984
+ const a = JSON.parse(c.function?.arguments || "{}");
985
+ if (a && typeof a === "object")
986
+ args = a;
987
+ }
988
+ catch { /* unparseable — no targets */ }
989
+ calls.set(c.id ?? "", { name: c.function?.name ?? "", args });
990
+ }
991
+ }
992
+ else if (s.role === "tool") {
993
+ const c = calls.get(s.tool_call_id ?? "");
994
+ if (c)
995
+ t.observe(c.name, c.args, String(s.content ?? ""));
996
+ }
997
+ });
998
+ return t.evidence();
999
+ }
1000
+ /** Whether a flywheel row looped: its tag, else its recorded loop evidence, else its steps replayed. Rows from before the
1001
+ * engine tagged them (11/02's review loop among them, graded:true and scored +2.63 on its continuation) are judged
1002
+ * the same way as new ones — by the fold, the consolidation and the training export alike. */
1003
+ export function rowLooped(row) {
1004
+ return row.looped ?? isLooped(row.loop ?? loopEvidenceFromSteps(row.steps, row.cwd));
1005
+ }
1006
+ /** Longest shared directory of some paths ("" when they share none worth naming). */
1007
+ export function commonDir(paths) {
1008
+ if (!paths.length)
1009
+ return "";
1010
+ const split = paths.map((p) => p.split("/").slice(0, -1));
1011
+ const first = split[0];
1012
+ let n = first.length;
1013
+ for (const s of split) {
1014
+ let i = 0;
1015
+ while (i < n && s[i] === first[i])
1016
+ i++;
1017
+ n = i;
1018
+ }
1019
+ const dir = first.slice(0, n).join("/");
1020
+ return dir && dir !== "." ? dir + "/" : "";
1021
+ }
1022
+ /** "a.ts ×3, b.ts ×2 (in ~/repo/src/)" — the files with their read counts, the shared directory named once and the
1023
+ * home directory (when known) shortened to ~. Items that would pass `maxChars` become "…". */
1024
+ export function describeReads(files, maxChars = 160, home = globalThis.process?.env?.HOME) {
1025
+ if (!files.length)
1026
+ return "";
1027
+ const dir = commonDir(files.map((f) => f.target));
1028
+ const where = dir ? ` (in ${home && dir.startsWith(home + "/") ? "~" + dir.slice(home.length) : dir})` : "";
1029
+ let out = "";
1030
+ for (const f of files) {
1031
+ const it = `${f.target.slice(dir.length)} ×${f.count}`;
1032
+ const next = out ? `${out}, ${it}` : it;
1033
+ if (out && next.length + where.length > maxChars) {
1034
+ out += ", …";
1035
+ break;
1036
+ }
1037
+ out = next;
1038
+ }
1039
+ return out + where;
1040
+ }
1041
+ const NUDGE_LABEL = {
1042
+ no_write_progress: "no write-progress", reasoning_loop: "reasoning loop", no_edit_streak: "no file changed",
1043
+ repeated_step: "repeated step", self_loop: "you said you were looping", stale_reread: "re-read unchanged files",
1044
+ };
1045
+ /** What the loop reset's digest keeps of one file's latest output, and of all of them together (chars). */
1046
+ export const LOOP_DIGEST_FILE_CHARS = 4_000;
1047
+ export const LOOP_DIGEST_CHARS = 16_000;
1048
+ const tilde = (p, home) => (home && p.startsWith(home + "/") ? "~" + p.slice(home.length) : p);
1049
+ /** The digest's file outputs: each distinct latest output once (one `cat a b` serves both files), headed by its files and
1050
+ * the call, capped per file and in total; a file left out is named, never cut silently. */
1051
+ function latestOutputs(files) {
1052
+ const dir = commonDir(files.map((f) => f.target));
1053
+ const groups = new Map();
1054
+ for (const f of files) {
1055
+ if (f.body === undefined || !f.call)
1056
+ continue;
1057
+ const name = f.target.slice(dir.length) || f.target;
1058
+ const g = groups.get(f.body);
1059
+ if (g)
1060
+ g.names.push(name);
1061
+ else
1062
+ groups.set(f.body, { names: [name], call: f.call });
1063
+ }
1064
+ const out = [];
1065
+ const left = [];
1066
+ let used = 0;
1067
+ for (const [body, g] of groups) {
1068
+ const room = Math.min(LOOP_DIGEST_FILE_CHARS, LOOP_DIGEST_CHARS - used);
1069
+ if (room < 200) {
1070
+ left.push(...g.names);
1071
+ continue;
1072
+ }
1073
+ const text = body.length > room ? `${body.slice(0, room)}\n… [${body.length - room} more chars — read only the lines you need]` : body;
1074
+ used += Math.min(body.length, room);
1075
+ out.push(`--- ${g.names.join(", ")} · ${g.call}\n${text.replace(/\s+$/, "") || "(no output)"}`);
1076
+ }
1077
+ if (left.length)
1078
+ out.push(`(no room left for the output of ${left.join(", ")} — read only the lines you need)`);
1079
+ return out.join("\n");
1080
+ }
1081
+ /** The ONE note a loop reset leaves in place of the turn's rounds (agent.ts resetLoop): why, the request, the task list,
1082
+ * what the turn changed and read — with each file's latest output, so nothing has to be read again — the read-only
1083
+ * calls it repeated, the model's own findings, and the next action. `answer` = the request is a review / question /
1084
+ * research (write the answer now); otherwise make the smallest change and verify it. `replaced` = the turn messages
1085
+ * the note stands in for (0: nothing was replaced, the note alone goes in). */
1086
+ export function loopRecoveryNote(o) {
1087
+ const home = o.home ?? globalThis.process?.env?.HOME;
1088
+ const kinds = Object.keys(o.evidence.kinds).map((k) => NUDGE_LABEL[k]).join(", ");
1089
+ const read = o.digest.files.filter((f) => f.body !== undefined).slice(0, 8); // a file written since its last read is in `written`
1090
+ const lines = [
1091
+ `Loop reset: ${o.evidence.nudges} loop warnings this turn (${kinds}) and you kept going the same way, ` +
1092
+ (o.replaced
1093
+ ? `so this turn's ${o.replaced} messages of reads and tool output were replaced by this digest — a clean context. Earlier turns are untouched.`
1094
+ : "so stop and reset now — this note replaces the warnings."),
1095
+ `The request: "${o.request.replace(/\s+/g, " ").trim().slice(0, 200)}"`,
1096
+ ];
1097
+ if (o.tasks?.trim())
1098
+ lines.push(o.tasks.trim());
1099
+ if (o.digest.written.length)
1100
+ lines.push(`Files you changed this turn: ${o.digest.written.map((p) => tilde(p, home)).join(", ")} — read one again only right before you edit it further.`);
1101
+ const shown = describeReads(read, 220, home);
1102
+ if (shown)
1103
+ lines.push(`Files you read this turn (times): ${shown}. Their latest output is below — work from it and do NOT read them again; if one exact detail is missing, read only that line range, once.`);
1104
+ if (o.digest.calls.length)
1105
+ lines.push(`Calls you repeated: ${o.digest.calls.slice(0, 5).map((c) => `${c.target} ×${c.count}`).join("; ")}.`);
1106
+ if (o.findings.length)
1107
+ lines.push(`What you found so far (your own notes):\n${o.findings.map((f) => `- ${f}`).join("\n")}`);
1108
+ const outputs = o.replaced ? latestOutputs(read) : ""; // nothing replaced: the outputs are still above
1109
+ if (outputs)
1110
+ lines.push(`Latest output of each file, as you last saw it:\n${outputs}`);
1111
+ lines.push(o.answer
1112
+ ? "Next action: write the answer for the owner now from what you have — what you checked, what you found, what you fixed, and what is still unverified. Prove a claim by running the project's type-check or tests once (for TypeScript: `npx tsc --noEmit`), never by reading the files again; a bundle/build step alone does not prove the code is correct."
1113
+ : "Next action: make the smallest change that moves the task forward, then verify it with the project's type-check and tests (for TypeScript: `npx tsc --noEmit`, then the test suite) — a bundle/build step alone does not prove the code is correct. Do not start another pass over the files.");
1114
+ return lines.join("\n");
1115
+ }
1116
+ // ── Dead rounds: a loop of refused repeats is recovered, and the turn goes on (2026-11-03) ─────────────────────
1117
+ // 11/03, Cortana on JL1: `grep -n "pub(crate) fn html_escape" src/routes.rs` and `sed -n '1315,1340p' src/routes.rs`, every
1118
+ // round, 12 times. agent.ts refused both from the 5th (LOOP_GUARD_LIMIT) but ended the turn only at the 10th
1119
+ // (LOOP_GUARD_HARD) and two recovery notes later: eight rounds of ~40 s that ran nothing. A round whose EVERY call is
1120
+ // refused as a repeat — by the identical-args or the repeated-action guard — is a dead round. At the first one the engine
1121
+ // replaces the looping rounds with ONE note of what those calls already returned and a review directive, and the turn goes
1122
+ // on (agent.ts recoverDeadRound). LoopRecovery's budget bounds it; past it the turn ends with loopStopNote. Owner, 11/03:
1123
+ // "the point is for the loop to be broken and the model to adjust / review and proceed - not stop".
1124
+ /** What a dead-round note keeps of one result, and of all of them (chars). */
1125
+ export const DEAD_ROUND_RESULT_CHARS = 2_000;
1126
+ export const DEAD_ROUND_NOTE_CHARS = 8_000;
1127
+ const LEDGER_RESULTS = 3; // distinct results an action keeps, the latest
1128
+ export const DEAD_ROUND_DIRECTIVE = "Review what you know; the next step must be different: an edit, a different command, an updated task list, or a question to the owner.";
1129
+ /** What every action this turn returned, by action fingerprint (agent.ts: a re-worded spelling is the same action), so a
1130
+ * dead-round note can hand the model the results instead of a refusal. Cleared when a write lands: what a call returned
1131
+ * before the change may no longer be true (the engine's repeat counters start over there too). */
1132
+ export class CallLedger {
1133
+ byFp = new Map();
1134
+ entry(fp, name, args) {
1135
+ let e = this.byFp.get(fp);
1136
+ if (!e) {
1137
+ e = { labels: [], name, args, ran: 0, refused: 0, results: new Map(), seen: new Set() };
1138
+ this.byFp.set(fp, e);
1139
+ }
1140
+ const label = callLabel(name, args);
1141
+ if (!e.labels.includes(label))
1142
+ e.labels.push(label);
1143
+ return e;
1144
+ }
1145
+ ran(fp, name, args, result) {
1146
+ const e = this.entry(fp, name, args);
1147
+ e.ran++;
1148
+ const body = result.replace(GUARD_NOTES_RE, "");
1149
+ const key = hash(body);
1150
+ e.seen.add(key);
1151
+ const seen = e.results.get(key);
1152
+ e.results.delete(key); // re-inserted last: the latest result is the last one
1153
+ e.results.set(key, seen ? { ...seen, times: seen.times + 1 } : { body: body.slice(0, DEAD_ROUND_RESULT_CHARS), chars: body.length, times: 1 });
1154
+ if (e.results.size > LEDGER_RESULTS)
1155
+ e.results.delete(e.results.keys().next().value);
1156
+ }
1157
+ refused(fp, name, args) {
1158
+ this.entry(fp, name, args).refused++;
1159
+ }
1160
+ clear() { this.byFp.clear(); }
1161
+ /** The actions behind `fps`, in that order (an action never seen is skipped). */
1162
+ calls(fps) {
1163
+ const out = [];
1164
+ for (const fp of fps) {
1165
+ const e = this.byFp.get(fp);
1166
+ if (e)
1167
+ out.push({ labels: [...e.labels], name: e.name, args: e.args, ran: e.ran, refused: e.refused, results: [...e.results.values()], distinct: e.seen.size });
1168
+ }
1169
+ return out;
1170
+ }
1171
+ /** The actions in the current repetition since the last landed write: refused at least once, or run `minRan` times.
1172
+ * A loop that alternates calls (A, B, A, B) refuses one per round; its other members count here too, so a recovery
1173
+ * replaces the whole cycle, not just the round that went dead. */
1174
+ repeating(minRan) {
1175
+ return [...this.byFp].filter(([, e]) => e.refused > 0 || e.ran >= minRan).map(([fp]) => fp);
1176
+ }
1177
+ }
1178
+ /** The note's results: each action's latest result once — actions that gave the same output share it — cut per result
1179
+ * and in total; an action left out is named, never cut silently. */
1180
+ function repeatedResults(calls) {
1181
+ const groups = new Map();
1182
+ for (const c of calls) {
1183
+ const last = c.results[c.results.length - 1];
1184
+ const same = c.distinct <= 1 && c.ran > 1 ? ", the same output each time" : c.distinct > 1 ? `, ${c.distinct} different outputs — the latest` : "";
1185
+ const head = `${c.labels.join(" | ")} · ran ${c.ran}×${same}`;
1186
+ const g = groups.get(last?.body ?? `\0${head}`);
1187
+ if (g)
1188
+ g.heads.push(head);
1189
+ else
1190
+ groups.set(last?.body ?? `\0${head}`, { heads: [head], chars: last?.chars ?? 0 });
1191
+ }
1192
+ const out = [];
1193
+ const left = [];
1194
+ let used = 0;
1195
+ for (const [body, g] of groups) {
1196
+ const none = body.startsWith("\0");
1197
+ if (!none && used + Math.min(body.length, DEAD_ROUND_RESULT_CHARS) > DEAD_ROUND_NOTE_CHARS) {
1198
+ left.push(...g.heads.map((h) => h.split(" · ")[0]));
1199
+ continue;
1200
+ }
1201
+ used += none ? 0 : body.length;
1202
+ const more = g.chars > body.length ? `\n… [${g.chars - body.length} more chars — if you need them, read only those lines]` : "";
1203
+ out.push(`--- ${g.heads.join("\n--- ")}\n${none ? "(no output was recorded)" : body.replace(/\s+$/, "") || "(no output)"}${more}`);
1204
+ }
1205
+ if (left.length)
1206
+ out.push(`(no room left for the output of ${left.join(", ")} — if you need it, read only the part you need)`);
1207
+ return out.join("\n");
1208
+ }
1209
+ /** The ONE note that stands in for a dead round's looping rounds (agent.ts recoverDeadRound): what happened, the request
1210
+ * and the task list, what those calls returned, and the review directive. `answer` = the request is a review / question /
1211
+ * research, where writing the answer is the different step. `rounds` = the looping rounds the note replaced. */
1212
+ export function deadRoundNote(o) {
1213
+ const lines = [
1214
+ `Loop recovery ${o.attempt}/${o.max}: your last round only repeated calls that had already run, and every one came back refused as a repeat — ` +
1215
+ (o.rounds > 1 ? `so the ${o.rounds} rounds of those calls were replaced by this note.` : "so that round was replaced by this note."),
1216
+ `The request: "${o.request.replace(/\s+/g, " ").trim().slice(0, 200)}"`,
1217
+ ];
1218
+ if (o.tasks?.trim())
1219
+ lines.push(o.tasks.trim());
1220
+ lines.push(`What those calls returned (each result once):\n${repeatedResults(o.calls)}`);
1221
+ const allSame = o.calls.every((c) => c.distinct <= 1);
1222
+ lines.push(`${allSame ? "Running them again returns the same and is refused." : "Running them again is refused; their outputs changed between runs, so check what changed before you rely on the latest."} ${DEAD_ROUND_DIRECTIVE}` +
1223
+ (o.answer ? " If you already have what the request needs, the answer is that step: write it now." : ""));
1224
+ return lines.join("\n");
1225
+ }
1226
+ /** The stop when a dead round finds the recovery budget spent; loopStopNote words it. */
1227
+ export function deadRoundStop(calls, count) {
1228
+ const named = calls.map((c) => c.labels[0]).filter(Boolean);
1229
+ const list = named.slice(0, 3).join(", ") + (named.length > 3 ? ", …" : "");
1230
+ return { action: "halt", code: "repeated_action", tool: calls[0]?.name ?? "tool batch", count, message: `every call in the round was refused as a repeat again (${list || "the same calls"})` };
1231
+ }
1232
+ const MENTOR_WAKE_RE = /^\s*\[mentor-wake\]/;
1233
+ const SYSTEM_NOTICE_RE = /^\s*\[system notice\]/;
1234
+ const BUS_MESSAGE_RE = /^--- from [^\s·]+(?: · ([^\n]+?))? \([^)\n]*\) ---\n([^\n]*)/m;
1235
+ /** A turn the shell started to deliver a background job's notice or a sub-agent's report: it serves the request before
1236
+ * it (the owner's last one), which only the caller knows. */
1237
+ export const isSystemNotice = (input) => SYSTEM_NOTICE_RE.test(input);
1238
+ /** The request a turn serves, in the words of whoever asked: for a `[mentor-wake]` turn the first bus message's subject
1239
+ * and opening line (bus/inbox.ts buildMentorWake) — the mentor asked, not the owner; otherwise the input itself. */
1240
+ export function servedTask(input) {
1241
+ if (!MENTOR_WAKE_RE.test(input))
1242
+ return input;
1243
+ const m = BUS_MESSAGE_RE.exec(input);
1244
+ const task = m ? [m[1], m[2]].map((x) => x?.trim()).filter(Boolean).join(": ") : "";
1245
+ return task || input;
1246
+ }