ctxtop 0.0.0-stage → 4.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (240) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +149 -0
  4. package/LICENSE +27 -0
  5. package/README.md +330 -3
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +145 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1474 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +114 -0
  25. package/config/modelCatalog.json +620 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +262 -0
  28. package/hooks/handlers/hookIo.mjs +255 -0
  29. package/hooks/handlers/hookIpcClient.mjs +83 -0
  30. package/hooks/handlers/post-tool-use.mjs +265 -0
  31. package/hooks/handlers/pre-model-switch.mjs +249 -0
  32. package/hooks/handlers/pre-tool-use.mjs +365 -0
  33. package/hooks/handlers/stop-gate.mjs +240 -0
  34. package/hooks/handlers/user-prompt-submit.mjs +143 -0
  35. package/hooks/hooks.json +81 -0
  36. package/hooks/post_invocation.mjs +13 -0
  37. package/hooks/post_tool_use.mjs +17 -0
  38. package/hooks/pre_invocation.mjs +14 -0
  39. package/hooks/pre_tool_use.mjs +97 -0
  40. package/hooks/register.js +687 -0
  41. package/hooks/session_start.mjs +14 -0
  42. package/hooks/stop.mjs +13 -0
  43. package/hooks.json +56 -0
  44. package/package.json +103 -4
  45. package/packages/antigravity/package.json +14 -0
  46. package/packages/antigravity/src/index.mjs +1 -0
  47. package/packages/claude-code/package.json +14 -0
  48. package/packages/claude-code/src/index.mjs +2 -0
  49. package/packages/core/package.json +14 -0
  50. package/packages/core/src/index.mjs +1 -0
  51. package/packages/engine-node/package.json +14 -0
  52. package/packages/engine-node/src/index.mjs +1 -0
  53. package/packages/mcp/package.json +17 -0
  54. package/packages/mcp/src/server.mjs +396 -0
  55. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  56. package/packages/pro/README-SIGNING.md +30 -0
  57. package/packages/pro/package.json +16 -0
  58. package/packages/pro/src/index.mjs +3 -0
  59. package/packages/pro/src/team_finops_pack.mjs +241 -0
  60. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  61. package/plugin.json +36 -0
  62. package/rules/AGENTS.md +10 -0
  63. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  64. package/sidecars/horizon-daemon/server.mjs +2002 -0
  65. package/sidecars/horizon-daemon/sidecar.json +19 -0
  66. package/skills/cost-radar/SKILL.md +21 -0
  67. package/skills/evolve/SKILL.md +21 -0
  68. package/skills/handoff/SKILL.md +42 -0
  69. package/skills/horizon/SKILL.md +17 -0
  70. package/skills/inspect/SKILL.md +18 -0
  71. package/skills/precheck/SKILL.md +44 -0
  72. package/src/adapters/antigravity/index.mjs +79 -0
  73. package/src/adapters/claude-code/index.mjs +155 -0
  74. package/src/cli/cost_radar.mjs +70 -0
  75. package/src/cli/doctor.mjs +351 -0
  76. package/src/cli/horizon_hud.mjs +686 -0
  77. package/src/cli/init.mjs +425 -0
  78. package/src/cli/postmortem.mjs +515 -0
  79. package/src/coach/cacheGravityRouter.mjs +12 -0
  80. package/src/config/modelCatalog.json +620 -0
  81. package/src/config/platformQuirks.json +19 -0
  82. package/src/core/action_queue.mjs +264 -0
  83. package/src/core/ag_bridge.mjs +346 -0
  84. package/src/core/atomic_io.mjs +124 -0
  85. package/src/core/baseline.mjs +607 -0
  86. package/src/core/blindspot_sensors.mjs +399 -0
  87. package/src/core/classifier.mjs +1757 -0
  88. package/src/core/coach/circuit_breakers.mjs +650 -0
  89. package/src/core/coach/contradiction_auditor.mjs +239 -0
  90. package/src/core/coach/effort_advisor.mjs +143 -0
  91. package/src/core/coach/handoff_hydrator.mjs +483 -0
  92. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  93. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  94. package/src/core/coach/reflector_queue.mjs +505 -0
  95. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  96. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  97. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  98. package/src/core/coach/task_quota_router.mjs +955 -0
  99. package/src/core/coach/turn_zero_gate.mjs +574 -0
  100. package/src/core/compaction_coach.mjs +1126 -0
  101. package/src/core/config.mjs +214 -0
  102. package/src/core/constants.mjs +1800 -0
  103. package/src/core/detectors_det01_to_16.mjs +1474 -0
  104. package/src/core/episodic_memory.mjs +135 -0
  105. package/src/core/fts5_output_compressor.mjs +359 -0
  106. package/src/core/git_ledger.mjs +189 -0
  107. package/src/core/handoff_audit.mjs +558 -0
  108. package/src/core/history.mjs +221 -0
  109. package/src/core/hook_diagnostics.mjs +158 -0
  110. package/src/core/horizon_classifier.mjs +326 -0
  111. package/src/core/horizon_config.mjs +802 -0
  112. package/src/core/host_watchdog.mjs +200 -0
  113. package/src/core/layer5_hygiene.mjs +966 -0
  114. package/src/core/log_resolver.mjs +231 -0
  115. package/src/core/mcp_auditor.mjs +138 -0
  116. package/src/core/micro_skills_store.mjs +91 -0
  117. package/src/core/offenders.mjs +161 -0
  118. package/src/core/parser.mjs +1996 -0
  119. package/src/core/path_canonicalizer.mjs +73 -0
  120. package/src/core/paths.mjs +310 -0
  121. package/src/core/prefix_cache_shield.mjs +386 -0
  122. package/src/core/pro_license.mjs +385 -0
  123. package/src/core/prompt_rubric.mjs +518 -0
  124. package/src/core/pruner.mjs +433 -0
  125. package/src/core/quota.mjs +1860 -0
  126. package/src/core/rsi_instinct_engine.mjs +1197 -0
  127. package/src/core/sanitizer.mjs +121 -0
  128. package/src/core/session_forensics.mjs +303 -0
  129. package/src/core/session_timeline.mjs +358 -0
  130. package/src/core/settings.mjs +99 -0
  131. package/src/core/shared/detectors.mjs +1342 -0
  132. package/src/core/shared/fnv1a64.mjs +85 -0
  133. package/src/core/shared/handoff_schema.mjs +123 -0
  134. package/src/core/shared/index.mjs +5 -0
  135. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  136. package/src/core/shared/micro_skills.mjs +1 -0
  137. package/src/core/shared/plugin_validator.mjs +202 -0
  138. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  139. package/src/core/sidecar_store.mjs +302 -0
  140. package/src/core/sprint_metrics.mjs +366 -0
  141. package/src/core/sqlite_client.mjs +283 -0
  142. package/src/core/storage_doctor.mjs +358 -0
  143. package/src/core/subagents.mjs +609 -0
  144. package/src/core/swarm_topology.mjs +360 -0
  145. package/src/core/task_quota_router.mjs +1656 -0
  146. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  147. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  148. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  149. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  150. package/src/core/timeline_svg.mjs +236 -0
  151. package/src/core/tool_surgeon.mjs +305 -0
  152. package/src/core/trajectory_stitcher.mjs +645 -0
  153. package/src/core/u_shaped_optimizer.mjs +789 -0
  154. package/src/core/wal_hygiene.mjs +233 -0
  155. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  156. package/src/core-isomorphic/catalog/index.mjs +1 -0
  157. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
  158. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  159. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  160. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  161. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  162. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  163. package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
  164. package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
  165. package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
  166. package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
  167. package/src/core-isomorphic/control/callTree.mjs +338 -0
  168. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  169. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  170. package/src/core-isomorphic/control/index.mjs +49 -0
  171. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  172. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  173. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  174. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  175. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  176. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
  177. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  178. package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
  179. package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
  180. package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
  181. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  182. package/src/core-isomorphic/economics/index.mjs +47 -0
  183. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  184. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  185. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
  186. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
  187. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
  188. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
  189. package/src/core-isomorphic/index.js +26 -0
  190. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  191. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  192. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  193. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  194. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
  195. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  196. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  197. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  198. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
  199. package/src/core-isomorphic/ui/modViews.mjs +1478 -0
  200. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  201. package/src/core-isomorphic/ustf/index.mjs +7 -0
  202. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  203. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  204. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  205. package/src/demo/synthetic_states.mjs +661 -0
  206. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  207. package/src/diagnostics/doctorEngine.mjs +203 -0
  208. package/src/engine-node/db/index.mjs +58 -0
  209. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  210. package/src/engine-node/db/probe.mjs +110 -0
  211. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  212. package/src/engine-node/index.mjs +9 -0
  213. package/src/engine-node/ipc/client.mjs +447 -0
  214. package/src/engine-node/ipc/index.mjs +22 -0
  215. package/src/engine-node/ipc/protocol.mjs +177 -0
  216. package/src/engine-node/ipc/server.mjs +445 -0
  217. package/src/engine-node/offloader/index.mjs +6 -0
  218. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  219. package/src/engine-node/sensors/blindspots.mjs +369 -0
  220. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  221. package/src/engine-node/sensors/index.mjs +7 -0
  222. package/src/hooks/portfolio_runtime.mjs +858 -0
  223. package/src/hooks/post_invocation.mjs +419 -0
  224. package/src/hooks/pre_invocation.mjs +1015 -0
  225. package/src/hooks/session_start.mjs +161 -0
  226. package/src/shims/agy_cli_compressor.mjs +705 -0
  227. package/src/shims/agy_git_guard.mjs +749 -0
  228. package/src/shims/ah_log_query.mjs +39 -0
  229. package/src/ui/costRadarSvg.mjs +6 -0
  230. package/src/ui/horizonGrid.mjs +1 -0
  231. package/src/ui/horizonPanelHtml.mjs +1 -0
  232. package/src/ui/horizon_panel.css +167 -0
  233. package/src/ui/horizon_panel.js +212 -0
  234. package/src/ui/modViews.mjs +1 -0
  235. package/src/utils/nodeIo.mjs +59 -0
  236. package/src/utils/runtime.mjs +1 -0
  237. package/src/webview/advanced_view.html +1808 -0
  238. package/src/webview/horizon_panel.html +11389 -0
  239. package/src/webview/registry.mjs +80 -0
  240. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,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,203 @@
