burnoff 1.4.1 → 2.1.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.
Files changed (62) hide show
  1. package/.claude-plugin/plugin.json +1 -1
  2. package/.github/workflows/burnoff-pr-gate.yml +5 -3
  3. package/.github/workflows/burnoff-startup-lint.yml +2 -2
  4. package/CHANGELOG.md +74 -0
  5. package/README.md +187 -213
  6. package/SECURITY.md +38 -0
  7. package/bin/burnoff.mjs +307 -32
  8. package/commands/burnoff.md +6 -4
  9. package/docs/CLAUDE_CODE_PLUGIN.md +29 -28
  10. package/docs/DESIGN_PARTNER_INTAKE.md +3 -3
  11. package/hooks/hook-io.mjs +216 -11
  12. package/hooks/hooks.json +44 -0
  13. package/hooks/post-tool-use.mjs +3 -1
  14. package/hooks/pre-tool-use.mjs +47 -8
  15. package/hooks/session-lifecycle.mjs +24 -3
  16. package/hooks/user-prompt-submit.mjs +98 -0
  17. package/package.json +6 -4
  18. package/scripts/bench-hooks.mjs +34 -3
  19. package/scripts/bench-savings.mjs +318 -0
  20. package/scripts/burnoff-statusline.mjs +138 -6
  21. package/src/ci/ci-gate.mjs +199 -13
  22. package/src/ci/pr-cost.mjs +417 -45
  23. package/src/ci/pr-summary.mjs +467 -0
  24. package/src/cli/audit.mjs +179 -28
  25. package/src/cli/doctor.mjs +32 -6
  26. package/src/cli/hook-health.mjs +9 -1
  27. package/src/cli/init.mjs +226 -39
  28. package/src/cli/preview.mjs +299 -0
  29. package/src/cli/startup-audit/formatter.mjs +248 -0
  30. package/src/cli/startup-audit/jsonc.mjs +601 -0
  31. package/src/cli/startup-audit/mcp-audit.mjs +735 -0
  32. package/src/cli/startup-audit/rules-hygiene.mjs +645 -0
  33. package/src/cli/startup-audit/telemetry-scan.mjs +975 -0
  34. package/src/cli/startup-audit.mjs +451 -2471
  35. package/src/clients/claude-code.mjs +41 -4
  36. package/src/config/catalog.json +295 -0
  37. package/src/config/effort.mjs +145 -0
  38. package/src/config/harness-quirks.mjs +340 -0
  39. package/src/config/loader.mjs +27 -2
  40. package/src/config/policy.mjs +81 -9
  41. package/src/config/pricing.mjs +247 -19
  42. package/src/config/semver.mjs +25 -0
  43. package/src/config/uncached-attribution.mjs +280 -41
  44. package/src/guards/compaction-baton.mjs +248 -0
  45. package/src/guards/loop-breaker.mjs +328 -47
  46. package/src/guards/model-switch-hook.mjs +126 -0
  47. package/src/guards/phase5-detectors.mjs +275 -21
  48. package/src/guards/post-tool-engine.mjs +333 -11
  49. package/src/guards/pre-tool-engine.mjs +607 -45
  50. package/src/guards/prefix-guard.mjs +609 -0
  51. package/src/guards/prompt-guard.mjs +309 -0
  52. package/src/guards/read-clamp.mjs +192 -8
  53. package/src/guards/session-hook.mjs +149 -7
  54. package/src/guards/shell-guard.mjs +56 -5
  55. package/src/guards/snooze.mjs +169 -5
  56. package/src/ipc/daemon.mjs +76 -0
  57. package/src/ipc/fast-client.mjs +165 -4
  58. package/src/ipc/protocol.mjs +16 -3
  59. package/src/storage/antigravity-parser.mjs +16 -2
  60. package/src/storage/file-lock.mjs +16 -3
  61. package/src/storage/jsonl-parser.mjs +133 -22
  62. package/src/storage/telemetry-metrics.mjs +254 -4
