burnoff 1.2.0 → 1.4.0

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.
@@ -35,6 +35,16 @@ import {
35
35
  recordReadIntervalEntry,
36
36
  updateReadSnapStoreAtomicSync
37
37
  } from './read-clamp.mjs';
38
+ import {
39
+ consumeMatchingAskSnoozeAtomicSync,
40
+ matchesSnoozeEntry
41
+ } from './snooze.mjs';
42
+ import {
43
+ PHASE5_DEFAULTS,
44
+ evaluateDet07CommandOutputGuard,
45
+ evaluateDet08EditIntegrityGuard,
46
+ evaluateDet09EditThrash
47
+ } from './phase5-detectors.mjs';
38
48
 
39
49
  const READ_TOOL_REGEX = /^(?:Read|read_file|view_file)$/i;
40
50
  const EDIT_WRITE_OR_READ_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit|Read|Grep|Glob|read_file|view_file|grep_search)$/i;
@@ -125,7 +135,137 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
125
135
  canonical.agentId || event.ownerId || event.agentId || event.subagentId || sessionId
126
136
  );
127
137
 
138
+ // Resolves interactive `ask` verdicts against active session/workspace snoozes.
139
+ // Security invariant: NEVER invoke for `deny` / `exitCode: 2` verdicts.
140
+ const evaluateAskWithSnooze = (verdict, targetText = '') => {
141
+ const evalNowMs = options.nowMs ?? Date.now();
142
+ let match = null;
143
+ if (Array.isArray(options.snoozes)) {
144
+ const memHit = options.snoozes.find((entry) =>
145
+ matchesSnoozeEntry(entry, { detectorId: verdict.detectorId, target: targetText, nowMs: evalNowMs })
146
+ );
147
+ if (memHit) {
148
+ if (memHit.remaining !== null && memHit.remaining !== undefined) {
149
+ memHit.remaining = Math.max(0, Number(memHit.remaining) - 1);
150
+ }
151
+ match = { matched: true, source: 'memory', grant: memHit };
152
+ }
153
+ } else if (shouldPersistState) {
154
+ match = consumeMatchingAskSnoozeAtomicSync(
155
+ {
156
+ sessionId,
157
+ detectorId: verdict.detectorId,
158
+ target: targetText,
159
+ nowMs: evalNowMs
160
+ },
161
+ cwdOptions
162
+ );
163
+ }
164
+
165
+ if (match?.matched) {
166
+ return {
167
+ snoozed: true,
168
+ response: finalize({
169
+ exitCode: 0,
170
+ stdout: '',
171
+ stderr: '',
172
+ snoozed: true,
173
+ verdict: {
174
+ ...verdict,
175
+ decision: 'allow',
176
+ snoozed: true,
177
+ snoozeGrantId: match.grant?.id || null,
178
+ reason: `[Burnoff Snoozed ${verdict.detectorId}] Allowed via active ${match.source || 'session'} grant.`
179
+ }
180
+ })
181
+ };
182
+ }
183
+
184
+ const askOut = {
185
+ hookSpecificOutput: {
186
+ hookEventName: 'PreToolUse',
187
+ permissionDecision: 'ask',
188
+ permissionDecisionReason: verdict.reason
189
+ }
190
+ };
191
+ return {
192
+ snoozed: false,
193
+ response: finalize({
194
+ exitCode: 0,
195
+ stdout: JSON.stringify(askOut),
196
+ stderr: '',
197
+ verdict
198
+ })
199
+ };
200
+ };
201
+
128
202
  let advisoryNotice = null;
