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,187 @@
1
+ /**
2
+ * @file src/telemetry/otelExporter.mjs
3
+ * Zero-socket local OpenTelemetry metric formatter and sink for Claude Code Highbeam.
4
+ * Maps `claude_code.token.usage`, `claude_code.cost.usage`, and `vcs.*` attributes when
5
+ * `CLAUDE_CODE_ENABLE_TELEMETRY=1` is set.
6
+ */
7
+
8
+ import { path, getCwd, appendJsonlSafe } from '../utils/runtime.mjs';
9
+
10
+ /**
11
+ * Checks whether OpenTelemetry export is enabled via environment or explicit option.
12
+ * @param {object} [options={}]
13
+ * @returns {boolean}
14
+ */
15
+ export function isOtelEnabled(options = {}) {
16
+ if (typeof options.enabled === 'boolean') {
17
+ return options.enabled;
18
+ }
19
+ const envVal = String(globalThis.process?.env?.CLAUDE_CODE_ENABLE_TELEMETRY || '').trim();
20
+ return envVal === '1' || envVal.toLowerCase() === 'true';
21
+ }
22
+
23
+ /**
24
+ * Strips embedded basic-auth/PAT credentials (`https://user:ghp_secret@github.com/...`)
25
+ * and query/fragment tokens before writing `vcs.repository.url.full` (`ISS-030`).
26
+ *
27
+ * @param {string} [rawUrl='']
28
+ * @returns {string}
29
+ */
30
+ export function sanitizeRepositoryUrl(rawUrl = '') {
31
+ const input = String(rawUrl || '').trim();
32
+ if (!input) return '';
33
+
34
+ const withoutQueryOrHash = input.split(/[?#]/)[0];
35
+
36
+ if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(withoutQueryOrHash)) {
37
+ return withoutQueryOrHash.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/@]+@/, '$1');
38
+ }
39
+
40
+ if (/^[^/:@]+:[^/@]+@[^/]+:/.test(withoutQueryOrHash)) {
41
+ return withoutQueryOrHash.replace(/^([^/:@]+):[^/@]+@/, '$1@');
42
+ }
43
+
44
+ return withoutQueryOrHash;
45
+ }
46
+
47
+ /**
48
+ * Formats normalized turn/session telemetry into OpenTelemetry data points.
49
+ * @param {object} telemetryState
50
+ * @param {object} [vcsMetadata={}]
51
+ * @returns {Array<object>}
52
+ */
53
+ export function buildOtelMetricRecords(telemetryState = {}, vcsMetadata = {}) {
54
+ const timestamp = telemetryState.lastUpdatedAt || Date.now();
55
+ const baseAttributes = {
56
+ 'session.id': String(telemetryState.sessionId || 'default'),
57
+ model: String(telemetryState.modelId || 'claude-sonnet-5-5'),
58
+ 'agent.id': telemetryState.lastAgentId ? String(telemetryState.lastAgentId) : 'main',
59
+ 'vcs.repository.url.full': sanitizeRepositoryUrl(
60
+ vcsMetadata.repositoryUrl || telemetryState.vcs?.repositoryUrl || ''
61
+ ),
62
+ 'vcs.ref.head.name': String(vcsMetadata.branch || telemetryState.vcs?.branch || ''),
63
+ 'vcs.ref.head.revision': String(vcsMetadata.revision || telemetryState.vcs?.revision || '')
64
+ };
65
+
66
+ const latestTurn = telemetryState.lastTurn || {};
67
+ const tokens = latestTurn.tokens || {
68
+ uncachedInput: telemetryState.uncachedInputTokens || 0,
69
+ output: telemetryState.outputTokens || 0,
70
+ cacheRead: telemetryState.cacheReadTokens || 0,
71
+ totalCacheWrite: telemetryState.cacheWriteTokens || 0
72
+ };
73
+ const costs = latestTurn.costsUSD || {
74
+ totalActualSpendUSD: telemetryState.totalActualSpendUSD || 0,
75
+ netCacheSavingsUSD: telemetryState.netCacheSavingsUSD || 0
76
+ };
77
+
78
+ const tokenTypes = [
79
+ { type: 'input', value: Number(tokens.uncachedInput || 0) },
80
+ { type: 'output', value: Number((tokens.output || 0) + (tokens.thinking || 0)) },
81
+ { type: 'cacheRead', value: Number(tokens.cacheRead || 0) },
82
+ { type: 'cacheCreation', value: Number(tokens.totalCacheWrite || 0) }
83
+ ];
84
+
85
+ const records = [];
86
+ for (const entry of tokenTypes) {
87
+ records.push({
88
+ metricName: 'claude_code.token.usage',
89
+ timestamp,
90
+ value: entry.value,
91
+ unit: 'tokens',
92
+ attributes: {
93
+ ...baseAttributes,
94
+ type: entry.type
95
+ }
96
+ });
97
+ }
98
+
99
+ records.push({
100
+ metricName: 'claude_code.cost.usage',
101
+ timestamp,
102
+ value: Number(costs.totalActualSpendUSD || 0),
103
+ unit: 'USD',
104
+ attributes: {
105
+ ...baseAttributes,
106
+ cache_savings_usd: Number(costs.netCacheSavingsUSD || 0),
107
+ negative_cache_roi: Boolean(telemetryState.cacheRoi?.negativeCacheRoi)
108
+ }
109
+ });
110
+
111
+ if (
112
+ telemetryState.savedQuotaUSD !== undefined ||
113
+ telemetryState.workspace30dSavedUSD !== undefined ||
114
+ telemetryState.interventionCount !== undefined ||
115
+ telemetryState.breakerTrips !== undefined ||
116
+ telemetryState.includeHorizonMetrics
117
+ ) {
118
+ records.push({
119
+ metricName: 'attention_horizon.saved_quota.usd',
120
+ timestamp,
121
+ value: Number(
122
+ telemetryState.savedQuotaUSD ??
123
+ telemetryState.workspace30dSavedUSD ??
124
+ costs.netCacheSavingsUSD ??
125
+ 0
126
+ ),
127
+ unit: 'USD',
128
+ attributes: {
129
+ ...baseAttributes
130
+ }
131
+ });
132
+
133
+ records.push({
134
+ metricName: 'attention_horizon.intervention.count',
135
+ timestamp,
136
+ value: Number(telemetryState.interventionCount ?? telemetryState.breakerTrips ?? 0),
137
+ unit: 'count',
138
+ attributes: {
139
+ ...baseAttributes
140
+ }
141
+ });
142
+ }
143
+
144
+ return records;
145
+ }
146
+
147
+ /**
148
+ * Exports OpenTelemetry metric records to a local sink or `.claude/cache/otel_metrics.jsonl`
149
+ * when `CLAUDE_CODE_ENABLE_TELEMETRY=1`. Never opens outbound network sockets.
150
+ *
151
+ * @param {object} telemetryState
152
+ * @param {object} [options={}]
153
+ * @returns {{ exported: boolean, recordCount: number, records: Array<object> }}
154
+ */
155
+ export function exportOtelTelemetry(telemetryState = {}, options = {}) {
156
+ if (!isOtelEnabled(options)) {
157
+ return { exported: false, recordCount: 0, records: [] };
158
+ }
159
+
160
+ const records = buildOtelMetricRecords(telemetryState, options.vcs || {});
161
+
162
+ if (typeof options.sink === 'function') {
163
+ options.sink(records);
164
+ return { exported: true, recordCount: records.length, records };
165
+ }
166
+
167
+ const cwd = options.cwd || getCwd(options);
168
+ if (cwd) {
169
+ const targetPath = options.otelFilePath || path.join(cwd, '.claude', 'cache', 'otel_metrics.jsonl');
170
+ let anyWritten = false;
171
+ for (const record of records) {
172
+ if (appendJsonlSafe(targetPath, record, options)) {
173
+ anyWritten = true;
174
+ }
175
+ }
176
+ return { exported: anyWritten, recordCount: records.length, records };
177
+ }
178
+
179
+ return { exported: false, recordCount: records.length, records };
180
+ }
181
+
182
+ export default {
183
+ isOtelEnabled,
184
+ sanitizeRepositoryUrl,
185
+ buildOtelMetricRecords,
186
+ exportOtelTelemetry
187
+ };
@@ -0,0 +1,522 @@
1
+ /**
2
+ * @file src/telemetry/scopeLockRegistry.mjs
3
+ * Concurrent Multi-Agent File-Scope Lockfile Registry (`.claude/locks/active_scopes.json`)
4
+ * and 5-Hour / Spend-Limit Quota Hard Brake (`DET-20`).
5
+ *
6
+ * Includes full dotfile support (`.github/*`, `.claude/*`, `.env.example`).
7
+ */
8
+
9
+ import { path, getCwd, writeJsonAtomic, readJsonSafe } from '../utils/runtime.mjs';
10
+
11
+ export const DEFAULT_SCOPE_LOCK_TTL_MS = 15 * 60 * 1000; // 15 minutes
12
+
13
+ /**
14
+ * Normalizes a file path or glob pattern to POSIX forward slashes for consistent scope matching.
15
+ * Preserves leading dotfiles (e.g. `.github/workflows/ci.yml`, `.claude/settings.json`, `.env.example`).
16
+ *
17
+ * @param {string} rawPath
18
+ * @param {string} [cwd='']
19
+ * @returns {string}
20
+ */
21
+ export function normalizeScopePath(rawPath = '', cwd = '') {
22
+ let cleaned = String(rawPath || '').trim().replace(/\\/g, '/');
23
+ if (!cleaned) return '';
24
+
25
+ if (cwd) {
26
+ const normCwd = String(cwd).trim().replace(/\\/g, '/').replace(/\/+$/, '');
27
+ if (normCwd && cleaned.toLowerCase().startsWith(normCwd.toLowerCase() + '/')) {
28
+ cleaned = cleaned.slice(normCwd.length + 1);
29
+ }
30
+ }
31
+
32
+ cleaned = cleaned.replace(/^(\.\/)+/, '').replace(/\/+/g, '/');
33
+ return cleaned;
34
+ }
35
+
36
+ /**
37
+ * Converts a scope glob pattern (supporting dotfiles like `.github/*`, `.claude/**`, `.env*`)
38
+ * into a RegExp that explicitly matches leading dots in path segments.
39
+ *
40
+ * @param {string} pattern
41
+ * @returns {RegExp}
42
+ */
43
+ export function globToDotfileRegex(pattern = '') {
44
+ const norm = normalizeScopePath(pattern);
45
+ if (!norm) return /^$/;
46
+
47
+ // If pattern is a directory prefix ending with `/`, match everything inside it
48
+ if (norm.endsWith('/')) {
49
+ const escapedDir = norm.replace(/[.+?^${}()|[\]\\]/g, '\\$&').replace(/\*/g, '.*');
50
+ return new RegExp(`^${escapedDir}.+$`, 'i');
51
+ }
52
+
53
+ let regexStr = '^';
54
+ for (let i = 0; i < norm.length; i++) {
55
+ const ch = norm[i];
56
+ if (ch === '*') {
57
+ if (norm[i + 1] === '*') {
58
+ // `**` matches across directory boundaries including dotfiles
59
+ regexStr += '.*';
60
+ i += 1;
61
+ if (norm[i + 1] === '/') {
62
+ i += 1;
63
+ }
64
+ } else {
65
+ // Single `*` matches any characters within a segment, INCLUDING leading `.`
66
+ regexStr += '[^/]*';
67
+ }
68
+ } else if (ch === '?') {
69
+ regexStr += '[^/]';
70
+ } else if ('.+^${}()|[]\\'.includes(ch)) {
71
+ regexStr += `\\${ch}`;
72
+ } else {
73
+ regexStr += ch;
74
+ }
75
+ }
76
+ regexStr += '$';
77
+ return new RegExp(regexStr, 'i');
78
+ }
79
+
80
+ /**
81
+ * Checks whether a target file path matches a scope pattern (including dotfiles).
82
+ * Also matches if the pattern is `dir/*` and the target is nested inside `dir/...`.
83
+ *
84
+ * @param {string} targetFilePath
85
+ * @param {string} scopePattern
86
+ * @param {string} [cwd='']
87
+ * @returns {boolean}
88
+ */
89
+ export function matchesScopePattern(targetFilePath, scopePattern, cwd = '') {
90
+ const normTarget = normalizeScopePath(targetFilePath, cwd);
91
+ const normPattern = normalizeScopePath(scopePattern, cwd);
92
+ if (!normTarget || !normPattern) return false;
93
+
94
+ if (normTarget.toLowerCase() === normPattern.toLowerCase()) {
95
+ return true;
96
+ }
97
+
98
+ // If scopePattern ends with `/*`, also match nested paths under that directory (e.g. `.github/*` matches `.github/workflows/ci.yml`)
99
+ if (normPattern.endsWith('/*') && !normPattern.endsWith('/**')) {
100
+ const prefix = normPattern.slice(0, -1).toLowerCase(); // includes trailing `/`
101
+ if (normTarget.toLowerCase().startsWith(prefix)) {
102
+ return true;
103
+ }
104
+ }
105
+
106
+ const rx = globToDotfileRegex(normPattern);
107
+ return rx.test(normTarget);
108
+ }
109
+
110
+ /**
111
+ * Resolves the lockfile path `.claude/locks/active_scopes.json`.
112
+ * @param {object} [options={}]
113
+ * @returns {string}
114
+ */
115
+ export function getScopeLocksPath(options = {}) {
116
+ if (options.locksFilePath) return options.locksFilePath;
117
+ const cwd = getCwd(options);
118
+ return path.join(cwd, '.claude', 'locks', 'active_scopes.json');
119
+ }
120
+
121
+ /**
122
+ * Normalizes a lock or Antigravity `leases[]` record (`{ agent_id, session_id, files_locked, expires_at }`
123
+ * or `{ trajectoryId, agentRole, claimedPaths, acquiredAtIso, expiresAtMs }`)
124
+ * into the canonical `{ ownerId, scopes, acquiredAt, expiresAt }` shape (`ISS-020`, `ISS-055`).
125
+ *
126
+ * @param {object} entry
127
+ * @param {string} [source='local']
128
+ * @returns {object | null}
129
+ */
130
+ function normalizeScopeLockEntry(entry, source = 'local') {
131
+ if (!entry || typeof entry !== 'object') return null;
132
+ const ownerId = String(
133
+ entry.ownerId ||
134
+ entry.agent_id ||
135
+ entry.trajectoryId ||
136
+ entry.session_id ||
137
+ entry.sessionId ||
138
+ entry.agentRole ||
139
+ ''
140
+ ).trim();
141
+
142
+ const rawScopes = Array.isArray(entry.scopes)
143
+ ? entry.scopes
144
+ : Array.isArray(entry.files_locked)
145
+ ? entry.files_locked
146
+ : Array.isArray(entry.claimedPaths)
147
+ ? entry.claimedPaths
148
+ : [];
149
+ const scopes = rawScopes.map((s) => String(s || '').trim()).filter(Boolean);
150
+ if (!ownerId || scopes.length === 0) return null;
151
+
152
+ const acquiredIsoRaw = String(
153
+ entry.acquired_at ||
154
+ entry.acquiredAtIso ||
155
+ (typeof entry.acquiredAt === 'string' ? entry.acquiredAt : '') ||
156
+ ''
157
+ ).trim();
158
+ const parsedAcquiredIso = acquiredIsoRaw ? Date.parse(acquiredIsoRaw) : NaN;
159
+ const acquiredAt =
160
+ typeof entry.acquiredAt === 'number' && Number.isFinite(entry.acquiredAt)
161
+ ? entry.acquiredAt
162
+ : typeof entry.acquiredAtMs === 'number' && Number.isFinite(entry.acquiredAtMs)
163
+ ? entry.acquiredAtMs
164
+ : Number.isFinite(parsedAcquiredIso)
165
+ ? parsedAcquiredIso
166
+ : 0;
167
+
168
+ const expiresIsoRaw = String(
169
+ entry.expires_at ||
170
+ entry.expiresAtIso ||
171
+ (typeof entry.expiresAt === 'string' ? entry.expiresAt : '') ||
172
+ ''
173
+ ).trim();
174
+ const parsedExpiresIso = expiresIsoRaw ? Date.parse(expiresIsoRaw) : NaN;
175
+ const expiresAt =
176
+ typeof entry.expiresAt === 'number' && Number.isFinite(entry.expiresAt)
177
+ ? entry.expiresAt
178
+ : typeof entry.expiresAtMs === 'number' && Number.isFinite(entry.expiresAtMs)
179
+ ? entry.expiresAtMs
180
+ : Number.isFinite(parsedExpiresIso)
181
+ ? parsedExpiresIso
182
+ : 0;
183
+
184
+ const normalized = {
185
+ ownerId,
186
+ scopes,
187
+ acquiredAt,
188
+ expiresAt
189
+ };
190
+ if (entry.agentRole) {
191
+ normalized.agentRole = String(entry.agentRole);
192
+ }
193
+ if (source === 'cross_harness') {
194
+ normalized.source = 'cross_harness';
195
+ }
196
+ return normalized;
197
+ }
198
+
199
+ /**
200
+ * Formats a normalized lock entry with both Claude Code (`ownerId`, `scopes`, `expiresAt`)
201
+ * and Antigravity (`agent_id`, `session_id`, `trajectoryId`, `files_locked`, `claimedPaths`,
202
+ * `acquired_at`, `expires_at`, `ttl_ms`) fields for bidirectional cross-harness parity (`ISS-055`).
203
+ *
204
+ * @param {object} lock
205
+ * @param {number} [fallbackTtlMs=DEFAULT_SCOPE_LOCK_TTL_MS]
206
+ * @returns {object}
207
+ */
208
+ function buildCrossCompatibleLockRecord(lock, fallbackTtlMs = DEFAULT_SCOPE_LOCK_TTL_MS) {
209
+ const acquiredAt = Number(lock.acquiredAt || Date.now());
210
+ const expiresAt = Number(lock.expiresAt || acquiredAt + fallbackTtlMs);
211
+ const ttlMs = Math.max(0, expiresAt - acquiredAt) || fallbackTtlMs;
212
+ const acquiredIso = new Date(acquiredAt).toISOString();
213
+ const expiresIso = new Date(expiresAt).toISOString();
214
+ return {
215
+ ownerId: lock.ownerId,
216
+ agent_id: lock.ownerId,
217
+ session_id: lock.ownerId,
218
+ trajectoryId: lock.ownerId,
219
+ scopes: [...lock.scopes],
220
+ files_locked: [...lock.scopes],
221
+ claimedPaths: [...lock.scopes],
222
+ acquiredAt,
223
+ acquiredAtMs: acquiredAt,
224
+ acquired_at: acquiredIso,
225
+ acquiredAtIso: acquiredIso,
226
+ expiresAt,
227
+ expiresAtMs: expiresAt,
228
+ expires_at: expiresIso,
229
+ expiresAtIso: expiresIso,
230
+ ttl_ms: ttlMs
231
+ };
232
+ }
233
+
234
+ /**
235
+ * Reads and prunes expired scope locks from `.claude/locks/active_scopes.json`
236
+ * (and cross-harness `.agents/locks/active_scopes.json` `locks[]` + `leases[]` when present in `cwd`).
237
+ * @param {object} [options={}]
238
+ * @returns {{ schemaVersion: string, locks: Array<object> }}
239
+ */
240
+ export function readActiveScopeLocks(options = {}) {
241
+ const nowMs = options.nowMs ?? Date.now();
242
+ const filePath = getScopeLocksPath(options);
243
+ const raw = readJsonSafe(filePath, { schemaVersion: '2026.11.1', locks: [] }, options);
244
+ const locks = [];
245
+ const seenKeys = new Set();
246
+
247
+ const pushUnique = (entry, source) => {
248
+ const norm = normalizeScopeLockEntry(entry, source);
249
+ if (!norm) return;
250
+ const dedupKey = `${source}::${norm.ownerId}::${norm.scopes.join('|')}`;
251
+ if (seenKeys.has(dedupKey)) return;
252
+ seenKeys.add(dedupKey);
253
+ locks.push(norm);
254
+ };
255
+
256
+ if (Array.isArray(raw?.locks)) {
257
+ for (const item of raw.locks) {
258
+ pushUnique(item, 'local');
259
+ }
260
+ }
261
+ if (Array.isArray(raw?.leases)) {
262
+ for (const lease of raw.leases) {
263
+ pushUnique(lease, 'local');
264
+ }
265
+ }
266
+
267
+ const resolvedCwd = options.cwd || getCwd(options);
268
+ if (!options.locksFilePath && resolvedCwd && resolvedCwd !== '.') {
269
+ const crossHarnessPath = path.join(resolvedCwd, '.agents', 'locks', 'active_scopes.json');
270
+ const crossRaw = readJsonSafe(crossHarnessPath, null, options);
271
+ if (Array.isArray(crossRaw?.locks)) {
272
+ for (const item of crossRaw.locks) {
273
+ pushUnique(item, 'cross_harness');
274
+ }
275
+ }
276
+ if (Array.isArray(crossRaw?.leases)) {
277
+ for (const lease of crossRaw.leases) {
278
+ pushUnique(lease, 'cross_harness');
279
+ }
280
+ }
281
+ }
282
+
283
+ const validLocks = locks.filter((lock) => !lock.expiresAt || lock.expiresAt > nowMs);
284
+ return {
285
+ version: 1,
286
+ schemaVersion: '2026.11.1',
287
+ locks: validLocks
288
+ };
289
+ }
290
+
291
+ /**
292
+ * Acquires a file-scope lock for `(ownerId)` if no conflicting lock exists.
293
+ *
294
+ * @param {object} params
295
+ * @param {string} params.ownerId - Unique owner identifier (`sessionId` or `sessionId:agentId`)
296
+ * @param {Array<string>} params.scopes - File paths or globs (including dotfiles)
297
+ * @param {number} [params.ttlMs=900000]
298
+ * @param {object} [options={}]
299
+ */
300
+ export function acquireScopeLock(params = {}, options = {}) {
301
+ const nowMs = options.nowMs ?? Date.now();
302
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '';
303
+ const ownerId = String(params.ownerId || 'default').trim();
304
+ const requestedScopes = Array.isArray(params.scopes)
305
+ ? params.scopes.map((s) => normalizeScopePath(s, cwd)).filter(Boolean)
306
+ : [];
307
+ const ttlMs = Number(params.ttlMs ?? DEFAULT_SCOPE_LOCK_TTL_MS);
308
+
309
+ const state = readActiveScopeLocks({ ...options, nowMs });
310
+
311
+ // Check if any requested scope collides with another owner's active lock
312
+ for (const existing of state.locks) {
313
+ if (existing.ownerId === ownerId) continue;
314
+ for (const existingScope of existing.scopes || []) {
315
+ for (const reqScope of requestedScopes) {
316
+ if (
317
+ matchesScopePattern(reqScope, existingScope, cwd) ||
318
+ matchesScopePattern(existingScope, reqScope, cwd)
319
+ ) {
320
+ return {
321
+ acquired: false,
322
+ conflict: {
323
+ ownerId: existing.ownerId,
324
+ conflictingScope: existingScope,
325
+ requestedScope: reqScope,
326
+ expiresAt: existing.expiresAt
327
+ }
328
+ };
329
+ }
330
+ }
331
+ }
332
+ }
333
+
334
+ const existingOtherLocks = state.locks.filter(
335
+ (l) => l.ownerId !== ownerId && l.source !== 'cross_harness'
336
+ );
337
+ const lockRecord = buildCrossCompatibleLockRecord(
338
+ {
339
+ ownerId,
340
+ scopes: requestedScopes,
341
+ acquiredAt: nowMs,
342
+ expiresAt: nowMs + ttlMs
343
+ },
344
+ ttlMs
345
+ );
346
+ const serializedLocks = [
347
+ ...existingOtherLocks.map((l) => buildCrossCompatibleLockRecord(l, ttlMs)),
348
+ lockRecord
349
+ ];
350
+
351
+ const filePath = getScopeLocksPath(options);
352
+ writeJsonAtomic(
353
+ filePath,
354
+ {
355
+ version: 1,
356
+ schemaVersion: '2026.11.1',
357
+ updatedAt: nowMs,
358
+ locks: serializedLocks,
359
+ leases: serializedLocks
360
+ },
361
+ options
362
+ );
363
+
364
+ return {
365
+ acquired: true,
366
+ lock: lockRecord,
367
+ conflict: null
368
+ };
369
+ }
370
+
371
+ /**
372
+ * Releases all scope locks held by `ownerId`.
373
+ * @param {string} ownerId
374
+ * @param {object} [options={}]
375
+ */
376
+ export function releaseScopeLock(ownerId, options = {}) {
377
+ const nowMs = options.nowMs ?? Date.now();
378
+ const state = readActiveScopeLocks({ ...options, nowMs });
379
+ const nextLocks = state.locks
380
+ .filter((l) => l.ownerId !== ownerId && l.source !== 'cross_harness')
381
+ .map((l) => buildCrossCompatibleLockRecord(l));
382
+ const filePath = getScopeLocksPath(options);
383
+ writeJsonAtomic(
384
+ filePath,
385
+ {
386
+ version: 1,
387
+ schemaVersion: '2026.11.1',
388
+ updatedAt: nowMs,
389
+ locks: nextLocks,
390
+ leases: nextLocks
391
+ },
392
+ options
393
+ );
394
+ return { released: true, remainingLocks: nextLocks.length };
395
+ }
396
+
397
+ /**
398
+ * Checks whether editing/writing `targetFilePath` by `ownerId` conflicts with an active scope lock,
399
+ * or whether a 5-hour / spend-limit quota hard brake is active (`DET-20`).
400
+ *
401
+ * @param {object} params
402
+ * @param {string} [params.targetFilePath='']
403
+ * @param {string} [params.ownerId='default']
404
+ * @param {object} [params.rateLimits={}]
405
+ * @param {object} [options={}]
406
+ */
407
+ export function evaluateScopeAndQuotaBrake(params = {}, options = {}) {
408
+ const nowMs = options.nowMs ?? params.nowMs ?? Date.now();
409
+ const cwd = options.cwd || globalThis.process?.cwd?.() || '';
410
+ const ownerId = String(
411
+ params.ownerId ||
412
+ params.agentId ||
413
+ params.agent_id ||
414
+ params.sessionId ||
415
+ params.session_id ||
416
+ 'default'
417
+ ).trim();
418
+ const targetFilePath = normalizeScopePath(
419
+ params.targetFilePath || params.filePath || params.file_path || params.path || '',
420
+ cwd
421
+ );
422
+ const rateLimits = params.rateLimits || {};
423
+
424
+ // 1. Check 5-Hour / Spend-Limit Quota Hard Brake
425
+ const fiveHour = rateLimits.fiveHour || rateLimits.five_hour || null;
426
+ const spendLimit = rateLimits.spendLimit || rateLimits.spend_limit || null;
427
+
428
+ if (fiveHour) {
429
+ const remPct =
430
+ typeof fiveHour.remaining_pct === 'number'
431
+ ? fiveHour.remaining_pct
432
+ : typeof fiveHour.limit === 'number' && fiveHour.limit > 0
433
+ ? ((fiveHour.limit - Number(fiveHour.used || 0)) / fiveHour.limit) * 100
434
+ : 100;
435
+ if (remPct <= 0) {
436
+ return {
437
+ detectorId: 'DET-20',
438
+ triggered: true,
439
+ decision: 'deny',
440
+ subType: 'QUOTA_FIVE_HOUR_EXHAUSTED',
441
+ reason: `[DET-20 Quota Hard Brake] 5-hour rate limit window is exhausted (0% remaining). Halting tool execution to prevent failed turn loops.`
442
+ };
443
+ }
444
+ }
445
+
446
+ if (spendLimit) {
447
+ const remUsd =
448
+ typeof spendLimit.remaining_usd === 'number'
449
+ ? spendLimit.remaining_usd
450
+ : typeof spendLimit.limit_usd === 'number'
451
+ ? spendLimit.limit_usd - Number(spendLimit.spent_usd || 0)
452
+ : Infinity;
453
+ if (remUsd <= 0) {
454
+ return {
455
+ detectorId: 'DET-20',
456
+ triggered: true,
457
+ decision: 'deny',
458
+ subType: 'QUOTA_SPEND_LIMIT_EXHAUSTED',
459
+ reason: `[DET-20 Quota Hard Brake] Session USD spend limit reached ($0.00 remaining). Halting tool execution.`
460
+ };
461
+ }
462
+ }
463
+
464
+ // 2. Check Concurrent Multi-Agent Scope Lockfile
465
+ if (targetFilePath) {
466
+ const isRead = Boolean(params.isRead || /^(read|read_file|view_file)$/i.test(String(params.toolName || '')));
467
+ const state = readActiveScopeLocks({ ...options, nowMs });
468
+ for (const lock of state.locks) {
469
+ if (lock.ownerId === ownerId) continue;
470
+ for (const scopePattern of lock.scopes || []) {
471
+ if (matchesScopePattern(targetFilePath, scopePattern, cwd)) {
472
+ if (isRead) {
473
+ return {
474
+ detectorId: 'DET-20',
475
+ triggered: true,
476
+ decision: 'allow',
477
+ advisory: true,
478
+ subType: 'SUBAGENT_DUPLICATE_READ_DIGEST',
479
+ conflictingOwner: lock.ownerId,
480
+ conflictingScope: scopePattern,
481
+ targetFilePath,
482
+ additionalContext: `[DET-20 Subagent Duplicate Read] File "${targetFilePath}" was already read/claimed by active subagent "${lock.ownerId}". Request parent StateBaton file digest instead of reading full cold file.`,
483
+ reason: `[DET-20 Subagent Duplicate Read] File "${targetFilePath}" was already read/claimed by active subagent "${lock.ownerId}". Request parent StateBaton file digest instead of reading full cold file.`
484
+ };
485
+ }
486
+ return {
487
+ detectorId: 'DET-20',
488
+ triggered: true,
489
+ decision: 'deny',
490
+ subType: 'SCOPE_LOCK_CONFLICT',
491
+ conflictingOwner: lock.ownerId,
492
+ conflictingScope: scopePattern,
493
+ targetFilePath,
494
+ reason:
495
+ `[DET-20 Concurrent Scope Lock] File "${targetFilePath}" is locked by active agent "${lock.ownerId}" ` +
496
+ `(scope "${scopePattern}"). Coordinate via StateBaton or wait for lock release.`
497
+ };
498
+ }
499
+ }
500
+ }
501
+ }
502
+
503
+ return {
504
+ detectorId: 'DET-20',
505
+ triggered: false,
506
+ decision: 'allow',
507
+ subType: null,
508
+ reason: null
509
+ };
510
+ }
511
+
512
+ export default {
513
+ DEFAULT_SCOPE_LOCK_TTL_MS,
514
+ normalizeScopePath,
515
+ globToDotfileRegex,
516
+ matchesScopePattern,
517
+ getScopeLocksPath,
518
+ readActiveScopeLocks,
519
+ acquireScopeLock,
520
+ releaseScopeLock,
521
+ evaluateScopeAndQuotaBrake
522
+ };