ctxtop 4.0.0 → 4.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +1 -1
- package/.claude-plugin/plugin.json +1 -1
- package/CHECKSUMS.sha256 +59 -42
- package/README.md +351 -330
- package/bin/ah-statusline.mjs +30 -0
- package/bin/ctxtop.mjs +330 -5
- package/config/default_flightcheck.json +19 -0
- package/config/modelCatalog.json +165 -0
- package/hooks/handlers/compact-lifecycle.mjs +323 -8
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +56 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +117 -16
- package/hooks/handlers/pre-model-switch.mjs +823 -24
- package/hooks/handlers/pre-tool-use.mjs +271 -4
- package/hooks/handlers/stop-gate.mjs +297 -11
- package/hooks/handlers/user-prompt-submit.mjs +224 -0
- package/hooks/hooks.json +50 -0
- package/hooks/post_tool_use.mjs +8 -0
- package/hooks/register.js +48 -9
- package/hooks/session_start.mjs +11 -1
- package/hooks/stop.mjs +11 -1
- package/package.json +11 -4
- package/packages/antigravity/package.json +1 -1
- package/packages/claude-code/package.json +1 -1
- package/packages/core/package.json +1 -1
- package/packages/engine-node/package.json +1 -1
- package/packages/mcp/package.json +1 -1
- package/packages/mcp/src/server.mjs +1 -1
- package/packages/pro/package.json +1 -1
- package/plugin.json +1 -1
- package/sidecars/horizon-daemon/server.mjs +38 -2
- package/skills/handoff/SKILL.md +8 -0
- package/src/adapters/antigravity/index.mjs +31 -1
- package/src/adapters/claude-code/index.mjs +40 -1
- package/src/cli/horizon_hud.mjs +254 -52
- package/src/config/modelCatalog.json +84 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/constants.mjs +191 -4
- package/src/core/detectors_det01_to_16.mjs +54 -5
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/layer5_hygiene.mjs +118 -0
- package/src/core/parser.mjs +2 -1
- package/src/core/paths.mjs +3 -2
- package/src/core/rsl_clash_auditor.mjs +423 -0
- package/src/core/rsl_distiller.mjs +372 -0
- package/src/core/rsl_ledger.mjs +969 -0
- package/src/core/rsl_triage.mjs +909 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/task_quota_router.mjs +1 -1
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
- package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
- package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
- package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
- package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
- package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
- package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
- package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +1 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
- package/src/core-isomorphic/ui/modViews.mjs +35 -9
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +95 -3
- package/src/engine-node/db/probe.mjs +234 -2
- package/src/engine-node/index.mjs +3 -0
- package/src/engine-node/sensors/blindspots.mjs +13 -6
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/post_invocation.mjs +196 -4
- package/src/hooks/pre_invocation.mjs +732 -22
- package/src/hooks/session_start.mjs +39 -1
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/horizon_panel.html +1325 -317
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/coach/resumeToolsetAuditor.mjs
|
|
3
|
+
* Session-resume MCP / tool-set change auditor (`Item 6`).
|
|
4
|
+
*
|
|
5
|
+
* Evidence (`t6_layers.csv` arm `CC-T`):
|
|
6
|
+
* Resuming a warm session with a changed `--mcp-config` / tool definition list invalidated
|
|
7
|
+
* the entire KV prefix (`0` cache read tokens on turn 6).
|
|
8
|
+
*
|
|
9
|
+
* Hook visibility on Claude Code `2.1.325` (`$0` verified):
|
|
10
|
+
* `SessionStart:resume` stdin includes `session_id`, `transcript_path`, `cwd`, `source`,
|
|
11
|
+
* `seconds_since_last_response`, `context_tokens`, `prompt_cache_likely_expired`, and
|
|
12
|
+
* `estimated_cache_write_usd` — it does NOT pass `tools` or `mcp_servers` directly, and
|
|
13
|
+
* `deferred_tools_delta` is appended to `.jsonl` after `SessionStart` during `system/init`.
|
|
14
|
+
* Therefore this auditor hashes MCP & tool configuration from `.mcp.json`, `.claude/settings*.json`,
|
|
15
|
+
* `~/.claude.json`, explicit CLI `--mcp-config`/`--tools` flags if supplied, and optional host
|
|
16
|
+
* `event.tools`/`event.mcp_servers` arrays (using pure runtime I/O adapters per Mod Law 4).
|
|
17
|
+
*/
|
|
18
|
+
|
|
19
|
+
import {
|
|
20
|
+
basenamePath,
|
|
21
|
+
fileExists,
|
|
22
|
+
getCwd,
|
|
23
|
+
getHomeDir,
|
|
24
|
+
joinPath,
|
|
25
|
+
readJsonSafe,
|
|
26
|
+
readTextSafe,
|
|
27
|
+
resolvePath,
|
|
28
|
+
sha256Hex
|
|
29
|
+
} from '../utils/runtime.mjs';
|
|
30
|
+
import {
|
|
31
|
+
isKnownCatalogModel,
|
|
32
|
+
normalizeModelId,
|
|
33
|
+
resolveEffectiveRates
|
|
34
|
+
} from '../config/catalogLoader.mjs';
|
|
35
|
+
|
|
36
|
+
function normalizeServerEntry(entry) {
|
|
37
|
+
if (!entry || typeof entry !== 'object') return null;
|
|
38
|
+
const envKeys =
|
|
39
|
+
entry.env && typeof entry.env === 'object' ? Object.keys(entry.env).sort() : [];
|
|
40
|
+
return {
|
|
41
|
+
type: String(entry.type || (entry.url ? 'http' : 'stdio')),
|
|
42
|
+
command: entry.command ? String(entry.command) : null,
|
|
43
|
+
args: Array.isArray(entry.args) ? entry.args.map(String) : [],
|
|
44
|
+
url: entry.url ? String(entry.url) : null,
|
|
45
|
+
envKeys,
|
|
46
|
+
disabled: Boolean(entry.disabled)
|
|
47
|
+
};
|
|
48
|
+
}
|
|
49
|
+
|
|
50
|
+
function mergeMcpServers(target, sourceObj) {
|
|
51
|
+
if (!sourceObj || typeof sourceObj !== 'object' || Array.isArray(sourceObj)) return;
|
|
52
|
+
for (const [name, cfg] of Object.entries(sourceObj)) {
|
|
53
|
+
const cleanName = String(name || '').trim();
|
|
54
|
+
if (!cleanName) continue;
|
|
55
|
+
const normalized = normalizeServerEntry(cfg);
|
|
56
|
+
if (normalized) {
|
|
57
|
+
target[cleanName] = normalized;
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
}
|
|
61
|
+
|
|
62
|
+
function parseCliMcpFlags(cliArgs = []) {
|
|
63
|
+
const args = Array.isArray(cliArgs) ? cliArgs.map(String) : [];
|
|
64
|
+
const mcpConfigs = [];
|
|
65
|
+
const toolFlags = [];
|
|
66
|
+
for (let i = 0; i < args.length; i += 1) {
|
|
67
|
+
const tok = args[i];
|
|
68
|
+
if (tok === '--mcp-config' && i + 1 < args.length) {
|
|
69
|
+
mcpConfigs.push(args[i + 1]);
|
|
70
|
+
i += 1;
|
|
71
|
+
} else if (tok.startsWith('--mcp-config=')) {
|
|
72
|
+
mcpConfigs.push(tok.slice('--mcp-config='.length));
|
|
73
|
+
} else if (
|
|
74
|
+
(tok === '--tools' || tok === '--allowedTools' || tok === '--disallowedTools') &&
|
|
75
|
+
i + 1 < args.length
|
|
76
|
+
) {
|
|
77
|
+
toolFlags.push(`${tok}:${args[i + 1]}`);
|
|
78
|
+
i += 1;
|
|
79
|
+
} else if (
|
|
80
|
+
tok.startsWith('--tools=') ||
|
|
81
|
+
tok.startsWith('--allowedTools=') ||
|
|
82
|
+
tok.startsWith('--disallowedTools=')
|
|
83
|
+
) {
|
|
84
|
+
toolFlags.push(tok);
|
|
85
|
+
}
|
|
86
|
+
}
|
|
87
|
+
return { mcpConfigs, toolFlags: toolFlags.sort() };
|
|
88
|
+
}
|
|
89
|
+
|
|
90
|
+
function tryReadParentProcCmdline(options = {}) {
|
|
91
|
+
try {
|
|
92
|
+
const proc = globalThis.process;
|
|
93
|
+
if (proc?.platform === 'linux' && proc?.ppid) {
|
|
94
|
+
const cmdlinePath = `/proc/${proc.ppid}/cmdline`;
|
|
95
|
+
if (fileExists(cmdlinePath, options)) {
|
|
96
|
+
const raw = readTextSafe(cmdlinePath, '', options);
|
|
97
|
+
if (typeof raw === 'string' && raw.length > 0) {
|
|
98
|
+
return raw.split('\0').filter(Boolean);
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
}
|
|
102
|
+
} catch {
|
|
103
|
+
// Fail-open; zero subprocess spawning in hot hook path
|
|
104
|
+
}
|
|
105
|
+
return null;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
/**
|
|
109
|
+
* Computes a deterministic SHA-256 hash of observable active MCP server & tool configuration.
|
|
110
|
+
* Strictly read-only, excludes secret env values, and never throws on malformed files.
|
|
111
|
+
*
|
|
112
|
+
* @param {object} [event={}]
|
|
113
|
+
* @param {object} [options={}]
|
|
114
|
+
* @returns {{ hash: string, serverNames: string[], toolCount: number, toolNames: string[], cliFlags: string[], sourcesInspected: string[], recordedAt: string }}
|
|
115
|
+
*/
|
|
116
|
+
export function computeActiveToolsetHash(event = {}, options = {}) {
|
|
117
|
+
const cwd = event.cwd || getCwd(options);
|
|
118
|
+
const homeDir = options.homeDir || event.homeDir || getHomeDir(options);
|
|
119
|
+
const ioOpts = { ...options, cwd, homeDir };
|
|
120
|
+
const mcpServers = {};
|
|
121
|
+
const toolSet = new Set();
|
|
122
|
+
const sourcesInspected = [];
|
|
123
|
+
|
|
124
|
+
// 1. Optional host-provided arrays (in case host or future CLI includes them)
|
|
125
|
+
if (Array.isArray(event.tools)) {
|
|
126
|
+
sourcesInspected.push('event.tools');
|
|
127
|
+
for (const t of event.tools) {
|
|
128
|
+
const name = typeof t === 'string' ? t : t?.name || t?.id;
|
|
129
|
+
if (name) toolSet.add(String(name));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
if (event.mcp_servers && typeof event.mcp_servers === 'object') {
|
|
133
|
+
sourcesInspected.push('event.mcp_servers');
|
|
134
|
+
if (Array.isArray(event.mcp_servers)) {
|
|
135
|
+
for (const s of event.mcp_servers) {
|
|
136
|
+
const sName = typeof s === 'string' ? s : s?.name;
|
|
137
|
+
if (sName) {
|
|
138
|
+
mcpServers[String(sName)] = normalizeServerEntry(
|
|
139
|
+
typeof s === 'object' ? s : { type: 'configured' }
|
|
140
|
+
);
|
|
141
|
+
}
|
|
142
|
+
}
|
|
143
|
+
} else {
|
|
144
|
+
mergeMcpServers(mcpServers, event.mcp_servers);
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
if (event.mcpServers && typeof event.mcpServers === 'object') {
|
|
148
|
+
sourcesInspected.push('event.mcpServers');
|
|
149
|
+
mergeMcpServers(mcpServers, event.mcpServers);
|
|
150
|
+
}
|
|
151
|
+
|
|
152
|
+
// 2. ~/.claude.json user + workspace project MCP config
|
|
153
|
+
if (options.includeUserClaudeJson !== false && homeDir) {
|
|
154
|
+
const userClaudePath = joinPath(homeDir, '.claude.json');
|
|
155
|
+
const userClaude = readJsonSafe(userClaudePath, null, ioOpts);
|
|
156
|
+
if (userClaude && typeof userClaude === 'object') {
|
|
157
|
+
sourcesInspected.push('home:.claude.json');
|
|
158
|
+
mergeMcpServers(mcpServers, userClaude.mcpServers);
|
|
159
|
+
if (cwd && userClaude.projects && typeof userClaude.projects === 'object') {
|
|
160
|
+
const normCwd = resolvePath(cwd).toLowerCase();
|
|
161
|
+
for (const [projPath, projCfg] of Object.entries(userClaude.projects)) {
|
|
162
|
+
if (
|
|
163
|
+
resolvePath(projPath).toLowerCase() === normCwd &&
|
|
164
|
+
projCfg &&
|
|
165
|
+
typeof projCfg === 'object'
|
|
166
|
+
) {
|
|
167
|
+
mergeMcpServers(mcpServers, projCfg.mcpServers);
|
|
168
|
+
}
|
|
169
|
+
}
|
|
170
|
+
}
|
|
171
|
+
}
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
// 3. Project .mcp.json and .claude/settings*.json
|
|
175
|
+
const projectFiles = [
|
|
176
|
+
{ rel: '.mcp.json', label: 'project:.mcp.json' },
|
|
177
|
+
{ rel: '.claude/settings.json', label: 'project:.claude/settings.json' },
|
|
178
|
+
{ rel: '.claude/settings.local.json', label: 'project:.claude/settings.local.json' }
|
|
179
|
+
];
|
|
180
|
+
for (const pf of projectFiles) {
|
|
181
|
+
const fullPath = cwd ? joinPath(cwd, pf.rel) : null;
|
|
182
|
+
const parsed = fullPath ? readJsonSafe(fullPath, null, ioOpts) : null;
|
|
183
|
+
if (parsed && typeof parsed === 'object') {
|
|
184
|
+
sourcesInspected.push(pf.label);
|
|
185
|
+
mergeMcpServers(mcpServers, parsed.mcpServers);
|
|
186
|
+
if (Array.isArray(parsed.tools)) {
|
|
187
|
+
for (const t of parsed.tools) {
|
|
188
|
+
if (typeof t === 'string' && t.trim()) toolSet.add(t.trim());
|
|
189
|
+
}
|
|
190
|
+
}
|
|
191
|
+
if (Array.isArray(parsed.enabledMcpjsonServers)) {
|
|
192
|
+
for (const s of parsed.enabledMcpjsonServers) {
|
|
193
|
+
toolSet.add(`mcp_enabled:${String(s)}`);
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
if (Array.isArray(parsed.disabledMcpjsonServers)) {
|
|
197
|
+
for (const s of parsed.disabledMcpjsonServers) {
|
|
198
|
+
toolSet.add(`mcp_disabled:${String(s)}`);
|
|
199
|
+
}
|
|
200
|
+
}
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
// 4. Explicit CLI args or readable parent cmdline (--mcp-config / --tools / --allowedTools)
|
|
205
|
+
const rawCliArgs =
|
|
206
|
+
options.cliArgs ?? event.cliArgs ?? event.cli_args ?? tryReadParentProcCmdline(ioOpts) ?? [];
|
|
207
|
+
const { mcpConfigs, toolFlags } = parseCliMcpFlags(rawCliArgs);
|
|
208
|
+
for (const cfgArg of mcpConfigs) {
|
|
209
|
+
const resolved = cwd ? resolvePath(cwd, cfgArg) : resolvePath(cfgArg);
|
|
210
|
+
const parsedCfg = readJsonSafe(resolved, null, ioOpts);
|
|
211
|
+
if (parsedCfg && typeof parsedCfg === 'object') {
|
|
212
|
+
sourcesInspected.push(`cli:--mcp-config(${basenamePath(resolved)})`);
|
|
213
|
+
mergeMcpServers(mcpServers, parsedCfg.mcpServers || parsedCfg);
|
|
214
|
+
} else {
|
|
215
|
+
toolFlags.push(`mcp-config:${basenamePath(cfgArg)}`);
|
|
216
|
+
}
|
|
217
|
+
}
|
|
218
|
+
|
|
219
|
+
const orderedServers = {};
|
|
220
|
+
for (const name of Object.keys(mcpServers).sort()) {
|
|
221
|
+
orderedServers[name] = mcpServers[name];
|
|
222
|
+
}
|
|
223
|
+
const toolNames = Array.from(toolSet).sort();
|
|
224
|
+
const payload = {
|
|
225
|
+
mcpServers: orderedServers,
|
|
226
|
+
tools: toolNames,
|
|
227
|
+
cliFlags: toolFlags
|
|
228
|
+
};
|
|
229
|
+
|
|
230
|
+
const hash = sha256Hex(JSON.stringify(payload), options);
|
|
231
|
+
|
|
232
|
+
return {
|
|
233
|
+
hash,
|
|
234
|
+
serverNames: Object.keys(orderedServers),
|
|
235
|
+
toolNames,
|
|
236
|
+
toolCount: toolNames.length,
|
|
237
|
+
cliFlags: toolFlags,
|
|
238
|
+
sourcesInspected,
|
|
239
|
+
recordedAt: new Date().toISOString()
|
|
240
|
+
};
|
|
241
|
+
}
|
|
242
|
+
|
|
243
|
+
/**
|
|
244
|
+
* Evaluates whether a changed tool-set / MCP config on `SessionStart:resume` warrants a one-line
|
|
245
|
+
* cache-rewrite advisory (`Item 6`, citing `t6_layers.csv` arm `CC-T`).
|
|
246
|
+
*
|
|
247
|
+
* @param {object} [params={}]
|
|
248
|
+
* @param {object} [options={}]
|
|
249
|
+
* @returns {object}
|
|
250
|
+
*/
|
|
251
|
+
export function evaluateResumeToolsetChange(params = {}, options = {}) {
|
|
252
|
+
const prev = params.previousHashRecord || null;
|
|
253
|
+
const curr = params.currentHashRecord || null;
|
|
254
|
+
const contextTokens = Math.max(0, Number(params.contextTokens ?? 0));
|
|
255
|
+
const minTokens = Math.max(0, Number(params.minContextTokens ?? 10_000));
|
|
256
|
+
const cacheExpired = Boolean(params.cacheExpired);
|
|
257
|
+
const ttlTier = params.cacheTtlTier === '1h' ? '1h' : '5m';
|
|
258
|
+
const rawModel = params.modelId || 'claude-sonnet-5-5';
|
|
259
|
+
|
|
260
|
+
if (!prev?.hash || !curr?.hash) {
|
|
261
|
+
return { changed: false, shouldWarn: false, reason: 'no_baseline', advisory: null };
|
|
262
|
+
}
|
|
263
|
+
if (prev.hash === curr.hash) {
|
|
264
|
+
return { changed: false, shouldWarn: false, reason: 'unchanged', advisory: null };
|
|
265
|
+
}
|
|
266
|
+
if (cacheExpired) {
|
|
267
|
+
return { changed: true, shouldWarn: false, reason: 'cache_already_expired', advisory: null };
|
|
268
|
+
}
|
|
269
|
+
if (contextTokens < minTokens) {
|
|
270
|
+
return { changed: true, shouldWarn: false, reason: 'small_or_cold_context', advisory: null };
|
|
271
|
+
}
|
|
272
|
+
|
|
273
|
+
const prevSet = new Set(Array.isArray(prev.serverNames) ? prev.serverNames : []);
|
|
274
|
+
const currSet = new Set(Array.isArray(curr.serverNames) ? curr.serverNames : []);
|
|
275
|
+
const added = [...currSet].filter((s) => !prevSet.has(s));
|
|
276
|
+
const removed = [...prevSet].filter((s) => !currSet.has(s));
|
|
277
|
+
const diffParts = [];
|
|
278
|
+
if (added.length > 0) diffParts.push(`+${added.join(',+')}`);
|
|
279
|
+
if (removed.length > 0) diffParts.push(`-${removed.join(',-')}`);
|
|
280
|
+
const diffSummary = diffParts.length > 0 ? diffParts.join(' ') : 'MCP/tool definitions updated';
|
|
281
|
+
|
|
282
|
+
const knownModel = isKnownCatalogModel(rawModel, options);
|
|
283
|
+
if (!knownModel) {
|
|
284
|
+
const advisory =
|
|
285
|
+
`[Highbeam Resume Toolset Advisory] Active MCP/tool set changed (${diffSummary}); ` +
|
|
286
|
+
`prices are unknown for ${String(rawModel)}, and the first turn will rewrite ~${Math.round(contextTokens).toLocaleString()} cached tokens (t6_layers CC-T).`;
|
|
287
|
+
return {
|
|
288
|
+
changed: true,
|
|
289
|
+
shouldWarn: true,
|
|
290
|
+
unknownModel: true,
|
|
291
|
+
estimatedWriteCostUSD: null,
|
|
292
|
+
diffSummary,
|
|
293
|
+
advisory
|
|
294
|
+
};
|
|
295
|
+
}
|
|
296
|
+
|
|
297
|
+
const modelId = normalizeModelId(rawModel, options);
|
|
298
|
+
const rates = resolveEffectiveRates(modelId, contextTokens, options);
|
|
299
|
+
const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
300
|
+
const estimatedWriteCostUSD = Number(((contextTokens / 1_000_000) * writeRate).toFixed(4));
|
|
301
|
+
|
|
302
|
+
const advisory =
|
|
303
|
+
`[Highbeam Resume Toolset Advisory] Active MCP/tool set changed (${diffSummary}); ` +
|
|
304
|
+
`the first turn will rewrite ~${Math.round(contextTokens).toLocaleString()} cached tokens ` +
|
|
305
|
+
`(~$${estimatedWriteCostUSD.toFixed(4)} at ${modelId} ${ttlTier} write rate, t6_layers CC-T).`;
|
|
306
|
+
|
|
307
|
+
return {
|
|
308
|
+
changed: true,
|
|
309
|
+
shouldWarn: true,
|
|
310
|
+
unknownModel: false,
|
|
311
|
+
modelId,
|
|
312
|
+
estimatedWriteCostUSD,
|
|
313
|
+
diffSummary,
|
|
314
|
+
advisory
|
|
315
|
+
};
|
|
316
|
+
}
|
|
317
|
+
|
|
318
|
+
export default {
|
|
319
|
+
computeActiveToolsetHash,
|
|
320
|
+
evaluateResumeToolsetChange
|
|
321
|
+
};
|
|
@@ -0,0 +1,305 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core-isomorphic/coach/smartCompactAdvisor.mjs
|
|
3
|
+
* Task-boundary `/compact` suggestion advisor (`Item 5`, gated OFF by default).
|
|
4
|
+
*
|
|
5
|
+
* Evidence & Provenance (`summary_smart_compact.md`):
|
|
6
|
+
* - H4 (`C1` vs `C0`, computed): Compacting saved `-$0.5814` to `-$0.6036` over `21` requests
|
|
7
|
+
* at `~139k` context (`C1_v2_r01`, `C1_v2_r02`), while costing `+$0.1307` to `+$0.1431` over
|
|
8
|
+
* `12` requests at `~42k–50k` context (`C1_r01`–`C1_r03`, `C1mem_r02`).
|
|
9
|
+
* - Compaction latency (live): synchronous `103.9s–126.0s` (`~2-minute`) pause (`C1`, `6` runs).
|
|
10
|
+
* - H7 (`evaluateSessionBoundaryDetector`, `phase1_boundary_detector.csv`): `24/30` (`80.00%`)
|
|
11
|
+
* precision and `24/24` (`100%`) recall on same-author scripted plans; `0` organic boundaries
|
|
12
|
+
* observed across `1,240` existing benchmark turns -> detector accuracy is **unverified**.
|
|
13
|
+
*/
|
|
14
|
+
|
|
15
|
+
import {
|
|
16
|
+
isKnownCatalogModel,
|
|
17
|
+
normalizeModelId,
|
|
18
|
+
resolveEffectiveRates
|
|
19
|
+
} from '../config/catalogLoader.mjs';
|
|
20
|
+
import {
|
|
21
|
+
estimateEmpiricalRemainingTurns,
|
|
22
|
+
resolveRequestsPerTurn
|
|
23
|
+
} from './cacheGravityRouter.mjs';
|
|
24
|
+
|
|
25
|
+
export const TEST_CMD_REGEX =
|
|
26
|
+
/\b(?:node\s+--test|npm\s+(?:run\s+)?test|pnpm\s+(?:run\s+)?test|yarn\s+test|bun\s+test|vitest|jest|pytest|cargo\s+test|go\s+test|tsc(?:\s|$)|npx\s+tsc)\b/i;
|
|
27
|
+
|
|
28
|
+
const EDIT_TOOL_REGEX =
|
|
29
|
+
/^(?:Write|Edit|MultiEdit|NotebookEdit|Replace|write_to_file|replace_file_content|multi_replace_file_content)$/i;
|
|
30
|
+
|
|
31
|
+
export const DEFAULT_POST_COMPACT_COOLDOWN_TURNS = 4;
|
|
32
|
+
|
|
33
|
+
/**
|
|
34
|
+
* Updates `openFailure` and `editsSinceBoundary` state across tool executions,
|
|
35
|
+
* reproducing `evaluateSessionBoundaryDetector` from `run_smart_compact_phase0_phase1.mjs`.
|
|
36
|
+
* Detector accuracy on organic transcripts is **unverified**.
|
|
37
|
+
*
|
|
38
|
+
* @param {object} [toolEvent={}]
|
|
39
|
+
* @param {object} [priorState={}]
|
|
40
|
+
* @returns {object}
|
|
41
|
+
*/
|
|
42
|
+
export function evaluateTaskBoundaryTurn(toolEvent = {}, priorState = {}) {
|
|
43
|
+
let openFailure = Boolean(priorState.openFailure);
|
|
44
|
+
let editsSinceBoundary = Math.max(0, Number(priorState.editsSinceBoundary || 0));
|
|
45
|
+
const lastBoundarySuggestedTurn = priorState.lastBoundarySuggestedTurn ?? null;
|
|
46
|
+
|
|
47
|
+
const toolName = String(toolEvent.toolName || toolEvent.tool_name || '');
|
|
48
|
+
const command = String(toolEvent.command || toolEvent.cmd || '');
|
|
49
|
+
const fileEdited = Boolean(toolEvent.fileEdited) || EDIT_TOOL_REGEX.test(toolName);
|
|
50
|
+
const isTestCmd = Boolean(command && TEST_CMD_REGEX.test(command));
|
|
51
|
+
|
|
52
|
+
if (fileEdited) {
|
|
53
|
+
editsSinceBoundary += 1;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
let boundaryDetected = false;
|
|
57
|
+
let detectorState = openFailure ? 'mid_debug' : 'other';
|
|
58
|
+
|
|
59
|
+
if (isTestCmd) {
|
|
60
|
+
const failed =
|
|
61
|
+
toolEvent.failed !== undefined
|
|
62
|
+
? Boolean(toolEvent.failed)
|
|
63
|
+
: toolEvent.succeeded !== undefined
|
|
64
|
+
? !Boolean(toolEvent.succeeded)
|
|
65
|
+
: typeof toolEvent.exitCode === 'number'
|
|
66
|
+
? toolEvent.exitCode !== 0
|
|
67
|
+
: false;
|
|
68
|
+
|
|
69
|
+
if (failed) {
|
|
70
|
+
openFailure = true;
|
|
71
|
+
detectorState = 'mid_debug';
|
|
72
|
+
} else if (openFailure || editsSinceBoundary > 0) {
|
|
73
|
+
boundaryDetected = true;
|
|
74
|
+
detectorState = 'task_boundary';
|
|
75
|
+
openFailure = false;
|
|
76
|
+
editsSinceBoundary = 0;
|
|
77
|
+
} else {
|
|
78
|
+
detectorState = 'other';
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
|
|
82
|
+
return {
|
|
83
|
+
boundaryDetected,
|
|
84
|
+
detectorState,
|
|
85
|
+
openFailure,
|
|
86
|
+
editsSinceBoundary,
|
|
87
|
+
lastBoundarySuggestedTurn,
|
|
88
|
+
detectorStatus: 'unverified'
|
|
89
|
+
};
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
/**
|
|
93
|
+
* Estimates counterfactual H4 compaction net USD saving over expected remaining requests,
|
|
94
|
+
* using runtime catalog prices and the DET-08 horizon logic.
|
|
95
|
+
*
|
|
96
|
+
* @param {object} [params={}]
|
|
97
|
+
* @param {object} [options={}]
|
|
98
|
+
* @returns {object}
|
|
99
|
+
*/
|
|
100
|
+
export function computeCompactionHorizonNetSaving(params = {}, options = {}) {
|
|
101
|
+
const rawModel = params.modelId || params.currentModel || 'claude-sonnet-5-5';
|
|
102
|
+
const preCompactTokens = Math.max(
|
|
103
|
+
0,
|
|
104
|
+
Number(params.preCompactTokens ?? params.cachedTokens ?? params.contextTokens ?? 0)
|
|
105
|
+
);
|
|
106
|
+
|
|
107
|
+
if (!isKnownCatalogModel(rawModel, options)) {
|
|
108
|
+
return {
|
|
109
|
+
unknownModel: true,
|
|
110
|
+
modelId: String(rawModel || ''),
|
|
111
|
+
preCompactTokens,
|
|
112
|
+
remainingRequestsUsed: null,
|
|
113
|
+
horizonSource: null,
|
|
114
|
+
isPlaceholderPrior: false,
|
|
115
|
+
netSavingUSD: null,
|
|
116
|
+
positive: false
|
|
117
|
+
};
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const modelId = normalizeModelId(rawModel, options);
|
|
121
|
+
const rates = resolveEffectiveRates(modelId, preCompactTokens, options);
|
|
122
|
+
const writeRatePer1M = params.cacheTtlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
123
|
+
|
|
124
|
+
let remainingRequestsUsed;
|
|
125
|
+
let horizonSource;
|
|
126
|
+
let isPlaceholderPrior = false;
|
|
127
|
+
if (
|
|
128
|
+
params.expectedRemainingRequests !== undefined &&
|
|
129
|
+
params.expectedRemainingRequests !== null &&
|
|
130
|
+
Number.isFinite(Number(params.expectedRemainingRequests))
|
|
131
|
+
) {
|
|
132
|
+
remainingRequestsUsed = Math.max(0, Number(params.expectedRemainingRequests));
|
|
133
|
+
horizonSource = 'explicit_requests';
|
|
134
|
+
} else if (
|
|
135
|
+
params.expectedRemainingTurns !== undefined &&
|
|
136
|
+
params.expectedRemainingTurns !== null &&
|
|
137
|
+
Number.isFinite(Number(params.expectedRemainingTurns))
|
|
138
|
+
) {
|
|
139
|
+
const rpt = resolveRequestsPerTurn(params, options).requestsPerTurn;
|
|
140
|
+
remainingRequestsUsed = Math.max(0, Number(params.expectedRemainingTurns)) * rpt;
|
|
141
|
+
horizonSource = 'explicit_turns';
|
|
142
|
+
} else {
|
|
143
|
+
const prior = estimateEmpiricalRemainingTurns(
|
|
144
|
+
{
|
|
145
|
+
turnsCompleted: params.turnsCompleted ?? 0,
|
|
146
|
+
apiCallsCompleted: params.apiCallsCompleted,
|
|
147
|
+
requestsPerTurn: params.requestsPerTurn,
|
|
148
|
+
contextGrowthPerTurn: params.contextGrowthPerTurn,
|
|
149
|
+
cachedTokens: preCompactTokens,
|
|
150
|
+
contextCeiling: params.contextCeiling,
|
|
151
|
+
autoCompactLimitTokens: params.autoCompactLimitTokens,
|
|
152
|
+
initialPrefixTokens: params.initialPrefixTokens
|
|
153
|
+
},
|
|
154
|
+
options
|
|
155
|
+
);
|
|
156
|
+
remainingRequestsUsed = Math.max(0, Number(prior.expectedRemainingRequests || 0));
|
|
157
|
+
horizonSource = prior.source;
|
|
158
|
+
isPlaceholderPrior = Boolean(prior.isPlaceholderPrior);
|
|
159
|
+
}
|
|
160
|
+
|
|
161
|
+
// H4 structural split: warm tools/system[0..1] survives read-side; compacted summary + tail rewrites once.
|
|
162
|
+
const postCompactWarmTokens =
|
|
163
|
+
params.postCompactWarmTokens !== undefined
|
|
164
|
+
? Math.max(0, Math.min(preCompactTokens, Number(params.postCompactWarmTokens)))
|
|
165
|
+
: Math.min(preCompactTokens, 8_000);
|
|
166
|
+
const postCompactColdWriteTokens =
|
|
167
|
+
params.postCompactColdWriteTokens !== undefined
|
|
168
|
+
? Math.max(0, Math.min(preCompactTokens, Number(params.postCompactColdWriteTokens)))
|
|
169
|
+
: Math.min(Math.max(0, preCompactTokens - postCompactWarmTokens), 8_000);
|
|
170
|
+
const estimatedCompactOutputTokens = Math.max(
|
|
171
|
+
0,
|
|
172
|
+
Number(params.estimatedCompactOutputTokens ?? 7_000)
|
|
173
|
+
);
|
|
174
|
+
|
|
175
|
+
const postCompactTotalTokens = postCompactWarmTokens + postCompactColdWriteTokens;
|
|
176
|
+
const reducedContextTokens = Math.max(0, preCompactTokens - postCompactTotalTokens);
|
|
177
|
+
|
|
178
|
+
const compactCallCostUSD =
|
|
179
|
+
(preCompactTokens / 1_000_000) * rates.readPer1M +
|
|
180
|
+
(estimatedCompactOutputTokens / 1_000_000) * rates.outputPer1M;
|
|
181
|
+
const firstPostTurnColdSurchargeUSD =
|
|
182
|
+
(postCompactColdWriteTokens / 1_000_000) * Math.max(0, writeRatePer1M - rates.readPer1M);
|
|
183
|
+
const perRequestReadSavingUSD = (reducedContextTokens / 1_000_000) * rates.readPer1M;
|
|
184
|
+
const grossReadSavingUSD = remainingRequestsUsed * perRequestReadSavingUSD;
|
|
185
|
+
const netSavingUSD = Number(
|
|
186
|
+
(grossReadSavingUSD - compactCallCostUSD - firstPostTurnColdSurchargeUSD).toFixed(6)
|
|
187
|
+
);
|
|
188
|
+
|
|
189
|
+
return {
|
|
190
|
+
unknownModel: false,
|
|
191
|
+
modelId,
|
|
192
|
+
preCompactTokens,
|
|
193
|
+
postCompactWarmTokens,
|
|
194
|
+
postCompactColdWriteTokens,
|
|
195
|
+
estimatedCompactOutputTokens,
|
|
196
|
+
remainingRequestsUsed: Number(remainingRequestsUsed.toFixed(2)),
|
|
197
|
+
horizonSource,
|
|
198
|
+
isPlaceholderPrior,
|
|
199
|
+
compactCallCostUSD: Number(compactCallCostUSD.toFixed(6)),
|
|
200
|
+
firstPostTurnColdSurchargeUSD: Number(firstPostTurnColdSurchargeUSD.toFixed(6)),
|
|
201
|
+
perRequestReadSavingUSD: Number(perRequestReadSavingUSD.toFixed(6)),
|
|
202
|
+
grossReadSavingUSD: Number(grossReadSavingUSD.toFixed(6)),
|
|
203
|
+
netSavingUSD,
|
|
204
|
+
positive: netSavingUSD > 0
|
|
205
|
+
};
|
|
206
|
+
}
|
|
207
|
+
|
|
208
|
+
/**
|
|
209
|
+
* Evaluates whether a non-blocking task-boundary `/compact` suggestion should be shown (`Item 5`).
|
|
210
|
+
* Gated OFF by default (`smartCompactBoundarySuggest: false`). Never triggers `/compact`.
|
|
211
|
+
*
|
|
212
|
+
* @param {object} [params={}]
|
|
213
|
+
* @param {object} [options={}]
|
|
214
|
+
* @returns {object}
|
|
215
|
+
*/
|
|
216
|
+
export function evaluateSmartCompactSuggestion(params = {}, options = {}) {
|
|
217
|
+
const enabled = Boolean(
|
|
218
|
+
params.enabled ??
|
|
219
|
+
options.smartCompactBoundarySuggest ??
|
|
220
|
+
options.horizonConfig?.thresholds?.smartCompactBoundarySuggest ??
|
|
221
|
+
options.horizonConfig?.smartCompactBoundarySuggest ??
|
|
222
|
+
false
|
|
223
|
+
);
|
|
224
|
+
|
|
225
|
+
if (!enabled) {
|
|
226
|
+
return {
|
|
227
|
+
shouldSuggest: false,
|
|
228
|
+
suppressedReason: 'disabled_by_default',
|
|
229
|
+
detectorStatus: 'unverified',
|
|
230
|
+
message: null
|
|
231
|
+
};
|
|
232
|
+
}
|
|
233
|
+
|
|
234
|
+
const turnsSinceLastCompact =
|
|
235
|
+
params.turnsSinceLastCompact !== undefined && params.turnsSinceLastCompact !== null
|
|
236
|
+
? Number(params.turnsSinceLastCompact)
|
|
237
|
+
: null;
|
|
238
|
+
if (
|
|
239
|
+
turnsSinceLastCompact !== null &&
|
|
240
|
+
Number.isFinite(turnsSinceLastCompact) &&
|
|
241
|
+
turnsSinceLastCompact < DEFAULT_POST_COMPACT_COOLDOWN_TURNS
|
|
242
|
+
) {
|
|
243
|
+
return {
|
|
244
|
+
shouldSuggest: false,
|
|
245
|
+
suppressedReason: 'post_compact_cooldown',
|
|
246
|
+
detectorStatus: 'unverified',
|
|
247
|
+
message: null
|
|
248
|
+
};
|
|
249
|
+
}
|
|
250
|
+
|
|
251
|
+
const detectorState = String(params.detectorState || 'other');
|
|
252
|
+
if (
|
|
253
|
+
detectorState === 'mid_debug' ||
|
|
254
|
+
Boolean(params.openFailure) ||
|
|
255
|
+
Number(params.consecutiveFailures || 0) > 0
|
|
256
|
+
) {
|
|
257
|
+
return {
|
|
258
|
+
shouldSuggest: false,
|
|
259
|
+
suppressedReason: 'mid_debug',
|
|
260
|
+
detectorStatus: 'unverified',
|
|
261
|
+
message: null
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
|
|
265
|
+
if (!params.boundaryDetected && detectorState !== 'task_boundary') {
|
|
266
|
+
return {
|
|
267
|
+
shouldSuggest: false,
|
|
268
|
+
suppressedReason: 'no_task_boundary',
|
|
269
|
+
detectorStatus: 'unverified',
|
|
270
|
+
message: null
|
|
271
|
+
};
|
|
272
|
+
}
|
|
273
|
+
|
|
274
|
+
const netSaving = computeCompactionHorizonNetSaving(params, options);
|
|
275
|
+
if (netSaving.unknownModel || !netSaving.positive) {
|
|
276
|
+
return {
|
|
277
|
+
shouldSuggest: false,
|
|
278
|
+
suppressedReason: netSaving.unknownModel ? 'unknown_model' : 'non_positive_net_saving',
|
|
279
|
+
detectorStatus: 'unverified',
|
|
280
|
+
netSaving,
|
|
281
|
+
message: null
|
|
282
|
+
};
|
|
283
|
+
}
|
|
284
|
+
|
|
285
|
+
const message =
|
|
286
|
+
`[Highbeam] Task boundary reached (unverified detector): running /compact saves ` +
|
|
287
|
+
`~$${netSaving.netSavingUSD.toFixed(2)} over ~${netSaving.remainingRequestsUsed} remaining requests, ` +
|
|
288
|
+
`with a ~2-minute synchronous pause (H4/H7).`;
|
|
289
|
+
|
|
290
|
+
return {
|
|
291
|
+
shouldSuggest: true,
|
|
292
|
+
suppressedReason: null,
|
|
293
|
+
detectorStatus: 'unverified',
|
|
294
|
+
netSaving,
|
|
295
|
+
message
|
|
296
|
+
};
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
export default {
|
|
300
|
+
TEST_CMD_REGEX,
|
|
301
|
+
DEFAULT_POST_COMPACT_COOLDOWN_TURNS,
|
|
302
|
+
evaluateTaskBoundaryTurn,
|
|
303
|
+
computeCompactionHorizonNetSaving,
|
|
304
|
+
evaluateSmartCompactSuggestion
|
|
305
|
+
};
|
|
@@ -302,11 +302,14 @@ export class TtlWatchdog {
|
|
|
302
302
|
totalPromptTokens,
|
|
303
303
|
this.options
|
|
304
304
|
);
|
|
305
|
-
const
|
|
305
|
+
const hasKnownPrices = Boolean(rates && !rates.unknownModel && rates.readPer1M !== null);
|
|
306
|
+
const writeRate = hasKnownPrices
|
|
307
|
+
? (tier === '1h' ? rates.write1hPer1M : rates.write5mPer1M)
|
|
308
|
+
: null;
|
|
306
309
|
// Cost of losing the warm cache and rewriting it at writeRate (1.25x 5m / 2.0x 1h) instead of reading at readPer1M
|
|
307
|
-
const expiryPenaltyUSD =
|
|
308
|
-
((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
|
|
309
|
-
|
|
310
|
+
const expiryPenaltyUSD = hasKnownPrices
|
|
311
|
+
? Number(((cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6))
|
|
312
|
+
: null;
|
|
310
313
|
|
|
311
314
|
const formattedRemaining = formatRemainingTtl(remainingSeconds);
|
|
312
315
|
const pauseDistribution = this.getPauseDistribution();
|
|
@@ -417,9 +420,13 @@ export class TtlWatchdog {
|
|
|
417
420
|
}
|
|
418
421
|
}
|
|
419
422
|
|
|
423
|
+
const penaltySuffix =
|
|
424
|
+
expiryPenaltyUSD !== null
|
|
425
|
+
? ` ($${expiryPenaltyUSD.toFixed(2)} rewrite)`
|
|
426
|
+
: ' (prices unknown)';
|
|
420
427
|
const bannerText = preSnapshotTriggered
|
|
421
|
-
? `amber TTL cliff (${formattedRemaining}): zero-token StateBaton pre-snapshot saved at T-${remainingSeconds}s (protects ${(cachedTokens / 1000).toFixed(1)}k cache
|
|
422
|
-
: `amber TTL warning (${formattedRemaining}): ${(cachedTokens / 1000).toFixed(1)}k warm cache on ${rates.shortLabel} expires soon (+$${expiryPenaltyUSD.toFixed(2)} rewrite penalty).`;
|
|
428
|
+
? `amber TTL cliff (${formattedRemaining}): zero-token StateBaton pre-snapshot saved at T-${remainingSeconds}s (protects ${(cachedTokens / 1000).toFixed(1)}k cache${penaltySuffix}).`
|
|
429
|
+
: `amber TTL warning (${formattedRemaining}): ${(cachedTokens / 1000).toFixed(1)}k warm cache on ${rates.shortLabel} expires soon${expiryPenaltyUSD !== null ? ` (+$${expiryPenaltyUSD.toFixed(2)} rewrite penalty)` : '; prices unknown'}.`;
|
|
423
430
|
|
|
424
431
|
return {
|
|
425
432
|
detectorId: 'DET-10',
|