ctxtop 4.0.0 → 4.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 (89) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHECKSUMS.sha256 +59 -42
  4. package/README.md +351 -330
  5. package/bin/ah-statusline.mjs +30 -0
  6. package/bin/ctxtop.mjs +330 -5
  7. package/config/default_flightcheck.json +19 -0
  8. package/config/modelCatalog.json +165 -0
  9. package/hooks/handlers/compact-lifecycle.mjs +323 -8
  10. package/hooks/handlers/config-change.mjs +402 -0
  11. package/hooks/handlers/hookIo.mjs +56 -0
  12. package/hooks/handlers/post-model-switch.mjs +111 -0
  13. package/hooks/handlers/post-tool-use.mjs +117 -16
  14. package/hooks/handlers/pre-model-switch.mjs +823 -24
  15. package/hooks/handlers/pre-tool-use.mjs +271 -4
  16. package/hooks/handlers/stop-gate.mjs +297 -11
  17. package/hooks/handlers/user-prompt-submit.mjs +224 -0
  18. package/hooks/hooks.json +50 -0
  19. package/hooks/post_tool_use.mjs +8 -0
  20. package/hooks/register.js +48 -9
  21. package/hooks/session_start.mjs +11 -1
  22. package/hooks/stop.mjs +11 -1
  23. package/package.json +11 -4
  24. package/packages/antigravity/package.json +1 -1
  25. package/packages/claude-code/package.json +1 -1
  26. package/packages/core/package.json +1 -1
  27. package/packages/engine-node/package.json +1 -1
  28. package/packages/mcp/package.json +1 -1
  29. package/packages/mcp/src/server.mjs +1 -1
  30. package/packages/pro/package.json +1 -1
  31. package/plugin.json +1 -1
  32. package/sidecars/horizon-daemon/server.mjs +38 -2
  33. package/skills/handoff/SKILL.md +8 -0
  34. package/src/adapters/antigravity/index.mjs +31 -1
  35. package/src/adapters/claude-code/index.mjs +40 -1
  36. package/src/cli/horizon_hud.mjs +254 -52
  37. package/src/config/modelCatalog.json +84 -0
  38. package/src/core/bucket_b_runtime.mjs +1200 -0
  39. package/src/core/constants.mjs +191 -4
  40. package/src/core/detectors_det01_to_16.mjs +54 -5
  41. package/src/core/doc_indexer.mjs +338 -0
  42. package/src/core/layer5_hygiene.mjs +118 -0
  43. package/src/core/parser.mjs +2 -1
  44. package/src/core/paths.mjs +3 -2
  45. package/src/core/rsl_clash_auditor.mjs +423 -0
  46. package/src/core/rsl_distiller.mjs +372 -0
  47. package/src/core/rsl_ledger.mjs +969 -0
  48. package/src/core/rsl_triage.mjs +909 -0
  49. package/src/core/session_auditor.mjs +658 -0
  50. package/src/core/shield_manager.mjs +1417 -0
  51. package/src/core/task_quota_router.mjs +1 -1
  52. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
  53. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  54. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  55. package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
  56. package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
  57. package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
  58. package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
  59. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
  60. package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
  61. package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
  62. package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
  63. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  64. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  65. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  66. package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
  67. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
  68. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
  69. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
  70. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  71. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
  72. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  73. package/src/core-isomorphic/index.js +1 -0
  74. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
  75. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
  76. package/src/core-isomorphic/ui/modViews.mjs +35 -9
  77. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  78. package/src/diagnostics/doctorEngine.mjs +95 -3
  79. package/src/engine-node/db/probe.mjs +234 -2
  80. package/src/engine-node/index.mjs +3 -0
  81. package/src/engine-node/sensors/blindspots.mjs +13 -6
  82. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  83. package/src/hooks/claude_rsl_hook.mjs +288 -0
  84. package/src/hooks/post_invocation.mjs +196 -4
  85. package/src/hooks/pre_invocation.mjs +732 -22
  86. package/src/hooks/session_start.mjs +39 -1
  87. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  88. package/src/utils/sessionCalibration.mjs +657 -0
  89. package/src/webview/horizon_panel.html +1325 -317
