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,913 @@
1
+ /**
2
+ * @file src/core-isomorphic/guards/det13_20_mcp_scope.mjs
3
+ * MCP Schema Bloat, Premature Stop, Format Batch, Subagent Recursion, Auto-Compaction, Settings Guard, IPI Sanitizer & Scope Lock (`DET-13`..`DET-20`).
4
+ * Pure-V8 isomorphic ESM module (zero `node:*` imports).
5
+ */
6
+
7
+ import { path, getCwd, readJsonSafe, writeJsonAtomic } from '../utils/runtime.mjs';
8
+ import {
9
+ FLIGHT_MODES,
10
+ normalizeFlightMode,
11
+ isSilentOrOffMode
12
+ } from '../coach/cacheGravityRouter.mjs';
13
+ import { RELAY_STATES } from '../coach/promptHygieneGovernor.mjs';
14
+ import { evaluateScopeAndQuotaBrake } from '../telemetry/scopeLockRegistry.mjs';
15
+ import { EDIT_WRITE_TOOL_REGEX } from './det01_03_shell_secret.mjs';
16
+
17
+ /**
18
+ * DET-13: MCP Schema Bloat (`> 15k` startup tokens / `20+` tools) & `tools_changed` Cache-Miss Guard.
19
+ *
20
+ * @param {object} [params={}]
21
+ * @param {number} [params.mcpSchemaTokens=0]
22
+ * @param {number} [params.mcpToolCount=0]
23
+ * @param {string|null} [params.lastMissCause=null]
24
+ * @param {boolean} [params.toolsChanged=false]
25
+ * @param {boolean} [params.cacheWarm=false]
26
+ */
27
+ export function evaluateDet13McpSchemaBloatGuard(params = {}) {
28
+ const mcpSchemaTokens = Math.max(0, Number(params.mcpSchemaTokens || 0));
29
+ const mcpToolCount = Math.max(0, Number(params.mcpToolCount || 0));
30
+ const bundledSkillsTokens = Math.max(0, Number(params.bundledSkillsTokens || 0));
31
+ const syncedSkillsTokens = Math.max(0, Number(params.syncedSkillsTokens || 0));
32
+ const claudeMdTokens = Math.max(0, Number(params.claudeMdTokens || 0));
33
+ const turnsElapsed = Math.max(0, Number(params.turnsElapsed || 0));
34
+ const mcpInvocations = Math.max(0, Number(params.mcpInvocations || 0));
35
+ const turn0StaticPrefillBreakdown = {
36
+ bundledSkillsTokens,
37
+ syncedSkillsTokens,
38
+ mcpSchemaTokens,
39
+ claudeMdTokens,
40
+ totalStaticPrefillTokens:
41
+ bundledSkillsTokens + syncedSkillsTokens + mcpSchemaTokens + claudeMdTokens
42
+ };
43
+
44
+ const lastMissCause =
45
+ params.lastMissCause || (params.toolsChanged ? 'tools_changed' : null);
46
+
47
+ if (lastMissCause === 'tools_changed') {
48
+ return {
49
+ detectorId: 'DET-13',
50
+ triggered: true,
51
+ decision: 'defer_mcp_mutation',
52
+ advisory: true,
53
+ subType: 'TOOLS_CHANGED_CACHE_MISS',
54
+ mcpSchemaTokens,
55
+ mcpToolCount,
56
+ turn0StaticPrefillBreakdown,
57
+ reason: `[DET-13 MCP Cache-Miss Guard] Mid-session MCP "tools_changed" invalidated the warm prompt cache prefix. Queue dynamic MCP registrations in PostCompactMutationQueue.`
58
+ };
59
+ }
60
+
61
+ const idleMcpHoarding5Turns =
62
+ mcpSchemaTokens >= 15_000 && turnsElapsed >= 5 && mcpInvocations === 0;
63
+
64
+ if (idleMcpHoarding5Turns) {
65
+ return {
66
+ detectorId: 'DET-13',
67
+ triggered: true,
68
+ decision: 'advise_lazy_mcp',
69
+ advisory: true,
70
+ subType: 'IDLE_MCP_HOARDING_5_TURNS',
71
+ recommendedEnv: 'ENABLE_TOOL_SEARCH=auto:5',
72
+ mcpSchemaTokens,
73
+ mcpToolCount,
74
+ turn0StaticPrefillBreakdown,
75
+ reason: `[DET-13 Idle MCP Hoarding] ${mcpSchemaTokens.toLocaleString()} MCP schema tokens injected with 0 invocations across ${turnsElapsed} turns (Turn-0 prefill = ${turn0StaticPrefillBreakdown.totalStaticPrefillTokens.toLocaleString()} tok). Set ENABLE_TOOL_SEARCH=auto:5 or disable unused MCP servers.`
76
+ };
77
+ }
78
+
79
+ if (mcpSchemaTokens > 15_000 || mcpToolCount >= 20) {
80
+ return {
81
+ detectorId: 'DET-13',
82
+ triggered: true,
83
+ decision: 'advise_lazy_mcp',
84
+ advisory: true,
85
+ subType: 'MCP_SCHEMA_BLOAT',
86
+ recommendedEnv: 'ENABLE_TOOL_SEARCH=auto:5',
87
+ mcpSchemaTokens,
88
+ mcpToolCount,
89
+ turn0StaticPrefillBreakdown,
90
+ reason: `[DET-13 MCP Schema Bloat] ${mcpToolCount} MCP tools consuming ${mcpSchemaTokens.toLocaleString()} startup tokens (> 15k cap). Set ENABLE_TOOL_SEARCH=auto:5 or disable unused MCP servers.`
91
+ };
92
+ }
93
+
94
+ return {
95
+ detectorId: 'DET-13',
96
+ triggered: false,
97
+ decision: 'allow',
98
+ mcpSchemaTokens,
99
+ mcpToolCount,
100
+ turn0StaticPrefillBreakdown,
101
+ reason: null
102
+ };
103
+ }
104
+
105
+ /**
106
+ * DET-14: Premature Completion `Stop` Gate.
107
+ * Strictly checks `stop_hook_active` first to prevent infinite loops.
108
+ * Advisory in `COACH` mode; blocks `Stop` in `AUTO_PILOT` mode only when code was edited without running tests.
109
+ *
110
+ * @param {object} [params={}]
111
+ * @param {boolean} [params.stopHookActive=false]
112
+ * @param {boolean} [params.codeEditedSinceLastTest=false]
113
+ * @param {Array<string>} [params.editedFiles=[]]
114
+ * @param {'OFF'|'SILENT'|'COACH'|'AUTO_PILOT'} [params.mode='COACH']
115
+ */
116
+ export function evaluateDet14PrematureStopGate(params = {}) {
117
+ const stopHookActive = Boolean(params.stopHookActive ?? params.stop_hook_active ?? false);
118
+ const mode = normalizeFlightMode(params.mode || FLIGHT_MODES.COACH);
119
+ const editedFiles = Array.isArray(params.editedFiles) ? params.editedFiles : [];
120
+ const codeEditedSinceLastTest = Boolean(
121
+ params.codeEditedSinceLastTest ?? editedFiles.length > 0
122
+ );
123
+
124
+ // Loop-safety invariant: NEVER block when `stop_hook_active` is already true
125
+ if (stopHookActive) {
126
+ return {
127
+ detectorId: 'DET-14',
128
+ triggered: false,
129
+ stopHookActive: true,
130
+ decision: 'allow',
131
+ advisory: false,
132
+ reason: null
133
+ };
134
+ }
135
+
136
+ if (!codeEditedSinceLastTest || isSilentOrOffMode(mode)) {
137
+ return {
138
+ detectorId: 'DET-14',
139
+ triggered: false,
140
+ stopHookActive: false,
141
+ decision: 'allow',
142
+ advisory: false,
143
+ reason: null
144
+ };
145
+ }
146
+
147
+ const fileSummary = editedFiles.slice(0, 4).join(', ') || 'workspace source files';
148
+
149
+ if (mode === FLIGHT_MODES.COACH) {
150
+ return {
151
+ detectorId: 'DET-14',
152
+ triggered: true,
153
+ stopHookActive: false,
154
+ decision: 'allow',
155
+ advisory: true,
156
+ reason: `[DET-14 Verification Advisory] Modified ${fileSummary} without running tests in this turn.`
157
+ };
158
+ }
159
+
160
+ // AUTO_PILOT mode: block premature Stop once
161
+ return {
162
+ detectorId: 'DET-14',
163
+ triggered: true,
164
+ stopHookActive: false,
165
+ decision: 'block',
166
+ advisory: false,
167
+ reason: `[DET-14 Premature Stop Gate] Modified ${fileSummary} without running verification tests. Run the relevant unit test suite before completing the turn.`
168
+ };
169
+ }
170
+
171
+ /**
172
+ * DET-15: Batched `Stop`-Phase Formatter.
173
+ * Collects modified files during the turn so formatting can run once at `Stop` instead of after every edit.
174
+ *
175
+ * @param {object} [params={}]
176
+ * @param {Array<string>} [params.modifiedFiles=[]]
177
+ */
178
+ export function evaluateDet15BatchedStopFormatter(params = {}) {
179
+ const files = Array.from(new Set(params.modifiedFiles || []))
180
+ .map((f) => String(f).trim())
181
+ .filter((f) => /\.(?:mjs|cjs|js|ts|tsx|jsx|json|md|css|html)$/i.test(f));
182
+
183
+ if (files.length === 0) {
184
+ const cmd = String(params.command || params.cmd || '').trim();
185
+ if (
186
+ cmd &&
187
+ /\b(?:prettier\s+(?:--write|-w)|biome\s+format\s+--write|gofmt\s+-w|rustfmt)\b/i.test(cmd)
188
+ ) {
189
+ return {
190
+ detectorId: 'DET-15',
191
+ triggered: true,
192
+ filesToFormat: [],
193
+ batchCommand: cmd
194
+ };
195
+ }
196
+ return {
197
+ detectorId: 'DET-15',
198
+ triggered: false,
199
+ filesToFormat: [],
200
+ batchCommand: null
201
+ };
202
+ }
203
+
204
+ return {
205
+ detectorId: 'DET-15',
206
+ triggered: true,
207
+ filesToFormat: files,
208
+ batchCommand: `npx prettier --write ${files.map((f) => `"${f}"`).join(' ')}`
209
+ };
210
+ }
211
+
212
+ /**
213
+ * DET-15: Pre-Invocation / Pre-Tool-Use Local CLI Formatter Bypass Advisory.
214
+ * Emits advisory recommending local `npx prettier --write` / `npx eslint --fix` on pasted >=40-line blocks.
215
+ *
216
+ * @param {object} [params={}]
217
+ */
218
+ export function evaluateDet15PreFormatBypass(params = {}) {
219
+ const prompt = String(params.prompt || params.userPrompt || '');
220
+ const newText = String(params.newText || '');
221
+ const lineCount = Number(
222
+ params.lineCount ??
223
+ (newText ? newText.split(/\r?\n/).length : (prompt.match(/\r?\n/g) || []).length)
224
+ );
225
+ const isFormattingIntent = /\b(fix\s+(?:the\s+)?indentation|sort\s+(?:the\s+)?imports|format\s+this\s+(?:code|file|block)|convert\s+tabs\s+to\s+spaces|run\s+prettier)\b/i.test(prompt);
226
+
227
+ if (isFormattingIntent && lineCount >= 40 && !/\b(add|implement|refactor|create|fix\s+bug|logic|test|calculate)\b/i.test(prompt)) {
228
+ return {
229
+ detectorId: 'DET-15',
230
+ triggered: true,
231
+ subType: 'LOCAL_FORMATTER_BYPASS',
232
+ decision: 'allow',
233
+ advisory: true,
234
+ reason: '[DET-15 Local Formatter Bypass] Prompt requests code formatting / import sorting on a pasted code block. Run `npx prettier --write <file>` or `npx eslint --fix <file>` directly (0 LLM tokens).'
235
+ };
236
+ }
237
+
238
+ return { detectorId: 'DET-15', triggered: false, decision: 'allow' };
239
+ }
240
+
241
+ /**
242
+ * DET-16: Subagent Token (`40k`) & Turn (`12`) Recursion Cap.
243
+ *
244
+ * @param {object} [params={}]
245
+ * @param {string} [params.agentId]
246
+ * @param {number} [params.turns=0]
247
+ * @param {number} [params.totalTokens=0]
248
+ * @param {number} [params.maxTurns=12]
249
+ * @param {number} [params.maxTokens=40000]
250
+ */
251
+ export function evaluateDet16SubagentRecursionCap(params = {}) {
252
+ const agentId = params.agentId || null;
253
+ if (!agentId) {
254
+ return { detectorId: 'DET-16', triggered: false, decision: 'allow', reason: null };
255
+ }
256
+
257
+ const turns = Math.max(0, Number(params.turns || 0));
258
+ const totalTokens = Math.max(0, Number(params.totalTokens || 0));
259
+ const maxTurns = Number(params.maxTurns ?? 12);
260
+ const maxTokens = Number(params.maxTokens ?? 40_000);
261
+
262
+ if (turns >= maxTurns || totalTokens >= maxTokens) {
263
+ return {
264
+ detectorId: 'DET-16',
265
+ triggered: true,
266
+ decision: 'deny',
267
+ agentId,
268
+ turns,
269
+ totalTokens,
270
+ reason: `[DET-16 Subagent Recursion Cap] Subagent "${agentId}" reached ${turns}/${maxTurns} turns and ${totalTokens.toLocaleString()}/${maxTokens.toLocaleString()} tokens. Terminate exploration and return synthesized summary immediately.`
271
+ };
272
+ }
273
+
274
+ return {
275
+ detectorId: 'DET-16',
276
+ triggered: false,
277
+ decision: 'allow',
278
+ agentId,
279
+ turns,
280
+ totalTokens,
281
+ reason: null
282
+ };
283
+ }
284
+
285
+ /**
286
+ * DET-17: Untimely Auto-Compaction Deferral (`PreCompact` `auto` mid-batch syntax guard).
287
+ *
288
+ * @param {object} [params={}]
289
+ * @param {'auto'|'manual'} [params.trigger='auto']
290
+ * @param {boolean} [params.midBatchEditInProgress=false]
291
+ * @param {boolean} [params.unbalancedSyntaxDetected=false]
292
+ */
293
+ export function evaluateDet17AutoCompactionDeferral(params = {}) {
294
+ const trigger = String(params.trigger || 'auto').toLowerCase();
295
+ const midBatch = Boolean(params.midBatchEditInProgress || params.unbalancedSyntaxDetected);
296
+ const cacheExpired = Boolean(params.cacheExpired);
297
+ const cachedTokens = Math.max(0, Number(params.cachedTokens ?? params.cached_tokens ?? 0));
298
+
299
+ if (cacheExpired && cachedTokens >= 25_000) {
300
+ return {
301
+ detectorId: 'DET-17',
302
+ subType: 'COLD_CACHE_COMPACT_BLOCKED',
303
+ triggered: true,
304
+ decision: 'defer',
305
+ reason: `[DET-17 Cold-Cache /compact Guard] Prompt cache TTL has expired (${cachedTokens.toLocaleString()} cold tokens). Running /compact now would pay full uncached input rates to summarize stale history — flush a <300-token StateBaton and /clear instead.`
306
+ };
307
+ }
308
+
309
+ if (trigger === 'auto' && midBatch) {
310
+ return {
311
+ detectorId: 'DET-17',
312
+ subType: 'MID_BATCH_DEFERRED',
313
+ triggered: true,
314
+ decision: 'defer',
315
+ reason: `[DET-17 Auto-Compaction Deferred] Deferring automatic compaction while a multi-file edit batch or syntax repair is in progress.`
316
+ };
317
+ }
318
+
319
+ return {
320
+ detectorId: 'DET-17',
321
+ triggered: false,
322
+ decision: 'allow',
323
+ reason: null
324
+ };
325
+ }
326
+
327
+ /**
328
+ * Pure zero-I/O evaluator for Silent Prefix Mutations (`Sim 01` & `Sim 16` in Claude Code):
329
+ * - `LATE_MCP_CONNECT`: MCP server count or schema hash changing after Turn 1
330
+ * - `MEMORY_MD_MID_THREAD_MUTATION`: Mid-thread `MEMORY.md` hash/byte change (up to 25KB)
331
+ * - `IDE_STATE_PREFIX_MUTATION`: Dynamic IDE state injected into system prefix instead of user-turn tail
332
+ * - `LOOKBACK_WINDOW_DELETION`: Message deletion inside 20-block lookback window shifting cached suffix
333
+ */
334
+ export function evaluateSilentPrefixMutations(params = {}) {
335
+ const turn = Math.max(1, Number(params.turnCount || 1));
336
+ const subTypes = [];
337
+ const details = [];
338
+ let shiftedSuffixTokens = 0;
339
+
340
+ if (turn > 1) {
341
+ const mcpCountChanged =
342
+ params.prevMcpServerCount != null &&
343
+ params.currMcpServerCount != null &&
344
+ Number(params.prevMcpServerCount) !== Number(params.currMcpServerCount);
345
+ const mcpHashChanged =
346
+ Boolean(params.prevMcpSchemaHash && params.currMcpSchemaHash) &&
347
+ String(params.prevMcpSchemaHash) !== String(params.currMcpSchemaHash);
348
+ if (mcpCountChanged || mcpHashChanged) {
349
+ subTypes.push('LATE_MCP_CONNECT');
350
+ details.push(
351
+ `Mid-session MCP server/schema change at Turn ${turn} (${params.prevMcpServerCount ?? '?'} -> ${params.currMcpServerCount ?? '?'} servers)`
352
+ );
353
+ }
354
+
355
+ const memHashChanged =
356
+ Boolean(params.prevMemoryMdHash && params.currMemoryMdHash) &&
357
+ String(params.prevMemoryMdHash) !== String(params.currMemoryMdHash);
358
+ const memBytesChanged =
359
+ params.prevMemoryMdBytes != null &&
360
+ params.currMemoryMdBytes != null &&
361
+ Number(params.prevMemoryMdBytes) !== Number(params.currMemoryMdBytes);
362
+ if (memHashChanged || memBytesChanged) {
363
+ subTypes.push('MEMORY_MD_MID_THREAD_MUTATION');
364
+ const kb =
365
+ params.currMemoryMdBytes != null
366
+ ? `${(Number(params.currMemoryMdBytes) / 1024).toFixed(1)}KB`
367
+ : 'updated';
368
+ details.push(`Mid-thread MEMORY.md mutation (${kb}) invalidated static system prefix`);
369
+ }
370
+
371
+ const ideHashChanged =
372
+ Boolean(params.prevIdePrefixHash && params.currIdePrefixHash) &&
373
+ String(params.prevIdePrefixHash) !== String(params.currIdePrefixHash);
374
+ if (Boolean(params.ideStateInSystemPrefix) || ideHashChanged) {
375
+ subTypes.push('IDE_STATE_PREFIX_MUTATION');
376
+ details.push(
377
+ 'Dynamic IDE state (active tab / highlighted lines / Problems diagnostics) injected into system prefix instead of user-turn tail'
378
+ );
379
+ }
380
+ }
381
+
382
+ if (
383
+ Array.isArray(params.prevMessageIds) &&
384
+ Array.isArray(params.currMessageIds) &&
385
+ params.prevMessageIds.length > 0
386
+ ) {
387
+ const currSet = new Set(params.currMessageIds);
388
+ let firstDeletedIdx = -1;
389
+ let deletedCount = 0;
390
+ for (let i = 0; i < params.prevMessageIds.length; i++) {
391
+ if (!currSet.has(params.prevMessageIds[i])) {
392
+ if (firstDeletedIdx === -1) firstDeletedIdx = i;
393
+ deletedCount += 1;
394
+ }
395
+ }
396
+ if (firstDeletedIdx !== -1) {
397
+ const remaining = Math.max(0, params.prevMessageIds.length - firstDeletedIdx - deletedCount);
398
+ if (Array.isArray(params.tokensPerMessage)) {
399
+ for (let j = firstDeletedIdx + deletedCount; j < params.prevMessageIds.length; j++) {
400
+ shiftedSuffixTokens += Math.max(0, Number(params.tokensPerMessage[j] || 0));
401
+ }
402
+ } else {
403
+ shiftedSuffixTokens = remaining * Math.max(1, Number(params.tokensPerMessage || 5000));
404
+ }
405
+ subTypes.push('LOOKBACK_WINDOW_DELETION');
406
+ details.push(
407
+ `Deleted ${deletedCount} historical message(s) starting at index ${firstDeletedIdx}, shifting ${shiftedSuffixTokens.toLocaleString()} suffix tokens outside 20-block lookback window`
408
+ );
409
+ }
410
+ }
411
+
412
+ const triggered = subTypes.length > 0;
413
+ const detectorId = subTypes.includes('LOOKBACK_WINDOW_DELETION')
414
+ ? 'DET-09'
415
+ : subTypes.includes('LATE_MCP_CONNECT')
416
+ ? 'DET-13'
417
+ : 'DET-09';
418
+
419
+ return {
420
+ detectorId,
421
+ triggered,
422
+ subTypes,
423
+ shiftedSuffixTokens:
424
+ shiftedSuffixTokens || (triggered ? Math.max(0, Number(params.cachedTokens || 0)) : 0),
425
+ details,
426
+ reason: triggered ? `[${detectorId} Silent Prefix Mutation] ${details.join('; ')}.` : null
427
+ };
428
+ }
429
+
430
+ /**
431
+ * DET-18: Untrusted Project `settings.json` Hook CVE & Clobber Guard.
432
+ *
433
+ * @param {object} [params={}]
434
+ * @param {string} [params.toolName='Write']
435
+ * @param {string} [params.filePath='']
436
+ * @param {string} [params.newText='']
437
+ */
438
+ export function evaluateDet18UntrustedSettingsGuard(params = {}) {
439
+ const filePath = String(params.filePath || params.path || '').trim().replace(/\\/g, '/');
440
+ if (!/(?:^|\/)\.claude\/settings(?:\.local)?\.json$/i.test(filePath)) {
441
+ return { detectorId: 'DET-18', triggered: false, decision: 'allow', reason: null };
442
+ }
443
+
444
+ const content = String(params.newText || params.content || '');
445
+ const suspiciousHookRegex =
446
+ /(?:\bcurl\b.*\|\s*(?:sh|bash|pwsh)|\bwget\b.*\|\s*(?:sh|bash)|\bInvoke-Expression\b|\biex\b\s*\(|\bnc\s+-e\b|\bbase64\s+-d\b.*\|\s*(?:sh|bash))/i;
447
+
448
+ if (suspiciousHookRegex.test(content)) {
449
+ return {
450
+ detectorId: 'DET-18',
451
+ triggered: true,
452
+ decision: 'deny',
453
+ subType: 'MALICIOUS_SETTINGS_HOOK_CVE',
454
+ targetPath: filePath,
455
+ reason: `[DET-18 Untrusted Settings CVE Guard] Blocked suspicious remote shell execution payload in "${filePath}".`
456
+ };
457
+ }
458
+
459
+ if (EDIT_WRITE_TOOL_REGEX.test(String(params.toolName || 'Write')) && !params.hasBackup) {
460
+ return {
461
+ detectorId: 'DET-18',
462
+ triggered: true,
463
+ decision: 'ask',
464
+ subType: 'SETTINGS_CLOBBER_GUARD',
465
+ targetPath: filePath,
466
+ reason: `[DET-18 Settings Clobber Guard] Direct modification of "${filePath}" requires user confirmation (or use "npx ah-claude install" for non-destructive backup merge).`
467
+ };
468
+ }
469
+
470
+ return { detectorId: 'DET-18', triggered: false, decision: 'allow', reason: null };
471
+ }
472
+
473
+ /**
474
+ * DET-19: Subagent Indirect Prompt Injection (IPI) & Untrusted URL Exfiltration Sanitizer (`ISS-053`).
475
+ * - Neutralizes XML boundary breakout tags (`</untrusted_subagent_data>`, `<untrusted_subagent_output>`) BEFORE wrapping.
476
+ * - Strips Unicode tag characters (`U+E0000`..`U+E007F`), zero-width/bidi override & isolate chars (`U+200B`..`U+200F`,
477
+ * `U+202A`..`U+202E`, `U+2060`..`U+2069`, `U+061C`, `U+FEFF`), general HTML comments (`<!-- ... -->`),
478
+ * `<script>`/`<style>` blocks, `data:text/html` / `application/javascript` URIs, chat template tokens,
479
+ * and line-leading prompt-injection role spoof headers.
480
+ * - Counts stripped/neutralized source characters BEFORE replacement substitution so `strippedCharCount > 0`
481
+ * whenever any injection vector is neutralized.
482
+ * - Wraps subagent / untrusted data in `<untrusted_subagent_data trust="untrusted" readonly="true">...</untrusted_subagent_data>`.
483
+ * - Blocks `WebFetch` URLs attempting to exfiltrate secrets/tokens in query strings.
484
+ *
485
+ * @param {object} [params={}]
486
+ * @param {string} [params.text='']
487
+ * @param {string} [params.url='']
488
+ * @param {boolean} [params.wrapUntrusted=true]
489
+ */
490
+ export function evaluateDet19SubagentIpiSanitizer(params = {}) {
491
+ const urlStr = String(params.url || '').trim();
492
+ if (urlStr) {
493
+ if (
494
+ /(?:api[_-]?key|secret|token|password|authorization|aws_access_key|sk-ant-)[=:]\S+/i.test(
495
+ urlStr
496
+ ) ||
497
+ /\$\{?[A-Z0-9_]*(?:KEY|SECRET|TOKEN|PASSWORD)[A-Z0-9_]*\}?/i.test(urlStr)
498
+ ) {
499
+ return {
500
+ detectorId: 'DET-19',
501
+ triggered: true,
502
+ blocked: true,
503
+ hadInjectionMarkers: false,
504
+ decision: 'deny',
505
+ subType: 'URL_EXFILTRATION_BLOCKED',
506
+ sanitizedText: '',
507
+ strippedCharCount: 0,
508
+ reason: `[DET-19 Untrusted URL Exfiltration Blocked] Outbound request URL contains credential or environment secret interpolation.`
509
+ };
510
+ }
511
+ }
512
+
513
+ const rawText = String(params.text ?? '');
514
+ if (!rawText) {
515
+ return {
516
+ detectorId: 'DET-19',
517
+ triggered: false,
518
+ blocked: false,
519
+ hadInjectionMarkers: false,
520
+ decision: 'allow',
521
+ sanitizedText: '',
522
+ strippedCharCount: 0,
523
+ reason: null
524
+ };
525
+ }
526
+
527
+ let strippedCharCount = 0;
528
+ let hadInjectionMarkers = false;
529
+
530
+ const stripEmpty = (text, regex) =>
531
+ text.replace(regex, (match) => {
532
+ strippedCharCount += match.length;
533
+ hadInjectionMarkers = true;
534
+ return '';
535
+ });
536
+
537
+ const stripWithMarker = (text, regex, replacement = '[STRIPPED_IPI_MARKER]') =>
538
+ text.replace(regex, (match) => {
539
+ strippedCharCount += match.length;
540
+ hadInjectionMarkers = true;
541
+ return replacement;
542
+ });
543
+
544
+ // 1. Neutralize closing/opening XML boundary tags FIRST so untrusted payloads can NEVER break out
545
+ const boundaryTagRegex = /<\s*\/?\s*untrusted_subagent_(?:data|output)\b[^>]*>/gi;
546
+ let cleaned = rawText.replace(boundaryTagRegex, (match) => {
547
+ strippedCharCount += match.length;
548
+ hadInjectionMarkers = true;
549
+ return match.replace(/</g, '&lt;').replace(/>/g, '&gt;');
550
+ });
551
+
552
+ // 2. Strip Unicode Tags (U+E0000..U+E007F) and zero-width / bidi overrides & isolates / Arabic Letter Mark (U+061C)
553
+ cleaned = stripEmpty(cleaned, /[\u{E0000}-\u{E007F}]/gu);
554
+ cleaned = stripEmpty(cleaned, /[\u061C\u200B-\u200F\u202A-\u202E\u2060-\u206F\uFEFF]/g);
555
+
556
+ // 3. Strip general HTML comments, <script>, <style>, executable data: URIs, and chat template tokens
557
+ cleaned = stripWithMarker(cleaned, /<!--[\s\S]*?-->/g);
558
+ cleaned = stripWithMarker(cleaned, /<\s*script\b[^>]*>[\s\S]*?<\s*\/\s*script\s*>/gi);
559
+ cleaned = stripWithMarker(cleaned, /<\s*style\b[^>]*>[\s\S]*?<\s*\/\s*style\s*>/gi);
560
+ cleaned = stripWithMarker(
561
+ cleaned,
562
+ /data:(?:text\/(?:html|javascript)|application\/(?:javascript|x-javascript)|image\/svg\+xml)[^,\s"')]*(?:,[^\s"')>]+)?/gi
563
+ );
564
+ cleaned = stripWithMarker(
565
+ cleaned,
566
+ /<\|(?:im_start|im_end|endoftext|assistant|system|user|startoftext|extra_\d+)\|>/gi
567
+ );
568
+
569
+ // 4. Neutralize line-leading prompt-injection role spoof headers
570
+ cleaned = cleaned.replace(
571
+ /(^|\n)([ \t]*(?:SYSTEM|DEVELOPER|IMPORTANT\s+INSTRUCTION|IGNORE\s+(?:ALL\s+)?PREVIOUS\s+INSTRUCTIONS)[ \t]*:)/gi,
572
+ (_full, prefix, roleHeader) => {
573
+ strippedCharCount += roleHeader.length;
574
+ hadInjectionMarkers = true;
575
+ return `${prefix}[STRIPPED_IPI_MARKER]:`;
576
+ }
577
+ );
578
+
579
+ if (params.wrapUntrusted !== false) {
580
+ cleaned = `<untrusted_subagent_data trust="untrusted" readonly="true">\n${cleaned}\n</untrusted_subagent_data>`;
581
+ }
582
+
583
+ return {
584
+ detectorId: 'DET-19',
585
+ triggered: hadInjectionMarkers,
586
+ blocked: false,
587
+ hadInjectionMarkers,
588
+ decision: 'allow',
589
+ subType: hadInjectionMarkers ? 'IPI_PAYLOAD_SANITIZED' : null,
590
+ sanitizedText: cleaned,
591
+ strippedCharCount,
592
+ reason: hadInjectionMarkers
593
+ ? `[DET-19 Subagent IPI Sanitizer] Neutralized ${strippedCharCount} char(s) of hidden Unicode / XML boundary / prompt-injection markers and wrapped output in <untrusted_subagent_data trust="untrusted" readonly="true">.`
594
+ : null
595
+ };
596
+ }
597
+
598
+ /**
599
+ * DET-20: Concurrent Multi-Agent File-Scope Lockfile + Quota Hard Brake.
600
+ * Wrapper delegating to `evaluateScopeAndQuotaBrake` in `src/telemetry/scopeLockRegistry.mjs`.
601
+ */
602
+ export function evaluateDet20ScopeLockAndQuotaBrake(params = {}, options = {}) {
603
+ return evaluateScopeAndQuotaBrake(params, options);
604
+ }
605
+
606
+ /**
607
+ * Sanitizes a session ID for `.claude/cache/ah_breaker_state_<sessionId>.json`.
608
+ * @param {string} [sessionId='default']
609
+ * @returns {string}
610
+ */
611
+ export function sanitizeBreakerSessionId(sessionId = 'default') {
612
+ return String(sessionId || 'default').replace(/[^a-zA-Z0-9._-]/g, '_');
613
+ }
614
+
615
+ /**
616
+ * Resolves the atomic CLI circuit-breaker state file path (`.claude/cache/ah_breaker_state_<sessionId>.json`).
617
+ * @param {string} [sessionId='default']
618
+ * @param {object} [options={}]
619
+ * @returns {string}
620
+ */
621
+ export function getBreakerStateFilePath(sessionId = 'default', options = {}) {
622
+ if (options?.breakerStatePath) {
623
+ return options.breakerStatePath;
624
+ }
625
+ const cwd = getCwd(options);
626
+ return path.join(
627
+ cwd,
628
+ '.claude',
629
+ 'cache',
630
+ `ah_breaker_state_${sanitizeBreakerSessionId(sessionId)}.json`
631
+ );
632
+ }
633
+
634
+ /**
635
+ * Safely reads a persisted `CircuitBreakerEngine` snapshot from disk (`ISS-038`).
636
+ * @param {string} [sessionId='default']
637
+ * @param {object} [options={}]
638
+ * @returns {object | null}
639
+ */
640
+ export function readBreakerStateSnapshot(sessionId = 'default', options = {}) {
641
+ return readJsonSafe(getBreakerStateFilePath(sessionId, options), null, options);
642
+ }
643
+
644
+ /**
645
+ * Atomically writes a `CircuitBreakerEngine` snapshot to disk (`ISS-038`).
646
+ * @param {string} [sessionId='default']
647
+ * @param {object} [snapshot={}]
648
+ * @param {object} [options={}]
649
+ * @returns {boolean}
650
+ */
651
+ export function writeBreakerStateSnapshot(sessionId = 'default', snapshot = {}, options = {}) {
652
+ return writeJsonAtomic(getBreakerStateFilePath(sessionId, options), snapshot, options);
653
+ }
654
+
655
+ /**
656
+ * Exports a serializable snapshot of a `CircuitBreakerEngine` instance (`ISS-038`).
657
+ * @param {object} engine
658
+ * @returns {object}
659
+ */
660
+ export function serializeCircuitBreakerState(engine) {
661
+ const hashObj = {};
662
+ for (const [k, v] of engine.fileHashHistory.entries()) {
663
+ hashObj[k] = Array.isArray(v) ? [...v] : [];
664
+ }
665
+ return {
666
+ schemaVersion: '1.0.0',
667
+ updatedAt: Date.now(),
668
+ mode: engine.mode,
669
+ consecutiveFailures: engine.consecutiveFailures,
670
+ lastFailedToolKey: engine.lastFailedToolKey,
671
+ sequentialSearchCount: engine.sequentialSearchCount,
672
+ fileHashHistory: hashObj,
673
+ modifiedFilesInTurn: Array.from(engine.modifiedFilesInTurn),
674
+ editedFiles: Array.from(engine.modifiedFilesInTurn),
675
+ unverifiedEdits: Array.isArray(engine.unverifiedEdits) ? engine.unverifiedEdits.slice(-32) : [],
676
+ turnFileDiffs: Array.isArray(engine.turnFileDiffs) ? engine.turnFileDiffs.slice(-32) : [],
677
+ pendingBatchEdits: Array.from(engine.pendingBatchEdits),
678
+ pendingFormatFiles: Array.from(engine.pendingFormatFiles),
679
+ codeEditedSinceLastTest: Boolean(engine.codeEditedSinceLastTest),
680
+ pendingVerificationCommand: Boolean(engine.pendingVerificationCommand),
681
+ lastFailingLocation: engine.lastFailingLocation || null,
682
+ pendingDownshiftModel: engine.pendingDownshiftModel || null,
683
+ pending_downshift: engine.pending_downshift ? { ...engine.pending_downshift } : null,
684
+ justCompacted: Boolean(engine.justCompacted),
685
+ turnsSinceLastCompact:
686
+ typeof engine.turnsSinceLastCompact === 'number' && Number.isFinite(engine.turnsSinceLastCompact)
687
+ ? Math.max(0, engine.turnsSinceLastCompact)
688
+ : null,
689
+ taskBoundaryState: engine.taskBoundaryState
690
+ ? {
691
+ openFailure: Boolean(engine.taskBoundaryState.openFailure),
692
+ editsSinceBoundary: Math.max(0, Number(engine.taskBoundaryState.editsSinceBoundary || 0)),
693
+ lastBoundarySuggestedTurn: engine.taskBoundaryState.lastBoundarySuggestedTurn ?? null
694
+ }
695
+ : { openFailure: false, editsSinceBoundary: 0, lastBoundarySuggestedTurn: null },
696
+ lastToolsetHash: engine.lastToolsetHash ? { ...engine.lastToolsetHash } : null,
697
+ lastContextTokens:
698
+ typeof engine.lastContextTokens === 'number' && Number.isFinite(engine.lastContextTokens)
699
+ ? Math.max(0, engine.lastContextTokens)
700
+ : null,
701
+ lastModelId: engine.lastModelId ? String(engine.lastModelId) : null,
702
+ activeBackgroundTasks: Array.isArray(engine.activeBackgroundTasks)
703
+ ? [...engine.activeBackgroundTasks]
704
+ : [],
705
+ activeWriteWorkers: Array.isArray(engine.activeWriteWorkers)
706
+ ? [...engine.activeWriteWorkers]
707
+ : [],
708
+ lastUserPrompt: engine.lastUserPrompt || '',
709
+ lastTurnGitCommitted: Boolean(engine.lastTurnGitCommitted),
710
+ committedTopDirs: Array.isArray(engine.committedTopDirs) ? [...engine.committedTopDirs] : [],
711
+ consecutiveTrivialMaxEffortTurns: engine.consecutiveTrivialMaxEffortTurns,
712
+ recentEditTimestampsByFile: { ...engine.recentEditTimestampsByFile },
713
+ totalDiscoveryCalls: engine.totalDiscoveryCalls,
714
+ consecutiveVisionTurns: engine.consecutiveVisionTurns,
715
+ unanchoredTurnFlag: Boolean(engine.unanchoredTurnFlag),
716
+ candidateFiles: Array.isArray(engine.candidateFiles) ? [...engine.candidateFiles] : [],
717
+ relayState: engine.relayState ? { ...engine.relayState } : { state: RELAY_STATES.IDLE, critiquePastes: 0, boundSpecPath: 'SPEC.md' },
718
+ steeredPrompts: Number(engine.steeredPrompts || 0),
719
+ blockedPrompts: Number(engine.blockedPrompts || 0),
720
+ sightseeingToolsPrevented: Number(engine.sightseeingToolsPrevented || 0),
721
+ subagentTurns: { ...engine.subagentTurns },
722
+ subagentTokens: { ...engine.subagentTokens },
723
+ det11AdvisedTurn: engine.det11AdvisedTurn,
724
+ det13AdvisedTurn: engine.det13AdvisedTurn,
725
+ queuedMutations: engine.router.mutationQueue.toJSON(),
726
+ hysteresisState: engine.router.hysteresisLock.getStatus()
727
+ };
728
+ }
729
+
730
+ /**
731
+ * Hydrates stateful breaker counters and queues onto a `CircuitBreakerEngine` instance (`ISS-038`).
732
+ * @param {object} engine
733
+ * @param {object | null} snap
734
+ * @returns {object}
735
+ */
736
+ export function hydrateCircuitBreakerState(engine, snap) {
737
+ if (!snap || typeof snap !== 'object') return engine;
738
+
739
+ if (typeof snap.consecutiveFailures === 'number' && Number.isFinite(snap.consecutiveFailures)) {
740
+ engine.consecutiveFailures = Math.max(0, snap.consecutiveFailures);
741
+ }
742
+ if (snap.lastFailedToolKey !== undefined) {
743
+ engine.lastFailedToolKey = snap.lastFailedToolKey ? String(snap.lastFailedToolKey) : null;
744
+ }
745
+ if (
746
+ typeof snap.sequentialSearchCount === 'number' &&
747
+ Number.isFinite(snap.sequentialSearchCount)
748
+ ) {
749
+ engine.sequentialSearchCount = Math.max(0, snap.sequentialSearchCount);
750
+ }
751
+ if (snap.fileHashHistory && typeof snap.fileHashHistory === 'object') {
752
+ engine.fileHashHistory = new Map();
753
+ for (const [k, v] of Object.entries(snap.fileHashHistory)) {
754
+ if (Array.isArray(v)) {
755
+ engine.fileHashHistory.set(k, v.slice(-6).map(String));
756
+ }
757
+ }
758
+ }
759
+ const editedList = Array.isArray(snap.modifiedFilesInTurn)
760
+ ? snap.modifiedFilesInTurn
761
+ : Array.isArray(snap.editedFiles)
762
+ ? snap.editedFiles
763
+ : null;
764
+ if (editedList) {
765
+ engine.modifiedFilesInTurn = new Set(editedList.filter(Boolean).map(String));
766
+ }
767
+ if (Array.isArray(snap.unverifiedEdits)) {
768
+ engine.unverifiedEdits = snap.unverifiedEdits
769
+ .filter((e) => e && typeof e.filePath === 'string')
770
+ .slice(-32)
771
+ .map((e) => ({
772
+ filePath: String(e.filePath),
773
+ netLines: Math.max(0, Number(e.netLines) || 0),
774
+ ...(Array.isArray(e.changedLines) ? { changedLines: e.changedLines.slice(0, 64).map(String) } : {})
775
+ }));
776
+ }
777
+ if (Array.isArray(snap.turnFileDiffs)) {
778
+ engine.turnFileDiffs = snap.turnFileDiffs
779
+ .filter((e) => e && typeof e.filePath === 'string')
780
+ .slice(-32)
781
+ .map((e) => ({
782
+ filePath: String(e.filePath),
783
+ addedLines: Array.isArray(e.addedLines) ? e.addedLines.slice(0, 400).map(String) : [],
784
+ deletedLineCount: Math.max(0, Number(e.deletedLineCount) || 0)
785
+ }));
786
+ }
787
+ if (Array.isArray(snap.pendingBatchEdits)) {
788
+ engine.pendingBatchEdits = new Set(snap.pendingBatchEdits.filter(Boolean).map(String));
789
+ }
790
+ if (Array.isArray(snap.pendingFormatFiles)) {
791
+ engine.pendingFormatFiles = new Set(snap.pendingFormatFiles.filter(Boolean).map(String));
792
+ }
793
+ if (typeof snap.codeEditedSinceLastTest === 'boolean') {
794
+ engine.codeEditedSinceLastTest = snap.codeEditedSinceLastTest;
795
+ }
796
+ if (typeof snap.pendingVerificationCommand === 'boolean') {
797
+ engine.pendingVerificationCommand = snap.pendingVerificationCommand;
798
+ }
799
+ if (snap.lastFailingLocation !== undefined) {
800
+ engine.lastFailingLocation = snap.lastFailingLocation ? String(snap.lastFailingLocation) : null;
801
+ }
802
+ if (snap.pendingDownshiftModel !== undefined) {
803
+ engine.pendingDownshiftModel = snap.pendingDownshiftModel ? String(snap.pendingDownshiftModel) : null;
804
+ }
805
+ if (snap.pending_downshift !== undefined) {
806
+ engine.pending_downshift =
807
+ snap.pending_downshift && typeof snap.pending_downshift === 'object'
808
+ ? { ...snap.pending_downshift }
809
+ : null;
810
+ if (engine.pending_downshift?.toModel && snap.pendingDownshiftModel === undefined) {
811
+ engine.pendingDownshiftModel = String(engine.pending_downshift.toModel);
812
+ }
813
+ }
814
+ if (typeof snap.justCompacted === 'boolean') {
815
+ engine.justCompacted = snap.justCompacted;
816
+ }
817
+ if (snap.turnsSinceLastCompact !== undefined) {
818
+ engine.turnsSinceLastCompact =
819
+ snap.turnsSinceLastCompact !== null && Number.isFinite(Number(snap.turnsSinceLastCompact))
820
+ ? Math.max(0, Number(snap.turnsSinceLastCompact))
821
+ : null;
822
+ }
823
+ if (snap.taskBoundaryState && typeof snap.taskBoundaryState === 'object') {
824
+ engine.taskBoundaryState = {
825
+ openFailure: Boolean(snap.taskBoundaryState.openFailure),
826
+ editsSinceBoundary: Math.max(0, Number(snap.taskBoundaryState.editsSinceBoundary || 0)),
827
+ lastBoundarySuggestedTurn: snap.taskBoundaryState.lastBoundarySuggestedTurn ?? null
828
+ };
829
+ }
830
+ if (snap.lastToolsetHash !== undefined) {
831
+ engine.lastToolsetHash =
832
+ snap.lastToolsetHash && typeof snap.lastToolsetHash === 'object'
833
+ ? { ...snap.lastToolsetHash }
834
+ : null;
835
+ }
836
+ if (snap.lastContextTokens !== undefined) {
837
+ engine.lastContextTokens =
838
+ snap.lastContextTokens !== null && Number.isFinite(Number(snap.lastContextTokens))
839
+ ? Math.max(0, Number(snap.lastContextTokens))
840
+ : null;
841
+ }
842
+ if (snap.lastModelId !== undefined) {
843
+ engine.lastModelId = snap.lastModelId ? String(snap.lastModelId) : null;
844
+ }
845
+ if (Array.isArray(snap.activeBackgroundTasks)) {
846
+ engine.activeBackgroundTasks = snap.activeBackgroundTasks.filter(Boolean).map(String);
847
+ }
848
+ if (Array.isArray(snap.activeWriteWorkers)) {
849
+ engine.activeWriteWorkers = snap.activeWriteWorkers.filter(Boolean).map(String);
850
+ }
851
+ if (typeof snap.lastUserPrompt === 'string') {
852
+ engine.lastUserPrompt = snap.lastUserPrompt;
853
+ }
854
+ if (typeof snap.lastTurnGitCommitted === 'boolean') {
855
+ engine.lastTurnGitCommitted = snap.lastTurnGitCommitted;
856
+ }
857
+ if (Array.isArray(snap.committedTopDirs)) {
858
+ engine.committedTopDirs = [...snap.committedTopDirs];
859
+ }
860
+ if (typeof snap.consecutiveTrivialMaxEffortTurns === 'number') {
861
+ engine.consecutiveTrivialMaxEffortTurns = snap.consecutiveTrivialMaxEffortTurns;
862
+ }
863
+ if (snap.recentEditTimestampsByFile && typeof snap.recentEditTimestampsByFile === 'object') {
864
+ engine.recentEditTimestampsByFile = { ...snap.recentEditTimestampsByFile };
865
+ }
866
+ if (typeof snap.totalDiscoveryCalls === 'number') {
867
+ engine.totalDiscoveryCalls = snap.totalDiscoveryCalls;
868
+ }
869
+ if (typeof snap.consecutiveVisionTurns === 'number') {
870
+ engine.consecutiveVisionTurns = snap.consecutiveVisionTurns;
871
+ }
872
+ if (typeof snap.unanchoredTurnFlag === 'boolean') {
873
+ engine.unanchoredTurnFlag = snap.unanchoredTurnFlag;
874
+ }
875
+ if (Array.isArray(snap.candidateFiles)) {
876
+ engine.candidateFiles = [...snap.candidateFiles];
877
+ }
878
+ if (snap.relayState && typeof snap.relayState === 'object') {
879
+ engine.relayState = { ...snap.relayState };
880
+ }
881
+ if (typeof snap.steeredPrompts === 'number') {
882
+ engine.steeredPrompts = snap.steeredPrompts;
883
+ }
884
+ if (typeof snap.blockedPrompts === 'number') {
885
+ engine.blockedPrompts = snap.blockedPrompts;
886
+ }
887
+ if (typeof snap.sightseeingToolsPrevented === 'number') {
888
+ engine.sightseeingToolsPrevented = snap.sightseeingToolsPrevented;
889
+ }
890
+ if (snap.subagentTurns && typeof snap.subagentTurns === 'object') {
891
+ engine.subagentTurns = { ...snap.subagentTurns };
892
+ }
893
+ if (snap.subagentTokens && typeof snap.subagentTokens === 'object') {
894
+ engine.subagentTokens = { ...snap.subagentTokens };
895
+ }
896
+ if (snap.det11AdvisedTurn !== undefined) {
897
+ engine.det11AdvisedTurn = snap.det11AdvisedTurn;
898
+ }
899
+ if (snap.det13AdvisedTurn !== undefined) {
900
+ engine.det13AdvisedTurn = snap.det13AdvisedTurn;
901
+ }
902
+ if (Array.isArray(snap.queuedMutations)) {
903
+ engine.router.mutationQueue.items = [...snap.queuedMutations];
904
+ }
905
+ if (snap.hysteresisState && typeof snap.hysteresisState === 'object') {
906
+ engine.router.hysteresisLock.locked = Boolean(snap.hysteresisState.locked);
907
+ engine.router.hysteresisLock.pinnedModel = snap.hysteresisState.pinnedModel || null;
908
+ engine.router.hysteresisLock.pinnedEffort = snap.hysteresisState.pinnedEffort || null;
909
+ engine.router.hysteresisLock.reason = snap.hysteresisState.reason || null;
910
+ engine.router.hysteresisLock.lockedAtTurn = snap.hysteresisState.lockedAtTurn ?? null;
911
+ }
912
+ return engine;
913
+ }