1
+ /**
2
+ * @file src/diagnostics/doctorEngine.mjs
3
+ * Contract Self-Check & Bounded Hook Runtime Diagnostics Engine (`ah-claude doctor` — `ISS-065`).
4
+ *
5
+ * Reads `<cwd>/.claude/cache/ah_diagnostics.jsonl` via `readRuntimeDiagnostics` and surfaces
6
+ * `hookDiagnostics` (`recentErrorCount` and up to the last 5 redacted `recentErrors`).
7
+ */
8
+
9
+ import {
10
+ fs,
11
+ path,
12
+ os,
13
+ fileURLToPath,
14
+ readJsonSafe,
15
+ getDiagnosticsFilePath,
16
+ readRuntimeDiagnostics
17
+ } from '../utils/nodeIo.mjs';
18
+ import { loadModelCatalog } from '../core-isomorphic/config/catalogLoader.mjs';
19
+ import { loadHorizonConfig } from '../core-isomorphic/config/horizonConfig.mjs';
20
+
21
+ /**
22
+ * Redacts the user's OS home directory from any diagnostic string.
23
+ *
24
+ * @param {string} text
25
+ * @param {string} [homeDir]
26
+ * @returns {string}
27
+ */
28
+ export function redactDoctorPaths(text, homeDir) {
29
+ const raw = String(text || '');
30
+ const home = homeDir || os?.homedir?.() || '';
31
+ if (!home) return raw;
32
+ const escapedWin = home.replace(/\//g, '\\').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
33
+ const posixHome = home.replace(/\\/g, '/').replace(/[.*+?^${}()|[\]\\]/g, '\\$&');
34
+ return raw
35
+ .replace(new RegExp(escapedWin, 'gi'), '~')
36
+ .replace(new RegExp(posixHome, 'gi'), '~');
37
+ }
38
+
39
+ /**
40
+ * Resolves the target `settings.json` path for `--project` or `--global`.
41
+ *
42
+ * @param {object} [options={}]
43
+ * @returns {string}
44
+ */
45
+ function resolveDoctorSettingsPath(options = {}) {
46
+ if (typeof options.settingsPath === 'string' && options.settingsPath.trim()) {
47
+ return options.settingsPath.trim();
48
+ }
49
+ const scope = options.scope === 'global' || options.global ? 'global' : 'project';
50
+ if (scope === 'global') {
51
+ const home = options.homeDir || os.homedir() || '.';
52
+ return path.join(home, '.claude', 'settings.json');
53
+ }
54
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
55
+ return path.join(cwd, '.claude', 'settings.json');
56
+ }
57
+
58
+ /**
59
+ * Reads `<cwd>/.claude/cache/ah_diagnostics.jsonl` and returns a zero-PII summary
60
+ * with total `recentErrorCount` and up to the newest 5 redacted `recentErrors` (`ISS-065`).
61
+ *
62
+ * @param {object} [options={}]
63
+ * @returns {{
64
+ * diagnosticsPath: string,
65
+ * recentErrorCount: number,
66
+ * recentErrors: Array<{ timestamp: string, source: string, operation: string, name: string, message: string }>
67
+ * }}
68
+ */
69
+ export function inspectHookDiagnostics(options = {}) {
70
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
71
+ const homeDir = options.homeDir || os?.homedir?.() || '';
72
+ const entries = readRuntimeDiagnostics({ ...options, cwd });
73
+ const recentErrors = entries.slice(-5).map((entry) => ({
74
+ timestamp: String(entry.timestamp || ''),
75
+ source: String(entry.source || 'unknown'),
76
+ operation: String(entry.operation || 'unknown'),
77
+ name: String(entry.name || 'Error'),
78
+ message: redactDoctorPaths(entry.message || '', homeDir).slice(0, 300)
79
+ }));
80
+
81
+ return {
82
+ diagnosticsPath: getDiagnosticsFilePath({ ...options, cwd }),
83
+ recentErrorCount: entries.length,
84
+ recentErrors
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Runs host contract & runtime diagnostic checks (`npx ah-claude doctor`).
90
+ *
91
+ * @param {object} [options={}]
92
+ * @returns {{
93
+ * ok: boolean,
94
+ * nodeVersion: string,
95
+ * checks: Array<{ id: string, ok: boolean, detail: string }>,
96
+ * hookDiagnostics: {
97
+ * diagnosticsPath: string,
98
+ * recentErrorCount: number,
99
+ * recentErrors: Array<{ timestamp: string, source: string, operation: string, name: string, message: string }>
100
+ * }
101
+ * }}
102
+ */
103
+ export function runDoctorDiagnostics(options = {}) {
104
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '.';
105
+ const nodeVersion = globalThis.process?.versions?.node || '0.0.0';
106
+ const major = Number(nodeVersion.split('.')[0] || 0);
107
+ const checks = [];
108
+
109
+ checks.push({
110
+ id: 'node_version',
111
+ ok: major >= 20,
112
+ detail: `Node.js v${nodeVersion} (requires >= 20.0.0)`
113
+ });
114
+
115
+ try {
116
+ const catalog = loadModelCatalog(options);
117
+ const modelCount = Object.keys(catalog.models || {}).length;
118
+ checks.push({
119
+ id: 'model_catalog',
120
+ ok: modelCount >= 6,
121
+ detail: `Loaded ${modelCount} Anthropic model rate cards (Haiku 5.5 100k cliff enabled)`
122
+ });
123
+ } catch (err) {
124
+ checks.push({
125
+ id: 'model_catalog',
126
+ ok: false,
127
+ detail: `Failed to load catalog: ${err?.message || String(err)}`
128
+ });
129
+ }
130
+
131
+ const pluginRoot = path.resolve(path.dirname(fileURLToPath(import.meta.url)), '..', '..');
132
+ const registerPath = path.join(pluginRoot, 'hooks', 'register.js');
133
+ const hooksJsonPath = path.join(pluginRoot, 'hooks', 'hooks.json');
134
+ const pluginJsonPath = path.join(pluginRoot, '.claude-plugin', 'plugin.json');
135
+
136
+ checks.push({
137
+ id: 'mod_entrypoint',
138
+ ok: Boolean(fs.existsSync(registerPath)),
139
+ detail: `hooks/register.js present at ${registerPath}`
140
+ });
141
+
142
+ const parsedHooksJson = readJsonSafe(hooksJsonPath, null);
143
+ const validHooksSchema = Boolean(
144
+ parsedHooksJson &&
145
+ typeof parsedHooksJson.hooks === 'object' &&
146
+ Array.isArray(parsedHooksJson.hooks.PreToolUse) &&
147
+ Array.isArray(parsedHooksJson.hooks.PreToolUse[0]?.hooks)
148
+ );
149
+ checks.push({
150
+ id: 'hooks_manifest',
151
+ ok: Boolean(fs.existsSync(hooksJsonPath) && validHooksSchema),
152
+ detail: `hooks/hooks.json valid (nested hooks schema)`
153
+ });
154
+
155
+ const parsedPluginJson = readJsonSafe(pluginJsonPath, null);
156
+ const validPluginSchema = Boolean(
157
+ parsedPluginJson &&
158
+ parsedPluginJson.entrypoint === undefined &&
159
+ Array.isArray(parsedPluginJson.commands) &&
160
+ parsedPluginJson.commands.every((c) => typeof c === 'string')
161
+ );
162
+ checks.push({
163
+ id: 'plugin_manifest',
164
+ ok: Boolean(fs.existsSync(pluginJsonPath) && validPluginSchema),
165
+ detail: `.claude-plugin/plugin.json valid`
166
+ });
167
+
168
+ const settingsPath = resolveDoctorSettingsPath({ ...options, cwd });
169
+ const settingsInstalled = Boolean(fs.existsSync(settingsPath));
170
+ checks.push({
171
+ id: 'settings_status',
172
+ ok: true,
173
+ detail: settingsInstalled
174
+ ? `settings.json present at ${settingsPath}`
175
+ : `settings.json not yet created at ${settingsPath} (run 'ah-claude install')`
176
+ });
177
+
178
+ const config = loadHorizonConfig({ ...options, cwd });
179
+ const customDetectors = Object.entries(config.detectors || {}).filter(
180
+ ([, mode]) => mode !== 'default'
181
+ ).length;
182
+ checks.push({
183
+ id: 'horizon_config',
184
+ ok: Boolean(config && config.detectors && Object.keys(config.detectors).length === 20),
185
+ detail: `20 detectors configured (FlightMode=${config.flightMode}, overrides=${customDetectors})`
186
+ });
187
+
188
+ const hookDiagnostics = inspectHookDiagnostics({ ...options, cwd });
189
+ const ok = checks.every((c) => c.ok);
190
+
191
+ return {
192
+ ok,
193
+ nodeVersion,
194
+ checks,
195
+ hookDiagnostics
196
+ };
197
+ }
198
+
199
+ export default {
200
+ redactDoctorPaths,
201
+ inspectHookDiagnostics,
202
+ runDoctorDiagnostics
203
+ };
@@ -0,0 +1,58 @@
1
+ /**
2
+ * @file src/engine-node/db/index.mjs
3
+ * Unified database client factory for Highbeam storage engines.
4
+ *
5
+ * Dynamically resolves to native read-only node:sqlite on Node >= 22.5,
6
+ * or pure-JS JsonlDatabaseFallbackWrapper on Node 20 LTS without warnings.
7
+ */
8
+
9
+ import { isNodeSqliteAvailable, getDatabaseSyncClass, suppressSqliteWarning } from './probe.mjs';
10
+ import { SqliteDatabaseSyncWrapper } from './sqlite_wrapper.mjs';
11
+ import { JsonlDatabaseFallbackWrapper } from './jsonl_fallback.mjs';
12
+
13
+ /**
14
+ * Returns a unified read-only database client.
15
+ *
16
+ * @param {object} options
17
+ * @param {string} options.dbPath - Path to database or session transcript
18
+ * @param {boolean} options.readOnly - Must strictly be true
19
+ * @param {boolean} [options.forceFallback=false] - Force JSONL fallback wrapper
20
+ * @returns {SqliteDatabaseSyncWrapper | JsonlDatabaseFallbackWrapper}
21
+ */
22
+ export function getDatabaseClient(options = {}) {
23
+ if (!options || typeof options !== 'object') {
24
+ throw new TypeError('getDatabaseClient requires an options object');
25
+ }
26
+ if (options.readOnly !== true) {
27
+ throw new Error('[Zero-Trust SQLite Guard] getDatabaseClient strictly requires { readOnly: true }');
28
+ }
29
+ if (!options.dbPath || typeof options.dbPath !== 'string') {
30
+ throw new TypeError('getDatabaseClient requires a non-empty dbPath string');
31
+ }
32
+
33
+ const { dbPath, forceFallback = false } = options;
34
+
35
+ if (!forceFallback && isNodeSqliteAvailable()) {
36
+ const DatabaseSync = getDatabaseSyncClass();
37
+ return new SqliteDatabaseSyncWrapper(dbPath, { ...options, DatabaseSync });
38
+ }
39
+
40
+ return new JsonlDatabaseFallbackWrapper(dbPath, options);
41
+ }
42
+
43
+ export {
44
+ isNodeSqliteAvailable,
45
+ getDatabaseSyncClass,
46
+ suppressSqliteWarning,
47
+ SqliteDatabaseSyncWrapper,
48
+ JsonlDatabaseFallbackWrapper
49
+ };
50
+
51
+ export default {
52
+ getDatabaseClient,
53
+ isNodeSqliteAvailable,
54
+ getDatabaseSyncClass,
55
+ suppressSqliteWarning,
56
+ SqliteDatabaseSyncWrapper,
57
+ JsonlDatabaseFallbackWrapper
58
+ };
@@ -0,0 +1,184 @@
1
+ /**
2
+ * @file src/engine-node/db/jsonl_fallback.mjs
3
+ * Pure-JS JSONL transcript reader and query emulator for Node 20 LTS environments.
4
+ *
5
+ * Provides equivalent get(), all(), and searchFts() interface for session transcripts,
6
+ * strictly enforcing the { readOnly: true } invariant and rejecting mutation queries.
7
+ */
8
+
9
+ import fs from 'node:fs';
10
+ import path from 'node:path';
11
+
12
+ const MUTATION_SQL_RE = /^\s*(INSERT|UPDATE|DELETE|DROP|ALTER|CREATE|REPLACE|ATTACH|DETACH|VACUUM|REINDEX)\b/i;
13
+
14
+ export class JsonlDatabaseFallbackWrapper {
15
+ /**
16
+ * @param {string} dbPath
17
+ * @param {object} options
18
+ * @param {boolean} options.readOnly - Must strictly be true
19
+ * @param {Array<object>} [options.records] - Direct pre-loaded records
20
+ */
21
+ constructor(dbPath, options = {}) {
22
+ if (!options || options.readOnly !== true) {
23
+ throw new Error('[Zero-Trust SQLite Guard] JsonlDatabaseFallbackWrapper strictly requires { readOnly: true }');
24
+ }
25
+ this.dbPath = dbPath;
26
+ this.readOnly = true;
27
+ this.isOpen = true;
28
+ this.records = [];
29
+ this._loadRecords(options);
30
+ }
31
+
32
+ _loadRecords(options = {}) {
33
+ if (options.records && Array.isArray(options.records)) {
34
+ this.records = [...options.records];
35
+ return;
36
+ }
37
+ if (!this.dbPath || typeof this.dbPath !== 'string') return;
38
+
39
+ try {
40
+ const targetPath = path.resolve(this.dbPath);
41
+ if (fs.existsSync(targetPath)) {
42
+ const stat = fs.statSync(targetPath);
43
+ if (stat.isFile() && targetPath.endsWith('.jsonl')) {
44
+ this._parseJsonlFile(targetPath);
45
+ return;
46
+ }
47
+
48
+ const sessionDir = stat.isDirectory() ? targetPath : path.dirname(targetPath);
49
+ const cand1 = path.join(sessionDir, '.system_generated', 'logs', 'transcript_full.jsonl');
50
+ if (fs.existsSync(cand1)) {
51
+ this._parseJsonlFile(cand1);
52
+ return;
53
+ }
54
+ const cand2 = path.join(sessionDir, '.system_generated', 'logs', 'transcript.jsonl');
55
+ if (fs.existsSync(cand2)) {
56
+ this._parseJsonlFile(cand2);
57
+ return;
58
+ }
59
+ const cand3 = path.join(sessionDir, 'transcript.jsonl');
60
+ if (fs.existsSync(cand3)) {
61
+ this._parseJsonlFile(cand3);
62
+ return;
63
+ }
64
+ }
65
+ } catch {
66
+ // Graceful fail-open on path lookup
67
+ }
68
+ }
69
+
70
+ _parseJsonlFile(filePath) {
71
+ try {
72
+ const content = fs.readFileSync(filePath, 'utf8');
73
+ const lines = content.split(/\r?\n/);
74
+ for (const line of lines) {
75
+ const trimmed = line.trim();
76
+ if (!trimmed) continue;
77
+ try {
78
+ const parsed = JSON.parse(trimmed);
79
+ if (parsed !== null && parsed !== undefined) this.records.push(parsed);
80
+ } catch {
81
+ // Ignore malformed individual JSONL line
82
+ }
83
+ }
84
+ } catch {
85
+ // File read error caught gracefully
86
+ }
87
+ }
88
+
89
+ _assertNotMutating(sql) {
90
+ if (MUTATION_SQL_RE.test(sql)) {
91
+ throw new Error(`[Zero-Trust SQLite Guard] Mutation query not permitted on read-only database: ${sql}`);
92
+ }
93
+ }
94
+
95
+ get(sql, params = []) {
96
+ const rows = this.all(sql, params);
97
+ return rows.length > 0 ? rows[0] : null;
98
+ }
99
+
100
+ all(sql, params = []) {
101
+ if (!this.isOpen) throw new Error('Database handle is closed');
102
+ this._assertNotMutating(sql);
103
+
104
+ // Handle SELECT COUNT(*)
105
+ if (/SELECT\s+COUNT\(\*\)\s+(?:AS\s+(\w+))?/i.test(sql)) {
106
+ const match = sql.match(/SELECT\s+COUNT\(\*\)\s+(?:AS\s+(\w+))?/i);
107
+ const alias = match ? match[1] || 'cnt' : 'cnt';
108
+ return [{ [alias]: this.records.length }];
109
+ }
110
+
111
+ let filtered = this.records;
112
+
113
+ // Handle WHERE column = ? or literal
114
+ const whereMatch = sql.match(/WHERE\s+([a-zA-Z0-9_]+)\s*=\s*(?:\?|'([^']*)'|(\d+))/i);
115
+ if (whereMatch) {
116
+ const col = whereMatch[1];
117
+ const expectedVal = whereMatch[2] !== undefined
118
+ ? whereMatch[2]
119
+ : whereMatch[3] !== undefined
120
+ ? Number(whereMatch[3])
121
+ : (Array.isArray(params) ? params[0] : params);
122
+
123
+ filtered = filtered.filter(r => r && (r[col] === expectedVal || String(r[col]) === String(expectedVal)));
124
+ }
125
+
126
+ // Handle LIMIT N
127
+ const limitMatch = sql.match(/LIMIT\s+(\d+)/i);
128
+ if (limitMatch) {
129
+ const lim = parseInt(limitMatch[1], 10);
130
+ filtered = filtered.slice(0, lim);
131
+ }
132
+
133
+ return filtered;
134
+ }
135
+
136
+ searchFts(query, limit = 10) {
137
+ if (!this.isOpen) throw new Error('Database handle is closed');
138
+ if (!query || typeof query !== 'string') return [];
139
+
140
+ const terms = query.toLowerCase().split(/\s+/).filter(Boolean);
141
+ if (terms.length === 0) return [];
142
+
143
+ const results = [];
144
+ for (const r of this.records) {
145
+ if (!r) continue;
146
+ const text = typeof r === 'string'
147
+ ? r
148
+ : Object.values(r).map(v => (typeof v === 'object' && v !== null ? JSON.stringify(v) : String(v ?? ''))).join(' ');
149
+ const lower = text.toLowerCase();
150
+ let score = 0;
151
+ let firstIdx = -1;
152
+
153
+ for (const term of terms) {
154
+ let idx = 0;
155
+ let count = 0;
156
+ while ((idx = lower.indexOf(term, idx)) !== -1) {
157
+ count++;
158
+ if (firstIdx === -1 || idx < firstIdx) firstIdx = idx;
159
+ idx += term.length;
160
+ }
161
+ if (count > 0) {
162
+ score += count * (term.length / Math.max(1, lower.length) + 1);
163
+ }
164
+ }
165
+
166
+ if (score > 0) {
167
+ const start = Math.max(0, firstIdx - 20);
168
+ const end = Math.min(text.length, firstIdx + 60);
169
+ const snippet = (start > 0 ? '...' : '') + text.slice(start, end) + (end < text.length ? '...' : '');
170
+ results.push({ ...r, snippet, score });
171
+ }
172
+ }
173
+
174
+ results.sort((a, b) => b.score - a.score);
175
+ return results.slice(0, limit);
176
+ }
177
+
178
+ close() {
179
+ this.isOpen = false;
180
+ this.records = [];
181
+ }
182
+ }
183
+
184
+ export default JsonlDatabaseFallbackWrapper;