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,483 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import { execFileSync } from 'node:child_process';
4
+ import { performance } from 'node:perf_hooks';
5
+ import { canonicalizePath } from '../paths.mjs';
6
+ import { AgBridgeService } from '../ag_bridge.mjs';
7
+ import { extractActiveTaskStep } from '../task_quota_router.mjs';
8
+ import { loadRegistry, deriveSessionClaimedPaths } from '../telemetry/scope_lock_registry.mjs';
9
+ import { atomicWriteFileSync } from '../atomic_io.mjs';
10
+
11
+ /**
12
+ * Phase 4.2 / Ring 1 Hardening: Baton-Pass Generator & Cross-Tool Portable Handoff Packet
13
+ * (`src/core/coach/handoff_hydrator.mjs`)
14
+ *
15
+ * - Deterministically generates standardized `docs/HANDOFF_<timestamp>.md` usable identically
16
+ * in Google Antigravity, Claude Code, Cursor, and Codex CLI:
17
+ * ## 1. Resume Contract & Active Step
18
+ * ## 2. Verified Unchanged File Schemas (Skip Re-Reading)
19
+ * ## 3. Active File Diffs & Owned Scope Paths
20
+ * ## 4. Negative Constraints & Ruled-Out Approaches
21
+ * - Integrates ScopeLockRegistry (DET-20) to pin owned file scopes across concurrent agents.
22
+ * - Supports silent pre-staging when `CacheTtlWatchdog` emits `TTL_PRE_SNAPSHOT` (`T-10s`).
23
+ * - Provides `[Launch Hydrated Session]` (`HandoffHydrationLauncher`): opens a new Antigravity
24
+ * chat thread and populates the Turn-1 bootstrap contract.
25
+ * - Includes Post-Handoff Amnesia Check on Turns 1–3 of the new session.
26
+ */
27
+
28
+ /**
29
+ * Formats any Date, epoch millisecond number, or ISO/hyphenated timestamp string into
30
+ * canonical UTC `YYYYMMDD_HHMMSS` format for `docs/HANDOFF_<YYYYMMDD_HHMMSS>.md`.
31
+ */
32
+ export function formatUtcHandoffTimestamp(tsInput = new Date()) {
33
+ if (typeof tsInput === 'string') {
34
+ const trimmed = tsInput.trim();
35
+ if (/^\d{8}_\d{6}$/.test(trimmed)) return trimmed;
36
+ const hyphMatch = trimmed.match(/^(\d{4})-(\d{2})-(\d{2})T(\d{2})[:-](\d{2})[:-](\d{2})(?:\.\d+)?Z?$/);
37
+ if (hyphMatch && !trimmed.includes('+') && !/\d{2}:\d{2}:\d{2}[+-]\d{2}/.test(trimmed)) {
38
+ return `${hyphMatch[1]}${hyphMatch[2]}${hyphMatch[3]}_${hyphMatch[4]}${hyphMatch[5]}${hyphMatch[6]}`;
39
+ }
40
+ if (/^\d{10,15}$/.test(trimmed)) {
41
+ const num = Number(trimmed);
42
+ const ms = trimmed.length === 10 ? num * 1000 : num;
43
+ return formatUtcHandoffTimestamp(new Date(ms));
44
+ }
45
+ }
46
+ const d = tsInput instanceof Date
47
+ ? tsInput
48
+ : (typeof tsInput === 'number' || typeof tsInput === 'string' ? new Date(tsInput) : new Date());
49
+ const validDate = Number.isNaN(d.getTime()) ? new Date() : d;
50
+ const yyyy = String(validDate.getUTCFullYear());
51
+ const mm = String(validDate.getUTCMonth() + 1).padStart(2, '0');
52
+ const dd = String(validDate.getUTCDate()).padStart(2, '0');
53
+ const hh = String(validDate.getUTCHours()).padStart(2, '0');
54
+ const mi = String(validDate.getUTCMinutes()).padStart(2, '0');
55
+ const ss = String(validDate.getUTCSeconds()).padStart(2, '0');
56
+ return `${yyyy}${mm}${dd}_${hh}${mi}${ss}`;
57
+ }
58
+
59
+ /**
60
+ * Parses a canonical 6-section `# Highbeam State Baton Handoff` markdown file
61
+ * (generated by either Google Antigravity or Claude Code) into structured state.
62
+ */
63
+ export function parsePortableHandoffMarkdown(markdown = '') {
64
+ const text = String(markdown || '');
65
+ const extractSection = (headingPattern) => {
66
+ const re = new RegExp(`^##\\s+${headingPattern}[^\\n]*\\n([\\s\\S]*?)(?=^##\\s+|$)`, 'im');
67
+ const m = text.match(re);
68
+ return m ? m[1].trim() : '';
69
+ };
70
+ const extractBullets = (block) => {
71
+ return String(block || '')
72
+ .split(/\r?\n/)
73
+ .map((l) => l.trim())
74
+ .filter((l) => /^[-*]\s+/.test(l))
75
+ .map((l) => l.replace(/^[-*]\s+/, '').trim())
76
+ .filter((l) => l && !/^\((?:none|no\s)/i.test(l));
77
+ };
78
+
79
+ const sessionMatch = text.match(/\*\*Session ID:\*\*\s*`?([^`\n|]+)`?/i);
80
+ const modelMatch = text.match(/\*\*Active Model:\*\*\s*`?([^`\n|]+)`?/i);
81
+ const capturedMatch = text.match(/\*\*Captured At:\*\*\s*`?([^`\n|]+)`?/i);
82
+
83
+ const sec1 = extractSection('1\\.\\s+Active Goal');
84
+ const sec2 = extractSection('2\\.\\s+Working Set Files');
85
+ const sec3 = extractSection('3\\.\\s+Verified Invariants');
86
+ const sec4 = extractSection('4\\.\\s+Dead Ends & Failures to Avoid');
87
+ const sec5 = extractSection('5\\.\\s+Queued Cache-Prefix Mutations');
88
+ const sec6 = extractSection('6\\.\\s+Exact Next Step');
89
+
90
+ const workingFiles = extractBullets(sec2)
91
+ .map((item) => {
92
+ const m = item.match(/`([^`]+)`/);
93
+ return m ? m[1] : item;
94
+ })
95
+ .filter(Boolean);
96
+
97
+ return {
98
+ isCanonicalStateBaton: text.includes('# Highbeam State Baton Handoff') || text.includes('# Attention Horizon State Baton Handoff'),
99
+ sessionId: sessionMatch ? sessionMatch[1].trim() : null,
100
+ activeModel: modelMatch ? modelMatch[1].trim() : null,
101
+ capturedAt: capturedMatch ? capturedMatch[1].trim() : null,
102
+ activeGoal: sec1,
103
+ workingSetFiles: Array.from(new Set(workingFiles)),
104
+ verifiedInvariants: extractBullets(sec3),
105
+ deadEnds: extractBullets(sec4),
106
+ queuedMutations: extractBullets(sec5),
107
+ exactNextStep: sec6
108
+ };
109
+ }
110
+
111
+ /**
112
+ * Discovers and parses the latest cross-edition State Baton from:
113
+ * 1. `<workspaceDir>/.agents/horizon/HANDOFF_LATEST.md`
114
+ * 2. `<workspaceDir>/docs/HANDOFF_*.md` (newest)
115
+ * 3. `<workspaceDir>/.claude/cache/state_baton.json` (read-only cross-harness fallback)
116
+ */
117
+ export function discoverAndHydrateLatestBaton(workspaceDir = process.cwd()) {
118
+ const candidates = [];
119
+ const latestMdPath = path.join(workspaceDir, '.agents', 'horizon', 'HANDOFF_LATEST.md');
120
+ if (fs.existsSync(latestMdPath)) {
121
+ try {
122
+ const stat = fs.statSync(latestMdPath);
123
+ candidates.push({ kind: 'markdown', path: latestMdPath, mtimeMs: stat.mtimeMs });
124
+ } catch {}
125
+ }
126
+
127
+ const docsDir = path.join(workspaceDir, 'docs');
128
+ if (fs.existsSync(docsDir)) {
129
+ try {
130
+ for (const name of fs.readdirSync(docsDir)) {
131
+ if (/^HANDOFF_.*\.md$/i.test(name)) {
132
+ const full = path.join(docsDir, name);
133
+ const stat = fs.statSync(full);
134
+ candidates.push({ kind: 'markdown', path: full, mtimeMs: stat.mtimeMs });
135
+ }
136
+ }
137
+ } catch {}
138
+ }
139
+
140
+ const claudeBatonJson = path.join(workspaceDir, '.claude', 'cache', 'state_baton.json');
141
+ if (fs.existsSync(claudeBatonJson)) {
142
+ try {
143
+ const stat = fs.statSync(claudeBatonJson);
144
+ candidates.push({ kind: 'claude_json', path: claudeBatonJson, mtimeMs: stat.mtimeMs });
145
+ } catch {}
146
+ }
147
+
148
+ if (candidates.length === 0) return null;
149
+ candidates.sort((a, b) => b.mtimeMs - a.mtimeMs);
150
+ const chosen = candidates[0];
151
+
152
+ if (chosen.kind === 'markdown') {
153
+ const raw = fs.readFileSync(chosen.path, 'utf8');
154
+ return {
155
+ sourcePath: chosen.path,
156
+ sourceKind: 'markdown',
157
+ ...parsePortableHandoffMarkdown(raw),
158
+ markdown: raw
159
+ };
160
+ }
161
+
162
+ try {
163
+ const rawJson = JSON.parse(fs.readFileSync(chosen.path, 'utf8'));
164
+ return {
165
+ sourcePath: chosen.path,
166
+ sourceKind: 'claude_json',
167
+ isCanonicalStateBaton: true,
168
+ sessionId: rawJson.sessionId || null,
169
+ activeModel: rawJson.activeModel || null,
170
+ capturedAt: rawJson.capturedAt || null,
171
+ activeGoal: rawJson.activeGoal || '',
172
+ workingSetFiles: Array.isArray(rawJson.workingSetFiles) ? rawJson.workingSetFiles : [],
173
+ verifiedInvariants: Array.isArray(rawJson.verifiedInvariants) ? rawJson.verifiedInvariants : [],
174
+ deadEnds: Array.isArray(rawJson.deadEnds) ? rawJson.deadEnds : [],
175
+ queuedMutations: Array.isArray(rawJson.queuedMutations) ? rawJson.queuedMutations : [],
176
+ exactNextStep: rawJson.exactNextStep || ''
177
+ };
178
+ } catch {
179
+ return null;
180
+ }
181
+ }
182
+
183
+ export function buildTurn1BootstrapContract({
184
+ handoffPath = 'docs/HANDOFF.md',
185
+ activeTaskStepText = 'Resume active [/] step in task.md',
186
+ verifiedSchemaFiles = []
187
+ } = {}) {
188
+ const verifiedList = verifiedSchemaFiles.length > 0
189
+ ? verifiedSchemaFiles.join(', ')
190
+ : '(none)';
191
+
192
+ return [
193
+ `# Turn-1 Hydrated Baton-Pass Contract`,
194
+ `- **Handoff Bundle:** \`${handoffPath}\``,
195
+ `- **Active Step (\`[/]\` in \`task.md\`):** ${activeTaskStepText}`,
196
+ `- **Execution Rules:**`,
197
+ ` 1. Resume immediately at the active \`[/]\` step in \`task.md\`.`,
198
+ ` 2. Always use \`StartLine\` and \`EndLine\` ranges when inspecting files.`,
199
+ ` 3. **SKIP \`view_file\` calls** on already-verified unchanged schema files: ${verifiedList}.`
200
+ ].join('\n');
201
+ }
202
+
203
+ function readGitDiffStatSafe(workspaceDir) {
204
+ try {
205
+ const out = execFileSync('git', ['diff', '--stat'], {
206
+ cwd: workspaceDir,
207
+ encoding: 'utf8',
208
+ stdio: ['ignore', 'pipe', 'ignore'],
209
+ timeout: 2000
210
+ });
211
+ return String(out || '').trim() || '(clean working tree)';
212
+ } catch {
213
+ return '(git diff unavailable)';
214
+ }
215
+ }
216
+
217
+ export class HandoffHydrationLauncher {
218
+ constructor(options = {}) {
219
+ this.workspaceDir = options.workspaceDir || process.cwd();
220
+ this.agBridge = options.agBridge || new AgBridgeService(options);
221
+ this.preStagedBundle = null;
222
+ this.lastGeneratedBundle = null;
223
+ }
224
+
225
+ /**
226
+ * Generates standardized `docs/HANDOFF_<YYYYMMDD_HHMMSS>.md` + `.agents/horizon/HANDOFF_LATEST.md`
227
+ * using the unified 6-section `# Highbeam State Baton Handoff` schema.
228
+ */
229
+ generateHandoffBundle({
230
+ workspaceDir = this.workspaceDir,
231
+ sessionId = 'active-session',
232
+ activeModel = 'gemini-3.1-pro',
233
+ taskMdContent = null,
234
+ gitDiffSummary = null,
235
+ verifiedSchemaFiles = [],
236
+ verifiedInvariants = [],
237
+ ownedScopePaths = null,
238
+ negativeConstraints = [],
239
+ queuedMutations = [],
240
+ exactNextStep = null,
241
+ timestamp = null,
242
+ writeToDisk = true,
243
+ writeDocsHandoff = true
244
+ } = {}) {
245
+ const startMs = performance.now();
246
+ const capturedIso = typeof timestamp === 'string' && /^\d{4}-\d{2}-\d{2}T/.test(timestamp)
247
+ ? timestamp
248
+ : new Date().toISOString();
249
+ const ts = formatUtcHandoffTimestamp(timestamp || capturedIso);
250
+ const handoffRelPath = `docs/HANDOFF_${ts}.md`;
251
+ const handoffAbsPath = path.join(workspaceDir, 'docs', `HANDOFF_${ts}.md`);
252
+ const latestHandoffRelPath = '.agents/horizon/HANDOFF_LATEST.md';
253
+ const latestHandoffAbsPath = path.join(workspaceDir, '.agents', 'horizon', 'HANDOFF_LATEST.md');
254
+
255
+ let resolvedTaskMd = taskMdContent;
256
+ if (resolvedTaskMd === null) {
257
+ const taskPath = path.join(workspaceDir, 'task.md');
258
+ resolvedTaskMd = fs.existsSync(taskPath) ? fs.readFileSync(taskPath, 'utf8') : '- [/] Continue active task\n';
259
+ }
260
+
261
+ const activeStep = extractActiveTaskStep(resolvedTaskMd);
262
+ const activeStepText = exactNextStep || (activeStep.found ? activeStep.rawText : 'Continue next pending item in task.md');
263
+ const resolvedGitDiff = gitDiffSummary !== null ? String(gitDiffSummary) : readGitDiffStatSafe(workspaceDir);
264
+
265
+ // Resolve owned scope paths from parameters, scope lockfile, or task.md
266
+ let resolvedScopePaths = Array.isArray(ownedScopePaths) ? ownedScopePaths : null;
267
+ if (resolvedScopePaths === null) {
268
+ try {
269
+ const reg = loadRegistry(workspaceDir);
270
+ const allPaths = new Set();
271
+ for (const l of reg.leases) {
272
+ for (const p of l.claimedPaths || []) {
273
+ allPaths.add(p);
274
+ }
275
+ }
276
+ if (allPaths.size > 0) {
277
+ resolvedScopePaths = Array.from(allPaths).sort();
278
+ } else {
279
+ resolvedScopePaths = deriveSessionClaimedPaths({ workspaceDir, taskMdContent: resolvedTaskMd });
280
+ }
281
+ } catch {
282
+ resolvedScopePaths = [];
283
+ }
284
+ }
285
+
286
+ const invariants = Array.isArray(verifiedInvariants) && verifiedInvariants.length > 0
287
+ ? verifiedInvariants
288
+ : ['Zero-trust read-only host telemetry invariants active; preserve verified schemas without full re-reads.'];
289
+
290
+ const constraints = negativeConstraints.length > 0
291
+ ? negativeConstraints
292
+ : [
293
+ 'NEVER modify AGENTS.md or .agents/CONTEXT.md while KV cache is warm (cachedTokens >= 15000).',
294
+ 'NEVER perform un-ranged full-file view_file calls on large source or verified schema files.',
295
+ 'NEVER delete existing test assertions or replace error handlers with empty stubs.'
296
+ ];
297
+
298
+ const queuedLines = Array.isArray(queuedMutations) && queuedMutations.length > 0
299
+ ? queuedMutations.map((m) => typeof m === 'string' ? `- ${m}` : `- \`${m.targetPath || 'AGENTS.md'}\` (${m.operation || 'ADD'}): ${m.ruleText || m.summary || JSON.stringify(m)}`)
300
+ : ['- (None — zero queued prefix mutations)'];
301
+
302
+ const markdown = [
303
+ `# Highbeam State Baton Handoff`,
304
+ `- **Session ID:** \`${sessionId}\``,
305
+ `- **Active Model:** \`${activeModel}\``,
306
+ `- **Captured At:** \`${capturedIso}\``,
307
+ ``,
308
+ `## 1. Active Goal`,
309
+ `**Active Step (\`[/]\` in \`task.md\`):** ${activeStepText}`,
310
+ ``,
311
+ '```markdown',
312
+ String(resolvedTaskMd).trim(),
313
+ '```',
314
+ ``,
315
+ `## 2. Working Set Files`,
316
+ `### Owned Scope Paths (Concurrent Lockfile DET-20)`,
317
+ ...(resolvedScopePaths.length > 0
318
+ ? resolvedScopePaths.map((f) => `- \`${f}\``)
319
+ : ['- (No explicit file leases claimed)']),
320
+ ``,
321
+ `### Verified Unchanged File Schemas (Skip Re-Reading)`,
322
+ ...(verifiedSchemaFiles.length > 0
323
+ ? verifiedSchemaFiles.map((f) => `- \`${f}\``)
324
+ : ['- (No unchanged schema files pinned)']),
325
+ ``,
326
+ `### Git Diff Summary`,
327
+ '```text',
328
+ resolvedGitDiff,
329
+ '```',
330
+ ``,
331
+ `## 3. Verified Invariants`,
332
+ ...invariants.map((inv) => `- ${inv}`),
333
+ ``,
334
+ `## 4. Dead Ends & Failures to Avoid`,
335
+ ...constraints.map((c) => `- ${c}`),
336
+ ``,
337
+ `## 5. Queued Cache-Prefix Mutations (Released on PostCompact)`,
338
+ ...queuedLines,
339
+ ``,
340
+ `## 6. Exact Next Step`,
341
+ `- ${activeStepText}`,
342
+ ``
343
+ ].join('\n');
344
+
345
+ if (writeToDisk) {
346
+ if (writeDocsHandoff !== false) {
347
+ atomicWriteFileSync(handoffAbsPath, markdown, { encoding: 'utf8' });
348
+ }
349
+ atomicWriteFileSync(latestHandoffAbsPath, markdown, { encoding: 'utf8' });
350
+ }
351
+
352
+ const bootstrapContract = buildTurn1BootstrapContract({
353
+ handoffPath: writeDocsHandoff !== false ? handoffRelPath : latestHandoffRelPath,
354
+ activeTaskStepText: activeStepText,
355
+ verifiedSchemaFiles
356
+ });
357
+
358
+ const bundle = {
359
+ timestamp: ts,
360
+ capturedAt: capturedIso,
361
+ handoffRelPath,
362
+ handoffAbsPath,
363
+ latestHandoffRelPath,
364
+ latestHandoffAbsPath,
365
+ activeStepText,
366
+ verifiedSchemaFiles: [...verifiedSchemaFiles],
367
+ ownedScopePaths: [...resolvedScopePaths],
368
+ negativeConstraints: [...constraints],
369
+ markdown,
370
+ bootstrapContract,
371
+ elapsedMs: Number((performance.now() - startMs).toFixed(3))
372
+ };
373
+
374
+ this.lastGeneratedBundle = bundle;
375
+ return bundle;
376
+ }
377
+
378
+ /**
379
+ * Silently pre-stages a zero-token disk handoff bundle to `.agents/horizon/HANDOFF_LATEST.md`
380
+ * when `CacheTtlWatchdog` emits `TTL_PRE_SNAPSHOT` (`T-10s`).
381
+ */
382
+ preStageOnTtlSnapshot(options = {}) {
383
+ this.preStagedBundle = this.generateHandoffBundle({
384
+ ...options,
385
+ writeToDisk: options.writeToDisk !== false,
386
+ writeDocsHandoff: options.writeDocsHandoff === true
387
+ });
388
+ return this.preStagedBundle;
389
+ }
390
+
391
+ /**
392
+ * Discovers and parses the latest cross-edition State Baton (`.agents/horizon/HANDOFF_LATEST.md`,
393
+ * `docs/HANDOFF_*.md`, or `.claude/cache/state_baton.json`).
394
+ */
395
+ discoverLatestBaton(workspaceDir = this.workspaceDir) {
396
+ return discoverAndHydrateLatestBaton(workspaceDir);
397
+ }
398
+
399
+ /**
400
+ * Executes `[Launch Hydrated Session]`: opens a new Antigravity chat thread and populates
401
+ * the Turn-1 bootstrap contract.
402
+ */
403
+ async launchHydratedSession(options = {}) {
404
+ const bundle = this.preStagedBundle || this.lastGeneratedBundle || this.generateHandoffBundle(options);
405
+ const spawnRes = await this.agBridge.spawnCleanSession({
406
+ sessionId: options.sessionId,
407
+ taskMd: options.taskMdContent,
408
+ handoffMd: bundle.markdown,
409
+ bootstrapPrompt: bundle.bootstrapContract
410
+ });
411
+
412
+ return {
413
+ ok: true,
414
+ action: 'LAUNCH_HYDRATED_SESSION',
415
+ sessionId: spawnRes.sessionId,
416
+ brainDir: spawnRes.brainDir,
417
+ handoffRelPath: bundle.handoffRelPath,
418
+ handoffAbsPath: bundle.handoffAbsPath,
419
+ bootstrapContract: bundle.bootstrapContract,
420
+ verifiedSchemaFiles: bundle.verifiedSchemaFiles,
421
+ transportUsed: spawnRes.transportUsed
422
+ };
423
+ }
424
+
425
+ /**
426
+ * Post-Handoff Amnesia Check on Turns 1–3 of the new session:
427
+ * Flags any redundant full-file `view_file` / `read_file` of files already summarized
428
+ * in `verifiedSchemaFiles` from the handoff bundle.
429
+ */
430
+ checkPostHandoffAmnesia(steps = [], verifiedSchemaFiles = null) {
431
+ const schemaFiles = Array.isArray(verifiedSchemaFiles)
432
+ ? verifiedSchemaFiles
433
+ : (this.lastGeneratedBundle?.verifiedSchemaFiles || []);
434
+
435
+ const canonVerifiedSet = new Set(schemaFiles.map((f) => canonicalizePath(f)));
436
+ const baseNameVerifiedSet = new Set(schemaFiles.map((f) => path.basename(String(f).replace(/\\/g, '/')).toLowerCase()));
437
+
438
+ const list = Array.isArray(steps) ? steps.slice(0, 3) : [];
439
+ const violations = [];
440
+
441
+ for (let turnIdx = 0; turnIdx < list.length; turnIdx++) {
442
+ const step = list[turnIdx] || {};
443
+ const calls = Array.isArray(step.toolCalls)
444
+ ? step.toolCalls
445
+ : (Array.isArray(step.tool_calls) ? step.tool_calls : [step]);
446
+
447
+ for (const call of calls) {
448
+ const name = String(call.name || call.tool || '').toLowerCase();
449
+ if (name !== 'view_file' && name !== 'read_file') continue;
450
+
451
+ const args = call.args || call.parameters || {};
452
+ const startLine = args.StartLine ?? args.start_line ?? call.StartLine ?? null;
453
+ const endLine = args.EndLine ?? args.end_line ?? call.EndLine ?? null;
454
+ const isFullRead = startLine === null && endLine === null;
455
+ if (!isFullRead) continue;
456
+
457
+ const rawPath = String(
458
+ call.path || args.AbsolutePath || args.TargetFile || args.Path || args.path || ''
459
+ ).trim();
460
+ if (!rawPath) continue;
461
+
462
+ const canon = canonicalizePath(rawPath);
463
+ const base = path.basename(rawPath.replace(/\\/g, '/')).toLowerCase();
464
+
465
+ if (canonVerifiedSet.has(canon) || baseNameVerifiedSet.has(base)) {
466
+ violations.push({
467
+ turnNumber: turnIdx + 1,
468
+ filePath: rawPath,
469
+ reason: `Redundant full-file read on Turn ${turnIdx + 1} of handoff-verified schema file "${rawPath}"`
470
+ });
471
+ }
472
+ }
473
+ }
474
+
475
+ return {
476
+ amnesiaDetected: violations.length > 0,
477
+ violationCount: violations.length,
478
+ violations
479
+ };
480
+ }
481
+ }
482
+
483
+ export default HandoffHydrationLauncher;