@goodandready/dsh-agent-loop-guard 0.3.5 → 0.3.6

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,20 @@
1
1
  # Changelog
2
2
 
3
+ ## [0.3.6] - 2026-11-18
4
+
5
+ ### Fixed
6
+ - **Telemetry Redaction Completeness (#156)**: `lastViolation.reason` is now redacted with `redactTelemetryText`, matching incident journal redaction; absolute target paths no longer leak through the telemetry endpoint.
7
+ - **Localization Standard Compliance (#154)**: Removed the in-plugin `ru` dictionary and registration; the client registers exactly `{ en, zh }`. Russian UI is provided by `dsh-russian-lang`, with translation keys tracked there.
8
+ - **Windows Test Portability (#161)**: Symlink assertion skips gracefully when Windows denies symlink creation (`EPERM`/`EACCES`), and case-sensitive target expectations are platform-aware.
9
+ - **Documentation Sync (#160)**: `index.md` names the current release line; DESIGN uses canonical `--dsw-alias-brand-primary` and state tokens; docs-consistency test guards both.
10
+ - **Line Budget Headroom (#164)**: Moved `decrementReservations` into `lib/target-quota-guard.js`, reducing `lib/guard-helpers.js` below 450 lines.
11
+ - **Dead Import Cleanup (#165)**: Removed the remaining unused `GUARD_PRESETS` import from `lib/guard-state.js`.
12
+ - **Windows Packaging Warning (#153)**: `pack-release.mjs` prefers `npm_execpath`, avoiding `shell:true` argument concatenation under `npm run`; `npm run pack:release` remains cross-platform.
13
+ - **Preset Documentation (#159)**: Clarified that `Balanced` is a recommended, stricter-than-default profile; server/client parity remains enforced by `test/presets-parity.test.js`.
14
+
15
+ ### Documentation
16
+ - Added `npm ci` and `npm audit --omit=dev --audit-level=high` to the verification workflow; the reviewed lockfile is part of the release gate.
17
+
3
18
  ## [0.3.5] - 2026-11-18
4
19
 
5
20
  ### Fixed
package/README.md CHANGED
@@ -48,7 +48,7 @@ When autonomous AI coding agents encounter unexpected tool failures, ambiguous i
48
48
  5. **Error Thrashing Guard**: Halts runaway failure cycles sharing normalized error signatures (`FS_ENOENT`, `FS_EPERM`, `EXIT_*`, `HTTP_*`, etc.) even when parameters vary.
49
49
  6. **Smart Steering**: 2-stage defense injecting actionable self-correction directives (`[LOOP_GUARD_STEER]`) before escalating to hard cancellation.
50
50
  7. **Incident Journal & Diagnostic Dump**: Circular telemetry buffer tracking recent incidents with execution chains and 1-click dump copying in Web UI.
51
- 8. **Sensitivity Presets**: 1-click preset selector (`Strict`, `Balanced`, `Autonomous Coding`) for immediate threshold configuration.
51
+ 8. **Sensitivity Presets**: 1-click preset selector (`Strict`, `Balanced`, `Autonomous Coding`) for immediate threshold configuration. `Balanced` is a recommended starting profile and is intentionally stricter than the schema defaults.
52
52
  9. **Zero Core Modifications**: Implemented purely through Cordis lifecycle hooks (`ctx.tools.guard`, `agent/pre-step`, `tools/execute`, `session/event`).
53
53
 
54
54
  ---
@@ -208,11 +208,13 @@ dsh-agent-loop-guard:
208
208
 
209
209
  ## 🧪 Testing & Verification
210
210
 
211
- Run the full automated test suite covering all loop denial paths, streaming output guards, and progress epochs:
211
+ The reviewed `package-lock.json` pins the peer dependency graph used for audit and CI. Use `npm ci` for a clean, lockfile-respecting install:
212
212
 
213
213
  ```bash
214
+ npm ci
214
215
  npm test
215
216
  npm run check
217
+ npm audit --omit=dev --audit-level=high
216
218
  ```
217
219
 
218
220
  ---
package/lib/client.js CHANGED
@@ -83,31 +83,6 @@ window.__ModuleLoader__.load({
83
83
  saving: 'Saving…', ready: 'Save Settings', saved: 'Saved',
84
84
  };
85
85
 
86
- const ru = {
87
- title: 'Agent Loop Guard', sub: 'Защита от бесконечных циклов инструментов и вывода ассистента', version: 'Версия',
88
- updateChecking: 'Проверка обновлений…', updateAvailable: 'Доступно обновление: v{v}', upToDate: 'Установлена актуальная версия',
89
- updateNow: 'Обновить сейчас', updateViaPluginsPage: 'Обновите на вкладке плагинов', updating: 'Обновление…',
90
- updateSuccess: 'Обновлено до v{v}. Перезапустите службу DSH для применения.', updateFailed: 'Ошибка обновления: {msg}', checkUpdateFailed: 'Не удалось проверить',
91
- telemetryTitle: 'Телеметрия защиты', telemetryLoadFailed: 'Не удалось загрузить телеметрию', totalBlocked: 'Предотвращено циклов', totalTruncations: 'Усечений',
92
- steeredCount: 'Упреждающих подсказок', lastViolation: 'Последний инцидент', noViolations: 'В текущем сеансе циклов не зафиксировано.',
93
- resetStats: 'Сбросить статистику', statsResetDone: 'Статистика сброшена', statsResetFailed: 'Не удалось сбросить статистику',
94
- presetsTitle: 'Профили', presetStrict: 'Строгий', presetBalanced: 'Баланс', presetAutonomous: 'Автономный код',
95
- presetApplied: 'Применен профиль {name}', copyDump: 'Скопировать дамп диагностики', dumpCopied: 'Дамп скопирован в буфер',
96
- incidentsTitle: 'Журнал инцидентов (Post-Mortem)', maxToolAttemptsPerTurn: 'Макс. попыток инструментов за ход (0 = выкл)',
97
- maxProgressToolCallsPerTurn: 'Макс. вызовов инструментов прогресса за ход', maxCallsPerRepeatGroup: 'Макс. повторов в группе',
98
- strictTools: 'Строгие инструменты (через запятую)', strictToolLimit: 'Лимит строгих инструментов',
99
- blockExactDuplicates: 'Блокировать точные дубликаты вызовов', dryRunMode: 'Режим аудита (логировать, но не блокировать)',
100
- assistantOutputGuard: 'Защита от циклов текста ассистента', maxRepeatedAssistantLines: 'Макс. повторов одной строки',
101
- maxRepeatedAssistantBlocks: 'Макс. повторов блока текста', maxAssistantBlockChars: 'Макс. размер блока текста для проверки',
102
- progressToolNames: 'Инструменты прогресса (через запятую)', pseudoToolCallThreshold: 'Порог циклов псевдовызовов (ходов, 0 = выкл)',
103
- oscillationDetection: 'Защита от осцилляций (циклов туда-сюда)', maxOscillationRepeats: 'Макс. повторов цикла осцилляции',
104
- payloadBloatGuard: 'Защита от раздувания результатов (обрезка)', maxToolResultChars: 'Макс. символов результата (0 = выкл)',
105
- errorThrashingGuard: 'Защита от серий ошибок инструментов', maxConsecutiveFailures: 'Порог серии ошибок перед блокировкой',
106
- adaptiveSteering: 'Умное наставление (предупреждать перед отменой)', targetQuotaGuard: 'Квоты обращений к файлам (защита от циклов по целям)',
107
- maxUnchangedReadsPerTarget: 'Макс. повторных чтений неизмененного файла', maxReadsPerTarget: 'Макс. чтений одного файла за ход',
108
- maxEditsPerTarget: 'Макс. правок одного файла за ход', maxTargetAttempts: 'Макс. всего операций над файлом за ход',
109
- saving: 'Сохранение…', ready: 'Сохранить настройки', saved: 'Сохранено',
110
- };
111
86
 
112
87
  const zh = {
113
88
  title: 'Agent Loop Guard', sub: '工具调用与助手输出防死循环熔断限制', version: '版本',
@@ -218,7 +193,7 @@ window.__ModuleLoader__.load({
218
193
  : (typeof ctx?.locale?.getSnapshot === 'function' ? ctx.locale.getSnapshot() : null);
219
194
  const loc = typeof snap === 'string' ? snap : (snap?.active || snap?.locale || snap?.id);
220
195
  const locStr = String(loc || (typeof navigator !== 'undefined' && navigator.language ? navigator.language : 'en')).toLowerCase();
221
- return locStr.startsWith('zh') ? zh : (locStr.startsWith('ru') ? ru : en);
196
+ return locStr.startsWith('zh') ? zh : en;
222
197
  }
223
198
 
224
199
  function PluginCard({ ctx: _ctx, t, bare, ...props }) {
@@ -541,7 +516,7 @@ window.__ModuleLoader__.load({
541
516
  exports.inject = ['slots', 'configForms', 'locale'];
542
517
  exports.apply = function apply(ctx) {
543
518
  if (typeof ctx.locale?.register === 'function') {
544
- const reg = () => ctx.locale.register(NS, { en, zh, ru });
519
+ const reg = () => ctx.locale.register(NS, { en, zh });
545
520
  if (typeof ctx.effect === 'function') ctx.effect(reg, 'dsh-agent-loop-guard: locale');
546
521
  else reg();
547
522
  }
@@ -311,36 +311,6 @@ export {
311
311
  handleTargetViolation,
312
312
  } from './target-quota-guard.js';
313
313
 
314
- export function decrementReservations(state, call) {
315
- if (!call || !call.counted || call.committed) return;
316
- state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
317
- if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
318
- if (call.repeatFingerprint) {
319
- const group = state.repeatGroups.get(call.repeatFingerprint);
320
- if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
321
- group.count = Math.max(0, group.count - 1);
322
- }
323
- }
324
- if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
325
- const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
326
- if (lastIdx !== -1) {
327
- state.recentCallSequence.splice(lastIdx, 1);
328
- }
329
- }
330
- if (call.fingerprint) {
331
- const exact = state.exactGroups.get(call.fingerprint);
332
- if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
333
- exact.count = Math.max(0, exact.count - 1);
334
- }
335
- }
336
- if (call.target && state.targetCallCounts) {
337
- const counts = state.targetCallCounts.get(call.target);
338
- if (counts) {
339
- if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
340
- if (counts.total > 0) counts.total -= 1;
341
- }
342
- }
343
- }
344
314
 
345
315
 
346
316
 
@@ -1,23 +1,18 @@
1
1
  import {
2
2
  isDefaultStopRequest,
3
3
  detectOscillation,
4
- DEFAULT_PSEUDO_TOOL_PATTERNS,
5
4
  compilePseudoToolPatterns,
6
5
  isPseudoToolCallText,
7
- compileStopPatterns,
8
6
  positiveInteger,
9
7
  nonNegativeInteger,
10
8
  hasStopRequest,
11
9
  callFingerprint,
12
10
  callRepeatFingerprint,
13
- resultFingerprint,
14
11
  safeCallSummary,
15
12
  outcomeFromExecution,
16
13
  normalizeErrorSignature,
17
- GUARD_PRESETS,
18
14
  formatSteeringAdvice,
19
15
  formatViolationGuidance,
20
- decrementReservations,
21
16
  } from './guard-helpers.js';
22
17
 
23
18
  import {
@@ -28,6 +23,7 @@ import {
28
23
  handleTargetViolation,
29
24
  maskSessionId,
30
25
  redactTelemetryText,
26
+ decrementReservations,
31
27
  } from './target-quota-guard.js';
32
28
 
33
29
  export * from './guard-helpers.js';
@@ -170,7 +166,7 @@ export class LoopGuardState {
170
166
  tool: extra.tool || 'assistant/output',
171
167
  timestamp: Date.now(),
172
168
  turn: extra.turn,
173
- reason: detail,
169
+ reason: redactTelemetryText(detail),
174
170
  };
175
171
  this.recordIncident(null, code, detail, extra.tool || 'assistant/output', null);
176
172
  }
@@ -178,6 +174,9 @@ export class LoopGuardState {
178
174
  getTelemetry() {
179
175
  return {
180
176
  ...this.metrics,
177
+ lastViolation: this.metrics.lastViolation
178
+ ? { ...this.metrics.lastViolation, reason: redactTelemetryText(this.metrics.lastViolation.reason) }
179
+ : null,
181
180
  activeAgents: this.byAgent.size,
182
181
  dryRunMode: Boolean(this.config.dryRunMode),
183
182
  incidents: (this.incidents || []).slice(-20).reverse(),
@@ -365,7 +364,7 @@ export class LoopGuardState {
365
364
  tool: String(name),
366
365
  timestamp: Date.now(),
367
366
  turn: state.turn,
368
- reason: detail,
367
+ reason: redactTelemetryText(detail),
369
368
  };
370
369
  this.recordIncident(agent, code, detail, name, state);
371
370
 
@@ -221,7 +221,7 @@ export function handleTargetViolation(state, guard, agent, name, args, check) {
221
221
  tool: String(name),
222
222
  timestamp: Date.now(),
223
223
  turn: state.turn,
224
- reason: check.detail,
224
+ reason: redactTelemetryText(check.detail),
225
225
  };
226
226
  guard.recordIncident(agent, check.code, check.detail, name, state);
227
227
  if (config.dryRunMode) return undefined;
@@ -241,4 +241,35 @@ export function redactTelemetryText(text) {
241
241
  sanitized = sanitized.replace(/(?:\/(?:[a-zA-Z0-9._-]+)\/)+(?:[a-zA-Z0-9._-]+\/)*([a-zA-Z0-9._-]+)/g, '.../$1');
242
242
  return sanitized;
243
243
  }
244
-
244
+
245
+
246
+ export function decrementReservations(state, call) {
247
+ if (!call || !call.counted || call.committed) return;
248
+ state.attemptsSinceProgress = Math.max(0, state.attemptsSinceProgress - 1);
249
+ if (call.isProgressTool) state.progressAttemptsSinceProgress = Math.max(0, state.progressAttemptsSinceProgress - 1);
250
+ if (call.repeatFingerprint) {
251
+ const group = state.repeatGroups.get(call.repeatFingerprint);
252
+ if (group && group.progressEpoch === state.progressEpoch && group.count > 0) {
253
+ group.count = Math.max(0, group.count - 1);
254
+ }
255
+ }
256
+ if (call.repeatFingerprint && state.recentCallSequence.length > 0) {
257
+ const lastIdx = state.recentCallSequence.lastIndexOf(call.repeatFingerprint);
258
+ if (lastIdx !== -1) {
259
+ state.recentCallSequence.splice(lastIdx, 1);
260
+ }
261
+ }
262
+ if (call.fingerprint) {
263
+ const exact = state.exactGroups.get(call.fingerprint);
264
+ if (exact && exact.progressEpoch === state.progressEpoch && exact.count > 0) {
265
+ exact.count = Math.max(0, exact.count - 1);
266
+ }
267
+ }
268
+ if (call.target && state.targetCallCounts) {
269
+ const counts = state.targetCallCounts.get(call.target);
270
+ if (counts) {
271
+ if (call.action && counts[call.action] > 0) counts[call.action] -= 1;
272
+ if (counts.total > 0) counts.total -= 1;
273
+ }
274
+ }
275
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@goodandready/dsh-agent-loop-guard",
3
- "version": "0.3.5",
3
+ "version": "0.3.6",
4
4
  "description": "Fail-closed runtime tool-call loop guard for DeepSeek Harness.",
5
5
  "type": "module",
6
6
  "main": "lib/index.js",