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,657 @@
1
+ /**
2
+ * @file src/utils/sessionCalibration.mjs
3
+ * Read-only Stop-hook session transcript calibrator for Claude Code (`DET-08`).
4
+ *
5
+ * Counts completed interactive turns (`turnsCompleted`), unique API calls (`apiCallsCompleted`),
6
+ * initial session prefix tokens, and the rolling median output tokens across the most recent
7
+ * turns, persisting compact numeric state outside `<cwd>` under
8
+ * `~/.attention-horizon/cache/sessions/cal_<sessionId>.json`.
9
+ */
10
+
11
+ import { fs, path, os, readJsonSafe, writeJsonAtomic } from './nodeIo.mjs';
12
+
13
+ export const ROLLING_OUTPUT_WINDOW = 10;
14
+ export const MIN_TRUSTED_OUTPUT_TURNS = 5;
15
+ export const DEFAULT_OUTPUT_SHRINKAGE_PRIOR_TOKENS = 500;
16
+ export const MIN_TRUSTED_RPT_TURNS = 5;
17
+ export const DEFAULT_RPT_SHRINKAGE_PRIOR = 2.0;
18
+ export const RPT_AGREEMENT_MAX_RELATIVE_SPREAD = 0.25;
19
+ export const OUTPUT_SHRINKAGE_PRIOR_METADATA = Object.freeze({
20
+ priorTokens: DEFAULT_OUTPUT_SHRINKAGE_PRIOR_TOKENS,
21
+ minTrustedTurns: MIN_TRUSTED_OUTPUT_TURNS,
22
+ effectivePseudoCountExampleAtN2: MIN_TRUSTED_OUTPUT_TURNS - 2,
23
+ isPlaceholderPrior: true,
24
+ provenance: 'placeholder_engineering_heuristic_midpoint_not_claude_code_telemetry',
25
+ description:
26
+ 'Heuristic 500-token output midpoint over a 5-turn ramp (effective k = minTrustedTurns - n, e.g. k = 3 at n = 2); not derived from Claude Code telemetry.'
27
+ });
28
+ export const RPT_SHRINKAGE_PRIOR_METADATA = Object.freeze({
29
+ priorRequestsPerTurn: DEFAULT_RPT_SHRINKAGE_PRIOR,
30
+ minTrustedTurns: MIN_TRUSTED_RPT_TURNS,
31
+ agreementReducedMinTurns: Number((MIN_TRUSTED_RPT_TURNS / 2).toFixed(2)),
32
+ agreementMaxRelativeSpread: RPT_AGREEMENT_MAX_RELATIVE_SPREAD,
33
+ localTranscriptOverrideMinSessions: 3,
34
+ effectivePseudoCountExampleAtN2: MIN_TRUSTED_RPT_TURNS - 2,
35
+ isPlaceholderPrior: true,
36
+ provenance: 'placeholder_single_tool_round_rpt_prior_2.0_not_empirical_evidence',
37
+ description:
38
+ 'Placeholder rationale of 2.0 requests/turn (1 tool round + 1 reply, not empirical evidence) over a 5-turn ramp (halved to 2.5 when >= 2 observed turns agree within 25% spread, w = 0.8 at n = 2), overridden once >= 3 non-current, non-benchmark local Claude Code transcripts exist; replaces earlier 1.0 (0 tool calls) placeholder.'
39
+ });
40
+
41
+ /**
42
+ * Linearly shrink an early rolling output median toward a conservative placeholder prior
43
+ * until `minTrustedTurns` turns of output have been observed.
44
+ */
45
+ export function shrinkRollingOutputEstimate(rollingMedian, sampleSize, options = {}) {
46
+ const minTurnsRaw = Number(options.minTrustedTurns);
47
+ const minTrustedTurns =
48
+ Number.isFinite(minTurnsRaw) && minTurnsRaw > 0
49
+ ? Math.round(minTurnsRaw)
50
+ : MIN_TRUSTED_OUTPUT_TURNS;
51
+ const priorRaw = Number(options.priorTokens);
52
+ const priorTokens =
53
+ Number.isFinite(priorRaw) && priorRaw > 0
54
+ ? Math.round(priorRaw)
55
+ : DEFAULT_OUTPUT_SHRINKAGE_PRIOR_TOKENS;
56
+ const count = Math.max(0, Math.round(Number(sampleSize) || 0));
57
+ const rawMedian = Number(rollingMedian);
58
+ if (!Number.isFinite(rawMedian) || rawMedian <= 0 || count === 0) {
59
+ return {
60
+ expectedOutputTokens: priorTokens,
61
+ rawRollingMedianOutputTokens: null,
62
+ sampleSize: 0,
63
+ shrinkageWeight: 0,
64
+ minTrustedTurns,
65
+ priorTokens,
66
+ effectiveSmoothingK: minTrustedTurns,
67
+ isPlaceholderShrinkagePrior: true,
68
+ shrinkagePriorProvenance: OUTPUT_SHRINKAGE_PRIOR_METADATA.provenance,
69
+ source: 'shrinkage_prior_default'
70
+ };
71
+ }
72
+ const weight = Math.min(1, count / minTrustedTurns);
73
+ const blended = Math.round(weight * rawMedian + (1 - weight) * priorTokens);
74
+ return {
75
+ expectedOutputTokens: Math.max(1, blended),
76
+ rawRollingMedianOutputTokens: Math.round(rawMedian),
77
+ sampleSize: count,
78
+ shrinkageWeight: Number(weight.toFixed(4)),
79
+ minTrustedTurns,
80
+ priorTokens,
81
+ effectiveSmoothingK: Math.max(0, minTrustedTurns - Math.min(minTrustedTurns, count)),
82
+ isPlaceholderShrinkagePrior: true,
83
+ shrinkagePriorProvenance: OUTPUT_SHRINKAGE_PRIOR_METADATA.provenance,
84
+ source: weight < 1 ? 'stop_hook_shrunk_median' : 'stop_hook_rolling_median'
85
+ };
86
+ }
87
+
88
+ /**
89
+ * Sanitizes a session ID for safe cache filenames.
90
+ * @param {string} [sessionId='default']
91
+ * @returns {string}
92
+ */
93
+ function sanitizeSessionId(sessionId = 'default') {
94
+ const cleaned = String(sessionId || 'default')
95
+ .trim()
96
+ .replace(/[^a-zA-Z0-9_-]/g, '_');
97
+ return cleaned || 'default';
98
+ }
99
+
100
+ /**
101
+ * Resolves the user home directory across options, `HOME`, `USERPROFILE`, and `os.homedir()`.
102
+ * @param {object} [options={}]
103
+ * @returns {string}
104
+ */
105
+ export function resolveCalibrationHomeDir(options = {}) {
106
+ return (
107
+ options.homeDir ||
108
+ globalThis.process?.env?.HOME ||
109
+ globalThis.process?.env?.USERPROFILE ||
110
+ os.homedir()
111
+ );
112
+ }
113
+
114
+ /**
115
+ * Computes the rounded integer median of positive finite numbers over the trailing window.
116
+ * @param {number[]} [values=[]]
117
+ * @param {number} [windowSize=ROLLING_OUTPUT_WINDOW]
118
+ * @returns {number | null}
119
+ */
120
+ export function computeRollingMedian(values = [], windowSize = ROLLING_OUTPUT_WINDOW) {
121
+ const nums = (Array.isArray(values) ? values : [])
122
+ .map((v) => Number(v))
123
+ .filter((v) => Number.isFinite(v) && v > 0);
124
+ if (nums.length === 0) return null;
125
+ const recent = nums.slice(-Math.max(1, Number(windowSize) || ROLLING_OUTPUT_WINDOW));
126
+ recent.sort((a, b) => a - b);
127
+ const mid = Math.floor(recent.length / 2);
128
+ return recent.length % 2 === 1
129
+ ? Math.round(recent[mid])
130
+ : Math.round((recent[mid - 1] + recent[mid]) / 2);
131
+ }
132
+
133
+ /**
134
+ * Computes the floating-point median of positive finite numbers over the trailing window (4 decimals).
135
+ * @param {number[]} [values=[]]
136
+ * @param {number} [windowSize=ROLLING_OUTPUT_WINDOW]
137
+ * @returns {number | null}
138
+ */
139
+ export function computeRollingMedianFloat(values = [], windowSize = ROLLING_OUTPUT_WINDOW) {
140
+ const nums = (Array.isArray(values) ? values : [])
141
+ .map((v) => Number(v))
142
+ .filter((v) => Number.isFinite(v) && v > 0);
143
+ if (nums.length === 0) return null;
144
+ const recent = nums.slice(-Math.max(1, Number(windowSize) || ROLLING_OUTPUT_WINDOW));
145
+ recent.sort((a, b) => a - b);
146
+ const mid = Math.floor(recent.length / 2);
147
+ const med = recent.length % 2 === 1 ? recent[mid] : (recent[mid - 1] + recent[mid]) / 2;
148
+ return Number(med.toFixed(4));
149
+ }
150
+
151
+ /**
152
+ * Computes the rounded integer median of non-negative finite numbers over the trailing window.
153
+ * @param {number[]} [values=[]]
154
+ * @param {number} [windowSize=ROLLING_OUTPUT_WINDOW]
155
+ * @returns {number | null}
156
+ */
157
+ export function computeRollingMedianNonNegative(values = [], windowSize = ROLLING_OUTPUT_WINDOW) {
158
+ const nums = (Array.isArray(values) ? values : [])
159
+ .map((v) => Number(v))
160
+ .filter((v) => Number.isFinite(v) && v >= 0);
161
+ if (nums.length === 0) return null;
162
+ const recent = nums.slice(-Math.max(1, Number(windowSize) || ROLLING_OUTPUT_WINDOW));
163
+ recent.sort((a, b) => a - b);
164
+ const mid = Math.floor(recent.length / 2);
165
+ return recent.length % 2 === 1
166
+ ? Math.round(recent[mid])
167
+ : Math.round((recent[mid - 1] + recent[mid]) / 2);
168
+ }
169
+
170
+ /**
171
+ * Linearly shrinks an early rolling requests/turn median toward a prior (`2.0` structural tool-round
172
+ * placeholder, or median `requests/turn` over >= 1 local deduplicated Claude Code transcript).
173
+ * When `>= 2` observed turns agree closely (relative spread `(max - min) / med <= maxSpread`),
174
+ * halves the effective shrinkage horizon (`Math.max(2, minTrustedTurns / 2)`, i.e. `2.5` at default `5`,
175
+ * giving `w = 0.8` at `n = 2`).
176
+ *
177
+ * @param {number | null} rollingMedianRpt
178
+ * @param {number} sampleSize
179
+ * @param {object} [options={}]
180
+ */
181
+ export function shrinkRollingRequestsPerTurn(rollingMedianRpt, sampleSize, options = {}) {
182
+ const minTurnsRaw = Number(options.minTrustedTurns);
183
+ const minTrustedTurns =
184
+ Number.isFinite(minTurnsRaw) && minTurnsRaw > 0
185
+ ? Math.round(minTurnsRaw)
186
+ : MIN_TRUSTED_RPT_TURNS;
187
+ const maxSpreadRaw = Number(options.agreementMaxRelativeSpread);
188
+ const maxSpread =
189
+ Number.isFinite(maxSpreadRaw) && maxSpreadRaw >= 0
190
+ ? maxSpreadRaw
191
+ : RPT_AGREEMENT_MAX_RELATIVE_SPREAD;
192
+ const hasLocalPrior =
193
+ options.priorSource === 'local_transcripts' &&
194
+ Number.isFinite(Number(options.priorRequestsPerTurn)) &&
195
+ Number(options.priorRequestsPerTurn) >= 1;
196
+ const priorRaw = Number(options.priorRequestsPerTurn);
197
+ const priorRequestsPerTurn =
198
+ Number.isFinite(priorRaw) && priorRaw > 0
199
+ ? Number(priorRaw.toFixed(4))
200
+ : DEFAULT_RPT_SHRINKAGE_PRIOR;
201
+ const isPlaceholderShrinkagePrior = !hasLocalPrior;
202
+ const shrinkagePriorProvenance = hasLocalPrior
203
+ ? 'local_claude_code_transcripts_median_rpt'
204
+ : RPT_SHRINKAGE_PRIOR_METADATA.provenance;
205
+
206
+ const recentCounts = Array.isArray(options.recentTurnRequestCounts)
207
+ ? options.recentTurnRequestCounts
208
+ .map((v) => Number(v))
209
+ .filter((v) => Number.isFinite(v) && v > 0)
210
+ .slice(-ROLLING_OUTPUT_WINDOW)
211
+ : [];
212
+ let turnsAgree = false;
213
+ if (recentCounts.length >= 2) {
214
+ const sortedCounts = [...recentCounts].sort((a, b) => a - b);
215
+ const mid = Math.floor(sortedCounts.length / 2);
216
+ const medR =
217
+ sortedCounts.length % 2 === 1
218
+ ? sortedCounts[mid]
219
+ : (sortedCounts[mid - 1] + sortedCounts[mid]) / 2;
220
+ const minR = sortedCounts[0];
221
+ const maxR = sortedCounts[sortedCounts.length - 1];
222
+ const relativeSpread = medR > 0 ? (maxR - minR) / medR : Infinity;
223
+ turnsAgree = relativeSpread <= maxSpread;
224
+ }
225
+
226
+ const effectiveMinTrustedTurns = turnsAgree
227
+ ? Math.max(2, Number((minTrustedTurns / 2).toFixed(4)))
228
+ : minTrustedTurns;
229
+
230
+ const count = Math.max(0, Math.round(Number(sampleSize) || 0));
231
+ const rawMedian = Number(rollingMedianRpt);
232
+ if (!Number.isFinite(rawMedian) || rawMedian <= 0 || count === 0) {
233
+ return {
234
+ expectedRequestsPerTurn: priorRequestsPerTurn,
235
+ rawRollingMedianRequestsPerTurn: null,
236
+ sampleSize: 0,
237
+ shrinkageWeight: 0,
238
+ minTrustedTurns,
239
+ effectiveMinTrustedTurns,
240
+ turnsAgree: false,
241
+ priorRequestsPerTurn,
242
+ effectiveSmoothingK: effectiveMinTrustedTurns,
243
+ isPlaceholderShrinkagePrior,
244
+ shrinkagePriorProvenance,
245
+ source: hasLocalPrior ? 'local_transcript_rpt_prior' : 'placeholder_rpt_prior_2.0'
246
+ };
247
+ }
248
+ const weight = Math.min(1, count / effectiveMinTrustedTurns);
249
+ const blended = Math.max(
250
+ 1,
251
+ Number((weight * rawMedian + (1 - weight) * priorRequestsPerTurn).toFixed(4))
252
+ );
253
+ return {
254
+ expectedRequestsPerTurn: blended,
255
+ rawRollingMedianRequestsPerTurn: Number(rawMedian.toFixed(4)),
256
+ sampleSize: count,
257
+ shrinkageWeight: Number(weight.toFixed(4)),
258
+ minTrustedTurns,
259
+ effectiveMinTrustedTurns,
260
+ turnsAgree,
261
+ priorRequestsPerTurn,
262
+ effectiveSmoothingK: Number(
263
+ Math.max(0, effectiveMinTrustedTurns - Math.min(effectiveMinTrustedTurns, count)).toFixed(4)
264
+ ),
265
+ isPlaceholderShrinkagePrior,
266
+ shrinkagePriorProvenance,
267
+ source:
268
+ weight >= 1
269
+ ? 'stop_hook_rolling_rpt_median'
270
+ : turnsAgree
271
+ ? 'stop_hook_agreed_shrunk_rpt_median'
272
+ : 'stop_hook_shrunk_rpt_median'
273
+ };
274
+ }
275
+
276
+ /**
277
+ * Resolves `~/.attention-horizon/cache/sessions/cal_<safeId>.json` (or explicit `options.calibrationPath`).
278
+ * @param {string} [sessionId='default']
279
+ * @param {object} [options={}]
280
+ * @returns {string}
281
+ */
282
+ export function getSessionCalibrationPath(sessionId = 'default', options = {}) {
283
+ if (typeof options.calibrationPath === 'string' && options.calibrationPath.trim()) {
284
+ return options.calibrationPath.trim();
285
+ }
286
+ const home = resolveCalibrationHomeDir(options);
287
+ const safeId = sanitizeSessionId(sessionId);
288
+ return path.join(home, '.attention-horizon', 'cache', 'sessions', `cal_${safeId}.json`);
289
+ }
290
+
291
+ /**
292
+ * Parses a Claude Code JSONL transcript read-only (`'r'`), deduplicating streaming assistant
293
+ * rows by `message.id` and extracting completed turn counts, rolling median output tokens,
294
+ * and initial prefix size without retaining any prompt or response prose.
295
+ *
296
+ * @param {string} transcriptPath
297
+ * @returns {{
298
+ * turnsCompleted: number,
299
+ * apiCallsCompleted: number,
300
+ * rollingMedianOutputTokens: number | null,
301
+ * rollingMedianOutputTokensPerCall: number | null,
302
+ * recentTurnOutputs: number[],
303
+ * initialPrefixTokens: number | null,
304
+ * latestContextTokens: number | null
305
+ * } | null}
306
+ */
307
+ /**
308
+ * Checks whether a Claude Code transcript `user` record represents a real human prompt
309
+ * (excluding tool results and synthetic `/model` or local-command UI rows).
310
+ * @param {object} obj
311
+ * @returns {boolean}
312
+ */
313
+ export function isRealHumanUserTranscriptEntry(obj) {
314
+ if (obj?.type !== 'user' || (obj?.message?.role !== 'user' && obj?.message)) {
315
+ return false;
316
+ }
317
+ if (obj?.isMeta === true || obj?.isCompactSummary === true) {
318
+ return false;
319
+ }
320
+ const content = obj?.message?.content;
321
+ if (typeof content === 'string') {
322
+ const trimmed = content.trim();
323
+ return (
324
+ trimmed.length > 0 &&
325
+ !/^<(?:local-command-|command-name>)/.test(trimmed) &&
326
+ !trimmed.startsWith('This session is being continued from a previous conversation')
327
+ );
328
+ }
329
+ return Array.isArray(content) && content.some((b) => b && b.type !== 'tool_result');
330
+ }
331
+
332
+ export function parseSessionTranscriptCalibration(transcriptPath) {
333
+ if (!transcriptPath || typeof transcriptPath !== 'string' || !fs.existsSync(transcriptPath)) {
334
+ return null;
335
+ }
336
+ let fd = null;
337
+ let raw = '';
338
+ try {
339
+ fd = fs.openSync(transcriptPath, 'r');
340
+ raw = fs.readFileSync(fd, 'utf8');
341
+ } catch {
342
+ return null;
343
+ } finally {
344
+ if (fd !== null) {
345
+ try {
346
+ fs.closeSync(fd);
347
+ } catch {
348
+ // Ignore close errors on read-only transcript fd
349
+ }
350
+ }
351
+ }
352
+
353
+ let currentTurnBucket = 0;
354
+ const byMsgId = new Map();
355
+ let lineIdx = 0;
356
+
357
+ for (const line of raw.split(/\r?\n/)) {
358
+ lineIdx += 1;
359
+ if (!line || !line.trim()) continue;
360
+ let obj;
361
+ try {
362
+ obj = JSON.parse(line);
363
+ } catch {
364
+ continue;
365
+ }
366
+
367
+ if (isRealHumanUserTranscriptEntry(obj)) {
368
+ currentTurnBucket += 1;
369
+ continue;
370
+ }
371
+
372
+ if (obj?.type === 'assistant' && obj?.message?.usage) {
373
+ const msg = obj.message;
374
+ const u = msg.usage;
375
+ const msgId = msg.id ? String(msg.id) : `anon_line_${lineIdx}`;
376
+ const prev = byMsgId.get(msgId);
377
+ const outTok = Number(u.output_tokens || 0);
378
+ const inTok = Number(u.input_tokens || 0);
379
+ const cwTok = Number(u.cache_creation_input_tokens || 0);
380
+ const crTok = Number(u.cache_read_input_tokens || 0);
381
+ const turnBucket = prev ? prev.turnBucket : currentTurnBucket > 0 ? currentTurnBucket : byMsgId.size + 1;
382
+
383
+ if (!prev) {
384
+ byMsgId.set(msgId, {
385
+ turnBucket,
386
+ outputTokens: outTok,
387
+ inputTokens: inTok,
388
+ cacheCreationTokens: cwTok,
389
+ cacheReadTokens: crTok
390
+ });
391
+ } else {
392
+ byMsgId.set(msgId, {
393
+ turnBucket: prev.turnBucket,
394
+ outputTokens: Math.max(prev.outputTokens, outTok),
395
+ inputTokens: outTok >= prev.outputTokens ? inTok : prev.inputTokens,
396
+ cacheCreationTokens: outTok >= prev.outputTokens ? cwTok : prev.cacheCreationTokens,
397
+ cacheReadTokens: outTok >= prev.outputTokens ? crTok : prev.cacheReadTokens
398
+ });
399
+ }
400
+ }
401
+ }
402
+
403
+ const orderedMsgs = Array.from(byMsgId.values());
404
+ const perCallOutputs = orderedMsgs.map((m) => m.outputTokens);
405
+ const turnSums = new Map();
406
+ const turnCallCounts = new Map();
407
+ const turnMsgGroups = new Map();
408
+ for (const m of orderedMsgs) {
409
+ turnSums.set(m.turnBucket, (turnSums.get(m.turnBucket) || 0) + m.outputTokens);
410
+ turnCallCounts.set(m.turnBucket, (turnCallCounts.get(m.turnBucket) || 0) + 1);
411
+ if (!turnMsgGroups.has(m.turnBucket)) turnMsgGroups.set(m.turnBucket, []);
412
+ turnMsgGroups.get(m.turnBucket).push(m);
413
+ }
414
+ const sortedTurnGroups = Array.from(turnMsgGroups.entries()).sort((a, b) => a[0] - b[0]);
415
+ const turnPromptGrowths = [];
416
+ let prevEndContext = null;
417
+ for (const [, msgs] of sortedTurnGroups) {
418
+ const firstMsgInTurn = msgs[0];
419
+ const lastMsgInTurn = msgs[msgs.length - 1];
420
+ const firstPrompt =
421
+ firstMsgInTurn.inputTokens +
422
+ firstMsgInTurn.cacheCreationTokens +
423
+ firstMsgInTurn.cacheReadTokens;
424
+ const endContext =
425
+ lastMsgInTurn.inputTokens +
426
+ lastMsgInTurn.cacheCreationTokens +
427
+ lastMsgInTurn.cacheReadTokens +
428
+ lastMsgInTurn.outputTokens;
429
+ const prevBoundary = prevEndContext === null ? firstPrompt : prevEndContext;
430
+ const growth = endContext - prevBoundary;
431
+ if (Number.isFinite(growth) && growth >= 0) {
432
+ turnPromptGrowths.push(Math.round(growth));
433
+ }
434
+ prevEndContext = endContext;
435
+ }
436
+ const turnOutputs = Array.from(turnSums.values());
437
+ const turnRequestCounts = Array.from(turnCallCounts.values());
438
+ const recentTurnOutputs = turnOutputs.slice(-ROLLING_OUTPUT_WINDOW);
439
+ const recentTurnRequestCounts = turnRequestCounts.slice(-ROLLING_OUTPUT_WINDOW);
440
+ const recentTurnPromptGrowths = turnPromptGrowths.slice(-ROLLING_OUTPUT_WINDOW);
441
+
442
+ const firstMsg = orderedMsgs[0] || null;
443
+ const lastMsg = orderedMsgs[orderedMsgs.length - 1] || null;
444
+ const initialPrefixTokens = firstMsg
445
+ ? firstMsg.inputTokens + firstMsg.cacheCreationTokens + firstMsg.cacheReadTokens
446
+ : null;
447
+ const latestContextTokens = lastMsg
448
+ ? lastMsg.inputTokens +
449
+ lastMsg.cacheCreationTokens +
450
+ lastMsg.cacheReadTokens +
451
+ lastMsg.outputTokens
452
+ : null;
453
+
454
+ const turnsCompleted = turnOutputs.length;
455
+ const apiCallsCompleted = byMsgId.size;
456
+ return {
457
+ turnsCompleted,
458
+ apiCallsCompleted,
459
+ outputSampleSize: recentTurnOutputs.length,
460
+ rptSampleSize: recentTurnRequestCounts.length,
461
+ promptGrowthSampleSize: recentTurnPromptGrowths.length,
462
+ requestsPerTurn:
463
+ turnsCompleted > 0 && apiCallsCompleted > 0
464
+ ? Number((apiCallsCompleted / turnsCompleted).toFixed(4))
465
+ : null,
466
+ rollingMedianRequestsPerTurn: computeRollingMedianFloat(
467
+ recentTurnRequestCounts,
468
+ ROLLING_OUTPUT_WINDOW
469
+ ),
470
+ recentTurnRequestCounts,
471
+ rollingMedianOutputTokens: computeRollingMedian(recentTurnOutputs, ROLLING_OUTPUT_WINDOW),
472
+ rollingMedianOutputTokensPerCall: computeRollingMedian(perCallOutputs, ROLLING_OUTPUT_WINDOW),
473
+ recentTurnOutputs,
474
+ rollingMedianPromptGrowthTokens: computeRollingMedianNonNegative(
475
+ recentTurnPromptGrowths,
476
+ ROLLING_OUTPUT_WINDOW
477
+ ),
478
+ recentTurnPromptGrowths,
479
+ initialPrefixTokens:
480
+ Number.isFinite(initialPrefixTokens) && initialPrefixTokens > 0 ? initialPrefixTokens : null,
481
+ latestContextTokens:
482
+ Number.isFinite(latestContextTokens) && latestContextTokens > 0 ? latestContextTokens : null
483
+ };
484
+ }
485
+
486
+ /**
487
+ * Updates persisted Stop-hook calibration metrics from `event.transcript_path` or direct `output_tokens`.
488
+ *
489
+ * @param {object} [event={}]
490
+ * @param {object} [options={}]
491
+ * @returns {object | null}
492
+ */
493
+ export function updateSessionCalibrationOnStop(event = {}, options = {}) {
494
+ const sessionId = event.session_id || event.sessionId || 'default';
495
+ const calPath = getSessionCalibrationPath(sessionId, options);
496
+ const nowMs = Number.isFinite(Number(options.nowMs)) ? Number(options.nowMs) : Date.now();
497
+ const txPath = event.transcript_path || event.transcriptPath;
498
+
499
+ if (typeof txPath === 'string' && txPath.trim() && fs.existsSync(txPath)) {
500
+ const parsed = parseSessionTranscriptCalibration(txPath);
501
+ if (parsed) {
502
+ const record = {
503
+ sessionId,
504
+ updatedAtMs: nowMs,
505
+ source: 'stop_transcript',
506
+ ...parsed
507
+ };
508
+ writeJsonAtomic(calPath, record, options);
509
+ return record;
510
+ }
511
+ }
512
+
513
+ const stopHookActive = Boolean(event.stop_hook_active ?? event.stopHookActive);
514
+ const directOut = Number(
515
+ event.output_tokens ?? event.outputTokens ?? event.usage?.output_tokens ?? 0
516
+ );
517
+ if (!stopHookActive && Number.isFinite(directOut) && directOut > 0) {
518
+ const prev = readJsonSafe(calPath, null, options);
519
+ const prevOutputs = Array.isArray(prev?.recentTurnOutputs) ? prev.recentTurnOutputs : [];
520
+ const recentTurnOutputs = [...prevOutputs, Math.round(directOut)].slice(-ROLLING_OUTPUT_WINDOW);
521
+ const prevRpts = Array.isArray(prev?.recentTurnRequestCounts) ? prev.recentTurnRequestCounts : [];
522
+ const directRptRaw = Number(event.requests_in_turn ?? event.requestsInTurn ?? 1);
523
+ const directRpt = Number.isFinite(directRptRaw) && directRptRaw >= 1 ? Math.round(directRptRaw) : 1;
524
+ const recentTurnRequestCounts = [...prevRpts, directRpt].slice(-ROLLING_OUTPUT_WINDOW);
525
+ const directContextRaw = Number(event.context_tokens ?? event.contextTokens ?? 0);
526
+ const prevGrowths = Array.isArray(prev?.recentTurnPromptGrowths) ? prev.recentTurnPromptGrowths : [];
527
+ let recentTurnPromptGrowths = prevGrowths;
528
+ let latestContextTokens = prev?.latestContextTokens ?? null;
529
+ if (Number.isFinite(directContextRaw) && directContextRaw > 0) {
530
+ const roundedCtx = Math.round(directContextRaw);
531
+ if (Number.isFinite(Number(prev?.latestContextTokens)) && Number(prev.latestContextTokens) > 0) {
532
+ const delta = roundedCtx - Number(prev.latestContextTokens);
533
+ if (delta >= 0) {
534
+ recentTurnPromptGrowths = [...prevGrowths, delta].slice(-ROLLING_OUTPUT_WINDOW);
535
+ }
536
+ }
537
+ latestContextTokens = roundedCtx;
538
+ }
539
+ const turnsCompleted = Number(prev?.turnsCompleted || 0) + 1;
540
+ const apiCallsCompleted = Number(prev?.apiCallsCompleted || 0) + directRpt;
541
+ const record = {
542
+ sessionId,
543
+ updatedAtMs: nowMs,
544
+ source: 'stop_direct_usage',
545
+ turnsCompleted,
546
+ apiCallsCompleted,
547
+ outputSampleSize: recentTurnOutputs.length,
548
+ rptSampleSize: recentTurnRequestCounts.length,
549
+ promptGrowthSampleSize: recentTurnPromptGrowths.length,
550
+ requestsPerTurn:
551
+ turnsCompleted > 0 && apiCallsCompleted > 0
552
+ ? Number((apiCallsCompleted / turnsCompleted).toFixed(4))
553
+ : null,
554
+ rollingMedianRequestsPerTurn: computeRollingMedianFloat(
555
+ recentTurnRequestCounts,
556
+ ROLLING_OUTPUT_WINDOW
557
+ ),
558
+ recentTurnRequestCounts,
559
+ rollingMedianOutputTokens: computeRollingMedian(recentTurnOutputs, ROLLING_OUTPUT_WINDOW),
560
+ rollingMedianOutputTokensPerCall: computeRollingMedian(recentTurnOutputs, ROLLING_OUTPUT_WINDOW),
561
+ recentTurnOutputs,
562
+ rollingMedianPromptGrowthTokens: computeRollingMedianNonNegative(
563
+ recentTurnPromptGrowths,
564
+ ROLLING_OUTPUT_WINDOW
565
+ ),
566
+ recentTurnPromptGrowths,
567
+ initialPrefixTokens: prev?.initialPrefixTokens ?? null,
568
+ latestContextTokens
569
+ };
570
+ writeJsonAtomic(calPath, record, options);
571
+ return record;
572
+ }
573
+
574
+ return null;
575
+ }
576
+
577
+ /**
578
+ * Reads persisted Stop-hook calibration snapshot or falls back read-only to `event.transcript_path`.
579
+ *
580
+ * @param {string} [sessionId='default']
581
+ * @param {object} [event={}]
582
+ * @param {object} [options={}]
583
+ * @returns {object | null}
584
+ */
585
+ export function readSessionCalibration(sessionId = 'default', event = {}, options = {}) {
586
+ const canCheckCache = Boolean(
587
+ options.homeDir ||
588
+ options.calibrationPath ||
589
+ event.cwd ||
590
+ options.cwd ||
591
+ event.transcript_path ||
592
+ event.transcriptPath ||
593
+ event.session_id ||
594
+ event.sessionId
595
+ );
596
+
597
+ if (canCheckCache) {
598
+ const calPath = getSessionCalibrationPath(sessionId, options);
599
+ const cached = readJsonSafe(calPath, null, options);
600
+ if (cached && typeof cached === 'object') {
601
+ const sampleSize =
602
+ cached.outputSampleSize ??
603
+ (Array.isArray(cached.recentTurnOutputs)
604
+ ? cached.recentTurnOutputs.length
605
+ : Number(cached.turnsCompleted || 0));
606
+ const turns = Number(cached.turnsCompleted || 0);
607
+ const calls = Number(cached.apiCallsCompleted || 0);
608
+ const rpt =
609
+ cached.requestsPerTurn ??
610
+ (turns > 0 && calls > 0 ? Number((calls / turns).toFixed(4)) : null);
611
+ const rptSampleSize =
612
+ cached.rptSampleSize ??
613
+ (Array.isArray(cached.recentTurnRequestCounts)
614
+ ? cached.recentTurnRequestCounts.length
615
+ : turns);
616
+ const rollingMedianRequestsPerTurn =
617
+ cached.rollingMedianRequestsPerTurn ??
618
+ (Array.isArray(cached.recentTurnRequestCounts)
619
+ ? computeRollingMedianFloat(cached.recentTurnRequestCounts, ROLLING_OUTPUT_WINDOW)
620
+ : rpt);
621
+ const promptGrowthSampleSize =
622
+ cached.promptGrowthSampleSize ??
623
+ (Array.isArray(cached.recentTurnPromptGrowths) ? cached.recentTurnPromptGrowths.length : 0);
624
+ const rollingMedianPromptGrowthTokens =
625
+ cached.rollingMedianPromptGrowthTokens !== undefined
626
+ ? cached.rollingMedianPromptGrowthTokens
627
+ : Array.isArray(cached.recentTurnPromptGrowths)
628
+ ? computeRollingMedianNonNegative(cached.recentTurnPromptGrowths, ROLLING_OUTPUT_WINDOW)
629
+ : null;
630
+ return {
631
+ ...cached,
632
+ outputSampleSize: Number.isFinite(Number(sampleSize)) ? Number(sampleSize) : 0,
633
+ rptSampleSize: Number.isFinite(Number(rptSampleSize)) ? Number(rptSampleSize) : 0,
634
+ promptGrowthSampleSize: Number.isFinite(Number(promptGrowthSampleSize))
635
+ ? Number(promptGrowthSampleSize)
636
+ : 0,
637
+ requestsPerTurn: rpt,
638
+ rollingMedianRequestsPerTurn,
639
+ rollingMedianPromptGrowthTokens
640
+ };
641
+ }
642
+ }
643
+
644
+ const txPath = event.transcript_path || event.transcriptPath;
645
+ if (typeof txPath === 'string' && txPath.trim() && fs.existsSync(txPath)) {
646
+ const parsed = parseSessionTranscriptCalibration(txPath);
647
+ if (parsed) {
648
+ return {
649
+ sessionId,
650
+ source: 'transcript_fallback',
651
+ ...parsed
652
+ };
653
+ }
654
+ }
655
+
656
+ return null;
657
+ }