burnoff 1.3.0 → 1.4.1
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/.claude-plugin/plugin.json +1 -1
- package/.github/workflows/burnoff-pr-gate.yml +3 -3
- package/.github/workflows/burnoff-startup-lint.yml +2 -2
- package/README.md +213 -195
- package/bin/burnoff.mjs +6 -5
- package/commands/burnoff.md +2 -2
- package/docs/CLAUDE_CODE_PLUGIN.md +6 -6
- package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
- package/hooks/hook-io.mjs +691 -599
- package/package.json +1 -1
- package/scripts/bench-hooks.mjs +252 -0
- package/scripts/burnoff-statusline.mjs +20 -0
- package/src/cli/audit.mjs +82 -4
- package/src/cli/doctor.mjs +583 -462
- package/src/cli/hook-health.mjs +429 -0
- package/src/cli/init.mjs +668 -646
- package/src/cli/startup-audit.mjs +147 -2
- package/src/clients/antigravity.mjs +285 -285
- package/src/config/policy.mjs +307 -294
- package/src/guards/credential-scrubber.mjs +185 -0
- package/src/guards/loop-breaker.mjs +797 -744
- package/src/guards/phase5-detectors.mjs +727 -0
- package/src/guards/post-tool-engine.mjs +875 -854
- package/src/guards/pre-tool-engine.mjs +973 -846
- package/src/guards/read-clamp.mjs +826 -804
- package/src/guards/shell-guard.mjs +1705 -1676
- package/src/guards/snooze.mjs +5 -2
- package/src/guards/structural-boundaries.mjs +175 -0
- package/src/ipc/fast-client.mjs +255 -255
- package/src/storage/antigravity-parser.mjs +18 -1
- package/src/storage/fts5-archive.mjs +734 -733
- package/src/storage/jsonl-parser.mjs +29 -1
- package/src/storage/telemetry-metrics.mjs +703 -0
|
@@ -1,854 +1,875 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* @file src/guards/post-tool-engine.mjs
|
|
3
|
-
* Pure ESM orchestrator for Claude Code `PostToolUse` evaluation.
|
|
4
|
-
* Atomically updates `DET-04` failure counters and `git stash` timestamps, strips ANSI/spinners,
|
|
5
|
-
* compresses eligible CLI logs via SQLite FTS5 (`npx burnoff search`), offloads >4,000-token blobs
|
|
6
|
-
* while preserving 100% of critical error lines, and replaces tool outputs in native host shapes.
|
|
7
|
-
*/
|
|
8
|
-
|
|
9
|
-
import fs from 'node:fs';
|
|
10
|
-
import path from 'node:path';
|
|
11
|
-
import crypto from 'node:crypto';
|
|
12
|
-
import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
|
|
13
|
-
import { loadBurnoffPolicy } from '../config/policy.mjs';
|
|
14
|
-
import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
|
|
15
|
-
import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
|
|
16
|
-
import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
|
|
17
|
-
import {
|
|
18
|
-
compressCliOutputFts5Sync,
|
|
19
|
-
classifyShellPostToolPolicy,
|
|
20
|
-
getDefaultToolLogsDbPath
|
|
21
|
-
} from '../storage/fts5-archive.mjs';
|
|
22
|
-
import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
|
|
23
|
-
import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
|
|
24
|
-
|
|
25
|
-
|
|
26
|
-
export const
|
|
27
|
-
export const
|
|
28
|
-
export const
|
|
29
|
-
export const
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
37
|
-
|
|
38
|
-
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
|
|
43
|
-
|
|
44
|
-
|
|
45
|
-
|
|
46
|
-
|
|
47
|
-
const
|
|
48
|
-
|
|
49
|
-
|
|
50
|
-
const
|
|
51
|
-
|
|
52
|
-
|
|
53
|
-
|
|
54
|
-
|
|
55
|
-
const
|
|
56
|
-
const
|
|
57
|
-
|
|
58
|
-
|
|
59
|
-
|
|
60
|
-
|
|
61
|
-
|
|
62
|
-
|
|
63
|
-
|
|
64
|
-
|
|
65
|
-
|
|
66
|
-
|
|
67
|
-
|
|
68
|
-
.
|
|
69
|
-
|
|
70
|
-
|
|
71
|
-
|
|
72
|
-
|
|
73
|
-
|
|
74
|
-
if (
|
|
75
|
-
|
|
76
|
-
|
|
77
|
-
|
|
78
|
-
.
|
|
79
|
-
.
|
|
80
|
-
|
|
81
|
-
|
|
82
|
-
|
|
83
|
-
|
|
84
|
-
|
|
85
|
-
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
resp[arrKey]
|
|
89
|
-
resp[arrKey].
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
|
|
94
|
-
|
|
95
|
-
|
|
96
|
-
|
|
97
|
-
|
|
98
|
-
|
|
99
|
-
|
|
100
|
-
|
|
101
|
-
*
|
|
102
|
-
|
|
103
|
-
|
|
104
|
-
|
|
105
|
-
|
|
106
|
-
if (
|
|
107
|
-
|
|
108
|
-
|
|
109
|
-
const
|
|
110
|
-
|
|
111
|
-
|
|
112
|
-
|
|
113
|
-
|
|
114
|
-
|
|
115
|
-
const
|
|
116
|
-
|
|
117
|
-
|
|
118
|
-
|
|
119
|
-
|
|
120
|
-
|
|
121
|
-
|
|
122
|
-
|
|
123
|
-
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
const
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
132
|
-
|
|
133
|
-
.
|
|
134
|
-
.
|
|
135
|
-
|
|
136
|
-
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
}
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
|
|
154
|
-
|
|
155
|
-
|
|
156
|
-
|
|
157
|
-
|
|
158
|
-
|
|
159
|
-
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
165
|
-
|
|
166
|
-
|
|
167
|
-
event.
|
|
168
|
-
event.
|
|
169
|
-
|
|
170
|
-
(
|
|
171
|
-
(typeof event.
|
|
172
|
-
|
|
173
|
-
|
|
174
|
-
|
|
175
|
-
|
|
176
|
-
|
|
177
|
-
|
|
178
|
-
|
|
179
|
-
resp.
|
|
180
|
-
resp.
|
|
181
|
-
resp.
|
|
182
|
-
resp.status === '
|
|
183
|
-
|
|
184
|
-
(
|
|
185
|
-
(typeof resp.
|
|
186
|
-
(typeof resp.
|
|
187
|
-
|
|
188
|
-
|
|
189
|
-
|
|
190
|
-
|
|
191
|
-
|
|
192
|
-
|
|
193
|
-
|
|
194
|
-
|
|
195
|
-
|
|
196
|
-
|
|
197
|
-
|
|
198
|
-
|
|
199
|
-
|
|
200
|
-
|
|
201
|
-
|
|
202
|
-
|
|
203
|
-
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
208
|
-
|
|
209
|
-
|
|
210
|
-
|
|
211
|
-
|
|
212
|
-
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
if (envRaw === '
|
|
217
|
-
if (envRaw === '
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
if (cfgMode === '
|
|
221
|
-
return 'auto';
|
|
222
|
-
|
|
223
|
-
|
|
224
|
-
|
|
225
|
-
|
|
226
|
-
|
|
227
|
-
|
|
228
|
-
|
|
229
|
-
|
|
230
|
-
|
|
231
|
-
|
|
232
|
-
|
|
233
|
-
|
|
234
|
-
|
|
235
|
-
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
239
|
-
|
|
240
|
-
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
247
|
-
|
|
248
|
-
|
|
249
|
-
|
|
250
|
-
|
|
251
|
-
|
|
252
|
-
|
|
253
|
-
|
|
254
|
-
|
|
255
|
-
|
|
256
|
-
|
|
257
|
-
|
|
258
|
-
|
|
259
|
-
|
|
260
|
-
|
|
261
|
-
|
|
262
|
-
|
|
263
|
-
|
|
264
|
-
let
|
|
265
|
-
let
|
|
266
|
-
let
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
if (
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
280
|
-
|
|
281
|
-
|
|
282
|
-
|
|
283
|
-
}
|
|
284
|
-
|
|
285
|
-
|
|
286
|
-
|
|
287
|
-
|
|
288
|
-
|
|
289
|
-
|
|
290
|
-
|
|
291
|
-
|
|
292
|
-
|
|
293
|
-
|
|
294
|
-
|
|
295
|
-
|
|
296
|
-
|
|
297
|
-
let
|
|
298
|
-
|
|
299
|
-
|
|
300
|
-
if (
|
|
301
|
-
|
|
302
|
-
ent.name
|
|
303
|
-
ent.name.startsWith('
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
307
|
-
|
|
308
|
-
|
|
309
|
-
|
|
310
|
-
|
|
311
|
-
|
|
312
|
-
|
|
313
|
-
|
|
314
|
-
|
|
315
|
-
|
|
316
|
-
|
|
317
|
-
|
|
318
|
-
|
|
319
|
-
|
|
320
|
-
}
|
|
321
|
-
|
|
322
|
-
|
|
323
|
-
|
|
324
|
-
|
|
325
|
-
|
|
326
|
-
|
|
327
|
-
|
|
328
|
-
|
|
329
|
-
|
|
330
|
-
|
|
331
|
-
|
|
332
|
-
|
|
333
|
-
|
|
334
|
-
|
|
335
|
-
const
|
|
336
|
-
const
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
const
|
|
342
|
-
|
|
343
|
-
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
|
|
354
|
-
|
|
355
|
-
|
|
356
|
-
|
|
357
|
-
|
|
358
|
-
|
|
359
|
-
|
|
360
|
-
|
|
361
|
-
|
|
362
|
-
const
|
|
363
|
-
const
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
const
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
|
|
382
|
-
|
|
383
|
-
|
|
384
|
-
}
|
|
385
|
-
|
|
386
|
-
|
|
387
|
-
|
|
388
|
-
|
|
389
|
-
|
|
390
|
-
|
|
391
|
-
|
|
392
|
-
|
|
393
|
-
|
|
394
|
-
|
|
395
|
-
const
|
|
396
|
-
|
|
397
|
-
|
|
398
|
-
'
|
|
399
|
-
'
|
|
400
|
-
|
|
401
|
-
|
|
402
|
-
|
|
403
|
-
|
|
404
|
-
|
|
405
|
-
|
|
406
|
-
|
|
407
|
-
|
|
408
|
-
|
|
409
|
-
|
|
410
|
-
|
|
411
|
-
|
|
412
|
-
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
|
|
416
|
-
const
|
|
417
|
-
const
|
|
418
|
-
const
|
|
419
|
-
const
|
|
420
|
-
|
|
421
|
-
`
|
|
422
|
-
|
|
423
|
-
|
|
424
|
-
|
|
425
|
-
|
|
426
|
-
|
|
427
|
-
|
|
428
|
-
|
|
429
|
-
|
|
430
|
-
|
|
431
|
-
|
|
432
|
-
|
|
433
|
-
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
}
|
|
438
|
-
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
|
|
449
|
-
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
continue;
|
|
457
|
-
}
|
|
458
|
-
if (
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
filteredLines.push(
|
|
466
|
-
}
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
|
|
475
|
-
|
|
476
|
-
|
|
477
|
-
|
|
478
|
-
|
|
479
|
-
|
|
480
|
-
|
|
481
|
-
|
|
482
|
-
|
|
483
|
-
|
|
484
|
-
|
|
485
|
-
|
|
486
|
-
|
|
487
|
-
|
|
488
|
-
|
|
489
|
-
|
|
490
|
-
|
|
491
|
-
|
|
492
|
-
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
|
|
499
|
-
|
|
500
|
-
|
|
501
|
-
|
|
502
|
-
|
|
503
|
-
|
|
504
|
-
|
|
505
|
-
|
|
506
|
-
|
|
507
|
-
|
|
508
|
-
|
|
509
|
-
|
|
510
|
-
}
|
|
511
|
-
|
|
512
|
-
|
|
513
|
-
|
|
514
|
-
|
|
515
|
-
|
|
516
|
-
|
|
517
|
-
|
|
518
|
-
|
|
519
|
-
|
|
520
|
-
|
|
521
|
-
|
|
522
|
-
|
|
523
|
-
|
|
524
|
-
|
|
525
|
-
|
|
526
|
-
|
|
527
|
-
|
|
528
|
-
|
|
529
|
-
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
|
|
538
|
-
|
|
539
|
-
|
|
540
|
-
|
|
541
|
-
|
|
542
|
-
|
|
543
|
-
|
|
544
|
-
|
|
545
|
-
|
|
546
|
-
|
|
547
|
-
|
|
548
|
-
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
|
|
552
|
-
|
|
553
|
-
|
|
554
|
-
|
|
555
|
-
|
|
556
|
-
|
|
557
|
-
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
const
|
|
563
|
-
|
|
564
|
-
);
|
|
565
|
-
const
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
|
|
570
|
-
|
|
571
|
-
|
|
572
|
-
|
|
573
|
-
|
|
574
|
-
|
|
575
|
-
|
|
576
|
-
|
|
577
|
-
|
|
578
|
-
|
|
579
|
-
|
|
580
|
-
|
|
581
|
-
|
|
582
|
-
|
|
583
|
-
|
|
584
|
-
|
|
585
|
-
|
|
586
|
-
|
|
587
|
-
|
|
588
|
-
|
|
589
|
-
|
|
590
|
-
|
|
591
|
-
|
|
592
|
-
|
|
593
|
-
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
|
|
598
|
-
|
|
599
|
-
|
|
600
|
-
|
|
601
|
-
|
|
602
|
-
|
|
603
|
-
|
|
604
|
-
|
|
605
|
-
|
|
606
|
-
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
|
|
611
|
-
|
|
612
|
-
|
|
613
|
-
|
|
614
|
-
|
|
615
|
-
|
|
616
|
-
|
|
617
|
-
|
|
618
|
-
|
|
619
|
-
|
|
620
|
-
|
|
621
|
-
|
|
622
|
-
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
|
|
629
|
-
|
|
630
|
-
|
|
631
|
-
|
|
632
|
-
|
|
633
|
-
|
|
634
|
-
|
|
635
|
-
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
|
|
640
|
-
|
|
641
|
-
|
|
642
|
-
|
|
643
|
-
|
|
644
|
-
if (
|
|
645
|
-
return {
|
|
646
|
-
exitCode: 0,
|
|
647
|
-
stdout: '',
|
|
648
|
-
stderr: '',
|
|
649
|
-
|
|
650
|
-
|
|
651
|
-
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
655
|
-
if (
|
|
656
|
-
|
|
657
|
-
|
|
658
|
-
|
|
659
|
-
|
|
660
|
-
|
|
661
|
-
|
|
662
|
-
|
|
663
|
-
|
|
664
|
-
|
|
665
|
-
|
|
666
|
-
|
|
667
|
-
|
|
668
|
-
|
|
669
|
-
|
|
670
|
-
|
|
671
|
-
|
|
672
|
-
|
|
673
|
-
|
|
674
|
-
|
|
675
|
-
|
|
676
|
-
|
|
677
|
-
|
|
678
|
-
|
|
679
|
-
|
|
680
|
-
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
688
|
-
|
|
689
|
-
|
|
690
|
-
|
|
691
|
-
|
|
692
|
-
|
|
693
|
-
|
|
694
|
-
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
698
|
-
|
|
699
|
-
|
|
700
|
-
|
|
701
|
-
|
|
702
|
-
|
|
703
|
-
|
|
704
|
-
|
|
705
|
-
|
|
706
|
-
|
|
707
|
-
|
|
708
|
-
|
|
709
|
-
|
|
710
|
-
|
|
711
|
-
|
|
712
|
-
|
|
713
|
-
|
|
714
|
-
|
|
715
|
-
|
|
716
|
-
|
|
717
|
-
|
|
718
|
-
|
|
719
|
-
|
|
720
|
-
|
|
721
|
-
|
|
722
|
-
|
|
723
|
-
|
|
724
|
-
|
|
725
|
-
|
|
726
|
-
|
|
727
|
-
|
|
728
|
-
|
|
729
|
-
|
|
730
|
-
|
|
731
|
-
|
|
732
|
-
|
|
733
|
-
|
|
734
|
-
|
|
735
|
-
|
|
736
|
-
|
|
737
|
-
|
|
738
|
-
|
|
739
|
-
|
|
740
|
-
|
|
741
|
-
|
|
742
|
-
|
|
743
|
-
|
|
744
|
-
|
|
745
|
-
|
|
746
|
-
|
|
747
|
-
|
|
748
|
-
|
|
749
|
-
|
|
750
|
-
|
|
751
|
-
|
|
752
|
-
|
|
753
|
-
|
|
754
|
-
|
|
755
|
-
|
|
756
|
-
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
|
|
767
|
-
|
|
768
|
-
|
|
769
|
-
|
|
770
|
-
|
|
771
|
-
|
|
772
|
-
|
|
773
|
-
|
|
774
|
-
|
|
775
|
-
|
|
776
|
-
|
|
777
|
-
|
|
778
|
-
|
|
779
|
-
|
|
780
|
-
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
|
|
784
|
-
|
|
785
|
-
|
|
786
|
-
|
|
787
|
-
|
|
788
|
-
|
|
789
|
-
|
|
790
|
-
|
|
791
|
-
|
|
792
|
-
|
|
793
|
-
|
|
794
|
-
|
|
795
|
-
|
|
796
|
-
|
|
797
|
-
|
|
798
|
-
|
|
799
|
-
|
|
800
|
-
|
|
801
|
-
|
|
802
|
-
|
|
803
|
-
|
|
804
|
-
|
|
805
|
-
|
|
806
|
-
|
|
807
|
-
|
|
808
|
-
|
|
809
|
-
|
|
810
|
-
|
|
811
|
-
|
|
812
|
-
|
|
813
|
-
|
|
814
|
-
|
|
815
|
-
|
|
816
|
-
|
|
817
|
-
|
|
818
|
-
|
|
819
|
-
|
|
820
|
-
|
|
821
|
-
|
|
822
|
-
|
|
823
|
-
|
|
824
|
-
|
|
825
|
-
|
|
826
|
-
|
|
827
|
-
|
|
828
|
-
|
|
829
|
-
|
|
830
|
-
|
|
831
|
-
|
|
832
|
-
|
|
833
|
-
|
|
834
|
-
|
|
835
|
-
|
|
836
|
-
|
|
837
|
-
|
|
838
|
-
|
|
839
|
-
|
|
840
|
-
|
|
841
|
-
|
|
842
|
-
|
|
843
|
-
|
|
844
|
-
|
|
845
|
-
|
|
846
|
-
|
|
847
|
-
|
|
848
|
-
|
|
849
|
-
|
|
850
|
-
|
|
851
|
-
|
|
852
|
-
|
|
853
|
-
|
|
854
|
-
|
|
1
|
+
/**
|
|
2
|
+
* @file src/guards/post-tool-engine.mjs
|
|
3
|
+
* Pure ESM orchestrator for Claude Code `PostToolUse` evaluation.
|
|
4
|
+
* Atomically updates `DET-04` failure counters and `git stash` timestamps, strips ANSI/spinners,
|
|
5
|
+
* compresses eligible CLI logs via SQLite FTS5 (`npx burnoff search`), offloads >4,000-token blobs
|
|
6
|
+
* while preserving 100% of critical error lines, and replaces tool outputs in native host shapes.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
import fs from 'node:fs';
|
|
10
|
+
import path from 'node:path';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { getClientAdapter, normalizeHookEvent } from '../clients/detect.mjs';
|
|
13
|
+
import { loadBurnoffPolicy } from '../config/policy.mjs';
|
|
14
|
+
import { getBurnoffCacheDir, getHomeDir } from '../config/paths.mjs';
|
|
15
|
+
import { computeTotalPromptTokens, resolveEffectiveRates } from '../config/loader.mjs';
|
|
16
|
+
import { atomicWriteFileSync } from '../storage/atomic-io.mjs';
|
|
17
|
+
import {
|
|
18
|
+
compressCliOutputFts5Sync,
|
|
19
|
+
classifyShellPostToolPolicy,
|
|
20
|
+
getDefaultToolLogsDbPath
|
|
21
|
+
} from '../storage/fts5-archive.mjs';
|
|
22
|
+
import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
|
|
23
|
+
import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
|
|
24
|
+
import { redactSecretsPure } from './credential-scrubber.mjs';
|
|
25
|
+
|
|
26
|
+
export const OFFLOAD_TOKEN_THRESHOLD = 4000;
|
|
27
|
+
export const CHARS_PER_TOKEN_ESTIMATE = 4;
|
|
28
|
+
export const DEFAULT_ARTIFACT_MAX_FILES = 200;
|
|
29
|
+
export const DEFAULT_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
|
|
30
|
+
export const OPPORTUNISTIC_GC_INTERVAL_MS = 24 * 60 * 60 * 1000;
|
|
31
|
+
|
|
32
|
+
export const CRITICAL_ERROR_REGEX =
|
|
33
|
+
/(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
|
|
34
|
+
|
|
35
|
+
const ANSI_CSI_OSC_REGEX =
|
|
36
|
+
/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
37
|
+
|
|
38
|
+
const DOWNLOAD_NOISE_LINE_REGEX =
|
|
39
|
+
/^\s*(?:npm\s+(?:http|verb|silly|timing|notice)\b|Progress:\s+resolved\s+\d+|Downloading\s+\S+\s+\[[=#>-]+\s*\]|\d+%\s+\[[=#>-]+\s*\]|Receiving objects:\s+\d+%|Resolving deltas:\s+\d+%)/i;
|
|
40
|
+
|
|
41
|
+
const PASSING_TEST_LINE_REGEX =
|
|
42
|
+
/^\s*(?:✔|✓|PASS\s+\S+|ok\s+\d+\s+-\s+)/;
|
|
43
|
+
|
|
44
|
+
const HTML_BOILERPLATE_BLOCK_REGEX =
|
|
45
|
+
/<(nav|footer|script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi;
|
|
46
|
+
|
|
47
|
+
const SHELL_TOOL_NAME_RE = /^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash)$/i;
|
|
48
|
+
const PROTECTED_WORKSPACE_TOOL_RE =
|
|
49
|
+
/^(?:Read|read_file|view_file|View|Edit|edit_file|Write|write_file|replace_file_content|MultiEdit|NotebookEdit)$/i;
|
|
50
|
+
const EDIT_WRITE_SCOPE_LOCK_REGEX = /^(?:Edit|Write|MultiEdit|NotebookEdit)$/i;
|
|
51
|
+
const ELIGIBLE_POST_TOOL_RE =
|
|
52
|
+
/^(?:Bash|PowerShell|pwsh|cmd|sh|run_command|execute_bash|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i;
|
|
53
|
+
|
|
54
|
+
export function stripAnsiAndSpinners(rawText = '') {
|
|
55
|
+
const withoutAnsi = String(rawText || '').replace(ANSI_CSI_OSC_REGEX, '');
|
|
56
|
+
const lines = withoutAnsi.split(/\n/);
|
|
57
|
+
const resolvedLines = lines.map((line) => {
|
|
58
|
+
const trimmedCr = line.replace(/\r$/, '');
|
|
59
|
+
if (!trimmedCr.includes('\r')) return trimmedCr;
|
|
60
|
+
const segments = trimmedCr.split('\r').filter((seg) => seg.trim().length > 0);
|
|
61
|
+
return segments.length > 0 ? segments[segments.length - 1] : '';
|
|
62
|
+
});
|
|
63
|
+
return resolvedLines.join('\n');
|
|
64
|
+
}
|
|
65
|
+
|
|
66
|
+
export function extractCriticalErrorLines(cleanText = '') {
|
|
67
|
+
return String(cleanText || '')
|
|
68
|
+
.split(/\r?\n/)
|
|
69
|
+
.filter((line) => CRITICAL_ERROR_REGEX.test(line));
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
export function extractPostToolText(event = {}) {
|
|
73
|
+
const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
|
|
74
|
+
if (typeof resp === 'string') return resp;
|
|
75
|
+
if (resp && typeof resp === 'object') {
|
|
76
|
+
if (Array.isArray(resp.content)) {
|
|
77
|
+
const blockText = resp.content
|
|
78
|
+
.filter((b) => b && b.type === 'text' && typeof b.text === 'string' && b.text.length > 0)
|
|
79
|
+
.map((b) => b.text)
|
|
80
|
+
.join('\n');
|
|
81
|
+
if (blockText.length > 0) return blockText;
|
|
82
|
+
}
|
|
83
|
+
const parts = [resp.stdout, resp.stderr, resp.output, resp.content, resp.result, resp.error]
|
|
84
|
+
.filter((x) => typeof x === 'string' && x.length > 0);
|
|
85
|
+
if (parts.length > 0) return parts.join('\n');
|
|
86
|
+
for (const arrKey of ['filenames', 'files']) {
|
|
87
|
+
if (
|
|
88
|
+
Array.isArray(resp[arrKey]) &&
|
|
89
|
+
resp[arrKey].length > 0 &&
|
|
90
|
+
resp[arrKey].every((item) => typeof item === 'string')
|
|
91
|
+
) {
|
|
92
|
+
return resp[arrKey].join('\n');
|
|
93
|
+
}
|
|
94
|
+
}
|
|
95
|
+
return '';
|
|
96
|
+
}
|
|
97
|
+
return resp !== undefined && resp !== null ? String(resp) : '';
|
|
98
|
+
}
|
|
99
|
+
|
|
100
|
+
/**
|
|
101
|
+
* Builds a replacement `tool_response` in the exact shape the host sent (`updatedToolOutput`).
|
|
102
|
+
* Returns `{ ok: false }` for unrecognized object shapes so no phantom savings are recorded.
|
|
103
|
+
*/
|
|
104
|
+
export function buildReplacementToolOutput(event = {}, finalOutput = '') {
|
|
105
|
+
const resp = event.tool_response ?? event.tool_output ?? event.toolOutput ?? event.output;
|
|
106
|
+
if (typeof resp === 'string') return { ok: true, value: finalOutput };
|
|
107
|
+
if (resp && typeof resp === 'object' && !Array.isArray(resp)) {
|
|
108
|
+
if (Array.isArray(resp.content)) {
|
|
109
|
+
const hasTextBlock = resp.content.some((b) => b && b.type === 'text' && typeof b.text === 'string');
|
|
110
|
+
const hasNonTextBlock = resp.content.some((b) => !b || b.type !== 'text');
|
|
111
|
+
if (hasTextBlock && !hasNonTextBlock) {
|
|
112
|
+
return { ok: true, value: { ...resp, content: [{ type: 'text', text: finalOutput }] } };
|
|
113
|
+
}
|
|
114
|
+
}
|
|
115
|
+
const textKeys = ['stdout', 'output', 'content', 'result', 'error', 'stderr'];
|
|
116
|
+
const primary = textKeys.find((k) => typeof resp[k] === 'string' && resp[k].length > 0);
|
|
117
|
+
if (primary) {
|
|
118
|
+
const next = { ...resp };
|
|
119
|
+
for (const k of textKeys) {
|
|
120
|
+
if (typeof next[k] === 'string') next[k] = k === primary ? finalOutput : '';
|
|
121
|
+
}
|
|
122
|
+
if (primary === 'content' && typeof next.numLines === 'number') {
|
|
123
|
+
next.numLines = finalOutput ? String(finalOutput).split(/\r?\n/).length : 0;
|
|
124
|
+
}
|
|
125
|
+
return { ok: true, value: next };
|
|
126
|
+
}
|
|
127
|
+
const arrayKeys = ['filenames', 'files'];
|
|
128
|
+
const primaryArr = arrayKeys.find(
|
|
129
|
+
(k) => Array.isArray(resp[k]) && resp[k].length > 0 && resp[k].every((item) => typeof item === 'string')
|
|
130
|
+
);
|
|
131
|
+
if (primaryArr) {
|
|
132
|
+
const nextItems = String(finalOutput || '')
|
|
133
|
+
.split(/\r?\n/)
|
|
134
|
+
.map((line) => line.trimEnd())
|
|
135
|
+
.filter((line) => line.length > 0);
|
|
136
|
+
const next = { ...resp, [primaryArr]: nextItems };
|
|
137
|
+
if (typeof next.numFiles === 'number') {
|
|
138
|
+
const pathCount = nextItems.filter((line) => !/^\[/.test(line.trim())).length;
|
|
139
|
+
next.numFiles = pathCount > 0 ? pathCount : nextItems.length;
|
|
140
|
+
}
|
|
141
|
+
if (typeof next.truncated === 'boolean') {
|
|
142
|
+
next.truncated = true;
|
|
143
|
+
}
|
|
144
|
+
return { ok: true, value: next };
|
|
145
|
+
}
|
|
146
|
+
return { ok: false };
|
|
147
|
+
}
|
|
148
|
+
return { ok: false };
|
|
149
|
+
}
|
|
150
|
+
|
|
151
|
+
function resolveHostShellOutputCap() {
|
|
152
|
+
const n = Number(globalThis.process?.env?.BASH_MAX_OUTPUT_LENGTH);
|
|
153
|
+
return Number.isFinite(n) && n > 0 ? n : 30_000;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export function isHostTruncatedShellOutput(toolName, rawOutput) {
|
|
157
|
+
if (!/^(?:Bash|PowerShell)$/i.test(String(toolName || ''))) return false;
|
|
158
|
+
return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
export function didToolExecutionFail(event = {}, toolNameHint = '') {
|
|
162
|
+
const hookEventName = String(event.hook_event_name || event.hookEventName || '');
|
|
163
|
+
if (hookEventName === 'PostToolUseFailure') {
|
|
164
|
+
return true;
|
|
165
|
+
}
|
|
166
|
+
if (
|
|
167
|
+
event.is_error === true ||
|
|
168
|
+
event.isError === true ||
|
|
169
|
+
event.succeeded === false ||
|
|
170
|
+
Boolean(event.tool_error || event.error) ||
|
|
171
|
+
(typeof event.exit_code === 'number' && event.exit_code !== 0) ||
|
|
172
|
+
(typeof event.exitCode === 'number' && event.exitCode !== 0)
|
|
173
|
+
) {
|
|
174
|
+
return true;
|
|
175
|
+
}
|
|
176
|
+
const resp = event.tool_response;
|
|
177
|
+
if (resp && typeof resp === 'object') {
|
|
178
|
+
if (
|
|
179
|
+
resp.is_error === true ||
|
|
180
|
+
resp.isError === true ||
|
|
181
|
+
resp.succeeded === false ||
|
|
182
|
+
resp.status === 'error' ||
|
|
183
|
+
resp.status === 'failed' ||
|
|
184
|
+
Boolean(resp.error) ||
|
|
185
|
+
(typeof resp.exit_code === 'number' && resp.exit_code !== 0) ||
|
|
186
|
+
(typeof resp.exitCode === 'number' && resp.exitCode !== 0) ||
|
|
187
|
+
(typeof resp.returncode === 'number' && resp.returncode !== 0)
|
|
188
|
+
) {
|
|
189
|
+
return true;
|
|
190
|
+
}
|
|
191
|
+
}
|
|
192
|
+
|
|
193
|
+
const rawTool = String(
|
|
194
|
+
toolNameHint || event.tool_name || event.toolName || event.toolCall?.name || event.name || ''
|
|
195
|
+
).trim();
|
|
196
|
+
const isShellLike =
|
|
197
|
+
!rawTool || SHELL_TOOL_NAME_RE.test(rawTool) || /^(?:Shell|Command)$/i.test(rawTool);
|
|
198
|
+
if (isShellLike) {
|
|
199
|
+
const rawText = stripAnsiAndSpinners(extractPostToolText(event));
|
|
200
|
+
if (rawText) {
|
|
201
|
+
const exitMarkerRe =
|
|
202
|
+
/(?:^|\r?\n)\s*(?:exit\s+(?:code|status)|command\s+exited\s+with\s+(?:code|status)|process\s+exited\s+with\s+(?:code|status)|returned\s+non-zero\s+exit\s+status)\s*[:=]?\s*(-?\d+)\b/gim;
|
|
203
|
+
for (const m of rawText.matchAll(exitMarkerRe)) {
|
|
204
|
+
const code = Number(m[1]);
|
|
205
|
+
if (Number.isFinite(code) && code !== 0) {
|
|
206
|
+
return true;
|
|
207
|
+
}
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
}
|
|
211
|
+
return false;
|
|
212
|
+
}
|
|
213
|
+
|
|
214
|
+
export function resolvePostOutputMode(policyPost = {}) {
|
|
215
|
+
const envRaw = String(globalThis.process?.env?.BURNOFF_POST_OUTPUT_MODE || '').trim().toLowerCase();
|
|
216
|
+
if (envRaw === 'context' || envRaw === 'additionalcontext') return 'context';
|
|
217
|
+
if (envRaw === 'replace' || envRaw === 'updatedtooloutput') return 'replace';
|
|
218
|
+
if (envRaw === 'auto') return 'auto';
|
|
219
|
+
const cfgMode = String(policyPost.outputMode || 'replace').trim().toLowerCase();
|
|
220
|
+
if (cfgMode === 'context' || cfgMode === 'additionalcontext') return 'context';
|
|
221
|
+
if (cfgMode === 'auto') return 'auto';
|
|
222
|
+
return 'replace';
|
|
223
|
+
}
|
|
224
|
+
|
|
225
|
+
export function enforceArtifactDirCap(
|
|
226
|
+
artifactsDir,
|
|
227
|
+
{
|
|
228
|
+
maxFiles = DEFAULT_ARTIFACT_MAX_FILES,
|
|
229
|
+
maxTotalBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
|
|
230
|
+
keepPath = null
|
|
231
|
+
} = {}
|
|
232
|
+
) {
|
|
233
|
+
if (!artifactsDir || !fs.existsSync(artifactsDir)) {
|
|
234
|
+
return { removedFiles: 0, reclaimedBytes: 0 };
|
|
235
|
+
}
|
|
236
|
+
const keepAbs = keepPath ? path.resolve(keepPath) : null;
|
|
237
|
+
let entries;
|
|
238
|
+
try {
|
|
239
|
+
entries = fs.readdirSync(artifactsDir, { withFileTypes: true });
|
|
240
|
+
} catch (err) {
|
|
241
|
+
void err; // ignore: unreadable artifacts dir skips cap
|
|
242
|
+
return { removedFiles: 0, reclaimedBytes: 0 };
|
|
243
|
+
}
|
|
244
|
+
|
|
245
|
+
const files = [];
|
|
246
|
+
let totalBytes = 0;
|
|
247
|
+
for (const ent of entries) {
|
|
248
|
+
if (!ent.isFile() || !/^burnoff_.*\.txt$/i.test(ent.name)) continue;
|
|
249
|
+
const full = path.join(artifactsDir, ent.name);
|
|
250
|
+
try {
|
|
251
|
+
const st = fs.statSync(full);
|
|
252
|
+
files.push({ full, abs: path.resolve(full), mtimeMs: st.mtimeMs || 0, size: st.size || 0 });
|
|
253
|
+
totalBytes += st.size || 0;
|
|
254
|
+
} catch (err) {
|
|
255
|
+
void err; // ignore: vanished artifact entry skipped
|
|
256
|
+
}
|
|
257
|
+
}
|
|
258
|
+
|
|
259
|
+
if (files.length <= maxFiles && totalBytes <= maxTotalBytes) {
|
|
260
|
+
return { removedFiles: 0, reclaimedBytes: 0 };
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
files.sort((a, b) => a.mtimeMs - b.mtimeMs);
|
|
264
|
+
let remainingFiles = files.length;
|
|
265
|
+
let remainingBytes = totalBytes;
|
|
266
|
+
let removedFiles = 0;
|
|
267
|
+
let reclaimedBytes = 0;
|
|
268
|
+
|
|
269
|
+
for (const f of files) {
|
|
270
|
+
if (remainingFiles <= maxFiles && remainingBytes <= maxTotalBytes) break;
|
|
271
|
+
if (keepAbs && f.abs === keepAbs) continue;
|
|
272
|
+
try {
|
|
273
|
+
fs.unlinkSync(f.full);
|
|
274
|
+
remainingFiles -= 1;
|
|
275
|
+
remainingBytes -= f.size;
|
|
276
|
+
removedFiles += 1;
|
|
277
|
+
reclaimedBytes += f.size;
|
|
278
|
+
} catch (err) {
|
|
279
|
+
void err; // ignore: locked or already removed artifact
|
|
280
|
+
}
|
|
281
|
+
}
|
|
282
|
+
|
|
283
|
+
return { removedFiles, reclaimedBytes };
|
|
284
|
+
}
|
|
285
|
+
|
|
286
|
+
function reapStaleFilesInDir(dirPath, cutoffMs, skipNames = new Set()) {
|
|
287
|
+
if (!dirPath || !fs.existsSync(dirPath)) {
|
|
288
|
+
return { removedFiles: 0, reclaimedBytes: 0 };
|
|
289
|
+
}
|
|
290
|
+
let entries;
|
|
291
|
+
try {
|
|
292
|
+
entries = fs.readdirSync(dirPath, { withFileTypes: true });
|
|
293
|
+
} catch (err) {
|
|
294
|
+
void err; // ignore: unreadable cache directory
|
|
295
|
+
return { removedFiles: 0, reclaimedBytes: 0 };
|
|
296
|
+
}
|
|
297
|
+
let removedFiles = 0;
|
|
298
|
+
let reclaimedBytes = 0;
|
|
299
|
+
for (const ent of entries) {
|
|
300
|
+
if (!ent.isFile()) continue;
|
|
301
|
+
if (
|
|
302
|
+
skipNames.has(ent.name) ||
|
|
303
|
+
ent.name.startsWith('tool_logs_fts5.db') ||
|
|
304
|
+
ent.name.startsWith('tool_logs_fallback.json')
|
|
305
|
+
) {
|
|
306
|
+
continue;
|
|
307
|
+
}
|
|
308
|
+
const full = path.join(dirPath, ent.name);
|
|
309
|
+
try {
|
|
310
|
+
const st = fs.statSync(full);
|
|
311
|
+
if (st.mtimeMs < cutoffMs) {
|
|
312
|
+
fs.unlinkSync(full);
|
|
313
|
+
removedFiles += 1;
|
|
314
|
+
reclaimedBytes += st.size;
|
|
315
|
+
}
|
|
316
|
+
} catch (err) {
|
|
317
|
+
void err; // ignore: locked or concurrently unlinked cache file
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
return { removedFiles, reclaimedBytes };
|
|
321
|
+
}
|
|
322
|
+
|
|
323
|
+
/**
|
|
324
|
+
* Throttled (<= 1x per 24h) cache reap, artifact cap enforcement, and monthly ledger rotation.
|
|
325
|
+
*/
|
|
326
|
+
export function runOpportunisticPostToolGc({
|
|
327
|
+
baseCwd = null,
|
|
328
|
+
homeDir = null,
|
|
329
|
+
maxCacheAgeDays = 14,
|
|
330
|
+
nowMs = Date.now(),
|
|
331
|
+
force = false,
|
|
332
|
+
artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES,
|
|
333
|
+
artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES
|
|
334
|
+
} = {}) {
|
|
335
|
+
const cacheDir = getBurnoffCacheDir(homeDir);
|
|
336
|
+
const stampPath = path.join(cacheDir, 'burnoff_last_gc.json');
|
|
337
|
+
const skipNames = new Set(['burnoff_last_gc.json']);
|
|
338
|
+
|
|
339
|
+
if (!force && fs.existsSync(stampPath)) {
|
|
340
|
+
try {
|
|
341
|
+
const raw = JSON.parse(fs.readFileSync(stampPath, 'utf8'));
|
|
342
|
+
const lastGcMs = Number(raw?.lastGcMs || 0);
|
|
343
|
+
if (lastGcMs > 0 && nowMs - lastGcMs < OPPORTUNISTIC_GC_INTERVAL_MS) {
|
|
344
|
+
return { skipped: true, reason: 'throttled_24h', lastGcMs };
|
|
345
|
+
}
|
|
346
|
+
} catch (err) {
|
|
347
|
+
void err; // ignore: corrupt stamp file falls through to run GC
|
|
348
|
+
}
|
|
349
|
+
}
|
|
350
|
+
|
|
351
|
+
try {
|
|
352
|
+
fs.mkdirSync(cacheDir, { recursive: true });
|
|
353
|
+
atomicWriteFileSync(stampPath, JSON.stringify({ lastGcMs: nowMs }) + '\n', {
|
|
354
|
+
encoding: 'utf8',
|
|
355
|
+
mode: 0o600,
|
|
356
|
+
dirMode: 0o700
|
|
357
|
+
});
|
|
358
|
+
} catch (err) {
|
|
359
|
+
void err; // ignore: stamp write error does not fail hook
|
|
360
|
+
}
|
|
361
|
+
|
|
362
|
+
const cutoffMs = nowMs - Math.max(1, Number(maxCacheAgeDays || 14)) * 24 * 60 * 60 * 1000;
|
|
363
|
+
const homeReap = reapStaleFilesInDir(cacheDir, cutoffMs, skipNames);
|
|
364
|
+
const wsCacheReap = baseCwd
|
|
365
|
+
? reapStaleFilesInDir(path.join(baseCwd, '.claude', 'cache'), cutoffMs, skipNames)
|
|
366
|
+
: { removedFiles: 0, reclaimedBytes: 0 };
|
|
367
|
+
const artifactsDir = baseCwd ? path.join(baseCwd, '.claude', 'cache', 'artifacts') : null;
|
|
368
|
+
const wsArtifactsReap = artifactsDir
|
|
369
|
+
? reapStaleFilesInDir(artifactsDir, cutoffMs, skipNames)
|
|
370
|
+
: { removedFiles: 0, reclaimedBytes: 0 };
|
|
371
|
+
const cappedArtifacts = artifactsDir
|
|
372
|
+
? enforceArtifactDirCap(artifactsDir, { maxFiles: artifactMaxFiles, maxTotalBytes: artifactMaxBytes })
|
|
373
|
+
: { removedFiles: 0, reclaimedBytes: 0 };
|
|
374
|
+
const ledgerRotation = rotateMonthlyLedger({ homeDir, nowMs });
|
|
375
|
+
|
|
376
|
+
return {
|
|
377
|
+
skipped: false,
|
|
378
|
+
lastGcMs: nowMs,
|
|
379
|
+
reapedFiles: homeReap.removedFiles + wsCacheReap.removedFiles + wsArtifactsReap.removedFiles,
|
|
380
|
+
reclaimedBytes:
|
|
381
|
+
homeReap.reclaimedBytes + wsCacheReap.reclaimedBytes + wsArtifactsReap.reclaimedBytes + cappedArtifacts.reclaimedBytes,
|
|
382
|
+
cappedArtifacts,
|
|
383
|
+
ledgerRotation
|
|
384
|
+
};
|
|
385
|
+
}
|
|
386
|
+
|
|
387
|
+
function offloadOversizedOutput(
|
|
388
|
+
toolName,
|
|
389
|
+
cleanText,
|
|
390
|
+
filteredLines,
|
|
391
|
+
criticalErrorLines,
|
|
392
|
+
baseCwd,
|
|
393
|
+
{ artifactMaxFiles = DEFAULT_ARTIFACT_MAX_FILES, artifactMaxBytes = DEFAULT_ARTIFACT_MAX_TOTAL_BYTES } = {}
|
|
394
|
+
) {
|
|
395
|
+
const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
|
|
396
|
+
const candidateArtifactPath = path.join(
|
|
397
|
+
baseCwd,
|
|
398
|
+
'.claude',
|
|
399
|
+
'cache',
|
|
400
|
+
'artifacts',
|
|
401
|
+
`burnoff_${sha256}.txt`
|
|
402
|
+
);
|
|
403
|
+
|
|
404
|
+
try {
|
|
405
|
+
atomicWriteFileSync(candidateArtifactPath, cleanText, { encoding: 'utf8', mode: 0o600, dirMode: 0o700 });
|
|
406
|
+
enforceArtifactDirCap(path.dirname(candidateArtifactPath), {
|
|
407
|
+
maxFiles: artifactMaxFiles,
|
|
408
|
+
maxTotalBytes: artifactMaxBytes,
|
|
409
|
+
keepPath: candidateArtifactPath
|
|
410
|
+
});
|
|
411
|
+
} catch (err) {
|
|
412
|
+
void err; // ignore: fail-open offload preserves ANSI-cleaned output in memory
|
|
413
|
+
return { offloaded: false, artifactPath: null, output: cleanText };
|
|
414
|
+
}
|
|
415
|
+
|
|
416
|
+
const originalTokens = Math.ceil(cleanText.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
417
|
+
const rawLines = cleanText.split(/\n/);
|
|
418
|
+
const nonEmpty = filteredLines.filter((l) => l.trim().length > 0);
|
|
419
|
+
const sampleLines = nonEmpty.slice(0, 3);
|
|
420
|
+
const summaryParts = [
|
|
421
|
+
`[Burnoff Artifact Offload: ${originalTokens.toLocaleString('en-US')} tokens (${rawLines.length} lines) archived locally]`,
|
|
422
|
+
`Sample lines (1..${sampleLines.length}):`,
|
|
423
|
+
...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
|
|
424
|
+
];
|
|
425
|
+
|
|
426
|
+
if (criticalErrorLines.length > 0) {
|
|
427
|
+
summaryParts.push(`Critical Error / Failure Lines Preserved Verbatim (${criticalErrorLines.length}):`);
|
|
428
|
+
for (const errLine of criticalErrorLines) {
|
|
429
|
+
summaryParts.push(` ${errLine}`);
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
|
|
433
|
+
return {
|
|
434
|
+
offloaded: true,
|
|
435
|
+
artifactPath: candidateArtifactPath,
|
|
436
|
+
output: summaryParts.join('\n')
|
|
437
|
+
};
|
|
438
|
+
}
|
|
439
|
+
|
|
440
|
+
function sanitizePostOutputFallback(toolName, rawOutput, { baseCwd, allowOffload, offloadThresholdTokens }) {
|
|
441
|
+
const originalTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
442
|
+
const scrubbedInit = redactSecretsPure(stripAnsiAndSpinners(rawOutput));
|
|
443
|
+
let cleaned = scrubbedInit.sanitized;
|
|
444
|
+
let redactedSecrets = scrubbedInit.redactedCount;
|
|
445
|
+
if (/^WebFetch$/i.test(toolName)) {
|
|
446
|
+
cleaned = cleaned.replace(HTML_BOILERPLATE_BLOCK_REGEX, '');
|
|
447
|
+
}
|
|
448
|
+
const criticalErrorLines = extractCriticalErrorLines(cleaned);
|
|
449
|
+
const rawLines = cleaned.split(/\n/);
|
|
450
|
+
const filteredLines = [];
|
|
451
|
+
let strippedPassingTests = 0;
|
|
452
|
+
|
|
453
|
+
for (const line of rawLines) {
|
|
454
|
+
if (CRITICAL_ERROR_REGEX.test(line)) {
|
|
455
|
+
filteredLines.push(line);
|
|
456
|
+
continue;
|
|
457
|
+
}
|
|
458
|
+
if (DOWNLOAD_NOISE_LINE_REGEX.test(line)) {
|
|
459
|
+
continue;
|
|
460
|
+
}
|
|
461
|
+
if (PASSING_TEST_LINE_REGEX.test(line) && rawLines.length > 10) {
|
|
462
|
+
strippedPassingTests += 1;
|
|
463
|
+
continue;
|
|
464
|
+
}
|
|
465
|
+
filteredLines.push(line);
|
|
466
|
+
}
|
|
467
|
+
if (strippedPassingTests > 0) {
|
|
468
|
+
filteredLines.push(`[... ${strippedPassingTests} passing test lines compacted by Burnoff ...]`);
|
|
469
|
+
}
|
|
470
|
+
|
|
471
|
+
let sanitizedText = filteredLines.join('\n');
|
|
472
|
+
for (const errLine of criticalErrorLines) {
|
|
473
|
+
if (!sanitizedText.includes(errLine)) {
|
|
474
|
+
sanitizedText += `\n${errLine}`;
|
|
475
|
+
}
|
|
476
|
+
}
|
|
477
|
+
|
|
478
|
+
const postFilterTokens = Math.ceil(sanitizedText.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
479
|
+
let offloaded = false;
|
|
480
|
+
let artifactPath = null;
|
|
481
|
+
let finalOutput = sanitizedText;
|
|
482
|
+
|
|
483
|
+
if (allowOffload && baseCwd && (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens)) {
|
|
484
|
+
const cleanScrub = redactSecretsPure(cleaned);
|
|
485
|
+
cleaned = cleanScrub.sanitized;
|
|
486
|
+
redactedSecrets = Math.max(redactedSecrets, cleanScrub.redactedCount);
|
|
487
|
+
const offRes = offloadOversizedOutput(toolName, cleaned, filteredLines, criticalErrorLines, baseCwd);
|
|
488
|
+
offloaded = offRes.offloaded;
|
|
489
|
+
artifactPath = offRes.artifactPath;
|
|
490
|
+
finalOutput = redactSecretsPure(offRes.output).sanitized;
|
|
491
|
+
} else {
|
|
492
|
+
const finalScrub = redactSecretsPure(finalOutput);
|
|
493
|
+
finalOutput = finalScrub.sanitized;
|
|
494
|
+
redactedSecrets = Math.max(redactedSecrets, finalScrub.redactedCount);
|
|
495
|
+
}
|
|
496
|
+
|
|
497
|
+
const finalTokens = Math.ceil(finalOutput.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
498
|
+
return {
|
|
499
|
+
toolName,
|
|
500
|
+
eligible: true,
|
|
501
|
+
sanitized: finalOutput !== rawOutput,
|
|
502
|
+
offloaded,
|
|
503
|
+
artifactPath,
|
|
504
|
+
redactedSecrets,
|
|
505
|
+
originalTokens,
|
|
506
|
+
finalTokens,
|
|
507
|
+
savedTokens: Math.max(0, originalTokens - finalTokens),
|
|
508
|
+
criticalErrorsPreserved: criticalErrorLines.length,
|
|
509
|
+
updatedToolOutput: finalOutput
|
|
510
|
+
};
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function appendMissingCriticalLines(summaryText, criticalLines) {
|
|
514
|
+
if (!criticalLines || criticalLines.length === 0) return summaryText;
|
|
515
|
+
const missing = [];
|
|
516
|
+
for (const line of criticalLines) {
|
|
517
|
+
const probe = line.trim().slice(0, 140);
|
|
518
|
+
if (probe && !summaryText.includes(probe)) {
|
|
519
|
+
missing.push(line);
|
|
520
|
+
}
|
|
521
|
+
}
|
|
522
|
+
if (missing.length === 0) return summaryText;
|
|
523
|
+
return `${summaryText}\nCritical Error / Failure Lines Preserved:\n${missing.map((l) => ` ${l}`).join('\n')}`;
|
|
524
|
+
}
|
|
525
|
+
|
|
526
|
+
/**
|
|
527
|
+
* Evaluates a `PostToolUse` hook event and returns the host-formatted output contract.
|
|
528
|
+
*/
|
|
529
|
+
export function runPostToolUseHook(event = {}, options = {}) {
|
|
530
|
+
const { client, adapter, canonical } =
|
|
531
|
+
event && event.__canonical === true
|
|
532
|
+
? { client: event.client || 'claude-code', adapter: getClientAdapter(event.client || 'claude-code'), canonical: event }
|
|
533
|
+
: normalizeHookEvent(event, options);
|
|
534
|
+
|
|
535
|
+
const finalize = (res) => (client === 'antigravity' ? adapter.renderPost(res) : res);
|
|
536
|
+
|
|
537
|
+
const rawEvent = canonical.raw || event;
|
|
538
|
+
const toolName = String(canonical.toolName || 'Bash');
|
|
539
|
+
const rawOutput = extractPostToolText(rawEvent);
|
|
540
|
+
const tier1Active = Boolean(
|
|
541
|
+
options.tier1Active ||
|
|
542
|
+
rawEvent.tier1Active ||
|
|
543
|
+
globalThis.process?.env?.BURNOFF_TIER1_ACTIVE === '1'
|
|
544
|
+
);
|
|
545
|
+
const failed = canonical.failed === true || didToolExecutionFail(rawEvent, toolName);
|
|
546
|
+
|
|
547
|
+
if (
|
|
548
|
+
tier1Active &&
|
|
549
|
+
/^(?:Grep|Glob)$/i.test(toolName) &&
|
|
550
|
+
rawOutput.length < 16_000 &&
|
|
551
|
+
!failed
|
|
552
|
+
) {
|
|
553
|
+
return finalize({
|
|
554
|
+
exitCode: 0,
|
|
555
|
+
stdout: '',
|
|
556
|
+
stderr: '',
|
|
557
|
+
fastPath: 'tier1_active',
|
|
558
|
+
sanitized: { modified: false, offloaded: false, savedTokens: 0 }
|
|
559
|
+
});
|
|
560
|
+
}
|
|
561
|
+
|
|
562
|
+
const sessionId = String(canonical.sessionId || 'default');
|
|
563
|
+
const hasExplicitCwd = Boolean(canonical.cwd || options.cwd);
|
|
564
|
+
const baseCwd = path.resolve(String(canonical.cwd || options.cwd || process.cwd()));
|
|
565
|
+
const cwdOptions = { ...(hasExplicitCwd ? { ...options, cwd: baseCwd } : options), client };
|
|
566
|
+
const policy = options.policy || loadBurnoffPolicy(baseCwd);
|
|
567
|
+
const postCfg = policy.postTool || {};
|
|
568
|
+
|
|
569
|
+
const toolInput = canonical.toolInput || {};
|
|
570
|
+
const filePath = String(
|
|
571
|
+
toolInput.file_path || toolInput.notebook_path || toolInput.filePath || toolInput.path || toolInput.Path || toolInput.TargetFile || event.filePath || ''
|
|
572
|
+
).trim();
|
|
573
|
+
const cmdStr = String(
|
|
574
|
+
toolInput.command || toolInput.CommandLine || toolInput.cmd || event.command || ''
|
|
575
|
+
);
|
|
576
|
+
const rawExit =
|
|
577
|
+
event.exit_code ??
|
|
578
|
+
event.exitCode ??
|
|
579
|
+
event.tool_response?.exit_code ??
|
|
580
|
+
event.tool_response?.exitCode;
|
|
581
|
+
|
|
582
|
+
const shouldPersistState =
|
|
583
|
+
options.persistState !== false &&
|
|
584
|
+
Boolean(canonical.cwd || options.cwd || options.breakerStatePath || options.persistState);
|
|
585
|
+
|
|
586
|
+
if (shouldPersistState) {
|
|
587
|
+
recordToolOutcomeAtomicSync(
|
|
588
|
+
sessionId,
|
|
589
|
+
{
|
|
590
|
+
toolName,
|
|
591
|
+
command: cmdStr,
|
|
592
|
+
filePath,
|
|
593
|
+
failed,
|
|
594
|
+
nowMs: options.nowMs ?? Date.now()
|
|
595
|
+
},
|
|
596
|
+
cwdOptions
|
|
597
|
+
);
|
|
598
|
+
|
|
599
|
+
if (
|
|
600
|
+
EDIT_WRITE_SCOPE_LOCK_REGEX.test(toolName) &&
|
|
601
|
+
filePath &&
|
|
602
|
+
policy.guards?.scopeLockEnabled !== false
|
|
603
|
+
) {
|
|
604
|
+
const ownerId = String(
|
|
605
|
+
canonical.agentId || rawEvent.ownerId || rawEvent.agentId || rawEvent.subagentId || sessionId
|
|
606
|
+
);
|
|
607
|
+
try {
|
|
608
|
+
releaseScopeLock(ownerId, {
|
|
609
|
+
...cwdOptions,
|
|
610
|
+
scope: filePath,
|
|
611
|
+
nowMs: options.nowMs ?? Date.now()
|
|
612
|
+
});
|
|
613
|
+
} catch (err) {
|
|
614
|
+
void err; // ignore: best-effort scope lock release
|
|
615
|
+
}
|
|
616
|
+
}
|
|
617
|
+
|
|
618
|
+
if (options.disableOpportunisticGc !== true) {
|
|
619
|
+
try {
|
|
620
|
+
runOpportunisticPostToolGc({
|
|
621
|
+
baseCwd: hasExplicitCwd ? baseCwd : null,
|
|
622
|
+
homeDir: options.homeDir || null,
|
|
623
|
+
maxCacheAgeDays: Number(postCfg.retentionDays ?? 30),
|
|
624
|
+
nowMs: options.nowMs ?? Date.now(),
|
|
625
|
+
artifactMaxFiles: Number(options.artifactMaxFiles ?? postCfg.artifactMaxFiles ?? DEFAULT_ARTIFACT_MAX_FILES),
|
|
626
|
+
artifactMaxBytes: Number(options.artifactMaxBytes ?? postCfg.artifactMaxBytes ?? DEFAULT_ARTIFACT_MAX_TOTAL_BYTES)
|
|
627
|
+
});
|
|
628
|
+
} catch (gcErr) {
|
|
629
|
+
void gcErr; // ignore: non-fatal opportunistic post-tool gc
|
|
630
|
+
}
|
|
631
|
+
}
|
|
632
|
+
}
|
|
633
|
+
|
|
634
|
+
// Antigravity PostToolUse expects `{}` only and provides no tool stdout to compress.
|
|
635
|
+
if (client === 'antigravity') {
|
|
636
|
+
return finalize({
|
|
637
|
+
exitCode: 0,
|
|
638
|
+
stdout: '{}',
|
|
639
|
+
stderr: '',
|
|
640
|
+
sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
|
|
641
|
+
});
|
|
642
|
+
}
|
|
643
|
+
|
|
644
|
+
if (isHostTruncatedShellOutput(toolName, rawOutput)) {
|
|
645
|
+
return {
|
|
646
|
+
exitCode: 0,
|
|
647
|
+
stdout: '',
|
|
648
|
+
stderr: '',
|
|
649
|
+
hostTruncated: true,
|
|
650
|
+
sanitized: { modified: false, offloaded: false, savedTokens: 0 }
|
|
651
|
+
};
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
|
|
655
|
+
if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
|
|
656
|
+
return {
|
|
657
|
+
exitCode: 0,
|
|
658
|
+
stdout: '',
|
|
659
|
+
stderr: '',
|
|
660
|
+
sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 }
|
|
661
|
+
};
|
|
662
|
+
}
|
|
663
|
+
|
|
664
|
+
const isShellTool = SHELL_TOOL_NAME_RE.test(toolName);
|
|
665
|
+
let shellPolicy = { allowFts5: true, allowOffload: true, reason: 'default' };
|
|
666
|
+
if (isShellTool && cmdStr) {
|
|
667
|
+
shellPolicy = classifyShellPostToolPolicy(cmdStr);
|
|
668
|
+
}
|
|
669
|
+
|
|
670
|
+
let finalOutput = rawOutput;
|
|
671
|
+
let wasModified = false;
|
|
672
|
+
let ftsSavedTokens = 0;
|
|
673
|
+
let sanitized = {
|
|
674
|
+
toolName,
|
|
675
|
+
eligible: true,
|
|
676
|
+
sanitized: false,
|
|
677
|
+
offloaded: false,
|
|
678
|
+
artifactPath: null,
|
|
679
|
+
originalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
|
|
680
|
+
finalTokens: Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE),
|
|
681
|
+
savedTokens: 0,
|
|
682
|
+
criticalErrorsPreserved: 0,
|
|
683
|
+
updatedToolOutput: rawOutput
|
|
684
|
+
};
|
|
685
|
+
|
|
686
|
+
const ftsEnabled =
|
|
687
|
+
postCfg.fts5Enabled !== false && options.enableFts5CliCompression !== false;
|
|
688
|
+
const minFtsBytes = Number(options.minBytes ?? postCfg.minBytesToCompress ?? 4096);
|
|
689
|
+
|
|
690
|
+
if (ftsEnabled && hasExplicitCwd && isShellTool && cmdStr && shellPolicy.allowFts5 !== false) {
|
|
691
|
+
try {
|
|
692
|
+
const ftsScrub = redactSecretsPure(stripAnsiAndSpinners(rawOutput));
|
|
693
|
+
const ansiCleanShell = ftsScrub.sanitized;
|
|
694
|
+
const criticalLines = extractCriticalErrorLines(ansiCleanShell);
|
|
695
|
+
const ftsDbPath =
|
|
696
|
+
options.dbPath ||
|
|
697
|
+
options.ftsDbPath ||
|
|
698
|
+
getDefaultToolLogsDbPath(options.homeDir || null);
|
|
699
|
+
const turnId = String(event.tool_use_id || event.turn_id || event.turnId || `turn-${Date.now()}`);
|
|
700
|
+
const ftsComp = compressCliOutputFts5Sync({
|
|
701
|
+
sessionId,
|
|
702
|
+
turnId,
|
|
703
|
+
command: cmdStr,
|
|
704
|
+
exitCode: typeof rawExit === 'number' ? rawExit : (failed ? 1 : 0),
|
|
705
|
+
rawOutput: ansiCleanShell,
|
|
706
|
+
dbPath: ftsDbPath,
|
|
707
|
+
homeDir: options.homeDir || null,
|
|
708
|
+
recordLedger: false,
|
|
709
|
+
minBytes: minFtsBytes,
|
|
710
|
+
minTokensSaved: Number(options.minTokensSaved ?? 500),
|
|
711
|
+
retentionDays: Number(postCfg.retentionDays ?? 30)
|
|
712
|
+
});
|
|
713
|
+
|
|
714
|
+
if (ftsComp.compressed && ftsComp.tokensSaved > 0) {
|
|
715
|
+
const guaranteedOutput = redactSecretsPure(
|
|
716
|
+
appendMissingCriticalLines(ftsComp.output, criticalLines)
|
|
717
|
+
).sanitized;
|
|
718
|
+
const guaranteedTokens = Math.ceil(guaranteedOutput.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
719
|
+
const rawTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
720
|
+
const netSavedTokens = Math.max(0, rawTokens - guaranteedTokens);
|
|
721
|
+
if (netSavedTokens > 0 && guaranteedOutput.length < rawOutput.length) {
|
|
722
|
+
finalOutput = guaranteedOutput;
|
|
723
|
+
ftsSavedTokens = netSavedTokens;
|
|
724
|
+
wasModified = true;
|
|
725
|
+
sanitized = {
|
|
726
|
+
...sanitized,
|
|
727
|
+
sanitized: true,
|
|
728
|
+
offloaded: false,
|
|
729
|
+
redactedSecrets: ftsScrub.redactedCount,
|
|
730
|
+
finalTokens: guaranteedTokens,
|
|
731
|
+
savedTokens: netSavedTokens,
|
|
732
|
+
criticalErrorsPreserved: criticalLines.length,
|
|
733
|
+
turnId,
|
|
734
|
+
queryHandle: ftsComp.queryHandle,
|
|
735
|
+
updatedToolOutput: finalOutput
|
|
736
|
+
};
|
|
737
|
+
}
|
|
738
|
+
}
|
|
739
|
+
} catch (ftsErr) {
|
|
740
|
+
void ftsErr; // ignore: FTS5 failure fails open cleanly to sanitizer fallback
|
|
741
|
+
}
|
|
742
|
+
}
|
|
743
|
+
|
|
744
|
+
const isMcpTool = /^mcp__/i.test(toolName);
|
|
745
|
+
const postOutputMode = resolvePostOutputMode(postCfg);
|
|
746
|
+
|
|
747
|
+
if (ftsSavedTokens === 0) {
|
|
748
|
+
const allowOffload =
|
|
749
|
+
(isMcpTool || postOutputMode !== 'auto') &&
|
|
750
|
+
!(isShellTool && shellPolicy.allowOffload === false) &&
|
|
751
|
+
options.disableOffload !== true;
|
|
752
|
+
sanitized = sanitizePostOutputFallback(toolName, rawOutput, {
|
|
753
|
+
baseCwd: hasExplicitCwd ? baseCwd : null,
|
|
754
|
+
allowOffload,
|
|
755
|
+
offloadThresholdTokens: Number(
|
|
756
|
+
options.offloadThresholdTokens ?? postCfg.offloadThresholdTokens ?? OFFLOAD_TOKEN_THRESHOLD
|
|
757
|
+
)
|
|
758
|
+
});
|
|
759
|
+
finalOutput = sanitized.updatedToolOutput;
|
|
760
|
+
wasModified = sanitized.sanitized;
|
|
761
|
+
}
|
|
762
|
+
|
|
763
|
+
const hadSecretRedaction = Number(sanitized.redactedSecrets || 0) > 0;
|
|
764
|
+
const replacement =
|
|
765
|
+
!isMcpTool && wasModified && postOutputMode === 'replace'
|
|
766
|
+
? buildReplacementToolOutput(event, finalOutput)
|
|
767
|
+
: { ok: false };
|
|
768
|
+
const wouldInflate =
|
|
769
|
+
!isMcpTool &&
|
|
770
|
+
!hadSecretRedaction &&
|
|
771
|
+
replacement.ok &&
|
|
772
|
+
finalOutput.length >= rawOutput.length;
|
|
773
|
+
const effectiveReplacementOk = replacement.ok && !wouldInflate;
|
|
774
|
+
const emitContext =
|
|
775
|
+
!isMcpTool &&
|
|
776
|
+
!effectiveReplacementOk &&
|
|
777
|
+
wasModified &&
|
|
778
|
+
postOutputMode === 'context';
|
|
779
|
+
|
|
780
|
+
if (!wasModified || (!isMcpTool && !effectiveReplacementOk && !emitContext)) {
|
|
781
|
+
return {
|
|
782
|
+
exitCode: 0,
|
|
783
|
+
stdout: '',
|
|
784
|
+
stderr: '',
|
|
785
|
+
sanitized
|
|
786
|
+
};
|
|
787
|
+
}
|
|
788
|
+
|
|
789
|
+
const outputAcceptedByHost = isMcpTool ? wasModified : effectiveReplacementOk;
|
|
790
|
+
const totalSavedTokens = outputAcceptedByHost
|
|
791
|
+
? (ftsSavedTokens > 0 ? ftsSavedTokens : sanitized.savedTokens)
|
|
792
|
+
: 0;
|
|
793
|
+
|
|
794
|
+
if (totalSavedTokens > 0 && options.recordLedger !== false && (hasExplicitCwd || options.ledgerPath || options.recordLedger === true)) {
|
|
795
|
+
const rawEventModel =
|
|
796
|
+
typeof event.model === 'string'
|
|
797
|
+
? event.model
|
|
798
|
+
: event.model?.id || event.model?.model_id || event.modelId || event.model_id;
|
|
799
|
+
const modelId = rawEventModel || 'claude-sonnet-5-5';
|
|
800
|
+
const usageSource = event.usage || event.context_window?.current_usage || {};
|
|
801
|
+
const totalPromptTokens = computeTotalPromptTokens(usageSource);
|
|
802
|
+
const rates = resolveEffectiveRates(modelId, totalPromptTokens, cwdOptions);
|
|
803
|
+
const computedSavedUSD =
|
|
804
|
+
rates && !rates.unknownModel && Number.isFinite(rates.inputPer1M)
|
|
805
|
+
? Number(((totalSavedTokens / 1_000_000) * rates.inputPer1M).toFixed(6))
|
|
806
|
+
: 0;
|
|
807
|
+
const writeRatePer1M =
|
|
808
|
+
rates && !rates.unknownModel ? (rates.write5mPer1M ?? rates.inputPer1M) : 0;
|
|
809
|
+
const writeRateUSD =
|
|
810
|
+
Number.isFinite(writeRatePer1M) && writeRatePer1M > 0
|
|
811
|
+
? Number(((totalSavedTokens / 1_000_000) * writeRatePer1M).toFixed(6))
|
|
812
|
+
: 0;
|
|
813
|
+
|
|
814
|
+
recordSavingsReceipt(
|
|
815
|
+
{
|
|
816
|
+
sessionId,
|
|
817
|
+
cwd: baseCwd,
|
|
818
|
+
modelId: rates.unknownModel ? (rates.rawModelId || modelId) : rates.modelId,
|
|
819
|
+
ledgerBucket: LEDGER_BUCKETS.AVOIDED_WRITE,
|
|
820
|
+
category: sanitized.offloaded
|
|
821
|
+
? 'ARTIFACT_OFFLOAD_4K'
|
|
822
|
+
: ftsSavedTokens > 0
|
|
823
|
+
? 'CLI_FTS5_COMPRESSED'
|
|
824
|
+
: 'LOSSLESS_POST_SANITIZER',
|
|
825
|
+
savedTokens: totalSavedTokens,
|
|
826
|
+
savedUSD: computedSavedUSD,
|
|
827
|
+
writeRateUSD,
|
|
828
|
+
detail: `${toolName} output compressed (+${totalSavedTokens} tokens saved)`
|
|
829
|
+
},
|
|
830
|
+
cwdOptions
|
|
831
|
+
);
|
|
832
|
+
}
|
|
833
|
+
|
|
834
|
+
const hookSpecificOutput = isMcpTool
|
|
835
|
+
? {
|
|
836
|
+
hookEventName: 'PostToolUse',
|
|
837
|
+
updatedMCPToolOutput: finalOutput
|
|
838
|
+
}
|
|
839
|
+
: effectiveReplacementOk
|
|
840
|
+
? {
|
|
841
|
+
hookEventName: 'PostToolUse',
|
|
842
|
+
updatedToolOutput: replacement.value
|
|
843
|
+
}
|
|
844
|
+
: {
|
|
845
|
+
hookEventName: 'PostToolUse',
|
|
846
|
+
additionalContext: finalOutput
|
|
847
|
+
};
|
|
848
|
+
|
|
849
|
+
return {
|
|
850
|
+
exitCode: 0,
|
|
851
|
+
stdout: JSON.stringify({ hookSpecificOutput }),
|
|
852
|
+
stderr: '',
|
|
853
|
+
sanitized,
|
|
854
|
+
hookSpecificOutput
|
|
855
|
+
};
|
|
856
|
+
}
|
|
857
|
+
|
|
858
|
+
export default {
|
|
859
|
+
OFFLOAD_TOKEN_THRESHOLD,
|
|
860
|
+
CHARS_PER_TOKEN_ESTIMATE,
|
|
861
|
+
DEFAULT_ARTIFACT_MAX_FILES,
|
|
862
|
+
DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,
|
|
863
|
+
OPPORTUNISTIC_GC_INTERVAL_MS,
|
|
864
|
+
CRITICAL_ERROR_REGEX,
|
|
865
|
+
stripAnsiAndSpinners,
|
|
866
|
+
extractCriticalErrorLines,
|
|
867
|
+
extractPostToolText,
|
|
868
|
+
enforceArtifactDirCap,
|
|
869
|
+
runOpportunisticPostToolGc,
|
|
870
|
+
resolvePostOutputMode,
|
|
871
|
+
buildReplacementToolOutput,
|
|
872
|
+
isHostTruncatedShellOutput,
|
|
873
|
+
didToolExecutionFail,
|
|
874
|
+
runPostToolUseHook
|
|
875
|
+
};
|