@@ -0,0 +1,1200 @@
1
+ /**
2
+ * @file src/core/bucket_b_runtime.mjs
3
+ * Node.js Runtime & Shadow-Telemetry Adapter for Bucket B Guardrails (`ctxtop`).
4
+ *
5
+ * Responsibilities:
6
+ * - SKU-isolated workspace manifest / `.npmrc` / workspace-package discovery for `#6 SLOPSQUAT_DEP_GATE`
7
+ * - Cold (`<25ms`) + incremental (`<3ms`) 5-line FNV-1a shingle index cache for `#8 DUPLICATE_CLONE_DETECTOR`
8
+ * - Zero-spawn cached dirty-file state reader for `#13 VAGUE_PROMPT_ANCHOR`
9
+ * - `AGENTS.md` / `CLAUDE.md` candidate hook preview scanner for `#20 PROSE_TO_HOOK_COMPILER` (`ctxtop doctor`)
10
+ * - Unified `SHADOW` / `COACH` hook evaluation wrapper emitting `.hints.jsonl` records via `recordBucketBShadowHint`
11
+ */
12
+
13
+ import fs from 'node:fs';
14
+ import path from 'node:path';
15
+ import { performance } from 'node:perf_hooks';
16
+ import { recordBucketBShadowHint } from './shield_manager.mjs';
17
+ import {
18
+ isBucketBForbiddenSkuPath,
19
+ evaluateSlopsquatCommand,
20
+ evaluateGrepGlobFirewall,
21
+ distillHtmlWebPayload,
22
+ evaluateBlastRadiusBreaker,
23
+ computeFileShingles,
24
+ detectDuplicateClones,
25
+ evaluateHardcodedOracle,
26
+ evaluateOverengineeringDiffGate,
27
+ evaluateSubagentGovernor,
28
+ evaluateVaguePromptAnchor,
29
+ evaluateMcpCliRouter,
30
+ evaluateLspSymbolRouter,
31
+ compileProseRulesToHooks
32
+ } from '../core-isomorphic/guards/bucketBHeuristics.mjs';
33
+
34
+ const CODE_SCAN_EXT_RE = /\.(?:mjs|cjs|js|ts|tsx|jsx)$/i;
35
+ const SKIP_WALK_DIRS = new Set([
36
+ '.git',
37
+ 'node_modules',
38
+ '.agents',
39
+ '.claude',
40
+ 'evaluation_bundles',
41
+ 'dist',
42
+ 'build',
43
+ 'coverage',
44
+ 'experiments'
45
+ ]);
46
+
47
+ const MEM_SHINGLE_CACHE = new Map();
48
+
49
+ export const BUCKET_B_ALPHA_IDS = Object.freeze([
50
+ '#2_GREP_GLOB_FIREWALL',
51
+ '#6_SLOPSQUAT_DEP_GATE',
52
+ '#9_WEB_BOILERPLATE_BUDGETER',
53
+ '#4_BLAST_RADIUS_BREAKER'
54
+ ]);
55
+
56
+ export const BUCKET_B_BETA_IDS = Object.freeze([
57
+ '#8_DUPLICATE_CLONE_DETECTOR',
58
+ '#3B_EVILGENIE_ORACLE',
59
+ '#19_OVERENGINEERING_DIFF_GATE'
60
+ ]);
61
+
62
+ export const BUCKET_B_GAMMA_COACH_IDS = Object.freeze([
63
+ '#5_SUBAGENT_TEAM_GOVERNOR',
64
+ '#13_VAGUE_PROMPT_ANCHOR',
65
+ '#16_MCP_CLI_ROUTER'
66
+ ]);
67
+
68
+ export const BUCKET_B_GAMMA_SHADOW_IDS = Object.freeze(['#17_LSP_SYMBOL_ROUTER']);
69
+ export const BUCKET_B_GAMMA_PREVIEW_IDS = Object.freeze(['#20_PROSE_TO_HOOK_COMPILER']);
70
+
71
+ function isSilentOrOffFlightMode(options = {}) {
72
+ const fm = String(
73
+ options.mode || options.flightMode || options.horizonConfig?.flightMode || ''
74
+ )
75
+ .trim()
76
+ .toUpperCase();
77
+ return fm === 'SILENT' || fm === 'OFF';
78
+ }
79
+
80
+ /**
81
+ * Resolves rollout stage for Sub-Wave B-Alpha (`#2`, `#6`, `#9`, `#4`) — promoted to `'COACH'`
82
+ * by default after achieving `100%` precision and `0%` false-deny SLAs; drops to `'SHADOW'`
83
+ * whenever flight mode is `'SILENT'` or `'OFF'`.
84
+ *
85
+ * @param {object} [options={}]
86
+ * @returns {'SHADOW' | 'COACH' | 'ENFORCE'}
87
+ */
88
+ export function resolveBucketBAlphaStage(options = {}) {
89
+ if (isSilentOrOffFlightMode(options)) return 'SHADOW';
90
+ const raw = String(
91
+ options.bucketBAlphaStage ||
92
+ options.bucketBStage ||
93
+ process.env.CTXTOP_BUCKET_B_ALPHA_MODE ||
94
+ process.env.CTXTOP_BUCKET_B_MODE ||
95
+ options.horizonConfig?.bucketBAlphaMode ||
96
+ options.horizonConfig?.bucketBMode ||
97
+ 'COACH'
98
+ )
99
+ .trim()
100
+ .toUpperCase();
101
+ if (raw === 'SHADOW') return 'SHADOW';
102
+ if (raw === 'ENFORCE') return 'ENFORCE';
103
+ return 'COACH';
104
+ }
105
+
106
+ /**
107
+ * Resolves rollout stage for Sub-Wave B-Beta (`#8`, `#3b`, `#19`) — promoted to `'COACH'`
108
+ * by default; drops to `'SHADOW'` whenever flight mode is `'SILENT'` or `'OFF'`.
109
+ *
110
+ * @param {object} [options={}]
111
+ * @returns {'SHADOW' | 'COACH' | 'ENFORCE'}
112
+ */
113
+ export function resolveBucketBBetaStage(options = {}) {
114
+ if (isSilentOrOffFlightMode(options)) return 'SHADOW';
115
+ const raw = String(
116
+ options.bucketBBetaStage ||
117
+ options.bucketBStage ||
118
+ process.env.CTXTOP_BUCKET_B_BETA_MODE ||
119
+ process.env.CTXTOP_BUCKET_B_MODE ||
120
+ options.horizonConfig?.bucketBBetaMode ||
121
+ options.horizonConfig?.bucketBMode ||
122
+ 'COACH'
123
+ )
124
+ .trim()
125
+ .toUpperCase();
126
+ if (raw === 'SHADOW') return 'SHADOW';
127
+ if (raw === 'ENFORCE') return 'ENFORCE';
128
+ return 'COACH';
129
+ }
130
+
131
+ /**
132
+ * Resolves rollout stage for promoted Sub-Wave B-Gamma guardrails (`#5`, `#13`, `#16`) —
133
+ * promoted to `'COACH'` by default (and `'SHADOW'` whenever flight mode is `'SILENT'` or `'OFF'`).
134
+ *
135
+ * @param {object} [options={}]
136
+ * @returns {'SHADOW' | 'COACH' | 'ENFORCE'}
137
+ */
138
+ export function resolveBucketBGammaCoachStage(options = {}) {
139
+ if (isSilentOrOffFlightMode(options)) return 'SHADOW';
140
+ const raw = String(
141
+ options.bucketBGammaStage ||
142
+ options.bucketBStage ||
143
+ process.env.CTXTOP_BUCKET_B_GAMMA_MODE ||
144
+ process.env.CTXTOP_BUCKET_B_MODE ||
145
+ options.horizonConfig?.bucketBGammaMode ||
146
+ options.horizonConfig?.bucketBMode ||
147
+ 'COACH'
148
+ )
149
+ .trim()
150
+ .toUpperCase();
151
+ if (raw === 'SHADOW') return 'SHADOW';
152
+ if (raw === 'ENFORCE') return 'ENFORCE';
153
+ return 'COACH';
154
+ }
155
+
156
+ /**
157
+ * Resolves the active rollout stage for default-`SHADOW` Sub-Wave B-Gamma guardrails (`#17 LSP_SYMBOL_ROUTER`).
158
+ * Defaults to `'SHADOW'` (`0` prompt tokens, `0` blocks) unless explicitly promoted via `bucketBLspStage` / `bucketBStage`.
159
+ *
160
+ * @param {object} [options={}]
161
+ * @returns {'SHADOW' | 'COACH' | 'ENFORCE'}
162
+ */
163
+ export function resolveBucketBStage(options = {}) {
164
+ if (isSilentOrOffFlightMode(options)) return 'SHADOW';
165
+ const raw = String(
166
+ options.bucketBLspStage ||
167
+ options.bucketBStage ||
168
+ process.env.CTXTOP_BUCKET_B_LSP_MODE ||
169
+ process.env.CTXTOP_BUCKET_B_MODE ||
170
+ options.horizonConfig?.bucketBLspMode ||
171
+ options.horizonConfig?.bucketBMode ||
172
+ 'SHADOW'
173
+ )
174
+ .trim()
175
+ .toUpperCase();
176
+ if (raw === 'COACH') return 'COACH';
177
+ if (raw === 'ENFORCE') return 'ENFORCE';
178
+ return 'SHADOW';
179
+ }
180
+
181
+ /**
182
+ * Loads pre-verified offline CLI authentication/installation metadata from
183
+ * `<cwd>/.agents/telemetry/cli_capabilities.json` merged with `horizonConfig` / `options`.
184
+ * Zero subprocess spawns and zero network requests.
185
+ *
186
+ * @param {string} cwd
187
+ * @param {object} [options={}]
188
+ * @returns {Record<string, { installed?: boolean, authValid?: boolean, authExpired?: boolean }>}
189
+ */
190
+ export function loadVerifiedCliCapabilities(cwd, options = {}) {
191
+ let diskCaps = {};
192
+ if (cwd) {
193
+ const capPath = path.join(path.resolve(cwd), '.agents', 'telemetry', 'cli_capabilities.json');
194
+ if (fs.existsSync(capPath)) {
195
+ try {
196
+ const parsed = JSON.parse(fs.readFileSync(capPath, 'utf8'));
197
+ if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
198
+ diskCaps = parsed;
199
+ }
200
+ } catch (_err) {
201
+ diskCaps = {};
202
+ }
203
+ }
204
+ }
205
+ const cfgCaps =
206
+ options?.horizonConfig?.cliCapabilities &&
207
+ typeof options.horizonConfig.cliCapabilities === 'object'
208
+ ? options.horizonConfig.cliCapabilities
209
+ : {};
210
+ const optCaps =
211
+ options?.cliCapabilities && typeof options.cliCapabilities === 'object'
212
+ ? options.cliCapabilities
213
+ : {};
214
+ return { ...diskCaps, ...cfgCaps, ...optCaps };
215
+ }
216
+
217
+ /**
218
+ * Loads existing package manifest dependencies, monorepo workspace names, and private `.npmrc` scopes
219
+ * from `cwd` (`< 3ms`, strictly offline and SKU-isolated).
220
+ *
221
+ * @param {string} cwd
222
+ * @returns {{ manifestDeps: Set<string>, workspacePackages: Set<string>, privateScopes: Set<string> }}
223
+ */
224
+ export function loadWorkspacePackageAllowlist(cwd) {
225
+ const baseCwd = path.resolve(cwd || process.cwd());
226
+ const manifestDeps = new Set();
227
+ const workspacePackages = new Set();
228
+ const privateScopes = new Set();
229
+
230
+ // 1. Root package.json
231
+ const pkgJsonPath = path.join(baseCwd, 'package.json');
232
+ if (fs.existsSync(pkgJsonPath)) {
233
+ try {
234
+ const pkg = JSON.parse(fs.readFileSync(pkgJsonPath, 'utf8'));
235
+ if (pkg.name) {
236
+ workspacePackages.add(String(pkg.name).toLowerCase());
237
+ if (String(pkg.name).startsWith('@')) {
238
+ const slashIdx = String(pkg.name).indexOf('/');
239
+ if (slashIdx > 1) privateScopes.add(String(pkg.name).slice(0, slashIdx).toLowerCase());
240
+ }
241
+ }
242
+ for (const field of [
243
+ 'dependencies',
244
+ 'devDependencies',
245
+ 'peerDependencies',
246
+ 'optionalDependencies'
247
+ ]) {
248
+ const map = pkg[field];
249
+ if (map && typeof map === 'object') {
250
+ for (const depName of Object.keys(map)) {
251
+ manifestDeps.add(depName.toLowerCase());
252
+ }
253
+ }
254
+ }
255
+ const wsList = Array.isArray(pkg.workspaces)
256
+ ? pkg.workspaces
257
+ : Array.isArray(pkg.workspaces?.packages)
258
+ ? pkg.workspaces.packages
259
+ : [];
260
+ for (const wsRel of wsList) {
261
+ const cleanRel = String(wsRel || '').replace(/\/\*+$/, '');
262
+ if (!cleanRel || isBucketBForbiddenSkuPath(cleanRel)) continue;
263
+ const wsPkgPath = path.join(baseCwd, cleanRel, 'package.json');
264
+ if (fs.existsSync(wsPkgPath)) {
265
+ try {
266
+ const wsPkg = JSON.parse(fs.readFileSync(wsPkgPath, 'utf8'));
267
+ if (wsPkg.name) {
268
+ workspacePackages.add(String(wsPkg.name).toLowerCase());
269
+ if (String(wsPkg.name).startsWith('@')) {
270
+ const idx = String(wsPkg.name).indexOf('/');
271
+ if (idx > 1) privateScopes.add(String(wsPkg.name).slice(0, idx).toLowerCase());
272
+ }
273
+ }
274
+ } catch (_err) {
275
+ // Skip unreadable workspace manifest
276
+ }
277
+ }
278
+ }
279
+ } catch (_err) {
280
+ // Skip malformed package.json
281
+ }
282
+ }
283
+
284
+ // 2. Project `.npmrc` private scopes (`@corp:registry=https://...`) — never reads auth tokens
285
+ const npmrcPath = path.join(baseCwd, '.npmrc');
286
+ if (fs.existsSync(npmrcPath)) {
287
+ try {
288
+ const lines = fs.readFileSync(npmrcPath, 'utf8').split(/\r?\n/);
289
+ for (const line of lines) {
290
+ const m = line.trim().match(/^(@[a-z0-9._-]+):registry\s*=/i);
291
+ if (m) privateScopes.add(m[1].toLowerCase());
292
+ }
293
+ } catch (_err) {
294
+ // Non-fatal
295
+ }
296
+ }
297
+
298
+ // 3. Python `requirements.txt` / `pyproject.toml` if present
299
+ const reqPath = path.join(baseCwd, 'requirements.txt');
300
+ if (fs.existsSync(reqPath)) {
301
+ try {
302
+ const lines = fs.readFileSync(reqPath, 'utf8').split(/\r?\n/);
303
+ for (const l of lines) {
304
+ const trimmed = l.trim();
305
+ if (!trimmed || trimmed.startsWith('#') || trimmed.startsWith('-')) continue;
306
+ const base = trimmed.split(/[=<>~!;\s[]/)[0].trim().toLowerCase().replace(/_/g, '-');
307
+ if (base) manifestDeps.add(base);
308
+ }
309
+ } catch (_err) {
310
+ // Non-fatal
311
+ }
312
+ }
313
+
314
+ return { manifestDeps, workspacePackages, privateScopes };
315
+ }
316
+
317
+ /**
318
+ * Walks SKU-allowed source directories (`src`, `hooks`, `bin` by default) to build or refresh
319
+ * `.agents/telemetry/shingle_index.json` for `#8 DUPLICATE_CLONE_DETECTOR`.
320
+ *
321
+ * @param {string} cwd
322
+ * @param {object} [options={}]
323
+ * @param {string[]} [options.scanDirs=['src', 'hooks']]
324
+ * @param {boolean} [options.persist=true]
325
+ */
326
+ export function buildOrLoadWorkspaceShingleIndex(cwd, options = {}) {
327
+ const baseCwd = path.resolve(cwd || process.cwd());
328
+ const scanDirs = Array.isArray(options.scanDirs) ? options.scanDirs : ['src', 'hooks'];
329
+ const indexPath = path.join(baseCwd, '.agents', 'telemetry', 'shingle_index.json');
330
+
331
+ let cachedFiles = {};
332
+ if (options.useCache !== false) {
333
+ const memCached = MEM_SHINGLE_CACHE.get(baseCwd);
334
+ if (memCached && memCached.files && typeof memCached.files === 'object') {
335
+ cachedFiles = memCached.files;
336
+ } else if (fs.existsSync(indexPath)) {
337
+ try {
338
+ const parsed = JSON.parse(fs.readFileSync(indexPath, 'utf8'));
339
+ if (parsed && parsed.version === 1 && parsed.files && typeof parsed.files === 'object') {
340
+ cachedFiles = parsed.files;
341
+ }
342
+ } catch (_err) {
343
+ cachedFiles = {};
344
+ }
345
+ }
346
+ }
347
+
348
+ const nextFiles = {};
349
+ const postings = {};
350
+
351
+ const addFilePostings = (relNorm, shingles) => {
352
+ for (const sh of shingles) {
353
+ if (!postings[sh.hash]) postings[sh.hash] = [];
354
+ postings[sh.hash].push({ file: relNorm, startLine: sh.startLine });
355
+ }
356
+ };
357
+
358
+ const walk = (absDir) => {
359
+ if (!fs.existsSync(absDir)) return;
360
+ let entries = [];
361
+ try {
362
+ entries = fs.readdirSync(absDir, { withFileTypes: true });
363
+ } catch (_err) {
364
+ return;
365
+ }
366
+ for (const ent of entries) {
367
+ if (SKIP_WALK_DIRS.has(ent.name)) continue;
368
+ const fullPath = path.join(absDir, ent.name);
369
+ const relNorm = path.relative(baseCwd, fullPath).replace(/\\/g, '/');
370
+ if (isBucketBForbiddenSkuPath(relNorm)) continue;
371
+
372
+ if (ent.isDirectory()) {
373
+ walk(fullPath);
374
+ } else if (ent.isFile() && CODE_SCAN_EXT_RE.test(ent.name)) {
375
+ if (options.useCache !== false) {
376
+ let stat;
377
+ try {
378
+ stat = fs.statSync(fullPath);
379
+ } catch (_err) {
380
+ continue;
381
+ }
382
+ const prev = cachedFiles[relNorm];
383
+ if (
384
+ prev &&
385
+ prev.mtimeMs === stat.mtimeMs &&
386
+ prev.size === stat.size &&
387
+ Array.isArray(prev.shingles)
388
+ ) {
389
+ nextFiles[relNorm] = prev;
390
+ addFilePostings(relNorm, prev.shingles);
391
+ continue;
392
+ }
393
+ try {
394
+ const content = fs.readFileSync(fullPath, 'utf8');
395
+ const shingles = computeFileShingles(content, 5);
396
+ nextFiles[relNorm] = { mtimeMs: stat.mtimeMs, size: stat.size, shingles };
397
+ addFilePostings(relNorm, shingles);
398
+ } catch (_err) {
399
+ // Skip unreadable file
400
+ }
401
+ } else {
402
+ try {
403
+ const content = fs.readFileSync(fullPath, 'utf8');
404
+ const shingles = computeFileShingles(content, 5);
405
+ nextFiles[relNorm] = { mtimeMs: 0, size: content.length, shingles };
406
+ addFilePostings(relNorm, shingles);
407
+ } catch (_err) {
408
+ // Skip unreadable file
409
+ }
410
+ }
411
+ }
412
+ }
413
+ };
414
+
415
+ for (const relDir of scanDirs) {
416
+ if (isBucketBForbiddenSkuPath(relDir)) continue;
417
+ walk(path.join(baseCwd, relDir));
418
+ }
419
+
420
+ const indexState = {
421
+ version: 1,
422
+ files: nextFiles,
423
+ postings
424
+ };
425
+
426
+ if (options.useCache !== false) {
427
+ if (!MEM_SHINGLE_CACHE.has(baseCwd) && MEM_SHINGLE_CACHE.size >= 8) {
428
+ const oldestKey = MEM_SHINGLE_CACHE.keys().next().value;
429
+ if (oldestKey !== undefined) MEM_SHINGLE_CACHE.delete(oldestKey);
430
+ }
431
+ MEM_SHINGLE_CACHE.set(baseCwd, { files: nextFiles, postings });
432
+ }
433
+
434
+ if (options.persist !== false) {
435
+ try {
436
+ fs.mkdirSync(path.dirname(indexPath), { recursive: true });
437
+ fs.writeFileSync(indexPath, JSON.stringify({ version: 1, files: nextFiles }), 'utf8');
438
+ } catch (_err) {
439
+ // Non-fatal cache write
440
+ }
441
+ }
442
+
443
+ return indexState;
444
+ }
445
+
446
+ /**
447
+ * Parallel libuv file-reader variant of `buildOrLoadWorkspaceShingleIndex` (`< 25ms` cold on Windows NTFS).
448
+ *
449
+ * @param {string} cwd
450
+ * @param {object} [options={}]
451
+ */
452
+ export async function buildOrLoadWorkspaceShingleIndexAsync(cwd, options = {}) {
453
+ const baseCwd = path.resolve(cwd || process.cwd());
454
+ const scanDirs = Array.isArray(options.scanDirs) ? options.scanDirs : ['src', 'hooks'];
455
+ const indexPath = path.join(baseCwd, '.agents', 'telemetry', 'shingle_index.json');
456
+
457
+ const candidateFiles = [];
458
+ const walk = (absDir) => {
459
+ if (!fs.existsSync(absDir)) return;
460
+ let entries = [];
461
+ try {
462
+ entries = fs.readdirSync(absDir, { withFileTypes: true });
463
+ } catch (_err) {
464
+ return;
465
+ }
466
+ for (const ent of entries) {
467
+ if (SKIP_WALK_DIRS.has(ent.name)) continue;
468
+ const fullPath = path.join(absDir, ent.name);
469
+ const relNorm = path.relative(baseCwd, fullPath).replace(/\\/g, '/');
470
+ if (isBucketBForbiddenSkuPath(relNorm)) continue;
471
+ if (ent.isDirectory()) walk(fullPath);
472
+ else if (ent.isFile() && CODE_SCAN_EXT_RE.test(ent.name)) {
473
+ candidateFiles.push({ fullPath, relNorm });
474
+ }
475
+ }
476
+ };
477
+
478
+ for (const relDir of scanDirs) {
479
+ if (isBucketBForbiddenSkuPath(relDir)) continue;
480
+ walk(path.join(baseCwd, relDir));
481
+ }
482
+
483
+ const contents = await Promise.all(
484
+ candidateFiles.map(async (f) => {
485
+ try {
486
+ const text = await fs.promises.readFile(f.fullPath, 'utf8');
487
+ return { relNorm: f.relNorm, text };
488
+ } catch (_err) {
489
+ return null;
490
+ }
491
+ })
492
+ );
493
+
494
+ const nextFiles = {};
495
+ const postings = {};
496
+ for (const item of contents) {
497
+ if (!item) continue;
498
+ const shingles = computeFileShingles(item.text, 5);
499
+ nextFiles[item.relNorm] = { mtimeMs: 0, size: item.text.length, shingles };
500
+ for (const sh of shingles) {
501
+ if (!postings[sh.hash]) postings[sh.hash] = [];
502
+ postings[sh.hash].push({ file: item.relNorm, startLine: sh.startLine });
503
+ }
504
+ }
505
+
506
+ if (options.persist === true) {
507
+ try {
508
+ await fs.promises.mkdir(path.dirname(indexPath), { recursive: true });
509
+ await fs.promises.writeFile(indexPath, JSON.stringify({ version: 1, files: nextFiles }), 'utf8');
510
+ } catch (_err) {
511
+ // Non-fatal
512
+ }
513
+ }
514
+
515
+ return { version: 1, files: nextFiles, postings };
516
+ }
517
+
518
+ /**
519
+ * Incrementally updates a single file inside an in-memory shingle index in `< 3ms`.
520
+ *
521
+ * @param {{ files: Record<string, any>, postings: Record<string, Array<{ file: string, startLine: number }>> }} indexState
522
+ * @param {string} relPath
523
+ * @param {string} newContent
524
+ */
525
+ export function updateFileInShingleIndex(indexState, relPath, newContent = '') {
526
+ const relNorm = String(relPath || '').replace(/\\/g, '/').replace(/^\.\//, '');
527
+ if (!indexState || !relNorm || isBucketBForbiddenSkuPath(relNorm)) return indexState;
528
+
529
+ const prev = indexState.files?.[relNorm];
530
+ if (prev && Array.isArray(prev.shingles)) {
531
+ for (const sh of prev.shingles) {
532
+ const arr = indexState.postings[sh.hash];
533
+ if (Array.isArray(arr)) {
534
+ const filtered = arr.filter((p) => p.file !== relNorm);
535
+ if (filtered.length > 0) indexState.postings[sh.hash] = filtered;
536
+ else delete indexState.postings[sh.hash];
537
+ }
538
+ }
539
+ }
540
+
541
+ const shingles = computeFileShingles(newContent, 5);
542
+ indexState.files[relNorm] = {
543
+ mtimeMs: Date.now(),
544
+ size: Buffer.byteLength(newContent, 'utf8'),
545
+ shingles
546
+ };
547
+ for (const sh of shingles) {
548
+ if (!indexState.postings[sh.hash]) indexState.postings[sh.hash] = [];
549
+ indexState.postings[sh.hash].push({ file: relNorm, startLine: sh.startLine });
550
+ }
551
+ return indexState;
552
+ }
553
+
554
+ /**
555
+ * Scans workspace `AGENTS.md` and `CLAUDE.md` files for `#20 PROSE_TO_HOOK_COMPILER` preview candidates
556
+ * (`ctxtop doctor` top-level diagnostic property; `0` live hook mutations).
557
+ *
558
+ * @param {string} cwd
559
+ */
560
+ export function auditProseRuleHookCandidates(cwd) {
561
+ const baseCwd = path.resolve(cwd || process.cwd());
562
+ const ruleFiles = ['AGENTS.md', 'CLAUDE.md', '.claude/CLAUDE.md'];
563
+ const allCandidates = [];
564
+ const allSkippedConditional = [];
565
+
566
+ for (const rel of ruleFiles) {
567
+ const abs = path.join(baseCwd, rel);
568
+ if (!fs.existsSync(abs)) continue;
569
+ try {
570
+ const content = fs.readFileSync(abs, 'utf8');
571
+ const compiled = compileProseRulesToHooks(content, { sourceFile: rel });
572
+ allCandidates.push(...compiled.candidates);
573
+ allSkippedConditional.push(...compiled.skippedConditional);
574
+ } catch (_err) {
575
+ // Non-fatal
576
+ }
577
+ }
578
+
579
+ return {
580
+ candidateCount: allCandidates.length,
581
+ skippedConditionalCount: allSkippedConditional.length,
582
+ candidates: allCandidates,
583
+ skippedConditional: allSkippedConditional
584
+ };
585
+ }
586
+
587
+ /**
588
+ * Evaluates applicable Bucket B guardrails on an incoming `PreToolUse` / `pre_invocation` event.
589
+ * Sub-Waves B-Alpha (`#6`, `#4`) & B-Beta (`#8`, `#3b`) run in `'COACH'` mode by default
590
+ * (`'SHADOW'` in `SILENT`/`OFF`); Sub-Wave B-Gamma defaults to `'SHADOW'` (`0` stdout, `.hints.jsonl`).
591
+ *
592
+ * @param {object} params
593
+ * @param {'claude' | 'antigravity'} [params.platform='claude']
594
+ * @param {string} [params.sessionId='default']
595
+ * @param {string} [params.cwd]
596
+ * @param {boolean} [params.hasExplicitCwd]
597
+ * @param {string} [params.toolName='']
598
+ * @param {object} [params.toolInput={}]
599
+ * @param {string} [params.lastUserPrompt='']
600
+ * @param {Array<{ filePath: string, netLines?: number, changedLines?: string[] }>} [params.editsSinceVerify=[]]
601
+ * @param {object} [params.options={}]
602
+ */
603
+ export function runBucketBPreToolShadowPass(params = {}) {
604
+ const platform = params.platform === 'antigravity' ? 'antigravity' : 'claude';
605
+ const sessionId = params.sessionId || 'default';
606
+ const hasExplicitCwd = params.hasExplicitCwd !== false && Boolean(params.cwd);
607
+ const baseCwd = hasExplicitCwd ? path.resolve(params.cwd) : process.cwd();
608
+ const alphaStage = resolveBucketBAlphaStage(params.options);
609
+ const betaStage = resolveBucketBBetaStage(params.options);
610
+ const gammaCoachStage = resolveBucketBGammaCoachStage(params.options);
611
+ const gammaShadowStage = resolveBucketBStage(params.options);
612
+ const toolName = String(params.toolName || '');
613
+ const tIn = params.toolInput || {};
614
+ const recorded = [];
615
+ const activeRecords = [];
616
+
617
+ const emit = (guardrailId, verdict, elapsedMs, itemStage = gammaShadowStage) => {
618
+ if (!verdict?.triggered) return;
619
+ if (hasExplicitCwd) {
620
+ recordBucketBShadowHint(
621
+ sessionId,
622
+ {
623
+ guardrailId,
624
+ stage: itemStage,
625
+ platform,
626
+ wouldTrigger: true,
627
+ wouldDecision: verdict.decision || 'warn',
628
+ latencyMs: elapsedMs,
629
+ tokens_saved_est: verdict.tokensSavedEst || 0,
630
+ dollars_saved_est: Number((((verdict.tokensSavedEst || 0) / 1_000_000) * 3.0).toFixed(6)),
631
+ evidence: {
632
+ code: verdict.code || guardrailId,
633
+ reason: String(verdict.reason || '').slice(0, 220)
634
+ }
635
+ },
636
+ { cwd: baseCwd }
637
+ );
638
+ }
639
+ const entry = { guardrailId, stage: itemStage, verdict };
640
+ recorded.push(entry);
641
+ if (itemStage !== 'SHADOW') {
642
+ activeRecords.push(entry);
643
+ }
644
+ };
645
+
646
+ // #6 SLOPSQUAT_DEP_GATE (Sub-Wave B-Alpha -> default COACH) on shell install commands
647
+ if (/^(?:Bash|PowerShell|run_command)$/i.test(toolName)) {
648
+ const command = String(tIn.command || tIn.CommandLine || tIn.cmd || '');
649
+ if (/\b(?:npm|pnpm|yarn|bun|pip3?|uv|poetry|cargo)\b/i.test(command)) {
650
+ const t0 = performance.now();
651
+ const allowlist = hasExplicitCwd
652
+ ? loadWorkspacePackageAllowlist(baseCwd)
653
+ : { manifestDeps: new Set(), workspacePackages: new Set(), privateScopes: new Set() };
654
+ const verdict = evaluateSlopsquatCommand({
655
+ command,
656
+ ...allowlist,
657
+ registryMetadata: params.options?.registryMetadata
658
+ });
659
+ emit('#6_SLOPSQUAT_DEP_GATE', verdict, performance.now() - t0, alphaStage);
660
+ }
661
+ }
662
+
663
+ // #4 BLAST_RADIUS_BREAKER (B-Alpha -> COACH) & #3b Hardcoded Oracle / #8 Duplicate Clone (B-Beta -> COACH)
664
+ if (
665
+ /^(?:Edit|MultiEdit|Write|edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content)$/i.test(
666
+ toolName
667
+ )
668
+ ) {
669
+ const filePath = String(
670
+ tIn.file_path || tIn.Path || tIn.path || tIn.TargetFile || tIn.AbsolutePath || ''
671
+ );
672
+ const absTarget = filePath
673
+ ? (path.isAbsolute(filePath) ? path.resolve(filePath) : path.resolve(baseCwd, filePath))
674
+ : '';
675
+ const relFromCwd = absTarget ? path.relative(baseCwd, absTarget).replace(/\\/g, '/') : '';
676
+ const relTargetPath =
677
+ relFromCwd && !relFromCwd.startsWith('..') && !path.isAbsolute(relFromCwd)
678
+ ? relFromCwd
679
+ : filePath.replace(/\\/g, '/').replace(/^\.\//, '');
680
+
681
+ const addedCode = String(
682
+ tIn.new_string ??
683
+ tIn.Replacement ??
684
+ tIn.ReplacementContent ??
685
+ tIn.content ??
686
+ tIn.Content ??
687
+ tIn.CodeContent ??
688
+ (Array.isArray(tIn.edits)
689
+ ? tIn.edits.map((e) => e?.new_string ?? '').join('\n')
690
+ : Array.isArray(tIn.ReplacementChunks)
691
+ ? tIn.ReplacementChunks.map((c) => c?.ReplacementContent ?? c?.Replacement ?? '').join('\n')
692
+ : '') ??
693
+ ''
694
+ );
695
+
696
+ if (filePath) {
697
+ const tBlast = performance.now();
698
+ const changedLines = addedCode.split(/\r?\n/);
699
+ const netLines = changedLines.filter((l) => l.trim().length > 0).length;
700
+ const priorEdits = Array.isArray(params.editsSinceVerify) ? params.editsSinceVerify : [];
701
+ const editsSinceVerify = [...priorEdits, { filePath: relTargetPath || filePath, netLines, changedLines }];
702
+ const blastVerdict = evaluateBlastRadiusBreaker({
703
+ editsSinceVerify,
704
+ lastUserPrompt: params.lastUserPrompt || ''
705
+ });
706
+ if (blastVerdict.triggered) {
707
+ blastVerdict.decision = alphaStage === 'ENFORCE' ? 'ask' : 'warn';
708
+ }
709
+ emit('#4_BLAST_RADIUS_BREAKER', blastVerdict, performance.now() - tBlast, alphaStage);
710
+ }
711
+
712
+ if (relTargetPath && addedCode.length >= 60) {
713
+ const t0 = performance.now();
714
+ const verdict = evaluateHardcodedOracle({ filePath: relTargetPath, addedCode });
715
+ if (verdict.triggered) {
716
+ verdict.decision = betaStage === 'ENFORCE' ? 'ask' : 'warn';
717
+ }
718
+ emit('#3B_EVILGENIE_ORACLE', verdict, performance.now() - t0, betaStage);
719
+ }
720
+
721
+ if (
722
+ relTargetPath &&
723
+ addedCode.length >= 100 &&
724
+ CODE_SCAN_EXT_RE.test(relTargetPath) &&
725
+ !isBucketBForbiddenSkuPath(relTargetPath) &&
726
+ computeFileShingles(addedCode, 5).length >= 2
727
+ ) {
728
+ const tClone = performance.now();
729
+ const postings =
730
+ params.options?.shingleIndex ||
731
+ (hasExplicitCwd
732
+ ? buildOrLoadWorkspaceShingleIndex(baseCwd, {
733
+ useCache: true,
734
+ persist: params.options?.persistState !== false
735
+ }).postings
736
+ : {});
737
+ const cloneVerdict = detectDuplicateClones({
738
+ targetPath: relTargetPath,
739
+ addedCode,
740
+ shingleIndex: postings
741
+ });
742
+ if (cloneVerdict.triggered) {
743
+ cloneVerdict.decision = betaStage === 'ENFORCE' ? 'ask' : 'warn';
744
+ }
745
+ emit('#8_DUPLICATE_CLONE_DETECTOR', cloneVerdict, performance.now() - tClone, betaStage);
746
+ }
747
+ }
748
+
749
+ // #5 SUBAGENT_TEAM_GOVERNOR (Sub-Wave B-Gamma -> promoted COACH) on subagent/task spawns
750
+ if (
751
+ /^(?:Task|Agent|invoke_subagent)$/i.test(toolName) ||
752
+ (/^swarm$/i.test(toolName) && String(tIn.action || 'add').toLowerCase() === 'add')
753
+ ) {
754
+ const t0 = performance.now();
755
+ const verdict = evaluateSubagentGovernor({
756
+ typeName: tIn.subagent_type || tIn.TypeName || tIn.name || '',
757
+ role: tIn.description || tIn.Role || '',
758
+ prompt: tIn.prompt || tIn.Prompt || tIn.brief || '',
759
+ model: tIn.model || tIn.Model || 'inherit',
760
+ enableWriteTools: tIn.EnableWriteTools,
761
+ allowedTools: tIn.allowed_tools || tIn.tools,
762
+ workspace: tIn.isolation || tIn.Workspace || tIn.workspace || 'inherit'
763
+ });
764
+ if (verdict.triggered) {
765
+ verdict.decision = gammaCoachStage === 'ENFORCE' ? 'ask' : 'warn';
766
+ }
767
+ emit('#5_SUBAGENT_TEAM_GOVERNOR', verdict, performance.now() - t0, gammaCoachStage);
768
+ }
769
+
770
+ // #16 MCP_CLI_ROUTER (Sub-Wave B-Gamma -> capability-gated COACH) on heavy MCP read tools
771
+ let normalizedMcpToolName = '';
772
+ if (/^mcp__([a-z0-9_-]+)__([a-z0-9_-]+)$/i.test(toolName)) {
773
+ normalizedMcpToolName = toolName;
774
+ } else if (/^call_mcp_tool$/i.test(toolName)) {
775
+ const srv = String(tIn.ServerName || tIn.serverName || '').trim();
776
+ const tName = String(tIn.ToolName || tIn.toolName || '').trim();
777
+ if (srv && tName) {
778
+ normalizedMcpToolName = `mcp__${srv}__${tName}`;
779
+ }
780
+ } else {
781
+ const eagerMcpMatch = toolName.match(
782
+ /^mcp_(github|gh|aws|gcloud|sentry|kubectl|kubernetes)_([a-z0-9_-]+)$/i
783
+ );
784
+ if (eagerMcpMatch) {
785
+ normalizedMcpToolName = `mcp__${eagerMcpMatch[1]}__${eagerMcpMatch[2]}`;
786
+ }
787
+ }
788
+ if (normalizedMcpToolName) {
789
+ const t0 = performance.now();
790
+ const cliCapabilities = loadVerifiedCliCapabilities(
791
+ hasExplicitCwd ? baseCwd : '',
792
+ params.options
793
+ );
794
+ const verdict = evaluateMcpCliRouter({
795
+ toolName: normalizedMcpToolName,
796
+ cliCapabilities
797
+ });
798
+ if (verdict.triggered) {
799
+ verdict.decision = gammaCoachStage === 'ENFORCE' ? 'ask' : 'warn';
800
+ }
801
+ emit('#16_MCP_CLI_ROUTER', verdict, performance.now() - t0, gammaCoachStage);
802
+ }
803
+
804
+ // #17 LSP_SYMBOL_ROUTER (Sub-Wave B-Gamma -> default SHADOW, opt-in via lspCapabilities)
805
+ if (/^(?:Grep|grep_search|Read|read_file|view_file)$/i.test(toolName)) {
806
+ const lspCaps =
807
+ params.options?.lspCapabilities || params.options?.horizonConfig?.lspCapabilities || null;
808
+ if (lspCaps && lspCaps.lspToolEnabled === true) {
809
+ const t0 = performance.now();
810
+ const verdict = evaluateLspSymbolRouter({
811
+ symbol: String(tIn.pattern || tIn.Query || tIn.symbol || '').trim(),
812
+ filePath: String(tIn.path || tIn.SearchPath || tIn.file_path || tIn.Path || '').trim(),
813
+ symbolLookupCount: Number(tIn.symbolLookupCount ?? lspCaps.symbolLookupCount ?? 0),
814
+ lspToolEnabled: true,
815
+ activeExtensions: lspCaps.activeExtensions || []
816
+ });
817
+ if (verdict.triggered) {
818
+ verdict.decision = gammaShadowStage === 'ENFORCE' ? 'ask' : 'warn';
819
+ }
820
+ emit('#17_LSP_SYMBOL_ROUTER', verdict, performance.now() - t0, gammaShadowStage);
821
+ }
822
+ }
823
+
824
+ // Expose other runtime-callable evaluators for PostToolUse / UserPromptSubmit / tests
825
+ return {
826
+ stage: gammaShadowStage,
827
+ gammaCoachStage,
828
+ alphaStage,
829
+ betaStage,
830
+ shadowOnly:
831
+ alphaStage === 'SHADOW' &&
832
+ betaStage === 'SHADOW' &&
833
+ gammaCoachStage === 'SHADOW' &&
834
+ gammaShadowStage === 'SHADOW',
835
+ triggered: activeRecords.length > 0,
836
+ activeRecords,
837
+ recorded,
838
+ evaluators: {
839
+ evaluateGrepGlobFirewall,
840
+ distillHtmlWebPayload,
841
+ evaluateBlastRadiusBreaker,
842
+ detectDuplicateClones,
843
+ evaluateOverengineeringDiffGate,
844
+ evaluateVaguePromptAnchor,
845
+ evaluateLspSymbolRouter
846
+ }
847
+ };
848
+ }
849
+
850
+ function parseSearchOutputPath(line = '') {
851
+ const trimmed = String(line || '').replace(/\r$/, '').trim();
852
+ if (!trimmed || trimmed === '--' || /^Found\s+\d+\s+(?:results?|files?|matches?)/i.test(trimmed)) {
853
+ return null;
854
+ }
855
+ // Match `dir/file.ext:12:snippet` or `C:\dir\file.ext:12-snippet`
856
+ const lineNumMatch = trimmed.match(
857
+ /^((?:[A-Za-z]:[\\/])?[^:\s][^:]*?\.[A-Za-z0-9]{1,8}):\d+(?:[:\-]|$)/
858
+ );
859
+ if (lineNumMatch) return lineNumMatch[1];
860
+
861
+ // Match `dir/file.ext: snippet`
862
+ const colonSnippetMatch = trimmed.match(
863
+ /^((?:[A-Za-z]:[\\/])?[^:\s][^:]*?(?:[\\/][^:\s]+|\.[A-Za-z0-9]{1,8})):\s/
864
+ );
865
+ if (colonSnippetMatch) return colonSnippetMatch[1];
866
+
867
+ // Plain file path per line (requires `/` or `\` or extension, and no internal whitespace)
868
+ if (!/\s/.test(trimmed) && (/[\\/]/.test(trimmed) || /\.[A-Za-z0-9]{1,8}$/.test(trimmed))) {
869
+ return trimmed;
870
+ }
871
+ return null;
872
+ }
873
+
874
+ /**
875
+ * Evaluates Sub-Wave B-Alpha `PostToolUse` / `post_invocation` guardrails:
876
+ * - `#9 WEB_BOILERPLATE_BUDGETER` (lossless HTML `<pre>`/`<code>`/`<table>` distillation)
877
+ * - `#2 GREP_GLOB_FIREWALL` (active-context Top-K ranking for `>15` matched search files)
878
+ *
879
+ * Runs in `'COACH'` mode by default (`'SHADOW'` in `SILENT`/`OFF` modes) and records
880
+ * `.hints.jsonl` telemetry when `hasExplicitCwd` is true.
881
+ *
882
+ * @param {object} [params={}]
883
+ */
884
+ export function runBucketBPostToolPass(params = {}) {
885
+ const platform = params.platform === 'antigravity' ? 'antigravity' : 'claude';
886
+ const sessionId = params.sessionId || 'default';
887
+ const hasExplicitCwd = Boolean(params.hasExplicitCwd && params.cwd);
888
+ const baseCwd = hasExplicitCwd ? path.resolve(params.cwd) : process.cwd();
889
+ const alphaStage = resolveBucketBAlphaStage(params.options);
890
+ const toolName = String(params.toolName || '');
891
+ const tIn = params.toolInput || {};
892
+ const rawOutput = typeof params.rawOutput === 'string' ? params.rawOutput : String(params.rawOutput ?? '');
893
+
894
+ // 1. #9 WEB_BOILERPLATE_BUDGETER
895
+ if (
896
+ /^(?:WebFetch|read_url_content|mcp__(?:fetch|firecrawl|playwright|puppeteer|browser).*)$/i.test(
897
+ toolName
898
+ ) &&
899
+ rawOutput.length >= 1200 &&
900
+ /<(?:html|body|div|table|script|style|nav|header|footer|article|main|section|pre|code)\b/i.test(
901
+ rawOutput
902
+ )
903
+ ) {
904
+ const t0 = performance.now();
905
+ const verdict = distillHtmlWebPayload({
906
+ html: rawOutput,
907
+ webFetchesInTurn: Number(params.webFetchesInTurn) || 1
908
+ });
909
+ const elapsedMs = performance.now() - t0;
910
+ if (verdict.triggered) {
911
+ if (hasExplicitCwd) {
912
+ recordBucketBShadowHint(
913
+ sessionId,
914
+ {
915
+ guardrailId: '#9_WEB_BOILERPLATE_BUDGETER',
916
+ stage: alphaStage,
917
+ platform,
918
+ wouldTrigger: true,
919
+ wouldDecision: 'warn',
920
+ latencyMs: elapsedMs,
921
+ tokens_saved_est: verdict.tokensSavedEst || 0,
922
+ dollars_saved_est: Number((((verdict.tokensSavedEst || 0) / 1_000_000) * 3.0).toFixed(6)),
923
+ evidence: {
924
+ code: verdict.code || 'WEB_BOILERPLATE_BUDGETER',
925
+ reason: String(verdict.reason || '').slice(0, 220)
926
+ }
927
+ },
928
+ { cwd: baseCwd }
929
+ );
930
+ }
931
+ if (alphaStage !== 'SHADOW') {
932
+ return {
933
+ triggered: true,
934
+ stage: alphaStage,
935
+ guardrailId: '#9_WEB_BOILERPLATE_BUDGETER',
936
+ code: verdict.code || 'WEB_BOILERPLATE_BUDGETER',
937
+ updatedOutput: `${verdict.reason}\n\n${verdict.distilled}`,
938
+ savedTokens: verdict.tokensSavedEst || 0,
939
+ reason: verdict.reason
940
+ };
941
+ }
942
+ }
943
+ }
944
+
945
+ // 2. #2 GREP_GLOB_FIREWALL
946
+ if (/^(?:Grep|Glob|grep_search|find_by_name)$/i.test(toolName) && rawOutput) {
947
+ const t0 = performance.now();
948
+ const lines = rawOutput.split(/\r?\n/);
949
+ const linesByPath = new Map();
950
+ const matchPaths = [];
951
+
952
+ for (const rawLine of lines) {
953
+ const candidate = parseSearchOutputPath(rawLine);
954
+ if (!candidate) continue;
955
+ const norm = candidate.replace(/\\/g, '/').replace(/^\.\//, '');
956
+ if (!norm || isBucketBForbiddenSkuPath(norm)) continue;
957
+ if (!linesByPath.has(norm)) {
958
+ linesByPath.set(norm, []);
959
+ matchPaths.push(norm);
960
+ }
961
+ linesByPath.get(norm).push(rawLine.replace(/\r$/, ''));
962
+ }
963
+
964
+ if (matchPaths.length > 15) {
965
+ const query = String(tIn.pattern || tIn.Query || tIn.Pattern || '');
966
+ const verdict = evaluateGrepGlobFirewall({
967
+ matchPaths,
968
+ query,
969
+ lastUserPrompt: params.lastUserPrompt || '',
970
+ activeFiles: params.activeFiles || [],
971
+ dirtyFiles: params.dirtyFiles || [],
972
+ lastEditedFile: params.lastEditedFile || ''
973
+ });
974
+ const elapsedMs = performance.now() - t0;
975
+
976
+ if (verdict.triggered) {
977
+ if (hasExplicitCwd) {
978
+ recordBucketBShadowHint(
979
+ sessionId,
980
+ {
981
+ guardrailId: '#2_GREP_GLOB_FIREWALL',
982
+ stage: alphaStage,
983
+ platform,
984
+ wouldTrigger: true,
985
+ wouldDecision: 'warn',
986
+ latencyMs: elapsedMs,
987
+ tokens_saved_est: verdict.tokensSavedEst || 0,
988
+ dollars_saved_est: Number((((verdict.tokensSavedEst || 0) / 1_000_000) * 3.0).toFixed(6)),
989
+ evidence: {
990
+ code: verdict.code || 'GREP_GLOB_FIREWALL',
991
+ reason: String(verdict.reason || '').slice(0, 220)
992
+ }
993
+ },
994
+ { cwd: baseCwd }
995
+ );
996
+ }
997
+ if (alphaStage !== 'SHADOW') {
998
+ const topBlocks = [];
999
+ for (const p of verdict.topPaths) {
1000
+ const matchedLines = linesByPath.get(p) || [p];
1001
+ topBlocks.push(...matchedLines.slice(0, 4));
1002
+ }
1003
+ return {
1004
+ triggered: true,
1005
+ stage: alphaStage,
1006
+ guardrailId: '#2_GREP_GLOB_FIREWALL',
1007
+ code: verdict.code || 'GREP_GLOB_FIREWALL',
1008
+ updatedOutput: `${verdict.reason}\n${topBlocks.join('\n')}`,
1009
+ savedTokens: verdict.tokensSavedEst || 0,
1010
+ reason: verdict.reason,
1011
+ topPaths: verdict.topPaths,
1012
+ omittedCount: verdict.omittedCount
1013
+ };
1014
+ }
1015
+ }
1016
+ }
1017
+ }
1018
+
1019
+ return {
1020
+ triggered: false,
1021
+ stage: alphaStage,
1022
+ updatedOutput: rawOutput,
1023
+ savedTokens: 0
1024
+ };
1025
+ }
1026
+
1027
+ /**
1028
+ * Evaluates Sub-Wave B-Beta `Stop` / `post_invocation` guardrail (`#19 OVERENGINEERING_DIFF_GATE`).
1029
+ * Runs in `'COACH'` mode by default (`'SHADOW'` in `SILENT`/`OFF` modes) and records
1030
+ * `.hints.jsonl` telemetry when `hasExplicitCwd` is true.
1031
+ *
1032
+ * @param {object} [params={}]
1033
+ */
1034
+ export function runBucketBStopPass(params = {}) {
1035
+ const platform = params.platform === 'antigravity' ? 'antigravity' : 'claude';
1036
+ const sessionId = params.sessionId || 'default';
1037
+ const hasExplicitCwd = Boolean(params.hasExplicitCwd && params.cwd);
1038
+ const baseCwd = hasExplicitCwd ? path.resolve(params.cwd) : process.cwd();
1039
+ const betaStage = resolveBucketBBetaStage(params.options);
1040
+ const fileDiffs = Array.isArray(params.fileDiffs) ? params.fileDiffs : [];
1041
+ if (fileDiffs.length === 0) {
1042
+ return { triggered: false, stage: betaStage, savedTokens: 0 };
1043
+ }
1044
+
1045
+ const t0 = performance.now();
1046
+ const verdict = evaluateOverengineeringDiffGate({
1047
+ fileDiffs,
1048
+ lastUserPrompt: String(params.lastUserPrompt || '')
1049
+ });
1050
+ const elapsedMs = performance.now() - t0;
1051
+
1052
+ if (!verdict.triggered) {
1053
+ return { triggered: false, stage: betaStage, savedTokens: 0 };
1054
+ }
1055
+
1056
+ const decision = betaStage === 'ENFORCE' ? 'block' : 'warn';
1057
+ if (hasExplicitCwd) {
1058
+ recordBucketBShadowHint(
1059
+ sessionId,
1060
+ {
1061
+ guardrailId: '#19_OVERENGINEERING_DIFF_GATE',
1062
+ stage: betaStage,
1063
+ platform,
1064
+ wouldTrigger: true,
1065
+ wouldDecision: decision,
1066
+ latencyMs: elapsedMs,
1067
+ tokens_saved_est: verdict.tokensSavedEst || 0,
1068
+ dollars_saved_est: Number((((verdict.tokensSavedEst || 0) / 1_000_000) * 3.0).toFixed(6)),
1069
+ evidence: {
1070
+ code: verdict.code || 'OVERENGINEERING_DIFF_GATE',
1071
+ reason: String(verdict.reason || '').slice(0, 220)
1072
+ }
1073
+ },
1074
+ { cwd: baseCwd }
1075
+ );
1076
+ }
1077
+
1078
+ if (betaStage === 'SHADOW') {
1079
+ return {
1080
+ triggered: false,
1081
+ stage: betaStage,
1082
+ shadowed: true,
1083
+ savedTokens: 0
1084
+ };
1085
+ }
1086
+
1087
+ return {
1088
+ triggered: true,
1089
+ stage: betaStage,
1090
+ decision,
1091
+ guardrailId: '#19_OVERENGINEERING_DIFF_GATE',
1092
+ code: verdict.code || 'OVERENGINEERING_DIFF_GATE',
1093
+ reason: verdict.reason,
1094
+ savedTokens: verdict.tokensSavedEst || 0,
1095
+ nonTestAddedLines: verdict.nonTestAddedLines,
1096
+ testAddedLines: verdict.testAddedLines,
1097
+ unusedExportedAbstractions: verdict.unusedExportedAbstractions
1098
+ };
1099
+ }
1100
+
1101
+ /**
1102
+ * Evaluates Sub-Wave B-Gamma `UserPromptSubmit` / `handlePreInvocation` guardrail
1103
+ * (`#13 VAGUE_PROMPT_ANCHOR`) with `0` subprocess spawns using cached dirty/failing state.
1104
+ * Runs in `'COACH'` mode by default (`'SHADOW'` in `'SILENT'`/`'OFF'` modes) and NEVER blocks prompts.
1105
+ *
1106
+ * @param {object} [params={}]
1107
+ */
1108
+ export function runBucketBPromptPass(params = {}) {
1109
+ const platform = params.platform === 'antigravity' ? 'antigravity' : 'claude';
1110
+ const sessionId = params.sessionId || 'default';
1111
+ const hasExplicitCwd = params.hasExplicitCwd !== false && Boolean(params.cwd);
1112
+ const baseCwd = hasExplicitCwd ? path.resolve(params.cwd) : process.cwd();
1113
+ const gammaCoachStage = resolveBucketBGammaCoachStage(params.options);
1114
+
1115
+ if (params.isAutonomousOrSubagent) {
1116
+ return { triggered: false, stage: gammaCoachStage, savedTokens: 0 };
1117
+ }
1118
+
1119
+ const dirtySet = [];
1120
+ const seen = new Set();
1121
+ for (const rawItem of Array.isArray(params.cachedDirtyFiles) ? params.cachedDirtyFiles : []) {
1122
+ const rawStr = String(rawItem || '').trim();
1123
+ if (!rawStr) continue;
1124
+ let norm = rawStr.replace(/\\/g, '/').replace(/^\.\//, '');
1125
+ if (hasExplicitCwd && path.isAbsolute(rawStr)) {
1126
+ const rel = path.relative(baseCwd, rawStr).replace(/\\/g, '/');
1127
+ if (rel && !rel.startsWith('..') && !path.isAbsolute(rel)) {
1128
+ norm = rel;
1129
+ }
1130
+ }
1131
+ if (!norm || isBucketBForbiddenSkuPath(norm) || seen.has(norm)) continue;
1132
+ seen.add(norm);
1133
+ dirtySet.push(norm);
1134
+ if (dirtySet.length >= 5) break;
1135
+ }
1136
+
1137
+ let cleanLastFail = String(params.lastFailingLocation || '').trim().replace(/\\/g, '/');
1138
+ if (cleanLastFail && hasExplicitCwd && path.isAbsolute(cleanLastFail)) {
1139
+ const relFail = path.relative(baseCwd, cleanLastFail).replace(/\\/g, '/');
1140
+ if (relFail && !relFail.startsWith('..') && !path.isAbsolute(relFail)) {
1141
+ cleanLastFail = relFail;
1142
+ }
1143
+ }
1144
+ if (cleanLastFail && isBucketBForbiddenSkuPath(cleanLastFail)) {
1145
+ cleanLastFail = '';
1146
+ }
1147
+
1148
+ const t0 = performance.now();
1149
+ const verdict = evaluateVaguePromptAnchor({
1150
+ prompt: String(params.prompt || ''),
1151
+ cachedDirtyFiles: dirtySet,
1152
+ lastFailingLocation: cleanLastFail
1153
+ });
1154
+ const elapsedMs = performance.now() - t0;
1155
+
1156
+ if (!verdict.triggered) {
1157
+ return { triggered: false, stage: gammaCoachStage, savedTokens: 0 };
1158
+ }
1159
+
1160
+ if (hasExplicitCwd) {
1161
+ recordBucketBShadowHint(
1162
+ sessionId,
1163
+ {
1164
+ guardrailId: '#13_VAGUE_PROMPT_ANCHOR',
1165
+ stage: gammaCoachStage,
1166
+ platform,
1167
+ wouldTrigger: true,
1168
+ wouldDecision: 'warn',
1169
+ latencyMs: elapsedMs,
1170
+ tokens_saved_est: verdict.tokensSavedEst || 0,
1171
+ dollars_saved_est: Number((((verdict.tokensSavedEst || 0) / 1_000_000) * 3.0).toFixed(6)),
1172
+ evidence: {
1173
+ code: verdict.code || 'VAGUE_PROMPT_ANCHOR',
1174
+ reason: String(verdict.reason || '').slice(0, 220)
1175
+ }
1176
+ },
1177
+ { cwd: baseCwd }
1178
+ );
1179
+ }
1180
+
1181
+ if (gammaCoachStage === 'SHADOW') {
1182
+ return {
1183
+ triggered: false,
1184
+ stage: 'SHADOW',
1185
+ shadowed: true,
1186
+ savedTokens: 0
1187
+ };
1188
+ }
1189
+
1190
+ return {
1191
+ triggered: true,
1192
+ stage: gammaCoachStage,
1193
+ decision: 'warn',
1194
+ guardrailId: '#13_VAGUE_PROMPT_ANCHOR',
1195
+ code: verdict.code || 'VAGUE_PROMPT_ANCHOR',
1196
+ anchorContext: verdict.anchorContext,
1197
+ reason: `${verdict.anchorContext} — ${verdict.reason}`,
1198
+ savedTokens: verdict.tokensSavedEst || 0
1199
+ };
1200
+ }