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,301 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/guards/losslessPostSanitizer.mjs
|
|
3
|
+
* Lossless `PostToolUse` Sanitizer, Critical Error-Line Recovery Engine, and
|
|
4
|
+
* Programmatic Artifact Offloader (> 4,000 tokens -> `.claude/cache/artifacts/ah_<sha256>.txt`).
|
|
5
|
+
*
|
|
6
|
+
* Strict Invariant:
|
|
7
|
+
* - NEVER modifies or offloads workspace `Read` outputs (preserving exact file lines for `Edit`).
|
|
8
|
+
* - Guarantees 100% survival of lines matching `CRITICAL_ERROR_REGEX`.
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { path, getCwd, sha256Hex, writeTextAtomic } from '../utils/runtime.mjs';
|
|
12
|
+
|
|
13
|
+
export const OFFLOAD_TOKEN_THRESHOLD = 4000; // ~16 KB (~4 chars/token)
|
|
14
|
+
export const CHARS_PER_TOKEN_ESTIMATE = 4;
|
|
15
|
+
|
|
16
|
+
export const CRITICAL_ERROR_REGEX =
|
|
17
|
+
/(Error|Exception|FAIL|error\[E\d+\]|panic:|ERR!|ERESOLVE|AssertionError|SyntaxError)/i;
|
|
18
|
+
|
|
19
|
+
const ANSI_CSI_OSC_REGEX =
|
|
20
|
+
// eslint-disable-next-line no-control-regex
|
|
21
|
+
/\x1b\[[0-9;?]*[ -/]*[@-~]|\x1b\][^\x07\x1b]*(?:\x07|\x1b\\)/g;
|
|
22
|
+
|
|
23
|
+
const DOWNLOAD_NOISE_LINE_REGEX =
|
|
24
|
+
/^\s*(?:npm\s+(?:http|verb|silly|timing|notice)\b|Progress:\s+resolved\s+\d+|Downloading\s+\S+\s+\[[=#>-]+\s*\]|\d+%\s+\[[=#>-]+\s*\]|Receiving objects:\s+\d+%|Resolving deltas:\s+\d+%)/i;
|
|
25
|
+
|
|
26
|
+
const PASSING_TEST_LINE_REGEX =
|
|
27
|
+
/^\s*(?:✔|✓|PASS\s+\S+|ok\s+\d+\s+-\s+)/;
|
|
28
|
+
|
|
29
|
+
const HTML_BOILERPLATE_BLOCK_REGEX =
|
|
30
|
+
/<(nav|footer|script|style|svg|noscript)\b[^>]*>[\s\S]*?<\/\1>/gi;
|
|
31
|
+
|
|
32
|
+
/**
|
|
33
|
+
* Checks whether a tool name is eligible for `PostToolUse` sanitization and offloading.
|
|
34
|
+
* Workspace `Read` is strictly excluded.
|
|
35
|
+
*
|
|
36
|
+
* @param {string} [toolName='']
|
|
37
|
+
* @returns {boolean}
|
|
38
|
+
*/
|
|
39
|
+
export function isToolEligibleForSanitization(toolName = '') {
|
|
40
|
+
let cleaned = String(toolName || '').trim();
|
|
41
|
+
if (!cleaned) return false;
|
|
42
|
+
const unprefixed = cleaned.replace(/^(?:default_api:|mcp__[a-zA-Z0-9_-]+__)/i, '');
|
|
43
|
+
if (/^(Read|read_file|view_file|View|Edit|edit_file|Write|write_file|write_to_file|replace_file_content|MultiEdit|NotebookEdit)$/i.test(unprefixed)) {
|
|
44
|
+
return false;
|
|
45
|
+
}
|
|
46
|
+
return /^(Bash|PowerShell|pwsh|cmd|sh|WebFetch|Grep|Glob|Task|Agent|mcp__.+)$/i.test(cleaned);
|
|
47
|
+
}
|
|
48
|
+
|
|
49
|
+
/**
|
|
50
|
+
* Estimates token count from text length (~4 chars per token).
|
|
51
|
+
* @param {string} [text='']
|
|
52
|
+
* @returns {number}
|
|
53
|
+
*/
|
|
54
|
+
export function estimateTokenCount(text = '') {
|
|
55
|
+
const str = String(text || '');
|
|
56
|
+
if (!str) return 0;
|
|
57
|
+
return Math.ceil(str.length / CHARS_PER_TOKEN_ESTIMATE);
|
|
58
|
+
}
|
|
59
|
+
|
|
60
|
+
/**
|
|
61
|
+
* Strips ANSI escape sequences and resolves `\r` carriage-return spinner overwrites.
|
|
62
|
+
* @param {string} [rawText='']
|
|
63
|
+
* @returns {string}
|
|
64
|
+
*/
|
|
65
|
+
export function stripAnsiAndSpinners(rawText = '') {
|
|
66
|
+
const withoutAnsi = String(rawText || '').replace(ANSI_CSI_OSC_REGEX, '');
|
|
67
|
+
const lines = withoutAnsi.split(/\n/);
|
|
68
|
+
const resolvedLines = lines.map((line) => {
|
|
69
|
+
const trimmedCr = line.replace(/\r$/, '');
|
|
70
|
+
if (!trimmedCr.includes('\r')) return trimmedCr;
|
|
71
|
+
// Spinner overwrite: keep last non-empty segment after \r
|
|
72
|
+
const segments = trimmedCr.split('\r').filter((seg) => seg.trim().length > 0);
|
|
73
|
+
return segments.length > 0 ? segments[segments.length - 1] : '';
|
|
74
|
+
});
|
|
75
|
+
return resolvedLines.join('\n');
|
|
76
|
+
}
|
|
77
|
+
|
|
78
|
+
/**
|
|
79
|
+
* Extracts all critical error/failure lines verbatim from ANSI-cleaned text.
|
|
80
|
+
* @param {string} [cleanText='']
|
|
81
|
+
* @returns {Array<string>}
|
|
82
|
+
*/
|
|
83
|
+
export function extractCriticalErrorLines(cleanText = '') {
|
|
84
|
+
const lines = String(cleanText || '').split(/\r?\n/);
|
|
85
|
+
return lines.filter((line) => CRITICAL_ERROR_REGEX.test(line));
|
|
86
|
+
}
|
|
87
|
+
|
|
88
|
+
/**
|
|
89
|
+
* Infers a brief schema description of structured output (JSON, CSV/table, or log lines).
|
|
90
|
+
* @param {string} text
|
|
91
|
+
* @returns {string}
|
|
92
|
+
*/
|
|
93
|
+
function inferPayloadSchema(text = '') {
|
|
94
|
+
const trimmed = String(text || '').trim();
|
|
95
|
+
if (trimmed.startsWith('{') || trimmed.startsWith('[')) {
|
|
96
|
+
try {
|
|
97
|
+
const parsed = JSON.parse(trimmed);
|
|
98
|
+
if (Array.isArray(parsed)) {
|
|
99
|
+
const firstKeys =
|
|
100
|
+
parsed[0] && typeof parsed[0] === 'object' ? Object.keys(parsed[0]).slice(0, 8).join(', ') : typeof parsed[0];
|
|
101
|
+
return `JSON Array (${parsed.length} items, keys: [${firstKeys}])`;
|
|
102
|
+
}
|
|
103
|
+
if (parsed && typeof parsed === 'object') {
|
|
104
|
+
return `JSON Object (keys: [${Object.keys(parsed).slice(0, 10).join(', ')}])`;
|
|
105
|
+
}
|
|
106
|
+
} catch (_err) {
|
|
107
|
+
return 'Structured JSON/NDJSON stream';
|
|
108
|
+
}
|
|
109
|
+
}
|
|
110
|
+
const firstLine = trimmed.split(/\r?\n/)[0] || '';
|
|
111
|
+
if (firstLine.includes('\t') || (firstLine.split(',').length >= 4 && !firstLine.includes(' '))) {
|
|
112
|
+
return `Tabular output (header: ${firstLine.slice(0, 80)})`;
|
|
113
|
+
}
|
|
114
|
+
return 'Command stdout/stderr log stream';
|
|
115
|
+
}
|
|
116
|
+
|
|
117
|
+
/**
|
|
118
|
+
* Computes a SHA-256 hex digest of a string.
|
|
119
|
+
* @param {string} content
|
|
120
|
+
* @returns {string}
|
|
121
|
+
*/
|
|
122
|
+
function computeSha256(content = '', options = {}) {
|
|
123
|
+
return sha256Hex(String(content ?? ''), options);
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
/**
|
|
127
|
+
* Sanitizes `PostToolUse` output for `Bash|PowerShell|WebFetch|mcp__.*` (and multi-file `Grep`),
|
|
128
|
+
* preserving 100% of critical error lines and offloading outputs > 4,000 tokens to
|
|
129
|
+
* `.claude/cache/artifacts/ah_<sha256>.txt`.
|
|
130
|
+
*
|
|
131
|
+
* NEVER modifies or offloads workspace `Read` outputs.
|
|
132
|
+
*
|
|
133
|
+
* @param {object} [params={}]
|
|
134
|
+
* @param {string} [params.toolName='Bash']
|
|
135
|
+
* @param {string} [params.toolOutput='']
|
|
136
|
+
* @param {number} [params.offloadThresholdTokens=4000]
|
|
137
|
+
* @param {object} [options={}]
|
|
138
|
+
*/
|
|
139
|
+
export function sanitizePostToolOutput(params = {}, options = {}) {
|
|
140
|
+
const toolName = String(params.toolName || params.tool_name || '');
|
|
141
|
+
const rawOutput = String(
|
|
142
|
+
params.toolOutput ?? params.tool_output ?? params.output ?? ''
|
|
143
|
+
);
|
|
144
|
+
const offloadThresholdTokens = Number(
|
|
145
|
+
params.offloadThresholdTokens ?? options.offloadThresholdTokens ?? OFFLOAD_TOKEN_THRESHOLD
|
|
146
|
+
);
|
|
147
|
+
|
|
148
|
+
const originalTokens = estimateTokenCount(rawOutput);
|
|
149
|
+
|
|
150
|
+
// Strict Invariant: NEVER touch workspace Read/Edit/Write outputs
|
|
151
|
+
if (!isToolEligibleForSanitization(toolName)) {
|
|
152
|
+
return {
|
|
153
|
+
toolName,
|
|
154
|
+
eligible: false,
|
|
155
|
+
sanitized: false,
|
|
156
|
+
offloaded: false,
|
|
157
|
+
artifactPath: null,
|
|
158
|
+
originalTokens,
|
|
159
|
+
finalTokens: originalTokens,
|
|
160
|
+
savedTokens: 0,
|
|
161
|
+
criticalErrorsPreserved: 0,
|
|
162
|
+
updatedToolOutput: rawOutput,
|
|
163
|
+
hookSpecificOutput: null
|
|
164
|
+
};
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
// Step 1: Strip ANSI escape sequences and spinner overwrites
|
|
168
|
+
let cleaned = stripAnsiAndSpinners(rawOutput);
|
|
169
|
+
|
|
170
|
+
// Step 2: Strip HTML nav/footer/script/style boilerplate for WebFetch
|
|
171
|
+
if (/^WebFetch$/i.test(toolName)) {
|
|
172
|
+
cleaned = cleaned.replace(HTML_BOILERPLATE_BLOCK_REGEX, '');
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
// Step 3: Extract 100% of Critical Error lines from the ANSI-cleaned text BEFORE line filtering
|
|
176
|
+
const criticalErrorLines = extractCriticalErrorLines(cleaned);
|
|
177
|
+
|
|
178
|
+
// Step 4: Filter download progress bars and passing test lines (while keeping all critical error lines)
|
|
179
|
+
const rawLines = cleaned.split(/\n/);
|
|
180
|
+
const filteredLines = [];
|
|
181
|
+
let strippedPassingTests = 0;
|
|
182
|
+
|
|
183
|
+
for (const line of rawLines) {
|
|
184
|
+
if (CRITICAL_ERROR_REGEX.test(line)) {
|
|
185
|
+
filteredLines.push(line);
|
|
186
|
+
continue;
|
|
187
|
+
}
|
|
188
|
+
if (DOWNLOAD_NOISE_LINE_REGEX.test(line)) {
|
|
189
|
+
continue;
|
|
190
|
+
}
|
|
191
|
+
if (PASSING_TEST_LINE_REGEX.test(line) && rawLines.length > 10) {
|
|
192
|
+
strippedPassingTests += 1;
|
|
193
|
+
continue;
|
|
194
|
+
}
|
|
195
|
+
filteredLines.push(line);
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
if (strippedPassingTests > 0) {
|
|
199
|
+
filteredLines.push(`[... ${strippedPassingTests} passing test lines compacted by Highbeam ...]`);
|
|
200
|
+
}
|
|
201
|
+
|
|
202
|
+
let sanitizedText = filteredLines.join('\n');
|
|
203
|
+
|
|
204
|
+
// Step 5: Guarantee 100% Critical Error-Line Recovery
|
|
205
|
+
for (const errLine of criticalErrorLines) {
|
|
206
|
+
if (!sanitizedText.includes(errLine)) {
|
|
207
|
+
sanitizedText += `\n${errLine}`;
|
|
208
|
+
}
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
const postFilterTokens = estimateTokenCount(sanitizedText);
|
|
212
|
+
|
|
213
|
+
// Step 6: Programmatic Artifact Offloading when structured/command output exceeds 4,000 tokens
|
|
214
|
+
let offloaded = false;
|
|
215
|
+
let artifactPath = null;
|
|
216
|
+
let finalOutput = sanitizedText;
|
|
217
|
+
|
|
218
|
+
if (originalTokens > offloadThresholdTokens || postFilterTokens > offloadThresholdTokens) {
|
|
219
|
+
const sha256 = computeSha256(cleaned, options);
|
|
220
|
+
const cwd = getCwd(options);
|
|
221
|
+
const relativeArtifactPath = `.claude/cache/artifacts/ah_${sha256}.txt`;
|
|
222
|
+
const candidateArtifactPath = path.join(
|
|
223
|
+
cwd,
|
|
224
|
+
'.claude',
|
|
225
|
+
'cache',
|
|
226
|
+
'artifacts',
|
|
227
|
+
`ah_${sha256}.txt`
|
|
228
|
+
);
|
|
229
|
+
|
|
230
|
+
offloaded = writeTextAtomic(candidateArtifactPath, cleaned, options);
|
|
231
|
+
|
|
232
|
+
if (offloaded) {
|
|
233
|
+
artifactPath = candidateArtifactPath;
|
|
234
|
+
const nonEmptyLines = filteredLines.filter((l) => l.trim().length > 0);
|
|
235
|
+
const sampleLines = nonEmptyLines.slice(0, 3);
|
|
236
|
+
const schemaSummary = inferPayloadSchema(cleaned);
|
|
237
|
+
|
|
238
|
+
const summaryParts = [
|
|
239
|
+
`[Highbeam Artifact Offload: ${originalTokens.toLocaleString()} tokens (${rawLines.length} lines) -> ${relativeArtifactPath}]`,
|
|
240
|
+
`Schema: ${schemaSummary}`,
|
|
241
|
+
`Full lossless output saved to: ${artifactPath}`,
|
|
242
|
+
`Sample lines (1..${sampleLines.length}):`,
|
|
243
|
+
...sampleLines.map((l, idx) => ` ${idx + 1}: ${l.slice(0, 200)}`)
|
|
244
|
+
];
|
|
245
|
+
|
|
246
|
+
if (criticalErrorLines.length > 0) {
|
|
247
|
+
summaryParts.push(
|
|
248
|
+
`Critical Error / Failure Lines Preserved Verbatim (${criticalErrorLines.length}):`
|
|
249
|
+
);
|
|
250
|
+
for (const errLine of criticalErrorLines) {
|
|
251
|
+
summaryParts.push(` ${errLine}`);
|
|
252
|
+
}
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
finalOutput = summaryParts.join('\n');
|
|
256
|
+
} else {
|
|
257
|
+
// ISS-034: Never truncate to a broken pointer stub if offload write fails! Preserve full ANSI-cleaned output.
|
|
258
|
+
artifactPath = null;
|
|
259
|
+
finalOutput = cleaned;
|
|
260
|
+
}
|
|
261
|
+
}
|
|
262
|
+
|
|
263
|
+
const finalTokens = estimateTokenCount(finalOutput);
|
|
264
|
+
const savedTokens = Math.max(0, originalTokens - finalTokens);
|
|
265
|
+
const wasModified = finalOutput !== rawOutput;
|
|
266
|
+
const isMcpTool = /^mcp__/i.test(toolName);
|
|
267
|
+
|
|
268
|
+
return {
|
|
269
|
+
toolName,
|
|
270
|
+
eligible: true,
|
|
271
|
+
sanitized: wasModified,
|
|
272
|
+
offloaded,
|
|
273
|
+
artifactPath,
|
|
274
|
+
originalTokens,
|
|
275
|
+
finalTokens,
|
|
276
|
+
savedTokens,
|
|
277
|
+
criticalErrorsPreserved: criticalErrorLines.length,
|
|
278
|
+
updatedToolOutput: finalOutput,
|
|
279
|
+
hookSpecificOutput: wasModified
|
|
280
|
+
? isMcpTool
|
|
281
|
+
? {
|
|
282
|
+
hookEventName: 'PostToolUse',
|
|
283
|
+
updatedMCPToolOutput: finalOutput
|
|
284
|
+
}
|
|
285
|
+
: {
|
|
286
|
+
hookEventName: 'PostToolUse',
|
|
287
|
+
additionalContext: finalOutput
|
|
288
|
+
}
|
|
289
|
+
: null
|
|
290
|
+
};
|
|
291
|
+
}
|
|
292
|
+
|
|
293
|
+
export default {
|
|
294
|
+
OFFLOAD_TOKEN_THRESHOLD,
|
|
295
|
+
CRITICAL_ERROR_REGEX,
|
|
296
|
+
isToolEligibleForSanitization,
|
|
297
|
+
estimateTokenCount,
|
|
298
|
+
stripAnsiAndSpinners,
|
|
299
|
+
extractCriticalErrorLines,
|
|
300
|
+
sanitizePostToolOutput
|
|
301
|
+
};
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/index.js
|
|
3
|
+
* Highbeam v4.0 Isomorphic Mod Core (`@ctxtop/core-isomorphic`).
|
|
4
|
+
*
|
|
5
|
+
* Pure JS / ESM with strictly 0 node:* imports, 0 dynamic imports, 0 CommonJS require.
|
|
6
|
+
* Adheres to Claude Mod Laws 1–5.
|
|
7
|
+
*/
|
|
8
|
+
|
|
9
|
+
export * from './ustf/index.mjs';
|
|
10
|
+
export * from './catalog/index.mjs';
|
|
11
|
+
export * from './control/index.mjs';
|
|
12
|
+
export * from './economics/index.mjs';
|
|
13
|
+
export * from './diagnostics/index.mjs';
|
|
14
|
+
export * from './utils/runtime.mjs';
|
|
15
|
+
export * from './telemetry/telemetryBridge.mjs';
|
|
16
|
+
export * from './config/horizonConfig.mjs';
|
|
17
|
+
export * from './config/catalogLoader.mjs';
|
|
18
|
+
export * from './coach/cacheGravityRouter.mjs';
|
|
19
|
+
export * from './coach/ttlWatchdog.mjs';
|
|
20
|
+
export * from './coach/stateBatonHydrator.mjs';
|
|
21
|
+
export * from './coach/savedQuotaLedger.mjs';
|
|
22
|
+
export * from './guards/circuitBreakers.mjs';
|
|
23
|
+
export * from './ui/modViews.mjs';
|
|
24
|
+
export * from './ui/horizonGrid.mjs';
|
|
25
|
+
export * from './ui/costRadarSvg.mjs';
|
|
26
|
+
export * from './ui/horizonPanelHtml.mjs';
|
|
@@ -0,0 +1,187 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/telemetry/otelExporter.mjs
|
|
3
|
+
* Zero-socket local OpenTelemetry metric formatter and sink for Claude Code Highbeam.
|
|
4
|
+
* Maps `claude_code.token.usage`, `claude_code.cost.usage`, and `vcs.*` attributes when
|
|
5
|
+
* `CLAUDE_CODE_ENABLE_TELEMETRY=1` is set.
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import { path, getCwd, appendJsonlSafe } from '../utils/runtime.mjs';
|
|
9
|
+
|
|
10
|
+
/**
|
|
11
|
+
* Checks whether OpenTelemetry export is enabled via environment or explicit option.
|
|
12
|
+
* @param {object} [options={}]
|
|
13
|
+
* @returns {boolean}
|
|
14
|
+
*/
|
|
15
|
+
export function isOtelEnabled(options = {}) {
|
|
16
|
+
if (typeof options.enabled === 'boolean') {
|
|
17
|
+
return options.enabled;
|
|
18
|
+
}
|
|
19
|
+
const envVal = String(globalThis.process?.env?.CLAUDE_CODE_ENABLE_TELEMETRY || '').trim();
|
|
20
|
+
return envVal === '1' || envVal.toLowerCase() === 'true';
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
/**
|
|
24
|
+
* Strips embedded basic-auth/PAT credentials (`https://user:ghp_secret@github.com/...`)
|
|
25
|
+
* and query/fragment tokens before writing `vcs.repository.url.full` (`ISS-030`).
|
|
26
|
+
*
|
|
27
|
+
* @param {string} [rawUrl='']
|
|
28
|
+
* @returns {string}
|
|
29
|
+
*/
|
|
30
|
+
export function sanitizeRepositoryUrl(rawUrl = '') {
|
|
31
|
+
const input = String(rawUrl || '').trim();
|
|
32
|
+
if (!input) return '';
|
|
33
|
+
|
|
34
|
+
const withoutQueryOrHash = input.split(/[?#]/)[0];
|
|
35
|
+
|
|
36
|
+
if (/^[a-zA-Z][a-zA-Z0-9+.-]*:\/\//.test(withoutQueryOrHash)) {
|
|
37
|
+
return withoutQueryOrHash.replace(/^([a-zA-Z][a-zA-Z0-9+.-]*:\/\/)[^/@]+@/, '$1');
|
|
38
|
+
}
|
|
39
|
+
|
|
40
|
+
if (/^[^/:@]+:[^/@]+@[^/]+:/.test(withoutQueryOrHash)) {
|
|
41
|
+
return withoutQueryOrHash.replace(/^([^/:@]+):[^/@]+@/, '$1@');
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
return withoutQueryOrHash;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
/**
|
|
48
|
+
* Formats normalized turn/session telemetry into OpenTelemetry data points.
|
|
49
|
+
* @param {object} telemetryState
|
|
50
|
+
* @param {object} [vcsMetadata={}]
|
|
51
|
+
* @returns {Array<object>}
|
|
52
|
+
*/
|
|
53
|
+
export function buildOtelMetricRecords(telemetryState = {}, vcsMetadata = {}) {
|
|
54
|
+
const timestamp = telemetryState.lastUpdatedAt || Date.now();
|
|
55
|
+
const baseAttributes = {
|
|
56
|
+
'session.id': String(telemetryState.sessionId || 'default'),
|
|
57
|
+
model: String(telemetryState.modelId || 'claude-sonnet-5-5'),
|
|
58
|
+
'agent.id': telemetryState.lastAgentId ? String(telemetryState.lastAgentId) : 'main',
|
|
59
|
+
'vcs.repository.url.full': sanitizeRepositoryUrl(
|
|
60
|
+
vcsMetadata.repositoryUrl || telemetryState.vcs?.repositoryUrl || ''
|
|
61
|
+
),
|
|
62
|
+
'vcs.ref.head.name': String(vcsMetadata.branch || telemetryState.vcs?.branch || ''),
|
|
63
|
+
'vcs.ref.head.revision': String(vcsMetadata.revision || telemetryState.vcs?.revision || '')
|
|
64
|
+
};
|
|
65
|
+
|
|
66
|
+
const latestTurn = telemetryState.lastTurn || {};
|
|
67
|
+
const tokens = latestTurn.tokens || {
|
|
68
|
+
uncachedInput: telemetryState.uncachedInputTokens || 0,
|
|
69
|
+
output: telemetryState.outputTokens || 0,
|
|
70
|
+
cacheRead: telemetryState.cacheReadTokens || 0,
|
|
71
|
+
totalCacheWrite: telemetryState.cacheWriteTokens || 0
|
|
72
|
+
};
|
|
73
|
+
const costs = latestTurn.costsUSD || {
|
|
74
|
+
totalActualSpendUSD: telemetryState.totalActualSpendUSD || 0,
|
|
75
|
+
netCacheSavingsUSD: telemetryState.netCacheSavingsUSD || 0
|
|
76
|
+
};
|
|
77
|
+
|
|
78
|
+
const tokenTypes = [
|
|
79
|
+
{ type: 'input', value: Number(tokens.uncachedInput || 0) },
|
|
80
|
+
{ type: 'output', value: Number((tokens.output || 0) + (tokens.thinking || 0)) },
|
|
81
|
+
{ type: 'cacheRead', value: Number(tokens.cacheRead || 0) },
|
|
82
|
+
{ type: 'cacheCreation', value: Number(tokens.totalCacheWrite || 0) }
|
|
83
|
+
];
|
|
84
|
+
|
|
85
|
+
const records = [];
|
|
86
|
+
for (const entry of tokenTypes) {
|
|
87
|
+
records.push({
|
|
88
|
+
metricName: 'claude_code.token.usage',
|
|
89
|
+
timestamp,
|
|
90
|
+
value: entry.value,
|
|
91
|
+
unit: 'tokens',
|
|
92
|
+
attributes: {
|
|
93
|
+
...baseAttributes,
|
|
94
|
+
type: entry.type
|
|
95
|
+
}
|
|
96
|
+
});
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
records.push({
|
|
100
|
+
metricName: 'claude_code.cost.usage',
|
|
101
|
+
timestamp,
|
|
102
|
+
value: Number(costs.totalActualSpendUSD || 0),
|
|
103
|
+
unit: 'USD',
|
|
104
|
+
attributes: {
|
|
105
|
+
...baseAttributes,
|
|
106
|
+
cache_savings_usd: Number(costs.netCacheSavingsUSD || 0),
|
|
107
|
+
negative_cache_roi: Boolean(telemetryState.cacheRoi?.negativeCacheRoi)
|
|
108
|
+
}
|
|
109
|
+
});
|
|
110
|
+
|
|
111
|
+
if (
|
|
112
|
+
telemetryState.savedQuotaUSD !== undefined ||
|
|
113
|
+
telemetryState.workspace30dSavedUSD !== undefined ||
|
|
114
|
+
telemetryState.interventionCount !== undefined ||
|
|
115
|
+
telemetryState.breakerTrips !== undefined ||
|
|
116
|
+
telemetryState.includeHorizonMetrics
|
|
117
|
+
) {
|
|
118
|
+
records.push({
|
|
119
|
+
metricName: 'attention_horizon.saved_quota.usd',
|
|
120
|
+
timestamp,
|
|
121
|
+
value: Number(
|
|
122
|
+
telemetryState.savedQuotaUSD ??
|
|
123
|
+
telemetryState.workspace30dSavedUSD ??
|
|
124
|
+
costs.netCacheSavingsUSD ??
|
|
125
|
+
0
|
|
126
|
+
),
|
|
127
|
+
unit: 'USD',
|
|
128
|
+
attributes: {
|
|
129
|
+
...baseAttributes
|
|
130
|
+
}
|
|
131
|
+
});
|
|
132
|
+
|
|
133
|
+
records.push({
|
|
134
|
+
metricName: 'attention_horizon.intervention.count',
|
|
135
|
+
timestamp,
|
|
136
|
+
value: Number(telemetryState.interventionCount ?? telemetryState.breakerTrips ?? 0),
|
|
137
|
+
unit: 'count',
|
|
138
|
+
attributes: {
|
|
139
|
+
...baseAttributes
|
|
140
|
+
}
|
|
141
|
+
});
|
|
142
|
+
}
|
|
143
|
+
|
|
144
|
+
return records;
|
|
145
|
+
}
|
|
146
|
+
|
|
147
|
+
/**
|
|
148
|
+
* Exports OpenTelemetry metric records to a local sink or `.claude/cache/otel_metrics.jsonl`
|
|
149
|
+
* when `CLAUDE_CODE_ENABLE_TELEMETRY=1`. Never opens outbound network sockets.
|
|
150
|
+
*
|
|
151
|
+
* @param {object} telemetryState
|
|
152
|
+
* @param {object} [options={}]
|
|
153
|
+
* @returns {{ exported: boolean, recordCount: number, records: Array<object> }}
|
|
154
|
+
*/
|
|
155
|
+
export function exportOtelTelemetry(telemetryState = {}, options = {}) {
|
|
156
|
+
if (!isOtelEnabled(options)) {
|
|
157
|
+
return { exported: false, recordCount: 0, records: [] };
|
|
158
|
+
}
|
|
159
|
+
|
|
160
|
+
const records = buildOtelMetricRecords(telemetryState, options.vcs || {});
|
|
161
|
+
|
|
162
|
+
if (typeof options.sink === 'function') {
|
|
163
|
+
options.sink(records);
|
|
164
|
+
return { exported: true, recordCount: records.length, records };
|
|
165
|
+
}
|
|
166
|
+
|
|
167
|
+
const cwd = options.cwd || getCwd(options);
|
|
168
|
+
if (cwd) {
|
|
169
|
+
const targetPath = options.otelFilePath || path.join(cwd, '.claude', 'cache', 'otel_metrics.jsonl');
|
|
170
|
+
let anyWritten = false;
|
|
171
|
+
for (const record of records) {
|
|
172
|
+
if (appendJsonlSafe(targetPath, record, options)) {
|
|
173
|
+
anyWritten = true;
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return { exported: anyWritten, recordCount: records.length, records };
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
return { exported: false, recordCount: records.length, records };
|
|
180
|
+
}
|
|
181
|
+
|
|
182
|
+
export default {
|
|
183
|
+
isOtelEnabled,
|
|
184
|
+
sanitizeRepositoryUrl,
|
|
185
|
+
buildOtelMetricRecords,
|
|
186
|
+
exportOtelTelemetry
|
|
187
|
+
};
|