pi-braid 0.43.7 → 0.43.9

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 (64) hide show
  1. package/CHANGELOG.md +72 -0
  2. package/TOOLS.md +1 -1
  3. package/build-info.json +4 -4
  4. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  5. package/dist/extensions/core/skills-tool/auto-inject.d.ts +21 -0
  6. package/dist/extensions/core/skills-tool/auto-inject.js +105 -1
  7. package/dist/extensions/core/skills-tool/index.js +20 -2
  8. package/dist/extensions/core/skills-tool/loading-guidance.d.ts +4 -1
  9. package/dist/extensions/core/skills-tool/loading-guidance.js +4 -1
  10. package/dist/extensions/core/skills-tool/session-records.d.ts +107 -9
  11. package/dist/extensions/core/skills-tool/session-records.js +141 -5
  12. package/dist/extensions/enforcement/handlers/analysis/dreamer-handler.js +5 -1
  13. package/dist/extensions/enforcement/handlers/register-tool-call.js +5 -2
  14. package/dist/extensions/enforcement/verification-judge.d.ts +7 -0
  15. package/dist/extensions/enforcement/verification-judge.js +28 -21
  16. package/dist/extensions/memory/session-recall/ask.d.ts +95 -0
  17. package/dist/extensions/memory/session-recall/ask.js +376 -0
  18. package/dist/extensions/memory/session-recall/corpus-index.d.ts +200 -0
  19. package/dist/extensions/memory/session-recall/corpus-index.js +480 -0
  20. package/dist/extensions/memory/session-recall/index.js +173 -21
  21. package/dist/extensions/memory/session-recall/search.d.ts +29 -0
  22. package/dist/extensions/memory/session-recall/search.js +42 -9
  23. package/dist/lib/ai/payload-hygiene.d.ts +3 -0
  24. package/dist/lib/ai/payload-hygiene.js +34 -2
  25. package/dist/lib/config/braid-paths.d.ts +4 -0
  26. package/dist/lib/config/braid-paths.js +6 -0
  27. package/dist/lib/config/braid-settings.d.ts +44 -0
  28. package/dist/lib/config/braid-settings.js +41 -0
  29. package/dist/lib/detection/tool-loop-detector.d.ts +95 -46
  30. package/dist/lib/detection/tool-loop-detector.js +288 -180
  31. package/dist/lib/memory/constants.d.ts +38 -0
  32. package/dist/lib/memory/constants.js +196 -0
  33. package/dist/lib/memory/index.js +49 -10
  34. package/dist/lib/memory/lifecycle.d.ts +8 -0
  35. package/dist/lib/memory/lifecycle.js +43 -18
  36. package/dist/lib/reasoning/dreamer.d.ts +2 -1
  37. package/dist/lib/reasoning/dreamer.js +12 -7
  38. package/docs/LOCAL_DEV.md +1 -1
  39. package/docs/SETUP.md +2 -0
  40. package/package.json +1 -1
  41. package/src/extensions/core/AGENTS.md +3 -2
  42. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  43. package/src/extensions/core/skills-tool/auto-inject.ts +118 -1
  44. package/src/extensions/core/skills-tool/index.ts +21 -1
  45. package/src/extensions/core/skills-tool/loading-guidance.ts +4 -1
  46. package/src/extensions/core/skills-tool/session-records.ts +201 -9
  47. package/src/extensions/enforcement/handlers/analysis/dreamer-handler.ts +5 -1
  48. package/src/extensions/enforcement/handlers/register-tool-call.ts +5 -2
  49. package/src/extensions/enforcement/verification-judge.ts +32 -25
  50. package/src/extensions/memory/AGENTS.md +2 -2
  51. package/src/extensions/memory/session-recall/AGENTS.md +92 -18
  52. package/src/extensions/memory/session-recall/ask.ts +435 -0
  53. package/src/extensions/memory/session-recall/corpus-index.ts +609 -0
  54. package/src/extensions/memory/session-recall/index.ts +202 -21
  55. package/src/extensions/memory/session-recall/search.ts +61 -10
  56. package/src/lib/ai/payload-hygiene.ts +47 -3
  57. package/src/lib/config/braid-paths.ts +7 -0
  58. package/src/lib/config/braid-settings.ts +93 -3
  59. package/src/lib/detection/AGENTS.md +8 -7
  60. package/src/lib/detection/tool-loop-detector.ts +339 -195
  61. package/src/lib/memory/constants.ts +202 -0
  62. package/src/lib/memory/index.ts +59 -8
  63. package/src/lib/memory/lifecycle.ts +50 -16
  64. package/src/lib/reasoning/dreamer.ts +13 -6
