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,609 @@
1
+ import fs from 'node:fs';
2
+ import { getHomeDir } from './paths.mjs';
3
+ import { findSessionDirectory, parseTranscriptIncremental } from './parser.mjs';
4
+ import {
5
+ normalizeModelId,
6
+ resolveModelDescriptor,
7
+ resolveModelRates,
8
+ calculateModelCost,
9
+ createSwarmAgentState,
10
+ validateSwarmAgentState,
11
+ CORE_SCHEMAS
12
+ } from './constants.mjs';
13
+
14
+ /**
15
+ * Multi-Agent (`invoke_subagent`) Context Tree & Handoff Inspector.
16
+ *
17
+ * Scans parent transcript steps for `invoke_subagent` tool calls, resolves child
18
+ * session transcripts across `inherit`, `branch`, and `share` workspace modes,
19
+ * and computes isolated child exploration bloat vs. parent handoff compression.
20
+ */
21
+
22
+ export const HANDOFF_BLOAT_THRESHOLD_TOKENS = 4000;
23
+
24
+ export function inspectSubagentTree(steps = [], {
25
+ homeDir = getHomeDir(),
26
+ cacheDir = null
27
+ } = {}) {
28
+ const invocations = [];
29
+ const childIdsSeen = new Set();
30
+
31
+ for (let i = 0; i < steps.length; i++) {
32
+ const step = steps[i] || {};
33
+ const calls = step.toolCalls || [];
34
+ for (const call of calls) {
35
+ const name = String(call.name || '').toLowerCase();
36
+ if (name === 'invoke_subagent') {
37
+ const args = call.args || {};
38
+ const role = args.Role || args.role || 'Subagent';
39
+ const typeName = args.TypeName || args.typeName || 'self';
40
+ const workspaceMode = args.Workspace || args.workspace || 'inherit';
41
+ const model = args.Model || args.model || 'inherit';
42
+
43
+ // Extract returned conversationId or subagent response from subsequent steps
44
+ let childConversationId = call.result?.conversationId || call.conversationId || args.conversationId || null;
45
+ let handoffTokens = 0;
46
+ let handoffStepIdx = i;
47
+
48
+ // Look ahead up to 6 steps for the subagent completion/response or conversationId
49
+ for (let j = i; j < Math.min(steps.length, i + 7); j++) {
50
+ const lookStep = steps[j] || {};
51
+ const text = String(lookStep.content || '');
52
+ if (!childConversationId) {
53
+ const matches = text.matchAll(/conversation(?:Id|_id)["'\s:=]+([0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12})/gi);
54
+ for (const m of matches) {
55
+ if (m[1] && !childIdsSeen.has(m[1])) {
56
+ childConversationId = m[1];
57
+ break;
58
+ }
59
+ }
60
+ }
61
+ const isParentStep = !lookStep.agentId || lookStep.agentId === 'parent';
62
+ if (j > i && isParentStep && (text.toLowerCase().includes('subagent') || text.includes(role))) {
63
+ const est = lookStep.outputTokens || Math.ceil(text.length / 4) || 0;
64
+ if (est > handoffTokens) {
65
+ handoffTokens = est;
66
+ handoffStepIdx = j;
67
+ }
68
+ }
69
+ }
70
+
71
+ if (handoffTokens === 0) {
72
+ handoffTokens = Math.max(250, Math.min(2500, Math.ceil(String(step.content || '').length / 4) || 600));
73
+ }
74
+
75
+ let isolatedTokens = 0;
76
+ let childStepCount = 0;
77
+
78
+ // If child session exists on disk, measure its isolated transcript size
79
+ if (childConversationId) {
80
+ childIdsSeen.add(childConversationId);
81
+ try {
82
+ const childSession = findSessionDirectory(childConversationId, homeDir);
83
+ if (childSession && fs.existsSync(childSession.sessionDir)) {
84
+ const parsedChild = parseTranscriptIncremental(childSession.sessionDir, cacheDir);
85
+ childStepCount = (parsedChild.steps || []).length;
86
+ isolatedTokens = (parsedChild.steps || []).reduce((sum, cs) => {
87
+ const tok = cs.outputTokens || Math.ceil((cs.untruncatedLength || 0) / 4) || 500;
88
+ return sum + tok;
89
+ }, 0);
90
+ }
91
+ } catch {}
92
+ }
93
+
94
+ // Fallback estimate for child steps embedded via agentId === `child:...`
95
+ if (isolatedTokens === 0) {
96
+ const embeddedChildSteps = steps.filter(s => s.agentId && s.agentId !== 'parent');
97
+ if (embeddedChildSteps.length > 0) {
98
+ childStepCount = embeddedChildSteps.length;
99
+ isolatedTokens = embeddedChildSteps.reduce((sum, cs) => sum + (cs.outputTokens || Math.ceil((cs.untruncatedLength || 0) / 4) || 800), 0);
100
+ } else {
101
+ isolatedTokens = Math.max(handoffTokens * 12, 18000);
102
+ childStepCount = 8;
103
+ }
104
+ }
105
+
106
+ const compressionRatio = parseFloat((isolatedTokens / Math.max(1, handoffTokens)).toFixed(1));
107
+ const rawDumpLeak = handoffTokens >= HANDOFF_BLOAT_THRESHOLD_TOKENS;
108
+
109
+ const resolvedConvId = childConversationId || `subagent-step-${i}-${invocations.length}`;
110
+ if (invocations.some((inv) => inv.conversationId === resolvedConvId)) {
111
+ continue;
112
+ }
113
+
114
+ invocations.push({
115
+ stepIndex: i,
116
+ handoffStepIndex: handoffStepIdx,
117
+ conversationId: resolvedConvId,
118
+ role,
119
+ typeName,
120
+ workspaceMode,
121
+ model,
122
+ childStepCount,
123
+ isolatedTokens,
124
+ handoffTokens,
125
+ tokensSaved: Math.max(0, isolatedTokens - handoffTokens),
126
+ compressionRatio,
127
+ rawDumpLeak,
128
+ badgeLabel: `[Subagent: ${typeName} | ${(isolatedTokens / 1000).toFixed(1)}k isolated -> ${(handoffTokens / 1000).toFixed(1)}k handoff (${Math.round(compressionRatio)}x)]`
129
+ });
130
+ }
131
+ }
132
+ }
133
+
134
+ const totalIsolatedTokens = invocations.reduce((s, x) => s + x.isolatedTokens, 0);
135
+ const totalHandoffTokens = invocations.reduce((s, x) => s + x.handoffTokens, 0);
136
+ const totalSavedTokens = invocations.reduce((s, x) => s + x.tokensSaved, 0);
137
+ const overallCompressionRatio = totalHandoffTokens > 0
138
+ ? parseFloat((totalIsolatedTokens / totalHandoffTokens).toFixed(1))
139
+ : 0;
140
+
141
+ return {
142
+ count: invocations.length,
143
+ totalIsolatedTokens,
144
+ totalHandoffTokens,
145
+ totalSavedTokens,
146
+ overallCompressionRatio,
147
+ hasRawDumpLeak: invocations.some(x => x.rawDumpLeak),
148
+ invocations
149
+ };
150
+ }
151
+
152
+ /**
153
+ * Builds a parent -> subagent worktree DAG (`inherit`, `branch`, `share`),
154
+ * tracking isolated vs handoff tokens, `cacheCreationEphemeral5mInputTokens` TTL countdowns,
155
+ * and detecting concurrent `fileCollisions` when >= 2 active subagents edit the same file path.
156
+ */
157
+ export function buildSubagentWorktreeDag(steps = [], { childTranscripts = [], nowMs = Date.now() } = {}) {
158
+ const baseTree = inspectSubagentTree(steps);
159
+ const editsByAgent = new Map(); // canonPath -> Set<agentId>
160
+ const readsByAgent = new Map(); // canonPath -> Set<agentId>
161
+ const nodes = [];
162
+
163
+ for (const child of (childTranscripts || [])) {
164
+ const agentId = String(child.agentId || child.conversationId || `sub-${nodes.length}`);
165
+ const workspaceMode = child.workspaceMode || 'inherit';
166
+ const childSteps = Array.isArray(child.steps) ? child.steps : [];
167
+ let isolatedTokens = 0;
168
+ let latestTs = 0;
169
+ const modifiedFiles = new Set();
170
+ const readFiles = new Set();
171
+
172
+ for (const cs of childSteps) {
173
+ isolatedTokens += Math.max(0, Number(cs.outputTokens ?? cs.output_tokens ?? 0) || 0);
174
+ const ts = cs.createdAt ? Date.parse(cs.createdAt) : (cs.timestamp ? Date.parse(cs.timestamp) : 0);
175
+ if (Number.isFinite(ts) && ts > latestTs) latestTs = ts;
176
+
177
+ const calls = Array.isArray(cs.toolCalls) ? cs.toolCalls : (Array.isArray(cs.tool_calls) ? cs.tool_calls : []);
178
+ for (const c of calls) {
179
+ const name = String(c.name || c.tool || '').toLowerCase();
180
+ const args = c.args || c.parameters || c.Arguments || {};
181
+ const fp = args.Path || args.path || args.TargetFile || args.AbsolutePath;
182
+ if (fp && /edit|write|replace/i.test(name)) {
183
+ const norm = String(fp).replace(/\\/g, '/').toLowerCase();
184
+ modifiedFiles.add(norm);
185
+ if (!editsByAgent.has(norm)) editsByAgent.set(norm, new Set());
186
+ editsByAgent.get(norm).add(agentId);
187
+ }
188
+ if (fp && /view|read/i.test(name)) {
189
+ const norm = String(fp).replace(/\\/g, '/').toLowerCase();
190
+ readFiles.add(norm);
191
+ if (!readsByAgent.has(norm)) readsByAgent.set(norm, new Set());
192
+ readsByAgent.get(norm).add(agentId);
193
+ }
194
+ }
195
+ }
196
+
197
+ const idleSec = latestTs > 0 ? Math.max(0, Math.round((nowMs - latestTs) / 1000)) : 0;
198
+ const ttlRemainingSec = latestTs > 0 ? Math.max(0, 300 - idleSec) : 300;
199
+
200
+ nodes.push({
201
+ agentId,
202
+ workspaceMode,
203
+ isolatedTokens,
204
+ ttlWindowSec: 300,
205
+ ttlRemainingSec,
206
+ modifiedFiles: Array.from(modifiedFiles),
207
+ readFiles: Array.from(readFiles)
208
+ });
209
+ }
210
+
211
+ const fileCollisions = [];
212
+ for (const [filePath, agentsSet] of editsByAgent.entries()) {
213
+ if (agentsSet.size >= 2) {
214
+ fileCollisions.push({
215
+ filePath,
216
+ agents: Array.from(agentsSet),
217
+ severity: 'CONCURRENT_EDIT_COLLISION'
218
+ });
219
+ }
220
+ }
221
+
222
+ const readCollisions = [];
223
+ for (const [filePath, agentsSet] of readsByAgent.entries()) {
224
+ if (agentsSet.size >= 2) {
225
+ readCollisions.push({
226
+ filePath,
227
+ agents: Array.from(agentsSet),
228
+ severity: 'DUPLICATE_READ_COLLISION'
229
+ });
230
+ }
231
+ }
232
+
233
+ return {
234
+ parentInvocationCount: baseTree.count,
235
+ nodes,
236
+ fileCollisions,
237
+ hasFileCollision: fileCollisions.length > 0,
238
+ readCollisions,
239
+ hasReadCollision: readCollisions.length > 0
240
+ };
241
+ }
242
+
243
+ export const SWARM_IDLE_TTL_CONSTANTS = Object.freeze({
244
+ DEFAULT_CACHE_TTL_MS: 300000, // 5 minutes (300,000 ms)
245
+ DEFAULT_COLD_WAKE_THRESHOLD_TOKENS: 100000, // 100,000 warm prefix tokens
246
+ CLIFF_WARNING_SECONDS: 60, // warn when within 60 seconds of falling off cache cliff
247
+ SWARM_TOOL_MATCHER: 'invoke_subagent|define_subagent|send_message|manage_subagents'
248
+ });
249
+
250
+ /**
251
+ * Determines whether a model is considered a frontier model subject to cold-cache wakeup diagnostics.
252
+ */
253
+ export function isFrontierSwarmModel(modelId = '') {
254
+ const desc = resolveModelDescriptor(modelId);
255
+ if (desc && (desc.family === 'carbon' || desc.family === 'argon' || desc.family === 'opus' || desc.family === 'sonnet')) {
256
+ return true;
257
+ }
258
+ const norm = normalizeModelId(modelId);
259
+ return norm.includes('carbon') || norm.includes('argon') || norm.includes('opus') || norm.includes('pro');
260
+ }
261
+
262
+ /**
263
+ * Extracts target recipient agent IDs from a `send_message` tool call or `@mention` text.
264
+ */
265
+ export function extractTargetRecipientAgents(toolInput = {}, rawText = '') {
266
+ const targets = new Set();
267
+ const recipient = toolInput?.Recipient || toolInput?.recipient || toolInput?.targetAgent || toolInput?.agent_id || toolInput?.agentId;
268
+ if (recipient && typeof recipient === 'string' && recipient.trim()) {
269
+ targets.add(recipient.trim());
270
+ }
271
+ const msgText = String(toolInput?.Message || toolInput?.message || toolInput?.brief || rawText || '');
272
+ const mentionMatches = msgText.match(/@([a-z0-9_-]+)/gi) || [];
273
+ for (const m of mentionMatches) {
274
+ const clean = m.slice(1).trim();
275
+ if (clean) targets.add(clean);
276
+ }
277
+ return Array.from(targets);
278
+ }
279
+
280
+ /**
281
+ * Computes per-agent TTL countdown badges for the local state JSON so the UI/statusline
282
+ * warns when a parked Carbon coordinator or verifier is within 60 seconds of falling off the cache cliff.
283
+ */
284
+ export function computeSwarmRosterTtlBadges(swarmRoster = {}, {
285
+ nowMs = Date.now(),
286
+ cacheTtlMs = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS
287
+ } = {}) {
288
+ const badges = [];
289
+ const entries = swarmRoster instanceof Map
290
+ ? Array.from(swarmRoster.entries())
291
+ : Object.entries(swarmRoster || {});
292
+
293
+ for (const [keyId, rawAgent] of entries) {
294
+ if (!rawAgent || typeof rawAgent !== 'object') continue;
295
+ const state = createSwarmAgentState({ ...rawAgent, agent_id: rawAgent.agent_id || keyId });
296
+ const ttlMs = Number(state.cache_ttl_ms || cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
297
+ const elapsedMs = Math.max(0, nowMs - state.last_active_timestamp);
298
+ const remainingMs = state.status === 'terminated' ? 0 : Math.max(0, ttlMs - elapsedMs);
299
+ const remainingSec = Math.ceil(remainingMs / 1000);
300
+ const isExpired = state.status !== 'terminated' && elapsedMs > ttlMs;
301
+ const isNearCliff = state.status === 'idle_zero_token' && remainingSec > 0 && remainingSec <= SWARM_IDLE_TTL_CONSTANTS.CLIFF_WARNING_SECONDS;
302
+
303
+ const mins = Math.floor(remainingSec / 60);
304
+ const secs = remainingSec % 60;
305
+ const countdownLabel = remainingSec > 0
306
+ ? `${mins}m ${String(secs).padStart(2, '0')}s`
307
+ : '0m 00s (expired)';
308
+
309
+ const badgeText = isNearCliff
310
+ ? `⚠️ [${state.agent_id} • ${state.model_id}] Cache cliff in ${remainingSec}s (${Math.round(state.warm_prefix_tokens / 1000)}k warm) [CACHE CLIFF WARNING]`
311
+ : (isExpired
312
+ ? `❄️ [${state.agent_id} • ${state.model_id}] Cold cache (${Math.round(state.warm_prefix_tokens / 1000)}k expired)`
313
+ : `🟢 [${state.agent_id} • ${state.model_id}] ${countdownLabel} (${Math.round(state.warm_prefix_tokens / 1000)}k warm)`);
314
+
315
+ badges.push({
316
+ agent_id: state.agent_id,
317
+ model_id: state.model_id,
318
+ status: state.status,
319
+ warm_prefix_tokens: state.warm_prefix_tokens,
320
+ last_active_timestamp: state.last_active_timestamp,
321
+ cache_ttl_ms: ttlMs,
322
+ elapsed_ms: elapsedMs,
323
+ ttl_remaining_ms: remainingMs,
324
+ ttl_remaining_sec: remainingSec,
325
+ remaining_ttl_sec: remainingSec,
326
+ is_near_cliff: isNearCliff,
327
+ within_cliff_warning: isNearCliff,
328
+ is_expired: isExpired,
329
+ countdown_label: countdownLabel,
330
+ badge_text: badgeText,
331
+ badge_label: badgeText
332
+ });
333
+ }
334
+
335
+ return badges;
336
+ }
337
+
338
+ /**
339
+ * Evaluates a `PreToolUse` on `send_message` (or `@mention` dispatch) targeting a specific `Recipient` agent.
340
+ * If the target agent is running `gemini-4-carbon` (or another frontier model), has
341
+ * `warm_prefix_tokens >= cold_wake_threshold` (default 100,000), and `now - target.last_active_timestamp > cache_ttl_ms`,
342
+ * surfaces a Cold-Cache Wakeup diagnostic quantifying the uncached input rebuild cost using `resolveModelRates()`.
343
+ */
344
+ export function evaluateSwarmColdCacheWakeup({
345
+ recipientAgentId,
346
+ swarmRoster = {},
347
+ nowMs = Date.now(),
348
+ eventTimestampUtc = null,
349
+ serviceTier = 'standard',
350
+ coldWakeThresholdTokens = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS,
351
+ cacheTtlMs = SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS
352
+ } = {}) {
353
+ const targetRecord = swarmRoster instanceof Map
354
+ ? swarmRoster.get(recipientAgentId)
355
+ : (swarmRoster?.[recipientAgentId] || null);
356
+
357
+ if (!targetRecord) {
358
+ return {
359
+ triggered: false,
360
+ reason: 'UNKNOWN_AGENT',
361
+ recipientAgentId: recipientAgentId || null
362
+ };
363
+ }
364
+
365
+ const state = createSwarmAgentState({ ...targetRecord, agent_id: targetRecord.agent_id || recipientAgentId });
366
+ const ttlMs = Number(state.cache_ttl_ms || cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
367
+ const threshold = Number(coldWakeThresholdTokens ?? SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS);
368
+ const elapsedMs = Math.max(0, nowMs - state.last_active_timestamp);
369
+ const elapsedSec = Math.round(elapsedMs / 1000);
370
+ const ttlRemainingSec = Math.max(0, Math.ceil((ttlMs - elapsedMs) / 1000));
371
+ const isCacheExpired = elapsedMs > ttlMs;
372
+ const isFrontier = isFrontierSwarmModel(state.model_id);
373
+ const meetsTokenThreshold = state.warm_prefix_tokens >= threshold;
374
+
375
+ const effectiveTimestamp = eventTimestampUtc ?? nowMs;
376
+ const rates = resolveModelRates(state.model_id, effectiveTimestamp, serviceTier);
377
+ const uncachedRebuildCost = calculateModelCost(
378
+ { input_tokens: state.warm_prefix_tokens, output_tokens: 0, thinking_tokens: 0, cached_read_tokens: 0 },
379
+ { modelId: state.model_id, eventTimestampUtc: effectiveTimestamp, serviceTier }
380
+ );
381
+ const warmHitCost = calculateModelCost(
382
+ { input_tokens: 0, output_tokens: 0, thinking_tokens: 0, cached_read_tokens: state.warm_prefix_tokens },
383
+ { modelId: state.model_id, eventTimestampUtc: effectiveTimestamp, serviceTier }
384
+ );
385
+
386
+ const rebuildCostUsd = uncachedRebuildCost.inputCostUsd;
387
+ const warmReadCostUsd = warmHitCost.cachedReadCostUsd;
388
+ const penaltyDeltaUsd = Number((rebuildCostUsd - warmReadCostUsd).toFixed(6));
389
+
390
+ if (state.status !== 'terminated' && isFrontier && meetsTokenThreshold && isCacheExpired) {
391
+ return {
392
+ triggered: true,
393
+ coldWakeDetected: true,
394
+ cacheWarm: false,
395
+ diagnosticType: 'COLD_CACHE_WAKEUP',
396
+ recipientAgentId: state.agent_id,
397
+ modelId: state.model_id,
398
+ status: state.status,
399
+ warmPrefixTokens: state.warm_prefix_tokens,
400
+ elapsedMs,
401
+ elapsedSec,
402
+ cacheTtlMs: ttlMs,
403
+ ttlRemainingSec: 0,
404
+ pricingWindow: rates.pricingWindow,
405
+ serviceTier: rates.serviceTier,
406
+ inputRatePer1M: rates.input_per_1m,
407
+ cachedReadRatePer1M: rates.cached_read_per_1m,
408
+ uncachedRebuildCostUsd: rebuildCostUsd,
409
+ warmReadCostUsd,
410
+ penaltyDeltaUsd,
411
+ incrementalColdPenaltyUsd: penaltyDeltaUsd,
412
+ message: `[Cold-Cache Wakeup] Waking idle agent "${state.agent_id}" (${state.model_id}) after ${elapsedSec}s (> ${Math.round(ttlMs / 1000)}s TTL) triggers an uncached rebuild of ${state.warm_prefix_tokens.toLocaleString('en-US')} prefix tokens costing $${rebuildCostUsd.toFixed(4)} ($${rates.input_per_1m.toFixed(2)}/1M ${rates.pricingWindow} ${rates.serviceTier} rate vs $${warmReadCostUsd.toFixed(4)} warm hit).`
413
+ };
414
+ }
415
+
416
+ return {
417
+ triggered: false,
418
+ coldWakeDetected: false,
419
+ cacheWarm: !isCacheExpired,
420
+ diagnosticType: 'WARM_CACHE_HIT',
421
+ recipientAgentId: state.agent_id,
422
+ modelId: state.model_id,
423
+ status: state.status,
424
+ warmPrefixTokens: state.warm_prefix_tokens,
425
+ elapsedMs,
426
+ elapsedSec,
427
+ cacheTtlMs: ttlMs,
428
+ ttlRemainingSec,
429
+ pricingWindow: rates.pricingWindow,
430
+ serviceTier: rates.serviceTier,
431
+ uncachedRebuildCostUsd: 0,
432
+ warmReadCostUsd,
433
+ penaltyDeltaUsd: 0,
434
+ incrementalColdPenaltyUsd: 0,
435
+ message: ''
436
+ };
437
+ }
438
+
439
+ /**
440
+ * Stateful `/swarm` roster & idle-TTL tracker for coordinator and subagent lifecycles.
441
+ */
442
+ export class SwarmIdleTtlTracker {
443
+ constructor(options = {}) {
444
+ this.cacheTtlMs = Number(options.cacheTtlMs || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_CACHE_TTL_MS);
445
+ this.coldWakeThresholdTokens = Number(options.coldWakeThresholdTokens || SWARM_IDLE_TTL_CONSTANTS.DEFAULT_COLD_WAKE_THRESHOLD_TOKENS);
446
+ this.roster = new Map();
447
+ if (options.initialRoster && typeof options.initialRoster === 'object') {
448
+ for (const [k, v] of Object.entries(options.initialRoster)) {
449
+ const st = createSwarmAgentState({ ...v, agent_id: v?.agent_id || k, cache_ttl_ms: v?.cache_ttl_ms || this.cacheTtlMs });
450
+ this.roster.set(st.agent_id, st);
451
+ }
452
+ }
453
+ }
454
+
455
+ registerOrActivateAgent(agentId, {
456
+ modelId = 'gemini-4-carbon',
457
+ warmPrefixTokens = 0,
458
+ timestampMs = Date.now(),
459
+ role = null
460
+ } = {}) {
461
+ const existing = this.roster.get(agentId);
462
+ const state = createSwarmAgentState({
463
+ agent_id: agentId,
464
+ model_id: modelId || existing?.model_id || 'gemini-4-carbon',
465
+ status: 'active',
466
+ last_active_timestamp: timestampMs,
467
+ warm_prefix_tokens: warmPrefixTokens > 0 ? warmPrefixTokens : (existing?.warm_prefix_tokens || 0),
468
+ cache_ttl_ms: this.cacheTtlMs,
469
+ role: role || existing?.role || null
470
+ });
471
+ this.roster.set(state.agent_id, state);
472
+ return { ...state };
473
+ }
474
+
475
+ /**
476
+ * Transitions an agent to `idle_zero_token` when its turn completes while the parent swarm remains live.
477
+ */
478
+ markTurnCompleted(agentId, {
479
+ warmPrefixTokens = undefined,
480
+ timestampMs = Date.now(),
481
+ parentSwarmLive = true
482
+ } = {}) {
483
+ const existing = this.roster.get(agentId) || createSwarmAgentState({ agent_id: agentId });
484
+ const nextStatus = parentSwarmLive ? 'idle_zero_token' : 'terminated';
485
+ const updated = createSwarmAgentState({
486
+ ...existing,
487
+ agent_id: agentId,
488
+ status: nextStatus,
489
+ last_active_timestamp: timestampMs,
490
+ warm_prefix_tokens: warmPrefixTokens !== undefined ? warmPrefixTokens : existing.warm_prefix_tokens,
491
+ cache_ttl_ms: existing.cache_ttl_ms || this.cacheTtlMs
492
+ });
493
+ this.roster.set(updated.agent_id, updated);
494
+ return { ...updated };
495
+ }
496
+
497
+ terminateAgent(agentId, timestampMs = Date.now()) {
498
+ const existing = this.roster.get(agentId) || createSwarmAgentState({ agent_id: agentId });
499
+ const updated = createSwarmAgentState({
500
+ ...existing,
501
+ agent_id: agentId,
502
+ status: 'terminated',
503
+ last_active_timestamp: timestampMs
504
+ });
505
+ this.roster.set(updated.agent_id, updated);
506
+ return { ...updated };
507
+ }
508
+
509
+ interceptSendMessagePreToolUse(toolInput = {}, {
510
+ nowMs = Date.now(),
511
+ eventTimestampUtc = null,
512
+ serviceTier = 'standard'
513
+ } = {}) {
514
+ const recipients = extractTargetRecipientAgents(toolInput);
515
+ const diagnostics = [];
516
+ for (const recipientId of recipients) {
517
+ const diag = evaluateSwarmColdCacheWakeup({
518
+ recipientAgentId: recipientId,
519
+ swarmRoster: this.roster,
520
+ nowMs,
521
+ eventTimestampUtc: eventTimestampUtc ?? nowMs,
522
+ serviceTier,
523
+ coldWakeThresholdTokens: this.coldWakeThresholdTokens,
524
+ cacheTtlMs: this.cacheTtlMs
525
+ });
526
+ diagnostics.push(diag);
527
+ }
528
+ const triggeredDiagnostics = diagnostics.filter(d => d.triggered);
529
+ return {
530
+ triggered: triggeredDiagnostics.length > 0,
531
+ recipients,
532
+ diagnostics,
533
+ coldWakeupAlerts: triggeredDiagnostics,
534
+ primaryAlert: triggeredDiagnostics[0] || null
535
+ };
536
+ }
537
+
538
+ getBadges(nowMsOrOpts = Date.now()) {
539
+ const nowMs = typeof nowMsOrOpts === 'object' && nowMsOrOpts !== null
540
+ ? (nowMsOrOpts.nowMs ?? Date.now())
541
+ : nowMsOrOpts;
542
+ return computeSwarmRosterTtlBadges(this.roster, { nowMs, cacheTtlMs: this.cacheTtlMs });
543
+ }
544
+
545
+ getTtlBadges(nowMsOrOpts = Date.now()) {
546
+ return this.getBadges(nowMsOrOpts);
547
+ }
548
+
549
+ touchAgentActive(agentId, options = {}) {
550
+ return this.registerOrActivateAgent(agentId, options);
551
+ }
552
+
553
+ onTurnComplete(agentId, options = {}) {
554
+ if (options.modelId && !this.roster.has(agentId)) {
555
+ this.registerOrActivateAgent(agentId, {
556
+ modelId: options.modelId,
557
+ warmPrefixTokens: options.warmPrefixTokens ?? 0,
558
+ timestampMs: options.timestampMs ?? Date.now()
559
+ });
560
+ } else if (options.modelId && this.roster.has(agentId)) {
561
+ const cur = this.roster.get(agentId);
562
+ this.roster.set(agentId, { ...cur, model_id: normalizeModelId(options.modelId) });
563
+ }
564
+ return this.markTurnCompleted(agentId, options);
565
+ }
566
+
567
+ handlePreToolSendMessage(toolInput = {}, options = {}) {
568
+ const res = this.interceptSendMessagePreToolUse(toolInput, options);
569
+ const primary = res.primaryAlert || res.diagnostics[0] || {
570
+ triggered: false,
571
+ coldWakeDetected: false,
572
+ cacheWarm: true,
573
+ uncachedRebuildCostUsd: 0,
574
+ incrementalColdPenaltyUsd: 0,
575
+ message: ''
576
+ };
577
+ return {
578
+ ...primary,
579
+ ...res,
580
+ coldWakeDetected: Boolean(primary.coldWakeDetected || res.triggered),
581
+ cacheWarm: Boolean(primary.cacheWarm && !res.triggered),
582
+ uncachedRebuildCostUsd: primary.uncachedRebuildCostUsd ?? 0,
583
+ incrementalColdPenaltyUsd: primary.incrementalColdPenaltyUsd ?? 0,
584
+ warmPrefixTokens: primary.warmPrefixTokens ?? 0,
585
+ message: primary.message || ''
586
+ };
587
+ }
588
+
589
+ getRosterSnapshot() {
590
+ const agents = {};
591
+ for (const [id, st] of this.roster.entries()) {
592
+ agents[id] = { ...st };
593
+ }
594
+ return agents;
595
+ }
596
+
597
+ toJSON(nowMs = Date.now()) {
598
+ const agents = {};
599
+ for (const [id, st] of this.roster.entries()) {
600
+ agents[id] = { ...st };
601
+ }
602
+ return {
603
+ agents,
604
+ badges: this.getBadges(nowMs)
605
+ };
606
+ }
607
+ }
608
+
609
+