ctxtop 0.0.0-stage → 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 (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,1202 @@
1
+ /**
2
+ * @file src/guards/circuitBreakers.mjs
3
+ * Normalized 20-Detector Circuit Breaker Engine (`DET-01` through `DET-20`)
4
+ * for Claude Code Highbeam.
5
+ *
6
+ * Enforces:
7
+ * - Option-argument skipping in `DET-01` (`git commit -m "-next"` never false-positives as `-n`)
8
+ * - Allowlist for `.env.example`, `.env.sample`, `.env.template` in `DET-02`
9
+ * - Manual-edit-only lockfile gate in `DET-03` (`npm install` via Bash/PowerShell is allowed)
10
+ * - Added/deleted diff-line-only scanning in `DET-05` (never scans whole file, never runs `git checkout --`)
11
+ * - Unicode tag `U+E0000`..`U+E007F` stripping & `<untrusted_subagent_data>` wrapping in `DET-19`
12
+ * - Dotfile-aware multi-agent scope locks in `DET-20`
13
+ */
14
+
15
+ import {
16
+ path,
17
+ sha256Hex,
18
+ getFileByteSizeSafe,
19
+ resolvePath,
20
+ getCwd,
21
+ readJsonSafe,
22
+ writeJsonAtomic,
23
+ readTextSafe,
24
+ fileExists
25
+ } from '../utils/runtime.mjs';
26
+ import { normalizeModelId, computeTotalPromptTokens } from '../config/catalogLoader.mjs';
27
+ import {
28
+ loadHorizonConfig,
29
+ resolveDetectorOverride,
30
+ applyDetectorOverride
31
+ } from '../config/horizonConfig.mjs';
32
+ import { recordRepoFileRead } from '../coach/repoCalibration.mjs';
33
+ import {
34
+ FLIGHT_MODES,
35
+ normalizeFlightMode,
36
+ isSilentOrOffMode,
37
+ isPrefixInstructionFile,
38
+ evaluateDet09PrefixMutationFence,
39
+ CacheGravityRouter
40
+ } from '../coach/cacheGravityRouter.mjs';
41
+
42
+ export { isPrefixInstructionFile, evaluateDet09PrefixMutationFence };
43
+ import { TtlWatchdog } from '../coach/ttlWatchdog.mjs';
44
+ import { evaluateScopeAndQuotaBrake, readActiveScopeLocks } from '../telemetry/scopeLockRegistry.mjs';
45
+ import { evaluateActiveDet30StepDown } from '../economics/driftLatency.mjs';
46
+ import { loadMicroSkillsRegistry, evaluateMicroSkillIntercept } from '../coach/microSkills.mjs';
47
+ import {
48
+ RELAY_STATES,
49
+ evaluateScopeBrake,
50
+ evaluateRelayBreaker,
51
+ evaluateTwoStageSightseeingIntercept
52
+ } from '../coach/promptHygieneGovernor.mjs';
53
+
54
+ import {
55
+ SHELL_TOOL_REGEX,
56
+ EDIT_WRITE_TOOL_REGEX,
57
+ SEARCH_READ_TOOL_REGEX,
58
+ tokenizeShellSegment,
59
+ evaluateDet01GitAndShellSafety,
60
+ evaluateDet02SecretBoundary,
61
+ evaluateDet03ProtectedFilesAskGate
62
+ } from './det01_03_shell_secret.mjs';
63
+ import {
64
+ evaluateDet04ConsecutiveFailures,
65
+ computeAddedAndDeletedDiffLines,
66
+ hashFileContent,
67
+ evaluateDet05DiffThrashing,
68
+ evaluateDet06BlindSearchGuard,
69
+ evaluateDet07OutputBombGuard,
70
+ evaluateDet11ContextRotGate,
71
+ evaluateDet12HaikuPreCliffBreaker
72
+ } from './det04_12_thrash_rot.mjs';
73
+ import {
74
+ evaluateDet13McpSchemaBloatGuard,
75
+ evaluateDet14PrematureStopGate,
76
+ evaluateDet15BatchedStopFormatter,
77
+ evaluateDet15PreFormatBypass,
78
+ evaluateDet16SubagentRecursionCap,
79
+ evaluateDet17AutoCompactionDeferral,
80
+ evaluateSilentPrefixMutations,
81
+ evaluateDet18UntrustedSettingsGuard,
82
+ evaluateDet19SubagentIpiSanitizer,
83
+ evaluateDet20ScopeLockAndQuotaBrake,
84
+ sanitizeBreakerSessionId,
85
+ getBreakerStateFilePath,
86
+ readBreakerStateSnapshot,
87
+ writeBreakerStateSnapshot,
88
+ serializeCircuitBreakerState,
89
+ hydrateCircuitBreakerState
90
+ } from './det13_20_mcp_scope.mjs';
91
+
92
+ export {
93
+ tokenizeShellSegment,
94
+ evaluateDet01GitAndShellSafety,
95
+ evaluateDet02SecretBoundary,
96
+ evaluateDet03ProtectedFilesAskGate,
97
+ evaluateDet04ConsecutiveFailures,
98
+ computeAddedAndDeletedDiffLines,
99
+ hashFileContent,
100
+ evaluateDet05DiffThrashing,
101
+ evaluateDet06BlindSearchGuard,
102
+ evaluateDet07OutputBombGuard,
103
+ evaluateDet11ContextRotGate,
104
+ evaluateDet12HaikuPreCliffBreaker,
105
+ evaluateDet13McpSchemaBloatGuard,
106
+ evaluateDet14PrematureStopGate,
107
+ evaluateDet15BatchedStopFormatter,
108
+ evaluateDet15PreFormatBypass,
109
+ evaluateDet16SubagentRecursionCap,
110
+ evaluateDet17AutoCompactionDeferral,
111
+ evaluateSilentPrefixMutations,
112
+ evaluateDet18UntrustedSettingsGuard,
113
+ evaluateDet19SubagentIpiSanitizer,
114
+ evaluateDet20ScopeLockAndQuotaBrake,
115
+ sanitizeBreakerSessionId,
116
+ getBreakerStateFilePath,
117
+ readBreakerStateSnapshot,
118
+ writeBreakerStateSnapshot
119
+ };
120
+
121
+ /**
122
+ * Unified Stateful Circuit Breaker Engine (`DET-01`..`DET-20`).
123
+ */
124
+ export class CircuitBreakerEngine {
125
+ /**
126
+ * @param {object} [options={}]
127
+ */
128
+ constructor(options = {}) {
129
+ this.options = options;
130
+ this.horizonConfig = options.horizonConfig || loadHorizonConfig(options);
131
+ this.mode = normalizeFlightMode(
132
+ options.mode || options.flightMode || this.horizonConfig?.flightMode || FLIGHT_MODES.COACH
133
+ );
134
+ this.consecutiveFailures = Number(options.consecutiveFailures || 0);
135
+ this.lastFailedToolKey = options.lastFailedToolKey || null;
136
+ this.sequentialSearchCount = Number(options.sequentialSearchCount || 0);
137
+ this.fileHashHistory = new Map();
138
+ this.modifiedFilesInTurn = new Set();
139
+ this.unverifiedEdits = Array.isArray(options.unverifiedEdits)
140
+ ? options.unverifiedEdits.filter((e) => e && typeof e.filePath === 'string').map((e) => ({ ...e }))
141
+ : [];
142
+ this.turnFileDiffs = Array.isArray(options.turnFileDiffs)
143
+ ? options.turnFileDiffs.filter((e) => e && typeof e.filePath === 'string').map((e) => ({ ...e }))
144
+ : [];
145
+ this.pendingBatchEdits = new Set();
146
+ this.pendingFormatFiles = new Set();
147
+ this.codeEditedSinceLastTest = Boolean(options.codeEditedSinceLastTest || false);
148
+ this.lastTurnGitCommitted = Boolean(options.lastTurnGitCommitted || false);
149
+ this.committedTopDirs = Array.isArray(options.committedTopDirs) ? [...options.committedTopDirs] : [];
150
+ this.pendingVerificationCommand = Boolean(options.pendingVerificationCommand || false);
151
+ this.lastFailingLocation = options.lastFailingLocation ? String(options.lastFailingLocation) : null;
152
+ this.pending_downshift =
153
+ options.pending_downshift && typeof options.pending_downshift === 'object'
154
+ ? { ...options.pending_downshift }
155
+ : null;
156
+ this.pendingDownshiftModel = options.pendingDownshiftModel
157
+ ? String(options.pendingDownshiftModel)
158
+ : this.pending_downshift?.toModel
159
+ ? String(this.pending_downshift.toModel)
160
+ : null;
161
+ this.justCompacted = Boolean(options.justCompacted || false);
162
+ this.turnsSinceLastCompact =
163
+ options.turnsSinceLastCompact !== undefined &&
164
+ options.turnsSinceLastCompact !== null &&
165
+ Number.isFinite(Number(options.turnsSinceLastCompact))
166
+ ? Math.max(0, Number(options.turnsSinceLastCompact))
167
+ : null;
168
+ this.taskBoundaryState =
169
+ options.taskBoundaryState && typeof options.taskBoundaryState === 'object'
170
+ ? {
171
+ openFailure: Boolean(options.taskBoundaryState.openFailure),
172
+ editsSinceBoundary: Math.max(0, Number(options.taskBoundaryState.editsSinceBoundary || 0)),
173
+ lastBoundarySuggestedTurn: options.taskBoundaryState.lastBoundarySuggestedTurn ?? null
174
+ }
175
+ : { openFailure: false, editsSinceBoundary: 0, lastBoundarySuggestedTurn: null };
176
+ this.lastToolsetHash =
177
+ options.lastToolsetHash && typeof options.lastToolsetHash === 'object'
178
+ ? { ...options.lastToolsetHash }
179
+ : null;
180
+ this.lastContextTokens =
181
+ options.lastContextTokens !== undefined &&
182
+ options.lastContextTokens !== null &&
183
+ Number.isFinite(Number(options.lastContextTokens))
184
+ ? Math.max(0, Number(options.lastContextTokens))
185
+ : null;
186
+ this.lastModelId = options.lastModelId ? String(options.lastModelId) : null;
187
+ this.activeBackgroundTasks = Array.isArray(options.activeBackgroundTasks)
188
+ ? [...options.activeBackgroundTasks]
189
+ : [];
190
+ this.activeWriteWorkers = Array.isArray(options.activeWriteWorkers)
191
+ ? [...options.activeWriteWorkers]
192
+ : [];
193
+ this.lastUserPrompt = options.lastUserPrompt ? String(options.lastUserPrompt) : '';
194
+ this.consecutiveTrivialMaxEffortTurns = Number(options.consecutiveTrivialMaxEffortTurns || 0);
195
+ this.recentEditTimestampsByFile = options.recentEditTimestampsByFile && typeof options.recentEditTimestampsByFile === 'object' ? { ...options.recentEditTimestampsByFile } : {};
196
+ this.totalDiscoveryCalls = Number(options.totalDiscoveryCalls || 0);
197
+ this.consecutiveVisionTurns = Number(options.consecutiveVisionTurns || 0);
198
+ this.unanchoredTurnFlag = Boolean(options.unanchoredTurnFlag || false);
199
+ this.candidateFiles = Array.isArray(options.candidateFiles) ? [...options.candidateFiles] : [];
200
+ this.relayState = options.relayState && typeof options.relayState === 'object'
201
+ ? { ...options.relayState }
202
+ : { state: RELAY_STATES.IDLE, critiquePastes: 0, boundSpecPath: 'SPEC.md' };
203
+ this.steeredPrompts = Number(options.steeredPrompts || 0);
204
+ this.blockedPrompts = Number(options.blockedPrompts || 0);
205
+ this.sightseeingToolsPrevented = Number(options.sightseeingToolsPrevented || 0);
206
+ this.subagentTurns = {};
207
+ this.subagentTokens = {};
208
+ this.det11AdvisedTurn = null;
209
+ this.det13AdvisedTurn = null;
210
+ this.router =
211
+ options.router instanceof CacheGravityRouter
212
+ ? options.router
213
+ : new CacheGravityRouter({ mode: this.mode, ...options });
214
+ this.watchdog =
215
+ options.watchdog instanceof TtlWatchdog
216
+ ? options.watchdog
217
+ : new TtlWatchdog({ mode: this.mode, ...options });
218
+
219
+ if (options.initialState && typeof options.initialState === 'object') {
220
+ this.hydrateStateSnapshot(options.initialState);
221
+ }
222
+ }
223
+
224
+ /**
225
+ * Updates the active flight mode across the engine, router, and watchdog (`ISS-038`).
226
+ * @param {string} mode
227
+ * @returns {string}
228
+ */
229
+ setMode(mode) {
230
+ this.mode = normalizeFlightMode(mode);
231
+ this.router.setMode(this.mode);
232
+ this.watchdog.setMode(this.mode);
233
+ return this.mode;
234
+ }
235
+
236
+ /**
237
+ * Reloads `.attention-horizon.json` and synchronizes flight mode unless pinned by explicit `options.mode`.
238
+ * @param {object} [overrideOptions={}]
239
+ * @returns {object}
240
+ */
241
+ refreshConfig(overrideOptions = {}) {
242
+ const mergedOpts = { ...this.options, ...overrideOptions };
243
+ delete mergedOpts.horizonConfig;
244
+ this.horizonConfig = overrideOptions.horizonConfig || loadHorizonConfig(mergedOpts);
245
+ const nextMode =
246
+ overrideOptions.mode || overrideOptions.flightMode || this.horizonConfig?.flightMode || FLIGHT_MODES.COACH;
247
+ this.setMode(nextMode);
248
+ return this.horizonConfig;
249
+ }
250
+
251
+ /**
252
+ * Exports a serializable snapshot of all stateful breaker counters and queues (`ISS-038`).
253
+ * @returns {object}
254
+ */
255
+ exportStateSnapshot() {
256
+ return serializeCircuitBreakerState(this);
257
+ }
258
+
259
+ /**
260
+ * Hydrates stateful breaker counters and queues from a previously exported snapshot (`ISS-038`).
261
+ * @param {object | null} snap
262
+ * @returns {this}
263
+ */
264
+ hydrateStateSnapshot(snap) {
265
+ return hydrateCircuitBreakerState(this, snap);
266
+ }
267
+
268
+ /**
269
+ * Evaluates `PreToolUse` across all relevant pre-execution detectors
270
+ * (`DET-01`, `DET-02`, `DET-03`, `DET-04`, `DET-05`, `DET-06`, `DET-07`, `DET-11`, `DET-12`, `DET-13`, `DET-16`, `DET-18`, `DET-19`, `DET-20`),
271
+ * applying any per-detector overrides (`off` | `warn` | `block`) from `.attention-horizon.json`.
272
+ *
273
+ * @param {object} [toolEvent={}]
274
+ * @param {object} [telemetryState={}]
275
+ */
276
+ evaluatePreToolUse(toolEvent = {}, telemetryState = {}) {
277
+ const toolName = String(toolEvent.tool_name || toolEvent.toolName || '');
278
+ const toolInput = toolEvent.tool_input || toolEvent.toolInput || {};
279
+ const command = String(toolInput.command || toolInput.cmd || toolEvent.command || '');
280
+ const filePath = String(
281
+ toolInput.file_path ||
282
+ toolInput.notebook_path ||
283
+ toolInput.filePath ||
284
+ toolInput.path ||
285
+ toolEvent.filePath ||
286
+ ''
287
+ );
288
+ const firstEdit = Array.isArray(toolInput.edits) && toolInput.edits[0] ? toolInput.edits[0] : null;
289
+ let oldText = String(
290
+ toolInput.old_string ?? toolInput.oldText ?? firstEdit?.old_string ?? ''
291
+ );
292
+ if (!oldText && String(toolName).toLowerCase() === 'write' && filePath) {
293
+ oldText = readTextSafe(filePath, null, this.options) || '';
294
+ }
295
+ const newText = String(
296
+ toolInput.new_string ??
297
+ toolInput.new_source ??
298
+ toolInput.content ??
299
+ toolInput.newText ??
300
+ firstEdit?.new_string ??
301
+ ''
302
+ );
303
+ const urlStr = String(toolInput.url || toolEvent.url || '');
304
+ const activeMode = normalizeFlightMode(
305
+ toolEvent.mode || telemetryState.flightMode || this.mode || FLIGHT_MODES.COACH
306
+ );
307
+ const silentCoachMode = isSilentOrOffMode(activeMode);
308
+ const resolveVerdict = (verdict) => applyDetectorOverride(verdict, this.horizonConfig);
309
+ const applyHabitSlug = (slug, verdict) => {
310
+ const slugMode = resolveDetectorOverride(slug, this.horizonConfig);
311
+ if (slugMode === 'off') {
312
+ return { ...verdict, triggered: false, decision: 'allow', suppressedByConfig: true };
313
+ }
314
+ if (slugMode === 'warn') {
315
+ return { ...verdict, triggered: true, decision: 'allow', advisory: true, overrideMode: 'warn' };
316
+ }
317
+ if (slugMode === 'block') {
318
+ return { ...verdict, triggered: true, decision: 'deny', advisory: false, overrideMode: 'block' };
319
+ }
320
+ return resolveVerdict(verdict);
321
+ };
322
+ const isCoachAdvisorySuppressed = (detId) => {
323
+ if (!silentCoachMode) return false;
324
+ const explicitOverride = resolveDetectorOverride(detId, this.horizonConfig);
325
+ return explicitOverride !== 'warn' && explicitOverride !== 'block';
326
+ };
327
+
328
+ // 1. DET-20: Quota Hard Brake & Concurrent Scope Lock
329
+ const isSearchRead = SEARCH_READ_TOOL_REGEX.test(toolName);
330
+ const det20 = resolveVerdict(
331
+ evaluateDet20ScopeLockAndQuotaBrake(
332
+ {
333
+ targetFilePath: (EDIT_WRITE_TOOL_REGEX.test(toolName) || isSearchRead) ? filePath : '',
334
+ isRead: isSearchRead,
335
+ toolName,
336
+ ownerId:
337
+ toolEvent.ownerId ||
338
+ toolEvent.agentId ||
339
+ toolEvent.subagentId ||
340
+ telemetryState.sessionId ||
341
+ 'default',
342
+ rateLimits: telemetryState.rateLimits || {}
343
+ },
344
+ this.options
345
+ )
346
+ );
347
+ if (det20.triggered) return det20;
348
+
349
+ // 1.0b Two-Stage Prompt Hygiene Sightseeing Interception (Scope Brake & Relay Breaker Web Search)
350
+ const scopeOverride = resolveDetectorOverride('vague-prompt-rubric', this.horizonConfig);
351
+ const relayOverride = resolveDetectorOverride('relay-breaker', this.horizonConfig);
352
+ const twoStage = evaluateTwoStageSightseeingIntercept({
353
+ toolName,
354
+ toolArgs: toolInput,
355
+ unanchoredTurnFlag: Boolean(toolEvent.unanchoredTurnFlag ?? this.unanchoredTurnFlag),
356
+ candidateFiles: Array.isArray(toolEvent.candidateFiles)
357
+ ? toolEvent.candidateFiles
358
+ : (this.candidateFiles.length > 0 ? this.candidateFiles : Array.from(this.modifiedFilesInTurn)),
359
+ relayState: toolEvent.relayState ?? this.relayState,
360
+ overrideMode: scopeOverride !== 'default' ? scopeOverride : relayOverride,
361
+ flightMode: activeMode,
362
+ detectorId: 'DET-14'
363
+ });
364
+ if (twoStage.intercepted) {
365
+ if (twoStage.consumeFlag) {
366
+ this.unanchoredTurnFlag = false;
367
+ }
368
+ this.sightseeingToolsPrevented = Number(this.sightseeingToolsPrevented || 0) + 1;
369
+ return {
370
+ detectorId: 'DET-14',
371
+ triggered: true,
372
+ subType: twoStage.subType,
373
+ decision: twoStage.decision,
374
+ advisory: twoStage.decision === 'allow',
375
+ reason: twoStage.reason
376
+ };
377
+ }
378
+
379
+ // 1a. RSI-04 ('micro-skills'): Intercept known-broken repo shell commands
380
+ if (SHELL_TOOL_REGEX.test(toolName) && command) {
381
+ const msOverride = resolveDetectorOverride('micro-skills', this.horizonConfig);
382
+ if (msOverride !== 'off') {
383
+ const msReg = loadMicroSkillsRegistry(this.options);
384
+ const msIntercept = evaluateMicroSkillIntercept(msReg, {
385
+ command,
386
+ flightMode: activeMode,
387
+ overrideMode: msOverride
388
+ });
389
+ if (msIntercept.triggered) {
390
+ return {
391
+ detectorId: 'RSI-04',
392
+ triggered: true,
393
+ subType: msIntercept.subType,
394
+ decision: msIntercept.decision,
395
+ advisory: msIntercept.decision === 'allow',
396
+ failedCmd: msIntercept.failedCmd,
397
+ workingCmd: msIntercept.workingCmd,
398
+ reason: msIntercept.reason
399
+ };
400
+ }
401
+ }
402
+ }
403
+
404
+ // 1b. DET-15 ('formatter-bypass'): Local Formatter Bypass on pasted code block
405
+ const det15Bypass = evaluateDet15PreFormatBypass({
406
+ prompt: toolEvent.prompt || toolEvent.user_input || toolInput.prompt || '',
407
+ newText,
408
+ lineCount: toolEvent.fullFileNewLines || (newText ? newText.split(/\r?\n/).length : 0)
409
+ });
410
+ if (det15Bypass.triggered) {
411
+ const resolved = applyHabitSlug('formatter-bypass', det15Bypass);
412
+ if (resolved.triggered) return resolved;
413
+ }
414
+
415
+ // 1c. DET-05 ('drip-feed'): Conversational Drip-Feeding Detector (<90s window)
416
+ if (EDIT_WRITE_TOOL_REGEX.test(toolName) && filePath) {
417
+ const now = Number(toolEvent.timestampMs ?? toolEvent.nowMs ?? Date.now());
418
+ this.recentEditTimestampsByFile = this.recentEditTimestampsByFile || {};
419
+ const tsList = (this.recentEditTimestampsByFile[filePath] || []).filter((t) => (now - t) <= 90000);
420
+ tsList.push(now);
421
+ this.recentEditTimestampsByFile[filePath] = tsList;
422
+ if (tsList.length >= 4) {
423
+ const det05Drip = applyHabitSlug('drip-feed', {
424
+ detectorId: 'DET-05',
425
+ triggered: true,
426
+ subType: 'CONVERSATIONAL_DRIP_FEED',
427
+ decision: activeMode === FLIGHT_MODES.AUTO_PILOT ? 'ask' : 'allow',
428
+ advisory: true,
429
+ reason: `[DET-05 Conversational Drip-Feed] Detected ${tsList.length} rapid edits on "${filePath}" in <90s. Batch multiple micro-requirements into a single turn to preserve KV cache.`
430
+ });
431
+ if (det05Drip.triggered) return det05Drip;
432
+ }
433
+ }
434
+
435
+ // 1d. DET-14 ('vague-prompt-rubric'): Turn-1 Blind Multi-File Edit Gate (TDD *.test.*/*.spec.* exempted)
436
+ const currentTurnNum = Number(
437
+ toolEvent.turnId ??
438
+ toolEvent.turn_id ??
439
+ telemetryState.turnCount ??
440
+ telemetryState.currentTurn ??
441
+ 0
442
+ );
443
+ if (SEARCH_READ_TOOL_REGEX.test(toolName)) {
444
+ this.totalDiscoveryCalls = Number(this.totalDiscoveryCalls || 0) + 1;
445
+ }
446
+ if (EDIT_WRITE_TOOL_REGEX.test(toolName)) {
447
+ const rawPromptStr = String(toolEvent.prompt || toolEvent.user_input || toolInput.prompt || '');
448
+ const hasSpecificAnchor = /(?:^|\s)@[A-Za-z0-9_./\\-]+\.[A-Za-z0-9]+/.test(rawPromptStr);
449
+ const candidateModified = new Set(this.modifiedFilesInTurn);
450
+ if (filePath) candidateModified.add(filePath);
451
+ const nonTestModifiedCount = Array.from(candidateModified).filter((fp) => {
452
+ const np = String(fp || '').replace(/\\/g, '/');
453
+ return !/(?:^|\/)(?:tests?|__tests__|specs?|migrations|docs)\//i.test(np) &&
454
+ !/\.(?:test|spec)\.[a-z0-9]+$|\.md$/i.test(np);
455
+ }).length;
456
+
457
+ if (currentTurnNum <= 1 && Number(this.totalDiscoveryCalls || 0) === 0 && nonTestModifiedCount >= 2 && !hasSpecificAnchor) {
458
+ if (filePath) this.modifiedFilesInTurn.add(filePath);
459
+ const det14Blind = applyHabitSlug('vague-prompt-rubric', {
460
+ detectorId: 'DET-14',
461
+ triggered: true,
462
+ subType: 'BLIND_UNPLANNED_MULTI_EDIT',
463
+ decision: activeMode === FLIGHT_MODES.AUTO_PILOT ? 'deny' : 'allow',
464
+ advisory: activeMode !== FLIGHT_MODES.AUTO_PILOT,
465
+ reason: `[DET-14 Blind Multi-File Edit] Turn 1 multi-file edit (${nonTestModifiedCount} non-test files) with 0 prior read/grep discovery calls. Verify existing architecture or create a plan first.`
466
+ });
467
+ if (det14Blind.triggered) return det14Blind;
468
+ }
469
+ }
470
+
471
+ // 1e. DET-08 ('effort-overkill'): Pinned Opus Max Effort Trivial Streak
472
+ const activeModelId =
473
+ (typeof toolEvent.model === 'string' ? toolEvent.model : toolEvent.model?.id) ||
474
+ toolEvent.modelId ||
475
+ telemetryState.modelId;
476
+ const activeEffort = String(toolEvent.effort || telemetryState.effort || '').toLowerCase();
477
+ const isOpusModel = /(?:claude-)?opus/i.test(String(activeModelId || ''));
478
+ if (EDIT_WRITE_TOOL_REGEX.test(toolName) && isOpusModel && activeEffort === 'max') {
479
+ const { oldLineCount, newLineCount } = computeAddedAndDeletedDiffLines(oldText, newText);
480
+ const diffLinesChanged = Math.abs(newLineCount - oldLineCount);
481
+ if (diffLinesChanged <= 3) {
482
+ this.consecutiveTrivialMaxEffortTurns = Number(this.consecutiveTrivialMaxEffortTurns || 0) + 1;
483
+ } else {
484
+ this.consecutiveTrivialMaxEffortTurns = 0;
485
+ }
486
+ if (this.consecutiveTrivialMaxEffortTurns >= 3 || Number(toolEvent.consecutiveTrivialMaxEffortTurns) >= 3) {
487
+ const det08Streak = applyHabitSlug('effort-overkill', {
488
+ detectorId: 'DET-08',
489
+ triggered: true,
490
+ subType: 'PINNED_MAX_EFFORT_TRIVIAL_STREAK',
491
+ decision: 'allow',
492
+ advisory: true,
493
+ reason: `[DET-08 Pinned Max Effort Streak] Opus 4.6 pinned at effort: max across ${this.consecutiveTrivialMaxEffortTurns} trivial edits (<=3 lines). Run /effort low or switch to Sonnet/Haiku to reduce output token latency by 68%.`
494
+ });
495
+ if (det08Streak.triggered) return det08Streak;
496
+ }
497
+ }
498
+
499
+ // 1f. DET-20 ('vision-screenshot-coach'): Vision / Screenshot & Base64 Accumulation Guard
500
+ let base64ImageBlocks = 0;
501
+ let msgCompoundingVisionTokens = 0;
502
+ if (Array.isArray(toolEvent.messages)) {
503
+ const msgLen = toolEvent.messages.length;
504
+ for (let i = 0; i < msgLen; i++) {
505
+ const msg = toolEvent.messages[i];
506
+ const blocks = Array.isArray(msg?.content) ? msg.content : [];
507
+ let msgImgs = 0;
508
+ for (const b of blocks) {
509
+ if (b && (b.type === 'image' || b?.source?.type === 'base64')) {
510
+ base64ImageBlocks += 1;
511
+ msgImgs += 1;
512
+ }
513
+ }
514
+ if (msgImgs > 0) {
515
+ const turnsResent = Math.max(1, Math.ceil((msgLen - i) / 2));
516
+ msgCompoundingVisionTokens += msgImgs * 1600 * turnsResent;
517
+ }
518
+ }
519
+ }
520
+ const hasImageAttachment = Boolean(
521
+ toolEvent.has_image_attachment ||
522
+ toolEvent.hasImageAttachment ||
523
+ base64ImageBlocks > 0 ||
524
+ (Array.isArray(toolEvent.media) && toolEvent.media.some((m) => String(m?.mime_type || '').startsWith('image/'))) ||
525
+ /\.(?:png|jpg|jpeg|webp|gif)$/i.test(filePath)
526
+ );
527
+ if (hasImageAttachment) {
528
+ this.consecutiveVisionTurns = Number(this.consecutiveVisionTurns || 0) + 1;
529
+ } else {
530
+ this.consecutiveVisionTurns = 0;
531
+ }
532
+ const effectiveConsecutiveVision = Math.max(
533
+ this.consecutiveVisionTurns,
534
+ Number(toolEvent.consecutive_vision_turns ?? toolEvent.consecutiveVisionTurns ?? 0)
535
+ );
536
+ const imageCount = Math.max(
537
+ base64ImageBlocks,
538
+ Number(toolEvent.image_count ?? toolEvent.imageCount ?? (hasImageAttachment ? 1 : 0))
539
+ );
540
+ if ((effectiveConsecutiveVision >= 2 || imageCount >= 2) && hasImageAttachment) {
541
+ const cumulativeVisionTaxTokens = Math.max(
542
+ msgCompoundingVisionTokens,
543
+ imageCount * 1600 * Math.max(1, effectiveConsecutiveVision)
544
+ );
545
+ const det20Vision = applyHabitSlug('vision-screenshot-coach', {
546
+ detectorId: 'DET-20',
547
+ triggered: true,
548
+ subType: 'VISION_SCREENSHOT_ABUSE',
549
+ decision: 'allow',
550
+ advisory: true,
551
+ base64ImageBlocks,
552
+ cumulativeVisionTaxTokens,
553
+ reason: `[DET-20 Vision Token Drain] ${imageCount} screenshot/image blocks accumulated (~${cumulativeVisionTaxTokens.toLocaleString()} cumulative vision tokens) for text-debuggable issues. Paste error logs or DOM/CSS snippets directly.`
554
+ });
555
+ if (det20Vision.triggered) return det20Vision;
556
+ }
557
+
558
+ // 2. DET-16: Subagent Recursion Cap (40k tokens / 12 turns)
559
+ const agentId = toolEvent.agentId || toolEvent.subagentId || null;
560
+ if (agentId) {
561
+ const subFromTelemetry = telemetryState.subagents?.[agentId];
562
+ const turns =
563
+ subFromTelemetry?.turns !== undefined
564
+ ? Number(subFromTelemetry.turns)
565
+ : Number(this.subagentTurns[agentId] || 0);
566
+ const totalTokens =
567
+ subFromTelemetry?.totalTokens !== undefined
568
+ ? Number(subFromTelemetry.totalTokens)
569
+ : Number(this.subagentTokens[agentId] || 0);
570
+ if (subFromTelemetry || turns > 0 || totalTokens > 0) {
571
+ const det16 = resolveVerdict(
572
+ evaluateDet16SubagentRecursionCap({
573
+ agentId,
574
+ turns,
575
+ totalTokens
576
+ })
577
+ );
578
+ if (det16.triggered) return det16;
579
+ }
580
+ this.subagentTurns[agentId] = turns + 1;
581
+ this.subagentTokens[agentId] = totalTokens + Math.max(0, Number(toolEvent.tokensUsed || 0));
582
+ }
583
+
584
+ // 3. DET-04: Consecutive Tool Failure Breaker (>= 3)
585
+ const det04 = resolveVerdict(
586
+ evaluateDet04ConsecutiveFailures({
587
+ consecutiveFailures: this.consecutiveFailures,
588
+ threshold: this.horizonConfig?.thresholds?.consecutiveFailureLimit
589
+ })
590
+ );
591
+ if (det04.triggered) return det04;
592
+
593
+ // 4. DET-01: Destructive Shell & Git Hook-Bypass Blocker (Ring-0 Security + #3 Test Integrity + #18 Worktree Discard)
594
+ const effectiveUserPrompt = String(
595
+ toolEvent.lastUserInput ?? toolEvent.prompt ?? toolEvent.user_input ?? this.lastUserPrompt ?? ''
596
+ );
597
+ const det01 = resolveVerdict(
598
+ evaluateDet01GitAndShellSafety({
599
+ toolName,
600
+ command,
601
+ lastUserInput: effectiveUserPrompt,
602
+ userExplicitTestIntent: Boolean(toolEvent.userExplicitTestIntent)
603
+ })
604
+ );
605
+ if (det01.triggered) return det01;
606
+
607
+ // 4b. Item A9 (#18): Concurrent Multi-Agent Worktree Isolation Guard on write-capable Task/Agent spawns
608
+ if (/^(?:Task|Agent)$/i.test(toolName) && !isCoachAdvisorySuppressed('DET-20')) {
609
+ const subagentType = String(
610
+ toolInput.subagent_type || toolInput.subagentType || toolInput.agent_type || toolInput.type || ''
611
+ ).trim();
612
+ const isReadOnlySubagent =
613
+ /^(?:Explore|Plan|research|claude-code-guide|ah-flash-scout)$/i.test(subagentType) ||
614
+ toolInput.readonly === true;
615
+ if (!isReadOnlySubagent) {
616
+ const isolation = String(toolInput.isolation || '').trim().toLowerCase();
617
+ const activeLocksCount = readActiveScopeLocks(this.options).locks.length;
618
+ const activeWorkersCount = Math.max(
619
+ activeLocksCount,
620
+ Array.isArray(this.activeWriteWorkers) ? this.activeWriteWorkers.length : 0,
621
+ Number(toolEvent.activeWriteWorkers ?? telemetryState.activeWriteWorkers ?? 0)
622
+ );
623
+ if (isolation !== 'worktree' && activeWorkersCount >= 1) {
624
+ const det20Worktree = resolveVerdict({
625
+ detectorId: 'DET-20',
626
+ triggered: true,
627
+ subType: 'WORKTREE_ISOLATION_REQUIRED',
628
+ decision: activeMode === FLIGHT_MODES.AUTO_PILOT ? 'deny' : 'ask',
629
+ advisory: false,
630
+ reason:
631
+ `[DET-20 Worktree Isolation Guard (#18)] Spawning write-capable ${toolName} without isolation: "worktree" while ${activeWorkersCount} write worker(s)/lock(s) are already active risks shared-tree clobbering. Set isolation: "worktree".`
632
+ });
633
+ if (det20Worktree.triggered) return det20Worktree;
634
+ }
635
+ if (toolInput.run_in_background === true || toolInput.background === true) {
636
+ const workerId = String(
637
+ toolInput.name || toolInput.description || `${toolName}_${Date.now()}`
638
+ ).slice(0, 60);
639
+ if (!this.activeWriteWorkers.includes(workerId)) {
640
+ this.activeWriteWorkers.push(workerId);
641
+ }
642
+ }
643
+ }
644
+ }
645
+
646
+ // 5. DET-02: Secret & Credential Boundary (Ring-0 Security)
647
+ const det02 = resolveVerdict(evaluateDet02SecretBoundary({ toolName, filePath, command }));
648
+ if (det02.triggered) return det02;
649
+
650
+ // 6. DET-18: Untrusted Project settings.json CVE & Clobber Guard (Ring-0 Security)
651
+ const det18 = resolveVerdict(
652
+ evaluateDet18UntrustedSettingsGuard({
653
+ toolName,
654
+ filePath,
655
+ newText,
656
+ hasBackup: Boolean(toolEvent.hasBackup)
657
+ })
658
+ );
659
+ if (det18.triggered) return det18;
660
+
661
+ // 7. DET-03: Protected Migration, Lockfile & Workflow Ask Gate
662
+ const det03 = resolveVerdict(evaluateDet03ProtectedFilesAskGate({ toolName, filePath }));
663
+ if (det03.triggered) return det03;
664
+
665
+ // 8. DET-19: Untrusted URL Exfiltration Guard on WebFetch (Ring-0 Security)
666
+ if (/^WebFetch$/i.test(toolName) && urlStr) {
667
+ const det19Url = resolveVerdict(
668
+ evaluateDet19SubagentIpiSanitizer({ url: urlStr, wrapUntrusted: false })
669
+ );
670
+ if (det19Url.triggered && (det19Url.decision === 'deny' || det19Url.advisory)) {
671
+ return det19Url;
672
+ }
673
+ }
674
+
675
+ // 9. DET-05: AST/Diff Edit Thrashing, Test Integrity (#3) & Error Masking (#12) Breaker
676
+ if (EDIT_WRITE_TOOL_REGEX.test(toolName)) {
677
+ if (oldText || newText) {
678
+ const history = this.fileHashHistory.get(filePath) || [];
679
+ const rawDet05 = evaluateDet05DiffThrashing({
680
+ filePath,
681
+ oldText,
682
+ newText,
683
+ toolName,
684
+ flightMode: activeMode,
685
+ lastUserInput: effectiveUserPrompt,
686
+ userExplicitTestIntent: Boolean(toolEvent.userExplicitTestIntent),
687
+ fullFileOldLines: toolEvent.fullFileOldLines,
688
+ fullFileNewLines: toolEvent.fullFileNewLines,
689
+ hashHistory: history
690
+ });
691
+ const det05 = resolveVerdict(rawDet05);
692
+ if (det05.triggered) {
693
+ this.router.hysteresisLock.engage({
694
+ model: telemetryState.modelId || 'claude-opus-5-5',
695
+ effort: 'high',
696
+ reason: det05.subType
697
+ });
698
+ return det05;
699
+ }
700
+ history.push(rawDet05.nextHash);
701
+ this.fileHashHistory.set(filePath, history.slice(-6));
702
+ }
703
+ if (filePath) {
704
+ this.modifiedFilesInTurn.add(filePath);
705
+ this.pendingFormatFiles.add(filePath);
706
+ if (/^MultiEdit$/i.test(toolName)) {
707
+ this.pendingBatchEdits.add(filePath);
708
+ }
709
+ }
710
+ this.codeEditedSinceLastTest = true;
711
+ this.sequentialSearchCount = 0;
712
+
713
+ // 9b. DET-09: Warm-Prefix Instruction / MCP Config Mutation Fence (`CLAUDE.md`, `AGENTS.md`, `.mcp.json`, `.claude/rules/*.md`)
714
+ if (filePath && isPrefixInstructionFile(filePath) && !isCoachAdvisorySuppressed('DET-09')) {
715
+ const ttlRem =
716
+ toolEvent.ttlRemainingSeconds ??
717
+ telemetryState.promptCache?.ttlSeconds ??
718
+ telemetryState.ttlRemainingSeconds;
719
+ const ttlExpired = ttlRem !== undefined && ttlRem !== null && Number(ttlRem) <= 0;
720
+ const cachedTokens = Number(
721
+ toolEvent.cachedTokens ??
722
+ telemetryState.contextWindow?.cachedTokens ??
723
+ telemetryState.contextWindow?.cacheReadTokens ??
724
+ 0
725
+ );
726
+ const cacheWarm =
727
+ !ttlExpired &&
728
+ Boolean(toolEvent.cacheWarm ?? telemetryState.promptCache?.warm) &&
729
+ cachedTokens > 0;
730
+
731
+ if (cacheWarm) {
732
+ const det09Raw = this.router.interceptTopLevelMutation({
733
+ type: 'system_prompt',
734
+ key: filePath,
735
+ value: newText.slice(0, 120),
736
+ filePath,
737
+ currentModel:
738
+ (typeof toolEvent.model === 'string' ? toolEvent.model : toolEvent.model?.id) ||
739
+ toolEvent.modelId ||
740
+ telemetryState.modelId ||
741
+ 'claude-opus-5-5',
742
+ cachedTokens,
743
+ cacheWarm: true,
744
+ ttlRemainingSeconds: ttlRem,
745
+ cacheTtlTier: telemetryState.promptCache?.ttlTier || '5m'
746
+ });
747
+ if (det09Raw.triggered) {
748
+ const det09 = resolveVerdict(
749
+ activeMode === FLIGHT_MODES.AUTO_PILOT
750
+ ? det09Raw
751
+ : { ...det09Raw, decision: 'allow', advisory: true }
752
+ );
753
+ if (det09.triggered) return det09;
754
+ }
755
+ }
756
+ }
757
+ }
758
+
759
+ // 10. DET-07: Unbounded Command Output Bomb Guard
760
+ const det07 = resolveVerdict(
761
+ evaluateDet07OutputBombGuard({
762
+ toolName,
763
+ command,
764
+ filePath,
765
+ limit: toolInput.limit ?? toolEvent.limit
766
+ })
767
+ );
768
+ if (det07.triggered) return det07;
769
+
770
+ // Track git commit and test runs in shell commands
771
+ if (SHELL_TOOL_REGEX.test(toolName)) {
772
+ if (/\bgit\s+commit\b/i.test(command)) {
773
+ this.lastTurnGitCommitted = true;
774
+ this.committedTopDirs = Array.from(this.modifiedFilesInTurn)
775
+ .map((f) => f.split(/[\\/]/)[0])
776
+ .filter(Boolean);
777
+ }
778
+ if (
779
+ /\b(?:node\s+--test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|bun\s+test|vitest|jest|pytest|cargo\s+test|go\s+test|tsc(?:\s|$)|npx\s+tsc)\b/i.test(
780
+ command
781
+ )
782
+ ) {
783
+ this.pendingVerificationCommand = true;
784
+ }
785
+ this.sequentialSearchCount = 0;
786
+ }
787
+
788
+ // 11. DET-06: Main-Thread Blind Search Guard (> 6 sequential Read/Grep calls) + Repo Calibration
789
+ if (SEARCH_READ_TOOL_REGEX.test(toolName) && !agentId) {
790
+ this.sequentialSearchCount += 1;
791
+ let chronicAdvisory = null;
792
+ if (
793
+ /^(?:Read|read_file)$/i.test(toolName) &&
794
+ filePath &&
795
+ (this.options.enableRepoCalibration || this.options.calibrationPath)
796
+ ) {
797
+ let estimatedReadTokens = 0;
798
+ if (toolEvent.estimatedTokens !== undefined && toolEvent.estimatedTokens !== null) {
799
+ estimatedReadTokens = Math.max(0, Number(toolEvent.estimatedTokens));
800
+ } else if (Number(toolEvent.fileByteSize) > 0) {
801
+ estimatedReadTokens = Math.ceil(Number(toolEvent.fileByteSize) / 4);
802
+ } else {
803
+ const resolvedReadPath = resolvePath(getCwd(this.options), filePath);
804
+ const byteSize = getFileByteSizeSafe(resolvedReadPath, this.options);
805
+ estimatedReadTokens = byteSize > 0 ? Math.ceil(byteSize / 4) : 0;
806
+ }
807
+ const cal = recordRepoFileRead(
808
+ {
809
+ filePath,
810
+ estimatedTokens: estimatedReadTokens,
811
+ sessionId: telemetryState.sessionId || 'default'
812
+ },
813
+ this.options
814
+ );
815
+ if (cal.isChronicSink) {
816
+ chronicAdvisory = cal.recommendation;
817
+ }
818
+ }
819
+
820
+ if (!isCoachAdvisorySuppressed('DET-06')) {
821
+ const blindLimit = this.horizonConfig?.thresholds?.blindSearchLimit;
822
+ const det06 = resolveVerdict(
823
+ evaluateDet06BlindSearchGuard({
824
+ sequentialSearchCount: this.sequentialSearchCount,
825
+ threshold: blindLimit,
826
+ limit: blindLimit
827
+ })
828
+ );
829
+ if (det06.triggered) {
830
+ return chronicAdvisory
831
+ ? { ...det06, reason: `${det06.reason} | ${chronicAdvisory}` }
832
+ : det06;
833
+ }
834
+ if (chronicAdvisory && resolveDetectorOverride('DET-06', this.horizonConfig) !== 'off') {
835
+ return resolveVerdict({
836
+ detectorId: 'DET-06',
837
+ triggered: true,
838
+ decision: 'allow',
839
+ advisory: true,
840
+ subType: 'CHRONIC_REPO_FILE_SINK',
841
+ reason: chronicAdvisory
842
+ });
843
+ }
844
+ }
845
+ }
846
+
847
+ // 12. DET-12: Haiku 5.5 90,000-Token Pre-Cliff Breaker
848
+ const eventUsage = toolEvent.usage || toolEvent.context_window?.current_usage || null;
849
+ const totalDet12Tokens = Math.max(
850
+ computeTotalPromptTokens(telemetryState.contextWindow || {}),
851
+ computeTotalPromptTokens(toolEvent),
852
+ eventUsage ? computeTotalPromptTokens(eventUsage) : 0
853
+ );
854
+ const rawDet12 = evaluateDet12HaikuPreCliffBreaker({
855
+ modelId: activeModelId,
856
+ totalPromptTokens: totalDet12Tokens
857
+ });
858
+ if (rawDet12.triggered) {
859
+ // Hard >=98k cliff protection stays active even in SILENT/OFF unless explicitly overridden to 'off'
860
+ if (!rawDet12.advisory || !isCoachAdvisorySuppressed('DET-12')) {
861
+ const det12 = resolveVerdict(rawDet12);
862
+ if (det12.triggered) return det12;
863
+ }
864
+ }
865
+
866
+ const turnKey = String(
867
+ toolEvent.turnId ??
868
+ toolEvent.turn_id ??
869
+ telemetryState.turnCount ??
870
+ telemetryState.currentTurn ??
871
+ 0
872
+ );
873
+
874
+ // 13. DET-13: MCP Schema Bloat & tools_changed Cache-Miss Guard (once per turn)
875
+ if (!isCoachAdvisorySuppressed('DET-13') && this.det13AdvisedTurn !== turnKey) {
876
+ const mcpSchemaTokens = Number(
877
+ toolEvent.mcpSchemaTokens ??
878
+ telemetryState.mcpSchemaTokens ??
879
+ telemetryState.mcp?.schemaTokens ??
880
+ 0
881
+ );
882
+ const mcpToolCount = Number(
883
+ toolEvent.mcpToolCount ??
884
+ telemetryState.mcpToolCount ??
885
+ telemetryState.mcp?.toolCount ??
886
+ 0
887
+ );
888
+ const lastMissCause =
889
+ toolEvent.lastMissCause ||
890
+ telemetryState.lastMissCause ||
891
+ telemetryState.promptCache?.lastMissCause ||
892
+ (toolEvent.toolsChanged || telemetryState.toolsChanged ? 'tools_changed' : null);
893
+
894
+ if (mcpSchemaTokens > 0 || mcpToolCount > 0 || lastMissCause) {
895
+ const det13 = resolveVerdict(
896
+ evaluateDet13McpSchemaBloatGuard({
897
+ mcpSchemaTokens,
898
+ mcpToolCount,
899
+ lastMissCause,
900
+ bundledSkillsTokens: Number(toolEvent.bundledSkillsTokens ?? telemetryState.bundledSkillsTokens ?? 0),
901
+ syncedSkillsTokens: Number(toolEvent.syncedSkillsTokens ?? telemetryState.syncedSkillsTokens ?? 0),
902
+ claudeMdTokens: Number(toolEvent.claudeMdTokens ?? telemetryState.claudeMdTokens ?? 0),
903
+ turnsElapsed: Number(toolEvent.turnsElapsed ?? toolEvent.turnId ?? toolEvent.turn_id ?? telemetryState.turnCount ?? 0),
904
+ mcpInvocations: Number(toolEvent.mcpInvocations ?? telemetryState.mcpInvocations ?? 0)
905
+ })
906
+ );
907
+ if (det13.triggered) {
908
+ this.det13AdvisedTurn = turnKey;
909
+ return det13;
910
+ }
911
+ }
912
+ }
913
+
914
+ // 14. DET-11: Context Rot Soft Horizon Gate (once per turn)
915
+ if (!isCoachAdvisorySuppressed('DET-11') && this.det11AdvisedTurn !== turnKey) {
916
+ const totalInputTokens = Math.max(
917
+ totalDet12Tokens,
918
+ Number(
919
+ toolEvent.totalInputTokens ??
920
+ telemetryState.totalInputTokens ??
921
+ telemetryState.contextWindow?.totalInputTokens ??
922
+ 0
923
+ )
924
+ );
925
+ const distractorTokens =
926
+ toolEvent.distractorTokens ??
927
+ telemetryState.distractorTokens ??
928
+ telemetryState.contextWindow?.distractorTokens;
929
+ const distractorRatio =
930
+ toolEvent.distractorRatio ??
931
+ telemetryState.distractorRatio ??
932
+ telemetryState.contextWindow?.distractorRatio;
933
+
934
+ const postCommitOverride = resolveDetectorOverride('post-commit-handoff', this.horizonConfig);
935
+ const postCommitTopicShift =
936
+ postCommitOverride !== 'off' &&
937
+ Boolean(
938
+ toolEvent.postCommitTopicShift ??
939
+ toolEvent.topic_shift ??
940
+ toolEvent.topicShift ??
941
+ (this.lastTurnGitCommitted && (toolEvent.topic_shift || toolEvent.topicShift))
942
+ );
943
+
944
+ if (
945
+ (totalInputTokens > 0 &&
946
+ (distractorTokens !== undefined || distractorRatio !== undefined)) ||
947
+ postCommitTopicShift
948
+ ) {
949
+ const rawDet11 = evaluateDet11ContextRotGate({
950
+ totalInputTokens,
951
+ distractorTokens,
952
+ distractorRatio,
953
+ turnId: currentTurnNum,
954
+ lastTurnGitCommitted: this.lastTurnGitCommitted || Boolean(toolEvent.last_turn_git_committed),
955
+ topicShiftDetected: Boolean(toolEvent.topic_shift || toolEvent.topicShift),
956
+ postCommitTopicShift
957
+ });
958
+ const det11 =
959
+ rawDet11.subType === 'POST_COMMIT_TOPIC_SHIFT'
960
+ ? applyHabitSlug('post-commit-handoff', rawDet11)
961
+ : resolveVerdict(rawDet11);
962
+ if (det11.triggered) {
963
+ this.det11AdvisedTurn = turnKey;
964
+ return det11;
965
+ }
966
+ }
967
+ }
968
+
969
+ return {
970
+ detectorId: null,
971
+ triggered: false,
972
+ decision: 'allow',
973
+ reason: null
974
+ };
975
+ }
976
+
977
+ /**
978
+ * Records tool outcome to update `DET-04` consecutive failure counter.
979
+ * @param {boolean} succeeded
980
+ * @param {string | null} [toolKey=null]
981
+ */
982
+ recordToolOutcome(succeeded = true, toolKey = null) {
983
+ if (succeeded) {
984
+ this.consecutiveFailures = 0;
985
+ this.lastFailedToolKey = null;
986
+ } else {
987
+ this.consecutiveFailures += 1;
988
+ if (toolKey) {
989
+ this.lastFailedToolKey = String(toolKey);
990
+ }
991
+ }
992
+ return this.consecutiveFailures;
993
+ }
994
+
995
+ /**
996
+ * Updates `codeEditedSinceLastTest` and `lastFailingLocation` strictly on `PostToolUse`
997
+ * after a test/typecheck command actually completes with `exit_code === 0`.
998
+ *
999
+ * @param {{ succeeded: boolean, command?: string, outputText?: string }} outcome
1000
+ */
1001
+ recordVerificationOutcome(outcome = {}) {
1002
+ const succeeded = Boolean(outcome.succeeded);
1003
+ const command = String(outcome.command || '');
1004
+ const outputText = String(outcome.outputText || '');
1005
+ const isVerificationCmd =
1006
+ this.pendingVerificationCommand ||
1007
+ /\b(?:node\s+--test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|bun\s+test|vitest|jest|pytest|cargo\s+test|go\s+test|tsc(?:\s|$)|npx\s+tsc)\b/i.test(
1008
+ command
1009
+ );
1010
+
1011
+ if (!isVerificationCmd) {
1012
+ return {
1013
+ wasVerificationCommand: false,
1014
+ codeEditedSinceLastTest: this.codeEditedSinceLastTest,
1015
+ lastFailingLocation: this.lastFailingLocation
1016
+ };
1017
+ }
1018
+
1019
+ this.pendingVerificationCommand = false;
1020
+ if (succeeded) {
1021
+ this.codeEditedSinceLastTest = false;
1022
+ this.unverifiedEdits = [];
1023
+ this.lastFailingLocation = null;
1024
+ } else {
1025
+ if (this.modifiedFilesInTurn.size > 0 || this.codeEditedSinceLastTest) {
1026
+ this.codeEditedSinceLastTest = true;
1027
+ }
1028
+ const locMatch = outputText.match(
1029
+ /([A-Za-z0-9_./\\-]+\.(?:[cm]?[jt]sx?|py|rs|go|rb|java|kt|swift|c|cpp|h|hpp)):(\d+)(?::\d+)?/
1030
+ );
1031
+ if (locMatch) {
1032
+ this.lastFailingLocation = `${locMatch[1].replace(/\\/g, '/')}:${locMatch[2]}`;
1033
+ }
1034
+ }
1035
+
1036
+ return {
1037
+ wasVerificationCommand: true,
1038
+ codeEditedSinceLastTest: this.codeEditedSinceLastTest,
1039
+ lastFailingLocation: this.lastFailingLocation
1040
+ };
1041
+ }
1042
+
1043
+ /**
1044
+ * Evaluates `UserPromptSubmit` for Prompt Hygiene Governor (v4.1 Phase 1):
1045
+ * Relay Breaker (`'relay-breaker'`) & Scope Brake (`'vague-prompt-rubric'`).
1046
+ *
1047
+ * @param {object} [promptEvent={}]
1048
+ * @param {object} [telemetryState={}]
1049
+ */
1050
+ evaluateUserPromptSubmit(promptEvent = {}, telemetryState = {}) {
1051
+ const prompt = String(
1052
+ promptEvent.prompt ?? promptEvent.user_input ?? promptEvent.message ?? ''
1053
+ );
1054
+ this.lastUserPrompt = prompt;
1055
+ const activeMode = normalizeFlightMode(
1056
+ promptEvent.mode || telemetryState.flightMode || this.mode || FLIGHT_MODES.COACH
1057
+ );
1058
+ if (activeMode === FLIGHT_MODES.OFF) {
1059
+ return { triggered: false, decision: 'allow', reason: null };
1060
+ }
1061
+
1062
+ // Item A6 (#11): Active DET-30 Thinking Runaway Step-Down Gate (>4,000 thinking tokens & >12x ratio across >=2 turns)
1063
+ const det30Override = resolveDetectorOverride('DET-30', this.horizonConfig);
1064
+ if (det30Override !== 'off' && activeMode !== FLIGHT_MODES.SILENT) {
1065
+ const det30Eval = evaluateActiveDet30StepDown({
1066
+ recentTurns: promptEvent.recentTurns || telemetryState.recentTurns,
1067
+ thinkingDrift: promptEvent.thinkingDrift || telemetryState.thinkingDrift,
1068
+ mode: det30Override === 'block' ? FLIGHT_MODES.AUTO_PILOT : (det30Override === 'warn' ? FLIGHT_MODES.COACH : activeMode)
1069
+ });
1070
+ if (det30Eval.triggered) {
1071
+ if (det30Eval.decision === 'block') {
1072
+ this.blockedPrompts = Number(this.blockedPrompts || 0) + 1;
1073
+ } else {
1074
+ this.steeredPrompts = Number(this.steeredPrompts || 0) + 1;
1075
+ }
1076
+ return det30Eval;
1077
+ }
1078
+ }
1079
+
1080
+ const modifiedNonMd = Array.from(this.modifiedFilesInTurn).filter(
1081
+ (f) => !/\.md$/i.test(String(f || ''))
1082
+ );
1083
+ const relayOverride = resolveDetectorOverride('relay-breaker', this.horizonConfig);
1084
+ const relayEval = evaluateRelayBreaker({
1085
+ prompt,
1086
+ relayState: promptEvent.relayState ?? this.relayState,
1087
+ sourceCodeEditsInSession: Number(
1088
+ promptEvent.sourceCodeEditsInSession ?? modifiedNonMd.length
1089
+ ),
1090
+ sourceCodeEditedSinceLastRelay: Boolean(promptEvent.sourceCodeEditedSinceLastRelay),
1091
+ priorTurnWebSearches: Number(promptEvent.priorTurnWebSearches ?? 0),
1092
+ zeroEditSessionTokens: Number(
1093
+ promptEvent.zeroEditSessionTokens ??
1094
+ (modifiedNonMd.length === 0 ? (telemetryState.contextWindow?.totalInputTokens || 0) : 0)
1095
+ ),
1096
+ boundSpecPath: promptEvent.boundSpecPath ?? this.relayState?.boundSpecPath ?? 'SPEC.md',
1097
+ overrideMode: relayOverride,
1098
+ flightMode: activeMode,
1099
+ detectorId: 'DET-14'
1100
+ });
1101
+ this.relayState = relayEval.relayStateSnapshot;
1102
+ if (relayEval.triggered) {
1103
+ if (relayEval.decision === 'block') {
1104
+ this.blockedPrompts = Number(this.blockedPrompts || 0) + 1;
1105
+ } else {
1106
+ this.steeredPrompts = Number(this.steeredPrompts || 0) + 1;
1107
+ }
1108
+ return {
1109
+ detectorId: 'DET-14',
1110
+ slug: 'relay-breaker',
1111
+ triggered: true,
1112
+ subType: relayEval.subType,
1113
+ decision: relayEval.decision,
1114
+ relayState: relayEval.nextState,
1115
+ hudBadge: relayEval.hudBadge,
1116
+ reason: relayEval.tailInjection
1117
+ };
1118
+ }
1119
+
1120
+ const scopeOverride = resolveDetectorOverride('vague-prompt-rubric', this.horizonConfig);
1121
+ const scopeEval = evaluateScopeBrake({
1122
+ prompt,
1123
+ provenance: promptEvent.provenance || promptEvent.source || 'user',
1124
+ isAutonomousTurn: Boolean(promptEvent.isAutonomousTurn || promptEvent.autonomous),
1125
+ isSubagent: Boolean(promptEvent.isSubagent || promptEvent.agentId || promptEvent.subagentId),
1126
+ isScheduledTask: Boolean(promptEvent.isScheduledTask),
1127
+ isLoopIteration: Boolean(promptEvent.isLoopIteration),
1128
+ priorTurnEditedFilesCount: Number(
1129
+ promptEvent.priorTurnEditedFilesCount ?? this.modifiedFilesInTurn.size
1130
+ ),
1131
+ priorTurnSingleFileTarget:
1132
+ promptEvent.priorTurnSingleFileTarget ??
1133
+ (this.modifiedFilesInTurn.size === 1 ? Array.from(this.modifiedFilesInTurn)[0] : null),
1134
+ priorTurnHadToolOrTestFailure: Boolean(
1135
+ promptEvent.priorTurnHadToolOrTestFailure ?? (this.consecutiveFailures > 0)
1136
+ ),
1137
+ priorTurnAssistantAskedQuestion: Boolean(promptEvent.priorTurnAssistantAskedQuestion),
1138
+ activeSetPaths: promptEvent.activeSetPaths || [],
1139
+ modifiedFiles: Array.from(this.modifiedFilesInTurn),
1140
+ recentlyViewedFiles: promptEvent.recentlyViewedFiles || [],
1141
+ overrideMode: scopeOverride,
1142
+ flightMode: activeMode,
1143
+ detectorId: 'DET-14'
1144
+ });
1145
+ if (scopeEval.triggered) {
1146
+ this.unanchoredTurnFlag = true;
1147
+ this.candidateFiles = scopeEval.candidateFiles;
1148
+ if (scopeEval.decision === 'block') {
1149
+ this.blockedPrompts = Number(this.blockedPrompts || 0) + 1;
1150
+ } else {
1151
+ this.steeredPrompts = Number(this.steeredPrompts || 0) + 1;
1152
+ }
1153
+ return {
1154
+ detectorId: 'DET-14',
1155
+ slug: 'vague-prompt-rubric',
1156
+ triggered: true,
1157
+ subType: scopeEval.subType,
1158
+ decision: scopeEval.decision,
1159
+ candidateFiles: scopeEval.candidateFiles,
1160
+ reason: scopeEval.decision === 'block' ? scopeEval.blockReason : scopeEval.steerContext
1161
+ };
1162
+ }
1163
+
1164
+ this.unanchoredTurnFlag = false;
1165
+ return {
1166
+ detectorId: null,
1167
+ triggered: false,
1168
+ decision: 'allow',
1169
+ reason: null
1170
+ };
1171
+ }
1172
+ }
1173
+
1174
+ export default {
1175
+ tokenizeShellSegment,
1176
+ sanitizeBreakerSessionId,
1177
+ getBreakerStateFilePath,
1178
+ readBreakerStateSnapshot,
1179
+ writeBreakerStateSnapshot,
1180
+ evaluateDet01GitAndShellSafety,
1181
+ evaluateDet02SecretBoundary,
1182
+ evaluateDet03ProtectedFilesAskGate,
1183
+ evaluateDet04ConsecutiveFailures,
1184
+ computeAddedAndDeletedDiffLines,
1185
+ hashFileContent,
1186
+ evaluateDet05DiffThrashing,
1187
+ evaluateDet06BlindSearchGuard,
1188
+ evaluateDet07OutputBombGuard,
1189
+ isPrefixInstructionFile,
1190
+ evaluateDet09PrefixMutationFence,
1191
+ evaluateDet11ContextRotGate,
1192
+ evaluateDet12HaikuPreCliffBreaker,
1193
+ evaluateDet13McpSchemaBloatGuard,
1194
+ evaluateDet14PrematureStopGate,
1195
+ evaluateDet15BatchedStopFormatter,
1196
+ evaluateDet16SubagentRecursionCap,
1197
+ evaluateDet17AutoCompactionDeferral,
1198
+ evaluateDet18UntrustedSettingsGuard,
1199
+ evaluateDet19SubagentIpiSanitizer,
1200
+ evaluateDet20ScopeLockAndQuotaBrake,
1201
+ CircuitBreakerEngine
1202
+ };