ctxtop 0.0.0-stage → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (262) hide show
  1. package/.antigravity-plugin/plugin.json +36 -0
  2. package/.claude-plugin/plugin.json +18 -0
  3. package/CHECKSUMS.sha256 +166 -0
  4. package/LICENSE +27 -0
  5. package/README.md +350 -2
  6. package/SECURITY.md +22 -0
  7. package/agents/ah-flash-scout.md +25 -0
  8. package/assets/advanced_view_loaded_420px.png +0 -0
  9. package/assets/hero-demo.svg +188 -0
  10. package/assets/logo.svg +19 -0
  11. package/assets/simple_view_lean_420px.png +0 -0
  12. package/assets/simple_view_loaded_420px.png +0 -0
  13. package/assets/social-preview.svg +72 -0
  14. package/assets/zone_c_step3_shield_full.png +0 -0
  15. package/bin/ah-statusline.mjs +175 -0
  16. package/bin/cli.mjs +3 -0
  17. package/bin/ctxtop.mjs +1799 -0
  18. package/commands/cost-radar.md +11 -0
  19. package/commands/evolve.md +10 -0
  20. package/commands/handoff.md +10 -0
  21. package/commands/horizon.md +10 -0
  22. package/commands/inspect.md +10 -0
  23. package/commands/precheck.md +10 -0
  24. package/config/default_flightcheck.json +133 -0
  25. package/config/modelCatalog.json +785 -0
  26. package/config/platformQuirks.json +19 -0
  27. package/hooks/handlers/compact-lifecycle.mjs +577 -0
  28. package/hooks/handlers/config-change.mjs +402 -0
  29. package/hooks/handlers/hookIo.mjs +311 -0
  30. package/hooks/handlers/hookIpcClient.mjs +83 -0
  31. package/hooks/handlers/post-model-switch.mjs +111 -0
  32. package/hooks/handlers/post-tool-use.mjs +366 -0
  33. package/hooks/handlers/pre-model-switch.mjs +1048 -0
  34. package/hooks/handlers/pre-tool-use.mjs +632 -0
  35. package/hooks/handlers/stop-gate.mjs +526 -0
  36. package/hooks/handlers/user-prompt-submit.mjs +367 -0
  37. package/hooks/hooks.json +131 -0
  38. package/hooks/post_invocation.mjs +13 -0
  39. package/hooks/post_tool_use.mjs +25 -0
  40. package/hooks/pre_invocation.mjs +14 -0
  41. package/hooks/pre_tool_use.mjs +97 -0
  42. package/hooks/register.js +726 -0
  43. package/hooks/session_start.mjs +24 -0
  44. package/hooks/stop.mjs +23 -0
  45. package/hooks.json +56 -0
  46. package/package.json +110 -4
  47. package/packages/antigravity/package.json +14 -0
  48. package/packages/antigravity/src/index.mjs +1 -0
  49. package/packages/claude-code/package.json +14 -0
  50. package/packages/claude-code/src/index.mjs +2 -0
  51. package/packages/core/package.json +14 -0
  52. package/packages/core/src/index.mjs +1 -0
  53. package/packages/engine-node/package.json +14 -0
  54. package/packages/engine-node/src/index.mjs +1 -0
  55. package/packages/mcp/package.json +17 -0
  56. package/packages/mcp/src/server.mjs +396 -0
  57. package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
  58. package/packages/pro/README-SIGNING.md +30 -0
  59. package/packages/pro/package.json +16 -0
  60. package/packages/pro/src/index.mjs +3 -0
  61. package/packages/pro/src/team_finops_pack.mjs +241 -0
  62. package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
  63. package/plugin.json +36 -0
  64. package/rules/AGENTS.md +10 -0
  65. package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
  66. package/sidecars/horizon-daemon/server.mjs +2038 -0
  67. package/sidecars/horizon-daemon/sidecar.json +19 -0
  68. package/skills/cost-radar/SKILL.md +21 -0
  69. package/skills/evolve/SKILL.md +21 -0
  70. package/skills/handoff/SKILL.md +50 -0
  71. package/skills/horizon/SKILL.md +17 -0
  72. package/skills/inspect/SKILL.md +18 -0
  73. package/skills/precheck/SKILL.md +44 -0
  74. package/src/adapters/antigravity/index.mjs +109 -0
  75. package/src/adapters/claude-code/index.mjs +194 -0
  76. package/src/cli/cost_radar.mjs +70 -0
  77. package/src/cli/doctor.mjs +351 -0
  78. package/src/cli/horizon_hud.mjs +888 -0
  79. package/src/cli/init.mjs +425 -0
  80. package/src/cli/postmortem.mjs +515 -0
  81. package/src/coach/cacheGravityRouter.mjs +12 -0
  82. package/src/config/modelCatalog.json +704 -0
  83. package/src/config/platformQuirks.json +19 -0
  84. package/src/core/action_queue.mjs +264 -0
  85. package/src/core/ag_bridge.mjs +346 -0
  86. package/src/core/atomic_io.mjs +124 -0
  87. package/src/core/baseline.mjs +607 -0
  88. package/src/core/blindspot_sensors.mjs +399 -0
  89. package/src/core/bucket_b_runtime.mjs +1200 -0
  90. package/src/core/classifier.mjs +1757 -0
  91. package/src/core/coach/circuit_breakers.mjs +650 -0
  92. package/src/core/coach/contradiction_auditor.mjs +239 -0
  93. package/src/core/coach/effort_advisor.mjs +143 -0
  94. package/src/core/coach/handoff_hydrator.mjs +483 -0
  95. package/src/core/coach/progressive_checkpointer.mjs +551 -0
  96. package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
  97. package/src/core/coach/reflector_queue.mjs +505 -0
  98. package/src/core/coach/saved_quota_ledger.mjs +615 -0
  99. package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
  100. package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
  101. package/src/core/coach/task_quota_router.mjs +955 -0
  102. package/src/core/coach/turn_zero_gate.mjs +574 -0
  103. package/src/core/compaction_coach.mjs +1126 -0
  104. package/src/core/config.mjs +214 -0
  105. package/src/core/constants.mjs +1987 -0
  106. package/src/core/detectors_det01_to_16.mjs +1523 -0
  107. package/src/core/doc_indexer.mjs +338 -0
  108. package/src/core/episodic_memory.mjs +135 -0
  109. package/src/core/fts5_output_compressor.mjs +359 -0
  110. package/src/core/git_ledger.mjs +189 -0
  111. package/src/core/handoff_audit.mjs +558 -0
  112. package/src/core/history.mjs +221 -0
  113. package/src/core/hook_diagnostics.mjs +158 -0
  114. package/src/core/horizon_classifier.mjs +326 -0
  115. package/src/core/horizon_config.mjs +802 -0
  116. package/src/core/host_watchdog.mjs +200 -0
  117. package/src/core/layer5_hygiene.mjs +1084 -0
  118. package/src/core/log_resolver.mjs +231 -0
  119. package/src/core/mcp_auditor.mjs +138 -0
  120. package/src/core/micro_skills_store.mjs +91 -0
  121. package/src/core/offenders.mjs +161 -0
  122. package/src/core/parser.mjs +1997 -0
  123. package/src/core/path_canonicalizer.mjs +73 -0
  124. package/src/core/paths.mjs +311 -0
  125. package/src/core/prefix_cache_shield.mjs +386 -0
  126. package/src/core/pro_license.mjs +385 -0
  127. package/src/core/prompt_rubric.mjs +518 -0
  128. package/src/core/pruner.mjs +433 -0
  129. package/src/core/quota.mjs +1860 -0
  130. package/src/core/rsi_instinct_engine.mjs +1197 -0
  131. package/src/core/rsl_clash_auditor.mjs +423 -0
  132. package/src/core/rsl_distiller.mjs +372 -0
  133. package/src/core/rsl_ledger.mjs +969 -0
  134. package/src/core/rsl_triage.mjs +909 -0
  135. package/src/core/sanitizer.mjs +121 -0
  136. package/src/core/session_auditor.mjs +658 -0
  137. package/src/core/session_forensics.mjs +303 -0
  138. package/src/core/session_timeline.mjs +358 -0
  139. package/src/core/settings.mjs +99 -0
  140. package/src/core/shared/detectors.mjs +1342 -0
  141. package/src/core/shared/fnv1a64.mjs +85 -0
  142. package/src/core/shared/handoff_schema.mjs +123 -0
  143. package/src/core/shared/index.mjs +5 -0
  144. package/src/core/shared/ipi_sanitizer.mjs +165 -0
  145. package/src/core/shared/micro_skills.mjs +1 -0
  146. package/src/core/shared/plugin_validator.mjs +202 -0
  147. package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
  148. package/src/core/shield_manager.mjs +1417 -0
  149. package/src/core/sidecar_store.mjs +302 -0
  150. package/src/core/sprint_metrics.mjs +366 -0
  151. package/src/core/sqlite_client.mjs +283 -0
  152. package/src/core/storage_doctor.mjs +358 -0
  153. package/src/core/subagents.mjs +609 -0
  154. package/src/core/swarm_topology.mjs +360 -0
  155. package/src/core/task_quota_router.mjs +1656 -0
  156. package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
  157. package/src/core/telemetry/scope_lock_registry.mjs +578 -0
  158. package/src/core/telemetry/shadow_file_detector.mjs +291 -0
  159. package/src/core/telemetry/trajectory_watcher.mjs +259 -0
  160. package/src/core/timeline_svg.mjs +236 -0
  161. package/src/core/tool_surgeon.mjs +305 -0
  162. package/src/core/trajectory_stitcher.mjs +645 -0
  163. package/src/core/u_shaped_optimizer.mjs +789 -0
  164. package/src/core/wal_hygiene.mjs +233 -0
  165. package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
  166. package/src/core-isomorphic/catalog/index.mjs +1 -0
  167. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
  168. package/src/core-isomorphic/coach/microSkills.mjs +1 -0
  169. package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
  170. package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
  171. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  172. package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
  173. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  174. package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
  175. package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
  176. package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
  177. package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
  178. package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
  179. package/src/core-isomorphic/control/callTree.mjs +338 -0
  180. package/src/core-isomorphic/control/coachLatches.mjs +126 -0
  181. package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
  182. package/src/core-isomorphic/control/index.mjs +49 -0
  183. package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
  184. package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
  185. package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
  186. package/src/core-isomorphic/diagnostics/index.mjs +9 -0
  187. package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
  188. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
  189. package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
  190. package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
  191. package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
  192. package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
  193. package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
  194. package/src/core-isomorphic/economics/index.mjs +47 -0
  195. package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
  196. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  197. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  198. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  199. package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
  200. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
  201. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
  202. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
  203. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  204. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
  205. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  206. package/src/core-isomorphic/index.js +27 -0
  207. package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
  208. package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
  209. package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
  210. package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
  211. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
  212. package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
  213. package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
  214. package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
  215. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
  216. package/src/core-isomorphic/ui/modViews.mjs +1504 -0
  217. package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
  218. package/src/core-isomorphic/ustf/index.mjs +7 -0
  219. package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
  220. package/src/core-isomorphic/ustf/schema.mjs +186 -0
  221. package/src/core-isomorphic/utils/runtime.mjs +962 -0
  222. package/src/demo/synthetic_states.mjs +661 -0
  223. package/src/diagnostics/bugReportGenerator.mjs +253 -0
  224. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  225. package/src/diagnostics/doctorEngine.mjs +295 -0
  226. package/src/engine-node/db/index.mjs +58 -0
  227. package/src/engine-node/db/jsonl_fallback.mjs +184 -0
  228. package/src/engine-node/db/probe.mjs +342 -0
  229. package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
  230. package/src/engine-node/index.mjs +12 -0
  231. package/src/engine-node/ipc/client.mjs +447 -0
  232. package/src/engine-node/ipc/index.mjs +22 -0
  233. package/src/engine-node/ipc/protocol.mjs +177 -0
  234. package/src/engine-node/ipc/server.mjs +445 -0
  235. package/src/engine-node/offloader/index.mjs +6 -0
  236. package/src/engine-node/offloader/tool_offloader.mjs +241 -0
  237. package/src/engine-node/sensors/blindspots.mjs +376 -0
  238. package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
  239. package/src/engine-node/sensors/index.mjs +7 -0
  240. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  241. package/src/hooks/claude_rsl_hook.mjs +288 -0
  242. package/src/hooks/portfolio_runtime.mjs +858 -0
  243. package/src/hooks/post_invocation.mjs +611 -0
  244. package/src/hooks/pre_invocation.mjs +1725 -0
  245. package/src/hooks/session_start.mjs +199 -0
  246. package/src/shims/agy_cli_compressor.mjs +705 -0
  247. package/src/shims/agy_git_guard.mjs +749 -0
  248. package/src/shims/ah_log_query.mjs +39 -0
  249. package/src/ui/costRadarSvg.mjs +6 -0
  250. package/src/ui/horizonGrid.mjs +1 -0
  251. package/src/ui/horizonPanelHtml.mjs +1 -0
  252. package/src/ui/horizon_panel.css +167 -0
  253. package/src/ui/horizon_panel.js +212 -0
  254. package/src/ui/modViews.mjs +1 -0
  255. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  256. package/src/utils/nodeIo.mjs +59 -0
  257. package/src/utils/runtime.mjs +1 -0
  258. package/src/utils/sessionCalibration.mjs +657 -0
  259. package/src/webview/advanced_view.html +1808 -0
  260. package/src/webview/horizon_panel.html +12397 -0
  261. package/src/webview/registry.mjs +80 -0
  262. package/src/webview/simple_view.html +1370 -0