203
+ const appendAdvisory = (existing, nextVerdict) => {
204
+ if (!existing) return nextVerdict;
205
+ return {
206
+ ...existing,
207
+ additionalContext: [
208
+ existing.additionalContext || existing.reason,
209
+ nextVerdict.additionalContext || nextVerdict.reason
210
+ ]
211
+ .filter(Boolean)
212
+ .join('\n'),
213
+ reason: [existing.reason, nextVerdict.reason].filter(Boolean).join('\n')
214
+ };
215
+ };
216
+
217
+ const handlePhase5Verdict = (verdict, snoozeTarget, ledgerCategory) => {
218
+ if (!verdict || !verdict.triggered) return null;
219
+ if (verdict.decision === 'allow') {
220
+ advisoryNotice = appendAdvisory(advisoryNotice, verdict);
221
+ return null;
222
+ }
223
+ if (verdict.decision === 'ask') {
224
+ const evaluated = evaluateAskWithSnooze(verdict, snoozeTarget);
225
+ if (evaluated.snoozed) {
226
+ return evaluated.response;
227
+ }
228
+ if (canRecordLedger) {
229
+ recordSavingsReceipt(
230
+ {
231
+ sessionId,
232
+ cwd: baseCwd,
233
+ category: ledgerCategory,
234
+ detectorId: verdict.detectorId,
235
+ ring0Violation: false,
236
+ modelId,
237
+ savedTokens: 0,
238
+ savedUSD: 0,
239
+ detail: verdict.reason
240
+ },
241
+ cwdOptions
242
+ );
243
+ }
244
+ return evaluated.response;
245
+ }
246
+ if (canRecordLedger) {
247
+ recordSavingsReceipt(
248
+ {
249
+ sessionId,
250
+ cwd: baseCwd,
251
+ category: ledgerCategory,
252
+ detectorId: verdict.detectorId,
253
+ ring0Violation: false,
254
+ modelId,
255
+ savedTokens: 0,
256
+ savedUSD: 0,
257
+ detail: verdict.reason
258
+ },
259
+ cwdOptions
260
+ );
261
+ }
262
+ return finalize({
263
+ exitCode: 2,
264
+ stdout: '',
265
+ stderr: verdict.reason,
266
+ verdict
267
+ });
268
+ };
129
269
 
130
270
  // 1. DET-20: Concurrent file-scope locks & quota hard brakes
131
271
  if (guardsCfg.scopeLockEnabled !== false) {
@@ -169,19 +309,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
169
309
  });
170
310
  if (det01.triggered) {
171
311
  if (det01.decision === 'ask') {
172
- const askOut = {
173
- hookSpecificOutput: {
174
- hookEventName: 'PreToolUse',
175
- permissionDecision: 'ask',
176
- permissionDecisionReason: det01.reason
177
- }
178
- };
179
- return finalize({
180
- exitCode: 0,
181
- stdout: JSON.stringify(askOut),
182
- stderr: '',
183
- verdict: det01
184
- });
312
+ return evaluateAskWithSnooze(det01, command).response;
185
313
  }
186
314
  if (canRecordLedger) {
187
315
  recordSavingsReceipt(
@@ -221,19 +349,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
221
349
  });
222
350
  if (det02.triggered) {
223
351
  if (det02.decision === 'ask') {
224
- const askOut = {
225
- hookSpecificOutput: {
226
- hookEventName: 'PreToolUse',
227
- permissionDecision: 'ask',
228
- permissionDecisionReason: det02.reason
229
- }
230
- };
231
- return finalize({
232
- exitCode: 0,
233
- stdout: JSON.stringify(askOut),
234
- stderr: '',
235
- verdict: det02
236
- });
352
+ return evaluateAskWithSnooze(det02, rawPath || command).response;
237
353
  }
238
354
  if (canRecordLedger) {
239
355
  recordSavingsReceipt(
@@ -267,19 +383,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
267
383
  filePath: rawPath
268
384
  });
269
385
  if (det03.triggered && det03.decision === 'ask') {
270
- const askOut = {
271
- hookSpecificOutput: {
272
- hookEventName: 'PreToolUse',
273
- permissionDecision: 'ask',
274
- permissionDecisionReason: det03.reason
275
- }
276
- };
277
- return finalize({
278
- exitCode: 0,
279
- stdout: JSON.stringify(askOut),
280
- stderr: '',
281
- verdict: det03
282
- });
386
+ return evaluateAskWithSnooze(det03, rawPath).response;
283
387
  }
284
388
  }
285
389
 
@@ -301,6 +405,10 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
301
405
  });