@@ -1,6 +1,6 @@
1
1
  /**
2
- * Tool Loop Detector - single source of truth for "agent stuck calling
3
- * the same tool repeatedly."
2
+ * Tool Loop Detector - single source of truth for "agent stuck repeating
3
+ * the same call".
4
4
  *
5
5
  * One detector, one threshold, one window, one cooldown, one remedy.
6
6
  * Consumers (turn-outcome, dreamer, policy-rules) call detectToolLoop()
@@ -15,26 +15,44 @@
15
15
  * The two paths share a tryClaim-based dedup so only ONE whisper
16
16
  * per loop event reaches the agent.
17
17
  *
18
+ * IDENTITY, NOT NAME. A recorded call carries the tool name and an
19
+ * identity built from the arguments (toolCallIdentity). Sixteen `bash`
20
+ * calls running sixteen different commands are a chain of work: the agent
21
+ * is exploring, testing, committing, and nothing repeats. Sixteen runs of
22
+ * the same command are a repeat, and sixteen turns of that same command
23
+ * are a loop across turns. Name-only counting could not tell those apart,
24
+ * which is why the detector used to accuse a chain of work at the same
25
+ * threshold as a repeat. Measured over 672 stored accusations before the
26
+ * change: 667 had a tail of twenty distinct calls under one name, none was
27
+ * an identical repeat.
28
+ *
18
29
  * STATE LIFECYCLE:
19
30
  * - getToolLoopState(ctx) returns the per-session state via
20
31
  * getExtensionState. Resets on session_start, no manual reset
21
32
  * needed.
22
- * - recordToolCall() is called from the tool_call event handler
23
- * with the tool name.
33
+ * - recordToolCall(state, toolName, input) is called from the tool_call
34
+ * event handler with the call's arguments.
24
35
  * - recordTurnEnd() is called from turn_end to bump the counter
25
36
  * used for cooldown comparison.
26
37
  * - detectToolLoop() reads the state and returns the verdict.
27
38
  *
28
39
  * THRESHOLDS (one of each - change here, change everywhere):
29
- * - TOOL_LOOP_THRESHOLD: 16 consecutive same-tool calls
30
- * - TOOL_LOOP_WINDOW: 20 tools of history kept
40
+ * - TOOL_LOOP_THRESHOLD: 16 consecutive calls with one identity, or 16
41
+ * strictly alternating calls of two identities, or one identity across
42
+ * 16 consecutive turns
43
+ * - TOOL_LOOP_WINDOW: 20 calls of history kept
31
44
  * - TOOL_LOOP_COOLDOWN_TURNS: 8 turns between emissions
45
+ * - TOOL_TURN_WINDOW: 20 turns of per-turn history kept (the cross-turn
46
+ * shape needs 16 consecutive turns, so this bound is in turns)
32
47
  *
33
- * 16 catches real stuck loops without firing on heavy-but-productive
34
- * single-tool use (reading several files in succession); a lower
35
- * threshold false-positives on legitimate batch operations.
48
+ * 16 catches the same call returning sixteen times. It does not catch a chain
49
+ * of work that happens to use one tool, which is the whole point of the
50
+ * identity rule: reading several files, running a build, a commit, and a grep
51
+ * are different calls.
36
52
  *
37
- * Only THIS file emits the loop/addiction whisper. If any intentional
53
+ * Only this file decides a loop. The whisper that reaches the agent is the
54
+ * enforcement handler's, driven by this verdict; the analytics and dreamer
55
+ * paths keep their observations and deliver nothing. If any intentional
38
56
  * (metacognitive) tool - think, verify, verify_claim, finalize,
39
57
  * hypothesize, scratchpad, memory, memory_store, repl - appears anywhere
40
58
  * in the recorded window, the agent is engaged, not stuck, and
@@ -42,20 +60,38 @@
42
60
  * Per-episode single delivery is enforced here by markLoopFired() + the
43
61
  * 8-turn TOOL_LOOP_COOLDOWN_TURNS gate, and the whisper never wakes the
44
62
  * agent (triggerTurn:false, see enforcement/handlers/turn-end-handler.ts).
63
+ *
64
+ * The whisper states what was observed - the same call, with identical
65
+ * arguments, repeated - and never claims the absence of progress, which
66
+ * this module cannot see.
45
67
  */
46
68
 
47
69
  import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
48
70
  import { getExtensionState } from "../state/extension-state.js";
71
+ import { hashForDedup } from "../utils/dedup.js";
49
72
 
50
- /** Minimum consecutive same-tool calls in the recent history to flag. */
73
+ /** Minimum consecutive same-identity calls (or turns) in the recent history to flag. */
51
74
  export const TOOL_LOOP_THRESHOLD = 16;
52
75
 
53
- /** How many recent tools to retain in the rolling window. Must be >= TOOL_LOOP_THRESHOLD + 1. */
76
+ /** How many recent calls to retain in the rolling window. Must be >= TOOL_LOOP_THRESHOLD + 1. */
54
77
  export const TOOL_LOOP_WINDOW = 20;
55
78
 
