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,358 @@
1
+ /**
2
+ * @file src/core/session_timeline.mjs
3
+ * Pure, deterministic Session Timeline builder for the Simple View "Flight Recorder".
4
+ *
5
+ * Turns parsed transcript steps + classifier output into a per-turn picture of the
6
+ * conversation with GOOD / BAD / NEUTRAL practice markers, a cumulative-context line,
7
+ * baseline event markers (compact, checkpoint, model switch, cache-expired gap) and KPIs.
8
+ *
9
+ * Invariants: zero `node:*` imports, zero network, zero filesystem access, no model-generated text.
10
+ * Every reason string is a deterministic template.
11
+ */
12
+
13
+ export const TIMELINE_DEFAULTS = Object.freeze({
14
+ WINDOW_TURNS: 39,
15
+ CACHE_TTL_SEC: 300,
16
+ COLD_CLIFF_MIN_PREFIX_TOKENS: 50000,
17
+ SPIKE_TOKENS: 8000,
18
+ BURN_WINDOW_TURNS: 5,
19
+ MIN_TURNS_FOR_PROJECTION: 3,
20
+ CACHED_READ_DISCOUNT: 0.95,
21
+ INPUT_PRICE_PER_1M: 2.0
22
+ });
23
+
24
+ /** Practice taxonomy (kind decides bar color; text is the deterministic tooltip fragment). */
25
+ export const TIMELINE_TAGS = Object.freeze({
26
+ DUPLICATE_READ: { kind: 'bad', text: (n) => `Re-read a file in full${n > 1 ? ` ${n}\u00D7` : ''}` },
27
+ DEAD_ERROR: { kind: 'bad', text: (n) => `Error output left in context${n > 1 ? ` (${n} steps)` : ''}` },
28
+ SPIKE: { kind: 'bad', text: () => 'Single-step output spike' },
29
+ COMPACT_WHILE_WARM: { kind: 'bad', text: () => 'Compacted while cache was warm (lost the 95% discount)' },
30
+ MODEL_SWITCH_WARM: { kind: 'bad', text: () => 'Model/effort switched while cache was warm' },
31
+ COLD_CLIFF: { kind: 'bad', text: () => 'Resumed after cache expired with a large prefix' },
32
+ LINE_RANGE_READ: { kind: 'good', text: () => 'Read a line range instead of the full file' },
33
+ CHECKPOINT_SAVED: { kind: 'good', text: () => 'Saved a task.md checkpoint' },
34
+ COMPACT_WHILE_COLD: { kind: 'good', text: () => 'Compacted while cache was cold' },
35
+ SUBAGENT_DELEGATED: { kind: 'good', text: () => 'Delegated heavy work to a subagent' },
36
+ AUTO_FIX_FIRED: { kind: 'good', text: (n) => `Horizon auto-fix fired${n > 1 ? ` ${n}\u00D7` : ''}` }
37
+ });
38
+
39
+ const MARKER_LABELS = Object.freeze({
40
+ COMPACT: 'Compacted',
41
+ CHECKPOINT: 'task.md checkpoint',
42
+ MODEL_SWITCH: 'Model/effort switch',
43
+ COLD_GAP: 'Cache expired after idle gap'
44
+ });
45
+
46
+ function fmtK(n) {
47
+ const v = Math.max(0, Number(n) || 0);
48
+ if (v >= 1000000) return `${(v / 1000000).toFixed(1)}M`;
49
+ return `${(v / 1000).toFixed(1)}k`;
50
+ }
51
+
52
+ function isUserStep(s) {
53
+ return Boolean(s && (s.source === 'USER_EXPLICIT' || s.type === 'USER_INPUT' || s.role === 'user'));
54
+ }
55
+
56
+ function stepCalls(s) {
57
+ if (!s) return [];
58
+ if (Array.isArray(s.toolCalls)) return s.toolCalls;
59
+ if (Array.isArray(s.tool_calls)) return s.tool_calls;
60
+ return [];
61
+ }
62
+
63
+ function callName(c) {
64
+ return String(c?.name || c?.tool || '').toLowerCase();
65
+ }
66
+
67
+ function callArgs(c) {
68
+ return c?.args || c?.parameters || c?.Arguments || c?.input || {};
69
+ }
70
+
71
+ function callPath(c) {
72
+ const a = callArgs(c);
73
+ return String(
74
+ a.Path || a.path || a.TargetFile || a.Target || a.target || a.AbsolutePath || a.file_path || a.filePath || ''
75
+ );
76
+ }
77
+
78
+ const READ_TOOL_RE = /^(view_file|read_file|read)$/;
79
+ const OUTLINE_TOOL_RE = /^(view_file_outline|view_code_item)$/;
80
+ const WRITE_TOOL_RE = /^(write_to_file|write_file|edit_file|replace_file_content|multi_replace_file_content|write|edit|multiedit)$/;
81
+ const SUBAGENT_TOOL_RE = /^(invoke_subagent|task|agent)$/;
82
+ const CHECKPOINT_PATH_RE = /(^|[\\/])(task|handoff[^\\/]*)\.md$/i;
83
+
84
+ function isLineRangeRead(c) {
85
+ const n = callName(c);
86
+ if (OUTLINE_TOOL_RE.test(n)) return true;
87
+ if (!READ_TOOL_RE.test(n)) return false;
88
+ const a = callArgs(c);
89
+ return [a.StartLine, a.EndLine, a.start_line, a.end_line, a.offset, a.limit, a.startLine, a.endLine]
90
+ .some((v) => v !== undefined && v !== null && v !== '');
91
+ }
92
+
93
+ function tsMs(s) {
94
+ const raw = s?.createdAt || s?.timestamp || null;
95
+ if (!raw) return NaN;
96
+ const ms = typeof raw === 'number' ? raw : Date.parse(String(raw));
97
+ return Number.isFinite(ms) ? ms : NaN;
98
+ }
99
+
100
+ function finalizeTurn(t) {
101
+ const kinds = t.tags.map((k) => TIMELINE_TAGS[k]?.kind);
102
+ t.practice = kinds.includes('bad') ? 'bad' : (kinds.includes('good') ? 'good' : 'neutral');
103
+ const wanted = t.practice === 'neutral' ? [] : t.tags.filter((k) => TIMELINE_TAGS[k]?.kind === t.practice);
104
+ const texts = wanted.slice(0, 2).map((k) => TIMELINE_TAGS[k].text(t.tagCounts[k] || 1));
105
+ const head = `${fmtK(t.tokensAdded)} added`;
106
+ t.reason = texts.length > 0 ? `${head} \u00B7 ${texts.join(' \u00B7 ')}` : head;
107
+ }
108
+
109
+ function addTag(t, tag, count = 1) {
110
+ if (!TIMELINE_TAGS[tag]) return;
111
+ if (!t.tags.includes(tag)) t.tags.push(tag);
112
+ t.tagCounts[tag] = (t.tagCounts[tag] || 0) + count;
113
+ }
114
+
115
+ /**
116
+ * Builds the Session Timeline contract.
117
+ *
118
+ * @param {object} input
119
+ * @param {Array<object>} input.steps Parsed transcript steps (raw).
120
+ * @param {Array<{stepIndex:number,category:string,tokens:number,target?:string}>} input.classifiedSteps
121
+ * @param {Array<object>} [input.effortTransitions]
122
+ * @param {number} [input.safeLimit]
123
+ * @param {number} [input.totalActiveTokens]
124
+ * @param {(step:object)=>boolean} [input.isCompactionStep]
125
+ * @param {object} [input.options]
126
+ */
127
+ export function buildSessionTimeline(input = {}) {
128
+ const steps = Array.isArray(input.steps) ? input.steps : [];
129
+ const classified = new Map();
130
+ for (const c of Array.isArray(input.classifiedSteps) ? input.classifiedSteps : []) {
131
+ if (c && Number.isFinite(c.stepIndex)) classified.set(c.stepIndex, c);
132
+ }
133
+ const o = { ...TIMELINE_DEFAULTS, ...(input.options || {}) };
134
+ const ttl = Math.max(1, Number(o.CACHE_TTL_SEC) || TIMELINE_DEFAULTS.CACHE_TTL_SEC);
135
+ const safeLimit = Math.max(0, Number(input.safeLimit) || 0);
136
+ const isCompaction = typeof input.isCompactionStep === 'function' ? input.isCompactionStep : () => false;
137
+
138
+ const turns = [];
139
+ const markers = [];
140
+ const stepTurn = new Array(steps.length).fill(0);
141
+ const stepGap = new Array(steps.length).fill(null);
142
+ const coldCliffs = [];
143
+ let baseline = 0;
144
+ let running = 0;
145
+ let prevMs = NaN;
146
+ let hasTimestamps = false;
147
+ let cur = null;
148
+
149
+ const openTurn = (idx) => {
150
+ cur = {
151
+ turn: turns.length + 1,
152
+ firstStep: idx,
153
+ lastStep: idx,
154
+ hasUser: false,
155
+ tokensAdded: 0,
156
+ cumulative: 0,
157
+ startedAt: null,
158
+ endedAt: null,
159
+ cache: 'unknown',
160
+ tags: [],
161
+ tagCounts: {},
162
+ practice: 'neutral',
163
+ reason: ''
164
+ };
165
+ turns.push(cur);
166
+ };
167
+
168
+ for (let i = 0; i < steps.length; i++) {
169
+ const step = steps[i] || {};
170
+ const user = isUserStep(step);
171
+ if (!cur || (user && cur.hasUser)) openTurn(i);
172
+ if (user) cur.hasUser = true;
173
+ cur.lastStep = i;
174
+ stepTurn[i] = turns.length - 1;
175
+
176
+ const ms = tsMs(step);
177
+ let gap = null;
178
+ if (Number.isFinite(ms)) {
179
+ hasTimestamps = true;
180
+ if (Number.isFinite(prevMs)) gap = Math.max(0, (ms - prevMs) / 1000);
181
+ prevMs = ms;
182
+ const iso = new Date(ms).toISOString();
183
+ if (!cur.startedAt) cur.startedAt = iso;
184
+ cur.endedAt = iso;
185
+ }
186
+ stepGap[i] = gap;
187
+ if (i === cur.firstStep || (cur.cache === 'unknown' && gap !== null)) {
188
+ if (gap !== null) cur.cache = gap < ttl ? 'warm' : 'cold';
189
+ }
190
+
191
+ const cl = classified.get(i);
192
+ const tokens = Math.max(0, Number(cl?.tokens) || 0);
193
+ const cat = String(cl?.category || '');
194
+ if (cat === 'ANCHOR') {
195
+ baseline += tokens;
196
+ } else {
197
+ cur.tokensAdded += tokens;
198
+ running += tokens;
199
+ }
200
+
201
+ // Cold-cliff: resume after idle gap > TTL with a large prefix already in context.
202
+ const prefixBefore = baseline + running - (cat === 'ANCHOR' ? 0 : tokens);
203
+ if (gap !== null && gap > ttl && prefixBefore >= o.COLD_CLIFF_MIN_PREFIX_TOKENS && !cur.tags.includes('COLD_CLIFF')) {
204
+ addTag(cur, 'COLD_CLIFF');
205
+ coldCliffs.push({ turn: cur.turn, prefixTokens: prefixBefore, gapSec: Math.round(gap) });
206
+ markers.push({ turn: cur.turn, kind: 'COLD_GAP', label: `${MARKER_LABELS.COLD_GAP} (${Math.round(gap / 60)}m)` });
207
+ }
208
+
209
+ if (cat === 'STALE_DUPLICATE' && !String(cl?.target || '').startsWith('Older chat history')) {
210
+ addTag(cur, 'DUPLICATE_READ');
211
+ }
212
+ if (cat === 'DEAD_ERROR') addTag(cur, 'DEAD_ERROR');
213
+ if (i > 0 && cat !== 'ANCHOR' && cat !== '' && tokens >= o.SPIKE_TOKENS) addTag(cur, 'SPIKE');
214
+
215
+ for (const call of stepCalls(step)) {
216
+ const n = callName(call);
217
+ if (isLineRangeRead(call)) addTag(cur, 'LINE_RANGE_READ');
218
+ if (SUBAGENT_TOOL_RE.test(n)) addTag(cur, 'SUBAGENT_DELEGATED');
219
+ if (WRITE_TOOL_RE.test(n) && CHECKPOINT_PATH_RE.test(callPath(call))) {
220
+ addTag(cur, 'CHECKPOINT_SAVED');
221
+ markers.push({ turn: cur.turn, kind: 'CHECKPOINT', label: MARKER_LABELS.CHECKPOINT });
222
+ }
223
+ }
224
+
225
+ if (i > 0 && isCompaction(step)) {
226
+ if (gap === null) {
227
+ markers.push({ turn: cur.turn, kind: 'COMPACT', label: `${MARKER_LABELS.COMPACT} (cache state unknown)`, approx: true });
228
+ } else if (gap < ttl) {
229
+ addTag(cur, 'COMPACT_WHILE_WARM');
230
+ markers.push({ turn: cur.turn, kind: 'COMPACT', label: `${MARKER_LABELS.COMPACT} while warm` });
231
+ } else {
232
+ addTag(cur, 'COMPACT_WHILE_COLD');
233
+ markers.push({ turn: cur.turn, kind: 'COMPACT', label: `${MARKER_LABELS.COMPACT} while cold` });
234
+ }
235
+ }
236
+ cur.cumulative = baseline + running;
237
+ }
238
+
239
+ for (const tr of Array.isArray(input.effortTransitions) ? input.effortTransitions : []) {
240
+ const idx = Number(tr?.stepNumber ?? tr?.turnIndex);
241
+ if (!Number.isFinite(idx) || idx < 0 || idx >= steps.length) continue;
242
+ if (tr.fromLabel && tr.toLabel && tr.fromLabel === tr.toLabel) continue;
243
+ const t = turns[stepTurn[idx]];
244
+ if (!t) continue;
245
+ const gap = stepGap[idx];
246
+ const label = tr.toLabel ? `${MARKER_LABELS.MODEL_SWITCH} \u2192 ${tr.toLabel}` : MARKER_LABELS.MODEL_SWITCH;
247
+ if (gap !== null && gap < ttl) addTag(t, 'MODEL_SWITCH_WARM');
248
+ markers.push({ turn: t.turn, kind: 'MODEL_SWITCH', label });
249
+ }
250
+
251
+ for (const t of turns) finalizeTurn(t);
252
+
253
+ // Reconcile cumulative with the classifier's authoritative total (compaction can shrink context).
254
+ const total = Math.max(0, Number(input.totalActiveTokens) || 0);
255
+ const lastCum = turns.length ? turns[turns.length - 1].cumulative : 0;
256
+ let cumulativeScaled = false;
257
+ if (total > 0 && lastCum > total * 1.02) {
258
+ const k = total / lastCum;
259
+ for (const t of turns) t.cumulative = Math.round(t.cumulative * k);
260
+ cumulativeScaled = true;
261
+ }
262
+
263
+ const windowTurns = Math.max(1, Number(o.WINDOW_TURNS) || TIMELINE_DEFAULTS.WINDOW_TURNS);
264
+ const earlierCount = Math.max(0, turns.length - windowTurns);
265
+ const earlierTurns = turns.slice(0, earlierCount);
266
+ const kept = turns.slice(earlierCount);
267
+ const earlier = {
268
+ turns: earlierCount,
269
+ tokens: earlierTurns.reduce((s, t) => s + t.tokensAdded, 0),
270
+ bad: earlierTurns.filter((t) => t.practice === 'bad').length,
271
+ good: earlierTurns.filter((t) => t.practice === 'good').length
272
+ };
273
+ const firstKeptTurn = kept.length ? kept[0].turn : 1;
274
+ const keptMarkers = markers.filter((m) => m.turn >= firstKeptTurn);
275
+
276
+ const lossPerToken = (Number(o.INPUT_PRICE_PER_1M) / 1_000_000) * Number(o.CACHED_READ_DISCOUNT);
277
+ const coldRestartLossUsd = Number(
278
+ coldCliffs.reduce((s, c) => s + c.prefixTokens * lossPerToken, 0).toFixed(4)
279
+ );
280
+
281
+ const recent = turns.filter((t) => t.tokensAdded > 0).slice(-o.BURN_WINDOW_TURNS);
282
+ const burnRateTokens = recent.length >= 1
283
+ ? Math.round(recent.reduce((s, t) => s + t.tokensAdded, 0) / recent.length)
284
+ : 0;
285
+ const effectiveTotal = total > 0 ? total : lastCum;
286
+ const overLimit = safeLimit > 0 && effectiveTotal > safeLimit;
287
+ let turnsLeft = null;
288
+ if (turns.length >= o.MIN_TURNS_FOR_PROJECTION && safeLimit > 0 && burnRateTokens > 0) {
289
+ turnsLeft = overLimit ? 0 : Math.floor((safeLimit - effectiveTotal) / burnRateTokens);
290
+ }
291
+
292
+ return {
293
+ version: 1,
294
+ hasTimestamps,
295
+ cacheTtlSec: ttl,
296
+ safeLimit,
297
+ totalTurns: turns.length,
298
+ cumulativeScaled,
299
+ earlier,
300
+ turns: kept.map((t) => ({
301
+ turn: t.turn,
302
+ tokensAdded: t.tokensAdded,
303
+ cumulative: t.cumulative,
304
+ practice: t.practice,
305
+ tags: [...t.tags],
306
+ tagCounts: { ...t.tagCounts },
307
+ reason: t.reason,
308
+ cache: t.cache,
309
+ startedAt: t.startedAt,
310
+ endedAt: t.endedAt
311
+ })),
312
+ markers: keptMarkers,
313
+ coldCliffs,
314
+ kpis: {
315
+ burnRateTokens,
316
+ turnsLeft,
317
+ overLimit,
318
+ coldRestartLossUsd,
319
+ goodCount: turns.filter((t) => t.practice === 'good').length,
320
+ badCount: turns.filter((t) => t.practice === 'bad').length
321
+ }
322
+ };
323
+ }
324
+
325
+ /**
326
+ * Attaches verified ledger auto-fix events to their turns (adds AUTO_FIX_FIRED and updates reasons).
327
+ * Mutates `timeline` and each item's `turn`; returns `timeline`.
328
+ */
329
+ export function applyAutoFixToTimeline(timeline, items = []) {
330
+ if (!timeline || !Array.isArray(timeline.turns)) return timeline;
331
+ // Idempotent: clear previous auto-fix tags so repeated daemon ticks never double-count.
332
+ for (const t of timeline.turns) {
333
+ t.tags = t.tags.filter((k) => k !== 'AUTO_FIX_FIRED');
334
+ delete t.tagCounts.AUTO_FIX_FIRED;
335
+ }
336
+ for (const it of Array.isArray(items) ? items : []) {
337
+ const ms = Date.parse(String(it?.at || ''));
338
+ if (!Number.isFinite(ms)) continue;
339
+ let target = null;
340
+ for (const t of timeline.turns) {
341
+ const startMs = Date.parse(String(t.startedAt || ''));
342
+ if (Number.isFinite(startMs) && startMs <= ms) target = t;
343
+ }
344
+ if (!target) continue;
345
+ it.turn = target.turn;
346
+ if (!target.tags.includes('AUTO_FIX_FIRED')) target.tags.push('AUTO_FIX_FIRED');
347
+ target.tagCounts.AUTO_FIX_FIRED = (target.tagCounts.AUTO_FIX_FIRED || 0) + 1;
348
+ }
349
+ for (const t of timeline.turns) finalizeTurn(t);
350
+ timeline.kpis = {
351
+ ...(timeline.kpis || {}),
352
+ goodCount: timeline.turns.filter((t) => t.practice === 'good').length + (timeline.earlier?.good || 0),
353
+ badCount: timeline.turns.filter((t) => t.practice === 'bad').length + (timeline.earlier?.bad || 0)
354
+ };
355
+ return timeline;
356
+ }
357
+
358
+ export default buildSessionTimeline;
@@ -0,0 +1,99 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import os from 'node:os';
4
+ import { HORIZON_WINDOW, SHARED_1M_CONTEXT_POOL_TOKENS, resolvePatchedCliCeiling } from './constants.mjs';
5
+ import { atomicWriteFileSync } from './atomic_io.mjs';
6
+
7
+ /**
8
+ * User-editable Context Memory settings, stored at
9
+ * `<cacheDir>/settings.json`:
10
+ * { safeLimitTokens, reminderAtPct, modelOverrides: { [modelId]: safeLimitTokens } }
11
+ */
12
+
13
+ export const SETTINGS_LIMITS = {
14
+ SAFE_LIMIT_MIN: 20000,
15
+ SAFE_LIMIT_MAX: SHARED_1M_CONTEXT_POOL_TOKENS,
16
+ REMINDER_PCT_MIN: 50,
17
+ REMINDER_PCT_MAX: 99
18
+ };
19
+
20
+ export const DEFAULT_SETTINGS = Object.freeze({
21
+ safeLimitTokens: HORIZON_WINDOW.AMPUTATION_THRESHOLD_TOKENS,
22
+ reminderAtPct: 85,
23
+ modelOverrides: {}
24
+ });
25
+
26
+ const clamp = (n, lo, hi) => Math.min(hi, Math.max(lo, n));
27
+
28
+ function toInt(v) {
29
+ const n = typeof v === 'string' ? Number(v.replace(/[_,\s]/g, '')) : Number(v);
30
+ return Number.isFinite(n) ? Math.round(n) : NaN;
31
+ }
32
+
33
+ /** Returns a fully-populated, clamped settings object. Unknown keys are dropped. */
34
+ export function validateSettings(input = {}) {
35
+ const out = { ...DEFAULT_SETTINGS, modelOverrides: {} };
36
+ const limit = toInt(input.safeLimitTokens);
37
+ if (!Number.isNaN(limit)) out.safeLimitTokens = clamp(limit, SETTINGS_LIMITS.SAFE_LIMIT_MIN, SETTINGS_LIMITS.SAFE_LIMIT_MAX);
38
+ const pct = toInt(input.reminderAtPct);
39
+ if (!Number.isNaN(pct)) out.reminderAtPct = clamp(pct, SETTINGS_LIMITS.REMINDER_PCT_MIN, SETTINGS_LIMITS.REMINDER_PCT_MAX);
40
+ if (input.modelOverrides && typeof input.modelOverrides === 'object') {
41
+ for (const [model, v] of Object.entries(input.modelOverrides)) {
42
+ const n = toInt(v);
43
+ if (model && model.length <= 120 && !Number.isNaN(n)) {
44
+ out.modelOverrides[model] = clamp(n, SETTINGS_LIMITS.SAFE_LIMIT_MIN, SETTINGS_LIMITS.SAFE_LIMIT_MAX);
45
+ }
46
+ }
47
+ }
48
+ return out;
49
+ }
50
+
51
+ export function settingsFile(cacheDir) {
52
+ return path.join(cacheDir, 'settings.json');
53
+ }
54
+
55
+ export function loadSettings(cacheDir) {
56
+ try {
57
+ return validateSettings(JSON.parse(fs.readFileSync(settingsFile(cacheDir), 'utf8')));
58
+ } catch {
59
+ return validateSettings({});
60
+ }
61
+ }
62
+
63
+ /** Merges `patch` over the stored settings, validates, writes atomically, returns the result. */
64
+ export function saveSettings(cacheDir, patch = {}) {
65
+ const merged = validateSettings({ ...loadSettings(cacheDir), ...patch });
66
+ atomicWriteFileSync(settingsFile(cacheDir), JSON.stringify(merged, null, 2), 'utf8');
67
+ return merged;
68
+ }
69
+
70
+ /** Resolves `{ safeLimit, reminderAt, reminderAtPct }` for a model. */
71
+ export function resolveWindow(settings, modelId) {
72
+ const s = settings || DEFAULT_SETTINGS;
73
+ const safeLimit = (modelId && s.modelOverrides?.[modelId]) || s.safeLimitTokens;
74
+ return {
75
+ safeLimit,
76
+ reminderAtPct: s.reminderAtPct,
77
+ reminderAt: Math.round(safeLimit * s.reminderAtPct / 100)
78
+ };
79
+ }
80
+
81
+ /**
82
+ * Reads `~/.gemini/antigravity-cli/settings.json` (or a custom path)
83
+ * to inspect patched CLI context window overrides (512k or 900k whitelisted tiers).
84
+ */
85
+ export function loadCliSurfaceSettings(customFilePath = null) {
86
+ const targetFile = customFilePath || path.join(os.homedir(), '.gemini', 'antigravity-cli', 'settings.json');
87
+ try {
88
+ if (!fs.existsSync(targetFile)) return null;
89
+ const parsed = JSON.parse(fs.readFileSync(targetFile, 'utf8'));
90
+ if (!parsed || typeof parsed !== 'object') return null;
91
+ const patchedTokens = resolvePatchedCliCeiling(parsed);
92
+ return {
93
+ ...parsed,
94
+ patchedCeilingTokens: patchedTokens
95
+ };
96
+ } catch {
97
+ return null;
98
+ }
99
+ }