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.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,236 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Sprint 2.2 — `/cost-radar` HTML/SVG timeline artifact.
|
|
3
|
+
*
|
|
4
|
+
* Pure, zero-dependency renderer (no `node:*` imports) so it can be shared with the
|
|
5
|
+
* Claude Code edition and embedded into Antigravity Studio as an Artifact.
|
|
6
|
+
*
|
|
7
|
+
* Panels (dark, Tufte-style high data-ink, tabular figures):
|
|
8
|
+
* 1. Prefix-Cache Retention step chart per turn, bust markers + savings callout.
|
|
9
|
+
* 2. Thinking vs. Generation drift sparkline + TTFT strip, DET-30 loop turns highlighted.
|
|
10
|
+
* 3. Swarm / worktree topology graph (coordinator -> workers, worktrees, DET-20 overlaps).
|
|
11
|
+
*
|
|
12
|
+
* Unmeasured inputs render an explicit "no data" note — never fabricated values.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
export const COST_RADAR_DIMENSIONS = Object.freeze({
|
|
16
|
+
WIDTH: 640,
|
|
17
|
+
CHART_HEIGHT: 120,
|
|
18
|
+
PAD_LEFT: 36,
|
|
19
|
+
PAD_RIGHT: 12,
|
|
20
|
+
PAD_TOP: 14,
|
|
21
|
+
PAD_BOTTOM: 18
|
|
22
|
+
});
|
|
23
|
+
|
|
24
|
+
const COLORS = Object.freeze({
|
|
25
|
+
bg: '#0b1020',
|
|
26
|
+
fg: '#cbd5e1',
|
|
27
|
+
muted: '#64748b',
|
|
28
|
+
grid: '#1e293b',
|
|
29
|
+
good: '#34d399',
|
|
30
|
+
warn: '#fbbf24',
|
|
31
|
+
bad: '#f87171',
|
|
32
|
+
accent: '#60a5fa',
|
|
33
|
+
think: '#a78bfa'
|
|
34
|
+
});
|
|
35
|
+
|
|
36
|
+
export function escapeXml(value) {
|
|
37
|
+
return String(value ?? '')
|
|
38
|
+
.replace(/&/g, '&')
|
|
39
|
+
.replace(/</g, '<')
|
|
40
|
+
.replace(/>/g, '>')
|
|
41
|
+
.replace(/"/g, '"')
|
|
42
|
+
.replace(/'/g, ''');
|
|
43
|
+
}
|
|
44
|
+
|
|
45
|
+
function fmtUsd(n) {
|
|
46
|
+
const v = Number(n) || 0;
|
|
47
|
+
return v >= 1 ? `$${v.toFixed(2)}` : `$${v.toFixed(3)}`;
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function fmtTokens(n) {
|
|
51
|
+
const v = Number(n) || 0;
|
|
52
|
+
if (v >= 1_000_000) return `${(v / 1_000_000).toFixed(1)}M`;
|
|
53
|
+
if (v >= 1000) return `${(v / 1000).toFixed(1)}k`;
|
|
54
|
+
return String(Math.round(v));
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
function emptyPanel(message, height = 40) {
|
|
58
|
+
const { WIDTH } = COST_RADAR_DIMENSIONS;
|
|
59
|
+
return `<svg class="cr-svg" viewBox="0 0 ${WIDTH} ${height}" width="100%" role="img" aria-label="${escapeXml(message)}">` +
|
|
60
|
+
`<text x="${WIDTH / 2}" y="${height / 2 + 4}" text-anchor="middle" fill="${COLORS.muted}" font-size="11">${escapeXml(message)}</text></svg>`;
|
|
61
|
+
}
|
|
62
|
+
|
|
63
|
+
/**
|
|
64
|
+
* Panel 1: retention step chart. `retention.series` = [{ pct, bust, cause, ttlExpired, savedUSD }].
|
|
65
|
+
*/
|
|
66
|
+
export function renderRetentionStepChart(retention) {
|
|
67
|
+
const series = Array.isArray(retention?.series) ? retention.series : [];
|
|
68
|
+
if (!retention?.measured || series.length === 0) {
|
|
69
|
+
return emptyPanel('Prefix retention: no multi-turn cache usage measured yet');
|
|
70
|
+
}
|
|
71
|
+
const { WIDTH, CHART_HEIGHT: H, PAD_LEFT: L, PAD_RIGHT: R, PAD_TOP: T, PAD_BOTTOM: B } = COST_RADAR_DIMENSIONS;
|
|
72
|
+
const innerW = WIDTH - L - R;
|
|
73
|
+
const innerH = H - T - B;
|
|
74
|
+
const n = series.length;
|
|
75
|
+
const step = innerW / Math.max(1, n);
|
|
76
|
+
const y = (pct) => T + innerH - (Math.max(0, Math.min(100, pct)) / 100) * innerH;
|
|
77
|
+
|
|
78
|
+
let d = '';
|
|
79
|
+
let lastY = y(0);
|
|
80
|
+
const marks = [];
|
|
81
|
+
series.forEach((pt, i) => {
|
|
82
|
+
const x0 = L + i * step;
|
|
83
|
+
const x1 = x0 + step;
|
|
84
|
+
if (pt.ttlExpired || pt.pct === null || pt.pct === undefined) {
|
|
85
|
+
marks.push(`<rect x="${x0.toFixed(1)}" y="${T}" width="${step.toFixed(1)}" height="${innerH}" fill="${COLORS.grid}" opacity="0.6"><title>Turn ${i + 1}: TTL expired while idle (excluded)</title></rect>`);
|
|
86
|
+
return;
|
|
87
|
+
}
|
|
88
|
+
const yy = y(pt.pct);
|
|
89
|
+
d += d ? ` L${x0.toFixed(1)},${lastY.toFixed(1)} L${x0.toFixed(1)},${yy.toFixed(1)}` : `M${x0.toFixed(1)},${yy.toFixed(1)}`;
|
|
90
|
+
d += ` L${x1.toFixed(1)},${yy.toFixed(1)}`;
|
|
91
|
+
lastY = yy;
|
|
92
|
+
if (pt.bust) {
|
|
93
|
+
const cx = x0 + step / 2;
|
|
94
|
+
marks.push(`<path d="M${cx.toFixed(1)},${(yy - 7).toFixed(1)} l4,7 l-8,0 z" fill="${COLORS.bad}"><title>Turn ${i + 1}: prefix bust (${escapeXml(String(pt.cause || 'unknown').replace(/_/g, ' '))}) — ${pt.pct}% retained</title></path>`);
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
|
|
98
|
+
const grid = [0, 50, 90, 100].map((p) =>
|
|
99
|
+
`<line x1="${L}" x2="${WIDTH - R}" y1="${y(p).toFixed(1)}" y2="${y(p).toFixed(1)}" stroke="${COLORS.grid}" stroke-width="${p === 90 ? 1 : 0.5}"${p === 90 ? ' stroke-dasharray="3,3"' : ''}/>` +
|
|
100
|
+
`<text x="${L - 4}" y="${(y(p) + 3).toFixed(1)}" text-anchor="end" fill="${COLORS.muted}" font-size="9">${p}%</text>`
|
|
101
|
+
).join('');
|
|
102
|
+
|
|
103
|
+
const pct = retention.retentionIndexPct;
|
|
104
|
+
const color = retention.grade === 'A' ? COLORS.good : retention.grade === 'B' ? COLORS.warn : COLORS.bad;
|
|
105
|
+
const callout = `<text x="${WIDTH - R}" y="${T - 3}" text-anchor="end" fill="${color}" font-size="10">` +
|
|
106
|
+
`${escapeXml(`${pct}% retained · saved ${fmtUsd(retention.retainedDiscountSavingsUSD)} · leaked ${fmtUsd(retention.leakedColdPrefillUSD)}`)}</text>`;
|
|
107
|
+
|
|
108
|
+
return `<svg class="cr-svg" viewBox="0 0 ${WIDTH} ${H}" width="100%" role="img" aria-label="Prefix-cache retention per turn">` +
|
|
109
|
+
grid + marks.join('') +
|
|
110
|
+
(d ? `<path d="${d}" fill="none" stroke="${color}" stroke-width="1.5"/>` : '') +
|
|
111
|
+
callout +
|
|
112
|
+
`<text x="${L}" y="${H - 4}" fill="${COLORS.muted}" font-size="9">turns 2+ (${retention.measuredTurns} measured, ${retention.bustCount} bust${retention.bustCount === 1 ? '' : 's'}, ${retention.ttlExpiredTurns} TTL-expired)</text>` +
|
|
113
|
+
`</svg>`;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
/**
|
|
117
|
+
* Panel 2: drift sparkline (thinking:output ratio per turn) + TTFT strip.
|
|
118
|
+
*/
|
|
119
|
+
export function renderDriftSparkline(drift) {
|
|
120
|
+
const turns = Array.isArray(drift?.turns) ? drift.turns : [];
|
|
121
|
+
if (!drift?.measured || turns.length === 0) {
|
|
122
|
+
return emptyPanel('Thinking drift: no reported reasoning tokens yet');
|
|
123
|
+
}
|
|
124
|
+
const { WIDTH, PAD_LEFT: L, PAD_RIGHT: R } = COST_RADAR_DIMENSIONS;
|
|
125
|
+
const H = 96;
|
|
126
|
+
const sparkTop = 14;
|
|
127
|
+
const sparkH = 44;
|
|
128
|
+
const stripTop = sparkTop + sparkH + 12;
|
|
129
|
+
const stripH = 12;
|
|
130
|
+
const innerW = WIDTH - L - R;
|
|
131
|
+
const n = turns.length;
|
|
132
|
+
const step = innerW / Math.max(1, n);
|
|
133
|
+
const maxRatio = Math.max(12, ...turns.map((t) => Number(t.driftRatio) || 0));
|
|
134
|
+
const y = (r) => sparkTop + sparkH - (Math.min(maxRatio, Math.max(0, r)) / maxRatio) * sparkH;
|
|
135
|
+
const maxTtft = Math.max(1, ...turns.map((t) => Number(t.ttftMs) || 0));
|
|
136
|
+
|
|
137
|
+
const pts = turns.map((t, i) => `${(L + i * step + step / 2).toFixed(1)},${y(Number(t.driftRatio) || 0).toFixed(1)}`);
|
|
138
|
+
const loopBands = turns.map((t, i) => (t.driftState === 'loop_suspect'
|
|
139
|
+
? `<rect x="${(L + i * step).toFixed(1)}" y="${sparkTop}" width="${step.toFixed(1)}" height="${sparkH}" fill="${COLORS.bad}" opacity="0.18"><title>Turn ${i + 1}: DET-30 loop suspect — ${fmtTokens(t.thinkingTokens)} thinking, ${t.mutatingCalls} edits</title></rect>`
|
|
140
|
+
: '')).join('');
|
|
141
|
+
const thresholdY = y(12).toFixed(1);
|
|
142
|
+
const ttftStrip = turns.map((t, i) => {
|
|
143
|
+
if (typeof t.ttftMs !== 'number') return '';
|
|
144
|
+
const intensity = Math.max(0.15, Math.min(1, t.ttftMs / maxTtft));
|
|
145
|
+
return `<rect x="${(L + i * step + 0.5).toFixed(1)}" y="${stripTop}" width="${Math.max(1, step - 1).toFixed(1)}" height="${stripH}" fill="${COLORS.accent}" opacity="${intensity.toFixed(2)}"><title>Turn ${i + 1}: TTFT ${(t.ttftMs / 1000).toFixed(1)}s</title></rect>`;
|
|
146
|
+
}).join('');
|
|
147
|
+
const last = turns[turns.length - 1];
|
|
148
|
+
const dot = `<circle cx="${(L + (n - 1) * step + step / 2).toFixed(1)}" cy="${y(Number(last.driftRatio) || 0).toFixed(1)}" r="2.5" fill="${drift.loop?.triggered ? COLORS.bad : COLORS.think}"/>`;
|
|
149
|
+
const headline = drift.loop?.triggered
|
|
150
|
+
? `DET-30 ${String(drift.loop.severity || 'warn').toUpperCase()}: ${drift.loop.consecutiveLoopTurns || 0} consecutive loop turn(s)`
|
|
151
|
+
: `last ${drift.lastDriftRatio ?? '—'}x · rolling ${drift.rollingDriftRatio ?? '—'}x · avg TTFT ${drift.avgTtftMs != null ? (drift.avgTtftMs / 1000).toFixed(1) + 's' : '—'}`;
|
|
152
|
+
|
|
153
|
+
return `<svg class="cr-svg" viewBox="0 0 ${WIDTH} ${H}" width="100%" role="img" aria-label="Thinking vs generation drift and TTFT">` +
|
|
154
|
+
loopBands +
|
|
155
|
+
`<line x1="${L}" x2="${WIDTH - R}" y1="${thresholdY}" y2="${thresholdY}" stroke="${COLORS.bad}" stroke-width="0.6" stroke-dasharray="3,3"/>` +
|
|
156
|
+
`<text x="${L - 4}" y="${(Number(thresholdY) + 3).toFixed(1)}" text-anchor="end" fill="${COLORS.muted}" font-size="9">12x</text>` +
|
|
157
|
+
`<polyline points="${pts.join(' ')}" fill="none" stroke="${COLORS.think}" stroke-width="1.3"/>` + dot +
|
|
158
|
+
`<text x="${WIDTH - R}" y="10" text-anchor="end" fill="${drift.loop?.triggered ? COLORS.bad : COLORS.fg}" font-size="10">${escapeXml(headline)}</text>` +
|
|
159
|
+
`<text x="${L - 4}" y="${stripTop + 9}" text-anchor="end" fill="${COLORS.muted}" font-size="9">TTFT</text>` +
|
|
160
|
+
ttftStrip +
|
|
161
|
+
`<text x="${L}" y="${H - 4}" fill="${COLORS.muted}" font-size="9">thinking ÷ visible output per user turn (estimates excluded)</text>` +
|
|
162
|
+
`</svg>`;
|
|
163
|
+
}
|
|
164
|
+
|
|
165
|
+
/**
|
|
166
|
+
* Panel 3: swarm / worktree topology graph.
|
|
167
|
+
*/
|
|
168
|
+
export function renderTopologyGraph(topology) {
|
|
169
|
+
const workers = Array.isArray(topology?.workers) ? topology.workers : [];
|
|
170
|
+
const worktrees = Array.isArray(topology?.worktrees) ? topology.worktrees : [];
|
|
171
|
+
const collisions = Array.isArray(topology?.scopeLocks?.collisions) ? topology.scopeLocks.collisions : [];
|
|
172
|
+
if (workers.length === 0 && worktrees.length <= 1 && collisions.length === 0) {
|
|
173
|
+
return emptyPanel('Topology: solo agent · single worktree');
|
|
174
|
+
}
|
|
175
|
+
const { WIDTH } = COST_RADAR_DIMENSIONS;
|
|
176
|
+
const rowH = 18;
|
|
177
|
+
const rows = Math.max(workers.length, worktrees.length, 1);
|
|
178
|
+
const H = 30 + rows * rowH + (collisions.length > 0 ? 18 : 0);
|
|
179
|
+
const rootX = 60;
|
|
180
|
+
const rootY = 22 + (rows * rowH) / 2;
|
|
181
|
+
const workerX = 220;
|
|
182
|
+
const wtX = 440;
|
|
183
|
+
const stateColor = { working: COLORS.good, waiting: COLORS.accent, stopped: COLORS.warn, killed: COLORS.muted };
|
|
184
|
+
|
|
185
|
+
let out = `<circle cx="${rootX}" cy="${rootY.toFixed(1)}" r="6" fill="${COLORS.fg}"/>` +
|
|
186
|
+
`<text x="${rootX}" y="${(rootY + 18).toFixed(1)}" text-anchor="middle" fill="${COLORS.fg}" font-size="10">coordinator</text>`;
|
|
187
|
+
workers.forEach((w, i) => {
|
|
188
|
+
const wy = 22 + i * rowH + rowH / 2;
|
|
189
|
+
const color = stateColor[w.state] || COLORS.muted;
|
|
190
|
+
out += `<path d="M${rootX + 6},${rootY.toFixed(1)} C${rootX + 70},${rootY.toFixed(1)} ${workerX - 70},${wy.toFixed(1)} ${workerX - 5},${wy.toFixed(1)}" fill="none" stroke="${color}" stroke-width="1" opacity="${w.state === 'killed' ? 0.35 : 0.8}"${w.state === 'waiting' ? ' stroke-dasharray="3,3"' : ''}/>` +
|
|
191
|
+
`<circle cx="${workerX}" cy="${wy.toFixed(1)}" r="4" fill="${color}"/>` +
|
|
192
|
+
`<text x="${workerX + 9}" y="${(wy + 3).toFixed(1)}" fill="${COLORS.fg}" font-size="10">${escapeXml(`${w.name} · ${w.state}${w.parked ? ' ($0)' : ''} · ${w.model || 'inherit'} · ${w.workspace || 'inherit'}`)}</text>`;
|
|
193
|
+
});
|
|
194
|
+
worktrees.forEach((t, i) => {
|
|
195
|
+
const ty = 22 + i * rowH + rowH / 2;
|
|
196
|
+
const label = `${t.isMain ? '★ ' : ''}${t.branch || (t.detached ? `detached@${t.head || ''}` : t.name)}${t.locked ? ' [locked]' : ''}${t.prunable ? ' [prunable]' : ''}`;
|
|
197
|
+
out += `<rect x="${wtX}" y="${(ty - 6).toFixed(1)}" width="10" height="10" fill="none" stroke="${COLORS.accent}"/>` +
|
|
198
|
+
`<text x="${wtX + 16}" y="${(ty + 3).toFixed(1)}" fill="${COLORS.fg}" font-size="10">${escapeXml(label)}<title>${escapeXml(t.path || '')}</title></text>`;
|
|
199
|
+
});
|
|
200
|
+
if (collisions.length > 0) {
|
|
201
|
+
const cy = H - 8;
|
|
202
|
+
out += `<text x="12" y="${cy}" fill="${COLORS.bad}" font-size="10">${escapeXml(`DET-20 overlap: ${collisions.map((c) => `${c.trajectories.join(' ↔ ')} [${c.overlappingPaths.join(', ')}]`).join('; ')}`)}</text>`;
|
|
203
|
+
}
|
|
204
|
+
out += `<text x="${workerX}" y="12" fill="${COLORS.muted}" font-size="9">workers</text>` +
|
|
205
|
+
`<text x="${wtX}" y="12" fill="${COLORS.muted}" font-size="9">git worktrees</text>`;
|
|
206
|
+
return `<svg class="cr-svg" viewBox="0 0 ${WIDTH} ${H}" width="100%" role="img" aria-label="Swarm and worktree topology">${out}</svg>`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
/**
|
|
210
|
+
* Builds the full self-contained HTML artifact.
|
|
211
|
+
*/
|
|
212
|
+
export function renderCostRadarHtml({ retention = null, drift = null, topology = null, meta = {} } = {}) {
|
|
213
|
+
const title = meta.sessionTitle ? `Cost Radar — ${meta.sessionTitle}` : 'Cost Radar';
|
|
214
|
+
const generated = meta.generatedAt || new Date().toISOString();
|
|
215
|
+
const subtitleParts = [meta.model ? `model ${meta.model}` : null, meta.edition || null, `generated ${generated}`].filter(Boolean);
|
|
216
|
+
return `<!doctype html>
|
|
217
|
+
<html lang="en"><head><meta charset="utf-8"><meta name="viewport" content="width=device-width, initial-scale=1">
|
|
218
|
+
<title>${escapeXml(title)}</title>
|
|
219
|
+
<style>
|
|
220
|
+
:root { color-scheme: dark; }
|
|
221
|
+
body { margin: 0; padding: 16px 20px; background: ${COLORS.bg}; color: ${COLORS.fg}; font: 12px/1.45 ui-monospace, SFMono-Regular, Menlo, Consolas, monospace; font-variant-numeric: tabular-nums; }
|
|
222
|
+
h1 { font-size: 14px; font-weight: 600; margin: 0 0 2px; }
|
|
223
|
+
.sub { color: ${COLORS.muted}; font-size: 11px; margin-bottom: 12px; }
|
|
224
|
+
section { margin: 0 0 14px; max-width: 680px; }
|
|
225
|
+
h2 { font-size: 11px; font-weight: 500; color: ${COLORS.muted}; text-transform: uppercase; letter-spacing: 0.06em; margin: 0 0 4px; border-bottom: 1px solid ${COLORS.grid}; padding-bottom: 2px; }
|
|
226
|
+
.cr-svg { display: block; font-family: inherit; }
|
|
227
|
+
</style></head>
|
|
228
|
+
<body>
|
|
229
|
+
<h1>${escapeXml(title)}</h1>
|
|
230
|
+
<div class="sub">${escapeXml(subtitleParts.join(' · '))}</div>
|
|
231
|
+
<section id="cr-retention"><h2>Prefix-Cache Retention</h2>${renderRetentionStepChart(retention)}</section>
|
|
232
|
+
<section id="cr-drift"><h2>Thinking vs. Generation Drift · TTFT</h2>${renderDriftSparkline(drift)}</section>
|
|
233
|
+
<section id="cr-topology"><h2>Swarm & Worktree Topology</h2>${renderTopologyGraph(topology)}</section>
|
|
234
|
+
</body></html>
|
|
235
|
+
`;
|
|
236
|
+
}
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
import fs from 'node:fs';
|
|
2
|
+
import path from 'node:path';
|
|
3
|
+
import { canonicalizePath } from './paths.mjs';
|
|
4
|
+
|
|
5
|
+
/**
|
|
6
|
+
* Prefix-Safe Offline Tool-Output Surgeon (`--prune-tools`).
|
|
7
|
+
*
|
|
8
|
+
* Pairs every `tool_use` with its corresponding `tool_result` across Antigravity steps,
|
|
9
|
+
* Claude Code (`tool_use_id` / `sourceToolAssistantUUID`), and Cursor (`toolFormerData`),
|
|
10
|
+
* while strictly pinning Turn 0 (index 0) and the newest 6 turns (`steps.length - 6 .. steps.length - 1`).
|
|
11
|
+
*
|
|
12
|
+
* Flags a tool output as deterministically stale for truncation (retaining first 300 chars + 1-line note) when:
|
|
13
|
+
* 1. `SUPERSEDED_READ`: Earlier `Read`/`view_file` call on a file path is superseded by a later `Read` or `Edit`/`structuredPatch` on the exact same canonical path.
|
|
14
|
+
* 2. `UNREFERENCED_SEARCH`: Exploratory search (`grep`, `glob`, `find`, `grep_search`, `find_by_name`) returns >1,200 chars of stdout whose file paths are never referenced in the subsequent N=5 turns.
|
|
15
|
+
* 3. `RESOLVED_TEST_STDERR`: Verbose `Bash`/`run_command` test-failure `stderr` trace is superseded by a later passing test run (`exitCode === 0`).
|
|
16
|
+
*/
|
|
17
|
+
|
|
18
|
+
const READ_TOOL_NAMES = new Set(['read_file', 'view_file', 'read', 'view_file_outline', 'view_code_item']);
|
|
19
|
+
const EDIT_TOOL_NAMES = new Set(['edit_file', 'write_file', 'write_to_file', 'replace_file_content', 'multi_replace_file_content', 'edit', 'write']);
|
|
20
|
+
const SEARCH_TOOL_NAMES = new Set(['grep', 'glob', 'find', 'grep_search', 'find_by_name', 'ripgrep']);
|
|
21
|
+
const EXEC_TOOL_NAMES = new Set(['run_command', 'bash', 'execute_command']);
|
|
22
|
+
|
|
23
|
+
function isToolResultStep(step = {}, prev = null) {
|
|
24
|
+
if (!step || !prev) return false;
|
|
25
|
+
const prevCalls = Array.isArray(prev.toolCalls)
|
|
26
|
+
? prev.toolCalls
|
|
27
|
+
: (Array.isArray(prev.tool_calls) ? prev.tool_calls : []);
|
|
28
|
+
if (prevCalls.length === 0) return false;
|
|
29
|
+
const curCalls = Array.isArray(step.toolCalls)
|
|
30
|
+
? step.toolCalls
|
|
31
|
+
: (Array.isArray(step.tool_calls) ? step.tool_calls : []);
|
|
32
|
+
if (curCalls.length > 0) return false;
|
|
33
|
+
if (prev.type === 'PLANNER_RESPONSE' && (step.type === 'GENERIC' || step.type === 'tool_result' || step.source === 'MODEL')) return true;
|
|
34
|
+
if (step.type === 'TOOL_RESULT' || step.type === 'tool_result' || step.source === 'TOOL') return true;
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
|
|
38
|
+
function extractStepToolMeta(step = {}, idx = 0, steps = []) {
|
|
39
|
+
let calls = Array.isArray(step.toolCalls)
|
|
40
|
+
? step.toolCalls
|
|
41
|
+
: (Array.isArray(step.tool_calls) ? step.tool_calls : []);
|
|
42
|
+
if (calls.length === 0 && idx > 0 && Array.isArray(steps) && steps[idx - 1]) {
|
|
43
|
+
const prev = steps[idx - 1];
|
|
44
|
+
if (isToolResultStep(step, prev)) {
|
|
45
|
+
const prevCalls = Array.isArray(prev.toolCalls)
|
|
46
|
+
? prev.toolCalls
|
|
47
|
+
: (Array.isArray(prev.tool_calls) ? prev.tool_calls : []);
|
|
48
|
+
if (prevCalls.length > 0) {
|
|
49
|
+
calls = prevCalls;
|
|
50
|
+
}
|
|
51
|
+
}
|
|
52
|
+
}
|
|
53
|
+
const firstCall = calls[0] || {};
|
|
54
|
+
const rawName = String(
|
|
55
|
+
firstCall.name ||
|
|
56
|
+
firstCall.tool ||
|
|
57
|
+
step.toolName ||
|
|
58
|
+
step.toolFormerData?.name ||
|
|
59
|
+
''
|
|
60
|
+
).toLowerCase();
|
|
61
|
+
|
|
62
|
+
const args = firstCall.args || firstCall.parameters || firstCall.Arguments || step.toolFormerData?.params || {};
|
|
63
|
+
const rawPath = String(
|
|
64
|
+
args.Path ||
|
|
65
|
+
args.path ||
|
|
66
|
+
args.TargetFile ||
|
|
67
|
+
args.AbsolutePath ||
|
|
68
|
+
step.targetPath ||
|
|
69
|
+
step.toolUseResult?.filePath ||
|
|
70
|
+
''
|
|
71
|
+
).trim();
|
|
72
|
+
|
|
73
|
+
const toolUseId = String(
|
|
74
|
+
firstCall.id ||
|
|
75
|
+
firstCall.tool_use_id ||
|
|
76
|
+
step.tool_use_id ||
|
|
77
|
+
step.sourceToolAssistantUUID ||
|
|
78
|
+
step.toolFormerData?.toolCallId ||
|
|
79
|
+
`step-${idx}`
|
|
80
|
+
);
|
|
81
|
+
|
|
82
|
+
const hasStructuredPatch = Boolean(
|
|
83
|
+
step.structuredPatch ||
|
|
84
|
+
step.toolUseResult?.structuredPatch ||
|
|
85
|
+
step.edited_text_file ||
|
|
86
|
+
step.codeBlockDiff
|
|
87
|
+
);
|
|
88
|
+
|
|
89
|
+
const content = String(
|
|
90
|
+
step.content ??
|
|
91
|
+
step.toolUseResult?.stdout ??
|
|
92
|
+
step.toolUseResult?.content ??
|
|
93
|
+
step.toolFormerData?.result ??
|
|
94
|
+
''
|
|
95
|
+
);
|
|
96
|
+
|
|
97
|
+
const isError = Boolean(
|
|
98
|
+
step.status === 'ERROR' ||
|
|
99
|
+
(typeof step.exitCode === 'number' && step.exitCode !== 0) ||
|
|
100
|
+
step.is_error === true ||
|
|
101
|
+
/Traceback \(most recent call last\)|AssertionError|FAIL |ERR_|Exit code: [1-9]/i.test(content)
|
|
102
|
+
);
|
|
103
|
+
|
|
104
|
+
const isPassExec = EXEC_TOOL_NAMES.has(rawName) && !isError && (
|
|
105
|
+
step.exitCode === 0 ||
|
|
106
|
+
step.status === 'DONE' ||
|
|
107
|
+
/\bPASS\b|0 fail|exit code 0/i.test(content)
|
|
108
|
+
);
|
|
109
|
+
|
|
110
|
+
return {
|
|
111
|
+
toolName: rawName,
|
|
112
|
+
toolUseId,
|
|
113
|
+
rawPath: rawPath || null,
|
|
114
|
+
canonPath: rawPath ? canonicalizePath(rawPath) : null,
|
|
115
|
+
hasStructuredPatch,
|
|
116
|
+
content,
|
|
117
|
+
isError,
|
|
118
|
+
isPassExec
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
function extractCandidatePathsFromSearchOutput(text = '') {
|
|
123
|
+
const matches = String(text || '').match(/[A-Za-z0-9_./\\-]+\.(?:mjs|cjs|js|ts|tsx|jsx|json|md|py|go|rs|sql|html|css)/g) || [];
|
|
124
|
+
return Array.from(new Set(matches.map(m => path.basename(m).toLowerCase())));
|
|
125
|
+
}
|
|
126
|
+
|
|
127
|
+
export function analyzeStaleToolOutputs(steps = [], options = {}) {
|
|
128
|
+
const pinnedTailCount = Number.isFinite(options.pinnedTailCount) ? Math.max(0, options.pinnedTailCount) : 6;
|
|
129
|
+
const maxRetainedChars = Number.isFinite(options.maxRetainedChars) ? Math.max(80, options.maxRetainedChars) : 300;
|
|
130
|
+
const unreferencedTurnWindow = Number.isFinite(options.unreferencedTurnWindow) ? Math.max(1, options.unreferencedTurnWindow) : 5;
|
|
131
|
+
|
|
132
|
+
const list = Array.isArray(steps) ? steps : [];
|
|
133
|
+
const metaList = list.map((s, idx) => extractStepToolMeta(s, idx, list));
|
|
134
|
+
|
|
135
|
+
// Track latest read or edit index per canonical path
|
|
136
|
+
const latestTouchByPath = new Map();
|
|
137
|
+
let latestPassExecIdx = -1;
|
|
138
|
+
|
|
139
|
+
for (let i = 0; i < metaList.length; i++) {
|
|
140
|
+
const m = metaList[i];
|
|
141
|
+
if (m.canonPath && (READ_TOOL_NAMES.has(m.toolName) || EDIT_TOOL_NAMES.has(m.toolName) || m.hasStructuredPatch)) {
|
|
142
|
+
latestTouchByPath.set(m.canonPath, i);
|
|
143
|
+
}
|
|
144
|
+
if (m.isPassExec) {
|
|
145
|
+
latestPassExecIdx = i;
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const cutoffIndex = Math.max(1, list.length - pinnedTailCount);
|
|
150
|
+
const cachedTokensWatermark = Number.isFinite(options.cachedTokens) ? options.cachedTokens : null;
|
|
151
|
+
let splitIndex = 1;
|
|
152
|
+
if (cachedTokensWatermark && cachedTokensWatermark > 0) {
|
|
153
|
+
let cumulativeTokens = 0;
|
|
154
|
+
for (let j = 0; j < list.length; j++) {
|
|
155
|
+
const s = list[j];
|
|
156
|
+
const tok = Number(
|
|
157
|
+
s.totalTokens ??
|
|
158
|
+
s.tokens ??
|
|
159
|
+
s.output_tokens ??
|
|
160
|
+
s.outputTokens ??
|
|
161
|
+
(s.content ? Math.ceil(String(s.content).length / 4) : 0)
|
|
162
|
+
);
|
|
163
|
+
cumulativeTokens += tok;
|
|
164
|
+
if (cumulativeTokens <= cachedTokensWatermark) {
|
|
165
|
+
splitIndex = j + 1;
|
|
166
|
+
} else {
|
|
167
|
+
break;
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
const startIndex = Math.max(1, splitIndex);
|
|
172
|
+
const candidates = [];
|
|
173
|
+
const prunedSteps = list.map(s => ({ ...s }));
|
|
174
|
+
let totalSavedTokens = 0;
|
|
175
|
+
|
|
176
|
+
for (let i = startIndex; i < cutoffIndex; i++) {
|
|
177
|
+
const m = metaList[i];
|
|
178
|
+
const origLen = m.content.length;
|
|
179
|
+
if (origLen <= maxRetainedChars + 60) continue;
|
|
180
|
+
|
|
181
|
+
let reason = null;
|
|
182
|
+
if (m.canonPath && READ_TOOL_NAMES.has(m.toolName)) {
|
|
183
|
+
const latestIdx = latestTouchByPath.get(m.canonPath) ?? -1;
|
|
184
|
+
if (latestIdx > i) {
|
|
185
|
+
reason = 'SUPERSEDED_READ';
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (!reason && SEARCH_TOOL_NAMES.has(m.toolName) && origLen > 1200) {
|
|
190
|
+
const searchBasenames = extractCandidatePathsFromSearchOutput(m.content);
|
|
191
|
+
let referencedLater = false;
|
|
192
|
+
const winEnd = Math.min(list.length, i + 1 + unreferencedTurnWindow);
|
|
193
|
+
for (let k = i + 1; k < winEnd; k++) {
|
|
194
|
+
const nextText = JSON.stringify(list[k] || {}).toLowerCase();
|
|
195
|
+
if (searchBasenames.some(bn => bn && nextText.includes(bn))) {
|
|
196
|
+
referencedLater = true;
|
|
197
|
+
break;
|
|
198
|
+
}
|
|
199
|
+
}
|
|
200
|
+
if (!referencedLater) {
|
|
201
|
+
reason = 'UNREFERENCED_SEARCH';
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
if (!reason && EXEC_TOOL_NAMES.has(m.toolName) && m.isError && latestPassExecIdx > i) {
|
|
206
|
+
reason = 'RESOLVED_TEST_STDERR';
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
if (reason) {
|
|
210
|
+
const headSlice = m.content.slice(0, maxRetainedChars).trimEnd();
|
|
211
|
+
const droppedChars = Math.max(0, origLen - headSlice.length);
|
|
212
|
+
const savedTok = Math.max(1, Math.floor(droppedChars / 4));
|
|
213
|
+
const note = `\n... [Tool-Output Surgeon (${reason}): truncated ${droppedChars} chars (~${savedTok} tok) at Turn #${i}]`;
|
|
214
|
+
const truncatedContent = `${headSlice}${note}`;
|
|
215
|
+
|
|
216
|
+
candidates.push({
|
|
217
|
+
stepIndex: i,
|
|
218
|
+
toolUseId: m.toolUseId,
|
|
219
|
+
toolName: m.toolName || 'tool',
|
|
220
|
+
reason,
|
|
221
|
+
targetPath: m.rawPath,
|
|
222
|
+
originalChars: origLen,
|
|
223
|
+
truncatedChars: truncatedContent.length,
|
|
224
|
+
savedTokens: savedTok,
|
|
225
|
+
truncatedContent
|
|
226
|
+
});
|
|
227
|
+
|
|
228
|
+
totalSavedTokens += savedTok;
|
|
229
|
+
prunedSteps[i] = {
|
|
230
|
+
...prunedSteps[i],
|
|
231
|
+
content: truncatedContent,
|
|
232
|
+
output_tokens: Math.ceil(truncatedContent.length / 4),
|
|
233
|
+
outputTokens: Math.ceil(truncatedContent.length / 4),
|
|
234
|
+
surgeonTruncated: true,
|
|
235
|
+
surgeonReason: reason
|
|
236
|
+
};
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
|
|
240
|
+
return {
|
|
241
|
+
candidates,
|
|
242
|
+
totalSavedTokens,
|
|
243
|
+
prunedSteps
|
|
244
|
+
};
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
export function executeToolOutputSurgery(transcriptPath, options = {}) {
|
|
248
|
+
const dryRun = Boolean(options.dryRun);
|
|
249
|
+
const uncachedTail = Boolean(options.uncachedTail);
|
|
250
|
+
const cachedTokens = Number.isFinite(options.cachedTokens)
|
|
251
|
+
? options.cachedTokens
|
|
252
|
+
: (uncachedTail ? 50000 : null);
|
|
253
|
+
const opts = { ...options, cachedTokens };
|
|
254
|
+
if (!transcriptPath || !fs.existsSync(transcriptPath)) {
|
|
255
|
+
return {
|
|
256
|
+
success: false,
|
|
257
|
+
dryRun,
|
|
258
|
+
prunedCount: 0,
|
|
259
|
+
savedTokens: 0,
|
|
260
|
+
backupPath: null,
|
|
261
|
+
candidates: [],
|
|
262
|
+
error: 'Transcript file does not exist'
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const rawText = fs.readFileSync(transcriptPath, 'utf8');
|
|
267
|
+
const lines = rawText.split(/\r?\n/).filter(Boolean);
|
|
268
|
+
const parsedSteps = lines.map((line, idx) => {
|
|
269
|
+
try {
|
|
270
|
+
return JSON.parse(line);
|
|
271
|
+
} catch {
|
|
272
|
+
return { step_index: idx, content: line };
|
|
273
|
+
}
|
|
274
|
+
});
|
|
275
|
+
|
|
276
|
+
const analysis = analyzeStaleToolOutputs(parsedSteps, opts);
|
|
277
|
+
if (dryRun || analysis.candidates.length === 0) {
|
|
278
|
+
return {
|
|
279
|
+
success: true,
|
|
280
|
+
dryRun,
|
|
281
|
+
prunedCount: analysis.candidates.length,
|
|
282
|
+
savedTokens: analysis.totalSavedTokens,
|
|
283
|
+
backupPath: null,
|
|
284
|
+
candidates: analysis.candidates
|
|
285
|
+
};
|
|
286
|
+
}
|
|
287
|
+
|
|
288
|
+
const backupSuffix = uncachedTail ? 'pre_tail_trim' : 'pre_surgeon';
|
|
289
|
+
const backupPath = `${transcriptPath}.${backupSuffix}.${Date.now()}.bak`;
|
|
290
|
+
fs.copyFileSync(transcriptPath, backupPath);
|
|
291
|
+
|
|
292
|
+
const tmpPath = `${transcriptPath}.${process.pid}.tmp`;
|
|
293
|
+
const serialized = analysis.prunedSteps.map(s => JSON.stringify(s)).join('\n') + '\n';
|
|
294
|
+
fs.writeFileSync(tmpPath, serialized, 'utf8');
|
|
295
|
+
fs.renameSync(tmpPath, transcriptPath);
|
|
296
|
+
|
|
297
|
+
return {
|
|
298
|
+
success: true,
|
|
299
|
+
dryRun: false,
|
|
300
|
+
prunedCount: analysis.candidates.length,
|
|
301
|
+
savedTokens: analysis.totalSavedTokens,
|
|
302
|
+
backupPath,
|
|
303
|
+
candidates: analysis.candidates
|
|
304
|
+
};
|
|
305
|
+
}
|