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,802 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { atomicWriteFileSync } from './atomic_io.mjs';
5
+ export {
6
+ LEGACY_GA_V3_ID_MAP,
7
+ migrateLegacyHorizonConfig
8
+ } from '../core-isomorphic/catalog/detectorCatalog.mjs';
9
+
10
+ /**
11
+ * Unified Cross-Harness Configuration, Per-Detector Override Engine (`.attention-horizon.json`),
12
+ * Zero-PII Bug Report Generator (`doctor --diagnostic`), and Git Efficiency Receipt Exporter
13
+ * for Highbeam (`attention-horizon-antigravity`).
14
+ */
15
+
16
+ export const CANONICAL_DETECTOR_IDS = Object.freeze([
17
+ 'DET-01',
18
+ 'DET-02',
19
+ 'DET-03',
20
+ 'DET-04',
21
+ 'DET-05',
22
+ 'DET-06',
23
+ 'DET-07',
24
+ 'DET-08',
25
+ 'DET-09',
26
+ 'DET-10',
27
+ 'DET-11',
28
+ 'DET-12',
29
+ 'DET-13',
30
+ 'DET-14',
31
+ 'DET-15',
32
+ 'DET-16',
33
+ 'DET-17',
34
+ 'DET-18',
35
+ 'DET-19',
36
+ 'DET-20'
37
+ ]);
38
+
39
+ export const EXTENDED_DETECTOR_IDS = Object.freeze([
40
+ ...CANONICAL_DETECTOR_IDS,
41
+ 'DET-21',
42
+ 'DET-22',
43
+ 'DET-23',
44
+ 'DET-24',
45
+ 'DET-25',
46
+ 'DET-26',
47
+ 'DET-27',
48
+ 'DET-28',
49
+ 'DET-29',
50
+ 'DET-30'
51
+ ]);
52
+
53
+ export const RING0_SECURITY_DETECTORS = Object.freeze([
54
+ 'DET-08',
55
+ 'DET-15',
56
+ 'DET-18',
57
+ 'DET-19'
58
+ ]);
59
+
60
+ export const ANTIGRAVITY_DETECTOR_SLUGS = Object.freeze({
61
+ 'DET-01': 'retry-churn',
62
+ 'DET-02': 'edit-oscillation',
63
+ 'DET-03': 'assertion-weakening',
64
+ 'DET-04': 'fake-screenshot',
65
+ 'DET-05': 'premature-stop',
66
+ 'DET-06': 'redundant-reread',
67
+ 'DET-07': 'phantom-file',
68
+ 'DET-08': 'git-shell-safety',
69
+ 'DET-09': 'prefix-mutation-fence',
70
+ 'DET-10': 'output-bomb',
71
+ 'DET-11': 'zombie-process',
72
+ 'DET-12': 'premature-exec',
73
+ 'DET-13': 'subagent-collision',
74
+ 'DET-14': 'placeholder-slop',
75
+ 'DET-15': 'secret-boundary',
76
+ 'DET-16': 'ttl-watchdog',
77
+ 'DET-17': 'shadow-file-bloat',
78
+ 'DET-18': 'untrusted-settings',
79
+ 'DET-19': 'git-hook-bypass',
80
+ 'DET-20': 'scope-lock',
81
+ 'DET-21': 'blind-edit',
82
+ 'DET-22': 'file-shrinkage',
83
+ 'DET-23': 'empty-catch',
84
+ 'DET-24': 'high-turn-degradation',
85
+ 'DET-25': 'progressive-checkpoint',
86
+ 'DET-26': 'prompt-decomposer',
87
+ 'DET-27': 'rule-file-bloat',
88
+ 'DET-28': 'subagent-phantom',
89
+ 'DET-29': 'reflector-queue',
90
+ 'DET-30': 'thinking-drift-loop'
91
+ });
92
+
93
+ export const SLUG_TO_ANTIGRAVITY_DETECTOR = Object.freeze({
94
+ 'retry-churn': 'DET-01',
95
+ 'edit-oscillation': 'DET-02',
96
+ 'assertion-weakening': 'DET-03',
97
+ 'fake-screenshot': 'DET-04',
98
+ 'panic-spiral': 'DET-05',
99
+ 'premature-stop': 'DET-05',
100
+ 'redundant-reread': 'DET-06',
101
+ 'blind-search': 'DET-06',
102
+ 'phantom-file': 'DET-07',
103
+ 'git-shell-safety': 'DET-08',
104
+ 'prefix-mutation-fence': 'DET-09',
105
+ 'output-bomb': 'DET-10',
106
+ 'zombie-process': 'DET-11',
107
+ 'premature-exec': 'DET-12',
108
+ 'subagent-collision': 'DET-13',
109
+ 'placeholder-slop': 'DET-14',
110
+ 'secret-boundary': 'DET-15',
111
+ 'ttl-watchdog': 'DET-16',
112
+ 'shadow-file-bloat': 'DET-17',
113
+ 'context-rot': 'DET-17',
114
+ 'untrusted-settings': 'DET-18',
115
+ 'git-hook-bypass': 'DET-19',
116
+ 'scope-lock': 'DET-20',
117
+ 'blind-edit': 'DET-21',
118
+ 'blind-edit-without-read': 'DET-21',
119
+ 'file-shrinkage': 'DET-22',
120
+ 'diff-thrashing': 'DET-22',
121
+ 'empty-catch': 'DET-23',
122
+ 'high-turn-degradation': 'DET-24',
123
+ 'progressive-checkpoint': 'DET-25',
124
+ 'prompt-decomposer': 'DET-26',
125
+ 'vague-prompt-rubric': 'DET-26',
126
+ 'rule-file-bloat': 'DET-27',
127
+ 'subagent-phantom': 'DET-28',
128
+ 'reflector-queue': 'DET-29',
129
+ 'thinking-drift-loop': 'DET-30',
130
+ 'scratchpad-loop': 'DET-30'
131
+ });
132
+
133
+ /**
134
+ * Pure semantic developer-habit slugs (`off | warn | block | default`).
135
+ * Intentionally unaliased from Ring-0 numeric IDs (`DET-08`, `DET-15`, `DET-18`, `DET-19`)
136
+ * so disabling e.g. `"formatter-bypass"` never disables Ring-0 `DET-15` (`secret-boundary`).
137
+ */
138
+ export const HABIT_SEMANTIC_SLUGS = Object.freeze([
139
+ 'formatter-bypass',
140
+ 'drip-feed',
141
+ 'vague-prompt-rubric',
142
+ 'effort-overkill',
143
+ 'post-commit-handoff',
144
+ 'vision-screenshot-coach',
145
+ 'micro-skills',
146
+ 'relay-breaker'
147
+ ]);
148
+
149
+ /**
150
+ * Claude Code numeric DET-01..20 -> Antigravity detector / semantic mapping.
151
+ * Crucially, CC DET-19 (`subagent-ipi`) maps ONLY to `semanticDetectors['subagent-ipi']`
152
+ * and NEVER disables Antigravity Ring-0 `DET-19` (`git-hook-bypass`).
153
+ */
154
+ export const CLAUDE_CODE_DETECTOR_TRANSLATION = Object.freeze({
155
+ 'DET-01': { gaIds: ['DET-08', 'DET-19'], slug: 'git-shell-safety' },
156
+ 'DET-02': { gaIds: ['DET-15'], slug: 'secret-boundary' },
157
+ 'DET-03': { gaIds: [], slug: 'scope-drift' },
158
+ 'DET-04': { gaIds: ['DET-01'], slug: 'retry-churn' },
159
+ 'DET-05': { gaIds: ['DET-02'], slug: 'edit-oscillation' },
160
+ 'DET-06': { gaIds: ['DET-06'], slug: 'redundant-reread' },
161
+ 'DET-07': { gaIds: ['DET-10'], slug: 'output-bomb' },
162
+ 'DET-08': { gaIds: [], slug: 'cache-gravity-hold' },
163
+ 'DET-09': { gaIds: ['DET-09'], slug: 'prefix-mutation-fence' },
164
+ 'DET-10': { gaIds: ['DET-16'], slug: 'ttl-watchdog' },
165
+ 'DET-11': { gaIds: ['DET-17'], slug: 'shadow-file-bloat' },
166
+ 'DET-12': { gaIds: ['DET-22'], slug: 'file-shrinkage' },
167
+ 'DET-13': { gaIds: ['DET-03'], slug: 'assertion-weakening' },
168
+ 'DET-14': { gaIds: ['DET-23'], slug: 'empty-catch' },
169
+ 'DET-15': { gaIds: ['DET-14'], slug: 'placeholder-slop' },
170
+ 'DET-16': { gaIds: ['DET-05'], slug: 'premature-stop' },
171
+ 'DET-17': { gaIds: ['DET-21'], slug: 'blind-edit' },
172
+ 'DET-18': { gaIds: ['DET-18'], slug: 'untrusted-settings' },
173
+ 'DET-19': { gaIds: [], slug: 'subagent-ipi' },
174
+ 'DET-20': { gaIds: ['DET-20'], slug: 'scope-lock' },
175
+ 'DET-21': { gaIds: ['DET-30'], slug: 'thinking-drift-loop' }
176
+ });
177
+
178
+ export const DEFAULT_HORIZON_CONFIG = Object.freeze({
179
+ schemaVersion: '1.0.0',
180
+ detectorNamespace: 'antigravity',
181
+ flightMode: 'COACH',
182
+ detectors: Object.freeze(Object.fromEntries(EXTENDED_DETECTOR_IDS.map((id) => [id, 'default']))),
183
+ semanticDetectors: Object.freeze({
184
+ 'subagent-ipi': 'default',
185
+ 'cache-gravity-hold': 'default',
186
+ 'scope-drift': 'default',
187
+ 'formatter-bypass': 'default',
188
+ 'drip-feed': 'default',
189
+ 'vague-prompt-rubric': 'default',
190
+ 'effort-overkill': 'default',
191
+ 'post-commit-handoff': 'default',
192
+ 'vision-screenshot-coach': 'default',
193
+ 'micro-skills': 'default',
194
+ 'relay-breaker': 'default'
195
+ }),
196
+ thresholds: Object.freeze({
197
+ safeLimitTokens: 147000,
198
+ reminderAtPct: 75,
199
+ subagentOffloadTokens: 12000,
200
+ blindSearchLimit: 6,
201
+ consecutiveFailureLimit: 3,
202
+ microSkillConfirmSessions: 2
203
+ })
204
+ });
205
+
206
+ function parseNumericDetKey(rawId) {
207
+ const s = String(rawId || '').trim().toUpperCase();
208
+ if (/^DET[-_]?17B$/.test(s)) {
209
+ return 'DET-21';
210
+ }
211
+ const m = s.match(/^DET[-_]?(\d{1,2})$/);
212
+ if (!m) return null;
213
+ const num = Number(m[1]);
214
+ if (num < 1 || num > 30) return null;
215
+ return `DET-${String(num).padStart(2, '0')}`;
216
+ }
217
+
218
+ export function normalizeDetectorId(rawId) {
219
+ if (rawId === null || rawId === undefined) return null;
220
+ const trimmed = String(rawId).trim();
221
+ if (!trimmed) return null;
222
+
223
+ const numeric = parseNumericDetKey(trimmed);
224
+ if (numeric) return numeric;
225
+
226
+ const slugKey = trimmed.toLowerCase().replace(/_/g, '-');
227
+ if (slugKey === 'scope-brake') return 'DET-26';
228
+ if (Object.prototype.hasOwnProperty.call(SLUG_TO_ANTIGRAVITY_DETECTOR, slugKey)) {
229
+ return SLUG_TO_ANTIGRAVITY_DETECTOR[slugKey];
230
+ }
231
+ if (slugKey === 'spec-relay') return 'relay-breaker';
232
+ if (HABIT_SEMANTIC_SLUGS.includes(slugKey)) return slugKey;
233
+
234
+ return null;
235
+ }
236
+
237
+ export function normalizeDetectorMode(rawMode) {
238
+ if (rawMode === false || rawMode === 0) return 'off';
239
+ if (rawMode === true) return 'default';
240
+ const s = String(rawMode || 'default')
241
+ .trim()
242
+ .toLowerCase();
243
+ if (s === 'off' || s === 'disable' || s === 'disabled' || s === 'mute') return 'off';
244
+ if (s === 'warn' || s === 'advisory' || s === 'coach' || s === 'steer') return 'warn';
245
+ if (s === 'block' || s === 'deny' || s === 'strict' || s === 'enforce') return 'block';
246
+ return 'default';
247
+ }
248
+
249
+ export function resolveDetectorOverride(config, idOrSlug) {
250
+ if (!config || typeof config !== 'object') return 'default';
251
+ const slugLower = String(idOrSlug || '').trim().toLowerCase().replace(/_/g, '-');
252
+ const candidateSlugs =
253
+ slugLower === 'vague-prompt-rubric' || slugLower === 'scope-brake'
254
+ ? ['vague-prompt-rubric', 'prompt-decomposer', 'scope-brake']
255
+ : slugLower === 'prompt-decomposer'
256
+ ? ['prompt-decomposer', 'vague-prompt-rubric', 'scope-brake']
257
+ : slugLower === 'relay-breaker' || slugLower === 'spec-relay'
258
+ ? ['relay-breaker', 'spec-relay']
259
+ : [slugLower];
260
+
261
+ for (const cand of candidateSlugs) {
262
+ if (config.semanticDetectors && Object.prototype.hasOwnProperty.call(config.semanticDetectors, cand)) {
263
+ const semMode = normalizeDetectorMode(config.semanticDetectors[cand]);
264
+ if (semMode && semMode !== 'default') return semMode;
265
+ }
266
+ if (config.detectors && Object.prototype.hasOwnProperty.call(config.detectors, cand)) {
267
+ const detSlugMode = normalizeDetectorMode(config.detectors[cand]);
268
+ if (detSlugMode && detSlugMode !== 'default') return detSlugMode;
269
+ }
270
+ }
271
+
272
+ const normId = normalizeDetectorId(idOrSlug);
273
+ if (normId && config.detectors && Object.prototype.hasOwnProperty.call(config.detectors, normId)) {
274
+ return normalizeDetectorMode(config.detectors[normId]);
275
+ }
276
+ return 'default';
277
+ }
278
+
279
+ function readJsonSafe(targetPath, fallback = null) {
280
+ try {
281
+ if (!fs.existsSync(targetPath)) return fallback;
282
+ return JSON.parse(fs.readFileSync(targetPath, 'utf8'));
283
+ } catch {
284
+ return fallback;
285
+ }
286
+ }
287
+
288
+ function writeJsonAtomic(targetPath, data) {
289
+ try {
290
+ atomicWriteFileSync(targetPath, JSON.stringify(data, null, 2) + '\n', { encoding: 'utf8' });
291
+ return true;
292
+ } catch {
293
+ return false;
294
+ }
295
+ }
296
+
297
+ export function resolveHorizonConfigPaths(options = {}) {
298
+ const cwd = options.cwd || options.workspacePath || process.cwd();
299
+ const homeDir = options.homeDir || os.homedir();
300
+ const scope = options.scope === 'global' ? 'global' : 'project';
301
+
302
+ const projectConfigPath = options.configPath || path.join(cwd, '.attention-horizon.json');
303
+ const globalConfigPath = path.join(homeDir, '.attention-horizon', 'config.json');
304
+ const activeWritePath = scope === 'global' ? globalConfigPath : projectConfigPath;
305
+
306
+ return {
307
+ projectConfigPath,
308
+ globalConfigPath,
309
+ activeWritePath
310
+ };
311
+ }
312
+
313
+ function normalizeFlightMode(raw) {
314
+ const fm = String(raw || '').trim().toUpperCase().replace(/-/g, '_');
315
+ if (fm === 'AUTOPILOT') return 'AUTO_PILOT';
316
+ if (fm === 'COACH' || fm === 'AUTO_PILOT' || fm === 'SILENT' || fm === 'OFF') {
317
+ return fm;
318
+ }
319
+ return null;
320
+ }
321
+
322
+ export function loadHorizonConfig(options = {}) {
323
+ const { projectConfigPath, globalConfigPath } = resolveHorizonConfigPaths(options);
324
+ const globalRaw = readJsonSafe(globalConfigPath, null);
325
+ const projectRaw = readJsonSafe(projectConfigPath, null);
326
+
327
+ const detectors = { ...DEFAULT_HORIZON_CONFIG.detectors };
328
+ const semanticDetectors = { ...DEFAULT_HORIZON_CONFIG.semanticDetectors };
329
+ const thresholds = { ...DEFAULT_HORIZON_CONFIG.thresholds };
330
+ const warnings = [];
331
+ let flightMode = DEFAULT_HORIZON_CONFIG.flightMode;
332
+ let detectorNamespace = DEFAULT_HORIZON_CONFIG.detectorNamespace;
333
+
334
+ const mergeLayer = (layer, { isDiskLayer = false, sourceLabel = 'config' } = {}) => {
335
+ if (!layer || typeof layer !== 'object' || Array.isArray(layer)) return;
336
+
337
+ const rawNamespace = typeof layer.detectorNamespace === 'string'
338
+ ? layer.detectorNamespace.trim().toLowerCase()
339
+ : '';
340
+ const isClaudeNamespace = rawNamespace === 'claude-code' || rawNamespace === 'claude_code' || rawNamespace === 'claude';
341
+ const isAntigravityNamespace =
342
+ rawNamespace === 'antigravity' ||
343
+ rawNamespace === 'ga' ||
344
+ Boolean(layer.antigravityDetectors && typeof layer.antigravityDetectors === 'object');
345
+
346
+ if (rawNamespace) {
347
+ detectorNamespace = isClaudeNamespace ? 'claude-code' : 'antigravity';
348
+ }
349
+
350
+ if (typeof layer.flightMode === 'string' && layer.flightMode.trim()) {
351
+ const parsedFm = normalizeFlightMode(layer.flightMode);
352
+ if (parsedFm) {
353
+ flightMode = parsedFm;
354
+ }
355
+ }
356
+
357
+ // Track explicit semantic slug overrides in this layer
358
+ const explicitSlugsInLayer = new Map();
359
+ if (layer.semanticDetectors && typeof layer.semanticDetectors === 'object') {
360
+ for (const [sk, sv] of Object.entries(layer.semanticDetectors)) {
361
+ const cleanSlug = String(sk || '').trim().toLowerCase().replace(/_/g, '-');
362
+ const mode = normalizeDetectorMode(sv);
363
+ semanticDetectors[cleanSlug] = mode;
364
+ explicitSlugsInLayer.set(cleanSlug, mode);
365
+ const mappedGa = SLUG_TO_ANTIGRAVITY_DETECTOR[cleanSlug];
366
+ if (mappedGa) {
367
+ detectors[mappedGa] = mode;
368
+ }
369
+ }
370
+ }
371
+
372
+ // Translate explicit `claudeDetectors` map if present
373
+ if (layer.claudeDetectors && typeof layer.claudeDetectors === 'object') {
374
+ for (const [ck, cv] of Object.entries(layer.claudeDetectors)) {
375
+ const mode = normalizeDetectorMode(cv);
376
+ const ccNum = parseNumericDetKey(ck);
377
+ if (ccNum && CLAUDE_CODE_DETECTOR_TRANSLATION[ccNum]) {
378
+ const entry = CLAUDE_CODE_DETECTOR_TRANSLATION[ccNum];
379
+ if (entry.slug) semanticDetectors[entry.slug] = mode;
380
+ for (const gaId of entry.gaIds) {
381
+ detectors[gaId] = mode;
382
+ }
383
+ } else {
384
+ const cleanSlug = String(ck || '').trim().toLowerCase().replace(/_/g, '-');
385
+ if (cleanSlug === 'subagent-ipi') {
386
+ semanticDetectors['subagent-ipi'] = mode;
387
+ } else {
388
+ const normGa = normalizeDetectorId(ck);
389
+ if (normGa) detectors[normGa] = mode;
390
+ }
391
+ }
392
+ }
393
+ }
394
+
395
+ if (layer.detectors && typeof layer.detectors === 'object') {
396
+ // Pass 1: collect semantic slug keys first so Ring-0 guard knows whether a slug confirmed the intent
397
+ for (const [k, v] of Object.entries(layer.detectors)) {
398
+ const cleanKey = String(k || '').trim();
399
+ const numericKey = parseNumericDetKey(cleanKey);
400
+ if (!numericKey) {
401
+ const slugKey = cleanKey.toLowerCase().replace(/_/g, '-');
402
+ const mode = normalizeDetectorMode(v);
403
+ explicitSlugsInLayer.set(slugKey, mode);
404
+ semanticDetectors[slugKey] = mode;
405
+ if (slugKey !== 'subagent-ipi' && Object.prototype.hasOwnProperty.call(SLUG_TO_ANTIGRAVITY_DETECTOR, slugKey)) {
406
+ detectors[SLUG_TO_ANTIGRAVITY_DETECTOR[slugKey]] = mode;
407
+ }
408
+ }
409
+ }
410
+
411
+ // Pass 2: process numeric DET-XX keys according to namespace & Ring-0 Inversion Guard
412
+ for (const [k, v] of Object.entries(layer.detectors)) {
413
+ const numericKey = parseNumericDetKey(k);
414
+ if (!numericKey) continue;
415
+ const mode = normalizeDetectorMode(v);
416
+
417
+ if (isClaudeNamespace) {
418
+ const entry = CLAUDE_CODE_DETECTOR_TRANSLATION[numericKey];
419
+ if (entry) {
420
+ if (entry.slug && !explicitSlugsInLayer.has(entry.slug)) {
421
+ semanticDetectors[entry.slug] = mode;
422
+ }
423
+ for (const gaId of entry.gaIds) {
424
+ const gaSlug = ANTIGRAVITY_DETECTOR_SLUGS[gaId];
425
+ if (!gaSlug || !explicitSlugsInLayer.has(gaSlug)) {
426
+ detectors[gaId] = mode;
427
+ }
428
+ }
429
+ }
430
+ continue;
431
+ }
432
+
433
+ // Ring-0 Inversion Guard on un-namespaced legacy disk configs
434
+ const gaSlug = ANTIGRAVITY_DETECTOR_SLUGS[numericKey];
435
+ const slugConfirmedOff = gaSlug && explicitSlugsInLayer.get(gaSlug) === 'off';
436
+ const isUnnamespacedLegacy = isDiskLayer && !isAntigravityNamespace && !rawNamespace;
437
+
438
+ if (
439
+ isUnnamespacedLegacy &&
440
+ mode === 'off' &&
441
+ RING0_SECURITY_DETECTORS.includes(numericKey) &&
442
+ !slugConfirmedOff
443
+ ) {
444
+ detectors[numericKey] = 'warn';
445
+ warnings.push(
446
+ `[Ring-0 Inversion Guard] Clamped un-namespaced "${numericKey}": "off" in ${sourceLabel} to "warn" to prevent cross-edition Ring-0 security disablement. Set "detectorNamespace": "antigravity" or "${gaSlug}": "off" to disable explicitly.`
447
+ );
448
+ } else if (!gaSlug || !explicitSlugsInLayer.has(gaSlug)) {
449
+ detectors[numericKey] = mode;
450
+ }
451
+ }
452
+ }
453
+
454
+ // Explicit `antigravityDetectors` map always applies directly with full authority
455
+ if (layer.antigravityDetectors && typeof layer.antigravityDetectors === 'object') {
456
+ for (const [ak, av] of Object.entries(layer.antigravityDetectors)) {
457
+ const normGa = normalizeDetectorId(ak);
458
+ if (normGa) {
459
+ const mode = normalizeDetectorMode(av);
460
+ detectors[normGa] = mode;
461
+ const gaSlug = ANTIGRAVITY_DETECTOR_SLUGS[normGa];
462
+ if (gaSlug) semanticDetectors[gaSlug] = mode;
463
+ }
464
+ }
465
+ }
466
+
467
+ if (layer.thresholds && typeof layer.thresholds === 'object') {
468
+ for (const [tk, tv] of Object.entries(layer.thresholds)) {
469
+ if (tk in thresholds && (typeof tv === 'number' || typeof tv === 'boolean')) {
470
+ thresholds[tk] = tv;
471
+ }
472
+ }
473
+ }
474
+ };
475
+
476
+ mergeLayer(globalRaw, { isDiskLayer: true, sourceLabel: globalConfigPath });
477
+ mergeLayer(projectRaw, { isDiskLayer: true, sourceLabel: projectConfigPath });
478
+ if (options.overrides && typeof options.overrides === 'object') {
479
+ mergeLayer(options.overrides, { isDiskLayer: Boolean(options.treatOverridesAsDisk), sourceLabel: 'overrides' });
480
+ }
481
+
482
+ return {
483
+ schemaVersion: '1.0.0',
484
+ detectorNamespace,
485
+ flightMode,
486
+ detectors,
487
+ semanticDetectors,
488
+ thresholds,
489
+ warnings,
490
+ sources: {
491
+ globalLoaded: Boolean(globalRaw),
492
+ projectLoaded: Boolean(projectRaw),
493
+ projectConfigPath,
494
+ globalConfigPath
495
+ }
496
+ };
497
+ }
498
+
499
+ export function setDetectorOverride(detectorId, mode, options = {}) {
500
+ const rawSlug = String(detectorId || '').trim().toLowerCase().replace(/_/g, '-');
501
+ const normMode = normalizeDetectorMode(mode);
502
+ const { activeWritePath } = resolveHorizonConfigPaths(options);
503
+
504
+ if (rawSlug === 'subagent-ipi' || (HABIT_SEMANTIC_SLUGS.includes(rawSlug) && rawSlug !== 'vague-prompt-rubric')) {
505
+ const existing = readJsonSafe(activeWritePath, {}) || {};
506
+ const nextDetectors = { ...(existing.detectors || {}) };
507
+ const nextSemantic = { ...(existing.semanticDetectors || {}) };
508
+ if (normMode === 'default') {
509
+ delete nextDetectors[rawSlug];
510
+ delete nextSemantic[rawSlug];
511
+ } else {
512
+ nextDetectors[rawSlug] = normMode;
513
+ nextSemantic[rawSlug] = normMode;
514
+ }
515
+ const nextPayload = {
516
+ schemaVersion: '1.0.0',
517
+ detectorNamespace: 'antigravity',
518
+ ...existing,
519
+ detectorNamespace: 'antigravity',
520
+ detectors: nextDetectors,
521
+ semanticDetectors: nextSemantic
522
+ };
523
+ const ok = writeJsonAtomic(activeWritePath, nextPayload);
524
+ return {
525
+ ok,
526
+ detectorId: rawSlug,
527
+ slug: rawSlug,
528
+ mode: normMode,
529
+ configPath: activeWritePath,
530
+ config: loadHorizonConfig(options)
531
+ };
532
+ }
533
+
534
+ const normId = normalizeDetectorId(detectorId);
535
+ if (!normId) {
536
+ return {
537
+ ok: false,
538
+ detectorId: null,
539
+ mode: normMode,
540
+ configPath: activeWritePath,
541
+ config: loadHorizonConfig(options)
542
+ };
543
+ }
544
+
545
+ const slug = ANTIGRAVITY_DETECTOR_SLUGS[normId] || null;
546
+ const existing = readJsonSafe(activeWritePath, {}) || {};
547
+ const nextDetectors = { ...(existing.detectors || {}) };
548
+ const nextAntigravityDetectors = { ...(existing.antigravityDetectors || {}) };
549
+
550
+ if (normMode === 'default') {
551
+ delete nextDetectors[normId];
552
+ if (slug) delete nextDetectors[slug];
553
+ delete nextAntigravityDetectors[normId];
554
+ } else {
555
+ nextDetectors[normId] = normMode;
556
+ if (slug) nextDetectors[slug] = normMode;
557
+ nextAntigravityDetectors[normId] = normMode;
558
+ }
559
+
560
+ const nextPayload = {
561
+ schemaVersion: '1.0.0',
562
+ ...existing,
563
+ detectorNamespace: 'antigravity',
564
+ detectors: nextDetectors,
565
+ antigravityDetectors: nextAntigravityDetectors
566
+ };
567
+
568
+ const ok = writeJsonAtomic(activeWritePath, nextPayload);
569
+ return {
570
+ ok,
571
+ detectorId: normId,
572
+ slug,
573
+ mode: normMode,
574
+ configPath: activeWritePath,
575
+ config: loadHorizonConfig(options)
576
+ };
577
+ }
578
+
579
+ /**
580
+ * Maps a detector trigger or runtime telemetry state to concrete native slash-command
581
+ * recovery prescriptions (`/rewind`, `/fork`, `/mcp`, `/context`, `/effort`, `/handoff` -> `/clear`).
582
+ * Strictly preserves Antigravity UI Invariant #1: `/compact` is always a plain-text instruction
583
+ * (`Type /compact in the chat box and press Enter`) and never a clickable copy button.
584
+ */
585
+ export function mapTriggerToNativeCommand(trigger = {}) {
586
+ const platform = String(trigger.platform || 'antigravity').toLowerCase();
587
+ const normId = normalizeDetectorId(trigger.detectorId);
588
+ const consecutiveFailures = Number(
589
+ trigger.consecutiveFailures ?? trigger.failureCount ?? (normId === 'DET-01' ? 3 : 0)
590
+ );
591
+ const contextUsedPct = Number(trigger.contextUsedPct ?? trigger.context_used_pct ?? 0);
592
+ const modifiedFiles = Array.isArray(trigger.modifiedFiles)
593
+ ? trigger.modifiedFiles.filter(Boolean)
594
+ : [];
595
+ const unresolvedTasks = Array.isArray(trigger.unresolvedTasks)
596
+ ? trigger.unresolvedTasks.filter(Boolean)
597
+ : [];
598
+
599
+ // 1. Poisoned Context Recovery (/rewind and /fork)
600
+ if (consecutiveFailures >= 3 || normId === 'DET-01' || normId === 'DET-02') {
601
+ return {
602
+ category: 'POISONED_CONTEXT_RECOVERY',
603
+ primaryCommand: '/rewind',
604
+ secondaryCommand: '/fork',
605
+ clickableCopyAllowed: true,
606
+ preservedFiles: modifiedFiles,
607
+ summary:
608
+ 'Run `/rewind` to step back before the consecutive failure chain, or `/fork` to test a risky fix in isolation.'
609
+ };
610
+ }
611
+
612
+ // 2. Standing Overhead Trim (/mcp, /context, /effort)
613
+ if (
614
+ normId === 'DET-10' ||
615
+ normId === 'DET-11' ||
616
+ Boolean(trigger.instructionsOverBudget) ||
617
+ Boolean(trigger.idleMcpBloat)
618
+ ) {
619
+ const isEffort = normId === 'DET-11' || Boolean(trigger.effortStepDown);
620
+ return {
621
+ category: 'STANDING_OVERHEAD_TRIM',
622
+ primaryCommand: isEffort ? '/effort' : '/mcp',
623
+ secondaryCommand: isEffort ? '/mcp' : '/context',
624
+ clickableCopyAllowed: true,
625
+ preservedFiles: modifiedFiles,
626
+ summary: isEffort
627
+ ? 'Run `/effort` to step down reasoning cost on routine turns.'
628
+ : 'Run `/mcp` and `/context` to prune idle MCP tool manifests, or `/effort` to step down reasoning cost.'
629
+ };
630
+ }
631
+
632
+ // 3. Clean Session Baton (/handoff -> /clear)
633
+ if (Boolean(trigger.milestoneComplete) || Boolean(trigger.cacheEfficiencyDropped)) {
634
+ return {
635
+ category: 'CLEAN_SESSION_BATON',
636
+ primaryCommand: '/handoff',
637
+ secondaryCommand: '/clear',
638
+ sequence: '/handoff -> /clear',
639
+ clickableCopyAllowed: true,
640
+ preservedFiles: modifiedFiles,
641
+ summary: 'Run `/handoff` to write task.md / HANDOFF.md, followed immediately by `/clear`.'
642
+ };
643
+ }
644
+
645
+ // 4. Scoped Context Compaction (/compact) — Plain-text invariant enforced on Antigravity
646
+ const warnThreshold = Number(trigger.horizonWarningThresholdPct || 70);
647
+ if (contextUsedPct >= warnThreshold || normId === 'DET-09') {
648
+ const fileScope =
649
+ modifiedFiles.length > 0 ? modifiedFiles.join(', ') : 'active modified files';
650
+ const taskScope =
651
+ unresolvedTasks.length > 0 ? `; unresolved tasks: ${unresolvedTasks.join('; ')}` : '';
652
+ const isAntigravity = platform === 'antigravity';
653
+ return {
654
+ category: 'SCOPED_CONTEXT_COMPACTION',
655
+ primaryCommand: isAntigravity
656
+ ? 'Type /compact in the chat box and press Enter'
657
+ : `/compact Preserve modified files (${fileScope})${taskScope} and active architectural invariants.`,
658
+ secondaryCommand: '/handoff',
659
+ plainTextInstruction: 'Type /compact in the chat box and press Enter',
660
+ clickableCopyAllowed: !isAntigravity,
661
+ preservedFiles: modifiedFiles,
662
+ reclaimScope: `Preserve ${fileScope}${taskScope}`,
663
+ summary: `Type /compact in the chat box and press Enter (preserving ${fileScope}${taskScope}).`
664
+ };
665
+ }
666
+
667
+ return null;
668
+ }
669
+
670
+ /**
671
+ * Applies `.attention-horizon.json` detector overrides (`off` | `warn` | `block`)
672
+ * to an array of Antigravity detector findings (`evaluateDetectorsOnSteps`).
673
+ */
674
+ export function filterFindingsByHorizonConfig(findings = [], config = null) {
675
+ if (!Array.isArray(findings)) return findings;
676
+ const result = [];
677
+ for (const f of findings) {
678
+ const normId = normalizeDetectorId(f?.detectorId);
679
+ const mode = normId && config ? resolveDetectorOverride(config, normId) : 'default';
680
+ if (mode === 'off') {
681
+ continue;
682
+ }
683
+ const prescription =
684
+ f.prescription || mapTriggerToNativeCommand({ detectorId: normId }) || null;
685
+ const baseFinding = prescription ? { ...f, prescription } : f;
686
+ if (mode === 'warn') {
687
+ result.push({
688
+ ...baseFinding,
689
+ severity: 'WARN',
690
+ haltsGeneration: false,
691
+ overriddenByConfig: 'warn'
692
+ });
693
+ } else if (mode === 'block') {
694
+ result.push({
695
+ ...baseFinding,
696
+ severity: 'CRITICAL',
697
+ haltsGeneration: true,
698
+ overriddenByConfig: 'block'
699
+ });
700
+ } else {
701
+ result.push(baseFinding);
702
+ }
703
+ }
704
+ return result;
705
+ }
706
+
707
+ export function redactUserPaths(text, homeDir = os.homedir()) {
708
+ const raw = String(text || '');
709
+ if (!homeDir) return raw;
710
+ const escapedWin = homeDir.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
711
+ const posixHome = homeDir.replace(/\\/g, '/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
712
+ return raw
713
+ .replace(new RegExp(escapedWin, 'gi'), '~')
714
+ .replace(new RegExp(posixHome, 'gi'), '~');
715
+ }
716
+
717
+ export function resolveGitHeadMetadata(cwd = process.cwd()) {
718
+ try {
719
+ const gitDir = path.join(cwd, '.git');
720
+ const headPath = path.join(gitDir, 'HEAD');
721
+ if (!fs.existsSync(headPath)) {
722
+ return { branch: 'untracked', shortCommit: 'none', isGitRepo: false };
723
+ }
724
+ const headRaw = fs.readFileSync(headPath, 'utf8').trim();
725
+ if (headRaw.startsWith('ref:')) {
726
+ const refRel = headRaw.replace(/^ref:\s*/, '').trim();
727
+ const branch = refRel.replace(/^refs\/heads\//, '');
728
+ const refFullPath = path.join(gitDir, ...refRel.split('/'));
729
+ if (fs.existsSync(refFullPath)) {
730
+ const sha = fs.readFileSync(refFullPath, 'utf8').trim();
731
+ return { branch, shortCommit: sha.slice(0, 7) || 'HEAD', isGitRepo: true };
732
+ }
733
+ return { branch, shortCommit: 'HEAD', isGitRepo: true };
734
+ }
735
+ return { branch: 'detached', shortCommit: headRaw.slice(0, 7) || 'HEAD', isGitRepo: true };
736
+ } catch {
737
+ return { branch: 'unknown', shortCommit: 'none', isGitRepo: false };
738
+ }
739
+ }
740
+
741
+ export function generateAntigravityDiagnosticMarkdown(results = [], options = {}) {
742
+ const cwd = options.workspacePath || options.cwd || process.cwd();
743
+ const homeDir = options.homeDir || os.homedir();
744
+ const config = loadHorizonConfig({ ...options, cwd, homeDir });
745
+ const git = resolveGitHeadMetadata(cwd);
746
+ const activeOverrides = Object.entries(config.detectors || {})
747
+ .filter(([, m]) => m !== 'default')
748
+ .map(([id, m]) => `${id}=${m}`);
749
+
750
+ const sanitized = results.map((r) => ({
751
+ title: r.title,
752
+ status: r.status,
753
+ detail: redactUserPaths(r.detail, homeDir)
754
+ }));
755
+
756
+ const mdLines = [
757
+ '### Highbeam (Antigravity Edition) — Zero-PII Diagnostic Report',
758
+ '',
759
+ '| Field | Value |',
760
+ '| :--- | :--- |',
761
+ `| **Package** | \`attention-horizon-antigravity@3.4.0\` |`,
762
+ `| **OS / Arch** | \`${process.platform} (${process.arch})\` |`,
763
+ `| **Node.js** | \`${process.version}\` |`,
764
+ `| **Git Context** | \`${git.branch}@${git.shortCommit}\` |`,
765
+ `| **Flight Mode** | \`${config.flightMode}\` |`,
766
+ `| **Detector Overrides** | \`${activeOverrides.length ? activeOverrides.join(', ') : 'none (all 20 default)'}\` |`,
767
+ '',
768
+ '#### Doctor Check Matrix',
769
+ ...sanitized.map(
770
+ (r) => `- [${r.status === 'PASS' ? 'x' : ' '}] **\`${r.title}\`** (\`${r.status}\`): ${r.detail}`
771
+ )
772
+ ];
773
+
774
+ return {
775
+ ok: !sanitized.some((r) => r.status === 'FAIL'),
776
+ git,
777
+ config,
778
+ checks: sanitized,
779
+ markdown: mdLines.join('\n')
780
+ };
781
+ }
782
+
783
+ export default {
784
+ CANONICAL_DETECTOR_IDS,
785
+ EXTENDED_DETECTOR_IDS,
786
+ RING0_SECURITY_DETECTORS,
787
+ ANTIGRAVITY_DETECTOR_SLUGS,
788
+ SLUG_TO_ANTIGRAVITY_DETECTOR,
789
+ CLAUDE_CODE_DETECTOR_TRANSLATION,
790
+ DEFAULT_HORIZON_CONFIG,
791
+ normalizeDetectorId,
792
+ normalizeDetectorMode,
793
+ resolveDetectorOverride,
794
+ resolveHorizonConfigPaths,
795
+ loadHorizonConfig,
796
+ setDetectorOverride,
797
+ mapTriggerToNativeCommand,
798
+ filterFindingsByHorizonConfig,
799
+ redactUserPaths,
800
+ resolveGitHeadMetadata,
801
+ generateAntigravityDiagnosticMarkdown
802
+ };