56
79
  /** Minimum turns between successive loop whispers. */
57
80
  export const TOOL_LOOP_COOLDOWN_TURNS = 8;
58
81
 
82
+ /** How many turns of per-turn history to retain. A cross-turn loop needs
83
+ * TOOL_LOOP_THRESHOLD consecutive turns, so the bound is turn-shaped rather
84
+ * than call-shaped: bounding the total call count would evict the older turns
85
+ * of a busy agent and hide the very run the cross-turn shape looks for. Each
86
+ * turn's own call list is bounded by TOOL_LOOP_WINDOW. */
87
+ export const TOOL_TURN_WINDOW = TOOL_LOOP_THRESHOLD + 4;
88
+
89
+ /** Longest argument string kept verbatim in an identity. Longer values are
90
+ * replaced by a digest plus their length: a heredoc command runs to thousands
91
+ * of characters and would otherwise be retained twenty times over, while
92
+ * equality - the only thing the detector reads - survives the digest. */
93
+ const MAX_IDENTITY_VALUE_CHARS = 80;
94
+
59
95
  // Intentional-use filter: metacognitive tools that prove the agent is
60
96
  // engaged, not stuck. If any of these appears in the recorded window, the
61
97
  // agent is deliberately reflecting/verifying/closing-out, not mechanically
@@ -73,44 +109,50 @@ const INTENTIONAL_TOOLS = new Set([
73
109
  "repl",
74
110
  ]);
75
111
 
