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,433 @@
1
+ import fs from 'node:fs';
2
+ import path from 'node:path';
3
+ import crypto from 'node:crypto';
4
+ import { getHomeDir, canonicalizePath } from './paths.mjs';
5
+ import { findSessionDirectory, resolveSessionLogs, parseRawJsonl } from './parser.mjs';
6
+ import { classifyHorizon } from './classifier.mjs';
7
+ import { CATEGORIES, HORIZON_WINDOW } from './constants.mjs';
8
+ import { atomicWriteFileSync } from './atomic_io.mjs';
9
+
10
+ /**
11
+ * Prefix-Safe Surgical Context Pruner & Regex Signature Folder.
12
+ *
13
+ * Condenses `STALE_DUPLICATE` full-file reads into compact declaration signature stubs
14
+ * (preserving imports, exports, class/function/interface/type/def declarations and
15
+ * original line numbers) and collapses `DEAD_ERROR` stack traces into 1-line
16
+ * `[Resolved Error at Turn #N]` tombstones.
17
+ *
18
+ * Enforces Prefix-Cache Safety: checks whether the 5-minute prompt prefix cache TTL
19
+ * has expired (`isCacheCold`) or if the user explicitly confirms (`forceHotCache: true`),
20
+ * and writes an atomic `.pre_prune.<timestamp>.bak` backup before modifying any JSONL file.
21
+ */
22
+
23
+ const SIGNATURE_LINE_RE = /^\s*(?:export\s+|import\s+|async\s+function\s+|function\s+|class\s+|interface\s+|type\s+\w+\s*=|const\s+\w+\s*=\s*(?:async\s*)?\(|def\s+\w+|class\s+\w+|pub\s+(?:fn|struct|enum|trait)|fn\s+\w+|struct\s+\w+|CREATE\s+TABLE)/;
24
+
25
+ /**
26
+ * Folds raw source code or file read output into a compact AST-like signature stub
27
+ * with original line numbers preserved.
28
+ */
29
+ export function foldCodeToSignatureStub(rawContent, targetPath = 'file') {
30
+ const text = String(rawContent || '');
31
+ const lines = text.split(/\r?\n/);
32
+ if (lines.length <= 24 || text.length <= 1000) {
33
+ return { condensed: text, savedChars: 0, wasFolded: false };
34
+ }
35
+
36
+ const kept = [];
37
+ let skippedRun = 0;
38
+
39
+ for (let i = 0; i < lines.length; i++) {
40
+ const line = lines[i];
41
+ const lineNum = i + 1;
42
+ // Strip optional `123: ` prefix from read_file outputs before matching
43
+ const cleanLine = line.replace(/^\s*\d+\s*[:|]\s*/, '');
44
+ if (i < 3 || i >= lines.length - 2 || SIGNATURE_LINE_RE.test(cleanLine)) {
45
+ if (skippedRun > 0) {
46
+ kept.push(` /* ... [condensed ${skippedRun} implementation lines] ... */`);
47
+ skippedRun = 0;
48
+ }
49
+ kept.push(`${lineNum}: ${cleanLine.slice(0, 140)}`);
50
+ } else {
51
+ skippedRun++;
52
+ }
53
+ }
54
+ if (skippedRun > 0) {
55
+ kept.push(` /* ... [condensed ${skippedRun} implementation lines] ... */`);
56
+ }
57
+
58
+ const header = `[AST Signature Stub — Condensed Stale Read of ${path.basename(String(targetPath || 'file'))} (${lines.length} lines)]`;
59
+ const condensed = `${header}\n${kept.join('\n')}`;
60
+ const savedChars = Math.max(0, text.length - condensed.length);
61
+ return {
62
+ condensed: savedChars > 200 ? condensed : text,
63
+ savedChars: savedChars > 200 ? savedChars : 0,
64
+ wasFolded: savedChars > 200
65
+ };
66
+ }
67
+
68
+ /**
69
+ * Collapses a resolved Dead Error stack trace into a 1-line tombstone.
70
+ */
71
+ export function collapseDeadErrorToTombstone(rawContent, stepIndex = 0, target = 'Command') {
72
+ const text = String(rawContent || '');
73
+ if (text.length <= 400) {
74
+ return { condensed: text, savedChars: 0, wasCollapsed: false };
75
+ }
76
+ const firstMeaningfulLine = text
77
+ .split(/\r?\n/)
78
+ .map(l => l.trim())
79
+ .find(l => l.length > 0 && !l.startsWith('Created At:') && !l.startsWith('Completed At:')) || 'Error output';
80
+ const savedTokensEst = Math.round(text.length / 4);
81
+ const tombstone = `[Resolved Error at Turn #${stepIndex} (${target}): "${firstMeaningfulLine.slice(0, 120)}" — pruned ~${savedTokensEst} tokens of resolved stack trace]`;
82
+ const savedChars = Math.max(0, text.length - tombstone.length);
83
+ return {
84
+ condensed: tombstone,
85
+ savedChars,
86
+ wasCollapsed: savedChars > 100
87
+ };
88
+ }
89
+
90
+ /**
91
+ * Analyzes or executes prefix-safe surgical pruning on a session's JSONL transcript.
92
+ */
93
+ export function pruneSessionTranscript(sessionDir, {
94
+ dryRun = false,
95
+ forceHotCache = false,
96
+ cacheDir = null,
97
+ cwd = null,
98
+ workspacePath = null,
99
+ offloadDir = null,
100
+ nowMs = Date.now()
101
+ } = {}) {
102
+ if (!sessionDir || !fs.existsSync(sessionDir)) {
103
+ return { success: false, error: 'Session directory not found', prunedSteps: 0, savedTokens: 0 };
104
+ }
105
+
106
+ const resolved = resolveSessionLogs(sessionDir);
107
+ if (!resolved || !resolved.path || !fs.existsSync(resolved.path)) {
108
+ return { success: false, error: 'Single-file JSONL transcript not found for session', prunedSteps: 0, savedTokens: 0 };
109
+ }
110
+
111
+ const transcriptPath = resolved.path;
112
+ const rawFileContent = fs.readFileSync(transcriptPath, 'utf8');
113
+ const rawLines = rawFileContent.split(/\r?\n/).filter(l => l.trim().length > 0);
114
+ const parsedSteps = parseRawJsonl(rawFileContent, { tier: resolved.tier, stepsDir: resolved.stepsDir });
115
+ const state = classifyHorizon(parsedSteps, {
116
+ sessionId: path.basename(sessionDir),
117
+ cacheDir
118
+ });
119
+
120
+ const isCacheCold = Boolean(state.quota?.cache?.isCacheCold) || (state.quota?.cache?.idleSeconds >= 300);
121
+ const cacheTtlRemainingSec = state.quota?.cache?.ttlRemainingSec ?? 0;
122
+
123
+ if (!dryRun && !isCacheCold && !forceHotCache) {
124
+ return {
125
+ success: false,
126
+ requiresConfirmation: true,
127
+ isCacheCold: false,
128
+ cacheTtlRemainingSec,
129
+ error: `Prompt prefix cache is still warm (${cacheTtlRemainingSec}s TTL remaining). Condense after idle TTL expires, before switching models, or pass forceHotCache=true.`
130
+ };
131
+ }
132
+
133
+ // Pass 1 (ISS-040): Track (canonPath, startLine, endLine, lastEditTurnForPath) across the session
134
+ // so disjoint line-range reads, post-edit verification reads, and active latest reads are protected.
135
+ const activeCutoff = Math.max(0, parsedSteps.length - HORIZON_WINDOW.ACTIVE_SET_STEP_WINDOW);
136
+ const isEditToolRe = /^(edit_file|write_file|write_to_file|replace_file_content|multi_replace_file_content|edit|write|multiedit|notebookedit)$/i;
137
+ const isReadToolRe = /^(view_file|read_file|read)$/i;
138
+ const lastEditTurnByCanon = new Map();
139
+ const stepReadMetaByIdx = new Map();
140
+ const latestReadIdxByKey = new Map();
141
+ const latestFullReadIdxByCanon = new Map();
142
+
143
+ for (let i = 0; i < parsedSteps.length; i++) {
144
+ const calls = parsedSteps[i]?.toolCalls || [];
145
+ for (const c of calls) {
146
+ const toolName = String(c.name || c.tool || '').toLowerCase();
147
+ const args = c.args || c.parameters || c.Arguments || {};
148
+ const f = args.Path || args.path || args.TargetFile || args.AbsolutePath || args.Target;
149
+ if (!f) continue;
150
+ const canon = canonicalizePath(String(f));
151
+ if (!canon) continue;
152
+
153
+ if (isEditToolRe.test(toolName)) {
154
+ lastEditTurnByCanon.set(canon, i);
155
+ } else if (isReadToolRe.test(toolName)) {
156
+ const rawStart = args.StartLine ?? args.start_line ?? args.startLine ?? args.offset ?? null;
157
+ const rawEnd = args.EndLine ?? args.end_line ?? args.endLine ?? args.limit ?? null;
158
+ const startLine = rawStart !== null && rawStart !== undefined && rawStart !== '' && Number.isFinite(Number(rawStart))
159
+ ? Number(rawStart)
160
+ : 'FULL';
161
+ const endLine = rawEnd !== null && rawEnd !== undefined && rawEnd !== '' && Number.isFinite(Number(rawEnd))
162
+ ? Number(rawEnd)
163
+ : 'FULL';
164
+ const editGen = lastEditTurnByCanon.has(canon) ? lastEditTurnByCanon.get(canon) : -1;
165
+ const readKey = `${canon}::${startLine}::${endLine}::${editGen}`;
166
+ stepReadMetaByIdx.set(i, { canon, rawPath: String(f), startLine, endLine, editGen, readKey });
167
+ latestReadIdxByKey.set(readKey, i);
168
+ if (startLine === 'FULL' && endLine === 'FULL') {
169
+ latestFullReadIdxByCanon.set(canon, i);
170
+ }
171
+ }
172
+ }
173
+ }
174
+
175
+ const baseOffloadWorkspace = cwd || workspacePath || sessionDir;
176
+ const resolvedOffloadDir = offloadDir || path.join(baseOffloadWorkspace, '.agents', 'tmp');
177
+
178
+ const writeOffloadCopy = (rawText) => {
179
+ const hash12 = crypto.createHash('sha256').update(rawText, 'utf8').digest('hex').slice(0, 12);
180
+ const fileName = `offload_${hash12}.txt`;
181
+ const offloadAbsPath = path.join(resolvedOffloadDir, fileName);
182
+ const pointerRel = `.agents/tmp/${fileName}`;
183
+ if (!dryRun) {
184
+ atomicWriteFileSync(offloadAbsPath, rawText, { encoding: 'utf8' });
185
+ }
186
+ return { offloadAbsPath, pointerRel };
187
+ };
188
+
189
+ let prunedSteps = 0;
190
+ let savedCharsTotal = 0;
191
+ const prunedDetails = [];
192
+ const updatedLines = [];
193
+
194
+ for (let i = 0; i < rawLines.length; i++) {
195
+ const line = rawLines[i];
196
+ let entry;
197
+ try {
198
+ entry = JSON.parse(line);
199
+ } catch {
200
+ updatedLines.push(line);
201
+ continue;
202
+ }
203
+
204
+ // Never mutate Turn 0, checkpoints, or the active working window
205
+ if (i === 0 || i >= activeCutoff || entry.type === 'CHECKPOINT' || entry.type === 'SYSTEM_PROMPT') {
206
+ updatedLines.push(line);
207
+ continue;
208
+ }
209
+
210
+ const content = String(entry.content || '');
211
+ const calls = entry.tool_calls || entry.toolCalls || [];
212
+ const isReadOnlyFileCall = calls.length > 0 && calls.every(c => /^(view_file|read_file|read|view_file_outline|view_code_item)$/i.test(String(c.name || c.tool || '')));
213
+ const isError = entry.status === 'ERROR' ||
214
+ (typeof entry.exitCode === 'number' && entry.exitCode !== 0) ||
215
+ (!isReadOnlyFileCall && content.includes('Traceback (most recent call last)'));
216
+
217
+ let modified = false;
218
+ if (isError && content.length > 400) {
219
+ const collapsed = collapseDeadErrorToTombstone(content, entry.step_index ?? i, calls[0]?.name || 'Error');
220
+ if (collapsed.wasCollapsed) {
221
+ let offloadMeta;
222
+ try {
223
+ offloadMeta = writeOffloadCopy(content);
224
+ } catch {
225
+ // ISS-040 Safety Invariant: if offload write fails, preserve raw output intact!
226
+ updatedLines.push(line);
227
+ continue;
228
+ }
229
+ const condensedWithPointer = `${collapsed.condensed} [Offloaded: ${offloadMeta.pointerRel}]`;
230
+ const netSaved = Math.max(0, content.length - condensedWithPointer.length);
231
+ if (netSaved > 60) {
232
+ entry.content = condensedWithPointer;
233
+ entry.pruned_by_horizon = 'DEAD_ERROR_TOMBSTONE';
234
+ entry.offload_pointer = offloadMeta.pointerRel;
235
+ const newTok = Math.max(10, Math.ceil(condensedWithPointer.length / 4));
236
+ if (entry.output_tokens !== undefined) entry.output_tokens = newTok;
237
+ if (entry.outputTokens !== undefined) entry.outputTokens = newTok;
238
+ savedCharsTotal += netSaved;
239
+ prunedSteps++;
240
+ prunedDetails.push({
241
+ stepIndex: i,
242
+ kind: 'DEAD_ERROR',
243
+ savedTokens: Math.round(netSaved / 4),
244
+ offloadPointer: offloadMeta.pointerRel,
245
+ offloadPath: offloadMeta.offloadAbsPath
246
+ });
247
+ modified = true;
248
+ }
249
+ }
250
+ } else if (content.length > 1000) {
251
+ const readMeta = stepReadMetaByIdx.get(i) || null;
252
+ let targetFile = readMeta ? readMeta.rawPath : '';
253
+ let isSupersededFile = false;
254
+ let isProtectedActiveRead = false;
255
+
256
+ if (readMeta) {
257
+ const latestSameKeyIdx = latestReadIdxByKey.get(readMeta.readKey);
258
+ const currentFinalEditGen = lastEditTurnByCanon.has(readMeta.canon)
259
+ ? lastEditTurnByCanon.get(readMeta.canon)
260
+ : -1;
261
+ const latestFullIdx = latestFullReadIdxByCanon.get(readMeta.canon);
262
+
263
+ if (latestSameKeyIdx !== undefined && latestSameKeyIdx > i) {
264
+ // Identical (canonPath, startLine, endLine, editGen) read repeated later
265
+ isSupersededFile = true;
266
+ } else if (
267
+ readMeta.startLine === 'FULL' &&
268
+ readMeta.endLine === 'FULL' &&
269
+ readMeta.editGen < currentFinalEditGen &&
270
+ latestFullIdx !== undefined &&
271
+ latestFullIdx > i
272
+ ) {
273
+ // Full-file pre-edit read superseded by a later post-edit full-file read
274
+ isSupersededFile = true;
275
+ } else if (readMeta.editGen === currentFinalEditGen && latestSameKeyIdx === i) {
276
+ // Most recent read for this (canonPath, startLine, endLine, currentEditGen) — NEVER fold!
277
+ isProtectedActiveRead = true;
278
+ }
279
+ } else {
280
+ for (const c of calls) {
281
+ const args = c.args || c.parameters || {};
282
+ const f = args.Path || args.path || args.Target;
283
+ if (f) targetFile = String(f);
284
+ }
285
+ }
286
+
287
+ const isOldTurn = !isProtectedActiveRead && !readMeta && (i < parsedSteps.length - HORIZON_WINDOW.STALE_STEP_THRESHOLD);
288
+ if (isSupersededFile || isOldTurn) {
289
+ const folded = foldCodeToSignatureStub(content, targetFile || `turn-${i}`);
290
+ if (folded.wasFolded) {
291
+ let offloadMeta;
292
+ try {
293
+ offloadMeta = writeOffloadCopy(content);
294
+ } catch {
295
+ // ISS-040 Safety Invariant: if offload write fails, preserve raw output intact!
296
+ updatedLines.push(line);
297
+ continue;
298
+ }
299
+ const condensedWithPointer = `${folded.condensed}\n[Full raw output preserved at ${offloadMeta.pointerRel}]`;
300
+ const netSaved = Math.max(0, content.length - condensedWithPointer.length);
301
+ if (netSaved > 150) {
302
+ entry.content = condensedWithPointer;
303
+ entry.pruned_by_horizon = 'AST_SIGNATURE_STUB';
304
+ entry.offload_pointer = offloadMeta.pointerRel;
305
+ const newTok = Math.max(10, Math.ceil(condensedWithPointer.length / 4));
306
+ if (entry.output_tokens !== undefined) entry.output_tokens = newTok;
307
+ if (entry.outputTokens !== undefined) entry.outputTokens = newTok;
308
+ savedCharsTotal += netSaved;
309
+ prunedSteps++;
310
+ prunedDetails.push({
311
+ stepIndex: i,
312
+ kind: 'AST_FOLD',
313
+ target: targetFile || `turn-${i}`,
314
+ savedTokens: Math.round(netSaved / 4),
315
+ offloadPointer: offloadMeta.pointerRel,
316
+ offloadPath: offloadMeta.offloadAbsPath
317
+ });
318
+ modified = true;
319
+ }
320
+ }
321
+ }
322
+ }
323
+
324
+ updatedLines.push(modified ? JSON.stringify(entry) : line);
325
+ }
326
+
327
+ const savedTokens = Math.round(savedCharsTotal / 4);
328
+ let backupPath = null;
329
+
330
+ if (!dryRun && prunedSteps > 0) {
331
+ backupPath = `${transcriptPath}.pre_prune.${nowMs}.bak`;
332
+ fs.copyFileSync(transcriptPath, backupPath);
333
+ atomicWriteFileSync(transcriptPath, updatedLines.join('\n') + '\n', { encoding: 'utf8' });
334
+
335
+ // Invalidate incremental parser cache so the next poll reads the condensed transcript
336
+ const actualCacheDir = cacheDir || path.join(getHomeDir(), '.gemini', 'antigravity', 'cache', 'agy-horizon');
337
+ const idxCache = path.join(actualCacheDir, `${path.basename(sessionDir)}.idx.json`);
338
+ if (fs.existsSync(idxCache)) {
339
+ try { fs.unlinkSync(idxCache); } catch {}
340
+ }
341
+ }
342
+
343
+ return {
344
+ success: true,
345
+ dryRun,
346
+ isCacheCold,
347
+ cacheTtlRemainingSec,
348
+ prunedSteps,
349
+ savedTokens,
350
+ backupPath,
351
+ details: prunedDetails
352
+ };
353
+ }
354
+
355
+
356
+ /**
357
+ * Computes a compact unified delta diff + exported signature index when an agent re-reads
358
+ * a file that was modified since its previous unclipped read in the same session.
359
+ *
360
+ * @param {string} prevContent
361
+ * @param {string} nextContent
362
+ * @param {string} [targetPath='file']
363
+ * @param {number} [contextLines=3]
364
+ */
365
+ export function computeCompactLineDiff(prevContent = '', nextContent = '', targetPath = 'file', contextLines = 3) {
366
+ const prev = String(prevContent ?? '');
367
+ const next = String(nextContent ?? '');
368
+ if (!prev || !next || prev === next || next.length > 256 * 1024) {
369
+ return { diffText: next, savedChars: 0, savedTokens: 0, changedLines: 0, wasDiffed: false };
370
+ }
371
+
372
+ const oldLines = prev.split(/\r?\n/);
373
+ const newLines = next.split(/\r?\n/);
374
+
375
+ let prefixLen = 0;
376
+ const minLen = Math.min(oldLines.length, newLines.length);
377
+ while (prefixLen < minLen && oldLines[prefixLen] === newLines[prefixLen]) {
378
+ prefixLen++;
379
+ }
380
+
381
+ let suffixLen = 0;
382
+ while (
383
+ suffixLen < minLen - prefixLen &&
384
+ oldLines[oldLines.length - 1 - suffixLen] === newLines[newLines.length - 1 - suffixLen]
385
+ ) {
386
+ suffixLen++;
387
+ }
388
+
389
+ const oldChangedEnd = oldLines.length - suffixLen;
390
+ const newChangedEnd = newLines.length - suffixLen;
391
+
392
+ const ctxBeforeStart = Math.max(0, prefixLen - contextLines);
393
+ const oldCtxAfterEnd = Math.min(oldLines.length, oldChangedEnd + contextLines);
394
+ const newCtxAfterEnd = Math.min(newLines.length, newChangedEnd + contextLines);
395
+
396
+ const hunkLines = [];
397
+ hunkLines.push(`--- a/${targetPath}`);
398
+ hunkLines.push(`+++ b/${targetPath}`);
399
+ hunkLines.push(
400
+ `@@ -${ctxBeforeStart + 1},${Math.max(1, oldCtxAfterEnd - ctxBeforeStart)} +${ctxBeforeStart + 1},${Math.max(1, newCtxAfterEnd - ctxBeforeStart)} @@`
401
+ );
402
+
403
+ for (let i = ctxBeforeStart; i < prefixLen; i++) {
404
+ hunkLines.push(` ${oldLines[i]}`);
405
+ }
406
+ for (let i = prefixLen; i < oldChangedEnd; i++) {
407
+ hunkLines.push(`-${oldLines[i]}`);
408
+ }
409
+ for (let i = prefixLen; i < newChangedEnd; i++) {
410
+ hunkLines.push(`+${newLines[i]}`);
411
+ }
412
+ for (let i = newChangedEnd; i < newCtxAfterEnd; i++) {
413
+ hunkLines.push(` ${newLines[i]}`);
414
+ }
415
+
416
+ const folded = foldCodeToSignatureStub(next, targetPath);
417
+ const sigAppendix = folded.wasFolded ? `\n\n[Updated File Signature Index]\n${folded.condensed}` : '';
418
+ const diffText = `[Delta Read since prior snapshot of ${targetPath} (${oldLines.length} -> ${newLines.length} lines)]\n${hunkLines.join('\n')}${sigAppendix}`;
419
+ const savedChars = next.length - diffText.length;
420
+
421
+ if (savedChars <= 160 || diffText.length > next.length * 0.75) {
422
+ return { diffText: next, savedChars: 0, savedTokens: 0, changedLines: 0, wasDiffed: false };
423
+ }
424
+
425
+ const changedLines = (oldChangedEnd - prefixLen) + (newChangedEnd - prefixLen);
426
+ return {
427
+ diffText,
428
+ savedChars,
429
+ savedTokens: Math.max(1, Math.round(savedChars / 4)),
430
+ changedLines,
431
+ wasDiffed: true
432
+ };
433
+ }