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,327 @@
1
+ /**
2
+ * @file src/telemetry/sprintMetrics.mjs
3
+ * Sprint 1 "Metrics Wedge" for Claude Code (parity with Antigravity `src/core/sprint_metrics.mjs`):
4
+ *
5
+ * 1. Prefix-Cache Retention Index (0–100%) — incremental, per distinct API request.
6
+ * 2. Thinking vs. Generation Drift + DET-21 Scratchpad Loop Detector
7
+ * (Claude Code DET-21 ⇄ Antigravity DET-30 `thinking-drift-loop`).
8
+ *
9
+ * Pure ESM, zero `node:*` imports (Mod-safe). Only measured usage is scored: an
10
+ * unmeasured session reports `retentionIndexPct: null` (rendered "—"), never a fabricated 100%.
11
+ */
12
+
13
+ export const RETENTION_CONSTANTS = Object.freeze({
14
+ DEFAULT_TTL_SECONDS: 300,
15
+ BUST_RETAINED_RATIO: 0.5,
16
+ GRADE_A_PCT: 90,
17
+ GRADE_B_PCT: 70,
18
+ SERIES_MAX: 40
19
+ });
20
+
21
+ export const DRIFT_THRESHOLDS = Object.freeze({
22
+ MIN_THINKING_TOKENS: 4000,
23
+ LOOP_RATIO: 12,
24
+ ELEVATED_RATIO: 4,
25
+ CUMULATIVE_THINKING_TOKENS: 10000,
26
+ CONSECUTIVE_TURNS_CRITICAL: 2,
27
+ ROLLING_WINDOW: 3,
28
+ HISTORY: 10
29
+ });
30
+
31
+ export const THINKING_DRIFT_DETECTOR_ID = 'DET-30';
32
+ export const THINKING_DRIFT_DEPRECATED_ALIAS = 'DET-21';
33
+ export const THINKING_DRIFT_GA_DETECTOR_ID = 'DET-30';
34
+ export const THINKING_DRIFT_SLUG = 'thinking-drift-loop';
35
+
36
+ function num(v) {
37
+ const n = Number(v);
38
+ return Number.isFinite(n) && n > 0 ? n : 0;
39
+ }
40
+
41
+ function round2(v) {
42
+ return Number((Number(v) || 0).toFixed(2));
43
+ }
44
+
45
+ function round6(v) {
46
+ return Number((Number(v) || 0).toFixed(6));
47
+ }
48
+
49
+ export function createInitialPrefixRetention() {
50
+ return {
51
+ measured: false,
52
+ retentionIndexPct: null,
53
+ grade: 'n/a',
54
+ eligiblePrefixTokens: 0,
55
+ retainedPrefixTokens: 0,
56
+ leakedPrefixTokens: 0,
57
+ measuredTurns: 0,
58
+ bustCount: 0,
59
+ ttlExpiredTurns: 0,
60
+ bustCauses: {},
61
+ lastBust: null,
62
+ retainedDiscountSavingsUSD: 0,
63
+ leakedColdPrefillUSD: 0,
64
+ hasCacheTelemetry: false,
65
+ unmeasuredReason: 'insufficient_turns',
66
+ series: [],
67
+ streams: {}
68
+ };
69
+ }
70
+
71
+ export function createInitialThinkingDrift() {
72
+ return {
73
+ measured: false,
74
+ turns: [],
75
+ current: null,
76
+ lastTtftMs: null,
77
+ avgTtftMs: null,
78
+ lastDriftRatio: null,
79
+ rollingDriftRatio: null,
80
+ driftState: 'n/a',
81
+ loop: { detectorId: THINKING_DRIFT_DETECTOR_ID, triggered: false, severity: 'none', consecutiveLoopTurns: 0, message: '' }
82
+ };
83
+ }
84
+
85
+ /**
86
+ * Applies one distinct API request's prompt-side usage to the retention ledger.
87
+ *
88
+ * @param {object} retention - prior ledger (mutated copy returned)
89
+ * @param {object} req
90
+ * @param {string} req.streamKey - 'main' or subagent id
91
+ * @param {string} req.modelId
92
+ * @param {number} req.uncachedInputTokens
93
+ * @param {number} req.cacheReadTokens
94
+ * @param {number} req.cacheWriteTokens
95
+ * @param {number} req.nowMs
96
+ * @param {number} [req.ttlSeconds=300]
97
+ * @param {number} req.inputPer1M
98
+ * @param {number} req.readPer1M
99
+ */
100
+ export function applyPrefixRetentionRequest(retention, req = {}) {
101
+ const r = retention && typeof retention === 'object' ? retention : createInitialPrefixRetention();
102
+ if (!r.streams || typeof r.streams !== 'object') r.streams = {};
103
+ if (!r.bustCauses || typeof r.bustCauses !== 'object') r.bustCauses = {};
104
+
105
+ const total = num(req.uncachedInputTokens) + num(req.cacheReadTokens) + num(req.cacheWriteTokens);
106
+ if (total <= 0) return r;
107
+ if (num(req.cacheReadTokens) > 0 || num(req.cacheWriteTokens) > 0) r.hasCacheTelemetry = true;
108
+ if (!Array.isArray(r.series)) r.series = [];
109
+ const pushSeries = (pt) => {
110
+ r.series.push(pt);
111
+ if (r.series.length > RETENTION_CONSTANTS.SERIES_MAX) r.series = r.series.slice(-RETENTION_CONSTANTS.SERIES_MAX);
112
+ };
113
+
114
+ const key = String(req.streamKey || 'main');
115
+ const prev = r.streams[key] || null;
116
+ r.streams[key] = { promptTotal: total, atMs: num(req.nowMs), modelId: req.modelId || null };
117
+ if (!prev) return r;
118
+
119
+ const ttlSec = num(req.ttlSeconds) || RETENTION_CONSTANTS.DEFAULT_TTL_SECONDS;
120
+ const gapSec = prev.atMs > 0 && num(req.nowMs) >= prev.atMs ? (num(req.nowMs) - prev.atMs) / 1000 : null;
121
+ if (gapSec !== null && gapSec > ttlSec) {
122
+ r.ttlExpiredTurns += 1;
123
+ pushSeries({ eligible: 0, retained: 0, pct: null, bust: false, cause: null, ttlExpired: true, atMs: num(req.nowMs) });
124
+ return r;
125
+ }
126
+
127
+ const eligible = Math.min(prev.promptTotal, total);
128
+ if (eligible <= 0) return r;
129
+ const retained = Math.min(num(req.cacheReadTokens), eligible);
130
+ const leaked = eligible - retained;
131
+ const discountPerToken = Math.max(0, num(req.inputPer1M) - num(req.readPer1M)) / 1_000_000;
132
+
133
+ r.measuredTurns += 1;
134
+ r.eligiblePrefixTokens += eligible;
135
+ r.retainedPrefixTokens += retained;
136
+ r.leakedPrefixTokens = r.eligiblePrefixTokens - r.retainedPrefixTokens;
137
+ r.retainedDiscountSavingsUSD = round6(num(r.retainedDiscountSavingsUSD) + retained * discountPerToken);
138
+ r.leakedColdPrefillUSD = round6(num(r.leakedColdPrefillUSD) + leaked * discountPerToken);
139
+
140
+ const isBust = retained / eligible < RETENTION_CONSTANTS.BUST_RETAINED_RATIO;
141
+ pushSeries({
142
+ eligible,
143
+ retained,
144
+ pct: Math.round((100 * retained) / eligible),
145
+ bust: isBust,
146
+ cause: isBust ? (prev.modelId && req.modelId && prev.modelId !== req.modelId ? 'model_switch' : 'prefix_drift') : null,
147
+ ttlExpired: false,
148
+ savedUSD: round6(retained * discountPerToken),
149
+ atMs: num(req.nowMs)
150
+ });
151
+ if (isBust) {
152
+ const cause = prev.modelId && req.modelId && prev.modelId !== req.modelId ? 'model_switch' : 'prefix_drift';
153
+ r.bustCount += 1;
154
+ r.bustCauses[cause] = (r.bustCauses[cause] || 0) + 1;
155
+ r.lastBust = { cause, leakedTokens: leaked, leakedUSD: round6(leaked * discountPerToken), atMs: num(req.nowMs) };
156
+ }
157
+
158
+ // Honesty gate: zero cache reads/writes across every request => harness exposes no cache
159
+ // telemetry; report "unmeasured", never "0% retained / N busts".
160
+ r.measured = r.measuredTurns > 0 && r.hasCacheTelemetry === true;
161
+ r.unmeasuredReason = r.measured ? null : (r.measuredTurns > 0 ? 'no_cache_telemetry' : 'insufficient_turns');
162
+ r.retentionIndexPct = r.measured
163
+ ? Math.max(0, Math.min(100, Math.round((100 * r.retainedPrefixTokens) / r.eligiblePrefixTokens)))
164
+ : null;
165
+ r.grade = !r.measured
166
+ ? 'n/a'
167
+ : r.retentionIndexPct >= RETENTION_CONSTANTS.GRADE_A_PCT
168
+ ? 'A'
169
+ : r.retentionIndexPct >= RETENTION_CONSTANTS.GRADE_B_PCT ? 'B' : 'C';
170
+ return r;
171
+ }
172
+
173
+ export function formatRetentionCompact(r = {}) {
174
+ if (!r || !r.measured || r.retentionIndexPct === null || r.retentionIndexPct === undefined) return 'Ret —';
175
+ return `Ret ${r.retentionIndexPct}%`;
176
+ }
177
+
178
+ export function formatRetentionLabel(r = {}) {
179
+ if (r && r.unmeasuredReason === 'no_cache_telemetry') return 'Retention — (no cache telemetry reported)';
180
+ if (!r || !r.measured || r.retentionIndexPct === null || r.retentionIndexPct === undefined) {
181
+ return 'Retain — (no multi-turn usage yet)';
182
+ }
183
+ const parts = [`Retain ${r.retentionIndexPct}%`, `Saved $${round2(r.retainedDiscountSavingsUSD).toFixed(2)}`];
184
+ if (num(r.leakedColdPrefillUSD) > 0.005) parts.push(`Leaked $${round2(r.leakedColdPrefillUSD).toFixed(2)}`);
185
+ if (num(r.bustCount) > 0) parts.push(`${r.bustCount} bust${r.bustCount === 1 ? '' : 's'}`);
186
+ return parts.join(' · ');
187
+ }
188
+
189
+ export function classifyTurnDrift(t = {}) {
190
+ const thinking = num(t.thinkingTokens);
191
+ const ratio = thinking / Math.max(1, num(t.visibleOutputTokens));
192
+ if (thinking >= DRIFT_THRESHOLDS.MIN_THINKING_TOKENS && ratio >= DRIFT_THRESHOLDS.LOOP_RATIO && num(t.mutatingCalls) === 0) {
193
+ return 'loop_suspect';
194
+ }
195
+ if (thinking > 0 && ratio >= DRIFT_THRESHOLDS.ELEVATED_RATIO) return 'elevated';
196
+ return 'nominal';
197
+ }
198
+
199
+ export function evaluateThinkingDriftLoop(turnRecords = []) {
200
+ const records = Array.isArray(turnRecords) ? turnRecords : [];
201
+ let consecutive = 0;
202
+ let runThinking = 0;
203
+ for (let i = records.length - 1; i >= 0; i--) {
204
+ const rec = records[i];
205
+ if (num(rec.mutatingCalls) > 0) break;
206
+ runThinking += num(rec.thinkingTokens);
207
+ if (classifyTurnDrift(rec) === 'loop_suspect') consecutive += 1;
208
+ else break;
209
+ }
210
+ const last = records[records.length - 1] || null;
211
+ let severity = 'none';
212
+ if (consecutive >= DRIFT_THRESHOLDS.CONSECUTIVE_TURNS_CRITICAL ||
213
+ (consecutive >= 1 && runThinking >= DRIFT_THRESHOLDS.CUMULATIVE_THINKING_TOKENS)) {
214
+ severity = 'critical';
215
+ } else if (consecutive === 1) {
216
+ severity = 'warn';
217
+ }
218
+ const triggered = severity !== 'none';
219
+ const ratio = last ? round2(num(last.thinkingTokens) / Math.max(1, num(last.visibleOutputTokens))) : 0;
220
+ return {
221
+ detectorId: THINKING_DRIFT_DETECTOR_ID,
222
+ deprecatedAlias: THINKING_DRIFT_DEPRECATED_ALIAS,
223
+ gaDetectorId: THINKING_DRIFT_GA_DETECTOR_ID,
224
+ slug: THINKING_DRIFT_SLUG,
225
+ triggered,
226
+ severity,
227
+ consecutiveLoopTurns: consecutive,
228
+ trailingThinkingTokens: runThinking,
229
+ message: triggered
230
+ ? `${THINKING_DRIFT_DETECTOR_ID} Scratchpad Loop: ${ratio}x reasoning-to-output over ${consecutive} turn(s) with 0 edits. Give a concrete target file + acceptance test, or lower /effort.`
231
+ : ''
232
+ };
233
+ }
234
+
235
+ /**
236
+ * Applies one main-agent usage delta to the drift tracker.
237
+ *
238
+ * @param {object} drift
239
+ * @param {object} ev
240
+ * @param {'turn.step'|'turn.complete'} ev.eventType
241
+ * @param {number} ev.thinkingTokens - delta thinking tokens (reported, never estimated)
242
+ * @param {number} ev.outputTokens - delta visible output tokens
243
+ * @param {number} ev.nowMs
244
+ * @param {number|null} [ev.turnStartedAtMs]
245
+ * @param {number|null} [ev.ttftMs] - explicit TTFT from the host, if provided
246
+ * @param {number} [ev.turnMutations] - workspace edits observed in this turn so far
247
+ */
248
+ export function applyThinkingDriftEvent(drift, ev = {}) {
249
+ const d = drift && typeof drift === 'object' ? drift : createInitialThinkingDrift();
250
+ if (!Array.isArray(d.turns)) d.turns = [];
251
+
252
+ if (!d.current) {
253
+ d.current = {
254
+ startTs: num(ev.turnStartedAtMs) || null,
255
+ ttftMs: null,
256
+ thinkingTokens: 0,
257
+ visibleOutputTokens: 0,
258
+ mutatingCalls: 0
259
+ };
260
+ }
261
+ const cur = d.current;
262
+ if (!cur.startTs && num(ev.turnStartedAtMs)) cur.startTs = num(ev.turnStartedAtMs);
263
+ if (cur.ttftMs === null) {
264
+ if (num(ev.ttftMs) > 0) cur.ttftMs = num(ev.ttftMs);
265
+ else if (cur.startTs && num(ev.nowMs) >= cur.startTs && (num(ev.outputTokens) > 0 || num(ev.thinkingTokens) > 0)) {
266
+ cur.ttftMs = num(ev.nowMs) - cur.startTs;
267
+ }
268
+ }
269
+ cur.thinkingTokens += num(ev.thinkingTokens);
270
+ cur.visibleOutputTokens += num(ev.outputTokens);
271
+ cur.mutatingCalls = Math.max(cur.mutatingCalls, num(ev.turnMutations));
272
+
273
+ const snapshot = (t) => ({
274
+ ttftMs: t.ttftMs,
275
+ thinkingTokens: t.thinkingTokens,
276
+ visibleOutputTokens: t.visibleOutputTokens,
277
+ mutatingCalls: t.mutatingCalls,
278
+ driftRatio: round2(t.thinkingTokens / Math.max(1, t.visibleOutputTokens)),
279
+ driftState: classifyTurnDrift(t)
280
+ });
281
+
282
+ const live = snapshot(cur);
283
+ if (ev.eventType === 'turn.complete') {
284
+ if (live.thinkingTokens > 0 || live.visibleOutputTokens > 0 || live.ttftMs !== null) {
285
+ d.turns.push(live);
286
+ d.turns = d.turns.slice(-DRIFT_THRESHOLDS.HISTORY);
287
+ }
288
+ d.current = null;
289
+ }
290
+
291
+ // Evaluate over completed turns plus the in-flight turn (catches loops mid-turn).
292
+ const series = ev.eventType === 'turn.complete' ? d.turns : [...d.turns, live];
293
+ const scored = series.filter((t) => t.thinkingTokens > 0 || t.visibleOutputTokens > 0);
294
+ const last = scored[scored.length - 1] || null;
295
+ const rolling = scored.slice(-DRIFT_THRESHOLDS.ROLLING_WINDOW);
296
+ const ttfts = series.map((t) => t.ttftMs).filter((v) => typeof v === 'number');
297
+
298
+ d.measured = scored.some((t) => t.thinkingTokens > 0);
299
+ d.loop = evaluateThinkingDriftLoop(scored);
300
+ d.lastTtftMs = ttfts.length ? ttfts[ttfts.length - 1] : null;
301
+ d.avgTtftMs = ttfts.length ? Math.round(ttfts.reduce((a, b) => a + b, 0) / ttfts.length) : null;
302
+ d.lastDriftRatio = d.measured && last ? last.driftRatio : null;
303
+ d.rollingDriftRatio = d.measured
304
+ ? round2(rolling.reduce((a, t) => a + t.thinkingTokens, 0) / Math.max(1, rolling.reduce((a, t) => a + t.visibleOutputTokens, 0)))
305
+ : null;
306
+ d.driftState = !d.measured
307
+ ? 'n/a'
308
+ : d.loop.triggered ? 'loop_detected' : (last && last.driftState === 'elevated' ? 'elevated' : 'nominal');
309
+ return d;
310
+ }
311
+
312
+ export function formatTtft(ms) {
313
+ if (typeof ms !== 'number' || !Number.isFinite(ms)) return '—';
314
+ if (ms < 1000) return `${Math.round(ms)}ms`;
315
+ if (ms < 60000) return `${(ms / 1000).toFixed(1)}s`;
316
+ return `${Math.floor(ms / 60000)}m${Math.round((ms % 60000) / 1000)}s`;
317
+ }
318
+
319
+ export function formatDriftCompact(d = {}) {
320
+ if (!d || !d.measured || d.lastDriftRatio === null || d.lastDriftRatio === undefined) return 'Think —';
321
+ if (d.driftState === 'loop_detected') return `!LOOP ${d.lastDriftRatio}x`;
322
+ return `Think ${d.lastDriftRatio}x`;
323
+ }
324
+
325
+ export function formatDriftLabel(d = {}) {
326
+ return `${formatDriftCompact(d)} · TTFT ${formatTtft(d?.lastTtftMs)}`;
327
+ }
@@ -0,0 +1,152 @@
1
+ /**
2
+ * Sprint 2.1 (Claude Code) — Subagent lifecycle & worktree topology.
3
+ *
4
+ * Pure ESM, zero `node:*` imports (Mod-safe). Derives per-`agentId` lifecycle from the
5
+ * telemetry bridge's `state.subagents` / `state.subagentInFlightTurns` maps:
6
+ * - `working` : in-flight turn, or activity within the idle window (default 30s)
7
+ * - `waiting` : idle longer than the window with no completion seen (parked, $0)
8
+ * - `completed` : the subagent's final `turn.complete` was observed and nothing since
9
+ * Worktree / branch metadata is only reported when the host event supplied it.
10
+ */
11
+
12
+ export const SWARM_LIFECYCLE_CONSTANTS = Object.freeze({
13
+ IDLE_WINDOW_MS: 30000,
14
+ MAX_WORKERS: 24
15
+ });
16
+
17
+ function str(v) {
18
+ return typeof v === 'string' && v.trim() ? v.trim() : null;
19
+ }
20
+
21
+ /**
22
+ * Extracts optional worktree / branch / model metadata from a mod turn event.
23
+ */
24
+ export function extractAgentLocation(event = {}) {
25
+ const ev = event && typeof event === 'object' ? event : {};
26
+ return {
27
+ model: str(ev.model) || str(ev.result?.model),
28
+ worktree: str(ev.worktree) || str(ev.worktreePath) || str(ev.worktree_path) || str(ev.cwd) || null,
29
+ branch: str(ev.gitBranch) || str(ev.git_branch) || str(ev.branch) || null
30
+ };
31
+ }
32
+
33
+ /**
34
+ * Mutates a `state.subagents[agentKey]` record with lifecycle + location fields.
35
+ */
36
+ export function applySubagentLifecycle(sub, event = {}, { nowMs = 0, eventType = 'turn.step' } = {}) {
37
+ if (!sub || typeof sub !== 'object') return sub;
38
+ const loc = extractAgentLocation(event);
39
+ if (loc.model) sub.model = loc.model;
40
+ if (loc.worktree) sub.worktree = loc.worktree;
41
+ if (loc.branch) sub.branch = loc.branch;
42
+ if (!sub.firstSeenAt) sub.firstSeenAt = nowMs || sub.lastActiveAt || 0;
43
+ if (eventType === 'turn.complete') {
44
+ sub.completedAt = nowMs || sub.lastActiveAt || 0;
45
+ } else {
46
+ sub.completedAt = null;
47
+ }
48
+ return sub;
49
+ }
50
+
51
+ /**
52
+ * Builds the swarm summary rendered by the Pane and statusLine.
53
+ */
54
+ export function computeSwarmSummary(state = {}, {
55
+ nowMs = Date.now(),
56
+ idleWindowMs = SWARM_LIFECYCLE_CONSTANTS.IDLE_WINDOW_MS
57
+ } = {}) {
58
+ const subs = state && typeof state.subagents === 'object' && state.subagents ? state.subagents : {};
59
+ const inFlight = state && typeof state.subagentInFlightTurns === 'object' && state.subagentInFlightTurns
60
+ ? state.subagentInFlightTurns
61
+ : {};
62
+
63
+ const workers = Object.values(subs)
64
+ .filter((s) => s && typeof s === 'object' && s.agentId)
65
+ .map((s) => {
66
+ const lastActive = Number(s.lastActiveAt) || 0;
67
+ const idleMs = lastActive > 0 ? Math.max(0, nowMs - lastActive) : null;
68
+ let lifecycle;
69
+ if (inFlight[s.agentId]) lifecycle = 'working';
70
+ else if (s.completedAt && Number(s.completedAt) >= lastActive) lifecycle = 'completed';
71
+ else if (idleMs !== null && idleMs <= idleWindowMs) lifecycle = 'working';
72
+ else lifecycle = 'waiting';
73
+ return {
74
+ agentId: String(s.agentId),
75
+ state: lifecycle,
76
+ idleSec: idleMs === null ? null : Math.round(idleMs / 1000),
77
+ turns: Number(s.turns) || 0,
78
+ totalTokens: Number(s.totalTokens) || 0,
79
+ model: s.model || null,
80
+ worktree: s.worktree || null,
81
+ branch: s.branch || null
82
+ };
83
+ })
84
+ .sort((a, b) => (a.state === b.state ? b.totalTokens - a.totalTokens : (a.state === 'working' ? -1 : b.state === 'working' ? 1 : 0)))
85
+ .slice(0, SWARM_LIFECYCLE_CONSTANTS.MAX_WORKERS);
86
+
87
+ const counts = { working: 0, waiting: 0, completed: 0 };
88
+ for (const w of workers) counts[w.state] = (counts[w.state] || 0) + 1;
89
+ const live = counts.working + counts.waiting;
90
+
91
+ const wtMap = new Map();
92
+ const mainLoc = { worktree: str(state?.cwd) || str(state?.workspace) || null, branch: str(state?.gitBranch) || null };
93
+ if (mainLoc.worktree || mainLoc.branch) wtMap.set(`${mainLoc.worktree || ''}|${mainLoc.branch || ''}`, { ...mainLoc, agents: ['main'] });
94
+ for (const w of workers) {
95
+ if (!w.worktree && !w.branch) continue;
96
+ const key = `${w.worktree || ''}|${w.branch || ''}`;
97
+ const entry = wtMap.get(key) || { worktree: w.worktree, branch: w.branch, agents: [] };
98
+ entry.agents.push(w.agentId);
99
+ wtMap.set(key, entry);
100
+ }
101
+ const worktrees = Array.from(wtMap.values());
102
+
103
+ const parts = [];
104
+ if (live > 0) parts.push(`${live} live (${counts.working} working · ${counts.waiting} parked)`);
105
+ if (counts.completed > 0) parts.push(`${counts.completed} done`);
106
+ if (worktrees.length > 1) parts.push(`${worktrees.length} worktrees`);
107
+
108
+ return {
109
+ active: workers.length > 0,
110
+ live,
111
+ counts: { ...counts, total: workers.length },
112
+ workers,
113
+ worktrees,
114
+ worktreeCount: worktrees.length,
115
+ label: parts.length > 0 ? parts.join(' · ') : 'Solo'
116
+ };
117
+ }
118
+
119
+ /**
120
+ * Compact statusLine token: `Swarm 3W` (live workers) / '' when solo.
121
+ */
122
+ export function formatSwarmCompact(summary) {
123
+ if (!summary || !summary.live) return '';
124
+ return `Swarm ${summary.live}W`;
125
+ }
126
+
127
+ /**
128
+ * Converts the CC summary into the shared `/cost-radar` topology shape.
129
+ */
130
+ export function toCostRadarTopology(summary) {
131
+ if (!summary || !summary.active) return null;
132
+ const stateMap = { working: 'working', waiting: 'waiting', completed: 'killed' };
133
+ return {
134
+ workers: summary.workers.map((w) => ({
135
+ name: w.agentId,
136
+ state: stateMap[w.state] || 'waiting',
137
+ parked: w.state === 'waiting',
138
+ model: w.model || 'inherit',
139
+ workspace: w.branch || (w.worktree ? 'worktree' : 'inherit')
140
+ })),
141
+ worktrees: summary.worktrees.map((t, idx) => ({
142
+ path: t.worktree || '',
143
+ branch: t.branch || null,
144
+ name: t.worktree || t.branch || `wt-${idx}`,
145
+ isMain: idx === 0,
146
+ detached: false,
147
+ locked: false,
148
+ prunable: false
149
+ })),
150
+ scopeLocks: { leaseCount: 0, collisions: [] }
151
+ };
152
+ }