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,515 @@
1
+ /**
2
+ * Cross-Session Forensic Postmortem Engine.
3
+ * Deterministic local transcript forensics with file/line/config remediations.
4
+ */
5
+
6
+ import fs from 'node:fs';
7
+ import path from 'node:path';
8
+ import { fileURLToPath } from 'node:url';
9
+ import { getHomeDir, getBrainStores, getAntigravitySurfaces, isIgnorablePath, ensureSupportedNodeVersion } from '../core/paths.mjs';
10
+ import { parseTranscriptIncremental } from '../core/parser.mjs';
11
+ import { classifyHorizon } from '../core/classifier.mjs';
12
+ import { measureBaseline } from '../core/baseline.mjs';
13
+ import { getFlightcheckDir } from '../core/sidecar_store.mjs';
14
+ import { buildGitCommitTokenLedger } from '../core/git_ledger.mjs';
15
+ import { upsertEpisodicMemory } from '../core/episodic_memory.mjs';
16
+ import { atomicWriteFileSync } from '../core/atomic_io.mjs';
17
+
18
+ export const ROOT_CAUSES = {
19
+ CONTEXT_ROT_DECAY: 'CONTEXT_ROT_DECAY',
20
+ VERIFICATION_CHURN: 'VERIFICATION_CHURN',
21
+ SPEC_AMBIGUITY: 'SPEC_AMBIGUITY',
22
+ CLEAN: 'CLEAN',
23
+ INSUFFICIENT_EVIDENCE: 'INSUFFICIENT_EVIDENCE'
24
+ };
25
+
26
+ export const REWORK_SHAPES = {
27
+ CLEAN: 'Clean execution',
28
+ EARLY_REPLAN_STABLE: 'Early replan then stable finish',
29
+ VERIFICATION_CHURN: 'Late-stage verification churn',
30
+ EXPLORATORY: 'Exploratory / research session',
31
+ ABANDONED: 'Abandoned mid-flight'
32
+ };
33
+
34
+ /**
35
+ * Runs the forensic postmortem over historical Antigravity sessions.
36
+ */
37
+ export async function runPostmortem(options = {}) {
38
+ const {
39
+ last = 15,
40
+ workspace = process.cwd(),
41
+ json = false,
42
+ writeFiles = true,
43
+ demo = false
44
+ } = options;
45
+
46
+ const home = options.homeDir || getHomeDir();
47
+ const surfaces = getAntigravitySurfaces(home, { includeMissing: false });
48
+ const stores = surfaces.length > 0
49
+ ? surfaces.map(s => ({ name: s.name, path: s.brainDir }))
50
+ : getBrainStores(home);
51
+
52
+ const seenDirs = new Set();
53
+ const sessionCandidates = [];
54
+ for (const store of stores) {
55
+ if (!fs.existsSync(store.path)) continue;
56
+ try {
57
+ const dirs = fs.readdirSync(store.path, { withFileTypes: true })
58
+ .filter(d => d.isDirectory())
59
+ .map(d => {
60
+ const fullPath = path.join(store.path, d.name);
61
+ let mtimeMs = 0;
62
+ try {
63
+ const logsDir = path.join(fullPath, '.system_generated', 'logs');
64
+ const fullJsonl = path.join(logsDir, 'transcript_full.jsonl');
65
+ const compactJsonl = path.join(logsDir, 'transcript.jsonl');
66
+ if (fs.existsSync(fullJsonl)) mtimeMs = fs.statSync(fullJsonl).mtimeMs;
67
+ else if (fs.existsSync(compactJsonl)) mtimeMs = fs.statSync(compactJsonl).mtimeMs;
68
+ else mtimeMs = fs.statSync(fullPath).mtimeMs;
69
+ } catch {}
70
+ return { id: d.name, path: fullPath, store: store.name, mtimeMs };
71
+ });
72
+ for (const item of dirs) {
73
+ if (!seenDirs.has(item.path)) {
74
+ seenDirs.add(item.path);
75
+ sessionCandidates.push(item);
76
+ }
77
+ }
78
+ } catch {}
79
+ }
80
+
81
+ // Sort newest first and inspect up to `targetLimit` non-empty sessions
82
+ sessionCandidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
83
+ const targetLimit = Math.max(1, Number(last) || 15);
84
+
85
+ const diagnostics = [];
86
+ const hotspotMap = new Map(); // path -> { path, occurrences, wastedTokens, sessions: Set, sampleSteps: number[] }
87
+ let latestSessionSteps = [];
88
+ let totalTokensInspected = 0;
89
+ let totalSludgeUsd = 0;
90
+ let amputationSessionsCount = 0;
91
+ let strongProofCount = 0;
92
+ let totalPlanRevisions = 0;
93
+ let errorLoopCount = 0;
94
+ let totalDuplicateReadsCount = 0;
95
+ let totalDeadErrorsCount = 0;
96
+ let worstSessionOffender = null;
97
+
98
+ if (!demo) {
99
+ for (const candidate of sessionCandidates) {
100
+ if (diagnostics.length >= targetLimit) break;
101
+
102
+ let parsed = null;
103
+ try {
104
+ parsed = parseTranscriptIncremental(candidate.path, null);
105
+ } catch {
106
+ continue;
107
+ }
108
+
109
+ if (!parsed || !Array.isArray(parsed.steps) || parsed.steps.length === 0) {
110
+ continue;
111
+ }
112
+
113
+ let horizon = null;
114
+ try {
115
+ horizon = classifyHorizon(parsed.steps, {
116
+ sessionId: candidate.id,
117
+ brainDir: candidate.path,
118
+ logFilePath: parsed.filePath,
119
+ canonicalWorkspace: workspace,
120
+ useNativeCeiling: true
121
+ });
122
+ } catch {
123
+ continue;
124
+ }
125
+
126
+ if (!horizon) continue;
127
+ if (latestSessionSteps.length === 0) {
128
+ latestSessionSteps = parsed.steps;
129
+ }
130
+
131
+ const purity = horizon.metrics?.signalPurityPct ?? 100;
132
+ const tokens = horizon.window?.totalActiveTokens || 0;
133
+ const sludgeUsd = horizon.metrics?.sludgeTaxPerTurnUsd || 0;
134
+ const isAmputation = Boolean(horizon.amputation?.inAmputationZone);
135
+ const signals = horizon.brainSignals || {};
136
+
137
+ totalTokensInspected += tokens;
138
+ totalSludgeUsd += sludgeUsd;
139
+ if (isAmputation) amputationSessionsCount++;
140
+
141
+ const planChurn = signals.planChurn || { planRevisions: 0, warn: false };
142
+ const proofQuality = signals.proofQuality || { grade: 'None', reason: '' };
143
+ const contextRot = signals.contextRot || { splitRecommended: false, reason: '' };
144
+ const errorLoop = signals.errorLoop || { loop: false, fingerprint: null };
145
+
146
+ totalPlanRevisions += planChurn.planRevisions || 0;
147
+ if (proofQuality.grade === 'Strong') strongProofCount++;
148
+ if (errorLoop.loop) errorLoopCount++;
149
+
150
+ // Track hotspots from duplicate read offenders & classifier offenders
151
+ const dupOffenders = signals.duplicateReads?.topFiles || [];
152
+ const rawOffenders = horizon.offenders || [];
153
+ for (const off of dupOffenders) {
154
+ if (!off.path) continue;
155
+ totalDuplicateReadsCount += Math.max(1, (off.occurrences || 2) - 1);
156
+ const matchRaw = rawOffenders.find(r => r.target === off.path);
157
+ const curr = hotspotMap.get(off.path) || {
158
+ path: off.path,
159
+ occurrences: 0,
160
+ wastedTokens: 0,
161
+ sessions: new Set(),
162
+ sampleSteps: []
163
+ };
164
+ curr.occurrences += off.occurrences || 1;
165
+ curr.wastedTokens += off.wastedTokens || 0;
166
+ curr.sessions.add(candidate.id);
167
+ if (matchRaw && Array.isArray(matchRaw.stepIndices) && curr.sampleSteps.length === 0) {
168
+ curr.sampleSteps = matchRaw.stepIndices.slice(0, 6);
169
+ }
170
+ hotspotMap.set(off.path, curr);
171
+ }
172
+
173
+ if (rawOffenders.length > 0) {
174
+ const topOff = rawOffenders[0];
175
+ if (!worstSessionOffender || topOff.wastedTokens > worstSessionOffender.wastedTokens) {
176
+ worstSessionOffender = {
177
+ ...topOff,
178
+ sessionId: candidate.id
179
+ };
180
+ }
181
+ }
182
+
183
+ totalDeadErrorsCount += (signals.deadErrors?.errorCount || 0);
184
+
185
+ // Root Cause & Confidence Classification
186
+ let rootCause = ROOT_CAUSES.INSUFFICIENT_EVIDENCE;
187
+ let confidence = 'Low';
188
+ const evidenceFor = [];
189
+ const evidenceAgainst = [];
190
+
191
+ if (contextRot.splitRecommended || (purity < 45 && tokens > 100000)) {
192
+ rootCause = ROOT_CAUSES.CONTEXT_ROT_DECAY;
193
+ confidence = 'High';
194
+ evidenceFor.push(`High sludge dilution (${purity}% purity)`, contextRot.reason);
195
+ if (planChurn.planRevisions > 0) evidenceAgainst.push(`Plan underwent ${planChurn.planRevisions} revisions`);
196
+ } else if (errorLoop.loop || (proofQuality.grade === 'None' && (signals.deadErrors?.errorCount || 0) >= 3)) {
197
+ rootCause = ROOT_CAUSES.VERIFICATION_CHURN;
198
+ confidence = 'High';
199
+ evidenceFor.push(
200
+ errorLoop.loop ? `Repeated error loop: ${errorLoop.fingerprint}` : `${signals.deadErrors?.errorCount} dead errors without passing test`
201
+ );
202
+ if (purity > 70) evidenceAgainst.push(`Context purity remained relatively high (${purity}%)`);
203
+ } else if (planChurn.planRevisions >= 3) {
204
+ rootCause = ROOT_CAUSES.SPEC_AMBIGUITY;
205
+ confidence = 'Medium';
206
+ evidenceFor.push(`${planChurn.planRevisions} plan revisions indicate evolving spec or scope churn`);
207
+ } else if (purity >= 70 && !isAmputation && !errorLoop.loop) {
208
+ rootCause = ROOT_CAUSES.CLEAN;
209
+ confidence = parsed.steps.length >= 8 ? 'High' : 'Medium';
210
+ evidenceFor.push(`High signal purity (${purity}%)`, 'Zero amputation or error loops detected');
211
+ } else {
212
+ rootCause = ROOT_CAUSES.INSUFFICIENT_EVIDENCE;
213
+ confidence = 'Low';
214
+ evidenceFor.push(`Short or inconclusive session (${parsed.steps.length} steps)`);
215
+ }
216
+
217
+ let reworkShape = REWORK_SHAPES.CLEAN;
218
+ if (rootCause === ROOT_CAUSES.VERIFICATION_CHURN) {
219
+ reworkShape = REWORK_SHAPES.VERIFICATION_CHURN;
220
+ } else if (planChurn.planRevisions >= 1 && proofQuality.grade === 'Strong') {
221
+ reworkShape = REWORK_SHAPES.EARLY_REPLAN_STABLE;
222
+ } else if (tokens < 25000 && !dupOffenders.length) {
223
+ reworkShape = REWORK_SHAPES.EXPLORATORY;
224
+ } else if (rootCause === ROOT_CAUSES.CONTEXT_ROT_DECAY) {
225
+ reworkShape = REWORK_SHAPES.ABANDONED;
226
+ }
227
+
228
+ diagnostics.push({
229
+ session_id: candidate.id,
230
+ mtime: new Date(candidate.mtimeMs).toISOString(),
231
+ turns: horizon.window?.turnCount || parsed.steps.length,
232
+ total_tokens: tokens,
233
+ signal_purity_pct: purity,
234
+ sludge_tax_usd_turn: sludgeUsd,
235
+ primary_root_cause: rootCause,
236
+ confidence,
237
+ rework_shape: reworkShape,
238
+ proof_quality: proofQuality.grade,
239
+ plan_revisions: planChurn.planRevisions,
240
+ handoff_status: horizon.handoff?.result || 'UNKNOWN',
241
+ top_offender: rawOffenders[0] ? `${rawOffenders[0].target} (${Math.round(rawOffenders[0].wastedTokens / 1000)}k tok)` : 'None',
242
+ evidence_for: evidenceFor,
243
+ evidence_against: evidenceAgainst
244
+ });
245
+
246
+ if (writeFiles) {
247
+ try {
248
+ const epDbPath = path.join(getFlightcheckDir(), 'episodic_memory.db');
249
+ await upsertEpisodicMemory(epDbPath, {
250
+ sessionId: candidate.id,
251
+ workspacePath: workspace || process.cwd(),
252
+ title: `Session ${candidate.id.slice(0, 8)} (${reworkShape})`,
253
+ summary: `Purity ${purity}%, ${tokens.toLocaleString()} tokens, root cause: ${rootCause}.`,
254
+ decisions: evidenceFor,
255
+ modifiedFiles: dupOffenders.map(f => f.path).slice(0, 6),
256
+ updatedAt: new Date(candidate.mtimeMs).toISOString()
257
+ });
258
+ } catch {}
259
+ }
260
+ }
261
+ }
262
+
263
+ const gitLedger = buildGitCommitTokenLedger(workspace || process.cwd(), latestSessionSteps);
264
+
265
+ const sessionCount = diagnostics.length;
266
+ const isSynthetic = Boolean(demo);
267
+
268
+ // Baseline Turn-0 MCP & Rule overhead check
269
+ let baseline = null;
270
+ try {
271
+ baseline = measureBaseline(workspace || process.cwd(), home);
272
+ } catch {}
273
+
274
+ const worstPurityPct = isSynthetic
275
+ ? 34.8
276
+ : (sessionCount > 0 ? Math.min(...diagnostics.map(d => d.signal_purity_pct)) : 0);
277
+ const avgPurityPct = isSynthetic
278
+ ? 62.4
279
+ : (sessionCount > 0 ? Math.round(diagnostics.reduce((s, d) => s + d.signal_purity_pct, 0) / sessionCount) : 0);
280
+ const strongProofRatePct = isSynthetic
281
+ ? 55
282
+ : (sessionCount > 0 ? Math.round((strongProofCount / sessionCount) * 100) : 0);
283
+ const avgPlanRevisions = isSynthetic
284
+ ? 1.2
285
+ : (sessionCount > 0 ? Number((totalPlanRevisions / sessionCount).toFixed(1)) : 0);
286
+ const estTokensM = isSynthetic
287
+ ? '1.84M'
288
+ : `${(totalTokensInspected / 1000000).toFixed(2)}M`;
289
+ const totalSludgeFormatted = isSynthetic
290
+ ? '$1.92'
291
+ : `$${totalSludgeUsd.toFixed(2)}`;
292
+
293
+ const recommendations = [];
294
+ const allHotspots = Array.from(hotspotMap.values()).sort((a, b) => b.wastedTokens - a.wastedTokens);
295
+
296
+ // Rec 1: Ignorable file hotspots -> .antigravityignore
297
+ const ignorableHotspots = allHotspots.filter(h => isIgnorablePath(h.path));
298
+ if (ignorableHotspots.length > 0) {
299
+ const topIgnorable = ignorableHotspots[0];
300
+ const wastedK = Math.max(0.1, (topIgnorable.wastedTokens / 1000).toFixed(1));
301
+ recommendations.push({
302
+ id: 'REC-IGNORE-HOTSPOTS',
303
+ observed_pattern: `Non-source file "${topIgnorable.path}" had ${topIgnorable.occurrences} redundant read(s) across ${topIgnorable.sessions.size} session(s), wasting ~${wastedK}k tokens.`,
304
+ likely_cause: 'Lockfile, build artifact, or scratch file is unignored in workspace.',
305
+ change_to_make: `Run: echo "${topIgnorable.path}" >> .antigravityignore`,
306
+ confidence: 'High',
307
+ rollback_method: 'Remove line from .antigravityignore'
308
+ });
309
+ }
310
+
311
+ // Rec 2: Active source file duplicate reads -> Line-bounded read_file or Surgical Pruner
312
+ const sourceHotspots = allHotspots.filter(h => !isIgnorablePath(h.path));
313
+ if (sourceHotspots.length > 0) {
314
+ const topSource = sourceHotspots[0];
315
+ const wastedK = Math.max(0.1, (topSource.wastedTokens / 1000).toFixed(1));
316
+ const stepStr = topSource.sampleSteps.length > 0 ? ` (e.g., steps [${topSource.sampleSteps.join(', ')}])` : '';
317
+ recommendations.push({
318
+ id: 'REC-BOUNDED-SOURCE-READS',
319
+ observed_pattern: `Source file "${topSource.path}" had ${topSource.occurrences} superseded read(s) across ${topSource.sessions.size} session(s)${stepStr}, wasting ~${wastedK}k tokens.`,
320
+ likely_cause: 'Unbounded full-file reads instead of targeted line-range reads or surgical pruning.',
321
+ change_to_make: `Use line-bounded reads: read_file { Path: "${topSource.path}", StartLine: 1, EndLine: 250 } or fold stale reads via npx ctxtop --serve (Condense Stale Reads).`,
322
+ confidence: 'High',
323
+ rollback_method: 'Restore from .pre_prune backup in session logs directory'
324
+ });
325
+ }
326
+
327
+ // Rec 3: Heavy MCP Server Schema Overhead
328
+ const mcpRows = (baseline?.rows || []).filter(r => r.kind === 'mcp' && (r.schemaTokens || r.tokens) >= 4000);
329
+ if (mcpRows.length > 0) {
330
+ const topMcp = mcpRows.sort((a, b) => (b.schemaTokens || b.tokens) - (a.schemaTokens || a.tokens))[0];
331
+ const schemaTok = topMcp.schemaTokens || topMcp.tokens;
332
+ recommendations.push({
333
+ id: 'REC-MCP-SCHEMA-TAX',
334
+ observed_pattern: `${topMcp.source} injects ~${Math.round(schemaTok / 1000)}k tokens (${topMcp.toolCount || '?'} tools) into Turn-0 baseline metadata.`,
335
+ likely_cause: 'Large MCP server tool catalog loaded in workspace or global config.',
336
+ change_to_make: `Ensure ${topMcp.source.replace('MCP: ', '')} is set to "loading": "lazy" in ~/.gemini/config/mcp_config.json or disable when unused.`,
337
+ confidence: 'High',
338
+ rollback_method: 'Re-enable server in mcp_config.json'
339
+ });
340
+ }
341
+
342
+ // Rec 4: Amputation / Threshold Compaction
343
+ if (amputationSessionsCount > 0) {
344
+ recommendations.push({
345
+ id: 'REC-SAFE-LIMIT-COMPACT',
346
+ observed_pattern: `${amputationSessionsCount} of ${sessionCount} sessions crossed the safe attention limit (>140k-179k tokens).`,
347
+ likely_cause: 'Delayed compaction allowing superseded file snapshots and resolved error traces to accumulate.',
348
+ change_to_make: 'Save state to task.md and run /compact when active context crosses 140k tokens.',
349
+ confidence: 'High',
350
+ rollback_method: 'None'
351
+ });
352
+ }
353
+
354
+ // Rec 5: Verification / Error Loops
355
+ if (errorLoopCount > 0 || (strongProofRatePct < 50 && sessionCount >= 3)) {
356
+ recommendations.push({
357
+ id: 'REC-VERIFICATION-HYGIENE',
358
+ observed_pattern: errorLoopCount > 0
359
+ ? `${errorLoopCount} session(s) hit 3+ consecutive command failures with identical error fingerprints.`
360
+ : `Automated test proof was recorded in only ${strongProofRatePct}% of audited sessions.`,
361
+ likely_cause: 'Repeating failing commands in the main context window without isolating root cause.',
362
+ change_to_make: 'Delegate failing test triage to invoke_subagent (research) or register a CLI output dampener in .agents/hooks.json.',
363
+ confidence: 'High',
364
+ rollback_method: 'Remove PreToolUse entry from .agents/hooks.json'
365
+ });
366
+ }
367
+
368
+ const cappedRecommendations = recommendations.slice(0, 5);
369
+
370
+ const timestampStr = new Date().toISOString().replace(/[:.]/g, '-');
371
+ const outDir = path.join(getFlightcheckDir(), 'postmortems', timestampStr);
372
+
373
+ const reportMarkdown = [
374
+ '# Highbeam Session Postmortem Report',
375
+ '',
376
+ `**Generated**: ${new Date().toISOString()} `,
377
+ `**Sessions Audited**: ${isSynthetic ? '14 (Demo)' : sessionCount} `,
378
+ `**Total Active Tokens Inspected**: ${estTokensM} `,
379
+ '',
380
+ '## Executive Telemetry KPIs',
381
+ '',
382
+ '| KPI Dimension | Value | Rating | Health Guideline |',
383
+ '| :--- | :---: | :---: | :--- |',
384
+ `| **Worst Signal Purity** | **${worstPurityPct}%** | ${worstPurityPct >= 70 ? 'GOOD' : (worstPurityPct >= 45 ? 'WARN' : 'CRITICAL')} | Target >70% signal |`,
385
+ `| **Average Purity** | **${avgPurityPct}%** | ${avgPurityPct >= 70 ? 'GOOD' : (avgPurityPct >= 50 ? 'WARN' : 'CRITICAL')} | Historical average across sessions |`,
386
+ `| **Over-Limit Sessions** | **${amputationSessionsCount}** | ${amputationSessionsCount === 0 ? 'GOOD' : 'HAZARD'} | Sessions crossing safe token limit |`,
387
+ `| **Strong Proof Rate** | **${strongProofRatePct}%** | ${strongProofRatePct >= 70 ? 'GOOD' : (strongProofRatePct >= 40 ? 'MODERATE' : 'LOW')} | Verified via automated test suite |`,
388
+ `| **Avg Plan Revisions** | **${avgPlanRevisions}** | ${avgPlanRevisions <= 1.5 ? 'STABLE' : (avgPlanRevisions < 3 ? 'MODERATE' : 'CHURN')} | Revisions >= 3 indicate churn |`,
389
+ `| **Repetitive Error Loops** | **${errorLoopCount}** | ${errorLoopCount === 0 ? 'NONE' : 'DETECTED'} | Identical command failure fingerprint |`,
390
+ `| **Sludge Tax Wasted** | **${totalSludgeFormatted}** | TELEMETRY | Cumulative wasted re-sending noise |`,
391
+ '',
392
+ '## Top Hotspot Files (Duplicate Reads)',
393
+ '',
394
+ allHotspots.length === 0
395
+ ? '_No duplicate file reads detected across audited sessions._'
396
+ : [
397
+ '| File Path | Occurrences | Wasted Tokens | Sessions Affected | Action |',
398
+ '| :--- | :---: | :---: | :---: | :--- |',
399
+ ...allHotspots
400
+ .slice(0, 8)
401
+ .map(h => `| \`${h.path}\` | ${h.occurrences} | ~${Math.round(h.wastedTokens / 1000)}k | ${h.sessions.size} | ${isIgnorablePath(h.path) ? 'Add to `.antigravityignore`' : 'Use `StartLine`/`EndLine` or Surgical Pruner'} |`)
402
+ ].join('\n'),
403
+ '',
404
+ '## Actionable Recommendations (Max 5)',
405
+ '',
406
+ cappedRecommendations.length === 0
407
+ ? '_All inspected sessions exhibit clean context hygiene. No configuration changes required._'
408
+ : cappedRecommendations.map((r, idx) => [
409
+ `### ${idx + 1}. [${r.id}] ${r.change_to_make}`,
410
+ `- **Observed Pattern**: ${r.observed_pattern}`,
411
+ `- **Likely Cause**: ${r.likely_cause}`,
412
+ `- **Confidence**: ${r.confidence}`,
413
+ `- **Safe Rollback**: ${r.rollback_method}`
414
+ ].join('\n')).join('\n\n')
415
+ ].join('\n');
416
+
417
+ if (writeFiles && !isSynthetic) {
418
+ try {
419
+ atomicWriteFileSync(path.join(outDir, 'session_analysis_report.md'), reportMarkdown);
420
+
421
+ const jsonlContent = diagnostics.map(d => JSON.stringify(d)).join('\n');
422
+ atomicWriteFileSync(path.join(outDir, 'conversation_diagnostics.jsonl'), jsonlContent);
423
+ } catch {}
424
+ }
425
+
426
+ const hotspotsSummary = allHotspots.slice(0, 5).map(h => ({
427
+ path: h.path,
428
+ occurrences: h.occurrences,
429
+ wastedTokens: h.wastedTokens,
430
+ sessionsAffected: h.sessions.size,
431
+ ignorable: isIgnorablePath(h.path),
432
+ sampleSteps: h.sampleSteps
433
+ }));
434
+
435
+ const resultPayload = {
436
+ isSynthetic,
437
+ sessionCount: isSynthetic ? 14 : sessionCount,
438
+ estTokensM,
439
+ worstPurityPct,
440
+ avgPurityPct,
441
+ strongProofRatePct,
442
+ avgPlanRevisions,
443
+ amputationSessionsCount,
444
+ totalDuplicateReads: isSynthetic ? 47 : Math.max(0, totalDuplicateReadsCount),
445
+ totalDeadErrors: isSynthetic ? 19 : Math.max(0, totalDeadErrorsCount),
446
+ sludgeUsdFormatted: totalSludgeFormatted,
447
+ errorLoopCount,
448
+ hotspots: hotspotsSummary,
449
+ worstSessionOffender,
450
+ recommendations: cappedRecommendations,
451
+ gitLedger,
452
+ reportPath: writeFiles && !isSynthetic ? path.join(outDir, 'session_analysis_report.md') : null,
453
+ diagnostics
454
+ };
455
+
456
+ if (json) {
457
+ console.log(JSON.stringify(resultPayload, null, 2));
458
+ }
459
+
460
+ return resultPayload;
461
+ }
462
+
463
+ export function printPostmortemSummary(res) {
464
+ console.log(`\n\x1b[1mHighbeam Forensic Postmortem (${res.sessionCount} sessions${res.isSynthetic ? ' [Demo]' : ''})\x1b[0m`);
465
+ console.log('='.repeat(76));
466
+ console.log(` Tokens Inspected : ${res.estTokensM} | Avg Purity : ${res.avgPurityPct}% (Worst: ${res.worstPurityPct}%)`);
467
+ console.log(` Duplicate Reads : ${res.totalDuplicateReads} reads | Dead Errors: ${res.totalDeadErrors} traces | Est. Waste: ${res.sludgeUsdFormatted}`);
468
+ console.log(` Over Safe Limit : ${res.amputationSessionsCount} sessions | Error Loops: ${res.errorLoopCount} | Proof Rate: ${res.strongProofRatePct}%`);
469
+
470
+ if (res.hotspots && res.hotspots.length > 0) {
471
+ console.log('\n\x1b[1mTop Duplicate-Read File Hotspots:\x1b[0m');
472
+ for (const h of res.hotspots) {
473
+ const wastedK = Math.max(0.1, (h.wastedTokens / 1000).toFixed(1));
474
+ const stepsNote = h.sampleSteps && h.sampleSteps.length ? ` [steps ${h.sampleSteps.join(',')}]` : '';
475
+ console.log(` • ${h.path} — ${h.occurrences} superseded read(s) (~${wastedK}k tok wasted across ${h.sessionsAffected} session(s))${stepsNote}`);
476
+ }
477
+ }
478
+
479
+ if (res.recommendations && res.recommendations.length > 0) {
480
+ console.log('\n\x1b[1mConcrete Remediations:\x1b[0m');
481
+ for (const [idx, r] of res.recommendations.entries()) {
482
+ console.log(` ${idx + 1}. [\x1b[36m${r.id}\x1b[0m] ${r.change_to_make}`);
483
+ console.log(` └─ ${r.observed_pattern}`);
484
+ }
485
+ }
486
+
487
+ if (res.reportPath) {
488
+ console.log(`\nReport written to: \x1b[36m${res.reportPath}\x1b[0m\n`);
489
+ } else {
490
+ console.log('');
491
+ }
492
+ }
493
+
494
+ export function isPostmortemMain(argv1 = process.argv[1], metaUrl = import.meta.url) {
495
+ if (!argv1) return false;
496
+ try {
497
+ return fs.realpathSync(argv1) === fs.realpathSync(fileURLToPath(metaUrl));
498
+ } catch {
499
+ return path.resolve(argv1) === path.resolve(fileURLToPath(metaUrl));
500
+ }
501
+ }
502
+
503
+ const isMain = isPostmortemMain();
504
+ if (isMain) {
505
+ const args = process.argv.slice(2);
506
+ const lastIdx = args.indexOf('--last');
507
+ const last = lastIdx !== -1 ? Number(args[lastIdx + 1]) : 15;
508
+ const json = args.includes('--json');
509
+ const demo = args.includes('--demo');
510
+ runPostmortem({ last, json, demo, writeFiles: true }).then(res => {
511
+ if (!json) {
512
+ printPostmortemSummary(res);
513
+ }
514
+ });
515
+ }
@@ -0,0 +1,12 @@
1
+ /**
2
+ * @file src/coach/cacheGravityRouter.mjs
3
+ * Backward-compatibility Coach adapter re-exporting cache gravity router and flight computer.
4
+ */
5
+
6
+ export * from '../core-isomorphic/coach/cacheGravityRouter.mjs';
7
+ export {
8
+ calculateBreakEvenCStar,
9
+ computeClosedFormBreakEven,
10
+ evaluateCacheGravity,
11
+ MODEL_BREAK_EVEN_RATES
12
+ } from '../core-isomorphic/economics/cacheGravity.mjs';