302
406
  if (det04.triggered) {
303
407
  if (det04.decision === 'ask') {
408
+ const evaluated = evaluateAskWithSnooze(det04, rawPath || command);
409
+ if (evaluated.snoozed) {
410
+ return evaluated.response;
411
+ }
304
412
  if (canRecordLedger) {
305
413
  recordSavingsReceipt(
306
414
  {
@@ -317,19 +425,7 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
317
425
  cwdOptions
318
426
  );
319
427
  }
320
- const askOut = {
321
- hookSpecificOutput: {
322
- hookEventName: 'PreToolUse',
323
- permissionDecision: 'ask',
324
- permissionDecisionReason: det04.reason
325
- }
326
- };
327
- return finalize({
328
- exitCode: 0,
329
- stdout: JSON.stringify(askOut),
330
- stderr: '',
331
- verdict: det04
332
- });
428
+ return evaluated.response;
333
429
  }
334
430
  if (canRecordLedger) {
335
431
  recordSavingsReceipt(
@@ -417,23 +513,83 @@ function evaluatePreToolUseCore(event = {}, options = {}) {
417
513
  }
418
514
 
419
515
  if (det05.triggered) {
420
- if (advisoryNotice) {
421
- advisoryNotice = {
422
- ...advisoryNotice,
423
- additionalContext: [
424
- advisoryNotice.additionalContext || advisoryNotice.reason,
425
- det05.additionalContext || det05.reason
426
- ]
427
- .filter(Boolean)
428
- .join('\n'),
429
- reason: [advisoryNotice.reason, det05.reason].filter(Boolean).join('\n')
430
- };
431
- } else {
432
- advisoryNotice = det05;
433
- }
516
+ advisoryNotice = appendAdvisory(advisoryNotice, det05);
434
517
  }
435
518
  }
436
519
 
520
+ // 5c. DET-07: Bash Stdout-Flood & Read-Clamp Bypass Guard
521
+ if (guardsCfg.det07Enabled !== false && SHELL_TOOL_REGEX.test(toolName) && command) {
522
+ const det07 = evaluateDet07CommandOutputGuard({
523
+ toolName,
524
+ command,
525
+ cwd: baseCwd,
526
+ mode: guardMode,
527
+ flightMode,
528
+ action: options.det07Action ?? guardsCfg.det07Action ?? PHASE5_DEFAULTS.det07Action,
529
+ maxBytes:
530
+ options.det07ReadBypassMaxBytes ??
531
+ guardsCfg.det07ReadBypassMaxBytes ??
532
+ policy.readClamp?.maxBytes ??
533
+ PHASE5_DEFAULTS.det07ReadBypassMaxBytes,
534
+ maxLines:
535
+ options.det07ReadBypassMaxLines ??
536
+ guardsCfg.det07ReadBypassMaxLines ??
537
+ policy.readClamp?.maxLines ??
538
+ PHASE5_DEFAULTS.det07ReadBypassMaxLines,
539
+ neverClampExt: policy.readClamp?.neverClampExt ?? [],
540
+ neverClampCodeOffCliff: policy.readClamp?.neverClampCodeOffCliff ?? true
541
+ });
542
+ const det07Response = handlePhase5Verdict(det07, command, 'STDOUT_FLOOD_GUARDED');
543
+ if (det07Response) return det07Response;
544
+ }
545
+
546
+ // 5d. DET-08: Edit-Time Test-Weakening & Empty-Catch Guard (runs before DET-20 lock)
547
+ if (guardsCfg.det08Enabled !== false && EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) && rawPath) {
548
+ const det08 = evaluateDet08EditIntegrityGuard({
549
+ toolName,
550
+ filePath: rawPath,
551
+ toolInput: tIn,
552
+ cwd: baseCwd,
553
+ mode: guardMode,
554
+ flightMode,
555
+ action: options.det08Action ?? guardsCfg.det08Action ?? PHASE5_DEFAULTS.det08Action,
556
+ checkTestSkip:
557
+ options.det08CheckTestSkip ?? guardsCfg.det08CheckTestSkip ?? PHASE5_DEFAULTS.det08CheckTestSkip,
558
+ checkEmptyCatch:
559
+ options.det08CheckEmptyCatch ?? guardsCfg.det08CheckEmptyCatch ?? PHASE5_DEFAULTS.det08CheckEmptyCatch
560
+ });
561
+ const det08Response = handlePhase5Verdict(det08, rawPath, 'EDIT_INTEGRITY_GUARDED');
562
+ if (det08Response) return det08Response;
563
+ }
564
+
565
+ // 5e. DET-09: Same-File Rapid Edit-Thrash Breaker (runs before DET-20 lock)
566
+ if (guardsCfg.det09Enabled !== false && EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) && rawPath) {
567
+ const det09 = evaluateDet09EditThrash({
568
+ toolName,
569
+ filePath: rawPath,
570
+ cwd: baseCwd,
571
+ editThrashHistory:
572
+ event.editThrashHistory ??
573
+ options.editThrashHistory ??
574
+ priorSnap?.editThrashHistory ??
575
+ {},
576
+ maxEditsPerFile:
577
+ options.det09MaxEditsPerFile ??
578
+ guardsCfg.det09MaxEditsPerFile ??
579
+ PHASE5_DEFAULTS.det09MaxEditsPerFile,
580
+ windowSec:
581
+ options.det09WindowSec ??
582
+ guardsCfg.det09WindowSec ??
583
+ PHASE5_DEFAULTS.det09WindowSec,
584
+ mode: guardMode,
585
+ flightMode,
586
+ action: options.det09Action ?? guardsCfg.det09Action ?? PHASE5_DEFAULTS.det09Action,
587
+ nowMs: options.nowMs ?? Date.now()
588
+ });
589
+ const det09Response = handlePhase5Verdict(det09, rawPath, 'EDIT_THRASH_GUARDED');
590
+ if (det09Response) return det09Response;
591
+ }
592
+
437
593
  // 6. Bounded Read Guard & Per-File Read-Interval Cache (`updatedInput`)
438
594
  const isSubagent = Boolean(
439
595
  canonical.isSidechain ||
@@ -0,0 +1,363 @@
1
+ /**
2
+ * @file src/guards/snooze.mjs
3
+ * Session- and workspace-scoped `allow-once` / timed snooze grants for interactive `ask` gates.
4
+ * Security invariant: grants NEVER bypass `deny` / `exitCode: 2` Ring-0 hard blocks.
5
+ */
6
+
7
+ import fs from 'node:fs';
8
+ import path from 'node:path';
9
+ import crypto from 'node:crypto';
10
+ import { getBurnoffRuntimeDir, getWorkspaceStateDir } from '../config/paths.mjs';
11
+ import { atomicWriteJsonSync } from '../storage/atomic-io.mjs';
12
+ import { withFileLockSync } from '../storage/file-lock.mjs';
13
+ import { getBreakerStateFilePath, sanitizeBreakerSessionId } from './loop-breaker.mjs';
14
+
15
+ export const ALLOWED_SNOOZE_DETECTORS = Object.freeze([
16
+ 'DET-01',
17
+ 'DET-02',
18
+ 'DET-03',
19
+ 'DET-04',
20
+ 'DET-07',
21
+ 'DET-08',
22
+ 'DET-09',
23
+ '*'
24
+ ]);
25
+
26
+ export const DEFAULT_ALLOW_ONCE_TTL_MS = 30 * 60 * 1000;
27
+ export const DEFAULT_SNOOZE_TTL_MS = 15 * 60 * 1000;
28
+ const MAX_SNOOZES_STORED = 32;
29
+
30
+ function readJsonSafe(filePath, fallback = null) {
31
+ try {
32
+ if (!fs.existsSync(filePath)) return fallback;
33
+ return JSON.parse(fs.readFileSync(filePath, 'utf8'));
34
+ } catch {
35
+ return fallback; // ignore: corrupt or missing snooze file falls back cleanly
36
+ }
37
+ }
38
+
39
+ /**
40
+ * Normalizes a detector identifier for ask snooze grants (`DET-01`..`DET-04`, `DET-07`..`DET-09`, or `*`).
41
+ * Returns `null` for unsupported or invalid IDs (such as `DET-20` or empty non-default input).
42
+ */
43
+ export function normalizeSnoozeDetectorId(raw = '*') {
44
+ if (raw === undefined || raw === null || raw === '') return '*';
45
+ const s = String(raw).trim().toUpperCase();
46
+ if (!s || s === '*' || s === 'ALL') return '*';
47
+ if (/^DET-0[1-47-9]$/.test(s)) return s;
48
+ return null;
49
+ }
50
+
51
+ /**
52
+ * Resolves workspace-wide snooze store path `<cacheDir>/burnoff_snoozes.json`.
53
+ */
54
+ export function getWorkspaceSnoozeFilePath(options = {}) {
55
+ if (options?.snoozeFilePath) {
56
+ return path.resolve(String(options.snoozeFilePath));
57
+ }
58
+ if (options?.client === 'antigravity') {
59
+ const wsCwd = options?.cwd ? path.resolve(String(options.cwd)) : process.cwd();
60
+ return path.join(getWorkspaceStateDir(wsCwd, options.homeDir), 'burnoff_snoozes.json');
61
+ }
62
+ if (options?.cwd) {
63
+ return path.join(path.resolve(String(options.cwd)), '.claude', 'cache', 'burnoff_snoozes.json');
64
+ }
65
+ if (options?.useRuntimeDir) {
66
+ return path.join(getBurnoffRuntimeDir(options.homeDir || null), 'burnoff_snoozes.json');
67
+ }
68
+ return path.join(process.cwd(), '.claude', 'cache', 'burnoff_snoozes.json');
69
+ }
70
+
71
+ /**
72
+ * Removes expired (`expiresAtMs <= nowMs`) or exhausted (`remaining <= 0`) snooze entries.
73
+ */
74
+ export function pruneExpiredSnoozes(snoozes = [], nowMs = Date.now()) {
75
+ if (!Array.isArray(snoozes)) return [];
76
+ return snoozes.filter((entry) => {
77
+ if (!entry || typeof entry !== 'object') return false;
78
+ const expiresAt = Number(entry.expiresAtMs || 0);
79
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs) return false;
80
+ if (entry.remaining !== null && entry.remaining !== undefined) {
81
+ const rem = Number(entry.remaining);
82
+ if (!Number.isFinite(rem) || rem <= 0) return false;
83
+ }
84
+ return true;
85
+ });
86
+ }
87
+
88
+ function normalizeScopeString(val = '') {
89
+ return String(val || '').replace(/\\/g, '/').trim().toLowerCase();
90
+ }
91
+
92
+ /**
93
+ * Returns true if an active snooze entry matches the detector and optional target scope.
94
+ */
95
+ export function matchesSnoozeEntry(entry, { detectorId, target = '', nowMs = Date.now() } = {}) {
96
+ if (!entry || typeof entry !== 'object') return false;
97
+ const det = normalizeSnoozeDetectorId(detectorId);
98
+ if (!det || det === '*') return false;
99
+
100
+ const expiresAt = Number(entry.expiresAtMs || 0);
101
+ if (!Number.isFinite(expiresAt) || expiresAt <= nowMs) return false;
102
+ if (entry.remaining !== null && entry.remaining !== undefined) {
103
+ const rem = Number(entry.remaining);
104
+ if (!Number.isFinite(rem) || rem <= 0) return false;
105
+ }
106
+
107
+ const entryDet = normalizeSnoozeDetectorId(entry.detectorId || '*');
108
+ if (!entryDet || (entryDet !== '*' && entryDet !== det)) return false;
109
+
110
+ const scope = normalizeScopeString(entry.scope || '*');
111
+ if (!scope || scope === '*') return true;
112
+
113
+ const normTarget = normalizeScopeString(target);
114
+ return normTarget.includes(scope);
115
+ }
116
+
117
+ function normalizeGrantInput({
118
+ detectorId = '*',
119
+ scope = '*',
120
+ count = 1,
121
+ ttlMs = DEFAULT_ALLOW_ONCE_TTL_MS,
122
+ reason = '',
123
+ nowMs = Date.now()
124
+ } = {}) {
125
+ const normalizedDet = normalizeSnoozeDetectorId(detectorId);
126
+ if (!normalizedDet) {
127
+ throw new Error(`Unsupported detectorId "${detectorId}". Allowed: ${ALLOWED_SNOOZE_DETECTORS.join(', ')}`);
128
+ }
129
+ const finiteTtl = Number(ttlMs);
130
+ const safeTtlMs = Number.isFinite(finiteTtl) && finiteTtl > 0 ? finiteTtl : DEFAULT_ALLOW_ONCE_TTL_MS;
131
+ const remaining =
132
+ count === null || count === undefined
133
+ ? null
134
+ : Math.max(1, Math.floor(Number(count) || 1));
135
+
136
+ return {
137
+ id: crypto.randomUUID(),
138
+ detectorId: normalizedDet,
139
+ scope: String(scope || '*').trim() || '*',
140
+ remaining,
141
+ reason: String(reason || '').trim(),
142
+ createdAtMs: nowMs,
143
+ expiresAtMs: nowMs + safeTtlMs
144
+ };
145
+ }
146
+
147
+ /**
148
+ * Atomically grants an `allow-once` or timed snooze override.
149
+ * Stores inside `burnoff_breaker_state_<sessionId>.json` when `sessionId` is supplied,
150
+ * otherwise inside workspace-scoped `burnoff_snoozes.json`.
151
+ */
152
+ export function grantAskSnoozeAtomicSync(
153
+ {
154
+ sessionId = null,
155
+ detectorId = '*',
156
+ scope = '*',
157
+ count = 1,
158
+ ttlMs = DEFAULT_ALLOW_ONCE_TTL_MS,
159
+ reason = '',
160
+ nowMs = Date.now()
161
+ } = {},
162
+ options = {}
163
+ ) {
164
+ const grant = normalizeGrantInput({ detectorId, scope, count, ttlMs, reason, nowMs });
165
+ const hasSession = typeof sessionId === 'string' && sessionId.trim().length > 0;
166
+ const targetPath = hasSession
167
+ ? getBreakerStateFilePath(sessionId, options)
168
+ : getWorkspaceSnoozeFilePath(options);
169
+
170
+ withFileLockSync(
171
+ targetPath,
172
+ () => {
173
+ const prior = readJsonSafe(targetPath, null);
174
+ const base = prior && typeof prior === 'object' ? { ...prior } : {};
175
+ const pruned = pruneExpiredSnoozes(base.snoozes || [], nowMs);
176
+ const nextSnoozes = [...pruned, grant].slice(-MAX_SNOOZES_STORED);
177
+ const next = hasSession
178
+ ? {
179
+ schemaVersion: '1.0.0',
180
+ ...base,
181
+ sessionId: sanitizeBreakerSessionId(sessionId),
182
+ snoozes: nextSnoozes,
183
+ updatedAt: nowMs
184
+ }
185
+ : {
186
+ schemaVersion: '1.0.0',
187
+ snoozes: nextSnoozes,
188
+ updatedAt: nowMs
189
+ };
190
+ atomicWriteJsonSync(targetPath, next, {
191
+ ...options,
192
+ maxRetries: Math.max(10, Number(options?.maxRetries || 10))
193
+ });
194
+ },
195
+ options
196
+ );
197
+
198
+ return {
199
+ ok: true,
200
+ target: hasSession ? 'session' : 'workspace',
201
+ path: targetPath,
202
+ grant
203
+ };
204
+ }
205
+
206
+ /**
207
+ * Lists currently active (non-expired, non-exhausted) snoozes for session and/or workspace.
208
+ */
209
+ export function listActiveSnoozes({ sessionId = null, nowMs = Date.now() } = {}, options = {}) {
210
+ const entries = [];
211
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
212
+ const sessPath = getBreakerStateFilePath(sessionId, options);
213
+ const sessDoc = readJsonSafe(sessPath, null);
214
+ for (const entry of pruneExpiredSnoozes(sessDoc?.snoozes || [], nowMs)) {
215
+ entries.push({ ...entry, source: 'session', path: sessPath });
216
+ }
217
+ }
218
+ const wsPath = getWorkspaceSnoozeFilePath(options);
219
+ const wsDoc = readJsonSafe(wsPath, null);
220
+ for (const entry of pruneExpiredSnoozes(wsDoc?.snoozes || [], nowMs)) {
221
+ entries.push({ ...entry, source: 'workspace', path: wsPath });
222
+ }
223
+ return entries;
224
+ }
225
+
226
+ /**
227
+ * Atomically clears snoozes from session and/or workspace stores.
228
+ */
229
+ export function clearAskSnoozesAtomicSync({ sessionId = null, detectorId = null } = {}, options = {}) {
230
+ const filterDet = detectorId ? normalizeSnoozeDetectorId(detectorId) : null;
231
+ if (detectorId && !filterDet) {
232
+ throw new Error(`Unsupported detectorId "${detectorId}". Allowed: ${ALLOWED_SNOOZE_DETECTORS.join(', ')}`);
233
+ }
234
+
235
+ let clearedCount = 0;
236
+ const targets = [getWorkspaceSnoozeFilePath(options)];
237
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
238
+ targets.unshift(getBreakerStateFilePath(sessionId, options));
239
+ }
240
+
241
+ for (const targetPath of targets) {
242
+ if (!fs.existsSync(targetPath)) continue;
243
+ withFileLockSync(
244
+ targetPath,
245
+ () => {
246
+ const prior = readJsonSafe(targetPath, null);
247
+ if (!prior || !Array.isArray(prior.snoozes) || prior.snoozes.length === 0) return;
248
+ const kept =
249
+ !filterDet || filterDet === '*'
250
+ ? []
251
+ : prior.snoozes.filter((e) => normalizeSnoozeDetectorId(e?.detectorId || '*') !== filterDet);
252
+ clearedCount += prior.snoozes.length - kept.length;
253
+ if (kept.length !== prior.snoozes.length) {
254
+ atomicWriteJsonSync(
255
+ targetPath,
256
+ { ...prior, snoozes: kept, updatedAt: Date.now() },
257
+ { ...options, maxRetries: Math.max(10, Number(options?.maxRetries || 10)) }
258
+ );
259
+ }
260
+ },
261
+ options
262
+ );
263
+ }
264
+
265
+ return { ok: true, clearedCount };
266
+ }
267
+
268
+ function tryConsumeFromFileSync(filePath, sourceLabel, { detectorId, target = '', nowMs = Date.now() }, options = {}) {
269
+ if (!filePath || !fs.existsSync(filePath)) return null;
270
+ // Quick lock-free pre-check on parsed JSON so non-snoozed files skip lock overhead cleanly
271
+ const quickSnap = readJsonSafe(filePath, null);
272
+ const quickList = pruneExpiredSnoozes(quickSnap?.snoozes || [], nowMs);
273
+ if (!quickList.some((entry) => matchesSnoozeEntry(entry, { detectorId, target, nowMs }))) {
274
+ return null;
275
+ }
276
+
277
+ let consumed = null;
278
+ withFileLockSync(
279
+ filePath,
280
+ () => {
281
+ const prior = readJsonSafe(filePath, null);
282
+ if (!prior || typeof prior !== 'object') return;
283
+ const active = pruneExpiredSnoozes(prior.snoozes || [], nowMs);
284
+ const idx = active.findIndex((entry) => matchesSnoozeEntry(entry, { detectorId, target, nowMs }));
285
+ if (idx === -1) return;
286
+
287
+ const matchedEntry = { ...active[idx] };
288
+ const nextList = [...active];
289
+ if (matchedEntry.remaining !== null && matchedEntry.remaining !== undefined) {
290
+ const nextRemaining = Number(matchedEntry.remaining) - 1;
291
+ if (nextRemaining <= 0) {
292
+ nextList.splice(idx, 1);
293
+ } else {
294
+ nextList[idx] = { ...matchedEntry, remaining: nextRemaining };
295
+ }
296
+ }
297
+
298
+ atomicWriteJsonSync(
299
+ filePath,
300
+ {
301
+ ...prior,
302
+ snoozes: nextList,
303
+ updatedAt: nowMs
304
+ },
305
+ { ...options, maxRetries: Math.max(10, Number(options?.maxRetries || 10)) }
306
+ );
307
+ consumed = matchedEntry;
308
+ },
309
+ options
310
+ );
311
+
312
+ return consumed ? { matched: true, source: sourceLabel, grant: consumed } : null;
313
+ }
314
+
315
+ /**
316
+ * Checks session breaker state first and workspace snooze store second for an active grant
317
+ * matching an `ask` verdict. Atomically consumes one use when `remaining` is finite.
318
+ */
319
+ export function consumeMatchingAskSnoozeAtomicSync(
320
+ { sessionId = 'default', detectorId, target = '', nowMs = Date.now() } = {},
321
+ options = {}
322
+ ) {
323
+ const det = normalizeSnoozeDetectorId(detectorId);
324
+ if (!det || det === '*') {
325
+ return { matched: false };
326
+ }
327
+
328
+ if (typeof sessionId === 'string' && sessionId.trim().length > 0) {
329
+ const sessPath = getBreakerStateFilePath(sessionId, options);
330
+ const sessMatch = tryConsumeFromFileSync(
331
+ sessPath,
332
+ 'session',
333
+ { detectorId: det, target, nowMs },
334
+ options
335
+ );
336
+ if (sessMatch) return sessMatch;
337
+ }
338
+
339
+ const wsPath = getWorkspaceSnoozeFilePath(options);
340
+ const wsMatch = tryConsumeFromFileSync(
341
+ wsPath,
342
+ 'workspace',
343
+ { detectorId: det, target, nowMs },
344
+ options
345
+ );
346
+ if (wsMatch) return wsMatch;
347
+
348
+ return { matched: false };
349
+ }
350
+
351
+ export default {
352
+ ALLOWED_SNOOZE_DETECTORS,
353
+ DEFAULT_ALLOW_ONCE_TTL_MS,
354
+ DEFAULT_SNOOZE_TTL_MS,
355
+ normalizeSnoozeDetectorId,
356
+ getWorkspaceSnoozeFilePath,
357
+ pruneExpiredSnoozes,
358
+ matchesSnoozeEntry,
359
+ grantAskSnoozeAtomicSync,
360
+ listActiveSnoozes,
361
+ clearAskSnoozesAtomicSync,
362
+ consumeMatchingAskSnoozeAtomicSync
363
+ };