@@ -22,8 +22,22 @@ import {
22
22
  import { recordSavingsReceipt, rotateMonthlyLedger, LEDGER_BUCKETS } from '../storage/ledger.mjs';
23
23
  import { recordToolOutcomeAtomicSync, releaseScopeLock } from './loop-breaker.mjs';
24
24
  import { redactSecretsPure } from './credential-scrubber.mjs';
25
+ import { compareSemver } from '../config/semver.mjs';
25
26
 
26
27
  export const OFFLOAD_TOKEN_THRESHOLD = 4000;
28
+ export const DEFAULT_WEBFETCH_MAX_TOKENS = 4000;
29
+ /**
30
+ * First Claude Code release that saves large Bash output to disk instead of truncating it inline.
31
+ * Source: official changelog, 2.1.2 — "Changed large bash command outputs to be saved to disk instead of
32
+ * truncated, allowing Claude to read the full content" (https://code.claude.com/docs/en/changelog).
33
+ * Note: `bashOutputMaxChars` (configurable inline ceiling) arrived later in 2.1.261 and is NOT this cutoff.
34
+ * The hook payload carries no Claude Code version, so this legacy branch only runs when
35
+ * `claudeCodeVersion` is supplied via policy/options; otherwise the modern path always applies.
36
+ */
37
+ export const LEGACY_INLINE_TRUNC_CUTOFF = '2.1.2';
38
+ export const HOST_SHELL_OUTPUT_DEFAULT_CAP = 30_000;
39
+ export const HOST_SHELL_OUTPUT_MIN_CAP = 4_000;
40
+ export const HOST_SHELL_OUTPUT_MAX_CAP = 128_000;
27
41
  export const CHARS_PER_TOKEN_ESTIMATE = 4;
28
42
  export const DEFAULT_ARTIFACT_MAX_FILES = 200;
29
43
  export const DEFAULT_ARTIFACT_MAX_TOTAL_BYTES = 50 * 1024 * 1024;
@@ -148,14 +162,90 @@ export function buildReplacementToolOutput(event = {}, finalOutput = '') {
148
162
  return { ok: false };
149
163
  }
150
164
 
151
- function resolveHostShellOutputCap() {
152
- const n = Number(globalThis.process?.env?.BASH_MAX_OUTPUT_LENGTH);
153
- return Number.isFinite(n) && n > 0 ? n : 30_000;
165
+ const FETCH_MCP_TOOL_PART_RE = /(?:fetch|scrape|browse|get_?page|read_?url|crawl)/i;
166
+
167
+ /**
168
+ * True for the native `WebFetch` tool and raw web/docs MCP fetch tools
169
+ * (`mcp__<server>__<tool>` where `<tool>` looks like fetch/scrape/browse/get_page/read_url/crawl).
170
+ */
171
+ export function isFetchLikeTool(toolName = '') {
172
+ const name = String(toolName || '');
173
+ if (/^WebFetch$/i.test(name)) return true;
174
+ const m = name.match(/^mcp__(.+?)__(.+)$/i);
175
+ return Boolean(m && FETCH_MCP_TOOL_PART_RE.test(m[2]));
176
+ }
177
+
178
+ function readJsonFileSafe(filePath) {
179
+ try {
180
+ if (!filePath || !fs.existsSync(filePath)) return null;
181
+ const parsed = JSON.parse(fs.readFileSync(filePath, 'utf8'));
182
+ return parsed && typeof parsed === 'object' && !Array.isArray(parsed) ? parsed : null;
183
+ } catch (err) {
184
+ void err; // ignore: unreadable/malformed Claude settings fall through to next source
185
+ return null;
186
+ }
187
+ }
188
+
189
+ function coerceBashOutputMaxChars(value) {
190
+ if (value === undefined || value === null || value === '' || typeof value === 'boolean') return null;
191
+ const n = Number(value);
192
+ if (!Number.isFinite(n) || n <= 0) return null;
193
+ return Math.min(HOST_SHELL_OUTPUT_MAX_CAP, Math.max(HOST_SHELL_OUTPUT_MIN_CAP, Math.floor(n)));
194
+ }
195
+
196
+ /**
197
+ * Resolves Claude Code's inline Bash output cap. `bashOutputMaxChars` from settings wins
198
+ * (`.claude/settings.local.json` -> `.claude/settings.json` -> `~/.claude/settings.json`, clamped to
199
+ * [4,000, 128,000]); only when unset does `BASH_MAX_OUTPUT_LENGTH` (default 30,000) apply.
200
+ * `settings` may be passed directly to bypass file lookup.
201
+ */
202
+ export function resolveHostShellOutputCap({ cwd, homeDir, env, settings } = {}) {
203
+ const sources = [];
204
+ if (settings && typeof settings === 'object') {
205
+ sources.push(settings);
206
+ } else {
207
+ const baseDir = cwd ? path.resolve(String(cwd)) : '';
208
+ let home = homeDir || '';
209
+ if (!home) {
210
+ try {
211
+ home = getHomeDir();
212
+ } catch (err) {
213
+ void err; // ignore: missing home dir skips user-level settings
214
+ }
215
+ }
216
+ if (baseDir) {
217
+ sources.push(readJsonFileSafe(path.join(baseDir, '.claude', 'settings.local.json')));
218
+ sources.push(readJsonFileSafe(path.join(baseDir, '.claude', 'settings.json')));
219
+ }
220
+ if (home) sources.push(readJsonFileSafe(path.join(home, '.claude', 'settings.json')));
221
+ }
222
+ for (const src of sources) {
223
+ const cap = coerceBashOutputMaxChars(src?.bashOutputMaxChars);
224
+ if (cap !== null) return cap;
225
+ }
226
+ const activeEnv = env && typeof env === 'object' ? env : globalThis.process?.env;
227
+ const n = Number(activeEnv?.BASH_MAX_OUTPUT_LENGTH);
228
+ return Number.isFinite(n) && n > 0 ? n : HOST_SHELL_OUTPUT_DEFAULT_CAP;
229
+ }
230
+
231
+ function isLegacyInlineTruncationHost(opts = {}) {
232
+ if (opts.legacyInlineTruncation === true) return true;
233
+ if (!opts.claudeCodeVersion) return false;
234
+ const cmp = compareSemver(String(opts.claudeCodeVersion), LEGACY_INLINE_TRUNC_CUTOFF);
235
+ return cmp !== null && cmp < 0;
154
236
  }
155
237
 
156
- export function isHostTruncatedShellOutput(toolName, rawOutput) {
238
+ /**
239
+ * Modern Claude Code persists oversized Bash output to a file and hands the model a small preview, so
240
+ * a long inline `tool_response` is complete (not host-truncated) and is compressed normally. Only an
241
+ * explicitly legacy host (`opts.legacyInlineTruncation` or `opts.claudeCodeVersion` below
242
+ * `LEGACY_INLINE_TRUNC_CUTOFF`) still truncates inline at the cap, where `length >= cap - 100` skips.
243
+ * Hook point: add a fixture-backed persisted-output preview check here once a real >30K sample exists.
244
+ */
245
+ export function isHostTruncatedShellOutput(toolName, rawOutput, opts = {}) {
157
246
  if (!/^(?:Bash|PowerShell)$/i.test(String(toolName || ''))) return false;
158
- return String(rawOutput || '').length >= resolveHostShellOutputCap() - 100;
247
+ if (!isLegacyInlineTruncationHost(opts || {})) return false;
248
+ return String(rawOutput || '').length >= resolveHostShellOutputCap(opts || {}) - 100;
159
249
  }
160
250
 
161
251
  export function didToolExecutionFail(event = {}, toolNameHint = '') {
@@ -437,21 +527,125 @@ function offloadOversizedOutput(
437
527
  };
438
528
  }
439
529
 
440
- function sanitizePostOutputFallback(toolName, rawOutput, { baseCwd, allowOffload, offloadThresholdTokens }) {
530
+ function buildWebFetchBudgetDigest(cleanText, maxTokens, baseCwd) {
531
+ const maxChars = Math.max(600, Math.floor(Number(maxTokens || DEFAULT_WEBFETCH_MAX_TOKENS) * CHARS_PER_TOKEN_ESTIMATE * 0.85));
532
+ let artifactPath = null;
533
+ if (baseCwd) {
534
+ const sha256 = crypto.createHash('sha256').update(cleanText, 'utf8').digest('hex');
535
+ const candidatePath = path.join(baseCwd, '.claude', 'cache', 'artifacts', `burnoff_${sha256}.txt`);
536
+ try {
537
+ atomicWriteFileSync(candidatePath, cleanText, { encoding: 'utf8', mode: 0o600, dirMode: 0o700 });
538
+ artifactPath = candidatePath;
539
+ } catch (err) {
540
+ void err; // ignore: fail-open still caps in-memory digest to token budget
541
+ }
542
+ }
543
+
544
+ const rawTokens = Math.ceil(cleanText.length / CHARS_PER_TOKEN_ESTIMATE);
545
+ const lines = cleanText.split(/\r?\n/);
546
+ // Each heading keeps the first lines of its first code fence so API/function signatures survive
547
+ // the digest alongside the outline (not only prose paragraphs).
548
+ const headings = [];
549
+ const leadExcerpts = [];
550
+ const orphanSignatures = [];
551
+ let inFence = false;
552
+ let fenceLinesTaken = 0;
553
+ let fenceTarget = null;
554
+ for (let i = 0; i < lines.length; i += 1) {
555
+ const t = lines[i].trim();
556
+ if (/^(?:```|~~~)/.test(t)) {
557
+ if (!inFence) {
558
+ inFence = true;
559
+ fenceLinesTaken = 0;
560
+ const cur = headings[headings.length - 1];
561
+ fenceTarget = cur && !cur.fenceSeen ? cur : null;
562
+ if (fenceTarget) fenceTarget.fenceSeen = true;
563
+ } else {
564
+ inFence = false;
565
+ fenceTarget = null;
566
+ }
567
+ continue;
568
+ }
569
+ if (inFence) {
570
+ if (t && fenceLinesTaken < 2) {
571
+ fenceLinesTaken += 1;
572
+ if (fenceTarget) fenceTarget.sigs.push(t.slice(0, 160));
573
+ else if (!headings.length && orphanSignatures.length < 6) orphanSignatures.push(t.slice(0, 160));
574
+ }
575
+ continue;
576
+ }
577
+ if (!t) continue;
578
+ if (/^(?:#{1,6}\s+|<h[1-6][^>]*>)/i.test(t) || /^[A-Z0-9][A-Za-z0-9 ._:-]{2,80}:$/.test(t)) {
579
+ if (headings.length < 120) {
580
+ headings.push({ text: t.replace(/<[^>]+>/g, '').slice(0, 140), sigs: [], fenceSeen: false });
581
+ }
582
+ } else if (leadExcerpts.length < 12 && t.length >= 20) {
583
+ leadExcerpts.push(t.slice(0, 220));
584
+ }
585
+ }
586
+
587
+ const header =
588
+ `[Burnoff WebFetch Budget Offload: ~${rawTokens.toLocaleString('en-US')} raw tok trimmed to <=${maxTokens} tok budget` +
589
+ `${artifactPath ? `; full text archived at ${artifactPath}` : ''}]`;
590
+ const parts = [header];
591
+ if (headings.length > 0) {
592
+ parts.push('Headings / Sections:');
593
+ for (const h of headings) {
594
+ parts.push(`- ${h.text}`);
595
+ for (const sig of h.sigs) parts.push(` > ${sig}`);
596
+ }
597
+ }
598
+ if (orphanSignatures.length > 0) {
599
+ parts.push('Code / Signatures:', ...orphanSignatures.map((s) => ` ${s}`));
600
+ }
601
+ if (leadExcerpts.length > 0) {
602
+ parts.push('Lead Excerpts:', ...leadExcerpts.map((l) => ` ${l}`));
603
+ }
604
+ let digest = parts.join('\n');
605
+ if (digest.length > maxChars) {
606
+ digest = `${digest.slice(0, Math.max(0, maxChars - 24)).trimEnd()}\n[... budget capped ...]`;
607
+ }
608
+ return {
609
+ offloaded: Boolean(artifactPath),
610
+ artifactPath,
611
+ output: digest
612
+ };
613
+ }
614
+
615
+ function sanitizePostOutputFallback(
616
+ toolName,
617
+ rawOutput,
618
+ { baseCwd, allowOffload, offloadThresholdTokens, webFetchMaxTokens = DEFAULT_WEBFETCH_MAX_TOKENS }
619
+ ) {
441
620
  const originalTokens = Math.ceil(rawOutput.length / CHARS_PER_TOKEN_ESTIMATE);
442
621
  const scrubbedInit = redactSecretsPure(stripAnsiAndSpinners(rawOutput));
443
622
  let cleaned = scrubbedInit.sanitized;
444
623
  let redactedSecrets = scrubbedInit.redactedCount;
445
- if (/^WebFetch$/i.test(toolName)) {
624
+ const isWebFetch = isFetchLikeTool(toolName);
625
+ if (isWebFetch) {
446
626
  cleaned = cleaned.replace(HTML_BOILERPLATE_BLOCK_REGEX, '');
447
627
  }
448
- const criticalErrorLines = extractCriticalErrorLines(cleaned);
628
+
629
+ // Never apply stack-trace error line extraction to scraped WebFetch documentation prose,
630
+ // and cap unique error lines on other tools to prevent pathological blow-up.
631
+ let criticalErrorLines = [];
632
+ if (!isWebFetch) {
633
+ const seenErr = new Set();
634
+ for (const line of extractCriticalErrorLines(cleaned)) {
635
+ const key = line.trim();
636
+ if (!key || seenErr.has(key)) continue;
637
+ seenErr.add(key);
638
+ criticalErrorLines.push(line);
639
+ if (criticalErrorLines.length >= 25) break;
640
+ }
641
+ }
642
+
449
643
  const rawLines = cleaned.split(/\n/);
450
644
  const filteredLines = [];
451
645
  let strippedPassingTests = 0;
452
646
 
453
647
  for (const line of rawLines) {
454
- if (CRITICAL_ERROR_REGEX.test(line)) {
648
+ if (!isWebFetch && CRITICAL_ERROR_REGEX.test(line)) {
455
649
  filteredLines.push(line);
456
650
  continue;
457
651
  }
@@ -480,7 +674,15 @@ function sanitizePostOutputFallback(toolName, rawOutput, { baseCwd, allowOffload
480
674
  let artifactPath = null;
481
675
  let finalOutput = sanitizedText;
482
676
 
483
- if (allowOffload && baseCwd && (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens)) {
677
+ if (isWebFetch && postFilterTokens > webFetchMaxTokens) {
678
+ const cleanScrub = redactSecretsPure(cleaned);
679
+ cleaned = cleanScrub.sanitized;
680
+ redactedSecrets = Math.max(redactedSecrets, cleanScrub.redactedCount);
681
+ const wfDigest = buildWebFetchBudgetDigest(cleaned, webFetchMaxTokens, allowOffload ? baseCwd : null);
682
+ offloaded = wfDigest.offloaded;
683
+ artifactPath = wfDigest.artifactPath;
684
+ finalOutput = redactSecretsPure(wfDigest.output).sanitized;
685
+ } else if (allowOffload && baseCwd && (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens)) {
484
686
  const cleanScrub = redactSecretsPure(cleaned);
485
687
  cleaned = cleanScrub.sanitized;
486
688
  redactedSecrets = Math.max(redactedSecrets, cleanScrub.redactedCount);
@@ -641,7 +843,15 @@ export function runPostToolUseHook(event = {}, options = {}) {
641
843
  });
642
844
  }
643
845
 
644
- if (isHostTruncatedShellOutput(toolName, rawOutput)) {
846
+ if (
847
+ isHostTruncatedShellOutput(toolName, rawOutput, {
848
+ cwd: hasExplicitCwd ? baseCwd : null,
849
+ homeDir: options.homeDir,
850
+ env: options.env,
851
+ claudeCodeVersion: options.claudeCodeVersion ?? postCfg.claudeCodeVersion,
852
+ legacyInlineTruncation: options.legacyInlineTruncation ?? postCfg.legacyInlineTruncation
853
+ })
854
+ ) {
645
855
  return {
646
856
  exitCode: 0,
647
857
  stdout: '',
@@ -651,7 +861,115 @@ export function runPostToolUseHook(event = {}, options = {}) {
651
861
  };
652
862
  }
653
863
 
864
+ function inspectPostEditFormatting(absFilePath, baseCwd, opts = {}) {
865
+ try {
866
+ if (!absFilePath || !fs.existsSync(absFilePath)) return null;
867
+ const st = fs.statSync(absFilePath);
868
+ if (!st.isFile() || st.size === 0 || st.size > 128 * 1024) return null;
869
+ if (!/\.(?:[cm]?[jt]sx?|py|go|rs|java|rb|css|scss|html)$/i.test(absFilePath)) return null;
870
+
871
+ let formatterModified = Boolean(opts.autoFormatted);
872
+ const beforeContent = fs.readFileSync(absFilePath, 'utf8');
873
+ const beforeHash = crypto.createHash('sha256').update(beforeContent, 'utf8').digest('hex');
874
+
875
+ if (opts.preEditHash && opts.preEditHash !== beforeHash) {
876
+ formatterModified = true;
877
+ }
878
+
879
+ if (
880
+ (opts.mode === 'format' || opts.mode === 'auto' || opts.mode === 'write') &&
881
+ typeof opts.formatterRunner === 'function'
882
+ ) {
883
+ opts.formatterRunner(absFilePath, baseCwd);
884
+ if (fs.existsSync(absFilePath)) {
885
+ const afterContent = fs.readFileSync(absFilePath, 'utf8');
886
+ const afterHash = crypto.createHash('sha256').update(afterContent, 'utf8').digest('hex');
887
+ if (afterHash !== beforeHash) {
888
+ formatterModified = true;
889
+ }
890
+ }
891
+ }
892
+
893
+ const src = formatterModified ? fs.readFileSync(absFilePath, 'utf8') : beforeContent;
894
+ const mixedLine = /^(?:\t+ +| +\t+)/m.test(src);
895
+ const hasTabs = /^\t+\S/m.test(src);
896
+ const hasSpaces = /^ {2,}\S/m.test(src);
897
+ const hasMixedIndent = mixedLine || (hasTabs && hasSpaces);
898
+ if (!hasMixedIndent && !formatterModified) return null;
899
+
900
+ let cmdHint = 'your local formatter';
901
+ if (fs.existsSync(path.join(baseCwd, 'biome.json'))) {
902
+ cmdHint = `npx biome check --write "${absFilePath}"`;
903
+ } else if (
904
+ /\.(?:[cm]?[jt]sx?|css|scss|html)$/i.test(absFilePath) ||
905
+ ['.prettierrc', '.prettierrc.json', '.prettierrc.js', '.prettierrc.mjs'].some((n) =>
906
+ fs.existsSync(path.join(baseCwd, n))
907
+ )
908
+ ) {
909
+ cmdHint = `npx prettier --write "${absFilePath}"`;
910
+ } else if (/\.py$/i.test(absFilePath) || fs.existsSync(path.join(baseCwd, 'ruff.toml')) || fs.existsSync(path.join(baseCwd, 'pyproject.toml'))) {
911
+ cmdHint = `ruff format "${absFilePath}"`;
912
+ } else if (/\.go$/i.test(absFilePath) || fs.existsSync(path.join(baseCwd, 'go.mod'))) {
913
+ cmdHint = `gofmt -w "${absFilePath}"`;
914
+ } else if (/\.rs$/i.test(absFilePath) || fs.existsSync(path.join(baseCwd, 'rustfmt.toml'))) {
915
+ cmdHint = `rustfmt "${absFilePath}"`;
916
+ }
917
+
918
+ const msgs = [];
919
+ if (formatterModified) {
920
+ msgs.push(
921
+ `[Burnoff BO-FMT-02 Auto-Format Notice] Formatter modified ${path.basename(absFilePath)} on disk; ` +
922
+ `re-read edited lines before subsequent exact-match Edit calls to avoid stale-context failures.`
923
+ );
924
+ }
925
+ if (hasMixedIndent) {
926
+ msgs.push(
927
+ `[Burnoff BO-FMT-01 Post-Edit Formatter Coach] Mixed tab/space indentation detected in ${path.basename(absFilePath)}. ` +
928
+ `Run \`${cmdHint}\` instead of spending LLM tokens fixing whitespace.`
929
+ );
930
+ }
931
+ const msg = msgs.join('\n');
932
+ return {
933
+ exitCode: 0,
934
+ stdout: JSON.stringify({
935
+ hookSpecificOutput: {
936
+ hookEventName: 'PostToolUse',
937
+ additionalContext: msg
938
+ }
939
+ }),
940
+ stderr: '',
941
+ formatterModified,
942
+ sanitized: { eligible: false, sanitized: false, offloaded: false, savedTokens: 0 },
943
+ hookSpecificOutput: {
944
+ hookEventName: 'PostToolUse',
945
+ additionalContext: msg
946
+ }
947
+ };
948
+ } catch (fmtErr) {
949
+ void fmtErr; // ignore: non-fatal post-edit formatting inspection
950
+ return null;
951
+ }
952
+ }
953
+
654
954
  const unprefixed = toolName.replace(/^mcp__[a-zA-Z0-9_-]+__/i, '');
955
+ if (
956
+ !failed &&
957
+ EDIT_WRITE_SCOPE_LOCK_REGEX.test(unprefixed) &&
958
+ filePath &&
959
+ postCfg.autoFormatOnSave !== 'off' &&
960
+ options.autoFormatOnSave !== false
961
+ ) {
962
+ const absEditedPath = path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(baseCwd, filePath);
963
+ const fmtMode = String(options.autoFormatOnSave || postCfg.autoFormatOnSave || 'advisory').toLowerCase();
964
+ const fmtRes = inspectPostEditFormatting(absEditedPath, baseCwd, {
965
+ mode: fmtMode,
966
+ autoFormatted: Boolean(rawEvent.autoFormatted || rawEvent.formatterModified || options.autoFormatted),
967
+ preEditHash: options.preEditHash || rawEvent.preEditHash || null,
968
+ formatterRunner: options.formatterRunner || null
969
+ });
970
+ if (fmtRes) return fmtRes;
971
+ }
972
+
655
973
  if (PROTECTED_WORKSPACE_TOOL_RE.test(unprefixed) || !ELIGIBLE_POST_TOOL_RE.test(toolName)) {
656
974
  return {
657
975
  exitCode: 0,
@@ -754,6 +1072,9 @@ export function runPostToolUseHook(event = {}, options = {}) {
754
1072
  allowOffload,
755
1073
  offloadThresholdTokens: Number(
756
1074
  options.offloadThresholdTokens ?? postCfg.offloadThresholdTokens ?? OFFLOAD_TOKEN_THRESHOLD
1075
+ ),
1076
+ webFetchMaxTokens: Number(
1077
+ options.webFetchMaxTokens ?? postCfg.webFetchMaxTokens ?? DEFAULT_WEBFETCH_MAX_TOKENS
757
1078
  )
758
1079
  });
759
1080
  finalOutput = sanitized.updatedToolOutput;
@@ -857,6 +1178,7 @@ export function runPostToolUseHook(event = {}, options = {}) {
857
1178
 
858
1179
  export default {
859
1180
  OFFLOAD_TOKEN_THRESHOLD,
1181
+ DEFAULT_WEBFETCH_MAX_TOKENS,
860
1182
  CHARS_PER_TOKEN_ESTIMATE,
861
1183
  DEFAULT_ARTIFACT_MAX_FILES,
862
1184
  DEFAULT_ARTIFACT_MAX_TOTAL_BYTES,