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,1126 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { createRequire } from 'node:module';
5
+ import { execFileSync } from 'node:child_process';
6
+ import { getHomeDir, canonicalizePath, getAntigravitySurfaces } from './paths.mjs';
7
+ import { SESSION_RISK_THRESHOLDS, resolveModelCeiling } from './constants.mjs';
8
+ import { SQLITE_OPEN_READONLY_OPTIONS } from './parser.mjs';
9
+ import { PrefixCacheShield } from './prefix_cache_shield.mjs';
10
+ import { atomicWriteFileSync } from './atomic_io.mjs';
11
+ import { formatUtcHandoffTimestamp } from './coach/handoff_hydrator.mjs';
12
+
13
+ /**
14
+ * Phase 2: Cache-Aware Compaction, Tail Surgeon & Baton-Pass (/handoff) Coach (`compaction_coach.mjs`)
15
+ *
16
+ * Eliminates auto-compaction stalls, protects against the 256k binary clamp wipe,
17
+ * surgically trims uncached tail sludge without busting warm prefix caches,
18
+ * and executes zero-amnesia session handoffs with 5 deterministic sections.
19
+ */
20
+
21
+ export const WATERMARKS = Object.freeze({
22
+ CASCADE_SYNC: SESSION_RISK_THRESHOLDS.WARM_CACHE_LOCK_TOKENS,
23
+ WARM_CACHE_LOCK_MIN_TOKENS: SESSION_RISK_THRESHOLDS.WARM_CACHE_LOCK_TOKENS,
24
+ AUTO_COMPACT_SAFE: 179000,
25
+ BINARY_CLAMP: 256000, // 0x3e800 binary clamp
26
+ WARM_CACHE_LOCK_MAX_TOKENS: 160000,
27
+ BATON_PASS_TOKEN_TRIGGER: 145000,
28
+ WASTE_TRIGGER_TOKEN: 100000,
29
+ WASTE_TRIGGER_PCT: 45,
30
+ HIGH_TURN_THRESHOLD: 45,
31
+ LOW_SIGNAL_PCT_THRESHOLD: 35
32
+ });
33
+
34
+ /**
35
+ * Evaluates whether compaction should be deferred (Warm Cache Lock) or whether
36
+ * Baton-Pass (/handoff) should be triggered based on dual token + waste thresholds.
37
+ *
38
+ * @param {object} sessionTelemetry
39
+ * @returns {object} Assessment result with recommendations, actions, and badges
40
+ */
41
+ export function assessCompactionState(sessionTelemetry = {}) {
42
+ const totalTokens = Number(
43
+ sessionTelemetry.totalTokens ??
44
+ sessionTelemetry.totalActiveTokens ??
45
+ sessionTelemetry.contextTokens ??
46
+ 0
47
+ );
48
+
49
+ const cachedTokens = Number(
50
+ sessionTelemetry.cachedTokens ??
51
+ sessionTelemetry.cachedHistoryTokens ??
52
+ sessionTelemetry.cacheReadTokens ??
53
+ 0
54
+ );
55
+
56
+ const cacheTtlSeconds = Number(
57
+ sessionTelemetry.cacheTtlSeconds ??
58
+ sessionTelemetry.ttlRemainingSec ??
59
+ 0
60
+ );
61
+
62
+ const cacheHitRate = Number(
63
+ sessionTelemetry.cacheHitRate ??
64
+ (totalTokens > 0 ? cachedTokens / totalTokens : 0)
65
+ );
66
+
67
+ const reclaimableWastePct = Number(
68
+ sessionTelemetry.reclaimableWastePct ??
69
+ (totalTokens > 0 && sessionTelemetry.sludgeTokens
70
+ ? (Number(sessionTelemetry.sludgeTokens) / totalTokens) * 100
71
+ : (totalTokens > 0 && sessionTelemetry.reclaimableTokens
72
+ ? (Number(sessionTelemetry.reclaimableTokens) / totalTokens) * 100
73
+ : 0))
74
+ );
75
+
76
+ const reclaimableWasteTokens = Number(
77
+ sessionTelemetry.reclaimableWasteTokens ??
78
+ sessionTelemetry.sludgeTokens ??
79
+ sessionTelemetry.reclaimableTokens ??
80
+ Math.round((totalTokens * reclaimableWastePct) / 100)
81
+ );
82
+
83
+ const turnCount = Number(
84
+ sessionTelemetry.turnCount ??
85
+ sessionTelemetry.stepCount ??
86
+ 0
87
+ );
88
+
89
+ const lastTurnGitCommitted = Boolean(
90
+ sessionTelemetry.lastTurnGitCommitted ??
91
+ sessionTelemetry.last_turn_git_committed ??
92
+ false
93
+ );
94
+
95
+ const topicShiftDetected = Boolean(
96
+ sessionTelemetry.topicShiftDetected ??
97
+ sessionTelemetry.topic_shift ??
98
+ sessionTelemetry.topicShift ??
99
+ false
100
+ );
101
+
102
+ const activeSignalPct = Number(
103
+ sessionTelemetry.activeSignalPct ??
104
+ Math.max(0, 100 - reclaimableWastePct)
105
+ );
106
+
107
+ const explicitCeiling = Number(
108
+ sessionTelemetry.maxTokens ??
109
+ sessionTelemetry.ceilingTokens ??
110
+ sessionTelemetry.binaryClamp ??
111
+ 0
112
+ );
113
+ const dynamicModelId = sessionTelemetry.modelId || sessionTelemetry.model || null;
114
+ const resolvedBinaryClamp = explicitCeiling > 0
115
+ ? explicitCeiling
116
+ : (dynamicModelId
117
+ ? resolveModelCeiling(dynamicModelId, sessionTelemetry.contextWindow || null, { useLegacyDefault: false })
118
+ : WATERMARKS.BINARY_CLAMP);
119
+ const resolvedSafeLimit = Number(sessionTelemetry.safeLimitTokens) > 0
120
+ ? Number(sessionTelemetry.safeLimitTokens)
121
+ : (resolvedBinaryClamp === WATERMARKS.BINARY_CLAMP
122
+ ? WATERMARKS.AUTO_COMPACT_SAFE
123
+ : Math.round(resolvedBinaryClamp * 0.70));
124
+ const resolvedWarmLockMax = resolvedBinaryClamp > WATERMARKS.BINARY_CLAMP
125
+ ? Math.round(resolvedBinaryClamp * 0.625)
126
+ : WATERMARKS.WARM_CACHE_LOCK_MAX_TOKENS;
127
+
128
+ const clampDistance = Math.max(0, resolvedBinaryClamp - totalTokens);
129
+ const clampLabelK = `${Math.round(resolvedBinaryClamp / 1000)}k`;
130
+
131
+ const watermarks = {
132
+ current: totalTokens,
133
+ cascadeSync: WATERMARKS.CASCADE_SYNC,
134
+ safeLimit: resolvedSafeLimit,
135
+ binaryClamp: resolvedBinaryClamp,
136
+ clampDistance,
137
+ cachedTokens,
138
+ cacheHitRate,
139
+ cacheTtlSeconds,
140
+ turnCount,
141
+ activeSignalPct,
142
+ reclaimableWastePct,
143
+ reclaimableWasteTokens
144
+ };
145
+
146
+ // Rule 1: Warm Cache Lock
147
+ // While Cached Tokens >= 50,000, Cache Hit Rate >= 90%, TTL > 60s, and Total Tokens < warm lock max,
148
+ // suppress /compact and preserve 95% discount.
149
+ if (
150
+ cachedTokens >= WATERMARKS.WARM_CACHE_LOCK_MIN_TOKENS &&
151
+ cacheHitRate >= 0.90 &&
152
+ cacheTtlSeconds > 60 &&
153
+ totalTokens < resolvedWarmLockMax
154
+ ) {
155
+ return {
156
+ action: 'DEFER_COMPACTION',
157
+ badge: '🛡️ Prefix Cache Warm (95% discount active) — Defer Compaction',
158
+ shouldCompact: false,
159
+ recommendBatonPass: false,
160
+ recommendTailTrim: false,
161
+ warmCacheLocked: true,
162
+ reason: `Prefix cache is warm (${(cacheHitRate * 100).toFixed(0)}% hit rate, ${cacheTtlSeconds}s TTL remaining). Compacting now would discard the warm prefix cache and force cold-prefill costs.`,
163
+ triggers: {
164
+ warmCacheLock: true,
165
+ tokenTrigger: false,
166
+ wasteTrigger: false,
167
+ turnDegradationTrigger: false
168
+ },
169
+ watermarks
170
+ };
171
+ }
172
+
173
+ // Rule 1b (Rank 4 — DET-17): Suppress premature /compact recommendations while prefix cache hit ratio > 96% below 50,000 tokens
174
+ if (
175
+ cacheHitRate > 0.96 &&
176
+ totalTokens > 0 &&
177
+ totalTokens < 50000 &&
178
+ (sessionTelemetry.cacheTtlSeconds === undefined || cacheTtlSeconds > 0)
179
+ ) {
180
+ return {
181
+ action: 'DEFER_COMPACTION',
182
+ detectorId: 'DET-17',
183
+ badge: '🛡️ Prefix Cache >96% Hit Below 50k — Suppress Premature /compact',
184
+ shouldCompact: false,
185
+ suppressPrematureCompact: true,
186
+ recommendBatonPass: false,
187
+ recommendTailTrim: false,
188
+ warmCacheLocked: true,
189
+ reason: `Prefix cache hit ratio is ${(cacheHitRate * 100).toFixed(1)}% (>96%) at ${totalTokens.toLocaleString()} tokens (<50,000). Suppressing premature /compact preserves the warm prefix cache.`,
190
+ triggers: {
191
+ warmCacheLock: true,
192
+ tokenTrigger: false,
193
+ wasteTrigger: false,
194
+ turnDegradationTrigger: false
195
+ },
196
+ watermarks
197
+ };
198
+ }
199
+
200
+ // Critical Near-Clamp Alarm (>= auto-compact safe limit)
201
+ if (totalTokens >= resolvedSafeLimit) {
202
+ return {
203
+ action: 'EXECUTE_BATON_PASS',
204
+ badge: `⚠️ Critical Binary Clamp Risk (Approaching ${clampLabelK} limit) — Execute /handoff immediately`,
205
+ shouldCompact: false,
206
+ recommendBatonPass: true,
207
+ recommendTailTrim: false,
208
+ warmCacheLocked: false,
209
+ reason: `Context is ${clampDistance.toLocaleString()} tokens away from the ${clampLabelK} (${resolvedBinaryClamp === 256000 ? '0x3e800 ' : ''}ceiling) clamp. Auto-compaction will wipe prefix cache and cause amnesia.`,
210
+ triggers: {
211
+ warmCacheLock: false,
212
+ tokenTrigger: true,
213
+ wasteTrigger: false,
214
+ turnDegradationTrigger: false
215
+ },
216
+ watermarks
217
+ };
218
+ }
219
+
220
+ // Rule 1c (Sim 06): Cold-Cache /compact Block — redirect expired cache (>= 25k tokens) to <300-tok StateBaton handoff
221
+ const cacheExpired = Boolean(
222
+ sessionTelemetry.cacheExpired === true ||
223
+ (cacheTtlSeconds === 0 && Number(sessionTelemetry.elapsedSeconds || 0) > Number(sessionTelemetry.effectiveTtlSeconds || 300))
224
+ );
225
+ if (cacheExpired && totalTokens >= 25000 && Boolean(sessionTelemetry.compactRequested)) {
226
+ return {
227
+ action: 'EXECUTE_BATON_PASS',
228
+ detectorId: 'DET-10',
229
+ coldCompactBlocked: true,
230
+ badge: '🧊 Cold Cache (/compact Blocked) — Execute <300-tok StateBaton Handoff',
231
+ shouldCompact: false,
232
+ recommendBatonPass: true,
233
+ recommendTailTrim: false,
234
+ warmCacheLocked: false,
235
+ reason: `Cache TTL expired (${totalTokens.toLocaleString()} cold tokens). Running /compact now would pay full uncached input rates to summarize stale history — use a <300-token StateBaton (/handoff + /clear) instead.`,
236
+ triggers: {
237
+ warmCacheLock: false,
238
+ coldCompactBlocked: true,
239
+ tokenTrigger: false,
240
+ wasteTrigger: false,
241
+ turnDegradationTrigger: false
242
+ },
243
+ watermarks
244
+ };
245
+ }
246
+
247
+ // Rule 2: Dual Token + Waste Trigger
248
+ // Trigger Baton-Pass (/handoff) Coach when:
249
+ // - Post-Commit Topic Shift (Turn >= 15 && totalTokens >= 25,000 && lastTurnGitCommitted && topicShiftDetected) OR
250
+ // - Total Tokens >= 145,000 OR
251
+ // - (Total Tokens >= 100,000 && Reclaimable Waste >= 45% && Cache TTL === 0) OR
252
+ // - (Turn count > 45 && Active Signal < 35%)
253
+ const postCommitOverride = String(
254
+ sessionTelemetry.postCommitHandoffOverride ??
255
+ sessionTelemetry.horizonConfig?.semanticDetectors?.['post-commit-handoff'] ??
256
+ 'default'
257
+ ).toLowerCase();
258
+ const postCommitShiftTrigger =
259
+ postCommitOverride !== 'off' &&
260
+ Boolean(lastTurnGitCommitted && topicShiftDetected && (turnCount === 0 || turnCount >= 15) && totalTokens >= 25000);
261
+ const tokenTrigger = totalTokens >= WATERMARKS.BATON_PASS_TOKEN_TRIGGER;
262
+ const wasteTrigger = totalTokens >= WATERMARKS.WASTE_TRIGGER_TOKEN && reclaimableWastePct >= WATERMARKS.WASTE_TRIGGER_PCT && cacheTtlSeconds === 0;
263
+ const turnDegradationTrigger = turnCount > WATERMARKS.HIGH_TURN_THRESHOLD && activeSignalPct < WATERMARKS.LOW_SIGNAL_PCT_THRESHOLD;
264
+
265
+ if (postCommitShiftTrigger || tokenTrigger || wasteTrigger || turnDegradationTrigger) {
266
+ let reason = '';
267
+ if (postCommitShiftTrigger) {
268
+ reason = `Post-commit topic shift detected at Turn ${turnCount} (${Math.round(totalTokens / 1000)}K tokens). Previous milestone is committed to git — run /handoff or /compact before starting a new feature on stale context.`;
269
+ } else if (tokenTrigger) {
270
+ reason = `Total context tokens (${totalTokens.toLocaleString()}) reached Baton-Pass watermark (${WATERMARKS.BATON_PASS_TOKEN_TRIGGER.toLocaleString()}). Execute zero-amnesia /handoff before hitting the ${WATERMARKS.AUTO_COMPACT_SAFE.toLocaleString()} safe limit.`;
271
+ } else if (wasteTrigger) {
272
+ reason = `Cold cache (TTL=0) with high reclaimable waste (${reclaimableWastePct.toFixed(1)}% >= 45% at ${totalTokens.toLocaleString()} tokens). Baton-pass will reset context cleanly.`;
273
+ } else {
274
+ reason = `Long-running session (${turnCount} turns > 45) with degraded active signal (${activeSignalPct.toFixed(1)}% < 35%). Fresh baton-pass recommended.`;
275
+ }
276
+
277
+ return {
278
+ action: 'EXECUTE_BATON_PASS',
279
+ badge: '🤝 Execute Baton Pass (/handoff) — Zero-Amnesia Session Reset',
280
+ shouldCompact: false,
281
+ recommendBatonPass: true,
282
+ recommendTailTrim: false,
283
+ warmCacheLocked: false,
284
+ reason,
285
+ triggers: {
286
+ warmCacheLock: false,
287
+ tokenTrigger,
288
+ wasteTrigger,
289
+ turnDegradationTrigger,
290
+ postCommitTopicShift: postCommitShiftTrigger
291
+ },
292
+ watermarks
293
+ };
294
+ }
295
+
296
+ // Uncached Tail Sludge recommendation:
297
+ if (reclaimableWasteTokens >= 2000 || reclaimableWastePct >= 20) {
298
+ return {
299
+ action: 'TRIM_UNCACHED_TAIL',
300
+ badge: '✂️ Trim Uncached Tail (Preserve 50k Prefix Cache)',
301
+ shouldCompact: false,
302
+ recommendBatonPass: false,
303
+ recommendTailTrim: true,
304
+ warmCacheLocked: false,
305
+ reason: `Uncached tail contains ${reclaimableWasteTokens.toLocaleString()} tokens of reclaimable waste. Surgical trim preserves the warm 50k prefix head intact.`,
306
+ triggers: {
307
+ warmCacheLock: false,
308
+ tokenTrigger: false,
309
+ wasteTrigger: false,
310
+ turnDegradationTrigger: false
311
+ },
312
+ watermarks
313
+ };
314
+ }
315
+
316
+ return {
317
+ action: 'NOMINAL',
318
+ badge: 'Context Health Nominal',
319
+ shouldCompact: false,
320
+ recommendBatonPass: false,
321
+ recommendTailTrim: false,
322
+ warmCacheLocked: false,
323
+ reason: 'Context usage is within healthy limits.',
324
+ triggers: {
325
+ warmCacheLock: false,
326
+ tokenTrigger: false,
327
+ wasteTrigger: false,
328
+ turnDegradationTrigger: false
329
+ },
330
+ watermarks
331
+ };
332
+ }
333
+
334
+ /**
335
+ * Surgically truncates redundant tool outputs (DET-06 repeated reads, DET-10 CLI floods)
336
+ * strictly AFTER the warm prefix cache boundary (0 .. cachedTokens).
337
+ *
338
+ * Guarantees that the head prefix remains 100% byte-for-byte identical (SHA-256 matched).
339
+ *
340
+ * @param {Array<object>} steps Transcript steps or turns
341
+ * @param {object} [options={}]
342
+ * @param {number} [options.cachedTokens=50000] Head prefix token boundary to protect
343
+ * @param {number} [options.maxRetainedChars=300] Characters retained for pruned tail entries
344
+ * @returns {object} { prunedSteps, savedTokens, modifiedCount, splitIndex, warmCachePreserved, headBytesPreserved }
345
+ */
346
+ export function trimUncachedTail(steps = [], options = {}) {
347
+ const list = Array.isArray(steps) ? steps : [];
348
+ const cachedTokensWatermark = Number.isFinite(options.cachedTokens)
349
+ ? options.cachedTokens
350
+ : WATERMARKS.CASCADE_SYNC;
351
+ const maxRetainedChars = Number.isFinite(options.maxRetainedChars)
352
+ ? Math.max(80, options.maxRetainedChars)
353
+ : 300;
354
+
355
+ if (list.length === 0) {
356
+ return {
357
+ prunedSteps: [],
358
+ savedTokens: 0,
359
+ modifiedCount: 0,
360
+ splitIndex: 0,
361
+ warmCachePreserved: true,
362
+ headBytesPreserved: true,
363
+ candidates: []
364
+ };
365
+ }
366
+
367
+ // 1. Identify prefix head boundary (0 .. splitIndex - 1)
368
+ // Pin all steps whose cumulative tokens fall within cachedTokensWatermark.
369
+ // Step 0 (initial prompt/system) is ALWAYS pinned.
370
+ let cumulativeTokens = 0;
371
+ let splitIndex = 1;
372
+
373
+ for (let i = 0; i < list.length; i++) {
374
+ const s = list[i];
375
+ const tok = Number(
376
+ s.totalTokens ??
377
+ s.tokens ??
378
+ s.output_tokens ??
379
+ s.outputTokens ??
380
+ (s.content ? Math.ceil(String(s.content).length / 4) : 0)
381
+ );
382
+ cumulativeTokens += tok;
383
+ if (cumulativeTokens <= cachedTokensWatermark) {
384
+ splitIndex = i + 1;
385
+ } else {
386
+ break;
387
+ }
388
+ }
389
+
390
+ // Ensure splitIndex is at least 1 and does not exceed list.length
391
+ splitIndex = Math.min(list.length, Math.max(1, splitIndex));
392
+
393
+ // Compute SHA-256 fingerprint of the protected head prefix
394
+ const headPrefixRaw = JSON.stringify(list.slice(0, splitIndex));
395
+ const headPrefixShaBefore = crypto.createHash('sha256').update(headPrefixRaw).digest('hex');
396
+
397
+ const prunedSteps = list.map(s => ({ ...s }));
398
+ const candidates = [];
399
+ let savedTokens = 0;
400
+ let modifiedCount = 0;
401
+
402
+ const extractStepCallMeta = (stepsArr, idx) => {
403
+ const step = stepsArr[idx] || {};
404
+ let calls = Array.isArray(step.toolCalls)
405
+ ? step.toolCalls
406
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : []);
407
+ if (calls.length === 0 && idx > 0) {
408
+ const prev = stepsArr[idx - 1] || {};
409
+ const prevCalls = Array.isArray(prev.toolCalls)
410
+ ? prev.toolCalls
411
+ : (Array.isArray(prev.tool_calls) ? prev.tool_calls : []);
412
+ const curCalls = Array.isArray(step.toolCalls)
413
+ ? step.toolCalls
414
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : []);
415
+ const isToolResult = prevCalls.length > 0 && curCalls.length === 0 && (
416
+ (prev.type === 'PLANNER_RESPONSE' && (step.type === 'GENERIC' || step.type === 'tool_result' || step.source === 'MODEL')) ||
417
+ (step.type === 'TOOL_RESULT' || step.type === 'tool_result' || step.source === 'TOOL')
418
+ );
419
+ if (isToolResult) {
420
+ calls = prevCalls;
421
+ }
422
+ }
423
+ const firstCall = calls[0] || {};
424
+ const rawToolName = String(firstCall.name || firstCall.tool || step.toolName || '').toLowerCase();
425
+ const args = firstCall.args || firstCall.parameters || firstCall.Arguments || {};
426
+ const rawPath = String(
427
+ args.Path || args.path || args.TargetFile || args.AbsolutePath || args.file_path || step.targetPath || ''
428
+ ).trim();
429
+ const canonPath = rawPath ? canonicalizePath(rawPath) : null;
430
+ const rawStart = args.StartLine ?? args.start_line ?? args.startLine ?? args.offset ?? firstCall.StartLine ?? step.startLine ?? null;
431
+ const rawEnd = args.EndLine ?? args.end_line ?? args.endLine ?? args.limit ?? firstCall.EndLine ?? step.endLine ?? null;
432
+ const normStart = rawStart !== null && rawStart !== undefined && rawStart !== '' && Number.isFinite(Number(rawStart))
433
+ ? Number(rawStart)
434
+ : 'FULL';
435
+ const normEnd = rawEnd !== null && rawEnd !== undefined && rawEnd !== '' && Number.isFinite(Number(rawEnd))
436
+ ? Number(rawEnd)
437
+ : 'FULL';
438
+ return { rawToolName, rawPath, canonPath, startLine: normStart, endLine: normEnd };
439
+ };
440
+
441
+ // Pass 1: Track (canonPath, startLine, endLine, lastEditTurnForPath) across the session
442
+ // so disjoint line ranges, post-edit verification reads, and the most recent active read are NEVER truncated.
443
+ const lastEditTurnByPath = new Map();
444
+ const stepReadKeyByIdx = new Map();
445
+ const latestTailReadIdxByKey = new Map();
446
+ const isEditToolRe = /^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content|edit|write|multiedit|notebookedit)$/i;
447
+ const isReadToolRe = /^(read_file|view_file|read)$/i;
448
+
449
+ for (let idx = 0; idx < prunedSteps.length; idx++) {
450
+ const meta = extractStepCallMeta(prunedSteps, idx);
451
+ if (meta.canonPath && isEditToolRe.test(meta.rawToolName)) {
452
+ lastEditTurnByPath.set(meta.canonPath, idx);
453
+ } else if (meta.canonPath && isReadToolRe.test(meta.rawToolName)) {
454
+ const lastEditTurn = lastEditTurnByPath.has(meta.canonPath)
455
+ ? lastEditTurnByPath.get(meta.canonPath)
456
+ : -1;
457
+ const readKey = `${meta.canonPath}::${meta.startLine}::${meta.endLine}::${lastEditTurn}`;
458
+ stepReadKeyByIdx.set(idx, { readKey, lastEditTurn, ...meta });
459
+ if (idx >= splitIndex) {
460
+ latestTailReadIdxByKey.set(readKey, idx);
461
+ }
462
+ }
463
+ }
464
+
465
+ const baseWorkspace = options.cwd || options.workspacePath || null;
466
+ const resolvedOffloadDir = options.offloadDir || (baseWorkspace ? path.join(baseWorkspace, '.agents', 'tmp') : null);
467
+
468
+ for (let i = splitIndex; i < prunedSteps.length; i++) {
469
+ const step = prunedSteps[i];
470
+ const content = String(
471
+ step.content ??
472
+ step.toolUseResult?.stdout ??
473
+ step.toolUseResult?.content ??
474
+ step.toolFormerData?.result ??
475
+ ''
476
+ );
477
+
478
+ const { rawToolName, rawPath, canonPath } = extractStepCallMeta(prunedSteps, i);
479
+ const readMeta = stepReadKeyByIdx.get(i) || null;
480
+ const isReadStep = Boolean(canonPath && isReadToolRe.test(rawToolName));
481
+ const latestIdxForReadKey = readMeta ? latestTailReadIdxByKey.get(readMeta.readKey) : undefined;
482
+ const isLatestActiveRead = isReadStep && (latestIdxForReadKey === undefined || latestIdxForReadKey === i);
483
+
484
+ let candidateReason = null;
485
+
486
+ // A. DET-06: Repeated identical (canonPath, startLine, endLine, lastEditTurn) read in the tail.
487
+ // Preserve the MOST RECENT read intact; only older superseded identical reads are candidates.
488
+ if (isReadStep && readMeta && latestIdxForReadKey !== undefined && i < latestIdxForReadKey) {
489
+ candidateReason = 'DET-06_REDUNDANT_READ';
490
+ }
491
+
492
+ // B. DET-10: Unbounded CLI output flood (>12,000 characters or >80 lines)
493
+ if (!candidateReason && /^(run_command|execute_bash|bash|exec|powershell)$/i.test(rawToolName)) {
494
+ const lineCount = content.split(/\r?\n/).length;
495
+ if (content.length > 12000 || lineCount > 80) {
496
+ candidateReason = 'DET-10_CLI_FLOOD';
497
+ }
498
+ }
499
+
500
+ // C. Explicitly flagged or unreferenced search output (>1,200 chars)
501
+ if (!candidateReason && /^(grep|grep_search|find|find_by_name|search)$/i.test(rawToolName) && content.length > 1200) {
502
+ candidateReason = 'UNREFERENCED_SEARCH_OUTPUT';
503
+ }
504
+
505
+ // D. Prunable flag from caller (never slice the latest active read_file/view_file output)
506
+ if (!candidateReason && !isLatestActiveRead && (step.canPrune === true || step.isPrunable === true)) {
507
+ candidateReason = step.pruneReason || 'EXPLICIT_TAIL_PRUNE';
508
+ }
509
+
510
+ if (candidateReason && content.length > maxRetainedChars + 60) {
511
+ let offloadAbsPath = null;
512
+ let offloadPointer = null;
513
+ if (resolvedOffloadDir) {
514
+ const hash12 = crypto.createHash('sha256').update(content, 'utf8').digest('hex').slice(0, 12);
515
+ const fileName = `offload_${hash12}.txt`;
516
+ offloadAbsPath = path.join(resolvedOffloadDir, fileName);
517
+ offloadPointer = baseWorkspace && !options.offloadDir
518
+ ? `.agents/tmp/${fileName}`
519
+ : `.agents/tmp/${fileName}`;
520
+ try {
521
+ atomicWriteFileSync(offloadAbsPath, content, { encoding: 'utf8' });
522
+ } catch {
523
+ // ISS-040 Safety Invariant: if offload persistence fails, preserve raw output intact!
524
+ continue;
525
+ }
526
+ }
527
+
528
+ const headSlice = content.slice(0, maxRetainedChars).trimEnd();
529
+ const droppedChars = content.length - headSlice.length;
530
+ const stepSavedTok = Math.max(1, Math.floor(droppedChars / 4));
531
+ const pointerNote = offloadPointer ? ` — full output preserved at ${offloadPointer}` : '';
532
+ const annotation = `\n... [Tail Surgeon (${candidateReason}): truncated ${droppedChars} chars (~${stepSavedTok} tok) after warm cache watermark${pointerNote}]`;
533
+ const truncatedContent = `${headSlice}${annotation}`;
534
+
535
+ prunedSteps[i] = {
536
+ ...prunedSteps[i],
537
+ content: truncatedContent,
538
+ output_tokens: Math.ceil(truncatedContent.length / 4),
539
+ outputTokens: Math.ceil(truncatedContent.length / 4),
540
+ tailSurgeonTruncated: true,
541
+ tailSurgeonReason: candidateReason,
542
+ savedTokens: stepSavedTok,
543
+ ...(offloadAbsPath ? { offloadPath: offloadAbsPath, offloadPointer } : {})
544
+ };
545
+
546
+ candidates.push({
547
+ stepIndex: i,
548
+ toolName: rawToolName || 'tool',
549
+ targetPath: rawPath || null,
550
+ reason: candidateReason,
551
+ originalLength: content.length,
552
+ truncatedLength: truncatedContent.length,
553
+ savedTokens: stepSavedTok,
554
+ ...(offloadAbsPath ? { offloadPath: offloadAbsPath, offloadPointer } : {})
555
+ });
556
+
557
+ savedTokens += stepSavedTok;
558
+ modifiedCount++;
559
+ }
560
+ }
561
+
562
+ // 3. Verify head prefix is 100% byte-identical
563
+ const headPrefixRawAfter = JSON.stringify(prunedSteps.slice(0, splitIndex));
564
+ const headPrefixShaAfter = crypto.createHash('sha256').update(headPrefixRawAfter).digest('hex');
565
+ const headBytesPreserved = headPrefixShaBefore === headPrefixShaAfter;
566
+
567
+ return {
568
+ prunedSteps,
569
+ savedTokens,
570
+ modifiedCount,
571
+ splitIndex,
572
+ warmCachePreserved: true,
573
+ headBytesPreserved,
574
+ candidates
575
+ };
576
+ }
577
+
578
+ /**
579
+ * Parses markdown task checklist items into completed [x], in-progress [/], and pending [ ] sets.
580
+ */
581
+ export function parseTaskChecklist(taskMdContent = '') {
582
+ const text = String(taskMdContent || '');
583
+ const lines = text.split(/\r?\n/);
584
+ const completed = [];
585
+ const inProgress = [];
586
+ const pending = [];
587
+
588
+ for (const rawLine of lines) {
589
+ const line = rawLine.trim();
590
+ if (/^[-*]\s*\[x\]/i.test(line)) {
591
+ completed.push(line.replace(/^[-*]\s*\[x\]\s*/i, '').trim());
592
+ } else if (/^[-*]\s*\[\/\]/i.test(line)) {
593
+ inProgress.push(line.replace(/^[-*]\s*\[\/\]\s*/i, '').trim());
594
+ } else if (/^[-*]\s*\[ \]/i.test(line)) {
595
+ pending.push(line.replace(/^[-*]\s*\[ \]\s*/i, '').trim());
596
+ }
597
+ }
598
+
599
+ return { completed, inProgress, pending };
600
+ }
601
+
602
+ /**
603
+ * Extracts exported functions, classes, interfaces, and types from touched source files.
604
+ */
605
+ export function extractFileSignatures(filePaths = [], { workspacePath = '' } = {}) {
606
+ const results = [];
607
+
608
+ for (const relOrAbs of filePaths) {
609
+ if (!relOrAbs || typeof relOrAbs !== 'string') continue;
610
+ const absPath = path.isAbsolute(relOrAbs) ? relOrAbs : path.join(workspacePath, relOrAbs);
611
+ if (!fs.existsSync(absPath)) continue;
612
+
613
+ try {
614
+ const stat = fs.statSync(absPath);
615
+ if (!stat.isFile()) continue;
616
+
617
+ const content = fs.readFileSync(absPath, 'utf8');
618
+ const ext = path.extname(absPath).toLowerCase();
619
+ const functions = [];
620
+ const classes = [];
621
+ const types = [];
622
+
623
+ if (/^\.(mjs|js|ts|tsx|jsx)$/.test(ext)) {
624
+ const lines = content.split(/\r?\n/);
625
+ for (const line of lines) {
626
+ const fnMatch = line.match(/^export\s+(?:async\s+)?function\s+([A-Za-z0-9_$]+)\s*\(/);
627
+ if (fnMatch) functions.push(fnMatch[1]);
628
+
629
+ const classMatch = line.match(/^export\s+class\s+([A-Za-z0-9_$]+)/);
630
+ if (classMatch) classes.push(classMatch[1]);
631
+
632
+ const typeMatch = line.match(/^export\s+(?:type|interface)\s+([A-Za-z0-9_$]+)/);
633
+ if (typeMatch) types.push(typeMatch[1]);
634
+
635
+ const constMatch = line.match(/^export\s+const\s+([A-Za-z0-9_$]+)\s*=/);
636
+ if (constMatch && !functions.includes(constMatch[1])) {
637
+ types.push(constMatch[1]);
638
+ }
639
+ }
640
+ } else if (ext === '.py') {
641
+ const lines = content.split(/\r?\n/);
642
+ for (const line of lines) {
643
+ const fnMatch = line.match(/^(?:async\s+)?def\s+([A-Za-z0-9_]+)\s*\(/);
644
+ if (fnMatch) functions.push(fnMatch[1]);
645
+
646
+ const classMatch = line.match(/^class\s+([A-Za-z0-9_]+)/);
647
+ if (classMatch) classes.push(classMatch[1]);
648
+ }
649
+ }
650
+
651
+ results.push({
652
+ path: relOrAbs,
653
+ functions,
654
+ classes,
655
+ types
656
+ });
657
+ } catch {
658
+ // Gracefully continue on read errors
659
+ }
660
+ }
661
+
662
+ return results;
663
+ }
664
+
665
+ /**
666
+ * Safely queries the latest test execution state recorded in Phase 1's SQLite FTS5 table.
667
+ */
668
+ export function queryLatestFts5TestState(dbPath, sessionId = null) {
669
+ if (!dbPath || !fs.existsSync(dbPath)) return null;
670
+
671
+ try {
672
+ // node:sqlite DatabaseSync with SQLITE_OPEN_READONLY_OPTIONS
673
+ const { DatabaseSync } = (typeof process !== 'undefined' && process.versions?.node)
674
+ ? requireNodeSqlite()
675
+ : {};
676
+ if (!DatabaseSync) return null;
677
+
678
+ const db = new DatabaseSync(dbPath, SQLITE_OPEN_READONLY_OPTIONS);
679
+ let row = null;
680
+ try {
681
+ if (sessionId) {
682
+ const stmt = db.prepare('SELECT command, exit_code, raw_output, created_at FROM tool_logs WHERE session_id = ? ORDER BY rowid DESC LIMIT 1');
683
+ row = stmt.get(sessionId);
684
+ } else {
685
+ const stmt = db.prepare('SELECT command, exit_code, raw_output, created_at FROM tool_logs ORDER BY rowid DESC LIMIT 1');
686
+ row = stmt.get();
687
+ }
688
+ } finally {
689
+ db.close();
690
+ }
691
+
692
+ if (!row) return null;
693
+
694
+ const raw = String(row.raw_output || '');
695
+ const lines = raw.split(/\r?\n/);
696
+ const failingTests = lines
697
+ .filter(l => /^(FAILED|FAIL|✖)\s+|AssertionError/i.test(l.trim()))
698
+ .slice(0, 5)
699
+ .map(l => l.trim().slice(0, 120));
700
+
701
+ return {
702
+ command: row.command,
703
+ exitCode: Number(row.exit_code),
704
+ createdAt: row.created_at,
705
+ failingTests,
706
+ rawOutputPreview: lines.slice(0, 10).join('\n')
707
+ };
708
+ } catch {
709
+ return null;
710
+ }
711
+ }
712
+
713
+ function requireNodeSqlite() {
714
+ try {
715
+ const req = createRequire(import.meta.url);
716
+ return req('node:sqlite');
717
+ } catch {
718
+ return {};
719
+ }
720
+ }
721
+
722
+ /**
723
+ * Generates the deterministic 5-section markdown checkpoint for Baton Pass (/handoff).
724
+ *
725
+ * Sections:
726
+ * 1. Progressive Checkpoint Summary ([x], [/], [ ])
727
+ * 2. Active File Schemas & AST Signatures + git diff --stat
728
+ * 3. Verified Test & Build State (from Phase 1 SQLite FTS5 index)
729
+ * 4. Negative Constraints & Dead Ends (failed loops, DET-01..16 violations)
730
+ * 5. Pending RSI Instincts (queued in PrefixCacheShield)
731
+ * + Active Guardrail Pin
732
+ *
733
+ * @param {object} state
734
+ * @param {object} [options={}]
735
+ * @returns {string} Formatted markdown document
736
+ */
737
+ export function generateHandoffMarkdown(state = {}, options = {}) {
738
+ const timestamp = options.timestamp || new Date().toISOString();
739
+ const sourceSessionId = state.sessionId || state.guid || 'active-session';
740
+ const targetSessionId = options.newSessionId || options.newGuid || 'new-session';
741
+ const activeModel = state.modelId || state.model || state.activeModel || 'gemini-3.1-pro';
742
+ const totalTokens = state.totalTokens ?? state.totalActiveTokens ?? 0;
743
+ const workspacePath = options.workspacePath || process.cwd();
744
+
745
+ // 1. Parse Checkpoint Items from task.md
746
+ let checklist = { completed: [], inProgress: [], pending: [] };
747
+ if (state.taskMdContent) {
748
+ checklist = parseTaskChecklist(state.taskMdContent);
749
+ } else if (state.taskMdPath && fs.existsSync(state.taskMdPath)) {
750
+ try {
751
+ checklist = parseTaskChecklist(fs.readFileSync(state.taskMdPath, 'utf8'));
752
+ } catch {}
753
+ } else if (state.checklist) {
754
+ checklist = state.checklist;
755
+ }
756
+
757
+ // 2. Active File Schemas & AST Signatures
758
+ const activeFiles = Array.isArray(state.activeFiles)
759
+ ? state.activeFiles
760
+ : (Array.isArray(state.modifiedFiles) ? state.modifiedFiles : []);
761
+ const fileSignatures = extractFileSignatures(activeFiles, { workspacePath });
762
+
763
+ let gitDiffStat = state.gitDiffStat || '';
764
+ if (!gitDiffStat && workspacePath && fs.existsSync(workspacePath)) {
765
+ try {
766
+ gitDiffStat = execFileSync('git', ['diff', '--stat'], {
767
+ cwd: workspacePath,
768
+ encoding: 'utf8',
769
+ timeout: 2500,
770
+ stdio: ['ignore', 'pipe', 'ignore']
771
+ }).trim();
772
+ } catch {
773
+ gitDiffStat = '(Clean git status or diff unavailable)';
774
+ }
775
+ }
776
+
777
+ // 3. Verified Test & Build State
778
+ let testState = state.verifiedTestState || null;
779
+ if (!testState && options.fts5DbPath) {
780
+ testState = queryLatestFts5TestState(options.fts5DbPath, sourceSessionId);
781
+ }
782
+ if (!testState && state.lastTestCommand) {
783
+ testState = {
784
+ command: state.lastTestCommand,
785
+ exitCode: state.lastTestExitCode ?? 0,
786
+ failingTests: state.failingTests || []
787
+ };
788
+ }
789
+
790
+ // 4. Negative Constraints & Dead Ends
791
+ const negativeConstraints = Array.isArray(state.negativeConstraints)
792
+ ? state.negativeConstraints
793
+ : (Array.isArray(state.deadEnds) ? state.deadEnds : []);
794
+ const detectorViolations = Array.isArray(state.detectorViolations) ? state.detectorViolations : [];
795
+
796
+ // 5. Pending RSI Instincts & Staged Rules
797
+ const pendingRules = Array.isArray(state.pendingRuleDeltas)
798
+ ? state.pendingRuleDeltas
799
+ : (Array.isArray(state.stagedDeltas) ? state.stagedDeltas : []);
800
+
801
+ const exactNextStep = state.exactNextStep ||
802
+ checklist.inProgress[0] ||
803
+ checklist.pending[0] ||
804
+ 'Verify test suite and proceed with next roadmap phase';
805
+
806
+ // Build unified cross-edition 6-section State Baton markdown (ISS-054)
807
+ const md = [];
808
+ md.push(`# Highbeam State Baton Handoff`);
809
+ md.push(`- **Session ID:** \`${sourceSessionId}\``);
810
+ md.push(`- **Target Session:** \`${targetSessionId}\``);
811
+ md.push(`- **Active Model:** \`${activeModel}\``);
812
+ md.push(`- **Captured At:** \`${timestamp}\``);
813
+ md.push(`- **Context at Handoff:** \`${totalTokens.toLocaleString()} tokens\` (Safe Limit: 179,000 | Clamp: 256,000)`);
814
+ md.push(``);
815
+
816
+ // Section 1: Active Goal
817
+ md.push(`## 1. Active Goal`);
818
+ md.push(`### Completed Milestones (\`[x]\`)`);
819
+ if (checklist.completed.length > 0) {
820
+ for (const item of checklist.completed) {
821
+ md.push(`- [x] ${item}`);
822
+ }
823
+ } else {
824
+ md.push(`- (No completed items recorded)`);
825
+ }
826
+ md.push(``);
827
+
828
+ md.push(`### In-Progress Work (\`[/]\`)`);
829
+ if (checklist.inProgress.length > 0) {
830
+ for (const item of checklist.inProgress) {
831
+ md.push(`- [/] ${item}`);
832
+ }
833
+ } else {
834
+ md.push(`- (No active in-progress items)`);
835
+ }
836
+ md.push(``);
837
+
838
+ md.push(`### Pending Backlog (\`[ ]\`)`);
839
+ if (checklist.pending.length > 0) {
840
+ for (const item of checklist.pending) {
841
+ md.push(`- [ ] ${item}`);
842
+ }
843
+ } else {
844
+ md.push(`- (Backlog fully cleared)`);
845
+ }
846
+ md.push(``);
847
+
848
+ // Section 2: Working Set Files
849
+ md.push(`## 2. Working Set Files`);
850
+ if (fileSignatures.length > 0) {
851
+ for (const sig of fileSignatures) {
852
+ md.push(`- **\`${sig.path}\`**:`);
853
+ if (sig.functions.length > 0) md.push(` - Functions: \`${sig.functions.join('`, `')}\``);
854
+ if (sig.classes.length > 0) md.push(` - Classes: \`${sig.classes.join('`, `')}\``);
855
+ if (sig.types.length > 0) md.push(` - Types/Exports: \`${sig.types.join('`, `')}\``);
856
+ }
857
+ } else if (activeFiles.length > 0) {
858
+ for (const f of activeFiles) {
859
+ md.push(`- \`${f}\``);
860
+ }
861
+ } else {
862
+ md.push(`- (No active files modified in this session)`);
863
+ }
864
+ md.push(``);
865
+
866
+ md.push(`### Uncommitted Git Status & Diff Stat`);
867
+ md.push('```');
868
+ md.push(gitDiffStat || '(No uncommitted git changes)');
869
+ md.push('```');
870
+ md.push(``);
871
+
872
+ // Section 3: Verified Invariants
873
+ md.push(`## 3. Verified Invariants`);
874
+ if (testState) {
875
+ const statusStr = testState.exitCode === 0 ? '✅ PASSED (exit code 0)' : `❌ FAILED (exit code ${testState.exitCode})`;
876
+ md.push(`- **Last Command**: \`${testState.command || 'npm test'}\``);
877
+ md.push(`- **Status**: ${statusStr}`);
878
+ if (Array.isArray(testState.failingTests) && testState.failingTests.length > 0) {
879
+ md.push(`- **Failing Tests (${testState.failingTests.length})**:`);
880
+ for (const ft of testState.failingTests) {
881
+ md.push(` - \`${ft}\``);
882
+ }
883
+ }
884
+ } else {
885
+ md.push(`- Last Verified Status: ✅ Clean build / test suite passing`);
886
+ }
887
+ md.push(``);
888
+
889
+ // Section 4: Dead Ends & Failures to Avoid
890
+ md.push(`## 4. Dead Ends & Failures to Avoid`);
891
+ if (negativeConstraints.length > 0 || detectorViolations.length > 0) {
892
+ for (const nc of negativeConstraints) {
893
+ md.push(`- 🚫 **Dead End / Blocked**: ${nc}`);
894
+ }
895
+ for (const det of detectorViolations) {
896
+ md.push(`- 🛡️ **Detector Halt (\`${det.id || 'DET'}\`)**: ${det.message || det.reason}`);
897
+ }
898
+ } else {
899
+ md.push(`- (No dead-ends or loop spirals detected; follow existing architectural invariants)`);
900
+ }
901
+ md.push(``);
902
+
903
+ // Section 5: Queued Cache-Prefix Mutations (Released on PostCompact)
904
+ md.push(`## 5. Queued Cache-Prefix Mutations (Released on PostCompact)`);
905
+ if (pendingRules.length > 0) {
906
+ for (const delta of pendingRules) {
907
+ md.push(`- **[Staged Delta \`${delta.operation || 'ADD'}\`]** \`${delta.targetPath || 'GEMINI.md'}\`:`);
908
+ md.push(` \`\`\`markdown`);
909
+ md.push(` ${delta.ruleText || delta.newContent || JSON.stringify(delta)}`);
910
+ md.push(` \`\`\``);
911
+ }
912
+ } else {
913
+ md.push(`- (All staged rules flushed; zero pending mutations)`);
914
+ }
915
+ md.push(``);
916
+
917
+ // Section 6: Exact Next Step
918
+ md.push(`## 6. Exact Next Step`);
919
+ md.push(`- ${exactNextStep}`);
920
+ md.push(``);
921
+
922
+ // Active Guardrail Pin
923
+ md.push(`## Active Guardrail Pin`);
924
+ md.push(`- **NEVER** mutate \`GEMINI.md\`, \`AGENTS.md\`, \`.agents/CONTEXT.md\`, or \`SKILL.md\` while \`Cached History >= 50,000\` and \`Cache TTL > 0s\`; always route persistent rule writes through \`PrefixCacheShield\`.`);
925
+ md.push(`- **NEVER** open Antigravity host session databases in write mode; preserve \`SQLITE_OPEN_READONLY_OPTIONS\` (\`{ readOnly: true }\`).`);
926
+ md.push(`- **NEVER** delete, weaken, or skip existing \`assert\` / \`expect\` statements in any test file (\`DET-03\`).`);
927
+ md.push(`- **NEVER** render a clickable Copy \`/compact\` button in UI panels.`);
928
+ md.push(``);
929
+
930
+ return md.join('\n');
931
+ }
932
+
933
+ /**
934
+ * Executes a complete Baton Pass (/handoff) operation:
935
+ * 1. Generates `docs/HANDOFF_<YYYYMMDD_HHMMSS>.md`, `.agents/horizon/HANDOFF_LATEST.md`, and `.gemini/antigravity/agy-horizon/handoffs/HANDOFF_<GUID>.md`
936
+ * 2. Flushes staged `PrefixCacheShield` deltas to disk
937
+ * 3. Pre-seeds `<NEW_GUID>` brain directory with `task.md` and `implementation_plan.md`
938
+ *
939
+ * @param {object} state Active session state
940
+ * @param {object} [options={}]
941
+ * @returns {object} Handoff execution report
942
+ */
943
+ export function executeBatonPassHandoff(state = {}, options = {}) {
944
+ const homeDir = options.homeDir || getHomeDir();
945
+ const workspacePath = options.workspacePath || process.cwd();
946
+ const rawTimestamp = options.timestamp || new Date().toISOString();
947
+ const formattedTimestamp = formatUtcHandoffTimestamp(rawTimestamp);
948
+ const newGuid = options.newSessionId || options.newGuid || crypto.randomUUID();
949
+
950
+ // 1. Initialize PrefixCacheShield if provided or instantiate default
951
+ const shield = options.prefixCacheShield || new PrefixCacheShield({ homeDir });
952
+ const stagedStatus = shield.getStatus();
953
+
954
+ // Resolve taskMdContent if taskMdPath is provided
955
+ let taskMdContent = state.taskMdContent;
956
+ if (!taskMdContent && state.taskMdPath && fs.existsSync(state.taskMdPath)) {
957
+ try {
958
+ taskMdContent = fs.readFileSync(state.taskMdPath, 'utf8');
959
+ } catch {}
960
+ }
961
+
962
+ // Combine state with staged deltas and taskMdContent for handoff markdown
963
+ const compositeState = {
964
+ ...state,
965
+ taskMdContent,
966
+ stagedDeltas: stagedStatus.deltas || state.stagedDeltas || []
967
+ };
968
+
969
+ const handoffContent = generateHandoffMarkdown(compositeState, {
970
+ timestamp: rawTimestamp,
971
+ newSessionId: newGuid,
972
+ workspacePath,
973
+ fts5DbPath: options.fts5DbPath
974
+ });
975
+
976
+ // 2. Write `docs/HANDOFF_<YYYYMMDD_HHMMSS>.md` AND `.agents/horizon/HANDOFF_LATEST.md` in workspace
977
+ const docsDir = options.docsDir || path.join(workspacePath, 'docs');
978
+ const docsHandoffPath = path.join(docsDir, `HANDOFF_${formattedTimestamp}.md`);
979
+ const latestHandoffPath = path.join(workspacePath, '.agents', 'horizon', 'HANDOFF_LATEST.md');
980
+ atomicWriteFileSync(docsHandoffPath, handoffContent, { encoding: 'utf8' });
981
+ atomicWriteFileSync(latestHandoffPath, handoffContent, { encoding: 'utf8' });
982
+
983
+ // 3. Write `.gemini/antigravity/agy-horizon/handoffs/HANDOFF_<GUID>.md`
984
+ const horizonHandoffDir = options.horizonHandoffDir || path.join(homeDir, '.gemini', 'antigravity', 'agy-horizon', 'handoffs');
985
+ const horizonHandoffPath = path.join(horizonHandoffDir, `HANDOFF_${newGuid}.md`);
986
+ atomicWriteFileSync(horizonHandoffPath, handoffContent, { encoding: 'utf8' });
987
+
988
+ // 4. Flush PrefixCacheShield deltas now that session is handing off
989
+ const flushResult = shield.flushOnHandoff();
990
+
991
+ // 5. Pre-seed <NEW_GUID> brain session directory
992
+ const defaultBrainBase = getAntigravitySurfaces(homeDir)[0]?.brainDir || path.join(homeDir, '.gemini', 'antigravity', 'brain');
993
+ const brainBaseDir = options.brainBaseDir || defaultBrainBase;
994
+ const newBrainDir = path.join(brainBaseDir, newGuid);
995
+
996
+ // Generate pre-seeded task.md
997
+ const newTaskMdContent = generateNewSessionTaskMd(compositeState, newGuid, docsHandoffPath);
998
+ atomicWriteFileSync(path.join(newBrainDir, 'task.md'), newTaskMdContent, { encoding: 'utf8' });
999
+
1000
+ // Generate pre-seeded implementation_plan.md
1001
+ const planMdContent = generateNewSessionPlanMd(compositeState, newGuid, docsHandoffPath);
1002
+ atomicWriteFileSync(path.join(newBrainDir, 'implementation_plan.md'), planMdContent, { encoding: 'utf8' });
1003
+
1004
+ return {
1005
+ success: true,
1006
+ newGuid,
1007
+ timestamp: formattedTimestamp,
1008
+ capturedAt: rawTimestamp,
1009
+ handoffFilePath: docsHandoffPath,
1010
+ latestHandoffPath,
1011
+ horizonHandoffPath,
1012
+ newBrainDir,
1013
+ taskMdPath: path.join(newBrainDir, 'task.md'),
1014
+ implementationPlanPath: path.join(newBrainDir, 'implementation_plan.md'),
1015
+ flushedDeltasCount: flushResult.flushedCount || 0,
1016
+ modifiedFiles: flushResult.modifiedFiles || [],
1017
+ constraintsPreserved: true,
1018
+ markdown: handoffContent
1019
+ };
1020
+ }
1021
+
1022
+ function generateNewSessionTaskMd(state = {}, newGuid = '', handoffFilePath = '') {
1023
+ let checklist = { completed: [], inProgress: [], pending: [] };
1024
+ if (state.taskMdContent) {
1025
+ checklist = parseTaskChecklist(state.taskMdContent);
1026
+ } else if (state.taskMdPath && fs.existsSync(state.taskMdPath)) {
1027
+ try {
1028
+ checklist = parseTaskChecklist(fs.readFileSync(state.taskMdPath, 'utf8'));
1029
+ } catch {}
1030
+ } else if (state.checklist) {
1031
+ checklist = state.checklist;
1032
+ }
1033
+
1034
+ const lines = [];
1035
+ lines.push(`# Task Checklist: Session Baton-Pass Continuation (${newGuid.slice(0, 8)})`);
1036
+ lines.push(`Handoff Reference: \`${handoffFilePath}\``);
1037
+ lines.push(``);
1038
+
1039
+ lines.push(`## Preserved Completed Milestones`);
1040
+ if (checklist.completed.length > 0) {
1041
+ for (const c of checklist.completed) {
1042
+ lines.push(`- [x] ${c}`);
1043
+ }
1044
+ } else {
1045
+ lines.push(`- [x] Previous session state handed off cleanly`);
1046
+ }
1047
+ lines.push(``);
1048
+
1049
+ lines.push(`## Active Next Steps & Carried Tasks`);
1050
+ if (checklist.inProgress.length > 0) {
1051
+ for (const ip of checklist.inProgress) {
1052
+ lines.push(`- [/] ${ip}`);
1053
+ }
1054
+ }
1055
+ if (checklist.pending.length > 0) {
1056
+ for (const p of checklist.pending) {
1057
+ lines.push(`- [ ] ${p}`);
1058
+ }
1059
+ } else if (checklist.inProgress.length === 0) {
1060
+ lines.push(`- [ ] Verify test suite and proceed with next roadmap phase`);
1061
+ }
1062
+ lines.push(``);
1063
+
1064
+ lines.push(`## Active Guardrail Pin`);
1065
+ lines.push(`- **NEVER** mutate GEMINI.md, AGENTS.md, or SKILL.md while Cached History >= 50k and TTL > 0s.`);
1066
+ lines.push(`- **NEVER** open Antigravity host session databases in write mode.`);
1067
+ lines.push(`- **NEVER** delete, weaken, or skip existing assert / expect statements in any test file.`);
1068
+ lines.push(`- **ALWAYS** preserve verified state from handoff.`);
1069
+ lines.push(``);
1070
+
1071
+ return lines.join('\n');
1072
+ }
1073
+
1074
+ function generateNewSessionPlanMd(state = {}, newGuid = '', handoffFilePath = '') {
1075
+ const lines = [];
1076
+ lines.push(`# Implementation Plan: Session Continuation (${newGuid.slice(0, 8)})`);
1077
+ lines.push(`**Handoff Checkpoint**: \`${handoffFilePath}\``);
1078
+ lines.push(``);
1079
+ lines.push(`## Architectural Continuation`);
1080
+ lines.push(`This session continues execution with a clean context window, carrying forward verified test state, file schemas, and guardrail constraints from previous session \`${state.sessionId || 'parent'}\`.`);
1081
+ lines.push(``);
1082
+ lines.push(`## Verification Requirements`);
1083
+ lines.push(`- Zero lost constraints from handoff.`);
1084
+ lines.push(`- Verify test suite passes cleanly before proceeding with new edits.`);
1085
+ lines.push(``);
1086
+ return lines.join('\n');
1087
+ }
1088
+
1089
+ /**
1090
+ * State-aware Compaction Coach class
1091
+ */
1092
+ export class CompactionCoach {
1093
+ constructor(options = {}) {
1094
+ this.workspacePath = options.workspacePath || process.cwd();
1095
+ this.homeDir = options.homeDir || getHomeDir();
1096
+ this.prefixCacheShield = options.prefixCacheShield || new PrefixCacheShield({ homeDir: this.homeDir });
1097
+ this.fts5DbPath = options.fts5DbPath || null;
1098
+ }
1099
+
1100
+ assess(sessionTelemetry = {}) {
1101
+ return assessCompactionState(sessionTelemetry);
1102
+ }
1103
+
1104
+ trimTail(steps = [], options = {}) {
1105
+ return trimUncachedTail(steps, options);
1106
+ }
1107
+
1108
+ generateHandoff(state = {}, options = {}) {
1109
+ return generateHandoffMarkdown(state, {
1110
+ workspacePath: this.workspacePath,
1111
+ homeDir: this.homeDir,
1112
+ fts5DbPath: this.fts5DbPath,
1113
+ ...options
1114
+ });
1115
+ }
1116
+
1117
+ executeHandoff(state = {}, options = {}) {
1118
+ return executeBatonPassHandoff(state, {
1119
+ workspacePath: this.workspacePath,
1120
+ homeDir: this.homeDir,
1121
+ prefixCacheShield: this.prefixCacheShield,
1122
+ fts5DbPath: this.fts5DbPath,
1123
+ ...options
1124
+ });
1125
+ }
1126
+ }