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,253 @@
1
+ /**
2
+ * @file src/diagnostics/bugReportGenerator.mjs
3
+ * Zero-PII GitHub Issue Diagnostic Bundle (`IDEA-02` — `doctor --diagnostic`)
4
+ * and Git-Commit / Session Efficiency Receipt Exporter (`IDEA-04` — `receipt --markdown`).
5
+ *
6
+ * Uses pure `fs` inspection (`.git/HEAD`) with zero subprocess or network calls.
7
+ */
8
+
9
+ import { fs, path, os } from '../utils/nodeIo.mjs';
10
+ import { loadHorizonConfig } from '../core-isomorphic/config/horizonConfig.mjs';
11
+ import { getSavedQuotaReceiptSummary } from '../core-isomorphic/coach/savedQuotaLedger.mjs';
12
+ import { loadRepoCalibration, getTopChronicReadFiles } from '../core-isomorphic/coach/repoCalibration.mjs';
13
+ import { inspectHookDiagnostics } from './doctorEngine.mjs';
14
+
15
+ /**
16
+ * Redacts the user's OS home directory and username from any diagnostic string.
17
+ * @param {string} text
18
+ * @param {string} [homeDir]
19
+ * @returns {string}
20
+ */
21
+ export function redactUserPaths(text, homeDir) {
22
+ const raw = String(text || '');
23
+ const home = homeDir || os?.homedir?.() || '';
24
+ if (!home) return raw;
25
+ const escapedWin = home.replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
26
+ const posixHome = home.replace(/\\/g, '/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
27
+ return raw
28
+ .replace(new RegExp(escapedWin, 'gi'), '~')
29
+ .replace(new RegExp(posixHome, 'gi'), '~');
30
+ }
31
+
32
+ /**
33
+ * Resolves the current Git branch and short HEAD commit hash via pure read-only `.git/HEAD` inspection.
34
+ * Never spawns a child process.
35
+ *
36
+ * @param {string} [cwd='.']
37
+ * @returns {{ branch: string, shortCommit: string, isGitRepo: boolean }}
38
+ */
39
+ export function resolveGitHeadMetadata(cwd = '.') {
40
+ if (!fs || !path) {
41
+ return { branch: 'detached', shortCommit: 'none', isGitRepo: false };
42
+ }
43
+ try {
44
+ const gitDir = path.join(cwd, '.git');
45
+ const headPath = path.join(gitDir, 'HEAD');
46
+ if (!fs.existsSync(headPath)) {
47
+ return { branch: 'untracked', shortCommit: 'none', isGitRepo: false };
48
+ }
49
+ const headRaw = fs.readFileSync(headPath, 'utf-8').trim();
50
+ if (headRaw.startsWith('ref:')) {
51
+ const refRel = headRaw.replace(/^ref:\s*/, '').trim();
52
+ const branch = refRel.replace(/^refs\/heads\//, '');
53
+ const refFullPath = path.join(gitDir, ...refRel.split('/'));
54
+ if (fs.existsSync(refFullPath)) {
55
+ const sha = fs.readFileSync(refFullPath, 'utf-8').trim();
56
+ return {
57
+ branch,
58
+ shortCommit: sha.slice(0, 7) || 'HEAD',
59
+ isGitRepo: true
60
+ };
61
+ }
62
+ return { branch, shortCommit: 'HEAD', isGitRepo: true };
63
+ }
64
+ return {
65
+ branch: 'detached',
66
+ shortCommit: headRaw.slice(0, 7) || 'HEAD',
67
+ isGitRepo: true
68
+ };
69
+ } catch (_err) {
70
+ return { branch: 'unknown', shortCommit: 'none', isGitRepo: false };
71
+ }
72
+ }
73
+
74
+ /**
75
+ * Generates a 100% Zero-PII Markdown diagnostic bundle for GitHub issue reporting (`ah-claude doctor --diagnostic`).
76
+ *
77
+ * @param {object} doctorResult - Result from `runDoctorDiagnostics`
78
+ * @param {object} [options={}]
79
+ * @returns {{
80
+ * ok: boolean,
81
+ * environment: object,
82
+ * configSummary: object,
83
+ * checks: Array<object>,
84
+ * markdown: string
85
+ * }}
86
+ */
87
+ export function generateZeroPiiDiagnosticBundle(doctorResult, options = {}) {
88
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
89
+ const homeDir = options.homeDir || os?.homedir?.() || '';
90
+ const config = loadHorizonConfig({ ...options, cwd, homeDir });
91
+ const calibration = loadRepoCalibration({ ...options, cwd });
92
+
93
+ const platform = globalThis.process?.platform || 'unknown';
94
+ const arch = globalThis.process?.arch || 'unknown';
95
+ const nodeVersion = doctorResult?.nodeVersion || globalThis.process?.versions?.node || 'unknown';
96
+ const latencyTier =
97
+ platform === 'win32'
98
+ ? 'Tier-1 V8 Mod (~0.05ms, <0.1ms) | Tier-2 Win11 PowerShell (~40-90ms Node ESM CLI spawn)'
99
+ : 'Tier-1 V8 Mod (~0.05ms, <0.1ms) | Tier-2 POSIX (~5ms minimal shell / ~15-35ms Node ESM CLI cold-start)';
100
+
101
+ const activeOverrides = Object.entries(config.detectors || {})
102
+ .filter(([, mode]) => mode !== 'default')
103
+ .map(([id, mode]) => `${id}=${mode}`);
104
+
105
+ const sanitizedChecks = (doctorResult?.checks || []).map((c) => ({
106
+ id: c.id,
107
+ ok: Boolean(c.ok),
108
+ detail: redactUserPaths(c.detail, homeDir)
109
+ }));
110
+
111
+ const rawHookDiag =
112
+ doctorResult?.hookDiagnostics || inspectHookDiagnostics({ ...options, cwd, homeDir });
113
+ const hookDiagnostics = {
114
+ diagnosticsPath: redactUserPaths(rawHookDiag.diagnosticsPath || '', homeDir),
115
+ recentErrorCount: Number(rawHookDiag.recentErrorCount || 0),
116
+ recentErrors: (rawHookDiag.recentErrors || []).slice(-5).map((entry) => ({
117
+ timestamp: String(entry.timestamp || ''),
118
+ source: String(entry.source || 'unknown'),
119
+ operation: String(entry.operation || 'unknown'),
120
+ name: String(entry.name || 'Error'),
121
+ message: redactUserPaths(entry.message || '', homeDir).slice(0, 300)
122
+ }))
123
+ };
124
+
125
+ const environment = {
126
+ edition: 'attention-horizon-claude',
127
+ version: '1.0.0',
128
+ platform,
129
+ arch,
130
+ nodeVersion: `v${nodeVersion}`,
131
+ latencyTier,
132
+ networkProfile: 'ZERO_SOCKET_100%_LOCAL'
133
+ };
134
+
135
+ const configSummary = {
136
+ flightMode: config.flightMode,
137
+ projectConfigLoaded: config.sources.projectLoaded,
138
+ globalConfigLoaded: config.sources.globalLoaded,
139
+ detectorOverrides: activeOverrides,
140
+ calibratedSessionsCompacted: calibration.compactions.count,
141
+ empiricalCacheHitRatio: calibration.cachePerformance.empiricalHitRatio,
142
+ recentHookErrorCount: hookDiagnostics.recentErrorCount
143
+ };
144
+
145
+ const recentErrorLines =
146
+ hookDiagnostics.recentErrors.length > 0
147
+ ? hookDiagnostics.recentErrors.map(
148
+ (e) =>
149
+ `- \`[${e.timestamp}]\` **\`${e.source}#${e.operation}\`** (\`${e.name}\`): ${e.message}`
150
+ )
151
+ : ['- *(0 recent runtime errors recorded)*'];
152
+
153
+ const mdLines = [
154
+ '### Highbeam — Zero-PII Diagnostic Report',
155
+ '',
156
+ '| Field | Value |',
157
+ '| :--- | :--- |',
158
+ `| **Package** | \`${environment.edition}@${environment.version}\` |`,
159
+ `| **OS / Arch** | \`${platform} (${arch})\` |`,
160
+ `| **Node.js** | \`${environment.nodeVersion}\` |`,
161
+ `| **Flight Mode** | \`${configSummary.flightMode}\` |`,
162
+ `| **Detector Overrides** | \`${activeOverrides.length > 0 ? activeOverrides.join(', ') : 'none (all 20 default)'}\` |`,
163
+ `| **Recent Hook Errors** | \`${hookDiagnostics.recentErrorCount}\` |`,
164
+ `| **Latency Profile** | ${latencyTier} |`,
165
+ `| **Doctor Contract Status** | **${doctorResult?.ok ? 'ALL PASS' : 'ISSUES DETECTED'}** (${sanitizedChecks.filter((c) => c.ok).length}/${sanitizedChecks.length}) |`,
166
+ '',
167
+ '#### Contract Self-Check Matrix',
168
+ ...sanitizedChecks.map(
169
+ (c) => `- [${c.ok ? 'x' : ' '}] **\`${c.id}\`**: ${c.detail}`
170
+ ),
171
+ '',
172
+ '#### Recent Runtime Diagnostics (`ah_diagnostics.jsonl`)',
173
+ ...recentErrorLines
174
+ ];
175
+
176
+ return {
177
+ ok: Boolean(doctorResult?.ok),
178
+ environment,
179
+ configSummary,
180
+ checks: sanitizedChecks,
181
+ hookDiagnostics,
182
+ markdown: mdLines.join('\n')
183
+ };
184
+ }
185
+
186
+ /**
187
+ * Generates a shareable Git-Commit & Session Efficiency Receipt (`ah-claude receipt --markdown` / `--json`).
188
+ *
189
+ * @param {object} [options={}]
190
+ * @returns {{
191
+ * git: { branch: string, shortCommit: string, isGitRepo: boolean },
192
+ * summary: object,
193
+ * chronicFiles: Array<object>,
194
+ * markdown: string
195
+ * }}
196
+ */
197
+ export function generateGitCommitEfficiencyReceipt(options = {}) {
198
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
199
+ const git = resolveGitHeadMetadata(cwd);
200
+ const summary = getSavedQuotaReceiptSummary(options);
201
+ const chronicFiles = getTopChronicReadFiles({ ...options, cwd, limit: 3 });
202
+ const calibration = loadRepoCalibration({ ...options, cwd });
203
+
204
+ const categoryRows = Object.entries(summary.byCategory || {});
205
+ const catTableLines =
206
+ categoryRows.length > 0
207
+ ? categoryRows.map(
208
+ ([cat, info]) =>
209
+ `| \`${cat}\` | ${info.count} | ${info.savedTokens.toLocaleString()} tok | \`$${info.savedUSD.toFixed(4)}\` |`
210
+ )
211
+ : ['| `NONE_YET` | 0 | 0 tok | `$0.0000` |'];
212
+
213
+ const mdLines = [
214
+ `### Highbeam — Session & Git Efficiency Receipt (\`${git.branch}@${git.shortCommit}\`)`,
215
+ '',
216
+ '| Metric | Verified Value |',
217
+ '| :--- | :--- |',
218
+ `| **Git Context** | \`${git.branch}\` (\`${git.shortCommit}\`) |`,
219
+ `| **Total Saved Tokens** | **${summary.totalSavedTokens.toLocaleString()} tok** |`,
220
+ `| **Total Verified Savings (USD)** | **\`$${summary.totalSavedUSD.toFixed(4)}\`** (${summary.entryCount} ledger events) |`,
221
+ `| **Empirical Cache-Hit Baseline** | \`${(calibration.cachePerformance.empiricalHitRatio * 100).toFixed(1)}%\` (${calibration.cachePerformance.warmHitTurns}/${calibration.cachePerformance.totalTurns} turns) |`,
222
+ '',
223
+ '#### Savings Breakdown by Ledger Category',
224
+ '| Category | Events | Saved Tokens | Verified USD |',
225
+ '| :--- | :---: | :---: | :---: |',
226
+ ...catTableLines
227
+ ];
228
+
229
+ if (chronicFiles.length > 0) {
230
+ mdLines.push(
231
+ '',
232
+ '#### Top Repo Context-Sink Hotspots (Calibrated)',
233
+ ...chronicFiles.map(
234
+ (f) =>
235
+ `- \`${f.fileKey}\`: read **${f.readCount}x** across ${f.sessionCount} session(s) (~${f.totalEstimatedTokens.toLocaleString()} tok)`
236
+ )
237
+ );
238
+ }
239
+
240
+ return {
241
+ git,
242
+ summary,
243
+ chronicFiles,
244
+ markdown: mdLines.join('\n')
245
+ };
246
+ }
247
+
248
+ export default {
249
+ redactUserPaths,
250
+ resolveGitHeadMetadata,
251
+ generateZeroPiiDiagnosticBundle,
252
+ generateGitCommitEfficiencyReceipt
253
+ };
@@ -0,0 +1,396 @@
1
+ /**
2
+ * @file src/diagnostics/claudeHookCapabilities.mjs
3
+ * Startup feature-check for undocumented Claude Code hook contracts (`PreModelSwitch`,
4
+ * `permissionBehavior === "ask"`, payload keys `from_model`/`to_model`/`prompt_cache_warm`,
5
+ * and absence of `PreEffortChange`).
6
+ *
7
+ * Scans the installed Claude Code binary/bundle in bounded 4 MB chunks with 256-byte overlap,
8
+ * caches results by `(binaryPath, size, mtimeMs)` under `.attention-horizon/cache/ah_claude_capabilities.json`,
9
+ * and logs a non-fatal runtime diagnostic if the installed binary drops the hook contract.
10
+ */
11
+
12
+ import { execFileSync } from 'node:child_process';
13
+ import {
14
+ fs,
15
+ path,
16
+ os,
17
+ readJsonSafe,
18
+ writeJsonAtomic
19
+ } from '../utils/nodeIo.mjs';
20
+ import { recordRuntimeDiagnostic } from '../core-isomorphic/utils/runtime.mjs';
21
+
22
+ const CHUNK_BYTES = 4 * 1024 * 1024;
23
+ const OVERLAP_BYTES = 256;
24
+
25
+ const CAPABILITY_MARKERS = Object.freeze({
26
+ preModelSwitchSupported: 'PreModelSwitch',
27
+ postModelSwitchSupported: 'PostModelSwitch',
28
+ preEffortChangeSupported: 'PreEffortChange',
29
+ hasFromModelKey: 'from_model',
30
+ hasToModelKey: 'to_model',
31
+ hasPromptCacheWarmKey: 'prompt_cache_warm',
32
+ hasContextTokensKey: 'context_tokens',
33
+ hasAskBehavior: 'permissionBehavior==="ask"',
34
+ hasAskDialog: 'A PreModelSwitch hook asked',
35
+ sdkSetModelHooked: 'blocked_by_hook'
36
+ });
37
+
38
+ /**
39
+ * Resolves the underlying JS bundle or native binary when given a Windows `.cmd` / POSIX wrapper.
40
+ * @param {string} candidatePath
41
+ * @returns {string}
42
+ */
43
+ function unwrapClaudeShim(candidatePath) {
44
+ if (!candidatePath || !fs.existsSync(candidatePath)) return candidatePath;
45
+ const ext = path.extname(candidatePath).toLowerCase();
46
+ const dir = path.dirname(candidatePath);
47
+
48
+ if (ext === '.cmd' || ext === '.bat') {
49
+ const pkgBase = path.join(dir, 'node_modules', '@anthropic-ai', 'claude-code');
50
+ const exeInPkg = path.join(pkgBase, 'bin', 'claude.exe');
51
+ const jsInPkg = path.join(pkgBase, 'cli.js');
52
+ if (fs.existsSync(exeInPkg)) return exeInPkg;
53
+ if (fs.existsSync(jsInPkg)) return jsInPkg;
54
+ }
55
+
56
+ return candidatePath;
57
+ }
58
+
59
+ /**
60
+ * Resolves the active `claude` binary/bundle path from options, `CLAUDE_BIN`, or `PATH`.
61
+ * @param {object} [options={}]
62
+ * @returns {string | null}
63
+ */
64
+ export function resolveClaudeBinaryPath(options = {}) {
65
+ const candidates = [];
66
+ if (typeof options.claudeBinPath === 'string' && options.claudeBinPath.trim()) {
67
+ candidates.push(options.claudeBinPath.trim());
68
+ }
69
+ const envBin = globalThis.process?.env?.CLAUDE_BIN;
70
+ if (typeof envBin === 'string' && envBin.trim()) {
71
+ candidates.push(envBin.trim());
72
+ }
73
+
74
+ if (candidates.length === 0) {
75
+ const pathEnv = String(globalThis.process?.env?.PATH || '');
76
+ const sep = globalThis.process?.platform === 'win32' ? ';' : ':';
77
+ const names =
78
+ globalThis.process?.platform === 'win32'
79
+ ? ['claude.exe', 'claude.cmd', 'claude']
80
+ : ['claude'];
81
+ for (const dir of pathEnv.split(sep).filter(Boolean)) {
82
+ for (const name of names) {
83
+ candidates.push(path.join(dir, name));
84
+ }
85
+ }
86
+
87
+ // Standard local CLI & benchmark runtime locations (no hardcoded usernames)
88
+ const homeDir = options.homeDir || os.homedir();
89
+ const tmpDir = os.tmpdir();
90
+ if (homeDir) {
91
+ for (const name of names) {
92
+ candidates.push(path.join(homeDir, '.local', 'bin', name));
93
+ candidates.push(path.join(homeDir, '.claude', 'local', name));
94
+ candidates.push(
95
+ path.join(homeDir, '.claude', 'local', 'node_modules', '@anthropic-ai', 'claude-code', 'bin', name)
96
+ );
97
+ }
98
+ }
99
+ try {
100
+ if (tmpDir && fs.existsSync(tmpDir)) {
101
+ for (const ent of fs.readdirSync(tmpDir)) {
102
+ if (ent.includes('model-switch-runtime')) {
103
+ for (const name of names) {
104
+ candidates.push(
105
+ path.join(tmpDir, ent, 'cli', 'node_modules', '@anthropic-ai', 'claude-code', 'bin', name)
106
+ );
107
+ }
108
+ }
109
+ }
110
+ }
111
+ } catch {
112
+ // Ignore temp directory scan errors
113
+ }
114
+ }
115
+
116
+ for (const raw of candidates) {
117
+ try {
118
+ const unwrapped = unwrapClaudeShim(raw);
119
+ if (unwrapped && fs.existsSync(unwrapped)) {
120
+ const st = fs.statSync(unwrapped);
121
+ if (st.isFile()) return unwrapped;
122
+ }
123
+ } catch {
124
+ // Skip inaccessible candidate
125
+ }
126
+ }
127
+ return null;
128
+ }
129
+
130
+ /**
131
+ * Reads sibling `@anthropic-ai/claude-code/package.json` (fast, zero subprocess) or optionally
132
+ * queries `claude --version` when `options.probeVersion === true`.
133
+ *
134
+ * @param {string} binPath
135
+ * @param {object} [options={}]
136
+ * @returns {string | null}
137
+ */
138
+ function detectClaudeVersion(binPath, options = {}) {
139
+ const pkgCandidates = [
140
+ path.join(path.dirname(binPath), 'package.json'),
141
+ path.join(path.dirname(binPath), '..', 'package.json')
142
+ ];
143
+ for (const pkgPath of pkgCandidates) {
144
+ const parsed = readJsonSafe(pkgPath, null, options);
145
+ if (parsed && parsed.name === '@anthropic-ai/claude-code' && typeof parsed.version === 'string') {
146
+ return parsed.version;
147
+ }
148
+ }
149
+
150
+ if (options.probeVersion === true) {
151
+ try {
152
+ const out = execFileSync(binPath, ['--version'], {
153
+ encoding: 'utf8',
154
+ timeout: 3000,
155
+ stdio: ['ignore', 'pipe', 'ignore']
156
+ }).trim();
157
+ const match = out.match(/(\d+\.\d+\.\d+(?:[-+][^\s]+)?)/);
158
+ if (match) return match[1];
159
+ } catch {
160
+ // Ignore version subprocess failure
161
+ }
162
+ }
163
+ return null;
164
+ }
165
+
166
+ /**
167
+ * Streams a file in bounded 4 MB overlapping chunks to test exact ASCII substring markers
168
+ * without loading large standalone binaries wholly into V8 heap memory.
169
+ *
170
+ * @param {string} binPath
171
+ * @returns {Record<string, boolean>}
172
+ */
173
+ function scanBinaryMarkersChunked(binPath) {
174
+ const foundFlags = Object.fromEntries(Object.keys(CAPABILITY_MARKERS).map((k) => [k, false]));
175
+ const markerEntries = Object.entries(CAPABILITY_MARKERS);
176
+ const buf = Buffer.allocUnsafe(CHUNK_BYTES);
177
+ const fd = fs.openSync(binPath, 'r');
178
+ try {
179
+ let tail = '';
180
+ let bytesRead;
181
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_BYTES, null)) > 0) {
182
+ const chunkStr = tail + buf.subarray(0, bytesRead).toString('latin1');
183
+ let allFound = true;
184
+ for (const [key, marker] of markerEntries) {
185
+ if (!foundFlags[key]) {
186
+ if (chunkStr.includes(marker)) {
187
+ foundFlags[key] = true;
188
+ } else {
189
+ allFound = false;
190
+ }
191
+ }
192
+ }
193
+ if (allFound) break;
194
+ tail = chunkStr.slice(Math.max(0, chunkStr.length - OVERLAP_BYTES));
195
+ }
196
+ } finally {
197
+ fs.closeSync(fd);
198
+ }
199
+ return foundFlags;
200
+ }
201
+
202
+ /**
203
+ * Inspects the installed Claude Code CLI/bundle for `PreModelSwitch` support and contract parity.
204
+ *
205
+ * @param {object} [options={}]
206
+ * @returns {{
207
+ * found: boolean,
208
+ * binaryPath: string | null,
209
+ * claudeVersion: string | null,
210
+ * preModelSwitchSupported: boolean | null,
211
+ * postModelSwitchSupported: boolean | null,
212
+ * preEffortChangeSupported: boolean | null,
213
+ * supportsAskDecision: boolean | null,
214
+ * sdkSetModelHooked: boolean | null,
215
+ * payloadKeys: { from_model: boolean, to_model: boolean, prompt_cache_warm: boolean, context_tokens: boolean } | null,
216
+ * contractValid: boolean | null,
217
+ * cached: boolean,
218
+ * warning: string | null
219
+ * }}
220
+ */
221
+ export function inspectClaudeBinaryCapabilities(options = {}) {
222
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
223
+ const binPath = resolveClaudeBinaryPath(options);
224
+ if (!binPath) {
225
+ return {
226
+ found: false,
227
+ binaryPath: null,
228
+ claudeVersion: null,
229
+ preModelSwitchSupported: null,
230
+ postModelSwitchSupported: null,
231
+ preEffortChangeSupported: null,
232
+ supportsAskDecision: null,
233
+ sdkSetModelHooked: null,
234
+ payloadKeys: null,
235
+ contractValid: null,
236
+ cached: false,
237
+ warning: null
238
+ };
239
+ }
240
+
241
+ let stat;
242
+ try {
243
+ stat = fs.statSync(binPath);
244
+ } catch {
245
+ return {
246
+ found: false,
247
+ binaryPath: null,
248
+ claudeVersion: null,
249
+ preModelSwitchSupported: null,
250
+ postModelSwitchSupported: null,
251
+ preEffortChangeSupported: null,
252
+ supportsAskDecision: null,
253
+ sdkSetModelHooked: null,
254
+ payloadKeys: null,
255
+ contractValid: null,
256
+ cached: false,
257
+ warning: null
258
+ };
259
+ }
260
+
261
+ const cacheBaseDir = options.homeDir || cwd;
262
+ const cachePath =
263
+ options.cachePath ||
264
+ path.join(cacheBaseDir, '.attention-horizon', 'cache', 'ah_claude_capabilities.json');
265
+ if (!options.bypassCache) {
266
+ const cached = readJsonSafe(cachePath, null, options);
267
+ if (
268
+ cached &&
269
+ cached.binaryPath === binPath &&
270
+ cached.size === stat.size &&
271
+ cached.mtimeMs === stat.mtimeMs &&
272
+ cached.result &&
273
+ typeof cached.result.contractValid === 'boolean'
274
+ ) {
275
+ return { ...cached.result, cached: true };
276
+ }
277
+ }
278
+
279
+ const markers = scanBinaryMarkersChunked(binPath);
280
+ const claudeVersion = options.claudeVersion || detectClaudeVersion(binPath, options);
281
+ const payloadKeys = {
282
+ from_model: markers.hasFromModelKey,
283
+ to_model: markers.hasToModelKey,
284
+ prompt_cache_warm: markers.hasPromptCacheWarmKey,
285
+ context_tokens: markers.hasContextTokensKey
286
+ };
287
+ const supportsAskDecision = Boolean(markers.hasAskBehavior || markers.hasAskDialog);
288
+ const contractValid = Boolean(
289
+ markers.preModelSwitchSupported &&
290
+ payloadKeys.from_model &&
291
+ payloadKeys.to_model &&
292
+ payloadKeys.prompt_cache_warm &&
293
+ supportsAskDecision
294
+ );
295
+
296
+ const warning = contractValid
297
+ ? null
298
+ : `[Highbeam Startup Check] Claude Code (${claudeVersion || 'unknown'}) does not expose the expected undocumented PreModelSwitch hook contract; DET-08 native /model interception is unavailable.`;
299
+
300
+ if (warning && options.recordDiagnostic !== false) {
301
+ recordRuntimeDiagnostic(
302
+ 'claudeHookCapabilities',
303
+ 'inspectClaudeBinaryCapabilities',
304
+ new Error(warning),
305
+ { ...options, cwd }
306
+ );
307
+ }
308
+
309
+ const result = {
310
+ found: true,
311
+ binaryPath: binPath,
312
+ claudeVersion,
313
+ preModelSwitchSupported: markers.preModelSwitchSupported,
314
+ postModelSwitchSupported: markers.postModelSwitchSupported,
315
+ preEffortChangeSupported: markers.preEffortChangeSupported,
316
+ supportsAskDecision,
317
+ sdkSetModelHooked: markers.sdkSetModelHooked,
318
+ payloadKeys,
319
+ contractValid,
320
+ cached: false,
321
+ warning
322
+ };
323
+
324
+ if (options.writeCache !== false && (options.cwd || options.cachePath)) {
325
+ writeJsonAtomic(
326
+ cachePath,
327
+ {
328
+ binaryPath: binPath,
329
+ size: stat.size,
330
+ mtimeMs: stat.mtimeMs,
331
+ result
332
+ },
333
+ options
334
+ );
335
+ }
336
+
337
+ return result;
338
+ }
339
+
340
+ /**
341
+ * Extracts all selectable model IDs and official aliases from an installed Claude Code binary
342
+ * in bounded 4 MB chunks (Item 1.3).
343
+ *
344
+ * @param {string} binPath
345
+ * @returns {{
346
+ * found: boolean,
347
+ * modelIds: string[],
348
+ * aliases: string[],
349
+ * allSelectable: string[]
350
+ * }}
351
+ */
352
+ export function extractClaudeSelectableModelsFromBinary(binPath) {
353
+ if (!binPath || !fs.existsSync(binPath)) {
354
+ return { found: false, modelIds: [], aliases: [], allSelectable: [] };
355
+ }
356
+ const modelIds = new Set();
357
+ const aliases = new Set();
358
+ const buf = Buffer.allocUnsafe(CHUNK_BYTES);
359
+ const overlap = 8192;
360
+ const fd = fs.openSync(binPath, 'r');
361
+ try {
362
+ let tail = '';
363
+ let bytesRead;
364
+ while ((bytesRead = fs.readSync(fd, buf, 0, CHUNK_BYTES, null)) > 0) {
365
+ const chunkStr = tail + buf.subarray(0, bytesRead).toString('latin1');
366
+ if (chunkStr.includes('family:') && chunkStr.includes('display_name:')) {
367
+ for (const m of chunkStr.matchAll(/\{id:"(claude-[a-z0-9-]+)",family:"(?:haiku|sonnet|opus|fable|mythos)"/g)) {
368
+ modelIds.add(m[1]);
369
+ }
370
+ }
371
+ const aliasArrMatch = chunkStr.match(/\[("sonnet","opus"[^\]]{0,240})\]/);
372
+ if (aliasArrMatch) {
373
+ for (const m of aliasArrMatch[1].matchAll(/"([a-z0-9[\]-]+)"/g)) {
374
+ aliases.add(m[1]);
375
+ }
376
+ }
377
+ tail = chunkStr.slice(Math.max(0, chunkStr.length - overlap));
378
+ }
379
+ } finally {
380
+ fs.closeSync(fd);
381
+ }
382
+ const sortedIds = Array.from(modelIds).sort();
383
+ const sortedAliases = Array.from(aliases).sort();
384
+ return {
385
+ found: true,
386
+ modelIds: sortedIds,
387
+ aliases: sortedAliases,
388
+ allSelectable: Array.from(new Set([...sortedIds, ...sortedAliases]))
389
+ };
390
+ }
391
+
392
+ export default {
393
+ resolveClaudeBinaryPath,
394
+ inspectClaudeBinaryCapabilities,
395
+ extractClaudeSelectableModelsFromBinary
396
+ };