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,291 @@
1
+ import path from 'node:path';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { canonicalizePath } from '../paths.mjs';
4
+
5
+ /**
6
+ * Phase 1.2: `DET-17` Shadowed File Bloat Detector (`src/core/telemetry/shadow_file_detector.mjs`)
7
+ *
8
+ * Strictly read-only `.pb` / JSONL trajectory scanner with zero side effects.
9
+ * Scans tool-call blocks for multiple full-file `view_file` / `read_file` reads on the
10
+ * same normalized file path across turns where intermediate file edits
11
+ * (`replace_file_content`, `multi_replace_file_content`, `write_to_file`, `edit_file`, `write_file`)
12
+ * occurred.
13
+ *
14
+ * Computes `staleSnapshotCount` and `redundantTokens` per file and formats
15
+ * 40-Cell Flamegraph callout payloads:
16
+ * e.g. `router.mjs (3x snapshots • 42.1k stale tokens)`
17
+ */
18
+
19
+ const VIEW_FILE_TOOLS = new Set([
20
+ 'view_file',
21
+ 'read_file',
22
+ 'view_code',
23
+ 'mcp_filesystem_read_file'
24
+ ]);
25
+
26
+ const EDIT_FILE_TOOLS = new Set([
27
+ 'replace_file_content',
28
+ 'multi_replace_file_content',
29
+ 'write_to_file',
30
+ 'edit_file',
31
+ 'write_file',
32
+ 'apply_patch',
33
+ 'str_replace'
34
+ ]);
35
+
36
+ export function formatTokensCompactK(tokens = 0) {
37
+ const n = Math.max(0, Number(tokens) || 0);
38
+ return `${(n / 1000).toFixed(1)}k`;
39
+ }
40
+
41
+ function isPairedResultStep(nextStep = {}, curStep = {}) {
42
+ if (!nextStep || typeof nextStep !== 'object') return false;
43
+ const nextCalls = Array.isArray(nextStep.toolCalls)
44
+ ? nextStep.toolCalls
45
+ : (Array.isArray(nextStep.tool_calls) ? nextStep.tool_calls : []);
46
+ if (nextCalls.length > 0 || nextStep.tool || nextStep.name || nextStep.toolName) return false;
47
+ const nextType = String(nextStep.type || '').toUpperCase();
48
+ const nextSource = String(nextStep.source || '').toUpperCase();
49
+ if (nextType === 'USER_INPUT' || nextSource === 'USER_EXPLICIT' || nextType === 'SYSTEM_PROMPT') return false;
50
+ const curType = String(curStep.type || '').toUpperCase();
51
+ if (curType === 'PLANNER_RESPONSE' && (nextType === 'GENERIC' || nextType === 'TOOL_RESULT' || nextSource === 'TOOL' || nextSource === 'MODEL')) {
52
+ return true;
53
+ }
54
+ return nextType === 'TOOL_RESULT' || nextSource === 'TOOL';
55
+ }
56
+
57
+ function extractToolCallsFromStep(step = {}, stepIdx = 0, list = []) {
58
+ if (!step || typeof step !== 'object') return [];
59
+ const rawList = Array.isArray(step.toolCalls)
60
+ ? step.toolCalls
61
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : null);
62
+
63
+ if (rawList && rawList.length > 0) {
64
+ const nextStep = Array.isArray(list) ? list[stepIdx + 1] : null;
65
+ const hasPairedResult = isPairedResultStep(nextStep, step);
66
+ const ownTokens = Number(step.tokens ?? step.outputTokens ?? 0);
67
+ const nextTokens = hasPairedResult ? Number(nextStep.tokens ?? nextStep.outputTokens ?? 0) : 0;
68
+ const effectiveStepTokens = nextTokens > 0
69
+ ? Math.max(ownTokens, nextTokens)
70
+ : (ownTokens > 0 ? ownTokens : null);
71
+ const effectiveContent = hasPairedResult && nextStep.content
72
+ ? nextStep.content
73
+ : (step.content ?? '');
74
+
75
+ return rawList.map((call) => ({
76
+ ...call,
77
+ _stepIndex: Number.isFinite(step.stepIndex) ? step.stepIndex : stepIdx,
78
+ _stepTokens: effectiveStepTokens,
79
+ _stepContent: effectiveContent
80
+ }));
81
+ }
82
+
83
+ // Support flat tool-call block objects directly in `.pb` trajectory arrays
84
+ if (step.tool || step.name || step.toolName) {
85
+ return [{
86
+ ...step,
87
+ _stepIndex: Number.isFinite(step.stepIndex) ? step.stepIndex : stepIdx,
88
+ _stepTokens: step.tokens ?? step.outputTokens ?? null,
89
+ _stepContent: step.content ?? ''
90
+ }];
91
+ }
92
+
93
+ return [];
94
+ }
95
+
96
+ function resolveCallPath(call = {}) {
97
+ const args = call.args || call.parameters || call.Arguments || {};
98
+ const raw =
99
+ call.path ||
100
+ call.filePath ||
101
+ call.targetFile ||
102
+ args.AbsolutePath ||
103
+ args.TargetFile ||
104
+ args.Path ||
105
+ args.path ||
106
+ args.file_path ||
107
+ '';
108
+ return String(raw || '').trim();
109
+ }
110
+
111
+ function isFullFileViewCall(call = {}) {
112
+ if (call.isFullFile === false || call.rangedRead === true) return false;
113
+ if (call.isFullFile === true) return true;
114
+
115
+ const args = call.args || call.parameters || call.Arguments || {};
116
+ const startLine = args.StartLine ?? args.start_line ?? call.StartLine ?? call.startLine ?? null;
117
+ const endLine = args.EndLine ?? args.end_line ?? call.EndLine ?? call.endLine ?? null;
118
+ const totalLines = args.TotalLines ?? args.total_lines ?? call.totalLines ?? null;
119
+
120
+ if (startLine === null && endLine === null) {
121
+ return true;
122
+ }
123
+
124
+ if (Number(startLine) <= 1 && endLine !== null && totalLines !== null && Number(endLine) >= Number(totalLines)) {
125
+ return true;
126
+ }
127
+
128
+ return false;
129
+ }
130
+
131
+ function estimateCallTokens(call = {}) {
132
+ const explicit =
133
+ call.tokens ??
134
+ call.tokenCount ??
135
+ call.outputTokens ??
136
+ call.resultTokens ??
137
+ call._stepTokens ??
138
+ null;
139
+
140
+ if (Number.isFinite(Number(explicit)) && Number(explicit) > 0) {
141
+ return Math.round(Number(explicit));
142
+ }
143
+
144
+ const textPayload = String(
145
+ call.result ??
146
+ call.output ??
147
+ call.content ??
148
+ call._stepContent ??
149
+ ''
150
+ );
151
+ if (textPayload.length > 0) {
152
+ return Math.ceil(textPayload.length / 4);
153
+ }
154
+
155
+ const byteLen = Number(call.byteLength ?? call.bytes ?? 0);
156
+ if (byteLen > 0) {
157
+ return Math.ceil(byteLen / 4);
158
+ }
159
+
160
+ return 2500;
161
+ }
162
+
163
+ /**
164
+ * Scans `.pb` / transcript steps for `DET-17` Shadowed File Bloat.
165
+ *
166
+ * @param {Array} steps - Trajectory steps or `.pb` tool-call blocks
167
+ * @param {object} [options={}]
168
+ * @returns {object} { detectorId: 'DET-17', triggered, totalStaleSnapshots, totalRedundantTokens, offenders, flamegraphBadges, elapsedMs }
169
+ */
170
+ export function detectShadowedFileBloat(steps = [], options = {}) {
171
+ const startMs = performance.now();
172
+ const list = Array.isArray(steps) ? steps : [];
173
+
174
+ // normalizedPath -> { rawPath, events: Array<{ type: 'READ'|'EDIT', turnIndex, tokens, toolName }> }
175
+ const historyByFile = new Map();
176
+
177
+ for (let idx = 0; idx < list.length; idx++) {
178
+ const calls = extractToolCallsFromStep(list[idx], idx, list);
179
+ for (const call of calls) {
180
+ const toolName = String(call.name || call.tool || call.toolName || '').toLowerCase().trim();
181
+ if (!VIEW_FILE_TOOLS.has(toolName) && !EDIT_FILE_TOOLS.has(toolName)) {
182
+ continue;
183
+ }
184
+
185
+ const rawPath = resolveCallPath(call);
186
+ if (!rawPath) continue;
187
+ const normPath = canonicalizePath(rawPath);
188
+ if (!normPath) continue;
189
+
190
+ if (!historyByFile.has(normPath)) {
191
+ historyByFile.set(normPath, {
192
+ rawPath,
193
+ normalizedPath: normPath,
194
+ events: []
195
+ });
196
+ }
197
+
198
+ const record = historyByFile.get(normPath);
199
+ const turnIndex = Number.isFinite(call._stepIndex) ? call._stepIndex : idx;
200
+
201
+ if (VIEW_FILE_TOOLS.has(toolName)) {
202
+ if (!isFullFileViewCall(call)) continue;
203
+ record.events.push({
204
+ type: 'READ',
205
+ turnIndex,
206
+ tokens: estimateCallTokens(call),
207
+ toolName
208
+ });
209
+ } else if (EDIT_FILE_TOOLS.has(toolName)) {
210
+ record.events.push({
211
+ type: 'EDIT',
212
+ turnIndex,
213
+ tokens: 0,
214
+ toolName
215
+ });
216
+ }
217
+ }
218
+ }
219
+
220
+ const offenders = [];
221
+
222
+ for (const [, fileRecord] of historyByFile.entries()) {
223
+ const events = fileRecord.events;
224
+ const reads = events.filter((e) => e.type === 'READ');
225
+ if (reads.length < 2) continue;
226
+
227
+ // Identify whether intermediate edits occurred between the first and last full-file reads
228
+ const firstReadIdx = events.findIndex((e) => e.type === 'READ');
229
+ let lastReadIdx = -1;
230
+ for (let i = events.length - 1; i >= 0; i--) {
231
+ if (events[i].type === 'READ') {
232
+ lastReadIdx = i;
233
+ break;
234
+ }
235
+ }
236
+
237
+ const intermediateEdits = events
238
+ .slice(firstReadIdx + 1, lastReadIdx)
239
+ .filter((e) => e.type === 'EDIT');
240
+
241
+ if (intermediateEdits.length === 0) {
242
+ continue;
243
+ }
244
+
245
+ // Every full-file read prior to the latest full-file read is now a shadowed/stale snapshot
246
+ const staleReads = reads.slice(0, -1);
247
+ const staleSnapshotCount = staleReads.length;
248
+ const redundantTokens = staleReads.reduce((sum, r) => sum + r.tokens, 0);
249
+ const totalReadTokens = reads.reduce((sum, r) => sum + r.tokens, 0);
250
+ const baseName = path.basename(fileRecord.rawPath.replace(/\\/g, '/'));
251
+ const callout = `${baseName} (${staleSnapshotCount}x snapshots • ${formatTokensCompactK(redundantTokens)} stale tokens)`;
252
+
253
+ offenders.push({
254
+ detectorId: 'DET-17',
255
+ filePath: fileRecord.rawPath,
256
+ normalizedPath: fileRecord.normalizedPath,
257
+ baseName,
258
+ totalSnapshotCount: reads.length,
259
+ staleSnapshotCount,
260
+ intermediateEditCount: intermediateEdits.length,
261
+ redundantTokens,
262
+ totalReadTokens,
263
+ turnIndices: reads.map((r) => r.turnIndex),
264
+ staleTurnIndices: staleReads.map((r) => r.turnIndex),
265
+ callout
266
+ });
267
+ }
268
+
269
+ offenders.sort((a, b) => b.redundantTokens - a.redundantTokens || b.staleSnapshotCount - a.staleSnapshotCount);
270
+
271
+ const topLimit = Math.max(1, Number(options.limit || 5));
272
+ const topOffenders = offenders.slice(0, topLimit);
273
+ const totalStaleSnapshots = offenders.reduce((sum, o) => sum + o.staleSnapshotCount, 0);
274
+ const totalRedundantTokens = offenders.reduce((sum, o) => sum + o.redundantTokens, 0);
275
+
276
+ return {
277
+ detectorId: 'DET-17',
278
+ triggered: offenders.length > 0,
279
+ totalStaleSnapshots,
280
+ totalRedundantTokens,
281
+ offenders,
282
+ topOffenders,
283
+ flamegraphBadges: topOffenders.map((o) => o.callout),
284
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
285
+ };
286
+ }
287
+
288
+ export default {
289
+ detectShadowedFileBloat,
290
+ formatTokensCompactK
291
+ };
@@ -0,0 +1,259 @@
1
+ import { EventEmitter } from 'node:events';
2
+ import { performance } from 'node:perf_hooks';
3
+ import { evaluateDet08CacheGravityAndEffort } from '../shared/detectors.mjs';
4
+
5
+ /**
6
+ * Phase 1.1: Undo / Rewind Step Rollback Detector (`src/core/telemetry/trajectory_watcher.mjs`)
7
+ *
8
+ * Strictly read-only telemetry observer with zero disk or network side effects.
9
+ * Tracks `stepCount` across `.pb` / JSONL conversation updates.
10
+ * When `currentStepCount < previousStepCount` (user clicked Undo/Rewind in Antigravity chat):
11
+ * - Emits `TRAJECTORY_REWIND` with `{ sessionId, droppedSteps, newStepCount, previousStepCount }`
12
+ * - Immediately recomputes the 40-cell Flamegraph and context fill on the remaining steps
13
+ * - Notifies bound `HysteresisLock` and `circuit_breakers.mjs` instances to purge
14
+ * oscillation hashes and retry counters recorded during the rewound turns.
15
+ */
16
+
17
+ export const FLAMEGRAPH_CELL_COUNT = 40;
18
+ export const DEFAULT_CONTEXT_CEILING_TOKENS = 256000;
19
+
20
+ /**
21
+ * Pure <1ms 40-Cell Flamegraph and Context Fill recomputation for a step array.
22
+ */
23
+ export function computeFlamegraphAndContextFill(steps = [], options = {}) {
24
+ const list = Array.isArray(steps) ? steps : [];
25
+ const ceilingTokens = Math.max(1, Number(options.ceilingTokens || DEFAULT_CONTEXT_CEILING_TOKENS));
26
+ const tokensPerCell = Math.ceil(ceilingTokens / FLAMEGRAPH_CELL_COUNT);
27
+
28
+ let totalTokens = Number(options.baselineOverheadTokens || 0);
29
+ const stepTokenSlices = [];
30
+
31
+ for (let i = 0; i < list.length; i++) {
32
+ const step = list[i] || {};
33
+ const stepTokens = Number(
34
+ step.tokens ??
35
+ step.totalTokens ??
36
+ step.outputTokens ??
37
+ step.inputTokens ??
38
+ (typeof step.content === 'string' ? Math.ceil(step.content.length / 4) : 500)
39
+ );
40
+ const bounded = Math.max(0, stepTokens);
41
+ totalTokens += bounded;
42
+ stepTokenSlices.push({
43
+ stepIndex: i,
44
+ tokens: bounded,
45
+ type: step.type || step.role || 'STEP'
46
+ });
47
+ }
48
+
49
+ const cells = Array.from({ length: FLAMEGRAPH_CELL_COUNT }, (_, idx) => ({
50
+ cellIndex: idx,
51
+ capacityTokens: tokensPerCell,
52
+ filledTokens: 0,
53
+ fillRatio: 0,
54
+ status: 'FREE',
55
+ stepIndices: []
56
+ }));
57
+
58
+ let cursorTokens = Number(options.baselineOverheadTokens || 0);
59
+ if (cursorTokens > 0) {
60
+ let remainingBase = cursorTokens;
61
+ for (let c = 0; c < FLAMEGRAPH_CELL_COUNT && remainingBase > 0; c++) {
62
+ const alloc = Math.min(tokensPerCell, remainingBase);
63
+ cells[c].filledTokens += alloc;
64
+ cells[c].status = 'SYSTEM_PREFIX';
65
+ remainingBase -= alloc;
66
+ }
67
+ }
68
+
69
+ for (const slice of stepTokenSlices) {
70
+ let rem = slice.tokens;
71
+ for (let c = 0; c < FLAMEGRAPH_CELL_COUNT && rem > 0; c++) {
72
+ const space = Math.max(0, tokensPerCell - cells[c].filledTokens);
73
+ if (space <= 0) continue;
74
+ const alloc = Math.min(space, rem);
75
+ cells[c].filledTokens += alloc;
76
+ cells[c].stepIndices.push(slice.stepIndex);
77
+ if (cells[c].status === 'FREE') {
78
+ cells[c].status = 'ACTIVE';
79
+ }
80
+ rem -= alloc;
81
+ }
82
+ }
83
+
84
+ let populatedCells = 0;
85
+ for (const cell of cells) {
86
+ cell.fillRatio = Number((cell.filledTokens / tokensPerCell).toFixed(3));
87
+ if (cell.filledTokens > 0) populatedCells++;
88
+ }
89
+
90
+ return {
91
+ totalTokens,
92
+ ceilingTokens,
93
+ fillPct: Number(Math.min(100, (totalTokens / ceilingTokens) * 100).toFixed(2)),
94
+ populatedCells,
95
+ tokensPerCell,
96
+ cells
97
+ };
98
+ }
99
+
100
+ export class TrajectoryWatcher extends EventEmitter {
101
+ constructor(options = {}) {
102
+ super();
103
+ this.sessionStepCounts = new Map(); // sessionId -> number
104
+ this.sessionStepsCache = new Map(); // sessionId -> Array
105
+ this.sessionFlamegraphs = new Map(); // sessionId -> Flamegraph state
106
+ this.hysteresisLocks = new Set();
107
+ this.circuitBreakers = new Set();
108
+ this.recomputeCallback = typeof options.onRecomputeFlamegraph === 'function'
109
+ ? options.onRecomputeFlamegraph
110
+ : null;
111
+
112
+ if (options.hysteresisLock) {
113
+ this.registerHysteresisLock(options.hysteresisLock);
114
+ }
115
+ if (options.circuitBreaker) {
116
+ this.registerCircuitBreaker(options.circuitBreaker);
117
+ }
118
+ }
119
+
120
+ registerHysteresisLock(lockInstance) {
121
+ if (lockInstance && typeof lockInstance === 'object') {
122
+ this.hysteresisLocks.add(lockInstance);
123
+ }
124
+ return this;
125
+ }
126
+
127
+ registerCircuitBreaker(breakerInstance) {
128
+ if (breakerInstance && typeof breakerInstance === 'object') {
129
+ this.circuitBreakers.add(breakerInstance);
130
+ }
131
+ return this;
132
+ }
133
+
134
+ /**
135
+ * Observes a `.pb` or JSONL trajectory update for a given session.
136
+ * Detects Undo / Rewind step rollbacks in <2ms and triggers synchronous state recovery.
137
+ *
138
+ * @param {object} update
139
+ * @param {string} [update.sessionId='default']
140
+ * @param {number} [update.stepCount]
141
+ * @param {Array} [update.steps]
142
+ * @param {object} [update.options]
143
+ */
144
+ observeTrajectoryUpdate(update = {}) {
145
+ const startMs = performance.now();
146
+ const sessionId = String(update.sessionId || 'default');
147
+ const steps = Array.isArray(update.steps) ? update.steps : null;
148
+ const currentStepCount = Number.isFinite(update.stepCount)
149
+ ? Math.max(0, Number(update.stepCount))
150
+ : (steps ? steps.length : 0);
151
+
152
+ const previousStepCount = this.sessionStepCounts.has(sessionId)
153
+ ? this.sessionStepCounts.get(sessionId)
154
+ : currentStepCount;
155
+
156
+ const effectiveSteps = steps
157
+ ? steps.slice(0, currentStepCount)
158
+ : (this.sessionStepsCache.get(sessionId) || []).slice(0, currentStepCount);
159
+
160
+ this.sessionStepCounts.set(sessionId, currentStepCount);
161
+ if (steps || effectiveSteps.length > 0) {
162
+ this.sessionStepsCache.set(sessionId, effectiveSteps);
163
+ }
164
+
165
+ let rewindDetected = false;
166
+ let rewindPayload = null;
167
+
168
+ if (currentStepCount < previousStepCount) {
169
+ rewindDetected = true;
170
+ const droppedSteps = previousStepCount - currentStepCount;
171
+ const flamegraph = computeFlamegraphAndContextFill(effectiveSteps, update.options || {});
172
+ this.sessionFlamegraphs.set(sessionId, flamegraph);
173
+
174
+ if (this.recomputeCallback) {
175
+ try {
176
+ this.recomputeCallback({
177
+ sessionId,
178
+ newStepCount: currentStepCount,
179
+ droppedSteps,
180
+ steps: effectiveSteps,
181
+ flamegraph
182
+ });
183
+ } catch {}
184
+ }
185
+
186
+ // Notify all registered HysteresisLock instances
187
+ for (const lock of this.hysteresisLocks) {
188
+ if (typeof lock.onTrajectoryRewind === 'function') {
189
+ lock.onTrajectoryRewind({ sessionId, droppedSteps, newStepCount: currentStepCount });
190
+ } else if (typeof lock.unlock === 'function') {
191
+ lock.unlock('TRAJECTORY_REWIND');
192
+ }
193
+ }
194
+
195
+ // Notify all registered CircuitBreaker instances to purge oscillation hashes & retry counters
196
+ for (const breaker of this.circuitBreakers) {
197
+ if (typeof breaker.purgeRewoundTurns === 'function') {
198
+ breaker.purgeRewoundTurns(currentStepCount, sessionId);
199
+ } else if (typeof breaker.onTrajectoryRewind === 'function') {
200
+ breaker.onTrajectoryRewind({ sessionId, droppedSteps, newStepCount: currentStepCount });
201
+ }
202
+ }
203
+
204
+ rewindPayload = {
205
+ sessionId,
206
+ previousStepCount,
207
+ newStepCount: currentStepCount,
208
+ droppedSteps,
209
+ flamegraph,
210
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
211
+ };
212
+
213
+ this.emit('TRAJECTORY_REWIND', rewindPayload);
214
+ } else {
215
+ const flamegraph = computeFlamegraphAndContextFill(effectiveSteps, update.options || {});
216
+ this.sessionFlamegraphs.set(sessionId, flamegraph);
217
+ }
218
+
219
+ const effortAdvice = update.effortContext
220
+ ? evaluateDet08CacheGravityAndEffort({
221
+ turnCount: currentStepCount,
222
+ cachedTokens: Number(update.effortContext.cachedTokens || 0),
223
+ activeModel: update.effortContext.activeModel || 'gemini-4-carbon',
224
+ activeEffort: update.effortContext.activeEffort || 'high',
225
+ isSimpleTask: update.effortContext.isSimpleTask !== false,
226
+ recentTestFailures: Number(update.effortContext.recentTestFailures || 0),
227
+ det05Oscillation: Boolean(update.effortContext.det05Oscillation),
228
+ dismissalStrikes: Number(update.effortContext.dismissalStrikes || 0),
229
+ timestampUtc: update.effortContext.timestampUtc
230
+ })
231
+ : null;
232
+ if (effortAdvice && effortAdvice.triggered) {
233
+ this.emit('EFFORT_ADVISOR_CHIP', { sessionId, effortAdvice });
234
+ }
235
+
236
+ return {
237
+ sessionId,
238
+ previousStepCount,
239
+ currentStepCount,
240
+ rewindDetected,
241
+ droppedSteps: rewindDetected ? previousStepCount - currentStepCount : 0,
242
+ flamegraph: this.sessionFlamegraphs.get(sessionId),
243
+ rewindPayload,
244
+ effortAdvice,
245
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
246
+ };
247
+ }
248
+
249
+ getSessionState(sessionId = 'default') {
250
+ const id = String(sessionId || 'default');
251
+ return {
252
+ sessionId: id,
253
+ stepCount: this.sessionStepCounts.get(id) ?? 0,
254
+ flamegraph: this.sessionFlamegraphs.get(id) ?? null
255
+ };
256
+ }
257
+ }
258
+
259
+ export default TrajectoryWatcher;