@goodandready/dsh-agent-loop-guard 0.3.0 → 0.3.2

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.
@@ -290,6 +290,48 @@ export function normalizeErrorSignature(error) {
290
290
  .slice(0, 50);
291
291
  return sanitized.length > 0 ? sanitized : 'GENERIC_ERROR';
292
292
  }
293
+
294
+ export {
295
+ classifyToolAction,
296
+ extractTargetKey,
297
+ checkTargetQuota,
298
+ recordTargetOutcome,
299
+ handleTargetViolation,
300
+ } from './target-quota-guard.js';
301
+
302
+ export function decrementReservations(state, call) {
303
+ if (!call || !call.counted || call.committed) return;
304
+ state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
305
+ if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
306
+ if (call.repeatFingerprint) {
307
+ const group = state.repeatGroups.get(call.repeatFingerprint);
308
+ if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
309
+ group.count = Math.max(0, group.count - 1);
310
+ }
311
+ }
312
+ if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
313
+ const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
314
+ if (lastIdx !== -1) {
315
+ state.recentCallSequence.splice(lastIdx, 1);
316
+ }
317
+ }
318
+ if (call.fingerprint) {
319
+ const exact = state.exactGroups.get(call.fingerprint);
320
+ if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
321
+ exact.count = Math.max(0, exact.count - 1);
322
+ }
323
+ }
324
+ if (call.target && state.targetCallCounts) {
325
+ const counts = state.targetCallCounts.get(call.target);
326
+ if (counts) {
327
+ if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
328
+ if (counts.total > 0) counts.total -= 1;
329
+ }
330
+ }
331
+ }
332
+
333
+
334
+
293
335
  export const GUARD_PRESETS = {
294
336
  strict: {
295
337
  name: 'strict',
@@ -306,6 +348,11 @@ export const GUARD_PRESETS = {
306
348
  maxToolResultChars: 32_768,
307
349
  pseudoToolCallThreshold: 2,
308
350
  adaptiveSteering: true,
351
+ targetQuotaGuard: true,
352
+ maxUnchangedReadsPerTarget: 2,
353
+ maxReadsPerTarget: 4,
354
+ maxEditsPerTarget: 5,
355
+ maxTargetAttempts: 8,
309
356
  },
310
357
  balanced: {
311
358
  name: 'balanced',
@@ -322,6 +369,11 @@ export const GUARD_PRESETS = {
322
369
  maxToolResultChars: 65_536,
323
370
  pseudoToolCallThreshold: 3,
324
371
  adaptiveSteering: true,
372
+ targetQuotaGuard: true,
373
+ maxUnchangedReadsPerTarget: 3,
374
+ maxReadsPerTarget: 6,
375
+ maxEditsPerTarget: 8,
376
+ maxTargetAttempts: 12,
325
377
  },
326
378
  autonomous: {
327
379
  name: 'autonomous',
@@ -338,6 +390,11 @@ export const GUARD_PRESETS = {
338
390
  maxToolResultChars: 131_072,
339
391
  pseudoToolCallThreshold: 4,
340
392
  adaptiveSteering: true,
393
+ targetQuotaGuard: true,
394
+ maxUnchangedReadsPerTarget: 5,
395
+ maxReadsPerTarget: 10,
396
+ maxEditsPerTarget: 12,
397
+ maxTargetAttempts: 20,
341
398
  },
342
399
  };
343
400
 
@@ -351,6 +408,12 @@ export function formatSteeringAdvice(code, detail, name) {
351
408
  if (code === 'LOOP_GUARD_ERROR_THRASHING') {
352
409
  return `Repeated tool calls resulted in identical failures (${detail}). Stop repeating the failing action and diagnose the root cause or explain the roadblock.`;
353
410
  }
411
+ if (code === 'LOOP_GUARD_UNREFRESHED_READ') {
412
+ return `Target has been repeatedly read without changes (${detail}). The file content is already in your context. Proceed to edit, run checks, or provide an answer.`;
413
+ }
414
+ if (code === 'LOOP_GUARD_TARGET_QUOTA') {
415
+ return `Operations on this target reached quota limit (${detail}). Shift focus to other files or summarize findings.`;
416
+ }
354
417
  return `Potential loop condition detected (${detail}). Adjust your action or explain your plan.`;
355
418
  }
356
419
 
@@ -372,6 +435,10 @@ export function formatViolationGuidance(code, detail, name, config) {
372
435
  guidance += 'Consecutive turns completed with pseudo tool-call syntax but zero real tool executions. Cease outputting raw <invoke> tags and provide a direct answer, or verify tool syntax.';
373
436
  } else if (code === 'LOOP_GUARD_ERROR_THRASHING') {
374
437
  guidance += 'Repeated tool executions resulted in identical errors without state progression. Stop re-trying the failing operation. Investigate the failure reason, check file existence/permissions, or report the roadblock to the user.';
438
+ } else if (code === 'LOOP_GUARD_UNREFRESHED_READ') {
439
+ guidance += 'Target was read repeatedly without content changes. File contents are already in context. Do NOT re-read unchanged files; execute next steps or answer directly.';
440
+ } else if (code === 'LOOP_GUARD_TARGET_QUOTA') {
441
+ guidance += 'Target quota limit reached. Cease repeated operations on this specific target and work on other tasks or answer directly.';
375
442
  } else {
376
443
  guidance += 'Cease tool execution and provide a final text response. The next user turn will reset this guard.';
377
444
  }
@@ -17,27 +17,33 @@ import {
17
17
  GUARD_PRESETS,
18
18
  formatSteeringAdvice,
19
19
  formatViolationGuidance,
20
+ decrementReservations,
20
21
  } from './guard-helpers.js';
21
22
 
23
+ import {
24
+ classifyToolAction,
25
+ extractTargetKey,
26
+ checkTargetQuota,
27
+ recordTargetOutcome,
28
+ handleTargetViolation,
29
+ maskSessionId,
30
+ redactTelemetryText,
31
+ } from './target-quota-guard.js';
32
+
22
33
  export * from './guard-helpers.js';
34
+ export * from './target-quota-guard.js';
35
+
36
+
37
+
38
+ function cleanStringList(list, fallback = []) {
39
+ return Array.isArray(list) ? list.filter((n) => typeof n === 'string' && n.trim() !== '').map((n) => n.trim()) : fallback;
40
+ }
23
41
 
24
42
  export class LoopGuardState {
25
43
  constructor(config = {}) {
26
- const progressToolNames = Array.isArray(config.progressToolNames)
27
- ? config.progressToolNames
28
- .filter((name) => typeof name === 'string' && name.trim() !== '')
29
- .map((name) => name.trim())
30
- : ['todo_write'];
31
- const strictTools = Array.isArray(config.strictTools)
32
- ? config.strictTools
33
- .filter((name) => typeof name === 'string' && name.trim() !== '')
34
- .map((name) => name.trim())
35
- : [];
36
- const stopPatterns = Array.isArray(config.stopPatterns)
37
- ? config.stopPatterns
38
- .filter((name) => typeof name === 'string' && name.trim() !== '')
39
- .map((name) => name.trim())
40
- : [];
44
+ const progressToolNames = cleanStringList(config.progressToolNames, ['todo_write']);
45
+ const strictTools = cleanStringList(config.strictTools, []);
46
+ const stopPatterns = cleanStringList(config.stopPatterns, []);
41
47
  this.config = {
42
48
  ...config,
43
49
  maxToolAttemptsPerTurn: nonNegativeInteger(config.maxToolAttemptsPerTurn, 64),
@@ -54,6 +60,11 @@ export class LoopGuardState {
54
60
  errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : true,
55
61
  maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, 4),
56
62
  adaptiveSteering: Boolean(config.adaptiveSteering),
63
+ targetQuotaGuard: config.targetQuotaGuard !== undefined ? Boolean(config.targetQuotaGuard) : true,
64
+ maxUnchangedReadsPerTarget: config.maxUnchangedReadsPerTarget !== undefined ? positiveInteger(config.maxUnchangedReadsPerTarget, 3) : Math.max(3, positiveInteger(config.maxCallsPerRepeatGroup, 5)),
65
+ maxReadsPerTarget: positiveInteger(config.maxReadsPerTarget, 6),
66
+ maxEditsPerTarget: positiveInteger(config.maxEditsPerTarget, 8),
67
+ maxTargetAttempts: positiveInteger(config.maxTargetAttempts, 12),
57
68
  };
58
69
  this.stopPatterns = stopPatterns;
59
70
  this.pseudoPatterns = this.config.pseudoToolCallPatterns;
@@ -70,33 +81,20 @@ export class LoopGuardState {
70
81
  totalViolations: 0,
71
82
  steeredCount: 0,
72
83
  byCode: {
73
- LOOP_GUARD_STOP: 0,
74
- LOOP_GUARD_DUPLICATE: 0,
75
- LOOP_GUARD_REPEAT: 0,
76
- LOOP_GUARD_LIMIT: 0,
77
- LOOP_GUARD_PROGRESS_LIMIT: 0,
78
- LOOP_GUARD_OUTPUT: 0,
79
- LOOP_GUARD_PSEUDO_TOOL_CALL: 0,
80
- LOOP_GUARD_OSCILLATION: 0,
81
- LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
82
- LOOP_GUARD_ERROR_THRASHING: 0,
83
- LOOP_GUARD_STEER: 0,
84
+ LOOP_GUARD_STOP: 0, LOOP_GUARD_DUPLICATE: 0, LOOP_GUARD_REPEAT: 0,
85
+ LOOP_GUARD_LIMIT: 0, LOOP_GUARD_PROGRESS_LIMIT: 0, LOOP_GUARD_OUTPUT: 0,
86
+ LOOP_GUARD_PSEUDO_TOOL_CALL: 0, LOOP_GUARD_OSCILLATION: 0, LOOP_GUARD_PAYLOAD_TRUNCATED: 0,
87
+ LOOP_GUARD_ERROR_THRASHING: 0, LOOP_GUARD_STEER: 0, LOOP_GUARD_TARGET_QUOTA: 0,
88
+ LOOP_GUARD_UNREFRESHED_READ: 0,
84
89
  },
90
+ targetDenials: 0,
85
91
  lastViolation: null,
86
92
  };
87
93
  }
88
94
 
89
95
  updateConfig(config = {}) {
90
- const progressToolNames = Array.isArray(config.progressToolNames)
91
- ? config.progressToolNames
92
- .filter((name) => typeof name === 'string' && name.trim() !== '')
93
- .map((name) => name.trim())
94
- : Array.from(this.progressToolNames);
95
- const strictTools = Array.isArray(config.strictTools)
96
- ? config.strictTools
97
- .filter((name) => typeof name === 'string' && name.trim() !== '')
98
- .map((name) => name.trim())
99
- : Array.from(this.strictTools);
96
+ const progressToolNames = cleanStringList(config.progressToolNames, Array.from(this.progressToolNames));
97
+ const strictTools = cleanStringList(config.strictTools, Array.from(this.strictTools));
100
98
  this.config = {
101
99
  ...this.config,
102
100
  ...config,
@@ -109,11 +107,14 @@ export class LoopGuardState {
109
107
  errorThrashingGuard: config.errorThrashingGuard !== undefined ? Boolean(config.errorThrashingGuard) : this.config.errorThrashingGuard,
110
108
  maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, this.config.maxConsecutiveFailures ?? 4),
111
109
  adaptiveSteering: config.adaptiveSteering !== undefined ? Boolean(config.adaptiveSteering) : this.config.adaptiveSteering,
110
+ targetQuotaGuard: config.targetQuotaGuard !== undefined ? Boolean(config.targetQuotaGuard) : this.config.targetQuotaGuard,
111
+ maxUnchangedReadsPerTarget: config.maxUnchangedReadsPerTarget !== undefined ? positiveInteger(config.maxUnchangedReadsPerTarget, 3) : (this.config.maxUnchangedReadsPerTarget ?? 3),
112
+ maxReadsPerTarget: positiveInteger(config.maxReadsPerTarget, this.config.maxReadsPerTarget ?? 6),
113
+ maxEditsPerTarget: positiveInteger(config.maxEditsPerTarget, this.config.maxEditsPerTarget ?? 8),
114
+ maxTargetAttempts: positiveInteger(config.maxTargetAttempts, this.config.maxTargetAttempts ?? 12),
112
115
  };
113
116
  if (Array.isArray(config.stopPatterns)) {
114
- this.stopPatterns = config.stopPatterns
115
- .filter((name) => typeof name === 'string' && name.trim() !== '')
116
- .map((name) => name.trim());
117
+ this.stopPatterns = cleanStringList(config.stopPatterns, []);
117
118
  this.config.stopPatterns = this.stopPatterns;
118
119
  }
119
120
  if (config.pseudoToolCallThreshold !== undefined) {
@@ -143,13 +144,14 @@ export class LoopGuardState {
143
144
  const chain = state?.recentCallSequence
144
145
  ? state.recentCallSequence.slice(-5).map((fp) => fp.split(':', 1)[0])
145
146
  : (tool ? [String(tool)] : []);
147
+ const rawSession = state?.sessionId || this.agentKey(agent);
146
148
  this.incidents.push({
147
149
  id: 'inc-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6),
148
150
  timestamp: Date.now(),
149
- session: state?.sessionId || this.agentKey(agent),
151
+ session: maskSessionId(rawSession),
150
152
  code: String(code),
151
153
  tool: String(tool || 'system'),
152
- reason: String(detail || ''),
154
+ reason: redactTelemetryText(String(detail || '')),
153
155
  chain,
154
156
  });
155
157
  if (this.incidents.length > 30) this.incidents.shift();
@@ -183,6 +185,7 @@ export class LoopGuardState {
183
185
  for (const k of Object.keys(this.metrics.byCode)) {
184
186
  this.metrics.byCode[k] = 0;
185
187
  }
188
+ this.metrics.targetDenials = 0;
186
189
  this.metrics.lastViolation = null;
187
190
  this.incidents = [];
188
191
  }
@@ -216,30 +219,15 @@ export class LoopGuardState {
216
219
 
217
220
  emptyState(turn = undefined) {
218
221
  return {
219
- turn,
220
- attemptsSinceProgress: 0,
221
- progressAttemptsSinceProgress: 0,
222
- calls: [],
223
- nextCallKey: 1,
224
- stopRequested: false,
225
- answerOnly: false,
226
- stopReason: '',
227
- blockReason: undefined,
228
- progressEpoch: 0,
229
- repeatGroups: new Map(),
230
- exactGroups: new Map(),
231
- lastResults: new Map(),
232
- lastProgress: undefined,
233
- lastEvidence: undefined,
234
- consecutivePseudoTurns: 0,
235
- turnRealToolCalls: 0,
236
- turnHadPseudoCall: false,
237
- turnAssistantText: '',
238
- recentCallSequence: [],
239
- consecutiveFailures: 0,
240
- lastErrorSignature: null,
241
- errorRepeatCount: 0,
242
- steeredCodes: new Set(),
222
+ turn, attemptsSinceProgress: 0, progressAttemptsSinceProgress: 0, calls: [],
223
+ nextCallKey: 1, stopRequested: false, answerOnly: false, stopReason: '',
224
+ blockReason: undefined, progressEpoch: 0, repeatGroups: new Map(),
225
+ exactGroups: new Map(), lastResults: new Map(), lastProgress: undefined,
226
+ lastEvidence: undefined, consecutivePseudoTurns: 0, turnRealToolCalls: 0,
227
+ turnHadPseudoCall: false, turnAssistantText: '', recentCallSequence: [],
228
+ consecutiveFailures: 0, lastErrorSignature: null, errorRepeatCount: 0,
229
+ steeredCodes: new Set(), targetCallCounts: new Map(), targetReadFingerprints: new Map(),
230
+ targetDenialCounts: new Map(), thrashingRecoveryGrace: false,
243
231
  };
244
232
  }
245
233
 
@@ -301,6 +289,8 @@ export class LoopGuardState {
301
289
  state.lastErrorSignature = null;
302
290
  state.errorRepeatCount = 0;
303
291
  state.steeredCodes?.clear();
292
+ state.targetCallCounts?.clear();
293
+ state.targetReadFingerprints?.clear();
304
294
  }
305
295
 
306
296
  endTurn(agent, turnData = {}) {
@@ -342,27 +332,7 @@ export class LoopGuardState {
342
332
  }
343
333
 
344
334
  decrementReservations(state, call) {
345
- if (!call || !call.counted || call.committed) return;
346
- state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
347
- if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
348
- if (call.repeatFingerprint) {
349
- const group = state.repeatGroups.get(call.repeatFingerprint);
350
- if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
351
- group.count = Math.max(0, group.count - 1);
352
- }
353
- }
354
- if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
355
- const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
356
- if (lastIdx !== -1) {
357
- state.recentCallSequence.splice(lastIdx, 1);
358
- }
359
- }
360
- if (call.fingerprint) {
361
- const exact = state.exactGroups.get(call.fingerprint);
362
- if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
363
- exact.count = Math.max(0, exact.count - 1);
364
- }
365
- }
335
+ decrementReservations(state, call);
366
336
  }
367
337
 
368
338
  handleViolation(state, agent, name, args, callId, code, detail) {
@@ -372,6 +342,9 @@ export class LoopGuardState {
372
342
  if (this.config.adaptiveSteering && !state.steeredCodes?.has(code)) {
373
343
  if (!state.steeredCodes) state.steeredCodes = new Set();
374
344
  state.steeredCodes.add(code);
345
+ if (code === 'LOOP_GUARD_ERROR_THRASHING') {
346
+ state.thrashingRecoveryGrace = true;
347
+ }
375
348
  this.metrics.steeredCount = (this.metrics.steeredCount || 0) + 1;
376
349
  this.recordIncident(agent, 'LOOP_GUARD_STEER', `${code}: ${detail}`, name, state);
377
350
 
@@ -462,16 +435,20 @@ export class LoopGuardState {
462
435
  }
463
436
 
464
437
  if (this.config.errorThrashingGuard && (state.consecutiveFailures >= this.config.maxConsecutiveFailures || (state.errorRepeatCount >= this.config.maxConsecutiveFailures && state.lastErrorSignature))) {
465
- const sig = state.lastErrorSignature || 'UNKNOWN_ERROR';
466
- return this.handleViolation(
467
- state,
468
- agent,
469
- name,
470
- args,
471
- callId,
472
- 'LOOP_GUARD_ERROR_THRASHING',
473
- `tool calls produced ${state.consecutiveFailures} consecutive failures (signature: ${sig}) without productive progress`
474
- );
438
+ if (state.thrashingRecoveryGrace) {
439
+ state.thrashingRecoveryGrace = false;
440
+ } else {
441
+ const sig = state.lastErrorSignature || 'UNKNOWN_ERROR';
442
+ return this.handleViolation(
443
+ state,
444
+ agent,
445
+ name,
446
+ args,
447
+ callId,
448
+ 'LOOP_GUARD_ERROR_THRASHING',
449
+ `tool calls produced ${state.consecutiveFailures} consecutive failures (signature: ${sig}) without productive progress`
450
+ );
451
+ }
475
452
  }
476
453
 
477
454
  if (this.config.blockExactDuplicates && exactCount >= 1) {
@@ -482,6 +459,11 @@ export class LoopGuardState {
482
459
  const code = (this.config.blockExactDuplicates && exactCount >= maxRepeats) ? 'LOOP_GUARD_DUPLICATE' : 'LOOP_GUARD_REPEAT';
483
460
  return this.handleViolation(state, agent, name, args, callId, code, 'near-identical tool call repeated without a new result or state change after ' + repeatCount + ' attempts');
484
461
  }
462
+
463
+ if (this.config.targetQuotaGuard) {
464
+ const targetCheck = checkTargetQuota(state, this.config, name, args);
465
+ if (targetCheck) return handleTargetViolation(state, this, agent, name, args, targetCheck);
466
+ }
485
467
  const isProgressTool = this.progressToolNames.has(String(name));
486
468
  if (isProgressTool) {
487
469
  if (state.progressAttemptsSinceProgress >= this.config.maxProgressToolCallsPerTurn) {
@@ -501,11 +483,22 @@ export class LoopGuardState {
501
483
  count: (priorExact?.progressEpoch === state.progressEpoch ? priorExact.count : 0) + 1,
502
484
  progressEpoch: state.progressEpoch,
503
485
  });
486
+ const target = extractTargetKey(name, args);
487
+ const action = classifyToolAction(name);
488
+ if (target) {
489
+ if (!state.targetCallCounts) state.targetCallCounts = new Map();
490
+ const counts = state.targetCallCounts.get(target) || { read: 0, edit: 0, write: 0, delete: 0, default: 0, total: 0 };
491
+ counts[action] = (counts[action] || 0) + 1;
492
+ counts.total += 1;
493
+ state.targetCallCounts.set(target, counts);
494
+ }
504
495
  const call = {
505
496
  id,
506
497
  fingerprint,
507
498
  repeatFingerprint,
508
499
  isProgressTool,
500
+ target,
501
+ action,
509
502
  pending: true,
510
503
  committed: false,
511
504
  released: false,
@@ -554,6 +547,12 @@ export class LoopGuardState {
554
547
  state.lastErrorSignature = errorSig;
555
548
  state.errorRepeatCount = 1;
556
549
  }
550
+ } else {
551
+ state.consecutiveFailures = 0;
552
+ state.lastErrorSignature = null;
553
+ state.errorRepeatCount = 0;
554
+ state.thrashingRecoveryGrace = false;
555
+ if (state.steeredCodes) state.steeredCodes.delete('LOOP_GUARD_ERROR_THRASHING');
557
556
  }
558
557
 
559
558
  const prior = state.lastEvidence;
@@ -567,6 +566,7 @@ export class LoopGuardState {
567
566
  || prior.resultFingerprint !== outcome.resultFingerprint
568
567
  || prior.progressToken !== outcome.progressToken);
569
568
  call.productive = productive;
569
+ recordTargetOutcome(state, call, outcome, productive);
570
570
  state.lastResults.set(call.repeatFingerprint, outcome);
571
571
  if (productive) {
572
572
  state.lastEvidence = outcome;
package/lib/index.js CHANGED
@@ -124,6 +124,11 @@ export const Config = Schema.object({
124
124
  errorThrashingGuard: Schema.boolean().volatile().default(true),
125
125
  maxConsecutiveFailures: Schema.number().volatile().min(2).default(4),
126
126
  adaptiveSteering: Schema.boolean().volatile().default(true),
127
+ targetQuotaGuard: Schema.boolean().volatile().default(true),
128
+ maxUnchangedReadsPerTarget: Schema.number().volatile().min(1).default(3),
129
+ maxReadsPerTarget: Schema.number().volatile().min(1).default(6),
130
+ maxEditsPerTarget: Schema.number().volatile().min(1).default(8),
131
+ maxTargetAttempts: Schema.number().volatile().min(1).default(12),
127
132
  });
128
133
 
129
134
  function callIdFromEvent(event) {
@@ -0,0 +1,244 @@
1
+ import path from 'node:path';
2
+ import fs from 'node:fs';
3
+ import { createHash } from 'node:crypto';
4
+ import { formatSteeringAdvice } from './guard-helpers.js';
5
+
6
+ const READ_ACTIONS = new Set(['read', 'cat', 'inspect', 'fetch', 'load', 'show', 'open', 'view', 'tail', 'head']);
7
+ const EDIT_ACTIONS = new Set(['edit', 'patch', 'replace', 'modify', 'update', 'format', 'rewrite', 'insert', 'substitute']);
8
+ const WRITE_ACTIONS = new Set(['write', 'create', 'save', 'append', 'dump', 'generate', 'put', 'upload']);
9
+ const DELETE_ACTIONS = new Set(['delete', 'remove', 'unlink', 'rm', 'purge', 'destroy', 'drop', 'truncate', 'trash']);
10
+
11
+ export function classifyToolAction(name) {
12
+ if (!name || typeof name !== 'string') return 'default';
13
+ const clean = name.trim();
14
+ if (!clean) return 'default';
15
+
16
+ const tokens = clean
17
+ .replace(/([a-z0-9])([A-Z])/g, '$1_$2')
18
+ .toLowerCase()
19
+ .split(/[^a-z0-9]+/)
20
+ .filter(Boolean);
21
+
22
+ if (tokens.length === 0) return 'default';
23
+
24
+ for (const t of tokens) {
25
+ if (DELETE_ACTIONS.has(t)) return 'delete';
26
+ }
27
+ for (const t of tokens) {
28
+ if (EDIT_ACTIONS.has(t)) return 'edit';
29
+ }
30
+ for (const t of tokens) {
31
+ if (WRITE_ACTIONS.has(t)) return 'write';
32
+ }
33
+ for (const t of tokens) {
34
+ if (READ_ACTIONS.has(t)) return 'read';
35
+ }
36
+
37
+ return 'default';
38
+ }
39
+
40
+ export function extractTargetKey(name, args) {
41
+ if (!args) return null;
42
+ let raw = null;
43
+ if (typeof args === 'string') {
44
+ raw = args;
45
+ } else if (typeof args === 'object') {
46
+ raw = args.path ?? args.file ?? args.filePath ?? args.target ?? args.filename
47
+ ?? args.uri ?? args.dest ?? args.destination ?? args.src ?? args.source
48
+ ?? args.params?.path ?? args.params?.file;
49
+ }
50
+ if (!raw || typeof raw !== 'string') return null;
51
+ const trimmed = raw.trim();
52
+ if (!trimmed) return null;
53
+
54
+ let p = trimmed;
55
+ if (p.startsWith('file://')) {
56
+ p = p.slice(7);
57
+ if (/^\/[a-zA-Z]:/.test(p)) {
58
+ p = p.slice(1);
59
+ }
60
+ }
61
+
62
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(p)) {
63
+ return p;
64
+ }
65
+
66
+ p = p.replace(/\\/g, '/');
67
+ let normalized = path.posix.normalize(p);
68
+
69
+ if (normalized.length > 1 && normalized.endsWith('/')) {
70
+ normalized = normalized.slice(0, -1);
71
+ }
72
+
73
+ const winDriveMatch = /^([a-zA-Z]):(\/.*)?$/.exec(normalized);
74
+ if (winDriveMatch) {
75
+ normalized = winDriveMatch[1].toLowerCase() + ':' + (winDriveMatch[2] || '');
76
+ }
77
+
78
+ try {
79
+ const probe = path.isAbsolute(normalized) ? normalized : path.resolve(normalized);
80
+ if (fs.existsSync(probe)) {
81
+ const stat = fs.lstatSync(probe);
82
+ if (stat.isSymbolicLink()) {
83
+ const real = fs.realpathSync(probe).replace(/\\/g, '/');
84
+ normalized = real;
85
+ }
86
+ }
87
+ } catch {
88
+ // best-effort filesystem check
89
+ }
90
+
91
+ if (process.platform === 'win32') {
92
+ normalized = normalized.toLowerCase();
93
+ }
94
+
95
+ if (normalized.length > 512) {
96
+ normalized = normalized.slice(0, 512);
97
+ }
98
+
99
+ return normalized;
100
+ }
101
+
102
+ export function checkTargetQuota(state, config, name, args) {
103
+ if (!config.targetQuotaGuard) return undefined;
104
+ const target = extractTargetKey(name, args);
105
+ if (!target) return undefined;
106
+
107
+ const action = classifyToolAction(name);
108
+ const counts = state.targetCallCounts?.get(target) || { read: 0, edit: 0, write: 0, delete: 0, default: 0, total: 0 };
109
+
110
+ if (action === 'read' && state.targetReadFingerprints) {
111
+ const readInfo = state.targetReadFingerprints.get(target);
112
+ const maxUnchanged = config.maxUnchangedReadsPerTarget ?? 3;
113
+ if (readInfo && readInfo.unchangedReReads >= maxUnchanged) {
114
+ return {
115
+ code: 'LOOP_GUARD_UNREFRESHED_READ',
116
+ detail: `Target "${target}" has been read ${readInfo.unchangedReReads + 1} times without content changes. File content is already in context. Do not re-read unchanged files; proceed to process or edit, or answer the user directly.`,
117
+ target,
118
+ action,
119
+ nonLatching: true,
120
+ };
121
+ }
122
+ }
123
+
124
+ const maxReads = config.maxReadsPerTarget ?? 6;
125
+ if (action === 'read' && counts.read >= maxReads) {
126
+ return {
127
+ code: 'LOOP_GUARD_TARGET_QUOTA',
128
+ detail: `Read quota (${maxReads}) exceeded for target "${target}". Cease reading this file and proceed with alternative actions or summarize findings.`,
129
+ target,
130
+ action,
131
+ nonLatching: true,
132
+ };
133
+ }
134
+
135
+ const maxEdits = config.maxEditsPerTarget ?? 8;
136
+ if ((action === 'edit' || action === 'write') && (counts.edit + counts.write) >= maxEdits) {
137
+ return {
138
+ code: 'LOOP_GUARD_TARGET_QUOTA',
139
+ detail: `Modification quota (${maxEdits}) exceeded for target "${target}". Repeated modifications suggest an unproductive repair loop; diagnose root cause or explain roadblock.`,
140
+ target,
141
+ action,
142
+ nonLatching: true,
143
+ };
144
+ }
145
+
146
+ const maxTotal = config.maxTargetAttempts ?? 12;
147
+ if (counts.total >= maxTotal) {
148
+ return {
149
+ code: 'LOOP_GUARD_TARGET_QUOTA',
150
+ detail: `Total operation quota (${maxTotal}) exceeded for target "${target}".`,
151
+ target,
152
+ action,
153
+ nonLatching: true,
154
+ };
155
+ }
156
+
157
+ return undefined;
158
+ }
159
+
160
+ export function recordTargetOutcome(state, call, outcome) {
161
+ if (!call?.target) return;
162
+ const target = call.target;
163
+ const action = call.action;
164
+
165
+ if (outcome?.successful && state.targetDenialCounts?.has(target)) {
166
+ state.targetDenialCounts.delete(target);
167
+ }
168
+
169
+ if (action === 'read') {
170
+ if (!state.targetReadFingerprints) state.targetReadFingerprints = new Map();
171
+ const current = state.targetReadFingerprints.get(target);
172
+ const fp = outcome.resultFingerprint;
173
+ if (current && current.lastFingerprint === fp && outcome.successful) {
174
+ current.unchangedReReads = (current.unchangedReReads || 0) + 1;
175
+ } else {
176
+ state.targetReadFingerprints.set(target, {
177
+ lastFingerprint: fp,
178
+ unchangedReReads: 0,
179
+ });
180
+ }
181
+ } else if ((action === 'edit' || action === 'write') && outcome.successful) {
182
+ if (state.targetReadFingerprints?.has(target)) {
183
+ state.targetReadFingerprints.delete(target);
184
+ }
185
+ }
186
+ }
187
+
188
+ export function handleTargetViolation(state, guard, agent, name, args, check) {
189
+ const config = guard.config;
190
+ if (config.adaptiveSteering && !state.steeredCodes?.has(check.code)) {
191
+ if (!state.steeredCodes) state.steeredCodes = new Set();
192
+ state.steeredCodes.add(check.code);
193
+ guard.metrics.steeredCount = (guard.metrics.steeredCount || 0) + 1;
194
+ guard.recordIncident(agent, 'LOOP_GUARD_STEER', `${check.code}: ${check.detail}`, name, state);
195
+ const advice = formatSteeringAdvice(check.code, check.detail, name);
196
+ return `[LOOP_GUARD_STEER] Warning: ${advice} This operation on target is denied, but other tools and targets remain available. Repeated attempts on this target will terminate tool execution for this turn.`;
197
+ }
198
+
199
+ if (!state.targetDenialCounts) state.targetDenialCounts = new Map();
200
+ const denials = (state.targetDenialCounts.get(check.target) || 0) + 1;
201
+ state.targetDenialCounts.set(check.target, denials);
202
+ guard.metrics.targetDenials = (guard.metrics.targetDenials || 0) + 1;
203
+
204
+ const maxDenials = config.maxTargetDenialsBeforeEscalation ?? 3;
205
+ if (denials >= maxDenials) {
206
+ return guard.violation(
207
+ state,
208
+ agent,
209
+ name,
210
+ args,
211
+ undefined,
212
+ check.code,
213
+ `Target "${check.target}" denial repeated ${denials} times without switching targets; escalating to text-only mode to prevent token exhaustion.`
214
+ );
215
+ }
216
+
217
+ guard.metrics.totalViolations += 1;
218
+ guard.metrics.byCode[check.code] = (guard.metrics.byCode[check.code] || 0) + 1;
219
+ guard.metrics.lastViolation = {
220
+ code: check.code,
221
+ tool: String(name),
222
+ timestamp: Date.now(),
223
+ turn: state.turn,
224
+ reason: check.detail,
225
+ };
226
+ guard.recordIncident(agent, check.code, check.detail, name, state);
227
+ if (config.dryRunMode) return undefined;
228
+ return `[${check.code}] ${check.detail}`;
229
+ }
230
+
231
+ export function maskSessionId(session) {
232
+ if (!session) return 'sess-unknown';
233
+ const str = String(session);
234
+ const hash = createHash('sha256').update(str).digest('hex').slice(0, 8);
235
+ return 'sess-' + hash;
236
+ }
237
+
238
+ export function redactTelemetryText(text) {
239
+ if (!text || typeof text !== 'string') return '';
240
+ let sanitized = text.replace(/(?:[a-zA-Z]:[\\/](?:[^"'\s\r\n\\/]+[\\/])+)([^"'\s\r\n\\/]+)/g, '.../$1');
241
+ sanitized = sanitized.replace(/(?:\/(?:[a-zA-Z0-9._-]+)\/)+(?:[a-zA-Z0-9._-]+\/)*([a-zA-Z0-9._-]+)/g, '.../$1');
242
+ return sanitized;
243
+ }
244
+