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