@@ -0,0 +1,810 @@
1
+ /**
2
+ * @file src/coach/stateBatonHydrator.mjs
3
+ * Deterministic ~300-token Durable Fact Schema (`StateBaton`), `PreCompact` portable Markdown
4
+ * handoff generator (`docs/HANDOFF_<timestamp>.md`), `SessionStart` `additionalContext`
5
+ * injector, and `PostCompact` mutation queue + `SavedQuotaReceiptLedger` flusher.
6
+ *
7
+ * Strictly zero background LLM summarization workers ($0.00 worker cost).
8
+ */
9
+
10
+ import {
11
+ path,
12
+ getCwd,
13
+ fileExists,
14
+ getFileMtimeMsSafe,
15
+ readdirSafe,
16
+ readTextSafe,
17
+ writeTextAtomic,
18
+ writeJsonAtomic,
19
+ recordRuntimeDiagnostic
20
+ } from '../utils/runtime.mjs';
21
+ import { sanitizeSessionId } from '../telemetry/telemetryBridge.mjs';
22
+ import { PostCompactMutationQueue } from './cacheGravityRouter.mjs';
23
+ import { recordSavingsReceipt } from './savedQuotaLedger.mjs';
24
+
25
+ export const MAX_BATON_TOKEN_BUDGET = 300; // ~1,200 characters
26
+
27
+ // In-memory fallback set to guarantee idempotent compaction receipts even when disk I/O is disabled
28
+ const inMemoryRecordedCompactionKeys = new Set();
29
+
30
+ /**
31
+ * Reads and parses a persisted State Baton JSON file, recording a structured diagnostic if corrupted (`ISS-065`).
32
+ *
33
+ * @param {string} targetPath
34
+ * @param {string} operation
35
+ * @param {object} [ioOpts={}]
36
+ * @param {object} [diagOpts={}]
37
+ * @returns {any}
38
+ */
39
+ function readBatonJsonWithDiagnostics(targetPath, operation, ioOpts = {}, diagOpts = {}) {
40
+ const raw = readTextSafe(targetPath, null, ioOpts);
41
+ if (raw === null) return null;
42
+ try {
43
+ return JSON.parse(raw);
44
+ } catch (err) {
45
+ recordRuntimeDiagnostic('stateBatonHydrator', operation, err, diagOpts);
46
+ return null;
47
+ }
48
+ }
49
+
50
+ /**
51
+ * Resolves the State Baton persistence path `.claude/cache/state_baton_<sessionId>.json`.
52
+ * @param {string} [sessionId='default']
53
+ * @param {object} [options={}]
54
+ * @returns {string}
55
+ */
56
+ export function getStateBatonFilePath(sessionId = 'default', options = {}) {
57
+ const cwd = getCwd(options);
58
+ const safeId = sanitizeSessionId(sessionId);
59
+ return path.join(cwd, '.claude', 'cache', `state_baton_${safeId}.json`);
60
+ }
61
+
62
+ /**
63
+ * Builds or updates a deterministic Durable Fact Schema (`StateBaton`) bounded to ~300 tokens.
64
+ *
65
+ * @param {object} [input={}]
66
+ * @param {string} [input.sessionId='default']
67
+ * @param {string} [input.modelId='claude-sonnet-5-5']
68
+ * @param {string} [input.activeGoal]
69
+ * @param {Array<string>} [input.workingSetFiles]
70
+ * @param {Array<string>} [input.verifiedInvariants]
71
+ * @param {Array<string>} [input.deadEndsAndFailures]
72
+ * @param {Array<object>} [input.queuedCacheMutations]
73
+ * @param {number} [input.savedTokensBeforeCompact=0]
74
+ * @param {number} [input.savedUSDBeforeCompact=0]
75
+ * @param {number} [input.nowMs=Date.now()]
76
+ */
77
+ export function buildDurableStateBaton(input = {}) {
78
+ const nowMs = input.nowMs ?? Date.now();
79
+ const activeGoal = String(
80
+ input.activeGoal || 'Maintain active implementation progress and verified invariants across compaction'
81
+ )
82
+ .trim()
83
+ .slice(0, 240);
84
+
85
+ const workingSetFiles = Array.from(new Set(input.workingSetFiles || []))
86
+ .map((f) => String(f).trim())
87
+ .filter(Boolean)
88
+ .slice(0, 12);
89
+
90
+ const verifiedInvariants = Array.from(new Set(input.verifiedInvariants || []))
91
+ .map((inv) => String(inv).trim().slice(0, 140))
92
+ .filter(Boolean)
93
+ .slice(0, 6);
94
+
95
+ const deadEndsAndFailures = Array.from(new Set(input.deadEndsAndFailures || []))
96
+ .map((err) => String(err).trim().slice(0, 140))
97
+ .filter(Boolean)
98
+ .slice(0, 5);
99
+
100
+ const queuedCacheMutations = Array.isArray(input.queuedCacheMutations)
101
+ ? input.queuedCacheMutations.slice(0, 8)
102
+ : [];
103
+
104
+ const sessionId = sanitizeSessionId(input.sessionId || input.session_id || 'default');
105
+ const explicitCycle =
106
+ input.compactionId || input.compaction_id || input.compactionEpoch || input.turnId || null;
107
+ const compactionId = explicitCycle
108
+ ? `${sessionId}:${String(explicitCycle)}`
109
+ : `${sessionId}:compact:${nowMs}`;
110
+
111
+ return {
112
+ schemaVersion: '2026.11.1',
113
+ createdAt: nowMs,
114
+ sessionId,
115
+ compactionId,
116
+ ledgerReceiptRecorded: false,
117
+ lastRecordedCompactionId: null,
118
+ modelId: String(input.modelId || input.model_id || input.model || 'claude-sonnet-5-5'),
119
+ activeGoal,
120
+ workingSetFiles,
121
+ verifiedInvariants,
122
+ deadEndsAndFailures,
123
+ queuedCacheMutations,
124
+ metricsSnapshot: {
125
+ savedTokensBeforeCompact: Math.max(0, Math.round(Number(input.savedTokensBeforeCompact || 0))),
126
+ savedUSDBeforeCompact: Math.max(0, Number(Number(input.savedUSDBeforeCompact || 0).toFixed(6)))
127
+ }
128
+ };
129
+ }
130
+
131
+ /**
132
+ * Formats the Durable State Baton into a compact ~300-token `additionalContext` string
133
+ * for injection on `SessionStart[compact|resume|startup|clear|fork]`.
134
+ *
135
+ * @param {object} baton
136
+ * @returns {string}
137
+ */
138
+ export function formatBatonAdditionalContext(baton = {}) {
139
+ if (!baton || typeof baton !== 'object') return '';
140
+ const files =
141
+ Array.isArray(baton.workingSetFiles) && baton.workingSetFiles.length > 0
142
+ ? baton.workingSetFiles.join(', ')
143
+ : 'none recorded';
144
+ const invariants =
145
+ Array.isArray(baton.verifiedInvariants) && baton.verifiedInvariants.length > 0
146
+ ? baton.verifiedInvariants.map((i) => `- ${i}`).join('\n')
147
+ : '- Keep existing tests green and preserve cache prefix stability';
148
+ const deadEnds =
149
+ Array.isArray(baton.deadEndsAndFailures) && baton.deadEndsAndFailures.length > 0
150
+ ? baton.deadEndsAndFailures.map((d) => `- ${d}`).join('\n')
151
+ : '- None';
152
+ const mutations =
153
+ Array.isArray(baton.queuedCacheMutations) && baton.queuedCacheMutations.length > 0
154
+ ? baton.queuedCacheMutations.map((m) => `${m.type}=${JSON.stringify(m.value)}`).join(', ')
155
+ : 'none';
156
+
157
+ const block = [
158
+ `<attention_horizon_state_baton session="${baton.sessionId || 'default'}" model="${baton.modelId || 'claude-sonnet-5-5'}">`,
159
+ `Active Goal: ${baton.activeGoal || 'Continue active task'}`,
160
+ `Working Set Files: ${files}`,
161
+ `Verified Invariants:\n${invariants}`,
162
+ `Avoid Dead Ends / Prior Failures:\n${deadEnds}`,
163
+ `Post-Compaction Applied Mutations: ${mutations}`,
164
+ `</attention_horizon_state_baton>`
165
+ ].join('\n');
166
+
167
+ // Hard cap at ~1,200 chars (~300 tokens)
168
+ return block.length <= 1250 ? block : `${block.slice(0, 1210)}\n</attention_horizon_state_baton>`;
169
+ }
170
+
171
+ /**
172
+ * Renders a cross-tool portable Markdown handoff document (`docs/HANDOFF_<timestamp>.md`).
173
+ *
174
+ * @param {object} baton
175
+ * @returns {string}
176
+ */
177
+ export function renderPortableHandoffMarkdown(baton = {}) {
178
+ const isoDate = new Date(baton.createdAt || Date.now()).toISOString();
179
+ const filesList =
180
+ Array.isArray(baton.workingSetFiles) && baton.workingSetFiles.length > 0
181
+ ? baton.workingSetFiles.map((f) => `- \`${f}\``).join('\n')
182
+ : '- *(none recorded)*';
183
+ const invariantsList =
184
+ Array.isArray(baton.verifiedInvariants) && baton.verifiedInvariants.length > 0
185
+ ? baton.verifiedInvariants.map((i) => `- [x] ${i}`).join('\n')
186
+ : '- [x] Maintain existing test suite pass rate';
187
+ const deadEndsList =
188
+ Array.isArray(baton.deadEndsAndFailures) && baton.deadEndsAndFailures.length > 0
189
+ ? baton.deadEndsAndFailures.map((d) => `- ${d}`).join('\n')
190
+ : '- *(none recorded)*';
191
+ const mutationsList =
192
+ Array.isArray(baton.queuedCacheMutations) && baton.queuedCacheMutations.length > 0
193
+ ? baton.queuedCacheMutations
194
+ .map((m) => `- **${m.type}** (\`${m.key}\`): \`${JSON.stringify(m.value)}\` — ${m.reason || ''}`)
195
+ .join('\n')
196
+ : '- *(no deferred cache mutations)*';
197
+
198
+ return [
199
+ `# Highbeam State Baton Handoff`,
200
+ ``,
201
+ `- **Session ID:** \`${baton.sessionId || 'default'}\``,
202
+ `- **Active Model:** \`${baton.modelId || 'claude-sonnet-5-5'}\``,
203
+ `- **Captured At:** \`${isoDate}\``,
204
+ ``,
205
+ `## 1. Active Goal`,
206
+ `${baton.activeGoal || 'Continue active task'}`,
207
+ ``,
208
+ `## 2. Working Set Files`,
209
+ filesList,
210
+ ``,
211
+ `## 3. Verified Invariants`,
212
+ invariantsList,
213
+ ``,
214
+ `## 4. Dead Ends & Failures to Avoid`,
215
+ deadEndsList,
216
+ ``,
217
+ `## 5. Queued Cache-Prefix Mutations (Released on PostCompact)`,
218
+ mutationsList,
219
+ ``
220
+ ].join('\n');
221
+ }
222
+
223
+ /**
224
+ * Formats an epoch-ms timestamp as UTC `YYYYMMDD_HHMMSS` for shared cross-edition
225
+ * `HANDOFF_<YYYYMMDD_HHMMSS>.md` filenames (`ISS-055`).
226
+ *
227
+ * @param {number} [nowMs=Date.now()]
228
+ * @returns {string}
229
+ */
230
+ export function formatUtcHandoffTimestamp(nowMs = Date.now()) {
231
+ const numeric = Number(nowMs);
232
+ const d = new Date(Number.isFinite(numeric) ? numeric : Date.now());
233
+ const pad2 = (n) => String(n).padStart(2, '0');
234
+ return (
235
+ `${d.getUTCFullYear()}${pad2(d.getUTCMonth() + 1)}${pad2(d.getUTCDate())}_` +
236
+ `${pad2(d.getUTCHours())}${pad2(d.getUTCMinutes())}${pad2(d.getUTCSeconds())}`
237
+ );
238
+ }
239
+
240
+ /**
241
+ * Extracts a UTC epoch-ms timestamp from `HANDOFF_YYYYMMDD_HHMMSS.md` (or legacy `HANDOFF_<epochMs>.md`).
242
+ * @param {string} [filename='']
243
+ * @returns {number}
244
+ */
245
+ export function parseHandoffFilenameTimestampMs(filename = '') {
246
+ const base = path.basename(String(filename || ''));
247
+ const utcMatch = base.match(/^HANDOFF_(\d{4})(\d{2})(\d{2})_(\d{2})(\d{2})(\d{2})\.md$/i);
248
+ if (utcMatch) {
249
+ return Date.UTC(
250
+ Number(utcMatch[1]),
251
+ Number(utcMatch[2]) - 1,
252
+ Number(utcMatch[3]),
253
+ Number(utcMatch[4]),
254
+ Number(utcMatch[5]),
255
+ Number(utcMatch[6])
256
+ );
257
+ }
258
+ const epochMatch = base.match(/^HANDOFF_(\d{10,15})\.md$/i);
259
+ if (epochMatch) {
260
+ const ms = Number(epochMatch[1]);
261
+ return ms < 1e11 ? ms * 1000 : ms;
262
+ }
263
+ return 0;
264
+ }
265
+
266
+ /**
267
+ * Parses a portable Markdown handoff document (from either Claude Code `State Baton Handoff`,
268
+ * Antigravity `Baton-Pass Handoff Bundle`, or `/handoff` markdown) into a `StateBaton` object (`ISS-055`).
269
+ *
270
+ * @param {string} markdownText
271
+ * @param {object} [defaults={}]
272
+ * @returns {object | null}
273
+ */
274
+ export function parsePortableHandoffMarkdown(markdownText = '', defaults = {}) {
275
+ const raw = String(markdownText || '').trim();
276
+ if (!raw) return null;
277
+
278
+ const lines = raw.split(/\r?\n/);
279
+ let sessionId = defaults.sessionId || '';
280
+ let modelId = defaults.modelId || 'claude-sonnet-5-5';
281
+ let parsedCreatedAt = 0;
282
+
283
+ const goalLines = [];
284
+ const workingSetFiles = [];
285
+ const verifiedInvariants = [];
286
+ const deadEndsAndFailures = [];
287
+ const queuedCacheMutations = [];
288
+ const topSummaryLines = [];
289
+
290
+ let currentSection = 'preamble';
291
+
292
+ const classifyHeading = (headingText) => {
293
+ const h = headingText.toLowerCase();
294
+ if (
295
+ /(?:active\s+goal|resume\s+contract|active\s+step|objective|current\s+goal|active\s+task|next\s+step|next\s+action)/i.test(
296
+ h
297
+ )
298
+ ) {
299
+ return 'goal';
300
+ }
301
+ if (/(?:working\s+set|owned\s+scope|modified\s+files|active\s+files|files\s+locked|scope\s+paths|^files$)/i.test(h)) {
302
+ return 'files';
303
+ }
304
+ if (/(?:verified\s+invariant|verified\s+unchanged|invariant|architectural|file\s+schema|decision)/i.test(h)) {
305
+ return 'invariants';
306
+ }
307
+ if (/(?:dead\s+end|negative\s+constraint|failure|failed|avoid|do\s+not\s+repeat)/i.test(h)) {
308
+ return 'dead_ends';
309
+ }
310
+ if (/(?:queued\s+cache|deferred.*mutation|cache-prefix\s+mutation)/i.test(h)) {
311
+ return 'mutations';
312
+ }
313
+ return 'other';
314
+ };
315
+
316
+ const cleanBulletItem = (line) =>
317
+ line
318
+ .replace(/^\s*(?:[-*+]|\d+\.)\s*(?:\[[ xX]\]\s*)?/, '')
319
+ .trim();
320
+
321
+ const isPlaceholderBullet = (item) =>
322
+ !item ||
323
+ /^\*\(.*\)\*$/i.test(item) ||
324
+ /^(?:none|none\s+recorded|n\/a|no\s+deferred\s+cache\s+mutations)$/i.test(item);
325
+
326
+ for (const rawLine of lines) {
327
+ const trimmed = rawLine.trim();
328
+ if (!trimmed) continue;
329
+
330
+ // Top-level title
331
+ if (/^#\s+/.test(trimmed) && !/^##/.test(trimmed)) {
332
+ continue;
333
+ }
334
+
335
+ // Section heading
336
+ const headingMatch = trimmed.match(/^#{2,4}\s+(?:\d+\.\s*)?(.+)$/);
337
+ if (headingMatch) {
338
+ currentSection = classifyHeading(headingMatch[1]);
339
+ continue;
340
+ }
341
+
342
+ // Metadata extraction in preamble or anywhere near top
343
+ const sessionMeta = trimmed.match(
344
+ /(?:Session\s*ID|Trajectory(?:\s*\/\s*Session)?|Session)\s*:\**\s*`?([^`|*]+)`?/i
345
+ );
346
+ if (sessionMeta && currentSection === 'preamble') {
347
+ sessionId = sessionMeta[1].trim();
348
+ continue;
349
+ }
350
+
351
+ const modelMeta = trimmed.match(/(?:Active\s*Model|Model)\s*:\**\s*`?([^`|*]+)`?/i);
352
+ if (modelMeta && currentSection === 'preamble') {
353
+ modelId = modelMeta[1].trim();
354
+ continue;
355
+ }
356
+
357
+ const dateMeta = trimmed.match(
358
+ /(?:Captured\s*At|Generated(?:\s*At)?|Created(?:\s*At)?|Timestamp)\s*:\**\s*`?([^`]+)`?/i
359
+ );
360
+ if (dateMeta && currentSection === 'preamble') {
361
+ const ts = Date.parse(dateMeta[1].trim());
362
+ if (!Number.isNaN(ts)) parsedCreatedAt = ts;
363
+ continue;
364
+ }
365
+
366
+ if (currentSection === 'preamble') {
367
+ if (!trimmed.startsWith('>') && !trimmed.startsWith('---')) {
368
+ topSummaryLines.push(cleanBulletItem(trimmed));
369
+ }
370
+ continue;
371
+ }
372
+
373
+ if (currentSection === 'goal') {
374
+ const cleaned = cleanBulletItem(trimmed);
375
+ if (!isPlaceholderBullet(cleaned)) {
376
+ goalLines.push(cleaned);
377
+ }
378
+ } else if (currentSection === 'files') {
379
+ const cleaned = cleanBulletItem(trimmed);
380
+ if (!isPlaceholderBullet(cleaned)) {
381
+ const backtickMatch = cleaned.match(/^`([^`]+)`/);
382
+ const fileCandidate = (backtickMatch ? backtickMatch[1] : cleaned.split(/\s+[—–-]\s+/)[0]).trim();
383
+ if (fileCandidate && !isPlaceholderBullet(fileCandidate)) {
384
+ workingSetFiles.push(fileCandidate.replace(/^`|`$/g, ''));
385
+ }
386
+ }
387
+ } else if (currentSection === 'invariants') {
388
+ const cleaned = cleanBulletItem(trimmed);
389
+ if (!isPlaceholderBullet(cleaned)) {
390
+ verifiedInvariants.push(cleaned);
391
+ }
392
+ } else if (currentSection === 'dead_ends') {
393
+ const cleaned = cleanBulletItem(trimmed);
394
+ if (!isPlaceholderBullet(cleaned)) {
395
+ deadEndsAndFailures.push(cleaned);
396
+ }
397
+ } else if (currentSection === 'mutations') {
398
+ const mutMatch = trimmed.match(
399
+ /[-*]\s*\*\*([^*]+)\*\*\s*\(`([^`]+)`\)\s*:\s*`([^`]+)`(?:\s*[—-]\s*(.*))?/
400
+ );
401
+ if (mutMatch) {
402
+ let parsedVal = mutMatch[3];
403
+ if (/^(?:["{[\d-]|true$|false$|null$)/.test(parsedVal.trim())) {
404
+ try {
405
+ parsedVal = JSON.parse(mutMatch[3]);
406
+ } catch (err) {
407
+ recordRuntimeDiagnostic(
408
+ 'stateBatonHydrator',
409
+ 'parsePortableHandoffMarkdown.mutationValue',
410
+ err,
411
+ defaults
412
+ );
413
+ }
414
+ }
415
+ queuedCacheMutations.push({
416
+ type: mutMatch[1].trim(),
417
+ key: mutMatch[2].trim(),
418
+ value: parsedVal,
419
+ reason: (mutMatch[4] || '').trim()
420
+ });
421
+ }
422
+ }
423
+ }
424
+
425
+ const activeGoal =
426
+ goalLines.join(' ').trim() ||
427
+ topSummaryLines.join(' ').trim() ||
428
+ 'Continue active implementation from portable handoff baton';
429
+
430
+ const built = buildDurableStateBaton({
431
+ sessionId: sessionId || defaults.fallbackSessionId || 'default',
432
+ modelId,
433
+ activeGoal,
434
+ workingSetFiles,
435
+ verifiedInvariants,
436
+ deadEndsAndFailures,
437
+ queuedCacheMutations,
438
+ nowMs: parsedCreatedAt || defaults.nowMs || Date.now()
439
+ });
440
+
441
+ return {
442
+ ...built,
443
+ source: 'portable_markdown',
444
+ parsedCreatedAt
445
+ };
446
+ }
447
+
448
+ /**
449
+ * Executes `PreCompact` hydration:
450
+ * 1. Builds and persists the Durable State Baton to `.claude/cache/state_baton_<sessionId>.json`
451
+ * 2. Writes portable Markdown handoff to `HANDOFF_<YYYYMMDD_HHMMSS>.md` + `HANDOFF_LATEST.md`
452
+ * inside `.claude/cache/` (or explicit `options.handoffDir` when configured — keeping git-tracked `docs/` clean by default) (`ISS-055`).
453
+ *
454
+ * @param {object} [input={}]
455
+ * @param {object} [options={}]
456
+ * @returns {{ ok: boolean, baton: object, batonFilePath: string, handoffMarkdownPath: string, handoffLatestPath: string }}
457
+ */
458
+ export function handlePreCompactBatonFlush(input = {}, options = {}) {
459
+ const nowMs = options.nowMs ?? input.nowMs ?? Date.now();
460
+ const explicitCwd = options.cwd || input.cwd || null;
461
+ const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
462
+ const ioOpts = { ...options, cwd };
463
+ const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
464
+ const baton = buildDurableStateBaton({ ...input, nowMs });
465
+
466
+ const batonFilePath = getStateBatonFilePath(baton.sessionId, ioOpts);
467
+ const existingBaton = readBatonJsonWithDiagnostics(
468
+ batonFilePath,
469
+ 'handlePreCompactBatonFlush.readBaton',
470
+ ioOpts,
471
+ diagOpts
472
+ );
473
+
474
+ // Deduplicate concurrent Tier-1 Mod + Tier-2 CLI PreCompact flushes on the same compaction cycle (ISS-036)
475
+ const hasExplicitId = Boolean(
476
+ input.compactionId || input.compaction_id || input.compactionEpoch || input.turnId
477
+ );
478
+ if (
479
+ !hasExplicitId &&
480
+ existingBaton &&
481
+ existingBaton.compactionId &&
482
+ existingBaton.ledgerReceiptRecorded === false &&
483
+ Math.abs(nowMs - Number(existingBaton.createdAt || 0)) <= 5000
484
+ ) {
485
+ baton.compactionId = existingBaton.compactionId;
486
+ }
487
+
488
+ writeJsonAtomic(batonFilePath, baton, ioOpts);
489
+
490
+ const cacheDir = path.join(cwd, '.claude', 'cache');
491
+ const defaultBatonPath = path.join(cacheDir, 'state_baton.json');
492
+ writeJsonAtomic(defaultBatonPath, baton, ioOpts);
493
+
494
+ const utcStamp = formatUtcHandoffTimestamp(nowMs);
495
+ const targetHandoffDir = options.handoffDir || input.handoffDir || cacheDir;
496
+ const handoffMarkdownPath = path.join(targetHandoffDir, `HANDOFF_${utcStamp}.md`);
497
+ const handoffLatestPath = path.join(targetHandoffDir, 'HANDOFF_LATEST.md');
498
+ const cacheLatestPath = path.join(cacheDir, 'HANDOFF_LATEST.md');
499
+
500
+ if (options.writeMarkdown !== false) {
501
+ const markdownContent = renderPortableHandoffMarkdown(baton);
502
+ writeTextAtomic(handoffMarkdownPath, markdownContent, ioOpts);
503
+ writeTextAtomic(handoffLatestPath, markdownContent, ioOpts);
504
+ if (cacheLatestPath !== handoffLatestPath) {
505
+ writeTextAtomic(cacheLatestPath, markdownContent, ioOpts);
506
+ }
507
+ }
508
+
509
+ return {
510
+ ok: true,
511
+ baton,
512
+ compactionKey: `${baton.sessionId}:${baton.compactionId}`,
513
+ batonFilePath,
514
+ handoffMarkdownPath,
515
+ handoffLatestPath
516
+ };
517
+ }
518
+
519
+ /**
520
+ * Discovers the newest valid portable Markdown handoff artifact across `.agents/horizon/`,
521
+ * `.claude/cache/`, and `docs/` (`ISS-055`).
522
+ *
523
+ * @param {string} cwd
524
+ * @param {string} sessionId
525
+ * @param {object} ioOpts
526
+ * @returns {{ baton: object, path: string, effectiveTs: number, isExternal: boolean } | null}
527
+ */
528
+ function findNewestMarkdownHandoffCandidate(cwd, sessionId, ioOpts = {}) {
529
+ const candidates = [];
530
+
531
+ const pushCandidatePath = (filePath, isExternal) => {
532
+ if (!filePath || !fileExists(filePath, ioOpts)) return;
533
+ candidates.push({ filePath, isExternal });
534
+ };
535
+
536
+ if (ioOpts.handoffMarkdownPath) {
537
+ pushCandidatePath(ioOpts.handoffMarkdownPath, true);
538
+ }
539
+ pushCandidatePath(path.join(cwd, '.agents', 'horizon', 'HANDOFF_LATEST.md'), true);
540
+ pushCandidatePath(path.join(cwd, '.claude', 'cache', 'HANDOFF_LATEST.md'), false);
541
+
542
+ const scanDirs = [
543
+ { dir: path.join(cwd, '.agents', 'horizon'), isExternal: true },
544
+ { dir: path.join(cwd, 'docs'), isExternal: true }
545
+ ];
546
+ if (ioOpts.handoffDir) {
547
+ scanDirs.push({ dir: ioOpts.handoffDir, isExternal: true });
548
+ }
549
+
550
+ for (const { dir, isExternal } of scanDirs) {
551
+ const entries = readdirSafe(dir, ioOpts);
552
+ for (const entry of entries) {
553
+ if (/^HANDOFF_.*\.md$/i.test(entry)) {
554
+ pushCandidatePath(path.join(dir, entry), isExternal);
555
+ }
556
+ }
557
+ }
558
+
559
+ let best = null;
560
+ const visited = new Set();
561
+ for (const { filePath, isExternal } of candidates) {
562
+ if (visited.has(filePath)) continue;
563
+ visited.add(filePath);
564
+ const mdText = readTextSafe(filePath, null, ioOpts);
565
+ if (!mdText) continue;
566
+ const parsed = parsePortableHandoffMarkdown(mdText, { fallbackSessionId: sessionId });
567
+ if (!parsed) continue;
568
+ const mtimeMs = getFileMtimeMsSafe(filePath, ioOpts);
569
+ const nameTs = parseHandoffFilenameTimestampMs(filePath);
570
+ const effectiveTs = Math.max(mtimeMs, Number(parsed.parsedCreatedAt || 0), nameTs);
571
+ if (
572
+ !best ||
573
+ effectiveTs > best.effectiveTs ||
574
+ (effectiveTs === best.effectiveTs && isExternal && !best.isExternal)
575
+ ) {
576
+ best = {
577
+ baton: parsed,
578
+ path: filePath,
579
+ effectiveTs,
580
+ isExternal
581
+ };
582
+ }
583
+ }
584
+
585
+ return best;
586
+ }
587
+
588
+ /**
589
+ * Executes `SessionStart` (`startup|resume|clear|compact|fork`) State Baton hydration,
590
+ * returning the ~300-token `additionalContext` payload for Claude Code.
591
+ * Supports both `.claude/cache/state_baton*.json` AND cross-tool portable Markdown handoffs
592
+ * (`.agents/horizon/HANDOFF_LATEST.md`, `.claude/cache/HANDOFF_LATEST.md`, `docs/HANDOFF_*.md`) (`ISS-055`).
593
+ *
594
+ * @param {object} [event={}]
595
+ * @param {object} [options={}]
596
+ * @returns {{ hydrated: boolean, hydratedFrom?: string, baton: object | null, additionalContext: string, hookSpecificOutput: object | null }}
597
+ */
598
+ export function handleSessionStartHydration(event = {}, options = {}) {
599
+ const explicitCwd = options.cwd || event.cwd || null;
600
+ const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
601
+ const ioOpts = { ...options, cwd };
602
+ const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
603
+ const sessionId = sanitizeSessionId(event.session_id || event.sessionId || 'default');
604
+
605
+ const sessionBatonPath = getStateBatonFilePath(sessionId, ioOpts);
606
+ let jsonBaton = readBatonJsonWithDiagnostics(
607
+ sessionBatonPath,
608
+ 'handleSessionStartHydration.readSessionBaton',
609
+ ioOpts,
610
+ diagOpts
611
+ );
612
+ let jsonBatonPath = sessionBatonPath;
613
+
614
+ if (!jsonBaton) {
615
+ const fallbackPath = path.join(cwd, '.claude', 'cache', 'state_baton.json');
616
+ jsonBaton = readBatonJsonWithDiagnostics(
617
+ fallbackPath,
618
+ 'handleSessionStartHydration.readFallbackBaton',
619
+ ioOpts,
620
+ diagOpts
621
+ );
622
+ jsonBatonPath = fallbackPath;
623
+ }
624
+
625
+ const jsonEffectiveTs = jsonBaton
626
+ ? Math.max(getFileMtimeMsSafe(jsonBatonPath, ioOpts), Number(jsonBaton.createdAt || 0))
627
+ : 0;
628
+
629
+ const bestMarkdown = findNewestMarkdownHandoffCandidate(cwd, sessionId, ioOpts);
630
+
631
+ let baton = jsonBaton;
632
+ let hydratedFrom = jsonBaton ? 'json' : null;
633
+ let hydratedPath = jsonBaton ? jsonBatonPath : null;
634
+
635
+ if (bestMarkdown) {
636
+ const preferMarkdown =
637
+ !jsonBaton ||
638
+ (bestMarkdown.isExternal && bestMarkdown.effectiveTs > jsonEffectiveTs) ||
639
+ bestMarkdown.effectiveTs > jsonEffectiveTs + 50;
640
+ if (preferMarkdown) {
641
+ baton = bestMarkdown.baton;
642
+ hydratedFrom = 'markdown';
643
+ hydratedPath = bestMarkdown.path;
644
+ }
645
+ }
646
+
647
+ if (!baton) {
648
+ return {
649
+ hydrated: false,
650
+ hydratedFrom: null,
651
+ baton: null,
652
+ additionalContext: '',
653
+ hookSpecificOutput: null
654
+ };
655
+ }
656
+
657
+ const additionalContext = formatBatonAdditionalContext(baton);
658
+ return {
659
+ hydrated: true,
660
+ hydratedFrom,
661
+ hydratedPath,
662
+ baton,
663
+ additionalContext,
664
+ hookSpecificOutput: {
665
+ hookEventName: 'SessionStart',
666
+ additionalContext
667
+ }
668
+ };
669
+ }
670
+
671
+ /**
672
+ * Executes `PostCompact` queue flush and records savings into `SavedQuotaReceiptLedger` (`horizon_ledger.jsonl`).
673
+ * Deduplicates dual Tier-1 Mod + Tier-2 CLI execution using `(sessionId, compactionId)` (`ISS-036`).
674
+ *
675
+ * @param {object} [event={}]
676
+ * @param {object} [options={}]
677
+ */
678
+ export function handlePostCompactFlush(event = {}, options = {}) {
679
+ const nowMs = options.nowMs ?? Date.now();
680
+ const explicitCwd = options.cwd || event.cwd || null;
681
+ const cwd = getCwd(explicitCwd ? { ...options, cwd: explicitCwd } : options);
682
+ const ioOpts = { ...options, cwd };
683
+ const diagOpts = explicitCwd ? ioOpts : { ...options, cwd: undefined };
684
+ const sessionId = sanitizeSessionId(event.session_id || event.sessionId || 'default');
685
+
686
+ const sessionBatonPath = getStateBatonFilePath(sessionId, ioOpts);
687
+ const defaultBatonPath = path.join(cwd, '.claude', 'cache', 'state_baton.json');
688
+ let baton = readBatonJsonWithDiagnostics(
689
+ sessionBatonPath,
690
+ 'handlePostCompactFlush.readSessionBaton',
691
+ ioOpts,
692
+ diagOpts
693
+ );
694
+ if (!baton) {
695
+ baton = readBatonJsonWithDiagnostics(
696
+ defaultBatonPath,
697
+ 'handlePostCompactFlush.readFallbackBaton',
698
+ ioOpts,
699
+ diagOpts
700
+ );
701
+ }
702
+
703
+ const explicitCycle =
704
+ event.compactionId || event.compaction_id || event.compactionEpoch || event.turnId || null;
705
+ const cycleId = explicitCycle
706
+ ? `${sessionId}:${String(explicitCycle)}`
707
+ : baton?.compactionId || `${sessionId}:post:${baton?.createdAt || nowMs}`;
708
+ const dedupKey = `${cwd}::${sessionId}::${cycleId}`;
709
+
710
+ const alreadyRecordedOnBaton = Boolean(
711
+ baton &&
712
+ (baton.lastRecordedCompactionId === cycleId ||
713
+ (baton.compactionId === cycleId && baton.ledgerReceiptRecorded === true))
714
+ );
715
+
716
+ if (alreadyRecordedOnBaton || inMemoryRecordedCompactionKeys.has(dedupKey)) {
717
+ return {
718
+ ok: true,
719
+ deduplicated: true,
720
+ sessionId,
721
+ compactionId: cycleId,
722
+ flushedCount: 0,
723
+ appliedMutations: [],
724
+ totalAvoidedPenaltyUSD: 0,
725
+ ledgerEntry: null
726
+ };
727
+ }
728
+
729
+ const queue =
730
+ options.mutationQueue instanceof PostCompactMutationQueue
731
+ ? options.mutationQueue
732
+ : new PostCompactMutationQueue(baton?.queuedCacheMutations || event.queuedCacheMutations || []);
733
+
734
+ const flushResult = queue.flush({ nowMs });
735
+
736
+ // Clear queuedCacheMutations and persist idempotent compaction receipt marker in stored baton
737
+ if (baton) {
738
+ baton.queuedCacheMutations = [];
739
+ baton.lastFlushedAt = nowMs;
740
+ baton.ledgerReceiptRecorded = true;
741
+ baton.lastRecordedCompactionId = cycleId;
742
+ writeJsonAtomic(sessionBatonPath, baton, ioOpts);
743
+ writeJsonAtomic(defaultBatonPath, baton, ioOpts);
744
+ }
745
+ inMemoryRecordedCompactionKeys.add(dedupKey);
746
+
747
+ // Record savings receipt in append-only horizon_ledger.jsonl at most once per compaction cycle (`ISS-024`: never fabricate 25000/mutation)
748
+ const summedFlushedTokens = flushResult.appliedMutations.reduce(
749
+ (acc, entry) => acc + Math.max(0, Number(entry?.cachedTokens || entry?.savedTokens || 0)),
750
+ 0
751
+ );
752
+ const batonSavedBeforeCompact = Math.max(
753
+ 0,
754
+ Number(baton?.metricsSnapshot?.savedTokensBeforeCompact || 0)
755
+ );
756
+ const savedTokens = Math.max(
757
+ 0,
758
+ Number(event.tokensSaved ?? batonSavedBeforeCompact + summedFlushedTokens)
759
+ );
760
+ const savedUSD = Math.max(
761
+ 0,
762
+ Number(
763
+ event.usdSaved ??
764
+ (Number(baton?.metricsSnapshot?.savedUSDBeforeCompact || 0) +
765
+ Number(flushResult.totalAvoidedPenaltyUSD || 0))
766
+ )
767
+ );
768
+
769
+ let ledgerEntry = null;
770
+ if (savedTokens > 0 || savedUSD > 0 || flushResult.flushedCount > 0) {
771
+ const rec = recordSavingsReceipt(
772
+ {
773
+ timestamp: nowMs,
774
+ sessionId,
775
+ category: flushResult.flushedCount > 0 ? 'POST_COMPACT_MUTATION_RELEASE' : 'COMPACT_STATE_BATON',
776
+ modelId: baton?.modelId || event.modelId || 'claude-sonnet-5-5',
777
+ savedTokens,
778
+ savedUSD,
779
+ detail: `Flushed ${flushResult.flushedCount} deferred mutation(s) on fresh post-compaction prefix`
780
+ },
781
+ ioOpts
782
+ );
783
+ ledgerEntry = rec.entry;
784
+ }
785
+
786
+ return {
787
+ ok: true,
788
+ deduplicated: false,
789
+ sessionId,
790
+ compactionId: cycleId,
791
+ flushedCount: flushResult.flushedCount,
792
+ appliedMutations: flushResult.appliedMutations,
793
+ totalAvoidedPenaltyUSD: flushResult.totalAvoidedPenaltyUSD,
794
+ ledgerEntry
795
+ };
796
+ }
797
+
798
+ export default {
799
+ MAX_BATON_TOKEN_BUDGET,
800
+ getStateBatonFilePath,
801
+ buildDurableStateBaton,
802
+ formatBatonAdditionalContext,
803
+ formatUtcHandoffTimestamp,
804
+ parseHandoffFilenameTimestampMs,
805
+ renderPortableHandoffMarkdown,
806
+ parsePortableHandoffMarkdown,
807
+ handlePreCompactBatonFlush,
808
+ handleSessionStartHydration,
809
+ handlePostCompactFlush
810
+ };