@goodandready/dsh-agent-loop-guard 0.3.1 → 0.3.3

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/CHANGELOG.md CHANGED
@@ -1,5 +1,34 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.3] - 2026-11-16
4
+
5
+ ### Added
6
+ - **Hot Path Performance & Memory Optimizations (#158)**:
7
+ - **Pre-Compiled Pseudo-Tool Regex**: Regex patterns are compiled once in `LoopGuardState` constructor and config reload (`compiledPseudoPatterns`), eliminating re-compilation on every streaming delta chunk.
8
+ - **Sliding Tail Window Scan**: `observeAssistantText` inspects only an overlap tail window (`text.length + 256` bytes) instead of rescanning up to 64 KB on every delta, eliminating $O(N^2)$ streaming overhead.
9
+ - **Large Payload Fast Fingerprinting**: String arguments exceeding 2048 characters are hashed via deterministic prefix + length + SHA-256 fingerprint in `callFingerprint` and `callRepeatFingerprint`, preventing multi-megabyte JSON serialization and heap spikes during massive file writes.
10
+ - **Bounded Call Sequence History**: `state.calls` is bounded to the most recent 64 entries, preventing unbounded array growth in long-running sessions.
11
+ - **Audit-First Dry-Run Mode (#162)**: Extended `dryRunMode` to output repetition guard (`cancelOnOutputHit`) and pseudo-tool loop detector (`cancelOnPseudoHit`). Violations are recorded to telemetry and incident journals for audit without terminating agent execution or cancelling generation.
12
+ - **Automated Preset Parity Gate (#159)**: Added automated test suite `test/presets-parity.test.js` validating 1:1 parameter parity across server `GUARD_PRESETS` and client `CLIENT_PRESETS` for all profiles (`Strict`, `Balanced`, `Autonomous`). Aligned `LoopGuardState` constructor fallback for `maxUnchangedReadsPerTarget` with schema default (3).
13
+
14
+ ### Fixed
15
+ - **Dead Imports & Redundant Delegate Elimination (#165)**: Removed unused imports `GUARD_PRESETS` and `hasStopRequest` in `lib/index.js`. Removed redundant wrapper `LoopGuardState.decrementReservations` in favor of direct module function invocation.
16
+ - **SMB Mount Filemode Drift Protection (#166)**: Documented and enforced `core.fileMode = false` for SMB/Windows-mounted checkouts, preventing spurious 100755/100644 git status diffs.
17
+
18
+ ## [0.3.2] - 2026-11-16
19
+
20
+ ### Added
21
+ - **Target Quota Escalation Guard (#148)**: Target-specific non-latching denials now escalate to hard `answerOnly` text mode when an agent repeatedly ignores target quota denials (threshold: 3 consecutive denials on the same target, configurable via `maxTargetDenialsBeforeEscalation`). Prevents fail-open token burning loops while preserving non-latching flexibility for self-correcting models. Added `targetDenials` metric and updated steering warning text.
22
+ - **Smart Steering Recovery for Error Thrashing (#149)**: Introduced single-attempt recovery grace (`thrashingRecoveryGrace`) following `LOOP_GUARD_ERROR_THRASHING` steering warnings. Allows the agent to execute an alternative tool call or diagnosis command to recover. Resets failure counters and steering state on successful tool execution, and escalates to hard violation only if recovery fails.
23
+ - **Target Quota Engine Modular Extraction (#164)**: Extracted all target quota operations (`classifyToolAction`, `extractTargetKey`, `checkTargetQuota`, `recordTargetOutcome`, `handleTargetViolation`) into dedicated module `lib/target-quota-guard.js`, keeping all server modules strictly under line budget limits (< 450 lines in `guard-helpers.js`, < 595 lines in `guard-state.js`).
24
+
25
+ ### Fixed
26
+ - **Accurate Tool Action Classification (#150)**: Fixed token-boundary classification in `classifyToolAction` using camelCase/separator tokenization and exact action dictionaries. Eliminates false positive substring matches (`format_code`, `perform_action`, `confirm_changes` no longer misclassified as `delete` via `rm`; `review_changes`, `preview_url`, `locate_symbol` no longer misclassified as `read` via `view`/`cat`).
27
+ - **Path Case Preservation & Lexical Normalization (#151)**: Enhanced `extractTargetKey` with POSIX segment normalization (`..` and `.` resolution), symlink canonicalization via `fs.realpathSync`, Windows drive letter normalization (`c:`), and Linux case preservation (`README.md` and `readme.md` maintained as distinct targets on case-sensitive filesystems).
28
+ - **Per-Target Per-Turn Quota Accumulation (#152)**: Fixed per-target quota counters (`maxReadsPerTarget`, `maxEditsPerTarget`, `maxTargetAttempts`) being erroneously wiped on unrelated global progress. Counters now consistently accumulate per turn across interleaved tool calls.
29
+ - **Output Guard Orphaned Tool Call Cleanup (#155)**: Resolved silent output guard suppression caused by aborted or cancelled tool calls. `activeTools` reservations are now automatically cleared on turn boundaries (`turn/end`), step changes, and user interventions (`resetForUser`), with a hard upper bound of 64 active calls.
30
+ - **Telemetry Data Redaction & LAN Security (#156)**: Hardened `/api/@goodandready/dsh-agent-loop-guard/telemetry` against sensitive data leaks over LAN. Replaced raw session identifiers with pseudonymous hashes (`maskSessionId`) and sanitized absolute filesystem paths in incident reasons to masked basenames (`redactTelemetryText`).
31
+
3
32
  ## [0.3.1] - 2026-11-16
4
33
 
5
34
  ### Added
@@ -88,6 +88,9 @@ export class AssistantOutputGuardState {
88
88
  beginBlock(session, turn, step, index = 0) {
89
89
  const state = this.stateFor(session);
90
90
  if (state.turn !== turn || state.step !== step || state.index !== index) {
91
+ if (state.turn !== undefined && state.turn !== turn) {
92
+ state.activeTools.clear();
93
+ }
91
94
  state.turn = turn;
92
95
  state.step = step;
93
96
  state.index = index;
@@ -137,6 +140,7 @@ export class AssistantOutputGuardState {
137
140
  state.repeatCount = 0;
138
141
  state.triggered = false;
139
142
  state.seenMessages.clear();
143
+ state.activeTools.clear();
140
144
  }
141
145
 
142
146
  observeLine(session, line) {
@@ -273,10 +277,19 @@ export class AssistantOutputGuardState {
273
277
 
274
278
  markToolCall(session, callId) {
275
279
  const state = this.stateFor(session);
276
- if (typeof callId === 'string' && callId.length > 0) state.activeTools.add(callId);
280
+ if (typeof callId === 'string' && callId.length > 0) {
281
+ if (state.activeTools.size >= 64) {
282
+ state.activeTools.clear();
283
+ }
284
+ state.activeTools.add(callId);
285
+ }
277
286
  this.resetStreak(session);
278
287
  }
279
288
 
289
+ clearActiveTools(session) {
290
+ this.stateFor(session).activeTools.clear();
291
+ }
292
+
280
293
  markToolResult(session, callId) {
281
294
  const state = this.stateFor(session);
282
295
  if (typeof callId === 'string' && callId.length > 0) state.activeTools.delete(callId);
@@ -301,7 +314,9 @@ export class AssistantOutputGuardState {
301
314
  }
302
315
 
303
316
  endTurn(session) {
304
- return this.endBlock(session);
317
+ const hit = this.endBlock(session);
318
+ this.stateFor(session).activeTools.clear();
319
+ return hit;
305
320
  }
306
321
 
307
322
  dispose(session) {
@@ -95,7 +95,8 @@ export function isPseudoToolCallText(text, customPatterns = []) {
95
95
  for (const regex of DEFAULT_PSEUDO_TOOL_PATTERNS) {
96
96
  if (regex.test(text)) return true;
97
97
  }
98
- const compiled = compilePseudoToolPatterns(customPatterns);
98
+ if (!Array.isArray(customPatterns) || customPatterns.length === 0) return false;
99
+ const compiled = (customPatterns[0] instanceof RegExp) ? customPatterns : compilePseudoToolPatterns(customPatterns);
99
100
  for (const regex of compiled) {
100
101
  if (regex.test(text)) return true;
101
102
  }
@@ -119,14 +120,25 @@ export function compileStopPatterns(customPatterns = []) {
119
120
  const SECRET_KEY_PATTERN = /(?:token|secret|password|authorization|api[-_]?key|cookie)/iu;
120
121
 
121
122
  function stableJson(value) {
122
- if (value === null || typeof value !== 'object') return JSON.stringify(value);
123
+ if (value === null || typeof value !== 'object') {
124
+ if (typeof value === 'string' && value.length > 2048) {
125
+ return JSON.stringify(value.slice(0, 512) + ':len:' + value.length + ':hash:' + createHash('sha256').update(value).digest('hex').slice(0, 16));
126
+ }
127
+ return JSON.stringify(value);
128
+ }
123
129
  if (Array.isArray(value)) return '[' + value.map(stableJson).join(',') + ']';
124
130
  return '{' + Object.keys(value).sort().map((key) => JSON.stringify(key) + ':' + stableJson(value[key])).join(',') + '}';
125
131
  }
126
132
 
127
133
  function normalizedJson(value) {
128
134
  if (value === null || typeof value !== 'object') {
129
- if (typeof value === 'string') return JSON.stringify(value.trim().replace(/\s+/gu, ' '));
135
+ if (typeof value === 'string') {
136
+ const trimmed = value.trim().replace(/\s+/gu, ' ');
137
+ if (trimmed.length > 2048) {
138
+ return JSON.stringify(trimmed.slice(0, 512) + ':len:' + trimmed.length + ':hash:' + createHash('sha256').update(trimmed).digest('hex').slice(0, 16));
139
+ }
140
+ return JSON.stringify(trimmed);
141
+ }
130
142
  return JSON.stringify(value);
131
143
  }
132
144
  if (Array.isArray(value)) return '[' + value.map(normalizedJson).join(',') + ']';
@@ -291,141 +303,13 @@ export function normalizeErrorSignature(error) {
291
303
  return sanitized.length > 0 ? sanitized : 'GENERIC_ERROR';
292
304
  }
293
305
 
294
- export function extractTargetKey(name, args) {
295
- if (!args) return null;
296
- let raw = null;
297
- if (typeof args === 'string') {
298
- raw = args;
299
- } else if (typeof args === 'object') {
300
- raw = args.path ?? args.file ?? args.filePath ?? args.target ?? args.filename
301
- ?? args.uri ?? args.dest ?? args.destination ?? args.src ?? args.source
302
- ?? args.params?.path ?? args.params?.file;
303
- }
304
- if (!raw || typeof raw !== 'string') return null;
305
- const trimmed = raw.trim();
306
- if (!trimmed) return null;
307
-
308
- let normalized = trimmed.replace(/\\/g, '/');
309
- if (normalized.startsWith('file://')) {
310
- normalized = normalized.slice(7);
311
- }
312
- normalized = normalized.replace(/\/{2,}/g, '/');
313
- while (normalized.startsWith('./')) {
314
- normalized = normalized.slice(2);
315
- }
316
- normalized = normalized.replace(/\/\.\//g, '/');
317
- if (normalized.length > 1 && normalized.endsWith('/')) {
318
- normalized = normalized.slice(0, -1);
319
- }
320
- return normalized.toLowerCase();
321
- }
322
-
323
- export function classifyToolAction(name) {
324
- if (!name || typeof name !== 'string') return 'default';
325
- const lower = name.toLowerCase();
326
- if (lower.includes('read') || lower.includes('view') || lower.includes('cat') || lower.includes('inspect') || lower.includes('fetch')) {
327
- return 'read';
328
- }
329
- if (lower.includes('edit') || lower.includes('patch') || lower.includes('replace') || lower.includes('modify')) {
330
- return 'edit';
331
- }
332
- if (lower.includes('write') || lower.includes('create') || lower.includes('save') || lower.includes('append')) {
333
- return 'write';
334
- }
335
- if (lower.includes('delete') || lower.includes('remove') || lower.includes('unlink') || lower.includes('rm')) {
336
- return 'delete';
337
- }
338
- return 'default';
339
- }
340
-
341
- export function checkTargetQuota(state, config, name, args) {
342
- if (!config.targetQuotaGuard) return undefined;
343
- const target = extractTargetKey(name, args);
344
- if (!target) return undefined;
345
-
346
- const action = classifyToolAction(name);
347
- const counts = state.targetCallCounts?.get(target) || { read: 0, edit: 0, write: 0, delete: 0, default: 0, total: 0 };
348
-
349
- if (action === 'read' && state.targetReadFingerprints) {
350
- const readInfo = state.targetReadFingerprints.get(target);
351
- const maxUnchanged = config.maxUnchangedReadsPerTarget ?? 3;
352
- if (readInfo && readInfo.unchangedReReads >= maxUnchanged) {
353
- return {
354
- code: 'LOOP_GUARD_UNREFRESHED_READ',
355
- 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.`,
356
- target,
357
- action,
358
- nonLatching: true,
359
- };
360
- }
361
- }
362
-
363
- const maxReads = config.maxReadsPerTarget ?? 6;
364
- if (action === 'read' && counts.read >= maxReads) {
365
- return {
366
- code: 'LOOP_GUARD_TARGET_QUOTA',
367
- detail: `Read quota (${maxReads}) exceeded for target "${target}". Cease reading this file and proceed with alternative actions or summarize findings.`,
368
- target,
369
- action,
370
- nonLatching: true,
371
- };
372
- }
373
-
374
- const maxEdits = config.maxEditsPerTarget ?? 8;
375
- if ((action === 'edit' || action === 'write') && (counts.edit + counts.write) >= maxEdits) {
376
- return {
377
- code: 'LOOP_GUARD_TARGET_QUOTA',
378
- detail: `Modification quota (${maxEdits}) exceeded for target "${target}". Repeated modifications suggest an unproductive repair loop; diagnose root cause or explain roadblock.`,
379
- target,
380
- action,
381
- nonLatching: true,
382
- };
383
- }
384
-
385
- const maxTotal = config.maxTargetAttempts ?? 12;
386
- if (counts.total >= maxTotal) {
387
- return {
388
- code: 'LOOP_GUARD_TARGET_QUOTA',
389
- detail: `Total operation quota (${maxTotal}) exceeded for target "${target}".`,
390
- target,
391
- action,
392
- nonLatching: true,
393
- };
394
- }
395
-
396
- return undefined;
397
- }
398
-
399
- export function recordTargetOutcome(state, call, outcome, productive = false) {
400
- if (!call?.target) return;
401
- const target = call.target;
402
- const action = call.action;
403
-
404
- if (productive) {
405
- const counts = state.targetCallCounts?.get(target);
406
- if (counts) {
407
- counts.read = 0; counts.edit = 0; counts.write = 0; counts.delete = 0; counts.default = 0; counts.total = 0;
408
- }
409
- }
410
-
411
- if (action === 'read') {
412
- if (!state.targetReadFingerprints) state.targetReadFingerprints = new Map();
413
- const current = state.targetReadFingerprints.get(target);
414
- const fp = outcome.resultFingerprint;
415
- if (current && current.lastFingerprint === fp && outcome.successful) {
416
- current.unchangedReReads = (current.unchangedReReads || 0) + 1;
417
- } else {
418
- state.targetReadFingerprints.set(target, {
419
- lastFingerprint: fp,
420
- unchangedReReads: 0,
421
- });
422
- }
423
- } else if ((action === 'edit' || action === 'write') && outcome.successful) {
424
- if (state.targetReadFingerprints?.has(target)) {
425
- state.targetReadFingerprints.delete(target);
426
- }
427
- }
428
- }
306
+ export {
307
+ classifyToolAction,
308
+ extractTargetKey,
309
+ checkTargetQuota,
310
+ recordTargetOutcome,
311
+ handleTargetViolation,
312
+ } from './target-quota-guard.js';
429
313
 
430
314
  export function decrementReservations(state, call) {
431
315
  if (!call || !call.counted || call.committed) return;
@@ -459,25 +343,6 @@ export function decrementReservations(state, call) {
459
343
  }
460
344
 
461
345
 
462
- export function handleTargetViolation(state, guard, agent, name, args, check) {
463
- const config = guard.config;
464
- if (config.adaptiveSteering && !state.steeredCodes?.has(check.code)) {
465
- if (!state.steeredCodes) state.steeredCodes = new Set();
466
- state.steeredCodes.add(check.code);
467
- guard.metrics.steeredCount = (guard.metrics.steeredCount || 0) + 1;
468
- guard.recordIncident(agent, 'LOOP_GUARD_STEER', `${check.code}: ${check.detail}`, name, state);
469
- const advice = formatSteeringAdvice(check.code, check.detail, name);
470
- return `[LOOP_GUARD_STEER] Warning: ${advice} If this pattern continues, tool execution will be terminated for this turn.`;
471
- }
472
- guard.metrics.totalViolations += 1;
473
- guard.metrics.byCode[check.code] = (guard.metrics.byCode[check.code] || 0) + 1;
474
- guard.metrics.lastViolation = {
475
- code: check.code, tool: String(name), timestamp: Date.now(), turn: state.turn, reason: check.detail,
476
- };
477
- guard.recordIncident(agent, check.code, check.detail, name, state);
478
- if (config.dryRunMode) return undefined;
479
- return `[${check.code}] ${check.detail}`;
480
- }
481
346
 
482
347
  export const GUARD_PRESETS = {
483
348
  strict: {
@@ -17,33 +17,33 @@ import {
17
17
  GUARD_PRESETS,
18
18
  formatSteeringAdvice,
19
19
  formatViolationGuidance,
20
- extractTargetKey,
20
+ decrementReservations,
21
+ } from './guard-helpers.js';
22
+
23
+ import {
21
24
  classifyToolAction,
25
+ extractTargetKey,
22
26
  checkTargetQuota,
23
27
  recordTargetOutcome,
24
- decrementReservations,
25
28
  handleTargetViolation,
26
- } from './guard-helpers.js';
29
+ maskSessionId,
30
+ redactTelemetryText,
31
+ } from './target-quota-guard.js';
27
32
 
28
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
+ }
29
41
 
30
42
  export class LoopGuardState {
31
43
  constructor(config = {}) {
32
- const progressToolNames = Array.isArray(config.progressToolNames)
33
- ? config.progressToolNames
34
- .filter((name) => typeof name === 'string' && name.trim() !== '')
35
- .map((name) => name.trim())
36
- : ['todo_write'];
37
- const strictTools = Array.isArray(config.strictTools)
38
- ? config.strictTools
39
- .filter((name) => typeof name === 'string' && name.trim() !== '')
40
- .map((name) => name.trim())
41
- : [];
42
- const stopPatterns = Array.isArray(config.stopPatterns)
43
- ? config.stopPatterns
44
- .filter((name) => typeof name === 'string' && name.trim() !== '')
45
- .map((name) => name.trim())
46
- : [];
44
+ const progressToolNames = cleanStringList(config.progressToolNames, ['todo_write']);
45
+ const strictTools = cleanStringList(config.strictTools, []);
46
+ const stopPatterns = cleanStringList(config.stopPatterns, []);
47
47
  this.config = {
48
48
  ...config,
49
49
  maxToolAttemptsPerTurn: nonNegativeInteger(config.maxToolAttemptsPerTurn, 64),
@@ -61,13 +61,14 @@ export class LoopGuardState {
61
61
  maxConsecutiveFailures: positiveInteger(config.maxConsecutiveFailures, 4),
62
62
  adaptiveSteering: Boolean(config.adaptiveSteering),
63
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)),
64
+ maxUnchangedReadsPerTarget: config.maxUnchangedReadsPerTarget !== undefined ? positiveInteger(config.maxUnchangedReadsPerTarget, 3) : 3,
65
65
  maxReadsPerTarget: positiveInteger(config.maxReadsPerTarget, 6),
66
66
  maxEditsPerTarget: positiveInteger(config.maxEditsPerTarget, 8),
67
67
  maxTargetAttempts: positiveInteger(config.maxTargetAttempts, 12),
68
68
  };
69
69
  this.stopPatterns = stopPatterns;
70
70
  this.pseudoPatterns = this.config.pseudoToolCallPatterns;
71
+ this.compiledPseudoPatterns = compilePseudoToolPatterns(this.pseudoPatterns);
71
72
  this.logger = config.logger;
72
73
  this.onViolation = typeof config.onViolation === 'function' ? config.onViolation : undefined;
73
74
  this.progressToolNames = new Set(progressToolNames);
@@ -87,21 +88,14 @@ export class LoopGuardState {
87
88
  LOOP_GUARD_ERROR_THRASHING: 0, LOOP_GUARD_STEER: 0, LOOP_GUARD_TARGET_QUOTA: 0,
88
89
  LOOP_GUARD_UNREFRESHED_READ: 0,
89
90
  },
91
+ targetDenials: 0,
90
92
  lastViolation: null,
91
93
  };
92
94
  }
93
95
 
94
96
  updateConfig(config = {}) {
95
- const progressToolNames = Array.isArray(config.progressToolNames)
96
- ? config.progressToolNames
97
- .filter((name) => typeof name === 'string' && name.trim() !== '')
98
- .map((name) => name.trim())
99
- : Array.from(this.progressToolNames);
100
- const strictTools = Array.isArray(config.strictTools)
101
- ? config.strictTools
102
- .filter((name) => typeof name === 'string' && name.trim() !== '')
103
- .map((name) => name.trim())
104
- : Array.from(this.strictTools);
97
+ const progressToolNames = cleanStringList(config.progressToolNames, Array.from(this.progressToolNames));
98
+ const strictTools = cleanStringList(config.strictTools, Array.from(this.strictTools));
105
99
  this.config = {
106
100
  ...this.config,
107
101
  ...config,
@@ -121,9 +115,7 @@ export class LoopGuardState {
121
115
  maxTargetAttempts: positiveInteger(config.maxTargetAttempts, this.config.maxTargetAttempts ?? 12),
122
116
  };
123
117
  if (Array.isArray(config.stopPatterns)) {
124
- this.stopPatterns = config.stopPatterns
125
- .filter((name) => typeof name === 'string' && name.trim() !== '')
126
- .map((name) => name.trim());
118
+ this.stopPatterns = cleanStringList(config.stopPatterns, []);
127
119
  this.config.stopPatterns = this.stopPatterns;
128
120
  }
129
121
  if (config.pseudoToolCallThreshold !== undefined) {
@@ -132,6 +124,7 @@ export class LoopGuardState {
132
124
  if (Array.isArray(config.pseudoToolCallPatterns)) {
133
125
  this.pseudoPatterns = config.pseudoToolCallPatterns;
134
126
  this.config.pseudoToolCallPatterns = this.pseudoPatterns;
127
+ this.compiledPseudoPatterns = compilePseudoToolPatterns(this.pseudoPatterns);
135
128
  }
136
129
  if (config.oscillationDetection !== undefined) {
137
130
  this.config.oscillationDetection = Boolean(config.oscillationDetection);
@@ -153,13 +146,14 @@ export class LoopGuardState {
153
146
  const chain = state?.recentCallSequence
154
147
  ? state.recentCallSequence.slice(-5).map((fp) => fp.split(':', 1)[0])
155
148
  : (tool ? [String(tool)] : []);
149
+ const rawSession = state?.sessionId || this.agentKey(agent);
156
150
  this.incidents.push({
157
151
  id: 'inc-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6),
158
152
  timestamp: Date.now(),
159
- session: state?.sessionId || this.agentKey(agent),
153
+ session: maskSessionId(rawSession),
160
154
  code: String(code),
161
155
  tool: String(tool || 'system'),
162
- reason: String(detail || ''),
156
+ reason: redactTelemetryText(String(detail || '')),
163
157
  chain,
164
158
  });
165
159
  if (this.incidents.length > 30) this.incidents.shift();
@@ -193,6 +187,7 @@ export class LoopGuardState {
193
187
  for (const k of Object.keys(this.metrics.byCode)) {
194
188
  this.metrics.byCode[k] = 0;
195
189
  }
190
+ this.metrics.targetDenials = 0;
196
191
  this.metrics.lastViolation = null;
197
192
  this.incidents = [];
198
193
  }
@@ -234,6 +229,7 @@ export class LoopGuardState {
234
229
  turnHadPseudoCall: false, turnAssistantText: '', recentCallSequence: [],
235
230
  consecutiveFailures: 0, lastErrorSignature: null, errorRepeatCount: 0,
236
231
  steeredCodes: new Set(), targetCallCounts: new Map(), targetReadFingerprints: new Map(),
232
+ targetDenialCounts: new Map(), thrashingRecoveryGrace: false,
237
233
  };
238
234
  }
239
235
 
@@ -270,7 +266,8 @@ export class LoopGuardState {
270
266
  const state = this.stateFor(agent);
271
267
  if (state.turnHadPseudoCall) return;
272
268
  state.turnAssistantText = (state.turnAssistantText + text).slice(-65536);
273
- if (isPseudoToolCallText(state.turnAssistantText, this.pseudoPatterns)) {
269
+ const scanWindow = state.turnAssistantText.slice(-(text.length + 256));
270
+ if (isPseudoToolCallText(scanWindow, this.compiledPseudoPatterns || this.pseudoPatterns)) {
274
271
  state.turnHadPseudoCall = true;
275
272
  }
276
273
  }
@@ -337,10 +334,6 @@ export class LoopGuardState {
337
334
  return state.calls.findLast((call) => !call.released && !call.resultSeen);
338
335
  }
339
336
 
340
- decrementReservations(state, call) {
341
- decrementReservations(state, call);
342
- }
343
-
344
337
  handleViolation(state, agent, name, args, callId, code, detail) {
345
338
  if (code === 'LOOP_GUARD_STOP' || state.answerOnly) {
346
339
  return this.violation(state, agent, name, args, callId, code, detail);
@@ -348,6 +341,9 @@ export class LoopGuardState {
348
341
  if (this.config.adaptiveSteering && !state.steeredCodes?.has(code)) {
349
342
  if (!state.steeredCodes) state.steeredCodes = new Set();
350
343
  state.steeredCodes.add(code);
344
+ if (code === 'LOOP_GUARD_ERROR_THRASHING') {
345
+ state.thrashingRecoveryGrace = true;
346
+ }
351
347
  this.metrics.steeredCount = (this.metrics.steeredCount || 0) + 1;
352
348
  this.recordIncident(agent, 'LOOP_GUARD_STEER', `${code}: ${detail}`, name, state);
353
349
 
@@ -438,16 +434,20 @@ export class LoopGuardState {
438
434
  }
439
435
 
440
436
  if (this.config.errorThrashingGuard && (state.consecutiveFailures >= this.config.maxConsecutiveFailures || (state.errorRepeatCount >= this.config.maxConsecutiveFailures && state.lastErrorSignature))) {
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
- );
437
+ if (state.thrashingRecoveryGrace) {
438
+ state.thrashingRecoveryGrace = false;
439
+ } else {
440
+ const sig = state.lastErrorSignature || 'UNKNOWN_ERROR';
441
+ return this.handleViolation(
442
+ state,
443
+ agent,
444
+ name,
445
+ args,
446
+ callId,
447
+ 'LOOP_GUARD_ERROR_THRASHING',
448
+ `tool calls produced ${state.consecutiveFailures} consecutive failures (signature: ${sig}) without productive progress`
449
+ );
450
+ }
451
451
  }
452
452
 
453
453
  if (this.config.blockExactDuplicates && exactCount >= 1) {
@@ -505,6 +505,7 @@ export class LoopGuardState {
505
505
  resultSeen: false,
506
506
  };
507
507
  state.calls.push(call);
508
+ if (state.calls.length > 64) state.calls.shift();
508
509
  state.attemptsSinceProgress += 1;
509
510
  state.recentCallSequence.push(repeatFingerprint);
510
511
  if (state.recentCallSequence.length > 32) state.recentCallSequence.shift();
@@ -527,7 +528,7 @@ export class LoopGuardState {
527
528
  if (call === undefined) return { known: false, productive: false };
528
529
  if (call.pending && !call.committed) {
529
530
  call.released = true;
530
- this.decrementReservations(state, call);
531
+ decrementReservations(state, call);
531
532
  return { known: false, productive: false };
532
533
  }
533
534
  const outcome = outcomeFromExecution(execution, maybeResult);
@@ -546,6 +547,12 @@ export class LoopGuardState {
546
547
  state.lastErrorSignature = errorSig;
547
548
  state.errorRepeatCount = 1;
548
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');
549
556
  }
550
557
 
551
558
  const prior = state.lastEvidence;
package/lib/index.js CHANGED
@@ -1,8 +1,6 @@
1
1
  import Schema from '@deepseek-ai/schemastery';
2
2
  import {
3
3
  LoopGuardState,
4
- GUARD_PRESETS,
5
- hasStopRequest,
6
4
  nonNegativeInteger,
7
5
  positiveInteger,
8
6
  } from './guard-state.js';
@@ -173,6 +171,9 @@ function cancelOnPseudoHit(ctx, session, hit, state = null) {
173
171
  } catch (error) {
174
172
  ctx.logger?.debug?.('dsh-agent-loop-guard: failed to record external violation: ' + (error instanceof Error ? error.message : String(error)));
175
173
  }
174
+ if (state?.config?.dryRunMode) {
175
+ return;
176
+ }
176
177
  cancelForOutputLoop(ctx, session, hit.reason);
177
178
  }
178
179
 
@@ -197,6 +198,9 @@ function cancelOnOutputHit(ctx, session, assistantState, hit, state = null) {
197
198
  } catch (error) {
198
199
  ctx.logger?.debug?.('dsh-agent-loop-guard: failed to record external violation: ' + (error instanceof Error ? error.message : String(error)));
199
200
  }
201
+ if (state?.config?.dryRunMode) {
202
+ return;
203
+ }
200
204
  cancelForOutputLoop(ctx, session, hit.reason);
201
205
  }
202
206
 
@@ -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
+
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-agent-loop-guard",
3
- "version": "0.3.1",
3
+ "version": "0.3.3",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",
@@ -21,7 +21,7 @@
21
21
  ],
22
22
  "scripts": {
23
23
  "test": "node --test",
24
- "check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/guard-helpers.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js && node scripts/pack-check.mjs",
24
+ "check": "node --check lib/index.js && node --check lib/guard-state.js && node --check lib/guard-helpers.js && node --check lib/target-quota-guard.js && node --check lib/assistant-output-state.js && node --check lib/plugin-updater.js && node --check lib/client.js && node scripts/pack-check.mjs",
25
25
  "build:client": "node scripts/build-client.mjs",
26
26
  "pretest": "node scripts/build-client.mjs",
27
27
  "clean": "node scripts/clean-pack.mjs",