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
@@ -6,12 +6,18 @@
6
6
 
7
7
  import { loadHorizonConfig, resolveDetectorOverride } from '../../src/core-isomorphic/config/horizonConfig.mjs';
8
8
  import { isSilentOrOffMode } from '../../src/core-isomorphic/coach/cacheGravityRouter.mjs';
9
+ import { evaluateSmartCompactSuggestion } from '../../src/core-isomorphic/coach/smartCompactAdvisor.mjs';
10
+ import { computeActiveToolsetHash } from '../../src/core-isomorphic/coach/resumeToolsetAuditor.mjs';
11
+ import { readLiveStateSnapshot } from '../../src/core-isomorphic/telemetry/telemetryBridge.mjs';
12
+ import { updateSessionCalibrationOnStop } from '../../src/utils/sessionCalibration.mjs';
9
13
  import {
10
14
  evaluateDet14PrematureStopGate,
11
15
  evaluateDet15BatchedStopFormatter,
12
16
  readBreakerStateSnapshot,
13
17
  writeBreakerStateSnapshot
14
18
  } from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
19
+ import { runBucketBStopPass } from '../../src/core/bucket_b_runtime.mjs';
20
+ import { handleClaudeRslHook } from '../../src/hooks/claude_rsl_hook.mjs';
15
21
  import {
16
22
  isCliEntrypoint,
17
23
  readStdinJsonAsync,
@@ -36,6 +42,9 @@ export function runStopGateHook(event = {}, options = {}) {
36
42
  const horizonConfig = options.horizonConfig || loadHorizonConfig(cwdOptions);
37
43
  const effectiveMode = options.mode || event.mode || horizonConfig?.flightMode || 'COACH';
38
44
  const stopHookActive = Boolean(event.stop_hook_active ?? event.stopHookActive);
45
+ const isSessionEnd =
46
+ String(options.phase || event.phase || '').toLowerCase() === 'end' ||
47
+ event.hook_event_name === 'SessionEnd';
39
48
 
40
49
  const shouldPersistState =
41
50
  options.persistState !== false &&
@@ -45,6 +54,97 @@ export function runStopGateHook(event = {}, options = {}) {
45
54
  ? readBreakerStateSnapshot(sessionId, cwdOptions)
46
55
  : null;
47
56
 
57
+ const rawBgTasks =
58
+ event.active_background_tasks ??
59
+ event.activeBackgroundTasks ??
60
+ event.backgroundTasks ??
61
+ breakerSnap?.activeBackgroundTasks ??
62
+ [];
63
+ const activeBackgroundTasks = Array.isArray(rawBgTasks)
64
+ ? rawBgTasks
65
+ .filter(Boolean)
66
+ .map((t) => (typeof t === 'string' ? t : String(t?.id || t?.command || 'bg_task')))
67
+ : [];
68
+ const bgDrainWarning =
69
+ activeBackgroundTasks.length > 0 && !isSilentOrOffMode(effectiveMode)
70
+ ? `[Highbeam Quota Shield — Orphan Background Drain (#10)] ${activeBackgroundTasks.length} active background task(s) still running (${activeBackgroundTasks.slice(0, 3).join(', ')}). Terminate orphan daemons/watchers to prevent idle token & CPU drain.`
71
+ : null;
72
+
73
+ if (isSessionEnd) {
74
+ if (shouldPersistState) {
75
+ const liveEnd = options.telemetryState || readLiveStateSnapshot(sessionId, cwdOptions);
76
+ const endContextTokens = Number(
77
+ event.context_tokens ??
78
+ event.contextTokens ??
79
+ event.cached_tokens ??
80
+ event.cachedTokens ??
81
+ liveEnd?.contextWindow?.cachedTokens ??
82
+ breakerSnap?.lastContextTokens ??
83
+ 0
84
+ );
85
+ const endModelId = String(
86
+ event.model || event.modelId || liveEnd?.modelId || breakerSnap?.lastModelId || 'claude-sonnet-5-5'
87
+ );
88
+ const toolsetHash = computeActiveToolsetHash(event, cwdOptions);
89
+ writeBreakerStateSnapshot(
90
+ sessionId,
91
+ {
92
+ ...(breakerSnap || {}),
93
+ updatedAt: Date.now(),
94
+ ...(activeBackgroundTasks.length === 0 ? { activeBackgroundTasks: [] } : {}),
95
+ pending_downshift: null,
96
+ pendingDownshiftModel: null,
97
+ justCompacted: false,
98
+ lastToolsetHash: toolsetHash,
99
+ lastContextTokens: endContextTokens,
100
+ lastModelId: endModelId
101
+ },
102
+ cwdOptions
103
+ );
104
+ if (!stopHookActive && Boolean(event.cwd || options.cwd) && options.enableRsl !== false) {
105
+ try {
106
+ handleClaudeRslHook(event, { ...cwdOptions, event: 'SessionEnd' });
107
+ } catch {
108
+ // Fail open for RSL post-mortem
109
+ }
110
+ }
111
+ }
112
+ if (bgDrainWarning) {
113
+ const stdoutJson = { systemMessage: bgDrainWarning };
114
+ return {
115
+ exitCode: 0,
116
+ stdout: JSON.stringify(stdoutJson),
117
+ stdoutJson,
118
+ stderr: '',
119
+ activeBackgroundTasks,
120
+ bgDrainWarning
121
+ };
122
+ }
123
+ return {
124
+ exitCode: 0,
125
+ stdout: '',
126
+ stderr: '',
127
+ activeBackgroundTasks,
128
+ bgDrainWarning: null
129
+ };
130
+ }
131
+
132
+ const hasDirectOutput =
133
+ event.output_tokens !== undefined ||
134
+ event.outputTokens !== undefined ||
135
+ event.usage?.output_tokens !== undefined;
136
+ const shouldPersistCalibration =
137
+ options.persistCalibration !== false &&
138
+ Boolean(
139
+ event.transcript_path ||
140
+ event.transcriptPath ||
141
+ options.calibrationPath ||
142
+ (hasDirectOutput && (options.homeDir || event.cwd || options.cwd))
143
+ );
144
+ const sessionCalibration = shouldPersistCalibration
145
+ ? updateSessionCalibrationOnStop(event, cwdOptions)
146
+ : null;
147
+
48
148
  if (stopHookActive) {
49
149
  if (shouldPersistState && breakerSnap) {
50
150
  writeBreakerStateSnapshot(
@@ -55,6 +155,7 @@ export function runStopGateHook(event = {}, options = {}) {
55
155
  modifiedFilesInTurn: [],
56
156
  editedFiles: [],
57
157
  pendingFormatFiles: [],
158
+ turnFileDiffs: [],
58
159
  codeEditedSinceLastTest: false
59
160
  },
60
161
  cwdOptions
@@ -64,6 +165,7 @@ export function runStopGateHook(event = {}, options = {}) {
64
165
  exitCode: 0,
65
166
  stdout: '',
66
167
  stderr: '',
168
+ sessionCalibration,
67
169
  det14: {
68
170
  detectorId: 'DET-14',
69
171
  triggered: false,
@@ -154,38 +256,207 @@ export function runStopGateHook(event = {}, options = {}) {
154
256
  modifiedFiles: modifiedFilesForFormat
155
257
  });
156
258
 
157
- if (shouldPersistState && breakerSnap && det14.decision !== 'block') {
259
+ let stopPass = null;
260
+ if (
261
+ !isSessionEnd &&
262
+ !stopHookActive &&
263
+ det14.decision !== 'block' &&
264
+ String(effectiveMode).toUpperCase() !== 'OFF' &&
265
+ options.bucketBShadow !== false &&
266
+ event.bucketBShadow !== false
267
+ ) {
268
+ const turnFileDiffs = Array.isArray(event.fileDiffs)
269
+ ? event.fileDiffs
270
+ : Array.isArray(breakerSnap?.turnFileDiffs)
271
+ ? breakerSnap.turnFileDiffs
272
+ : [];
273
+ const lastUserPrompt = String(
274
+ event.lastUserPrompt ?? event.prompt ?? breakerSnap?.lastUserPrompt ?? ''
275
+ );
276
+ if (turnFileDiffs.length > 0) {
277
+ try {
278
+ stopPass = runBucketBStopPass({
279
+ platform: 'claude',
280
+ sessionId,
281
+ cwd: event.cwd || options.cwd || '',
282
+ hasExplicitCwd: Boolean(event.cwd || options.cwd),
283
+ fileDiffs: turnFileDiffs,
284
+ lastUserPrompt,
285
+ options: { ...options, mode: effectiveMode, horizonConfig }
286
+ });
287
+ } catch (_stopPassErr) {
288
+ stopPass = null;
289
+ }
290
+ }
291
+ }
292
+
293
+ const liveForStop =
294
+ shouldPersistState ||
295
+ event.smartCompactBoundarySuggest !== undefined ||
296
+ options.smartCompactBoundarySuggest !== undefined ||
297
+ horizonConfig?.thresholds?.smartCompactBoundarySuggest
298
+ ? (options.telemetryState || readLiveStateSnapshot(sessionId, cwdOptions))
299
+ : null;
300
+ const currentContextTokens = Number(
301
+ event.context_tokens ??
302
+ event.contextTokens ??
303
+ event.cached_tokens ??
304
+ event.cachedTokens ??
305
+ liveForStop?.contextWindow?.cachedTokens ??
306
+ breakerSnap?.lastContextTokens ??
307
+ 0
308
+ );
309
+ const currentModelId = String(
310
+ event.model ||
311
+ event.modelId ||
312
+ liveForStop?.modelId ||
313
+ breakerSnap?.lastModelId ||
314
+ 'claude-sonnet-5-5'
315
+ );
316
+ const effectiveTurnsSinceLastCompact =
317
+ event.turns_since_last_compact ??
318
+ event.turnsSinceLastCompact ??
319
+ breakerSnap?.turnsSinceLastCompact ??
320
+ null;
321
+ const boundaryReached = Boolean(
322
+ event.boundary_detected ?? event.boundaryDetected ?? breakerSnap?.turnBoundaryReached
323
+ );
324
+ const midDebugActive = Boolean(
325
+ event.mid_debug ??
326
+ event.midDebug ??
327
+ breakerSnap?.turnMidDebug ??
328
+ breakerSnap?.taskBoundaryState?.openFailure
329
+ );
330
+ const smartCompactSuggestion =
331
+ det14.decision === 'block' ||
332
+ stopPass?.decision === 'block' ||
333
+ isSilentOrOffMode(effectiveMode) ||
334
+ stopHookActive
335
+ ? { shouldSuggest: false, suppressedReason: 'blocked_or_silent', detectorStatus: 'unverified', message: null }
336
+ : evaluateSmartCompactSuggestion(
337
+ {
338
+ enabled:
339
+ event.smartCompactBoundarySuggest ??
340
+ options.smartCompactBoundarySuggest ??
341
+ horizonConfig?.thresholds?.smartCompactBoundarySuggest ??
342
+ false,
343
+ detectorState: midDebugActive
344
+ ? 'mid_debug'
345
+ : boundaryReached
346
+ ? 'task_boundary'
347
+ : (event.detectorState || 'other'),
348
+ boundaryDetected: boundaryReached,
349
+ openFailure: Boolean(breakerSnap?.taskBoundaryState?.openFailure),
350
+ consecutiveFailures: Number(breakerSnap?.consecutiveFailures || 0),
351
+ turnsSinceLastCompact: effectiveTurnsSinceLastCompact,
352
+ modelId: currentModelId,
353
+ preCompactTokens: currentContextTokens,
354
+ cacheTtlTier: liveForStop?.promptCache?.ttlTier === '1h' ? '1h' : '5m',
355
+ expectedRemainingRequests:
356
+ event.expected_remaining_requests ?? event.expectedRemainingRequests,
357
+ expectedRemainingTurns:
358
+ event.expected_remaining_turns ??
359
+ event.expectedRemainingTurns ??
360
+ horizonConfig?.expectedRemainingTurns,
361
+ turnsCompleted: sessionCalibration?.turnsCompleted ?? liveForStop?.turnsCompleted ?? 0,
362
+ apiCallsCompleted: sessionCalibration?.apiCallsCompleted,
363
+ requestsPerTurn:
364
+ event.requests_per_turn ??
365
+ event.requestsPerTurn ??
366
+ sessionCalibration?.requestsPerTurn,
367
+ contextGrowthPerTurn: sessionCalibration?.rollingMedianPromptGrowthTokens,
368
+ contextCeiling: liveForStop?.contextWindow?.contextCeiling
369
+ },
370
+ { ...cwdOptions, horizonConfig }
371
+ );
372
+
373
+ if (shouldPersistState && det14.decision !== 'block') {
374
+ const nextTurnsSinceCompact =
375
+ typeof breakerSnap?.turnsSinceLastCompact === 'number' &&
376
+ Number.isFinite(breakerSnap.turnsSinceLastCompact)
377
+ ? breakerSnap.turnsSinceLastCompact + 1
378
+ : null;
379
+ const toolsetHash =
380
+ event.cwd || cwdOptions.cwd || event.tools || event.mcp_servers || options.cliArgs || event.cliArgs
381
+ ? computeActiveToolsetHash(event, cwdOptions)
382
+ : (breakerSnap?.lastToolsetHash || null);
158
383
  writeBreakerStateSnapshot(
159
384
  sessionId,
160
385
  {
161
- ...breakerSnap,
386
+ ...(breakerSnap || {}),
162
387
  updatedAt: Date.now(),
163
388
  modifiedFilesInTurn: [],
164
389
  editedFiles: [],
165
390
  pendingFormatFiles: [],
166
- codeEditedSinceLastTest: false
391
+ turnFileDiffs: [],
392
+ codeEditedSinceLastTest: false,
393
+ justCompacted: false,
394
+ turnBoundaryReached: false,
395
+ turnMidDebug: false,
396
+ ...(nextTurnsSinceCompact !== null ? { turnsSinceLastCompact: nextTurnsSinceCompact } : {}),
397
+ ...(toolsetHash ? { lastToolsetHash: toolsetHash } : {}),
398
+ lastContextTokens: currentContextTokens,
399
+ lastModelId: currentModelId
167
400
  },
168
401
  cwdOptions
169
402
  );
403
+ if (!stopHookActive && Boolean(event.cwd || options.cwd) && options.enableRsl !== false) {
404
+ try {
405
+ handleClaudeRslHook(event, { ...cwdOptions, event: 'Stop' });
406
+ } catch {
407
+ // Fail open for RSL post-mortem
408
+ }
409
+ }
170
410
  }
171
411
 
172
412
  if (det14.decision === 'block') {
413
+ const locSuffix = breakerSnap?.lastFailingLocation
414
+ ? ` (last failing location: ${breakerSnap.lastFailingLocation})`
415
+ : '';
416
+ const stdoutJson = {
417
+ decision: 'block',
418
+ reason: `${det14.reason}${locSuffix}`
419
+ };
420
+ return {
421
+ exitCode: 0,
422
+ stdout: JSON.stringify(stdoutJson),
423
+ stdoutJson,
424
+ stderr: '',
425
+ sessionCalibration,
426
+ det14,
427
+ det15,
428
+ smartCompactSuggestion,
429
+ activeBackgroundTasks
430
+ };
431
+ }
432
+
433
+ if (stopPass?.triggered && stopPass.decision === 'block') {
173
434
  const stdoutJson = {
174
435
  decision: 'block',
175
- reason: det14.reason
436
+ reason: stopPass.reason
176
437
  };
177
438
  return {
178
439
  exitCode: 0,
179
440
  stdout: JSON.stringify(stdoutJson),
180
441
  stdoutJson,
181
442
  stderr: '',
443
+ sessionCalibration,
182
444
  det14,
183
- det15
445
+ det15,
446
+ smartCompactSuggestion,
447
+ overengineeringGate: stopPass,
448
+ activeBackgroundTasks
184
449
  };
185
450
  }
186
451
 
187
- if (det14.advisory || det15.triggered) {
188
- const reasons = [det14.reason, det15.batchCommand ? `Batch format: ${det15.batchCommand}` : null]
452
+ if (det14.advisory || det15.triggered || bgDrainWarning || stopPass?.triggered || smartCompactSuggestion.shouldSuggest) {
453
+ const reasons = [
454
+ det14.advisory ? det14.reason : null,
455
+ det15.batchCommand ? `Batch format: ${det15.batchCommand}` : null,
456
+ bgDrainWarning,
457
+ stopPass?.triggered ? stopPass.reason : null,
458
+ smartCompactSuggestion.shouldSuggest ? smartCompactSuggestion.message : null
459
+ ]
189
460
  .filter(Boolean)
190
461
  .join(' | ');
191
462
  const stdoutJson = {
@@ -196,8 +467,12 @@ export function runStopGateHook(event = {}, options = {}) {
196
467
  stdout: JSON.stringify(stdoutJson),
197
468
  stdoutJson,
198
469
  stderr: '',
470
+ sessionCalibration,
199
471
  det14,
200
- det15
472
+ det15,
473
+ smartCompactSuggestion,
474
+ ...(stopPass ? { overengineeringGate: stopPass } : {}),
475
+ activeBackgroundTasks
201
476
  };
202
477
  }
203
478
 
@@ -205,13 +480,17 @@ export function runStopGateHook(event = {}, options = {}) {
205
480
  exitCode: 0,
206
481
  stdout: '',
207
482
  stderr: '',
483
+ sessionCalibration,
208
484
  det14,
209
- det15
485
+ det15,
486
+ smartCompactSuggestion,
487
+ ...(stopPass ? { overengineeringGate: stopPass } : {}),
488
+ activeBackgroundTasks
210
489
  };
211
490
  }
212
491
 
213
492
  /**
214
- * CLI runner for `Stop` (`ISS-035`).
493
+ * CLI runner for `Stop` and `SessionEnd` (`--phase=end`) (`ISS-035`).
215
494
  * Non-blocking lifecycle hook on uncaught internal error: logs diagnostic to stderr and exits `0`.
216
495
  *
217
496
  * @param {object} [cliOptions={}]
@@ -221,8 +500,15 @@ export async function executeStopGateCli(cliOptions = {}) {
221
500
  const runHook = cliOptions.runHook || runStopGateHook;
222
501
  const ioOverride = cliOptions.ioOverride || {};
223
502
  try {
503
+ const argv = cliOptions.argv || globalThis.process?.argv || [];
504
+ const phaseArg = argv.find((a) => String(a).startsWith('--phase='));
505
+ const explicitPhase = phaseArg ? String(phaseArg).split('=')[1] : undefined;
224
506
  const payload = await readPayload(cliOptions.timeoutMs);
225
- const res = runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
507
+ const res = runHook(payload, {
508
+ persistState: true,
509
+ ...(cliOptions.hookOptions || {}),
510
+ ...(explicitPhase ? { phase: explicitPhase } : {})
511
+ });
226
512
  if (res.stdout) {
227
513
  exitWithStdoutJson(res.stdout, ioOverride);
228
514
  } else {
@@ -9,13 +9,23 @@
9
9
  * - Block: exit 0 with `{"decision":"block","reason":"..."}`
10
10
  */
11
11
 
12
+ import fs from 'node:fs';
13
+ import path from 'node:path';
12
14
  import { readLiveStateSnapshot } from '../../src/core-isomorphic/telemetry/telemetryBridge.mjs';
13
15
  import { loadHorizonConfig } from '../../src/core-isomorphic/config/horizonConfig.mjs';
16
+ import {
17
+ evaluateShardedSpecDrift,
18
+ evaluateTurn1ContractGate
19
+ } from '../../src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs';
14
20
  import {
15
21
  CircuitBreakerEngine,
16
22
  readBreakerStateSnapshot,
17
23
  writeBreakerStateSnapshot
18
24
  } from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
25
+ import { atomicWriteFileSync } from '../../src/core/atomic_io.mjs';
26
+ import { scorePromptSufficiency } from '../../src/core/prompt_rubric.mjs';
27
+ import { sanitizeRslSessionId } from '../../src/core/rsl_triage.mjs';
28
+ import { runBucketBPromptPass } from '../../src/core/bucket_b_runtime.mjs';
19
29
  import {
20
30
  isCliEntrypoint,
21
31
  readStdinJsonAsync,
@@ -24,6 +34,49 @@ import {
24
34
  exitWithStdoutJson
25
35
  } from './hookIo.mjs';
26
36
 
37
+ function getPromptStatePath(cwd, sessionId) {
38
+ return path.join(
39
+ path.resolve(cwd),
40
+ '.agents',
41
+ 'telemetry',
42
+ `prompt_state.${sanitizeRslSessionId(sessionId)}.json`
43
+ );
44
+ }
45
+
46
+ function readPromptStateSnapshot(cwd, sessionId, event = {}) {
47
+ const fallback = {
48
+ initialGoal: String(event.initialGoal || ''),
49
+ specShards: Array.isArray(event.specShards) ? event.specShards : [],
50
+ turnCount: Number(event.turnNumber ? Number(event.turnNumber) - 1 : 0),
51
+ lastAlertTurn: Number(event.lastShardedSpecAlertTurn || 0),
52
+ turn1ContractInjected: Boolean(event.turn1ContractInjected)
53
+ };
54
+ if (!cwd) return fallback;
55
+ const statePath = getPromptStatePath(cwd, sessionId);
56
+ if (!fs.existsSync(statePath)) return fallback;
57
+ let parsed = null;
58
+ try {
59
+ parsed = JSON.parse(fs.readFileSync(statePath, 'utf8'));
60
+ } catch (err) {
61
+ parsed = err ? null : null;
62
+ }
63
+ return parsed && typeof parsed === 'object' ? { ...fallback, ...parsed } : fallback;
64
+ }
65
+
66
+ function writePromptStateSnapshot(cwd, sessionId, nextState) {
67
+ if (!cwd) return;
68
+ const statePath = getPromptStatePath(cwd, sessionId);
69
+ let writeOk = false;
70
+ try {
71
+ fs.mkdirSync(path.dirname(statePath), { recursive: true });
72
+ atomicWriteFileSync(statePath, `${JSON.stringify(nextState, null, 2)}\n`);
73
+ writeOk = true;
74
+ } catch (err) {
75
+ writeOk = Boolean(err && false);
76
+ }
77
+ return writeOk;
78
+ }
79
+
27
80
  /**
28
81
  * Evaluates a `UserPromptSubmit` hook payload and returns the contract response.
29
82
  *
@@ -76,6 +129,177 @@ export function runUserPromptSubmitHook(event = {}, options = {}) {
76
129
  }
77
130
 
78
131
  if (!verdict.triggered) {
132
+ const resolvedCwd = event.cwd || options.cwd || '';
133
+ const promptText = String(event.prompt ?? event.user_input ?? event.message ?? '');
134
+ if (options.bucketBShadow !== false) {
135
+ try {
136
+ const provenance = String(event.provenance || event.source || '');
137
+ const isAutonomousOrSubagent = Boolean(
138
+ event.isAutonomousTurn ||
139
+ event.autonomous ||
140
+ event.isSubagent ||
141
+ event.agentId ||
142
+ event.subagentId ||
143
+ event.isScheduledTask ||
144
+ event.isLoopIteration ||
145
+ /^(?:scheduled|cron|loop|subagent|agent_callback|callback|auto|autonomous|background|system|hook|task_notification|wake)$/i.test(
146
+ provenance
147
+ )
148
+ );
149
+ const cachedDirtyFiles = Array.isArray(event.cachedDirtyFiles)
150
+ ? event.cachedDirtyFiles
151
+ : [
152
+ ...Array.from(engine.modifiedFilesInTurn || []),
153
+ ...(Array.isArray(engine.unverifiedEdits)
154
+ ? engine.unverifiedEdits.map((e) => e?.filePath)
155
+ : []),
156
+ ...(Array.isArray(event.modifiedFiles) ? event.modifiedFiles : [])
157
+ ];
158
+ const hasExplicitCwd = Boolean(resolvedCwd);
159
+ const promptAnchor = runBucketBPromptPass({
160
+ platform: 'claude',
161
+ sessionId,
162
+ cwd: resolvedCwd,
163
+ hasExplicitCwd,
164
+ prompt: promptText,
165
+ isAutonomousOrSubagent,
166
+ cachedDirtyFiles,
167
+ lastFailingLocation: event.lastFailingLocation ?? engine.lastFailingLocation ?? '',
168
+ options: {
169
+ ...options,
170
+ bucketBStage: event.bucketBStage ?? options.bucketBStage,
171
+ bucketBGammaStage: event.bucketBGammaStage ?? options.bucketBGammaStage,
172
+ mode: effectiveMode,
173
+ horizonConfig
174
+ }
175
+ });
176
+ if (promptAnchor.triggered) {
177
+ const anchorStdoutJson = {
178
+ hookSpecificOutput: {
179
+ hookEventName: 'UserPromptSubmit',
180
+ additionalContext: String(promptAnchor.reason || '').slice(0, 9500)
181
+ }
182
+ };
183
+ return {
184
+ exitCode: 0,
185
+ stdout: JSON.stringify(anchorStdoutJson),
186
+ stdoutJson: anchorStdoutJson,
187
+ stderr: '',
188
+ verdict: {
189
+ triggered: true,
190
+ detectorId: 'VAGUE_PROMPT_ANCHOR',
191
+ subType: 'VAGUE_PROMPT_ANCHOR',
192
+ decision: 'steer',
193
+ anchorContext: promptAnchor.anchorContext,
194
+ savedTokens: promptAnchor.savedTokens,
195
+ reason: promptAnchor.reason
196
+ }
197
+ };
198
+ }
199
+ } catch (err) {
200
+ if (options.onDiagnostic) options.onDiagnostic(err);
201
+ }
202
+ }
203
+
204
+ if (promptText.trim().length > 0 && effectiveMode !== 'SILENT' && effectiveMode !== 'OFF') {
205
+ const promptState = readPromptStateSnapshot(shouldPersistState ? resolvedCwd : '', sessionId, event);
206
+ const nextTurnNumber = Number(event.turnNumber ?? (Number(promptState.turnCount || 0) + 1));
207
+ const shardedEval = evaluateShardedSpecDrift({
208
+ prompt: promptText,
209
+ provenance: String(event.provenance || event.source || 'user'),
210
+ isAutonomousTurn: Boolean(event.isAutonomousTurn || event.autonomous),
211
+ isSubagent: Boolean(event.isSubagent || event.agentId || event.subagentId),
212
+ isScheduledTask: Boolean(event.isScheduledTask),
213
+ isLoopIteration: Boolean(event.isLoopIteration),
214
+ priorShards: Array.isArray(event.specShards) ? event.specShards : (promptState.specShards || []),
215
+ initialGoal: event.initialGoal ?? promptState.initialGoal ?? '',
216
+ totalTokens: Number(
217
+ event.totalTokens ?? event.totalInputTokens ?? liveState?.totalTokens ?? liveState?.contextTokens ?? 0
218
+ ),
219
+ turnNumber: nextTurnNumber,
220
+ lastAlertTurn: Number(event.lastShardedSpecAlertTurn ?? promptState.lastAlertTurn ?? 0),
221
+ overrideMode: horizonConfig?.detectors?.['sharded-spec-drift'] || 'default',
222
+ flightMode: effectiveMode,
223
+ detectorId: 'DET-14'
224
+ });
225
+
226
+ const activeSet = Array.isArray(liveState?.activeSetPaths) ? liveState.activeSetPaths : [];
227
+ const hasActiveSetMatch = activeSet.some((p) => {
228
+ const base = path.basename(String(p || ''));
229
+ return base && promptText.includes(base);
230
+ });
231
+ const canRunTurn1Gate =
232
+ !shardedEval.triggered &&
233
+ Boolean(resolvedCwd || event.enablePromptContractGate) &&
234
+ (horizonConfig?.detectors?.['turn1-contract-gate'] || 'default') !== 'off';
235
+ const contractEval = canRunTurn1Gate
236
+ ? evaluateTurn1ContractGate({
237
+ prompt: promptText,
238
+ provenance: String(event.provenance || event.source || 'user'),
239
+ isAutonomousTurn: Boolean(event.isAutonomousTurn || event.autonomous),
240
+ isSubagent: Boolean(event.isSubagent || event.agentId || event.subagentId),
241
+ isScheduledTask: Boolean(event.isScheduledTask),
242
+ isLoopIteration: Boolean(event.isLoopIteration),
243
+ inPlanMode: Boolean(event.permission_mode === 'plan' || event.inPlanMode),
244
+ turnNumber: nextTurnNumber,
245
+ invocationNum: Number(event.invocationNum ?? 1),
246
+ alreadyInjected: Boolean(promptState.turn1ContractInjected),
247
+ hasActiveSetMatch,
248
+ sufficiency: scorePromptSufficiency(promptText, { activeSetPaths: activeSet }),
249
+ overrideMode: horizonConfig?.detectors?.['turn1-contract-gate'] || 'default',
250
+ flightMode: effectiveMode,
251
+ detectorId: 'DET-14'
252
+ })
253
+ : { triggered: false };
254
+
255
+ if (shouldPersistState && resolvedCwd) {
256
+ writePromptStateSnapshot(resolvedCwd, sessionId, {
257
+ initialGoal: shardedEval.initialGoal,
258
+ specShards: shardedEval.specShards,
259
+ turnCount: nextTurnNumber,
260
+ lastAlertTurn: shardedEval.lastAlertTurn,
261
+ turn1ContractInjected: Boolean(promptState.turn1ContractInjected || contractEval.triggered)
262
+ });
263
+ }
264
+
265
+ const activeSteer = shardedEval.triggered
266
+ ? {
267
+ subType: shardedEval.subType,
268
+ reason: shardedEval.steerContext,
269
+ extra: { shardCount: shardedEval.shardCount }
270
+ }
271
+ : contractEval.triggered
272
+ ? {
273
+ subType: contractEval.subType,
274
+ reason: contractEval.contractDirective,
275
+ extra: {}
276
+ }
277
+ : null;
278
+
279
+ if (activeSteer) {
280
+ const steerStdoutJson = {
281
+ hookSpecificOutput: {
282
+ hookEventName: 'UserPromptSubmit',
283
+ additionalContext: String(activeSteer.reason || '').slice(0, 9500)
284
+ }
285
+ };
286
+ return {
287
+ exitCode: 0,
288
+ stdout: JSON.stringify(steerStdoutJson),
289
+ stdoutJson: steerStdoutJson,
290
+ stderr: '',
291
+ verdict: {
292
+ triggered: true,
293
+ detectorId: 'DET-14',
294
+ subType: activeSteer.subType,
295
+ decision: 'steer',
296
+ ...activeSteer.extra,
297
+ reason: activeSteer.reason
298
+ }
299
+ };
300
+ }
301
+ }
302
+
79
303
  return {
80
304
  exitCode: 0,
81
305
  stdout: '',