76
- /** True when the agent showed any intentional (metacognitive) tool in the
77
- * recorded history window. History is already capped at TOOL_LOOP_WINDOW. */
78
- function hasIntentionalToolInHistory(history: string[]): boolean {
79
- return history.some((t) => INTENTIONAL_TOOLS.has(t));
112
+ /** One recorded call: the tool, and the equality key for its arguments. */
113
+ export interface ToolCallRecord {
114
+ tool: string;
115
+ identity: string;
80
116
  }
81
117
 
82
- /** True when any per-turn tool set in the window contains an intentional tool. */
83
- function hasIntentionalToolInTurns(perTurn: Set<string>[]): boolean {
84
- for (const turn of perTurn) {
85
- for (const tool of turn) {
86
- if (INTENTIONAL_TOOLS.has(tool)) return true;
87
- }
88
- }
89
- return false;
118
+ /** A call to score, or a bare tool name. A bare name is what a caller has when
119
+ * it kept only names (the dreamer's historical log): it carries no argument
120
+ * evidence, so it cannot show that two calls are the same call. See
121
+ * detectToolLoopFromSequence for what that rules out. */
122
+ export type ToolCallLike = string | ToolCallRecord;
123
+
124
+ /** One turn's recorded calls, most recent turn first in ToolLoopState.perTurn. */
125
+ export interface ToolTurn {
126
+ /** Tool names seen in this turn - what the intentional-use filter reads. */
127
+ tools: Set<string>;
128
+ /** This turn's calls, oldest first, capped at TOOL_LOOP_WINDOW. */
129
+ calls: ToolCallRecord[];
90
130
  }
91
131
 
92
132
  export interface ToolLoopState {
93
- /** Tool sets per turn, most recent turn first. Each entry is the set of
94
- * tool names called in that turn. Using sets instead of a flat history
95
- * preserves turn boundaries, preventing false positives from same-tool
96
- * calls in different turns appearing adjacent after other tools age out. */
97
- perTurn: Set<string>[];
98
- /** Ordered flat history of tool calls (last TOOL_LOOP_WINDOW entries).
99
- * Used for tail-run detection: N consecutive same-tool calls whether
100
- * within a single turn or across turns. Pushed by recordToolCall,
101
- * shifted when exceeding WINDOW. */
102
- history: string[];
133
+ /** Calls per turn, most recent turn first. Turn boundaries are kept so a
134
+ * cross-turn loop (the same call every turn) can be scored separately from
135
+ * an intra-turn repeat, whose window spans the flat history below. */
136
+ perTurn: ToolTurn[];
137
+ /** Ordered flat history of the last TOOL_LOOP_WINDOW calls. Used for
138
+ * identity-run detection: consecutive calls that are the same call,
139
+ * whether within one turn or across turns. */
140
+ history: ToolCallRecord[];
103
141
  /** Turn index when we last emitted a loop whisper. -1 if never. */
104
142
  lastFiredAtTurn: number;
105
143
  /** Monotonically increasing turn counter for cooldown math. */
106
144
  turnCount: number;
107
145
  }
108
146
 
147
+ /** Which shape of repetition produced the verdict. */
148
+ export type ToolLoopPattern = "repeat" | "alternation" | "cross-turn" | "";
149
+
109
150
  export interface ToolLoopResult {
110
151
  isLoop: boolean;
111
152
  tool: string;
112
153
  count: number;
113
154
  message: string;
155
+ pattern: ToolLoopPattern;
114
156
  }
115
157
 
116
158
  export function createToolLoopState(): ToolLoopState {
@@ -127,27 +169,74 @@ export function getToolLoopState(ctx: ExtensionContext): ToolLoopState {
127
169
  }
128
170
 
129
171
  /**
130
- * Record a tool invocation. Call this from the tool_call event handler
131
- * with the tool name. Adds the tool to the current (most recent) turn's
132
- * tool set. If no turn has started yet, creates one.
172
+ * Normalize an argument value for equality: whitespace collapsed, object keys
173
+ * sorted (argument order is not identity), long strings digested.
133
174
  */
134
- export function recordToolCall(state: ToolLoopState, toolName: string): void {
135
- if (!toolName) return;
136
- if (state.perTurn.length === 0) {
137
- state.perTurn.push(new Set<string>());
175
+ function normalizeArgValue(value: unknown): unknown {
176
+ if (typeof value === "string") {
177
+ const collapsed = value.replace(/\s+/g, " ").trim();
178
+ return collapsed.length > MAX_IDENTITY_VALUE_CHARS
179
+ ? `#${hashForDedup(collapsed)}:${collapsed.length}`
180
+ : collapsed;
138
181
  }
139
- state.perTurn[0].add(toolName);
140
- // Trim perTurn to keep tool counts within WINDOW
141
- let totalTools = 0;
142
- for (const turn of state.perTurn) {
143
- totalTools += turn.size;
144
- }
145
- while (totalTools > TOOL_LOOP_WINDOW && state.perTurn.length > 1) {
146
- const removed = state.perTurn.pop()!;
147
- totalTools -= removed.size;
182
+ if (Array.isArray(value)) return value.map(normalizeArgValue);
183
+ if (value && typeof value === "object") {
184
+ const out: Record<string, unknown> = {};
185
+ const source = value as Record<string, unknown>;
186
+ for (const key of Object.keys(source).sort()) {
187
+ const normalized = normalizeArgValue(source[key]);
188
+ if (normalized !== undefined) out[key] = normalized;
189
+ }
190
+ return out;
148
191
  }
149
- // Push to ordered history for tail-run detection
150
- state.history.push(toolName);
192
+ return value;
193
+ }
194
+
195
+ /**
196
+ * Build the equality key for one tool call: the tool name plus its normalized
197
+ * arguments. Two calls share an identity exactly when they are the same call -
198
+ * same tool, same arguments - which is what "the agent repeated itself" means.
199
+ *
200
+ * A call whose arguments are absent or empty is identified by its name alone;
201
+ * there is no argument evidence to distinguish it from another call of the
202
+ * same tool, so they count as the same call.
203
+ */
204
+ export function toolCallIdentity(toolName: string, input?: unknown): string {
205
+ if (!toolName) return "";
206
+ if (input === undefined || input === null) return toolName;
207
+ const normalized = normalizeArgValue(input);
208
+ const serialized = JSON.stringify(normalized);
209
+ if (!serialized || serialized === "{}" || serialized === "null") return toolName;
210
+ return `${toolName} ${serialized}`;
211
+ }
212
+
213
+ function openTurn(): ToolTurn {
214
+ return { tools: new Set<string>(), calls: [] };
215
+ }
216
+
217
+ /** Drop whole turns from the oldest end past the per-turn window. */
218
+ function trimPerTurn(state: ToolLoopState): void {
219
+ while (state.perTurn.length > TOOL_TURN_WINDOW) state.perTurn.pop();
220
+ }
221
+
222
+ /**
223
+ * Record a tool invocation. Call this from the tool_call event handler with
224
+ * the tool name and its arguments. Adds the call to the current (most recent)
225
+ * turn. If no turn has started yet, creates one.
226
+ */
227
+ export function recordToolCall(state: ToolLoopState, toolName: string, input?: unknown): void {
228
+ if (!toolName) return;
229
+ if (state.perTurn.length === 0) state.perTurn.push(openTurn());
230
+ const turn = state.perTurn[0];
231
+ turn.tools.add(toolName);
232
+
233
+ const record: ToolCallRecord = { tool: toolName, identity: toolCallIdentity(toolName, input) };
234
+ turn.calls.push(record);
235
+ if (turn.calls.length > TOOL_LOOP_WINDOW) turn.calls.shift();
236
+
237
+ trimPerTurn(state);
238
+
239
+ state.history.push(record);
151
240
  if (state.history.length > TOOL_LOOP_WINDOW) {
152
241
  state.history.shift();
153
242
  }
@@ -156,21 +245,11 @@ export function recordToolCall(state: ToolLoopState, toolName: string): void {
156
245
  /**
157
246
  * Record the end of a turn. Call this from the turn_end handler to
158
247
  * bump the counter and open a new turn for the next round of tool calls.
159
- * Pushes a fresh perTurn entry so the next recordToolCall adds to the new
160
- * turn's set. History rotation happens in recordToolCall; perTurn entries
161
- * are trimmed to TOOL_LOOP_WINDOW here.
162
248
  */
163
249
  export function recordTurnEnd(state: ToolLoopState): void {
164
250
  state.turnCount++;
165
- state.perTurn.unshift(new Set<string>());
166
- let totalTools = 0;
167
- for (const turn of state.perTurn) {
168
- totalTools += turn.size;
169
- }
170
- while (totalTools > TOOL_LOOP_WINDOW && state.perTurn.length > 1) {
171
- const removed = state.perTurn.pop()!;
172
- totalTools -= removed.size;
173
- }
251
+ state.perTurn.unshift(openTurn());
252
+ trimPerTurn(state);
174
253
  }
175
254
 
176
255
  /**
@@ -182,183 +261,248 @@ export function markLoopFired(state: ToolLoopState): void {
182
261
  state.lastFiredAtTurn = state.turnCount;
183
262
  }
184
263
 
264
+ /** True when the agent showed any intentional (metacognitive) tool in the
265
+ * recorded history window. History is already capped at TOOL_LOOP_WINDOW. */
266
+ function hasIntentionalToolInHistory(history: ToolCallRecord[]): boolean {
267
+ return history.some((call) => INTENTIONAL_TOOLS.has(call.tool));
268
+ }
269
+
270
+ /** True when any per-turn tool set in the window contains an intentional tool. */
271
+ function hasIntentionalToolInTurns(perTurn: ToolTurn[]): boolean {
272
+ for (const turn of perTurn) {
273
+ for (const tool of turn.tools) {
274
+ if (INTENTIONAL_TOOLS.has(tool)) return true;
275
+ }
276
+ }
277
+ return false;
278
+ }
279
+
280
+ /** Length of the run of one identity at the end of the history. */
281
+ function identityTailRun(
282
+ history: ToolCallRecord[],
283
+ ): { count: number; call: ToolCallRecord } | null {
284
+ if (history.length === 0) return null;
285
+ const last = history[history.length - 1];
286
+ let count = 1;
287
+ for (let i = history.length - 2; i >= 0; i--) {
288
+ if (history[i].identity === last.identity) count++;
289
+ else break;
290
+ }
291
+ return { count, call: last };
292
+ }
293
+
294
+ /** Length of a strict two-identity oscillation at the end of the history
295
+ * (A,B,A,B,... - never A,A). Returns null when the last two calls are the
296
+ * same call, which is the repeat path's case, not this one. */
297
+ function alternationTailRun(
298
+ history: ToolCallRecord[],
299
+ ): { count: number; a: ToolCallRecord; b: ToolCallRecord } | null {
300
+ if (history.length < 2) return null;
301
+ const a = history[history.length - 1];
302
+ const b = history[history.length - 2];
303
+ if (a.identity === b.identity) return null;
304
+ let count = 2;
305
+ for (let i = history.length - 3; i >= 0; i--) {
306
+ const expected = count % 2 === 0 ? a : b;
307
+ if (history[i].identity === expected.identity) count++;
308
+ else break;
309
+ }
310
+ return { count, a, b };
311
+ }
312
+
313
+ const SUGGESTED_ACTIONS =
314
+ `\n\n**Suggested actions:**\n` +
315
+ `1. Use \`think()\` tool to re-evaluate your approach\n` +
316
+ `2. Check if the problem has changed - you may be solving the wrong issue\n` +
317
+ `3. Consider breaking the task into smaller steps\n` +
318
+ `4. Use the \`memory()\` tool to find past solutions to similar problems`;
319
+
320
+ function repeatMessage(call: ToolCallRecord, count: number, acrossTurns: boolean): string {
321
+ const observed = acrossTurns
322
+ ? `the same \`${call.tool}\` call, with identical arguments, ran in ${count} consecutive turns.`
323
+ : `the same \`${call.tool}\` call, with identical arguments, repeated ${count} times in a row.`;
324
+ return `Tool loop detected: ${observed}${SUGGESTED_ACTIONS}`;
325
+ }
326
+
327
+ function alternationMessage(a: ToolCallRecord, b: ToolCallRecord, count: number): string {
328
+ const pair =
329
+ a.tool === b.tool
330
+ ? `\`${a.tool}\` with two different arguments`
331
+ : `\`${a.tool}\`, \`${b.tool}\``;
332
+ return (
333
+ `Tool loop detected: two calls alternated ${count} times in a row ` +
334
+ `(${pair}), each call identical to its counterpart.` +
335
+ SUGGESTED_ACTIONS
336
+ );
337
+ }
338
+
339
+ const NOT_A_LOOP: ToolLoopResult = { isLoop: false, tool: "", count: 0, message: "", pattern: "" };
340
+
185
341
  /**
186
- * Detect a tool loop. Uses TWO detection paths:
187
- *
188
- * 1. Tail-run (intra-turn): checks the ordered `history` array for N
189
- * consecutive same-tool calls. Catches the common `read*8` loop even
190
- * when all calls happen in a single turn. This is the primary path;
191
- * the test suite and the stateless detectToolLoopFromSequence share
192
- * the same tail-run semantics.
193
- *
194
- * 2. Cross-turn (inter-turn): checks perTurn sets for the same tool
195
- * appearing in N consecutive turns. Catches loops where the agent
196
- * calls different tools but always returns to the same one.
342
+ * Detect a loop at the tail of a call sequence. Three shapes:
197
343
  *
198
- * Returns:
199
- * { isLoop: true, tool, count, message } when a loop is detected.
200
- * { isLoop: false, tool: "", count: 0, message: "" } otherwise.
344
+ * 1. Repeat: one identity at the end of the history, TOOL_LOOP_THRESHOLD or
345
+ * more calls long. The common `read the same file 16 times` loop.
346
+ * 2. Alternation: two identities oscillating strictly (A,B,A,B,...) for
347
+ * TOOL_LOOP_THRESHOLD or more calls. Each call is distinct from the one
348
+ * before it, so only the whole-window shape names this as a loop.
349
+ * 3. Cross-turn: one identity present in TOOL_LOOP_THRESHOLD consecutive
350
+ * turns. Catches an agent that does other work in between but returns to
351
+ * the same call every turn.
201
352
  *
202
- * The message is the unified whisper body. Consumers can either emit
203
- * it verbatim, customize it, or just observe the verdict.
353
+ * A tail of one tool name whose calls are all distinct is a chain of work and
354
+ * matches none of the three.
204
355
  */
205
356
  export function detectToolLoop(state: ToolLoopState): ToolLoopResult {
206
- // Cooldown gate. Only applies once we've fired at least once
357
+ // Cooldown gate. Only applies once we've fired at least once.
207
358
  if (
208
359
  state.lastFiredAtTurn >= 0 &&
209
360
  state.turnCount - state.lastFiredAtTurn < TOOL_LOOP_COOLDOWN_TURNS
210
361
  ) {
211
- return { isLoop: false, tool: "", count: 0, message: "" };
362
+ return NOT_A_LOOP;
212
363
  }
213
364
 
214
365
  // If the agent used any intentional (metacognitive) tool anywhere in the
215
- // recorded window, it is deliberately engaged, not stuck in a loop.
216
- // Applies to BOTH detection paths (tail-run on `history` and cross-turn
217
- // on `perTurn`); a think/verify/finalize inside the window kills the loop
218
- // verdict even when the tail still runs 16+ same-tool calls (the
219
- // false-positive class the 16 threshold guards against).
366
+ // recorded window, it is deliberately engaged, not stuck in a loop. Applies
367
+ // to all three shapes; a think/verify/finalize inside the window kills the
368
+ // loop verdict even when the tail still repeats.
220
369
  if (hasIntentionalToolInHistory(state.history) || hasIntentionalToolInTurns(state.perTurn)) {
221
- return { isLoop: false, tool: "", count: 0, message: "" };
370
+ return NOT_A_LOOP;
222
371
  }
223
372
 
224
- // Path 1: tail-run detection (ordered history) - count consecutive
225
- // same-tool calls at the end of the history array. This matches the
226
- // stateless detectToolLoopFromSequence semantics.
227
373
  if (state.history.length >= TOOL_LOOP_THRESHOLD) {
228
- const last = state.history[state.history.length - 1];
229
- let count = 1;
230
- for (let i = state.history.length - 2; i >= 0; i--) {
231
- if (state.history[i] === last) count++;
232
- else break;
233
- }
234
- if (count >= TOOL_LOOP_THRESHOLD) {
374
+ const repeat = identityTailRun(state.history);
375
+ if (repeat && repeat.count >= TOOL_LOOP_THRESHOLD) {
235
376
  return {
236
377
  isLoop: true,
237
- tool: last,
238
- count,
239
- message:
240
- `Tool loop detected: \`${last}\` called ${count} times in a row with no progress.` +
241
- `\n\n**Suggested actions:**\n` +
242
- `1. Use \`think()\` tool to re-evaluate your approach\n` +
243
- `2. Check if the problem has changed - you may be solving the wrong issue\n` +
244
- `3. Consider breaking the task into smaller steps\n` +
245
- `4. Use the \`memory()\` tool to find past solutions to similar problems`,
378
+ tool: repeat.call.tool,
379
+ count: repeat.count,
380
+ message: repeatMessage(repeat.call, repeat.count, false),
381
+ pattern: "repeat",
246
382
  };
247
383
  }
248
- }
249
-
250
- // Only relevant when the agent spans multiple turns with the same tool.
251
- if (state.perTurn.length < 2) {
252
- return { isLoop: false, tool: "", count: 0, message: "" };
253
- }
254
384
 
255
- const toolTurnCounts = new Map<string, { turnCount: number; exclusiveTurns: number }>();
256
- for (const turn of state.perTurn) {
257
- for (const tool of turn) {
258
- if (!toolTurnCounts.has(tool)) {
259
- toolTurnCounts.set(tool, { turnCount: 0, exclusiveTurns: 0 });
260
- }
261
- const entry = toolTurnCounts.get(tool)!;
262
- entry.turnCount++;
263
- if (turn.size === 1) {
264
- entry.exclusiveTurns++;
265
- }
385
+ const alternation = alternationTailRun(state.history);
386
+ if (alternation && alternation.count >= TOOL_LOOP_THRESHOLD) {
387
+ return {
388
+ isLoop: true,
389
+ tool: alternation.a.tool,
390
+ count: alternation.count,
391
+ message: alternationMessage(alternation.a, alternation.b, alternation.count),
392
+ pattern: "alternation",
393
+ };
266
394
  }
267
395
  }
268
396
 
269
- let bestTool = "";
270
- let bestCount = 0;
271
- let bestExclusive = 0;
272
- for (const [tool, counts] of toolTurnCounts) {
273
- if (counts.turnCount > bestCount) {
274
- bestTool = tool;
275
- bestCount = counts.turnCount;
276
- bestExclusive = counts.exclusiveTurns;
397
+ // Cross-turn: only relevant when the agent spans multiple turns. Empty
398
+ // turns are transparent: recordTurnEnd() opens the next turn, so the newest
399
+ // entry is empty at detection time by construction, and a turn that made no
400
+ // tool calls carries no evidence either way. A populated turn without the
401
+ // call ends the run.
402
+ const populated = state.perTurn.filter((turn) => turn.calls.length > 0);
403
+ if (populated.length >= 2) {
404
+ let best: { call: ToolCallRecord; turns: number } | null = null;
405
+ const seen = new Set<string>();
406
+ for (const call of populated[0].calls) {
407
+ if (seen.has(call.identity)) continue;
408
+ seen.add(call.identity);
409
+ let turns = 0;
410
+ for (const turn of populated) {
411
+ if (turn.calls.some((c) => c.identity === call.identity)) turns++;
412
+ else break;
413
+ }
414
+ if (!best || turns > best.turns) best = { call, turns };
277
415
  }
278
- }
279
-
280
- if (bestCount < TOOL_LOOP_THRESHOLD) {
281
- return { isLoop: false, tool: "", count: 0, message: "" };
282
- }
283
-
284
- let consecutiveTurns = 0;
285
- for (const turn of state.perTurn) {
286
- if (turn.has(bestTool)) {
287
- consecutiveTurns++;
288
- } else {
289
- break;
416
+ if (best && best.turns >= TOOL_LOOP_THRESHOLD) {
417
+ return {
418
+ isLoop: true,
419
+ tool: best.call.tool,
420
+ count: best.turns,
421
+ message: repeatMessage(best.call, best.turns, true),
422
+ pattern: "cross-turn",
423
+ };
290
424
  }
291
425
  }
292
426
 
293
- if (consecutiveTurns < TOOL_LOOP_THRESHOLD) {
294
- return { isLoop: false, tool: "", count: 0, message: "" };
295
- }
296
-
297
- return {
298
- isLoop: true,
299
- tool: bestTool,
300
- count: consecutiveTurns,
301
- message:
302
- `Tool loop detected: \`${bestTool}\` called in ${consecutiveTurns} consecutive turns.` +
303
- (bestExclusive >= 2
304
- ? ` In ${bestExclusive} of those turns, it was the only tool called.`
305
- : ``) +
306
- `\n\n**Suggested actions:**\n` +
307
- `1. Use \`think()\` tool to re-evaluate your approach\n` +
308
- `2. Check if the problem has changed - you may be solving the wrong issue\n` +
309
- `3. Consider breaking the task into smaller steps\n` +
310
- `4. Use the \`memory()\` tool to find past solutions to similar problems`,
311
- };
427
+ return NOT_A_LOOP;
312
428
  }
313
429
 
314
430
  //
315
- // The stateful detectToolLoop() above is for callers (the tool_call
316
- // event handler) that record calls incrementally. This helper is for
317
- // callers (the dreamer) that have a complete sequence at hand and
318
- // don't need cross-turn state. Same threshold, same window, same
319
- // message -- just no cooldown or history trim.
431
+ // The stateful detectToolLoop() above is for callers that record calls
432
+ // incrementally (the tool_call event handler and the failure-trace collector).
433
+ // This helper is for callers that hold a complete sequence at hand (the
434
+ // dreamer) and need no cooldown or cross-turn state. Same threshold, same
435
+ // window, same messages.
436
+ //
437
+ // It accepts recorded calls, and it accepts bare tool names for callers that
438
+ // kept only names - and a name is not a call. Sixteen identical names are
439
+ // indistinguishable from sixteen different commands under that name, which is
440
+ // exactly the false accusation this module was rewritten to stop making. A
441
+ // sequence that carries no identities therefore returns NOT a loop: the
442
+ // stateless path can only accuse when it can show the same call repeating, and
443
+ // a caller that wants that verdict must pass what recordToolCall recorded
444
+ // (ToolLoopState.history) rather than a name log.
320
445
 
321
446
  export interface StatelessLoopResult {
322
447
  isLoop: boolean;
323
448
  tool: string;
324
449
  count: number;
325
450
  message: string;
451
+ pattern: ToolLoopPattern;
452
+ }
453
+
454
+ /** Narrow a ToolCallLike to a record, or null when it is a bare name. */
455
+ function asRecord(entry: ToolCallLike): ToolCallRecord | null {
456
+ if (typeof entry === "string") return null;
457
+ if (!entry || typeof entry.tool !== "string" || typeof entry.identity !== "string") return null;
458
+ return entry;
326
459
  }
327
460
 
328
- export function detectToolLoopFromSequence(sequence: string[]): StatelessLoopResult {
461
+ export function detectToolLoopFromSequence(sequence: ToolCallLike[]): StatelessLoopResult {
329
462
  if (sequence.length < TOOL_LOOP_THRESHOLD) {
330
- return { isLoop: false, tool: "", count: 0, message: "" };
463
+ return { isLoop: false, tool: "", count: 0, message: "", pattern: "" };
331
464
  }
332
- // Cap to WINDOW so the check is consistent with the stateful path
465
+ // Cap to WINDOW so the check is consistent with the stateful path.
333
466
  const windowed =
334
467
  sequence.length > TOOL_LOOP_WINDOW ? sequence.slice(-TOOL_LOOP_WINDOW) : sequence;
335
468
 
336
- // Intentional-use filter: any metacognitive tool in the windowed
337
- // slice means the agent is engaged, not stuck — not a loop. Mirrors the
338
- // stateful detectToolLoop() so the dreamer's stateless path agrees with it.
339
- if (hasIntentionalToolInHistory(windowed)) {
340
- return { isLoop: false, tool: "", count: 0, message: "" };
469
+ const records: ToolCallRecord[] = [];
470
+ for (const entry of windowed) {
471
+ const record = asRecord(entry);
472
+ if (!record) {
473
+ // A bare name is not a call: no argument evidence, no identity.
474
+ return { isLoop: false, tool: "", count: 0, message: "", pattern: "" };
475
+ }
476
+ records.push(record);
341
477
  }
342
478
 
343
- const last = windowed[windowed.length - 1];
344
- let count = 1;
345
- for (let i = windowed.length - 2; i >= 0; i--) {
346
- if (windowed[i] === last) count++;
347
- else break;
479
+ // Intentional-use filter: any metacognitive tool in the windowed slice means
480
+ // the agent is engaged, not stuck. Mirrors the stateful path.
481
+ if (hasIntentionalToolInHistory(records)) {
482
+ return { isLoop: false, tool: "", count: 0, message: "", pattern: "" };
348
483
  }
349
- if (count < TOOL_LOOP_THRESHOLD) {
350
- return { isLoop: false, tool: "", count: 0, message: "" };
484
+
485
+ const repeat = identityTailRun(records);
486
+ if (repeat && repeat.count >= TOOL_LOOP_THRESHOLD) {
487
+ return {
488
+ isLoop: true,
489
+ tool: repeat.call.tool,
490
+ count: repeat.count,
491
+ message: repeatMessage(repeat.call, repeat.count, false),
492
+ pattern: "repeat",
493
+ };
351
494
  }
352
- return {
353
- isLoop: true,
354
- tool: last,
355
- count,
356
- message:
357
- `Tool loop detected: \`${last}\` called ${count} times in a row with no progress.\n\n` +
358
- `**Suggested actions:**\n` +
359
- `1. Use \`think()\` tool to re-evaluate your approach\n` +
360
- `2. Check if the problem has changed - you may be solving the wrong issue\n` +
361
- `3. Consider breaking the task into smaller steps\n` +
362
- `4. Use the \`memory()\` tool to find past solutions to similar problems`,
363
- };
495
+
496
+ const alternation = alternationTailRun(records);
497
+ if (alternation && alternation.count >= TOOL_LOOP_THRESHOLD) {
498
+ return {
499
+ isLoop: true,
500
+ tool: alternation.a.tool,
501
+ count: alternation.count,
502
+ message: alternationMessage(alternation.a, alternation.b, alternation.count),
503
+ pattern: "alternation",
504
+ };
505
+ }
506
+
507
+ return { isLoop: false, tool: "", count: 0, message: "", pattern: "" };
364
508
  }