@goodandready/dsh-agent-loop-guard 0.3.1 → 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.
- package/CHANGELOG.md +14 -0
- package/lib/assistant-output-state.js +17 -2
- package/lib/guard-helpers.js +7 -154
- package/lib/guard-state.js +50 -43
- package/lib/target-quota-guard.js +244 -0
- package/package.json +2 -2
package/CHANGELOG.md
CHANGED
|
@@ -1,5 +1,19 @@
|
|
|
1
1
|
# Changelog
|
|
2
2
|
|
|
3
|
+
## [0.3.2] - 2026-11-16
|
|
4
|
+
|
|
5
|
+
### Added
|
|
6
|
+
- **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.
|
|
7
|
+
- **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.
|
|
8
|
+
- **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`).
|
|
9
|
+
|
|
10
|
+
### Fixed
|
|
11
|
+
- **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`).
|
|
12
|
+
- **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).
|
|
13
|
+
- **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.
|
|
14
|
+
- **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.
|
|
15
|
+
- **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`).
|
|
16
|
+
|
|
3
17
|
## [0.3.1] - 2026-11-16
|
|
4
18
|
|
|
5
19
|
### 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)
|
|
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
|
-
|
|
317
|
+
const hit = this.endBlock(session);
|
|
318
|
+
this.stateFor(session).activeTools.clear();
|
|
319
|
+
return hit;
|
|
305
320
|
}
|
|
306
321
|
|
|
307
322
|
dispose(session) {
|
package/lib/guard-helpers.js
CHANGED
|
@@ -291,141 +291,13 @@ export function normalizeErrorSignature(error) {
|
|
|
291
291
|
return sanitized.length > 0 ? sanitized : 'GENERIC_ERROR';
|
|
292
292
|
}
|
|
293
293
|
|
|
294
|
-
export
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
|
|
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
|
-
}
|
|
294
|
+
export {
|
|
295
|
+
classifyToolAction,
|
|
296
|
+
extractTargetKey,
|
|
297
|
+
checkTargetQuota,
|
|
298
|
+
recordTargetOutcome,
|
|
299
|
+
handleTargetViolation,
|
|
300
|
+
} from './target-quota-guard.js';
|
|
429
301
|
|
|
430
302
|
export function decrementReservations(state, call) {
|
|
431
303
|
if (!call || !call.counted || call.committed) return;
|
|
@@ -459,25 +331,6 @@ export function decrementReservations(state, call) {
|
|
|
459
331
|
}
|
|
460
332
|
|
|
461
333
|
|
|
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
334
|
|
|
482
335
|
export const GUARD_PRESETS = {
|
|
483
336
|
strict: {
|
package/lib/guard-state.js
CHANGED
|
@@ -17,33 +17,33 @@ import {
|
|
|
17
17
|
GUARD_PRESETS,
|
|
18
18
|
formatSteeringAdvice,
|
|
19
19
|
formatViolationGuidance,
|
|
20
|
-
|
|
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
|
-
|
|
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 =
|
|
33
|
-
|
|
34
|
-
|
|
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),
|
|
@@ -87,21 +87,14 @@ export class LoopGuardState {
|
|
|
87
87
|
LOOP_GUARD_ERROR_THRASHING: 0, LOOP_GUARD_STEER: 0, LOOP_GUARD_TARGET_QUOTA: 0,
|
|
88
88
|
LOOP_GUARD_UNREFRESHED_READ: 0,
|
|
89
89
|
},
|
|
90
|
+
targetDenials: 0,
|
|
90
91
|
lastViolation: null,
|
|
91
92
|
};
|
|
92
93
|
}
|
|
93
94
|
|
|
94
95
|
updateConfig(config = {}) {
|
|
95
|
-
const progressToolNames = Array.
|
|
96
|
-
|
|
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);
|
|
96
|
+
const progressToolNames = cleanStringList(config.progressToolNames, Array.from(this.progressToolNames));
|
|
97
|
+
const strictTools = cleanStringList(config.strictTools, Array.from(this.strictTools));
|
|
105
98
|
this.config = {
|
|
106
99
|
...this.config,
|
|
107
100
|
...config,
|
|
@@ -121,9 +114,7 @@ export class LoopGuardState {
|
|
|
121
114
|
maxTargetAttempts: positiveInteger(config.maxTargetAttempts, this.config.maxTargetAttempts ?? 12),
|
|
122
115
|
};
|
|
123
116
|
if (Array.isArray(config.stopPatterns)) {
|
|
124
|
-
this.stopPatterns = config.stopPatterns
|
|
125
|
-
.filter((name) => typeof name === 'string' && name.trim() !== '')
|
|
126
|
-
.map((name) => name.trim());
|
|
117
|
+
this.stopPatterns = cleanStringList(config.stopPatterns, []);
|
|
127
118
|
this.config.stopPatterns = this.stopPatterns;
|
|
128
119
|
}
|
|
129
120
|
if (config.pseudoToolCallThreshold !== undefined) {
|
|
@@ -153,13 +144,14 @@ export class LoopGuardState {
|
|
|
153
144
|
const chain = state?.recentCallSequence
|
|
154
145
|
? state.recentCallSequence.slice(-5).map((fp) => fp.split(':', 1)[0])
|
|
155
146
|
: (tool ? [String(tool)] : []);
|
|
147
|
+
const rawSession = state?.sessionId || this.agentKey(agent);
|
|
156
148
|
this.incidents.push({
|
|
157
149
|
id: 'inc-' + Date.now().toString(36) + '-' + Math.random().toString(36).slice(2, 6),
|
|
158
150
|
timestamp: Date.now(),
|
|
159
|
-
session:
|
|
151
|
+
session: maskSessionId(rawSession),
|
|
160
152
|
code: String(code),
|
|
161
153
|
tool: String(tool || 'system'),
|
|
162
|
-
reason: String(detail || ''),
|
|
154
|
+
reason: redactTelemetryText(String(detail || '')),
|
|
163
155
|
chain,
|
|
164
156
|
});
|
|
165
157
|
if (this.incidents.length > 30) this.incidents.shift();
|
|
@@ -193,6 +185,7 @@ export class LoopGuardState {
|
|
|
193
185
|
for (const k of Object.keys(this.metrics.byCode)) {
|
|
194
186
|
this.metrics.byCode[k] = 0;
|
|
195
187
|
}
|
|
188
|
+
this.metrics.targetDenials = 0;
|
|
196
189
|
this.metrics.lastViolation = null;
|
|
197
190
|
this.incidents = [];
|
|
198
191
|
}
|
|
@@ -234,6 +227,7 @@ export class LoopGuardState {
|
|
|
234
227
|
turnHadPseudoCall: false, turnAssistantText: '', recentCallSequence: [],
|
|
235
228
|
consecutiveFailures: 0, lastErrorSignature: null, errorRepeatCount: 0,
|
|
236
229
|
steeredCodes: new Set(), targetCallCounts: new Map(), targetReadFingerprints: new Map(),
|
|
230
|
+
targetDenialCounts: new Map(), thrashingRecoveryGrace: false,
|
|
237
231
|
};
|
|
238
232
|
}
|
|
239
233
|
|
|
@@ -348,6 +342,9 @@ export class LoopGuardState {
|
|
|
348
342
|
if (this.config.adaptiveSteering && !state.steeredCodes?.has(code)) {
|
|
349
343
|
if (!state.steeredCodes) state.steeredCodes = new Set();
|
|
350
344
|
state.steeredCodes.add(code);
|
|
345
|
+
if (code === 'LOOP_GUARD_ERROR_THRASHING') {
|
|
346
|
+
state.thrashingRecoveryGrace = true;
|
|
347
|
+
}
|
|
351
348
|
this.metrics.steeredCount = (this.metrics.steeredCount || 0) + 1;
|
|
352
349
|
this.recordIncident(agent, 'LOOP_GUARD_STEER', `${code}: ${detail}`, name, state);
|
|
353
350
|
|
|
@@ -438,16 +435,20 @@ export class LoopGuardState {
|
|
|
438
435
|
}
|
|
439
436
|
|
|
440
437
|
if (this.config.errorThrashingGuard && (state.consecutiveFailures >= this.config.maxConsecutiveFailures || (state.errorRepeatCount >= this.config.maxConsecutiveFailures && state.lastErrorSignature))) {
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
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
|
+
}
|
|
451
452
|
}
|
|
452
453
|
|
|
453
454
|
if (this.config.blockExactDuplicates && exactCount >= 1) {
|
|
@@ -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;
|
|
@@ -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.
|
|
3
|
+
"version": "0.3.2",
|
|
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",
|