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,650 @@
1
+ import crypto from 'node:crypto';
2
+ import { execFileSync } from 'node:child_process';
3
+ import { performance } from 'node:perf_hooks';
4
+ import { canonicalizePath } from '../paths.mjs';
5
+ import { isTestFilePath, evaluateDet18UntrustedWorkspaceSettings } from '../detectors_det01_to_16.mjs';
6
+
7
+ /**
8
+ * Phase 3.1: Deterministic Circuit Breakers (`src/core/coach/circuit_breakers.mjs`)
9
+ *
10
+ * Zero-LLM-token (<2ms) stateful and batch circuit breakers:
11
+ * - `DET-01` (Retry Churn): >= 2 identical failing tool calls or non-zero exit codes.
12
+ * Triggers sticky tier escalation via `HysteresisLock`.
13
+ * - `DET-02` (AST Edit Oscillation): Rolling SHA-256 file hash matches state from
14
+ * T-2 or T-3 within 5 turns. Surfaces the 1-Click 3-Stage Stepwise Refinement
15
+ * (Design-by-Contract) Prompt Pill (injected as next user message so prefix cache
16
+ * remains 100% intact).
17
+ * - `DET-03` (Test Assertion Weakening): `git diff` on test files detects deleted
18
+ * `assert`/`expect` statements while fixing tests. Renders a 1-click git hunk revert action.
19
+ * - Supports `purgeRewoundTurns(newStepCount)` when `TrajectoryWatcher` emits `TRAJECTORY_REWIND`.
20
+ */
21
+
22
+ export const THREE_STAGE_CONTRACT_PROMPT = [
23
+ 'STOP modifying files immediately. Enter 3-Stage Stepwise Refinement (Design-by-Contract):',
24
+ 'Stage 1 (Preconditions & Invariants): State the exact input/output contract and root cause of the oscillation in <= 3 bullets.',
25
+ 'Stage 2 (Minimal Dry-Run Diff): Propose the smallest non-oscillating change that satisfies all existing assertions.',
26
+ 'Stage 3 (Targeted Verification): Run only the affected unit test before touching any other file.'
27
+ ].join('\n');
28
+
29
+ export function sha256Hex(content = '') {
30
+ return crypto.createHash('sha256').update(String(content ?? ''), 'utf8').digest('hex');
31
+ }
32
+
33
+ function normalizeToolSignature(toolName = '', args = {}) {
34
+ const cleanName = String(toolName || '').toLowerCase().trim();
35
+ const sortedKeys = Object.keys(args || {}).sort();
36
+ const normObj = {};
37
+ for (const k of sortedKeys) {
38
+ const val = args[k];
39
+ normObj[k] = typeof val === 'string' ? val.trim().replace(/\s+/g, ' ') : val;
40
+ }
41
+ return `${cleanName}::${JSON.stringify(normObj)}`;
42
+ }
43
+
44
+ export function inspectGitDiffAssertionWeakening(diffText = '', filePath = '') {
45
+ const lines = String(diffText || '').split(/\r?\n/);
46
+ const deletedAssertions = [];
47
+ const addedAssertions = [];
48
+
49
+ const assertRegex = /\b(assert(?:\.[a-zA-Z0-9_]+)?|expect|should)\s*\(|^\s*assert\s+/;
50
+
51
+ for (const rawLine of lines) {
52
+ if (rawLine.startsWith('---') || rawLine.startsWith('+++')) continue;
53
+ if (rawLine.startsWith('-')) {
54
+ const body = rawLine.slice(1);
55
+ if (assertRegex.test(body)) {
56
+ deletedAssertions.push(body.trim());
57
+ }
58
+ } else if (rawLine.startsWith('+')) {
59
+ const body = rawLine.slice(1);
60
+ if (assertRegex.test(body)) {
61
+ addedAssertions.push(body.trim());
62
+ }
63
+ }
64
+ }
65
+
66
+ const netDeletedCount = Math.max(0, deletedAssertions.length - addedAssertions.length);
67
+ return {
68
+ weakened: netDeletedCount > 0,
69
+ deletedCount: deletedAssertions.length,
70
+ addedCount: addedAssertions.length,
71
+ netDeletedCount,
72
+ deletedAssertions,
73
+ filePath
74
+ };
75
+ }
76
+
77
+ /**
78
+ * DET-04: Inspects before/after file content for destructive code-stripping (>50% shrinkage
79
+ * on non-trivial files >= 30 lines) when not explicitly requested by the user.
80
+ */
81
+ export function inspectFileShrinkage({
82
+ previousContent = '',
83
+ newContent = '',
84
+ filePath = '',
85
+ userPrompt = '',
86
+ minBaselineLines = 30,
87
+ shrinkageThreshold = 0.50
88
+ } = {}) {
89
+ const prevStr = String(previousContent ?? '');
90
+ const nextStr = String(newContent ?? '');
91
+ if (!prevStr) {
92
+ return {
93
+ stripped: false,
94
+ previousLines: 0,
95
+ newLines: nextStr ? nextStr.split(/\r?\n/).length : 0,
96
+ shrinkageRatio: 0,
97
+ shrinkagePct: 0,
98
+ userAuthorized: false,
99
+ filePath
100
+ };
101
+ }
102
+
103
+ const prevLines = prevStr.split(/\r?\n/).length;
104
+ const nextLines = nextStr ? nextStr.split(/\r?\n/).length : 0;
105
+ const userAuthorized = /\b(delete|remove|drop|strip|clear|truncate|gut|empty|rewrite\s+from\s+scratch)\b/i.test(
106
+ String(userPrompt || '')
107
+ );
108
+
109
+ if (prevLines < minBaselineLines) {
110
+ return {
111
+ stripped: false,
112
+ previousLines: prevLines,
113
+ newLines: nextLines,
114
+ shrinkageRatio: 0,
115
+ shrinkagePct: 0,
116
+ userAuthorized,
117
+ filePath
118
+ };
119
+ }
120
+
121
+ const droppedLines = Math.max(0, prevLines - nextLines);
122
+ const shrinkageRatio = prevLines > 0 ? droppedLines / prevLines : 0;
123
+ const shrinkagePct = Math.round(shrinkageRatio * 100);
124
+ const stripped = shrinkageRatio > shrinkageThreshold && !userAuthorized;
125
+
126
+ return {
127
+ stripped,
128
+ previousLines: prevLines,
129
+ newLines: nextLines,
130
+ droppedLines,
131
+ shrinkageRatio: Number(shrinkageRatio.toFixed(4)),
132
+ shrinkagePct,
133
+ userAuthorized,
134
+ filePath
135
+ };
136
+ }
137
+
138
+ /**
139
+ * DET-05: Inspects a unified diff or before/after diff lines for error-masking constructs:
140
+ * - Deleted `try` / `catch` blocks
141
+ * - Added empty `catch (e) {}` swallow blocks
142
+ * - Added `@ts-ignore`, `@ts-expect-error`, `eslint-disable`, or `# type: ignore` directives
143
+ */
144
+ export function inspectErrorMaskingDiff(diffText = '', filePath = '', { newContent = '' } = {}) {
145
+ const lines = String(diffText || '').split(/\r?\n/);
146
+ let removedTryCatchCount = 0;
147
+ let addedTryCatchCount = 0;
148
+ let suppressionsAddedCount = 0;
149
+ let emptyCatchAddedCount = 0;
150
+ const evidence = [];
151
+
152
+ const catchBlockRegex = /\bcatch\s*(?:\([^)]*\))?\s*\{|\bexcept(?:\s+[A-Za-z0-9_.,\s]+)?\s*:/;
153
+ const suppressionRegex = /(@ts-ignore|@ts-expect-error|eslint-disable(?:-next-line|-line)?|#\s*type:\s*ignore|#\s*noqa\b)/;
154
+ const singleLineEmptyCatchRegex = /\bcatch\s*(?:\([^)]*\))?\s*\{\s*(?:\/\/[^\n}]*)?\}/;
155
+
156
+ const removedCatchEvidence = [];
157
+
158
+ for (const rawLine of lines) {
159
+ if (rawLine.startsWith('---') || rawLine.startsWith('+++')) continue;
160
+ if (rawLine.startsWith('-')) {
161
+ const body = rawLine.slice(1);
162
+ if (catchBlockRegex.test(body)) {
163
+ removedTryCatchCount++;
164
+ removedCatchEvidence.push(`Removed error handler: ${body.trim()}`);
165
+ }
166
+ } else if (rawLine.startsWith('+')) {
167
+ const body = rawLine.slice(1);
168
+ if (catchBlockRegex.test(body)) {
169
+ addedTryCatchCount++;
170
+ }
171
+ if (suppressionRegex.test(body)) {
172
+ suppressionsAddedCount++;
173
+ evidence.push(`Added error suppression: ${body.trim()}`);
174
+ }
175
+ if (singleLineEmptyCatchRegex.test(body)) {
176
+ emptyCatchAddedCount++;
177
+ evidence.push(`Added empty catch swallow: ${body.trim()}`);
178
+ }
179
+ }
180
+ }
181
+
182
+ const netRemovedCatchCount = Math.max(0, removedTryCatchCount - addedTryCatchCount);
183
+ if (netRemovedCatchCount > 0) {
184
+ evidence.unshift(...removedCatchEvidence.slice(0, netRemovedCatchCount));
185
+ }
186
+
187
+ // Also check multi-line empty catch in newContent if provided
188
+ if (newContent) {
189
+ const multiEmptyMatches =
190
+ String(newContent).match(/\bcatch\s*(?:\([^)]*\))?\s*\{\s*(?:\/\/[^\n]*\s*)*\}/g) || [];
191
+ if (multiEmptyMatches.length > emptyCatchAddedCount) {
192
+ const extra = multiEmptyMatches.length - emptyCatchAddedCount;
193
+ emptyCatchAddedCount += extra;
194
+ evidence.push(`Empty catch block detected in ${filePath || 'file'}`);
195
+ }
196
+ }
197
+
198
+ const masked =
199
+ netRemovedCatchCount > 0 || emptyCatchAddedCount > 0 || suppressionsAddedCount > 0;
200
+
201
+ return {
202
+ masked,
203
+ netRemovedCatchCount,
204
+ emptyCatchAddedCount,
205
+ suppressionsAddedCount,
206
+ evidence,
207
+ filePath
208
+ };
209
+ }
210
+
211
+ export class CircuitBreakers {
212
+ constructor(options = {}) {
213
+ this.hysteresisLock = options.hysteresisLock || null;
214
+ this.workspacePath = options.workspacePath || process.cwd();
215
+ this.enableBlindEditGuard = Boolean(options.enableBlindEditGuard);
216
+ this.activeModel = options.activeModel || options.model || null;
217
+ // turnRecords: Array<{ turnIndex, toolSig, failed, exitCode, filePath, fileHash }>
218
+ this.turnRecords = [];
219
+ // fileHashHistory: normalizedPath -> Array<{ turnIndex, hash }>
220
+ this.fileHashHistory = new Map();
221
+ // DET-17b state tracking
222
+ this.readFiles = new Set();
223
+ this.hasSearchedWorkspace = false;
224
+ this.activeAlerts = [];
225
+ }
226
+
227
+ markFileIndexed(filePath = '') {
228
+ const norm = canonicalizePath(String(filePath || '').trim());
229
+ if (norm) this.readFiles.add(norm);
230
+ }
231
+
232
+ markWorkspaceSearched() {
233
+ this.hasSearchedWorkspace = true;
234
+ }
235
+
236
+ /**
237
+ * Records a turn or tool execution and evaluates DET-01, DET-02, and DET-03 in <2ms.
238
+ */
239
+ recordTurn(turnInput = {}) {
240
+ const startMs = performance.now();
241
+ const turnIndex = Number.isFinite(turnInput.turnIndex)
242
+ ? Number(turnInput.turnIndex)
243
+ : this.turnRecords.length;
244
+ const stepId = String(turnInput.activeTaskMdStepId || turnInput.stepId || 'active-step');
245
+
246
+ const toolName = String(turnInput.toolName || turnInput.tool || '').toLowerCase().trim();
247
+ const args = turnInput.args || turnInput.parameters || {};
248
+ const exitCode = Number(turnInput.exitCode ?? (turnInput.error ? 1 : 0));
249
+ const failed = Boolean(turnInput.failed || turnInput.error || exitCode !== 0);
250
+ const toolSig = normalizeToolSignature(toolName, args);
251
+
252
+ const rawPath = String(
253
+ turnInput.filePath ||
254
+ args.Path ||
255
+ args.path ||
256
+ args.TargetFile ||
257
+ args.AbsolutePath ||
258
+ ''
259
+ ).trim();
260
+ const normPath = rawPath ? canonicalizePath(rawPath) : '';
261
+
262
+ const replacementChunks = Array.isArray(args.ReplacementChunks) ? args.ReplacementChunks : null;
263
+ const chunksOld = replacementChunks
264
+ ? replacementChunks.map((ch) => String(ch?.TargetContent ?? ch?.Target ?? ch?.oldContent ?? '')).filter(Boolean).join('\n')
265
+ : undefined;
266
+ const chunksNew = replacementChunks
267
+ ? replacementChunks.map((ch) => String(ch?.ReplacementContent ?? ch?.Replacement ?? ch?.newContent ?? '')).filter(Boolean).join('\n')
268
+ : undefined;
269
+
270
+ const resolvedPreviousContent = turnInput.previousContent !== undefined
271
+ ? turnInput.previousContent
272
+ : (args.Target !== undefined
273
+ ? args.Target
274
+ : (args.TargetContent !== undefined ? args.TargetContent : chunksOld));
275
+
276
+ const resolvedNewContent = turnInput.newContent !== undefined
277
+ ? turnInput.newContent
278
+ : (args.Content !== undefined
279
+ ? args.Content
280
+ : (args.CodeContent !== undefined
281
+ ? args.CodeContent
282
+ : (args.Replacement !== undefined
283
+ ? args.Replacement
284
+ : (args.ReplacementContent !== undefined ? args.ReplacementContent : chunksNew))));
285
+
286
+ let fileHash = turnInput.fileHash || null;
287
+ if (!fileHash && resolvedNewContent !== undefined && resolvedNewContent !== null) {
288
+ fileHash = sha256Hex(resolvedNewContent);
289
+ }
290
+
291
+ this.turnRecords.push({
292
+ turnIndex,
293
+ stepId,
294
+ toolName,
295
+ toolSig,
296
+ failed,
297
+ exitCode,
298
+ filePath: rawPath,
299
+ normPath,
300
+ fileHash
301
+ });
302
+
303
+ const triggered = [];
304
+
305
+ // 1. Evaluate DET-01 (Retry Churn: >= 2 identical failing tool calls or non-zero exit codes)
306
+ const recentFailuresForSig = this.turnRecords.filter(
307
+ (r) => r.failed && r.toolSig === toolSig && (turnIndex - r.turnIndex) <= 5
308
+ );
309
+ const consecutiveNonZero = [];
310
+ for (let i = this.turnRecords.length - 1; i >= 0; i--) {
311
+ if (this.turnRecords[i].failed) {
312
+ consecutiveNonZero.push(this.turnRecords[i]);
313
+ } else {
314
+ break;
315
+ }
316
+ }
317
+
318
+ const rawActiveModel = String(
319
+ turnInput.activeModel ||
320
+ turnInput.currentModel ||
321
+ turnInput.model ||
322
+ this.activeModel ||
323
+ ''
324
+ ).toLowerCase().trim();
325
+ const escalatedFrontierModel = rawActiveModel.includes('carbon')
326
+ ? (rawActiveModel.includes('cyber-permissive') ? 'gemini-4-carbon-cyber-permissive' : 'gemini-4-carbon')
327
+ : 'gemini-4-argon';
328
+
329
+ if (failed && (recentFailuresForSig.length >= 2 || consecutiveNonZero.length >= 2)) {
330
+ const retryCount = Math.max(recentFailuresForSig.length, consecutiveNonZero.length);
331
+ if (this.hysteresisLock && typeof this.hysteresisLock.engage === 'function') {
332
+ this.hysteresisLock.engage({
333
+ stepId,
334
+ model: escalatedFrontierModel,
335
+ effort: 'high',
336
+ detectorId: 'DET-01',
337
+ reason: `DET-01 Retry Churn (${retryCount} failing attempts)`,
338
+ turnIndex
339
+ });
340
+ }
341
+
342
+ const alert = {
343
+ detectorId: 'DET-01',
344
+ name: 'Retry Churn',
345
+ severity: 'CRITICAL',
346
+ turnIndex,
347
+ retryCount,
348
+ escalatedTier: { model: escalatedFrontierModel, effort: 'high' },
349
+ message: `🚨 DET-01 Retry Churn: ${retryCount} consecutive failures detected. Sticky tier escalation engaged.`
350
+ };
351
+ triggered.push(alert);
352
+ this.activeAlerts.push(alert);
353
+ }
354
+
355
+ // 2. Evaluate DET-02 (AST Edit Oscillation: SHA-256 matches T-2 or T-3 within 5 turns)
356
+ if (normPath && fileHash && !failed) {
357
+ if (!this.fileHashHistory.has(normPath)) {
358
+ this.fileHashHistory.set(normPath, []);
359
+ }
360
+ const hist = this.fileHashHistory.get(normPath);
361
+
362
+ // Look for matching hash at T-2 or T-3 within <= 5 turns
363
+ const priorMatch = hist.find((entry, idx) => {
364
+ const turnsAgo = turnIndex - entry.turnIndex;
365
+ const snapshotsAgo = hist.length - idx;
366
+ return entry.hash === fileHash && turnsAgo <= 5 && (snapshotsAgo >= 2 || turnsAgo >= 2);
367
+ });
368
+
369
+ hist.push({ turnIndex, hash: fileHash });
370
+
371
+ if (priorMatch) {
372
+ if (this.hysteresisLock && typeof this.hysteresisLock.engage === 'function') {
373
+ this.hysteresisLock.engage({
374
+ stepId,
375
+ model: escalatedFrontierModel,
376
+ effort: 'high',
377
+ detectorId: 'DET-02',
378
+ reason: `DET-02 AST Edit Oscillation on ${rawPath} (reverted to turn #${priorMatch.turnIndex} state)`,
379
+ turnIndex
380
+ });
381
+ }
382
+
383
+ const alert = {
384
+ detectorId: 'DET-02',
385
+ name: 'AST Edit Oscillation',
386
+ severity: 'CRITICAL',
387
+ turnIndex,
388
+ filePath: rawPath,
389
+ matchedTurnIndex: priorMatch.turnIndex,
390
+ fileHash,
391
+ promptPill: {
392
+ label: '🛡️ Inject 3-Stage Stepwise Refinement Contract',
393
+ injectAsNextUserMessage: true,
394
+ preservesPrefixCache: true,
395
+ prompt: THREE_STAGE_CONTRACT_PROMPT
396
+ },
397
+ message: `🚨 DET-02 AST Edit Oscillation: ${rawPath} reverted to state from turn #${priorMatch.turnIndex}.`
398
+ };
399
+ triggered.push(alert);
400
+ this.activeAlerts.push(alert);
401
+ }
402
+ }
403
+
404
+ // 3. Evaluate DET-03 (Test Assertion Weakening via git diff or before/after content)
405
+ let resolvedDiffText = String(turnInput.gitDiff || '');
406
+ if (!resolvedDiffText && resolvedPreviousContent !== undefined && resolvedNewContent !== undefined) {
407
+ const oldLines = String(resolvedPreviousContent).split(/\r?\n/).map((l) => `-${l}`);
408
+ const newLines = String(resolvedNewContent).split(/\r?\n/).map((l) => `+${l}`);
409
+ resolvedDiffText = [...oldLines, ...newLines].join('\n');
410
+ }
411
+
412
+ if (rawPath && isTestFilePath(rawPath) && resolvedDiffText) {
413
+ const audit = inspectGitDiffAssertionWeakening(resolvedDiffText, rawPath);
414
+ if (audit.weakened) {
415
+ const alert = {
416
+ detectorId: 'DET-03',
417
+ name: 'Test Assertion Weakening',
418
+ severity: 'CRITICAL',
419
+ turnIndex,
420
+ filePath: rawPath,
421
+ deletedCount: audit.deletedCount,
422
+ netDeletedCount: audit.netDeletedCount,
423
+ deletedAssertions: audit.deletedAssertions,
424
+ revertAction: {
425
+ type: 'GIT_HUNK_REVERT',
426
+ nonDestructive: true,
427
+ requiresConfirmation: true,
428
+ label: `🔍 Preview & Restore Deleted Assertions in ${rawPath}`,
429
+ command: `git diff -- "${rawPath}"`,
430
+ prompt: `Restore the ${audit.netDeletedCount} deleted test assertion(s) in ${rawPath} without discarding other uncommitted changes (inspect diff via: git diff -- "${rawPath}").`,
431
+ filePath: rawPath
432
+ },
433
+ message: `🚨 DET-03 Test Assertion Weakening: ${audit.netDeletedCount} assert/expect statement(s) deleted in ${rawPath}.`
434
+ };
435
+ triggered.push(alert);
436
+ this.activeAlerts.push(alert);
437
+ }
438
+ }
439
+
440
+ // 4. Evaluate DET-22 (Destructive Code-Stripping / >50% File Shrinkage)
441
+ if (rawPath && resolvedPreviousContent !== undefined && resolvedNewContent !== undefined) {
442
+ const shrinkAudit = inspectFileShrinkage({
443
+ previousContent: resolvedPreviousContent,
444
+ newContent: resolvedNewContent,
445
+ filePath: rawPath,
446
+ userPrompt: turnInput.userPrompt || ''
447
+ });
448
+ if (shrinkAudit.stripped) {
449
+ const alert = {
450
+ detectorId: 'DET-22',
451
+ name: 'Destructive Code-Stripping (>50% File Shrinkage)',
452
+ severity: 'CRITICAL',
453
+ turnIndex,
454
+ filePath: rawPath,
455
+ previousLines: shrinkAudit.previousLines,
456
+ newLines: shrinkAudit.newLines,
457
+ shrinkagePct: shrinkAudit.shrinkagePct,
458
+ revertAction: {
459
+ type: 'GIT_HUNK_REVERT',
460
+ nonDestructive: true,
461
+ requiresConfirmation: true,
462
+ label: `🔍 Preview & Restore ${shrinkAudit.shrinkagePct}% Shrinkage in ${rawPath}`,
463
+ command: `git diff -- "${rawPath}"`,
464
+ prompt: `Restore the stripped code in ${rawPath} (${shrinkAudit.previousLines} -> ${shrinkAudit.newLines} lines) without discarding valid edits (inspect diff via: git diff -- "${rawPath}").`,
465
+ filePath: rawPath
466
+ },
467
+ message: `🚨 DET-22 Destructive Code-Stripping: ${rawPath} shrank by ${shrinkAudit.shrinkagePct}% (${shrinkAudit.previousLines} -> ${shrinkAudit.newLines} lines) without user authorization.`
468
+ };
469
+ triggered.push(alert);
470
+ this.activeAlerts.push(alert);
471
+ }
472
+ }
473
+
474
+ // 5. Evaluate DET-23 (Error-Masking & Silent try/catch Stripping)
475
+ if (rawPath && resolvedDiffText && !isTestFilePath(rawPath)) {
476
+ const maskAudit = inspectErrorMaskingDiff(resolvedDiffText, rawPath, {
477
+ newContent: resolvedNewContent || ''
478
+ });
479
+ if (maskAudit.masked) {
480
+ const alert = {
481
+ detectorId: 'DET-23',
482
+ name: 'Error-Masking & Try/Catch Stripping',
483
+ severity: 'HIGH',
484
+ turnIndex,
485
+ filePath: rawPath,
486
+ netRemovedCatchCount: maskAudit.netRemovedCatchCount,
487
+ emptyCatchAddedCount: maskAudit.emptyCatchAddedCount,
488
+ suppressionsAddedCount: maskAudit.suppressionsAddedCount,
489
+ evidence: maskAudit.evidence,
490
+ revertAction: {
491
+ type: 'GIT_HUNK_REVERT',
492
+ nonDestructive: true,
493
+ requiresConfirmation: true,
494
+ label: `🔍 Preview & Restore Error Handling in ${rawPath}`,
495
+ command: `git diff -- "${rawPath}"`,
496
+ prompt: `Restore proper try/catch error handling in ${rawPath} without silent suppression (inspect diff via: git diff -- "${rawPath}").`,
497
+ filePath: rawPath
498
+ },
499
+ message: `🚨 DET-23 Error-Masking Detected in ${rawPath}: ${maskAudit.evidence[0] || 'Error handler stripped or suppressed'}.`
500
+ };
501
+ triggered.push(alert);
502
+ this.activeAlerts.push(alert);
503
+ }
504
+ }
505
+
506
+ // 6. Track read/search indexing and evaluate DET-18 (Untrusted Settings) + DET-21 (Blind-Edit / Unindexed File Creation Guard)
507
+ const isReadTool = /^(read_file|view_file|view_file_outline|view_code_item)$/.test(toolName);
508
+ const isSearchTool = /^(grep_search|find_by_name|codebase_search|list_dir)$/.test(toolName);
509
+ const isWriteOrEditTool = /^(edit_file|replace_file_content|multi_replace_file_content|write_file|write_to_file)$/.test(toolName);
510
+
511
+ if (isWriteOrEditTool && rawPath) {
512
+ const det18Check = evaluateDet18UntrustedWorkspaceSettings({
513
+ targetPath: rawPath,
514
+ newContent: resolvedNewContent || '',
515
+ toolName,
516
+ userAuthorizedSettingsEdit: Boolean(turnInput.userAuthorizedSettingsEdit)
517
+ });
518
+ if (det18Check.blocked) {
519
+ const alert = {
520
+ detectorId: 'DET-18',
521
+ name: 'Untrusted Workspace Settings & Hook Injection Guard',
522
+ severity: 'CRITICAL',
523
+ turnIndex,
524
+ filePath: rawPath,
525
+ hazards: det18Check.hazards,
526
+ message: det18Check.message
527
+ };
528
+ triggered.push(alert);
529
+ this.activeAlerts.push(alert);
530
+ }
531
+ }
532
+
533
+ if (isReadTool && normPath) {
534
+ this.readFiles.add(normPath);
535
+ }
536
+ if (isSearchTool) {
537
+ this.hasSearchedWorkspace = true;
538
+ }
539
+
540
+ if ((this.enableBlindEditGuard || turnInput.checkBlindEdit) && isWriteOrEditTool && normPath) {
541
+ const isCreateNew = Boolean(turnInput.isNewFile || /^write_(file|to_file)$/.test(toolName));
542
+ const wasRead = this.readFiles.has(normPath);
543
+ if (!isCreateNew && !wasRead) {
544
+ const alert = {
545
+ detectorId: 'DET-21',
546
+ name: 'Blind-Edit Without Prior File Read',
547
+ severity: 'WARN',
548
+ turnIndex,
549
+ filePath: rawPath,
550
+ mode: 'blind_edit',
551
+ message: `⚠️ DET-21 Blind-Edit Guard: ${rawPath} was modified without prior read_file inspection in this session.`
552
+ };
553
+ triggered.push(alert);
554
+ this.activeAlerts.push(alert);
555
+ } else if (isCreateNew && !this.hasSearchedWorkspace && this.readFiles.size === 0) {
556
+ const alert = {
557
+ detectorId: 'DET-21',
558
+ name: 'Unindexed New File Creation',
559
+ severity: 'WARN',
560
+ turnIndex,
561
+ filePath: rawPath,
562
+ mode: 'unindexed_create',
563
+ message: `⚠️ DET-21 Unindexed File Creation: ${rawPath} was created without prior codebase search or file indexing.`
564
+ };
565
+ triggered.push(alert);
566
+ this.activeAlerts.push(alert);
567
+ }
568
+ // Once written/edited, mark it known for subsequent turns
569
+ this.readFiles.add(normPath);
570
+ }
571
+
572
+ return {
573
+ turnIndex,
574
+ triggered,
575
+ hasTripped: triggered.length > 0,
576
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
577
+ };
578
+ }
579
+
580
+ /**
581
+ * Purges oscillation hashes, retry counters, and alerts recorded during rewound turns
582
+ * (`turnIndex >= newStepCount`) when `TrajectoryWatcher` emits `TRAJECTORY_REWIND`.
583
+ */
584
+ purgeRewoundTurns(newStepCount = 0) {
585
+ const cutoff = Math.max(0, Number(newStepCount) || 0);
586
+ const beforeCount = this.turnRecords.length;
587
+ this.turnRecords = this.turnRecords.filter((r) => r.turnIndex < cutoff);
588
+ this.activeAlerts = this.activeAlerts.filter((a) => a.turnIndex < cutoff);
589
+
590
+ for (const [normPath, hist] of this.fileHashHistory.entries()) {
591
+ const kept = hist.filter((entry) => entry.turnIndex < cutoff);
592
+ if (kept.length === 0) {
593
+ this.fileHashHistory.delete(normPath);
594
+ } else {
595
+ this.fileHashHistory.set(normPath, kept);
596
+ }
597
+ }
598
+
599
+ if (this.hysteresisLock && typeof this.hysteresisLock.onTrajectoryRewind === 'function') {
600
+ this.hysteresisLock.onTrajectoryRewind({ newStepCount: cutoff });
601
+ }
602
+
603
+ return {
604
+ purgedTurnCount: Math.max(0, beforeCount - this.turnRecords.length),
605
+ remainingTurns: this.turnRecords.length,
606
+ activeAlertCount: this.activeAlerts.length
607
+ };
608
+ }
609
+
610
+ onTrajectoryRewind(rewindPayload = {}) {
611
+ return this.purgeRewoundTurns(rewindPayload.newStepCount ?? 0);
612
+ }
613
+
614
+ /**
615
+ * Generates a non-destructive git diff preview and explicit restoration prompt
616
+ * for DET-03 weakened test assertions (never executes destructive `git checkout --`).
617
+ */
618
+ revertWeakenedTestFile(filePath, { cwd = this.workspacePath, execFn = execFileSync } = {}) {
619
+ const target = String(filePath || '').trim();
620
+ if (!target) {
621
+ throw new Error('CircuitBreakers.revertWeakenedTestFile: filePath is required');
622
+ }
623
+ let diffPreview = '';
624
+ try {
625
+ const out = execFn('git', ['diff', '--', target], {
626
+ cwd,
627
+ encoding: 'utf8',
628
+ stdio: ['ignore', 'pipe', 'pipe'],
629
+ timeout: 3000
630
+ });
631
+ diffPreview = typeof out === 'string' ? out : (out ? String(out) : '');
632
+ } catch {
633
+ diffPreview = '';
634
+ }
635
+ this.activeAlerts = this.activeAlerts.filter(
636
+ (a) => !((a.detectorId === 'DET-03' || a.detectorId === 'DET-06') && canonicalizePath(a.filePath) === canonicalizePath(target))
637
+ );
638
+ return {
639
+ ok: true,
640
+ nonDestructive: true,
641
+ requiresConfirmation: true,
642
+ revertedFile: target,
643
+ previewCommand: `git diff -- "${target}"`,
644
+ diffPreview,
645
+ prompt: `Restore the deleted test assertions in ${target} without discarding other uncommitted edits.`
646
+ };
647
+ }
648
+ }
649
+
650
+ export default CircuitBreakers;