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,1417 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file src/core/shield_manager.mjs
|
|
3
|
+
* Unified Active Context Shield Manager, Net-Positive Read Firewall (`>=1,200` lines default,
|
|
4
|
+
* `150` lines near `100k`/`200k` pricing cliffs), Out-of-Band `.hints.jsonl` Telemetry,
|
|
5
|
+
* and Non-Destructive Hook Merger (`ctxtop shield --enable | --disable | --status`).
|
|
6
|
+
*/
|
|
7
|
+
|
|
8
|
+
import fs from 'node:fs';
|
|
9
|
+
import path from 'node:path';
|
|
10
|
+
import os from 'node:os';
|
|
11
|
+
import crypto from 'node:crypto';
|
|
12
|
+
import { fileURLToPath } from 'node:url';
|
|
13
|
+
import { atomicWriteFileSync } from './atomic_io.mjs';
|
|
14
|
+
import { buildIndex, isForbiddenSkuPath } from './doc_indexer.mjs';
|
|
15
|
+
import { normalizeModelKey, resolveModelRates } from './constants.mjs';
|
|
16
|
+
import {
|
|
17
|
+
recordInterventionSavings,
|
|
18
|
+
getSavedQuotaReceiptSummary
|
|
19
|
+
} from '../core-isomorphic/coach/savedQuotaLedger.mjs';
|
|
20
|
+
|
|
21
|
+
const __dirname = path.dirname(fileURLToPath(import.meta.url));
|
|
22
|
+
export const PKG_ROOT = path.resolve(__dirname, '..', '..').replace(/\\/g, '/');
|
|
23
|
+
|
|
24
|
+
export const DEFAULT_SHIELD_MAX_UNSLICED_LINES = 1200;
|
|
25
|
+
export const CLIFF_SHIELD_MAX_UNSLICED_LINES = 150;
|
|
26
|
+
export const COLD_CACHE_GAP_MS = 300_000; // 5-minute TTL
|
|
27
|
+
|
|
28
|
+
const CTXTOP_CLAUDE_SCRIPT_RE =
|
|
29
|
+
/hooks[\\/]handlers[\\/](?:pre-tool-use|post-tool-use)\.mjs/i;
|
|
30
|
+
|
|
31
|
+
/**
|
|
32
|
+
* Resolves known model prompt-pricing cliff thresholds (`100k` Haiku 5.5, `200k` Gemini 3.1/2.5 Pro).
|
|
33
|
+
*
|
|
34
|
+
* @param {string} [modelId='']
|
|
35
|
+
* @returns {number}
|
|
36
|
+
*/
|
|
37
|
+
export function resolvePromptCliffTokens(modelId = '') {
|
|
38
|
+
const norm = normalizeModelKey(modelId || '');
|
|
39
|
+
if (!norm) return 0;
|
|
40
|
+
if (norm.includes('haiku-5-5') || norm.includes('haiku-5.5')) {
|
|
41
|
+
return 100_000;
|
|
42
|
+
}
|
|
43
|
+
if (
|
|
44
|
+
norm.includes('gemini-3-1-pro') ||
|
|
45
|
+
norm.includes('gemini-3.1-pro') ||
|
|
46
|
+
norm.includes('gemini-2-5-pro') ||
|
|
47
|
+
norm.includes('gemini-2.5-pro')
|
|
48
|
+
) {
|
|
49
|
+
return 200_000;
|
|
50
|
+
}
|
|
51
|
+
return 0;
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Resolves `.agents/telemetry/ctxtop-shield.config.json` inside `<cwd>`.
|
|
56
|
+
*
|
|
57
|
+
* @param {object} [options={}]
|
|
58
|
+
* @returns {string}
|
|
59
|
+
*/
|
|
60
|
+
export function getShieldConfigPath(options = {}) {
|
|
61
|
+
if (typeof options.shieldConfigPath === 'string' && options.shieldConfigPath.trim()) {
|
|
62
|
+
return path.resolve(options.shieldConfigPath.trim());
|
|
63
|
+
}
|
|
64
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
65
|
+
return path.join(baseCwd, '.agents', 'telemetry', 'ctxtop-shield.config.json');
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Loads the Active Context Shield configuration, defaulting `enabled` to `false` until
|
|
70
|
+
* explicitly activated via `ctxtop shield --enable` (or programmatic override).
|
|
71
|
+
*
|
|
72
|
+
* @param {object} [options={}]
|
|
73
|
+
* @returns {{
|
|
74
|
+
* enabled: boolean,
|
|
75
|
+
* platforms: { antigravity: boolean, claude: boolean },
|
|
76
|
+
* maxUnslicedLines: number,
|
|
77
|
+
* cliffMaxUnslicedLines: number,
|
|
78
|
+
* updatedAt: string | null,
|
|
79
|
+
* configPath: string
|
|
80
|
+
* }}
|
|
81
|
+
*/
|
|
82
|
+
export function loadShieldConfig(options = {}) {
|
|
83
|
+
const configPath = getShieldConfigPath(options);
|
|
84
|
+
const defaults = {
|
|
85
|
+
enabled: false,
|
|
86
|
+
platforms: { antigravity: false, claude: false },
|
|
87
|
+
maxUnslicedLines: DEFAULT_SHIELD_MAX_UNSLICED_LINES,
|
|
88
|
+
cliffMaxUnslicedLines: CLIFF_SHIELD_MAX_UNSLICED_LINES,
|
|
89
|
+
updatedAt: null,
|
|
90
|
+
configPath
|
|
91
|
+
};
|
|
92
|
+
if (!fs.existsSync(configPath)) {
|
|
93
|
+
return defaults;
|
|
94
|
+
}
|
|
95
|
+
try {
|
|
96
|
+
const parsed = JSON.parse(fs.readFileSync(configPath, 'utf8'));
|
|
97
|
+
if (!parsed || typeof parsed !== 'object') return defaults;
|
|
98
|
+
const enabled = Boolean(parsed.enabled);
|
|
99
|
+
const platforms = {
|
|
100
|
+
antigravity:
|
|
101
|
+
parsed.platforms && typeof parsed.platforms.antigravity === 'boolean'
|
|
102
|
+
? parsed.platforms.antigravity
|
|
103
|
+
: enabled,
|
|
104
|
+
claude:
|
|
105
|
+
parsed.platforms && typeof parsed.platforms.claude === 'boolean'
|
|
106
|
+
? parsed.platforms.claude
|
|
107
|
+
: enabled
|
|
108
|
+
};
|
|
109
|
+
const maxLines = Number(parsed.maxUnslicedLines);
|
|
110
|
+
const cliffLines = Number(parsed.cliffMaxUnslicedLines);
|
|
111
|
+
return {
|
|
112
|
+
enabled: Boolean(enabled || platforms.antigravity || platforms.claude),
|
|
113
|
+
platforms,
|
|
114
|
+
maxUnslicedLines:
|
|
115
|
+
Number.isFinite(maxLines) && maxLines >= 100
|
|
116
|
+
? Math.round(maxLines)
|
|
117
|
+
: DEFAULT_SHIELD_MAX_UNSLICED_LINES,
|
|
118
|
+
cliffMaxUnslicedLines:
|
|
119
|
+
Number.isFinite(cliffLines) && cliffLines >= 50
|
|
120
|
+
? Math.round(cliffLines)
|
|
121
|
+
: CLIFF_SHIELD_MAX_UNSLICED_LINES,
|
|
122
|
+
updatedAt: parsed.updatedAt || null,
|
|
123
|
+
configPath
|
|
124
|
+
};
|
|
125
|
+
} catch {
|
|
126
|
+
return defaults;
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
/**
|
|
131
|
+
* Atomically persists `.agents/telemetry/ctxtop-shield.config.json`.
|
|
132
|
+
*
|
|
133
|
+
* @param {object} partial
|
|
134
|
+
* @param {object} [options={}]
|
|
135
|
+
*/
|
|
136
|
+
export function saveShieldConfig(partial = {}, options = {}) {
|
|
137
|
+
const current = loadShieldConfig(options);
|
|
138
|
+
const nextPlatforms = {
|
|
139
|
+
antigravity:
|
|
140
|
+
partial.platforms?.antigravity !== undefined
|
|
141
|
+
? Boolean(partial.platforms.antigravity)
|
|
142
|
+
: current.platforms.antigravity,
|
|
143
|
+
claude:
|
|
144
|
+
partial.platforms?.claude !== undefined
|
|
145
|
+
? Boolean(partial.platforms.claude)
|
|
146
|
+
: current.platforms.claude
|
|
147
|
+
};
|
|
148
|
+
const nextEnabled =
|
|
149
|
+
partial.enabled !== undefined
|
|
150
|
+
? Boolean(partial.enabled)
|
|
151
|
+
: Boolean(nextPlatforms.antigravity || nextPlatforms.claude);
|
|
152
|
+
const payload = {
|
|
153
|
+
enabled: nextEnabled,
|
|
154
|
+
platforms: nextPlatforms,
|
|
155
|
+
maxUnslicedLines:
|
|
156
|
+
Number.isFinite(Number(partial.maxUnslicedLines)) && Number(partial.maxUnslicedLines) >= 100
|
|
157
|
+
? Math.round(Number(partial.maxUnslicedLines))
|
|
158
|
+
: current.maxUnslicedLines,
|
|
159
|
+
cliffMaxUnslicedLines:
|
|
160
|
+
Number.isFinite(Number(partial.cliffMaxUnslicedLines)) && Number(partial.cliffMaxUnslicedLines) >= 50
|
|
161
|
+
? Math.round(Number(partial.cliffMaxUnslicedLines))
|
|
162
|
+
: current.cliffMaxUnslicedLines,
|
|
163
|
+
updatedAt: new Date().toISOString()
|
|
164
|
+
};
|
|
165
|
+
fs.mkdirSync(path.dirname(current.configPath), { recursive: true });
|
|
166
|
+
atomicWriteFileSync(current.configPath, `${JSON.stringify(payload, null, 2)}\n`);
|
|
167
|
+
return { ...payload, configPath: current.configPath };
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
function sanitizeSessionFileId(sessionId = 'default') {
|
|
171
|
+
const cleaned = String(sessionId || 'default')
|
|
172
|
+
.trim()
|
|
173
|
+
.replace(/[^A-Za-z0-9_-]/g, '_')
|
|
174
|
+
.slice(0, 80);
|
|
175
|
+
return cleaned || 'default';
|
|
176
|
+
}
|
|
177
|
+
|
|
178
|
+
/**
|
|
179
|
+
* Appends a zero-prompt-token telemetry event to `.agents/telemetry/<sessionId>.hints.jsonl`.
|
|
180
|
+
*
|
|
181
|
+
* @param {string} sessionId
|
|
182
|
+
* @param {object} eventRecord
|
|
183
|
+
* @param {object} [options={}]
|
|
184
|
+
* @returns {string}
|
|
185
|
+
*/
|
|
186
|
+
export function appendShieldHint(sessionId, eventRecord = {}, options = {}) {
|
|
187
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
188
|
+
const safeId = sanitizeSessionFileId(sessionId);
|
|
189
|
+
const telemetryDir = path.join(baseCwd, '.agents', 'telemetry');
|
|
190
|
+
const hintsPath = path.join(telemetryDir, `${safeId}.hints.jsonl`);
|
|
191
|
+
try {
|
|
192
|
+
fs.mkdirSync(telemetryDir, { recursive: true });
|
|
193
|
+
const row = {
|
|
194
|
+
timestamp: new Date().toISOString(),
|
|
195
|
+
sessionId: safeId,
|
|
196
|
+
...eventRecord
|
|
197
|
+
};
|
|
198
|
+
fs.appendFileSync(hintsPath, `${JSON.stringify(row)}\n`, 'utf8');
|
|
199
|
+
} catch {
|
|
200
|
+
// Non-fatal telemetry write
|
|
201
|
+
}
|
|
202
|
+
return hintsPath;
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
/**
|
|
206
|
+
* Appends a standardized `bucket_b_shadow_v1` telemetry record to `.agents/telemetry/<sessionId>.hints.jsonl`
|
|
207
|
+
* (`0` stdout/stderr bytes, `0` prompt tokens, `0` cache-prefix mutations).
|
|
208
|
+
*
|
|
209
|
+
* @param {string} sessionId
|
|
210
|
+
* @param {object} hint
|
|
211
|
+
* @param {string} hint.guardrailId - e.g. `'#2_GREP_GLOB_FIREWALL'`
|
|
212
|
+
* @param {'SHADOW' | 'COACH' | 'ENFORCE'} [hint.stage='SHADOW']
|
|
213
|
+
* @param {'claude' | 'antigravity'} [hint.platform='claude']
|
|
214
|
+
* @param {boolean} [hint.wouldTrigger=false]
|
|
215
|
+
* @param {string} [hint.wouldDecision='allow']
|
|
216
|
+
* @param {number} [hint.latencyMs=0]
|
|
217
|
+
* @param {number} [hint.tokens_saved_est=0]
|
|
218
|
+
* @param {number} [hint.dollars_saved_est=0]
|
|
219
|
+
* @param {object} [hint.evidence={}]
|
|
220
|
+
* @param {object} [options={}]
|
|
221
|
+
* @returns {string}
|
|
222
|
+
*/
|
|
223
|
+
export function recordBucketBShadowHint(sessionId, hint = {}, options = {}) {
|
|
224
|
+
const stage = String(hint.stage || 'SHADOW').toUpperCase();
|
|
225
|
+
return appendShieldHint(
|
|
226
|
+
sessionId,
|
|
227
|
+
{
|
|
228
|
+
schema: 'bucket_b_shadow_v1',
|
|
229
|
+
event: 'bucket_b_shadow',
|
|
230
|
+
guardrailId: String(hint.guardrailId || 'UNKNOWN'),
|
|
231
|
+
stage: stage === 'COACH' || stage === 'ENFORCE' ? stage : 'SHADOW',
|
|
232
|
+
platform: hint.platform === 'antigravity' ? 'antigravity' : 'claude',
|
|
233
|
+
wouldTrigger: Boolean(hint.wouldTrigger),
|
|
234
|
+
wouldDecision: String(hint.wouldDecision || 'allow'),
|
|
235
|
+
latencyMs: Number(Math.max(0, Number(hint.latencyMs) || 0).toFixed(3)),
|
|
236
|
+
tokens_saved_est: Math.max(0, Math.round(Number(hint.tokens_saved_est) || 0)),
|
|
237
|
+
dollars_saved_est: Number(Math.max(0, Number(hint.dollars_saved_est) || 0).toFixed(6)),
|
|
238
|
+
evidence: hint.evidence && typeof hint.evidence === 'object' ? hint.evidence : {}
|
|
239
|
+
},
|
|
240
|
+
options
|
|
241
|
+
);
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
/**
|
|
245
|
+
* Evaluates an incoming `Read` / `read_file` / `view_file` call against the Active Context Shield.
|
|
246
|
+
*
|
|
247
|
+
* Net-Positive Cache Math:
|
|
248
|
+
* - Default threshold is `1,200` lines (`~12k+` tokens), tightening to `150` lines when the session
|
|
249
|
+
* is at `>= 90%` of a model prompt-pricing cliff (`90k` Haiku 5.5 / `180k` Gemini 3.1/2.5 Pro).
|
|
250
|
+
* - Never blocks sliced reads (`StartLine`/`EndLine` or `offset`/`limit`/`pages`), `.index.md` files,
|
|
251
|
+
* or isolated `packages/airlock/` files.
|
|
252
|
+
*
|
|
253
|
+
* @param {object} params
|
|
254
|
+
* @param {'antigravity' | 'claude'} [params.platform='claude']
|
|
255
|
+
* @param {string} [params.sessionId='default']
|
|
256
|
+
* @param {string} [params.cwd]
|
|
257
|
+
* @param {string} [params.filePath='']
|
|
258
|
+
* @param {boolean} [params.hasSliceBounds=false]
|
|
259
|
+
* @param {number} [params.currentPromptTokens=0]
|
|
260
|
+
* @param {string} [params.modelId='claude-sonnet-5-5']
|
|
261
|
+
* @param {object} [params.shieldConfig]
|
|
262
|
+
* @param {boolean} [params.forceActive=false]
|
|
263
|
+
* @param {boolean} [params.recordLedger=true]
|
|
264
|
+
* @param {string} [params.ledgerPath]
|
|
265
|
+
* @returns {{
|
|
266
|
+
* action: 'allow' | 'deny',
|
|
267
|
+
* detectorId?: string,
|
|
268
|
+
* reason?: string,
|
|
269
|
+
* indexPath?: string,
|
|
270
|
+
* relIndexPath?: string,
|
|
271
|
+
* totalLines?: number,
|
|
272
|
+
* maxLines?: number,
|
|
273
|
+
* nearCliff?: boolean,
|
|
274
|
+
* savedTokens?: number,
|
|
275
|
+
* savedUSD?: number
|
|
276
|
+
* }}
|
|
277
|
+
*/
|
|
278
|
+
export function evaluateShieldReadGuard({
|
|
279
|
+
platform = 'claude',
|
|
280
|
+
sessionId = 'default',
|
|
281
|
+
cwd = process.cwd(),
|
|
282
|
+
filePath = '',
|
|
283
|
+
hasSliceBounds = false,
|
|
284
|
+
currentPromptTokens = 0,
|
|
285
|
+
modelId = 'claude-sonnet-5-5',
|
|
286
|
+
shieldConfig,
|
|
287
|
+
forceActive = false,
|
|
288
|
+
recordLedger = true,
|
|
289
|
+
ledgerPath
|
|
290
|
+
} = {}) {
|
|
291
|
+
const rawTarget = String(filePath || '').trim();
|
|
292
|
+
if (!rawTarget || hasSliceBounds) {
|
|
293
|
+
return { action: 'allow' };
|
|
294
|
+
}
|
|
295
|
+
if (rawTarget.endsWith('.index.md') || isForbiddenSkuPath(rawTarget)) {
|
|
296
|
+
return { action: 'allow' };
|
|
297
|
+
}
|
|
298
|
+
|
|
299
|
+
const baseCwd = path.resolve(cwd || process.cwd());
|
|
300
|
+
const absFile = path.isAbsolute(rawTarget) ? path.resolve(rawTarget) : path.resolve(baseCwd, rawTarget);
|
|
301
|
+
const relFile = path.relative(baseCwd, absFile).replace(/\\/g, '/');
|
|
302
|
+
if (isForbiddenSkuPath(absFile) || isForbiddenSkuPath(relFile)) {
|
|
303
|
+
return { action: 'allow' };
|
|
304
|
+
}
|
|
305
|
+
|
|
306
|
+
const cfg = shieldConfig || loadShieldConfig({ cwd: baseCwd });
|
|
307
|
+
const platformKey = platform === 'antigravity' ? 'antigravity' : 'claude';
|
|
308
|
+
const shieldEnabledForPlatform = Boolean(
|
|
309
|
+
forceActive || (cfg.enabled && cfg.platforms?.[platformKey] !== false)
|
|
310
|
+
);
|
|
311
|
+
|
|
312
|
+
const cliffTokens = resolvePromptCliffTokens(modelId);
|
|
313
|
+
const promptTok = Math.max(0, Number(currentPromptTokens) || 0);
|
|
314
|
+
const nearCliff = cliffTokens > 0 && promptTok >= Math.floor(cliffTokens * 0.9);
|
|
315
|
+
|
|
316
|
+
// Near a pricing cliff (>=90% of 100k/200k), cliff protection activates even if general shield is passive,
|
|
317
|
+
// unless shield was explicitly passed with forceActive === false and nearCliff === false.
|
|
318
|
+
if (!shieldEnabledForPlatform && !nearCliff) {
|
|
319
|
+
return { action: 'allow' };
|
|
320
|
+
}
|
|
321
|
+
|
|
322
|
+
if (!fs.existsSync(absFile)) {
|
|
323
|
+
return { action: 'allow' };
|
|
324
|
+
}
|
|
325
|
+
let stat;
|
|
326
|
+
try {
|
|
327
|
+
stat = fs.statSync(absFile);
|
|
328
|
+
} catch {
|
|
329
|
+
return { action: 'allow' };
|
|
330
|
+
}
|
|
331
|
+
if (!stat.isFile() || stat.size < 1024) {
|
|
332
|
+
return { action: 'allow' };
|
|
333
|
+
}
|
|
334
|
+
|
|
335
|
+
const maxLines = nearCliff
|
|
336
|
+
? (cfg.cliffMaxUnslicedLines || CLIFF_SHIELD_MAX_UNSLICED_LINES)
|
|
337
|
+
: (cfg.maxUnslicedLines || DEFAULT_SHIELD_MAX_UNSLICED_LINES);
|
|
338
|
+
|
|
339
|
+
let rawText;
|
|
340
|
+
try {
|
|
341
|
+
rawText = fs.readFileSync(absFile, 'utf8');
|
|
342
|
+
} catch {
|
|
343
|
+
return { action: 'allow' };
|
|
344
|
+
}
|
|
345
|
+
// Skip binary buffers with NUL bytes
|
|
346
|
+
if (rawText.includes('\0')) {
|
|
347
|
+
return { action: 'allow' };
|
|
348
|
+
}
|
|
349
|
+
|
|
350
|
+
const totalLines = rawText.length === 0 ? 0 : rawText.replace(/\r\n/g, '\n').split('\n').length;
|
|
351
|
+
if (totalLines <= maxLines) {
|
|
352
|
+
return { action: 'allow' };
|
|
353
|
+
}
|
|
354
|
+
|
|
355
|
+
const indexed = buildIndex(absFile, { cwd: baseCwd });
|
|
356
|
+
if (!indexed.ok) {
|
|
357
|
+
return { action: 'allow' };
|
|
358
|
+
}
|
|
359
|
+
|
|
360
|
+
const estFullTokens = Math.ceil(stat.size / 4);
|
|
361
|
+
const savedTokens = Math.max(0, estFullTokens - indexed.indexTokens);
|
|
362
|
+
const rates = resolveModelRates(modelId, Date.now(), 'standard', {
|
|
363
|
+
totalPromptTokens: promptTok + estFullTokens
|
|
364
|
+
});
|
|
365
|
+
const savedUSD = Number(((savedTokens / 1_000_000) * Number(rates.inputPer1M || 3.0)).toFixed(6));
|
|
366
|
+
|
|
367
|
+
const displayFile = !relFile.startsWith('..') && !path.isAbsolute(relFile) ? relFile : path.basename(absFile);
|
|
368
|
+
const displayIndex = !indexed.relIndexPath.startsWith('..') ? indexed.relIndexPath : indexed.indexPath;
|
|
369
|
+
const cliffTag = nearCliff
|
|
370
|
+
? ` (90% of ${(cliffTokens / 1000).toFixed(0)}k pricing cliff)`
|
|
371
|
+
: '';
|
|
372
|
+
|
|
373
|
+
const reason =
|
|
374
|
+
platformKey === 'antigravity'
|
|
375
|
+
? `Highbeam Shield blocked un-sliced read of ${displayFile} (${totalLines} lines > ${maxLines}-line cap${cliffTag}; +${savedTokens.toLocaleString('en-US')} tok saved). Structural map ready at ${displayIndex}: read ${displayIndex} first, then call read_file with StartLine and EndLine.`
|
|
376
|
+
: `Highbeam Shield blocked un-sliced Read of ${displayFile} (${totalLines} lines > ${maxLines}-line cap${cliffTag}; +${savedTokens.toLocaleString('en-US')} tok saved). Structural map ready at ${displayIndex}: call Read on ${displayIndex} first, then call Read on ${displayFile} with offset and limit.`;
|
|
377
|
+
|
|
378
|
+
if (recordLedger) {
|
|
379
|
+
recordInterventionSavings(
|
|
380
|
+
{
|
|
381
|
+
sessionId,
|
|
382
|
+
category: 'BOUNDED_READ_ENFORCED',
|
|
383
|
+
modelId,
|
|
384
|
+
savedTokens,
|
|
385
|
+
savedUSD,
|
|
386
|
+
dedupeId: `shield_read:${sessionId}:${displayFile}:${indexed.sha256?.slice(0, 8) || totalLines}`,
|
|
387
|
+
detail: `Blocked un-sliced read of ${displayFile} (${totalLines} lines -> ${displayIndex})`
|
|
388
|
+
},
|
|
389
|
+
{ cwd: baseCwd, ...(ledgerPath ? { ledgerPath } : {}) }
|
|
390
|
+
);
|
|
391
|
+
appendShieldHint(
|
|
392
|
+
sessionId,
|
|
393
|
+
{
|
|
394
|
+
event: 'blocked_unsliced_read',
|
|
395
|
+
platform: platformKey,
|
|
396
|
+
file: displayFile,
|
|
397
|
+
index_path: displayIndex,
|
|
398
|
+
lines_at_read: totalLines,
|
|
399
|
+
max_lines: maxLines,
|
|
400
|
+
near_cliff: nearCliff,
|
|
401
|
+
tokens_saved_est: savedTokens,
|
|
402
|
+
dollars_saved_est: savedUSD
|
|
403
|
+
},
|
|
404
|
+
{ cwd: baseCwd }
|
|
405
|
+
);
|
|
406
|
+
}
|
|
407
|
+
|
|
408
|
+
return {
|
|
409
|
+
action: 'deny',
|
|
410
|
+
detectorId: nearCliff ? 'DET-12' : 'DET-11',
|
|
411
|
+
reason,
|
|
412
|
+
indexPath: indexed.indexPath,
|
|
413
|
+
relIndexPath: displayIndex,
|
|
414
|
+
totalLines,
|
|
415
|
+
maxLines,
|
|
416
|
+
nearCliff,
|
|
417
|
+
savedTokens,
|
|
418
|
+
savedUSD
|
|
419
|
+
};
|
|
420
|
+
}
|
|
421
|
+
|
|
422
|
+
/**
|
|
423
|
+
* Ensures `.agents/` and `.claude/cache/` are listed in `.git/info/exclude` when `.git` exists,
|
|
424
|
+
* without touching tracked files.
|
|
425
|
+
*
|
|
426
|
+
* @param {string} baseCwd
|
|
427
|
+
*/
|
|
428
|
+
function ensureLocalGitExclude(baseCwd) {
|
|
429
|
+
const excludeFile = path.join(baseCwd, '.git', 'info', 'exclude');
|
|
430
|
+
if (!fs.existsSync(path.dirname(excludeFile))) return;
|
|
431
|
+
try {
|
|
432
|
+
const existing = fs.existsSync(excludeFile) ? fs.readFileSync(excludeFile, 'utf8') : '';
|
|
433
|
+
const needed = ['.agents/cache/', '.agents/telemetry/', '.claude/cache/'];
|
|
434
|
+
const missing = needed.filter((entry) => !existing.includes(entry));
|
|
435
|
+
if (missing.length > 0) {
|
|
436
|
+
const prefix = existing.endsWith('\n') || existing.length === 0 ? '' : '\n';
|
|
437
|
+
fs.writeFileSync(excludeFile, `${existing}${prefix}${missing.join('\n')}\n`, 'utf8');
|
|
438
|
+
}
|
|
439
|
+
} catch {
|
|
440
|
+
// Non-fatal
|
|
441
|
+
}
|
|
442
|
+
}
|
|
443
|
+
|
|
444
|
+
/**
|
|
445
|
+
* Non-destructively merges or removes `ctxtop-*` named hook groups in `<cwd>/.agents/hooks.json`.
|
|
446
|
+
* Preserves any `ctxvault` or custom user hook groups and NEVER touches `~/.gemini/antigravity-cli/settings.json`.
|
|
447
|
+
*
|
|
448
|
+
* @param {object} params
|
|
449
|
+
* @param {'enable' | 'disable'} params.mode
|
|
450
|
+
* @param {string} params.cwd
|
|
451
|
+
* @param {string} [params.pkgRoot=PKG_ROOT]
|
|
452
|
+
*/
|
|
453
|
+
export function syncAntigravityShieldHooks({ mode = 'enable', cwd = process.cwd(), pkgRoot = PKG_ROOT } = {}) {
|
|
454
|
+
const baseCwd = path.resolve(cwd);
|
|
455
|
+
const hooksFile = path.join(baseCwd, '.agents', 'hooks.json');
|
|
456
|
+
const rootNorm = String(pkgRoot || PKG_ROOT).replace(/\\/g, '/');
|
|
457
|
+
const preScript = `${rootNorm}/src/hooks/pre_invocation.mjs`;
|
|
458
|
+
const postScript = `${rootNorm}/src/hooks/post_invocation.mjs`;
|
|
459
|
+
|
|
460
|
+
let doc = {};
|
|
461
|
+
if (fs.existsSync(hooksFile)) {
|
|
462
|
+
try {
|
|
463
|
+
const parsed = JSON.parse(fs.readFileSync(hooksFile, 'utf8'));
|
|
464
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
465
|
+
doc = { ...parsed };
|
|
466
|
+
}
|
|
467
|
+
} catch {
|
|
468
|
+
doc = {};
|
|
469
|
+
}
|
|
470
|
+
}
|
|
471
|
+
|
|
472
|
+
if (mode === 'enable') {
|
|
473
|
+
doc['ctxtop-read-guard'] = {
|
|
474
|
+
PreToolUse: [
|
|
475
|
+
{
|
|
476
|
+
matcher: 'read_file|view_file',
|
|
477
|
+
hooks: [
|
|
478
|
+
{
|
|
479
|
+
type: 'command',
|
|
480
|
+
command: `node "${preScript}" --event=PreToolUse`,
|
|
481
|
+
timeout: 5
|
|
482
|
+
}
|
|
483
|
+
]
|
|
484
|
+
}
|
|
485
|
+
]
|
|
486
|
+
};
|
|
487
|
+
doc['ctxtop-tail-guard'] = {
|
|
488
|
+
PostToolUse: [
|
|
489
|
+
{
|
|
490
|
+
matcher: 'run_command',
|
|
491
|
+
hooks: [
|
|
492
|
+
{
|
|
493
|
+
type: 'command',
|
|
494
|
+
command: `node "${postScript}"`,
|
|
495
|
+
timeout: 5
|
|
496
|
+
}
|
|
497
|
+
]
|
|
498
|
+
}
|
|
499
|
+
]
|
|
500
|
+
};
|
|
501
|
+
doc['ctxtop-turn-tracker'] = {
|
|
502
|
+
PreInvocation: [
|
|
503
|
+
{
|
|
504
|
+
type: 'command',
|
|
505
|
+
command: `node "${preScript}"`,
|
|
506
|
+
timeout: 10
|
|
507
|
+
}
|
|
508
|
+
]
|
|
509
|
+
};
|
|
510
|
+
fs.mkdirSync(path.dirname(hooksFile), { recursive: true });
|
|
511
|
+
atomicWriteFileSync(hooksFile, `${JSON.stringify(doc, null, 2)}\n`);
|
|
512
|
+
} else if (fs.existsSync(hooksFile)) {
|
|
513
|
+
delete doc['ctxtop-read-guard'];
|
|
514
|
+
delete doc['ctxtop-tail-guard'];
|
|
515
|
+
delete doc['ctxtop-turn-tracker'];
|
|
516
|
+
atomicWriteFileSync(hooksFile, `${JSON.stringify(doc, null, 2)}\n`);
|
|
517
|
+
}
|
|
518
|
+
|
|
519
|
+
return { hooksPath: hooksFile, document: doc };
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function isCtxtopClaudeEntry(entry) {
|
|
523
|
+
if (!entry || typeof entry !== 'object') return false;
|
|
524
|
+
if (typeof entry.command === 'string' && CTXTOP_CLAUDE_SCRIPT_RE.test(entry.command)) {
|
|
525
|
+
return true;
|
|
526
|
+
}
|
|
527
|
+
if (Array.isArray(entry.hooks)) {
|
|
528
|
+
return entry.hooks.some(
|
|
529
|
+
(inner) => typeof inner?.command === 'string' && CTXTOP_CLAUDE_SCRIPT_RE.test(inner.command)
|
|
530
|
+
);
|
|
531
|
+
}
|
|
532
|
+
return false;
|
|
533
|
+
}
|
|
534
|
+
|
|
535
|
+
/**
|
|
536
|
+
* Non-destructively merges or removes `ctxtop` hook entries in `<cwd>/.claude/settings.json`
|
|
537
|
+
* under top-level `"hooks"`, preserving `ctxvault` and custom hooks and NEVER setting `"disableAllHooks": true`.
|
|
538
|
+
*
|
|
539
|
+
* @param {object} params
|
|
540
|
+
* @param {'enable' | 'disable'} params.mode
|
|
541
|
+
* @param {string} params.cwd
|
|
542
|
+
* @param {string} [params.pkgRoot=PKG_ROOT]
|
|
543
|
+
*/
|
|
544
|
+
export function syncClaudeShieldHooks({ mode = 'enable', cwd = process.cwd(), pkgRoot = PKG_ROOT } = {}) {
|
|
545
|
+
const baseCwd = path.resolve(cwd);
|
|
546
|
+
const settingsFile = path.join(baseCwd, '.claude', 'settings.json');
|
|
547
|
+
const rootNorm = String(pkgRoot || PKG_ROOT).replace(/\\/g, '/');
|
|
548
|
+
const preCmd = `node "${rootNorm}/hooks/handlers/pre-tool-use.mjs"`;
|
|
549
|
+
const postCmd = `node "${rootNorm}/hooks/handlers/post-tool-use.mjs"`;
|
|
550
|
+
|
|
551
|
+
let doc = {};
|
|
552
|
+
if (fs.existsSync(settingsFile)) {
|
|
553
|
+
try {
|
|
554
|
+
const parsed = JSON.parse(fs.readFileSync(settingsFile, 'utf8'));
|
|
555
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
556
|
+
doc = { ...parsed };
|
|
557
|
+
}
|
|
558
|
+
} catch {
|
|
559
|
+
doc = {};
|
|
560
|
+
}
|
|
561
|
+
}
|
|
562
|
+
|
|
563
|
+
// Safeguard: never introduce disableAllHooks: true
|
|
564
|
+
const hooksObj =
|
|
565
|
+
doc.hooks && typeof doc.hooks === 'object' && !Array.isArray(doc.hooks)
|
|
566
|
+
? { ...doc.hooks }
|
|
567
|
+
: {};
|
|
568
|
+
|
|
569
|
+
const preservedPre = Array.isArray(hooksObj.PreToolUse)
|
|
570
|
+
? hooksObj.PreToolUse.filter((entry) => !isCtxtopClaudeEntry(entry))
|
|
571
|
+
: [];
|
|
572
|
+
const preservedPost = Array.isArray(hooksObj.PostToolUse)
|
|
573
|
+
? hooksObj.PostToolUse.filter((entry) => !isCtxtopClaudeEntry(entry))
|
|
574
|
+
: [];
|
|
575
|
+
|
|
576
|
+
if (mode === 'enable') {
|
|
577
|
+
hooksObj.PreToolUse = [
|
|
578
|
+
...preservedPre,
|
|
579
|
+
{
|
|
580
|
+
matcher: 'Bash|PowerShell|Edit|MultiEdit|Write|NotebookEdit|Read|Grep|Glob|Task|Agent|WebFetch|mcp__.*',
|
|
581
|
+
hooks: [{ type: 'command', command: preCmd }]
|
|
582
|
+
}
|
|
583
|
+
];
|
|
584
|
+
hooksObj.PostToolUse = [
|
|
585
|
+
...preservedPost,
|
|
586
|
+
{
|
|
587
|
+
matcher: 'Bash|PowerShell|Grep|Glob|Task|Agent|WebFetch|mcp__.*',
|
|
588
|
+
hooks: [{ type: 'command', command: postCmd }]
|
|
589
|
+
}
|
|
590
|
+
];
|
|
591
|
+
doc.hooks = hooksObj;
|
|
592
|
+
fs.mkdirSync(path.dirname(settingsFile), { recursive: true });
|
|
593
|
+
atomicWriteFileSync(settingsFile, `${JSON.stringify(doc, null, 2)}\n`);
|
|
594
|
+
} else if (fs.existsSync(settingsFile)) {
|
|
595
|
+
if (preservedPre.length > 0) hooksObj.PreToolUse = preservedPre;
|
|
596
|
+
else delete hooksObj.PreToolUse;
|
|
597
|
+
if (preservedPost.length > 0) hooksObj.PostToolUse = preservedPost;
|
|
598
|
+
else delete hooksObj.PostToolUse;
|
|
599
|
+
doc.hooks = hooksObj;
|
|
600
|
+
atomicWriteFileSync(settingsFile, `${JSON.stringify(doc, null, 2)}\n`);
|
|
601
|
+
}
|
|
602
|
+
|
|
603
|
+
return { settingsPath: settingsFile, document: doc };
|
|
604
|
+
}
|
|
605
|
+
|
|
606
|
+
/**
|
|
607
|
+
* Runs a deterministic synthetic self-test verifying indexer + read-guard behavior (`< 50ms`).
|
|
608
|
+
*
|
|
609
|
+
* @returns {{ ok: boolean, elapsedMs: number, detail: string }}
|
|
610
|
+
*/
|
|
611
|
+
export function runShieldSelfTest() {
|
|
612
|
+
const start = performance.now();
|
|
613
|
+
const tmpDir = fs.mkdtempSync(path.join(os.tmpdir(), 'ctxtop-shield-selftest-'));
|
|
614
|
+
try {
|
|
615
|
+
const sampleFile = path.join(tmpDir, 'large_fixture.mjs');
|
|
616
|
+
const body = Array.from(
|
|
617
|
+
{ length: 1250 },
|
|
618
|
+
(_, idx) =>
|
|
619
|
+
idx % 250 === 0
|
|
620
|
+
? `export function sectionHandler_${idx}(requestContext) { return requestContext; }`
|
|
621
|
+
: ` const stepMetric_${idx} = ${idx};`
|
|
622
|
+
).join('\n');
|
|
623
|
+
fs.writeFileSync(sampleFile, body, 'utf8');
|
|
624
|
+
|
|
625
|
+
const denied = evaluateShieldReadGuard({
|
|
626
|
+
platform: 'claude',
|
|
627
|
+
sessionId: 'selftest',
|
|
628
|
+
cwd: tmpDir,
|
|
629
|
+
filePath: sampleFile,
|
|
630
|
+
hasSliceBounds: false,
|
|
631
|
+
forceActive: true,
|
|
632
|
+
recordLedger: false
|
|
633
|
+
});
|
|
634
|
+
const allowedSliced = evaluateShieldReadGuard({
|
|
635
|
+
platform: 'claude',
|
|
636
|
+
sessionId: 'selftest',
|
|
637
|
+
cwd: tmpDir,
|
|
638
|
+
filePath: sampleFile,
|
|
639
|
+
hasSliceBounds: true,
|
|
640
|
+
forceActive: true,
|
|
641
|
+
recordLedger: false
|
|
642
|
+
});
|
|
643
|
+
|
|
644
|
+
const elapsedMs = Number((performance.now() - start).toFixed(2));
|
|
645
|
+
const ok =
|
|
646
|
+
denied.action === 'deny' &&
|
|
647
|
+
Boolean(denied.indexPath && fs.existsSync(denied.indexPath)) &&
|
|
648
|
+
allowedSliced.action === 'allow';
|
|
649
|
+
return {
|
|
650
|
+
ok,
|
|
651
|
+
elapsedMs,
|
|
652
|
+
detail: ok
|
|
653
|
+
? `Self-test passed in ${elapsedMs}ms (1,250-line un-sliced read blocked + .index.md generated; sliced read allowed)`
|
|
654
|
+
: `Self-test failed (denied=${denied.action}, sliced=${allowedSliced.action})`
|
|
655
|
+
};
|
|
656
|
+
} finally {
|
|
657
|
+
try {
|
|
658
|
+
fs.rmSync(tmpDir, { recursive: true, force: true });
|
|
659
|
+
} catch {
|
|
660
|
+
// Ignore cleanup race
|
|
661
|
+
}
|
|
662
|
+
}
|
|
663
|
+
}
|
|
664
|
+
|
|
665
|
+
/**
|
|
666
|
+
* Aggregates Active Context Shield status and unified Session ROI metrics from
|
|
667
|
+
* `savedQuotaLedger.mjs` (`horizon_ledger.jsonl`) and `.agents/telemetry/*.hints.jsonl`.
|
|
668
|
+
*
|
|
669
|
+
* @param {object} [options={}]
|
|
670
|
+
*/
|
|
671
|
+
export function getShieldStatus(options = {}) {
|
|
672
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
673
|
+
const cfg = loadShieldConfig({ ...options, cwd: baseCwd });
|
|
674
|
+
const agHooksPath = path.join(baseCwd, '.agents', 'hooks.json');
|
|
675
|
+
const claudeSettingsPath = path.join(baseCwd, '.claude', 'settings.json');
|
|
676
|
+
|
|
677
|
+
let agConfigured = false;
|
|
678
|
+
if (fs.existsSync(agHooksPath)) {
|
|
679
|
+
try {
|
|
680
|
+
const parsed = JSON.parse(fs.readFileSync(agHooksPath, 'utf8'));
|
|
681
|
+
agConfigured = Boolean(parsed?.['ctxtop-read-guard']);
|
|
682
|
+
} catch {
|
|
683
|
+
agConfigured = false;
|
|
684
|
+
}
|
|
685
|
+
}
|
|
686
|
+
|
|
687
|
+
let claudeConfigured = false;
|
|
688
|
+
if (fs.existsSync(claudeSettingsPath)) {
|
|
689
|
+
try {
|
|
690
|
+
const parsed = JSON.parse(fs.readFileSync(claudeSettingsPath, 'utf8'));
|
|
691
|
+
const preArr = parsed?.hooks?.PreToolUse;
|
|
692
|
+
claudeConfigured = Array.isArray(preArr) && preArr.some((e) => isCtxtopClaudeEntry(e));
|
|
693
|
+
} catch {
|
|
694
|
+
claudeConfigured = false;
|
|
695
|
+
}
|
|
696
|
+
}
|
|
697
|
+
|
|
698
|
+
const ledgerSummary = getSavedQuotaReceiptSummary({
|
|
699
|
+
cwd: baseCwd,
|
|
700
|
+
...(options.homeDir ? { homeDir: options.homeDir } : {}),
|
|
701
|
+
...(options.ledgerPath ? { ledgerPath: options.ledgerPath } : {})
|
|
702
|
+
});
|
|
703
|
+
|
|
704
|
+
let readsBlocked = 0;
|
|
705
|
+
let logsCompacted = 0;
|
|
706
|
+
let thrashStopped = 0;
|
|
707
|
+
let hintTokensSaved = 0;
|
|
708
|
+
let hintDollarsSaved = 0;
|
|
709
|
+
let shadowHits = 0;
|
|
710
|
+
let shadowTokensSavedEst = 0;
|
|
711
|
+
let shadowDollarsSavedEst = 0;
|
|
712
|
+
const shadowByGuardrail = {};
|
|
713
|
+
let coachHits = 0;
|
|
714
|
+
let coachTokensSaved = 0;
|
|
715
|
+
let coachDollarsSaved = 0;
|
|
716
|
+
const coachByGuardrail = {};
|
|
717
|
+
|
|
718
|
+
const telemetryDir = path.join(baseCwd, '.agents', 'telemetry');
|
|
719
|
+
if (fs.existsSync(telemetryDir)) {
|
|
720
|
+
try {
|
|
721
|
+
for (const name of fs.readdirSync(telemetryDir)) {
|
|
722
|
+
if (!name.endsWith('.hints.jsonl')) continue;
|
|
723
|
+
const lines = fs
|
|
724
|
+
.readFileSync(path.join(telemetryDir, name), 'utf8')
|
|
725
|
+
.split(/\r?\n/)
|
|
726
|
+
.filter(Boolean);
|
|
727
|
+
for (const line of lines) {
|
|
728
|
+
try {
|
|
729
|
+
const row = JSON.parse(line);
|
|
730
|
+
if (row.schema === 'bucket_b_shadow_v1') {
|
|
731
|
+
if (row.wouldTrigger) {
|
|
732
|
+
const gid = String(row.guardrailId || 'UNKNOWN');
|
|
733
|
+
const tokEst = Math.max(0, Number(row.tokens_saved_est || 0));
|
|
734
|
+
const usdEst = Math.max(0, Number(row.dollars_saved_est || 0));
|
|
735
|
+
if (row.stage === 'COACH' || row.stage === 'ENFORCE') {
|
|
736
|
+
coachHits += 1;
|
|
737
|
+
coachByGuardrail[gid] = (coachByGuardrail[gid] || 0) + 1;
|
|
738
|
+
coachTokensSaved += tokEst;
|
|
739
|
+
coachDollarsSaved += usdEst;
|
|
740
|
+
hintTokensSaved += tokEst;
|
|
741
|
+
hintDollarsSaved += usdEst;
|
|
742
|
+
} else {
|
|
743
|
+
shadowHits += 1;
|
|
744
|
+
shadowByGuardrail[gid] = (shadowByGuardrail[gid] || 0) + 1;
|
|
745
|
+
shadowTokensSavedEst += tokEst;
|
|
746
|
+
shadowDollarsSavedEst += usdEst;
|
|
747
|
+
}
|
|
748
|
+
}
|
|
749
|
+
continue;
|
|
750
|
+
}
|
|
751
|
+
if (row.event === 'blocked_unsliced_read') readsBlocked += 1;
|
|
752
|
+
else if (row.event === 'truncated_tail_output') logsCompacted += 1;
|
|
753
|
+
else if (row.event === 'thrash_3x_breaker') thrashStopped += 1;
|
|
754
|
+
hintTokensSaved += Math.max(0, Number(row.tokens_saved_est || 0));
|
|
755
|
+
hintDollarsSaved += Math.max(0, Number(row.dollars_saved_est || 0));
|
|
756
|
+
} catch {
|
|
757
|
+
// Skip malformed hint row
|
|
758
|
+
}
|
|
759
|
+
}
|
|
760
|
+
}
|
|
761
|
+
} catch {
|
|
762
|
+
// Non-fatal
|
|
763
|
+
}
|
|
764
|
+
}
|
|
765
|
+
|
|
766
|
+
const tokensSaved = Math.max(
|
|
767
|
+
Number(ledgerSummary.workspace30dSavedTokens || 0),
|
|
768
|
+
hintTokensSaved
|
|
769
|
+
);
|
|
770
|
+
const dollarsSaved = Number(
|
|
771
|
+
Math.max(Number(ledgerSummary.workspace30dSavedUSD || 0), hintDollarsSaved).toFixed(4)
|
|
772
|
+
);
|
|
773
|
+
|
|
774
|
+
return {
|
|
775
|
+
enabled: cfg.enabled,
|
|
776
|
+
platforms: cfg.platforms,
|
|
777
|
+
maxUnslicedLines: cfg.maxUnslicedLines,
|
|
778
|
+
cliffMaxUnslicedLines: cfg.cliffMaxUnslicedLines,
|
|
779
|
+
configPath: cfg.configPath,
|
|
780
|
+
hooksConfigured: {
|
|
781
|
+
antigravity: agConfigured,
|
|
782
|
+
claude: claudeConfigured
|
|
783
|
+
},
|
|
784
|
+
roi: {
|
|
785
|
+
tokensSaved,
|
|
786
|
+
dollarsSaved,
|
|
787
|
+
readsBlocked,
|
|
788
|
+
logsCompacted,
|
|
789
|
+
thrashStopped,
|
|
790
|
+
bucketBCoach: {
|
|
791
|
+
hits: coachHits,
|
|
792
|
+
tokensSaved: Math.round(coachTokensSaved),
|
|
793
|
+
dollarsSaved: Number(coachDollarsSaved.toFixed(4)),
|
|
794
|
+
byGuardrail: coachByGuardrail
|
|
795
|
+
},
|
|
796
|
+
bucketBShadow: {
|
|
797
|
+
hits: shadowHits,
|
|
798
|
+
tokensSavedEst: Math.round(shadowTokensSavedEst),
|
|
799
|
+
dollarsSavedEst: Number(shadowDollarsSavedEst.toFixed(4)),
|
|
800
|
+
byGuardrail: shadowByGuardrail
|
|
801
|
+
}
|
|
802
|
+
}
|
|
803
|
+
};
|
|
804
|
+
}
|
|
805
|
+
|
|
806
|
+
/**
|
|
807
|
+
* Executes `ctxtop shield <--enable | --disable | --status> [--platform all|antigravity|claude]`.
|
|
808
|
+
*
|
|
809
|
+
* @param {object} [options={}]
|
|
810
|
+
* @param {'enable' | 'disable' | 'status'} [options.action='status']
|
|
811
|
+
* @param {'all' | 'antigravity' | 'claude'} [options.platform='all']
|
|
812
|
+
* @param {string} [options.cwd]
|
|
813
|
+
* @param {number} [options.maxUnslicedLines]
|
|
814
|
+
*/
|
|
815
|
+
export function configureShield(options = {}) {
|
|
816
|
+
const action = String(options.action || 'status').toLowerCase();
|
|
817
|
+
const platform = String(options.platform || 'all').toLowerCase();
|
|
818
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
819
|
+
const pkgRoot = options.pkgRoot || PKG_ROOT;
|
|
820
|
+
|
|
821
|
+
if (action === 'status') {
|
|
822
|
+
return {
|
|
823
|
+
ok: true,
|
|
824
|
+
action: 'status',
|
|
825
|
+
platform,
|
|
826
|
+
...getShieldStatus({ ...options, cwd: baseCwd })
|
|
827
|
+
};
|
|
828
|
+
}
|
|
829
|
+
|
|
830
|
+
const targetAg = platform === 'all' || platform === 'antigravity';
|
|
831
|
+
const targetClaude = platform === 'all' || platform === 'claude';
|
|
832
|
+
const current = loadShieldConfig({ ...options, cwd: baseCwd });
|
|
833
|
+
|
|
834
|
+
if (action === 'enable') {
|
|
835
|
+
ensureLocalGitExclude(baseCwd);
|
|
836
|
+
const nextPlatforms = {
|
|
837
|
+
antigravity: targetAg ? true : current.platforms.antigravity,
|
|
838
|
+
claude: targetClaude ? true : current.platforms.claude
|
|
839
|
+
};
|
|
840
|
+
saveShieldConfig(
|
|
841
|
+
{
|
|
842
|
+
enabled: true,
|
|
843
|
+
platforms: nextPlatforms,
|
|
844
|
+
...(options.maxUnslicedLines ? { maxUnslicedLines: options.maxUnslicedLines } : {})
|
|
845
|
+
},
|
|
846
|
+
{ ...options, cwd: baseCwd }
|
|
847
|
+
);
|
|
848
|
+
if (targetAg) {
|
|
849
|
+
syncAntigravityShieldHooks({ mode: 'enable', cwd: baseCwd, pkgRoot });
|
|
850
|
+
}
|
|
851
|
+
if (targetClaude) {
|
|
852
|
+
syncClaudeShieldHooks({ mode: 'enable', cwd: baseCwd, pkgRoot });
|
|
853
|
+
if (options.syncIdleDrain !== false) {
|
|
854
|
+
syncClaudeIdleDrainSettings({ cwd: baseCwd });
|
|
855
|
+
}
|
|
856
|
+
}
|
|
857
|
+
const selfTest = runShieldSelfTest();
|
|
858
|
+
const status = getShieldStatus({ ...options, cwd: baseCwd });
|
|
859
|
+
return {
|
|
860
|
+
ok: selfTest.ok,
|
|
861
|
+
action: 'enable',
|
|
862
|
+
platform,
|
|
863
|
+
selfTest,
|
|
864
|
+
...status
|
|
865
|
+
};
|
|
866
|
+
}
|
|
867
|
+
|
|
868
|
+
if (action === 'disable') {
|
|
869
|
+
const nextPlatforms = {
|
|
870
|
+
antigravity: targetAg ? false : current.platforms.antigravity,
|
|
871
|
+
claude: targetClaude ? false : current.platforms.claude
|
|
872
|
+
};
|
|
873
|
+
const stillEnabled = Boolean(nextPlatforms.antigravity || nextPlatforms.claude);
|
|
874
|
+
saveShieldConfig(
|
|
875
|
+
{
|
|
876
|
+
enabled: stillEnabled,
|
|
877
|
+
platforms: nextPlatforms
|
|
878
|
+
},
|
|
879
|
+
{ ...options, cwd: baseCwd }
|
|
880
|
+
);
|
|
881
|
+
if (targetAg) {
|
|
882
|
+
syncAntigravityShieldHooks({ mode: 'disable', cwd: baseCwd, pkgRoot });
|
|
883
|
+
}
|
|
884
|
+
if (targetClaude) {
|
|
885
|
+
syncClaudeShieldHooks({ mode: 'disable', cwd: baseCwd, pkgRoot });
|
|
886
|
+
}
|
|
887
|
+
const status = getShieldStatus({ ...options, cwd: baseCwd });
|
|
888
|
+
return {
|
|
889
|
+
ok: true,
|
|
890
|
+
action: 'disable',
|
|
891
|
+
platform,
|
|
892
|
+
...status
|
|
893
|
+
};
|
|
894
|
+
}
|
|
895
|
+
|
|
896
|
+
return {
|
|
897
|
+
ok: false,
|
|
898
|
+
action,
|
|
899
|
+
reason: `Unknown shield action: ${action}`
|
|
900
|
+
};
|
|
901
|
+
}
|
|
902
|
+
|
|
903
|
+
/**
|
|
904
|
+
* Non-destructively merges idle token-drain protections into `.claude/settings.local.json`:
|
|
905
|
+
* - `env.CLAUDE_CODE_GOAL_CHECKIN_MINUTES = "0"`
|
|
906
|
+
* - `crossSessionInbound = "hold"`
|
|
907
|
+
* - `idleCompaction = false`
|
|
908
|
+
*
|
|
909
|
+
* @param {object} [options={}]
|
|
910
|
+
*/
|
|
911
|
+
export function syncClaudeIdleDrainSettings(options = {}) {
|
|
912
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
913
|
+
const localSettingsPath = path.join(baseCwd, '.claude', 'settings.local.json');
|
|
914
|
+
let existing = {};
|
|
915
|
+
if (fs.existsSync(localSettingsPath)) {
|
|
916
|
+
try {
|
|
917
|
+
const parsed = JSON.parse(fs.readFileSync(localSettingsPath, 'utf8'));
|
|
918
|
+
if (parsed && typeof parsed === 'object' && !Array.isArray(parsed)) {
|
|
919
|
+
existing = parsed;
|
|
920
|
+
}
|
|
921
|
+
} catch {
|
|
922
|
+
existing = {};
|
|
923
|
+
}
|
|
924
|
+
}
|
|
925
|
+
const envObj =
|
|
926
|
+
existing.env && typeof existing.env === 'object' && !Array.isArray(existing.env)
|
|
927
|
+
? { ...existing.env }
|
|
928
|
+
: {};
|
|
929
|
+
if (envObj.CLAUDE_CODE_GOAL_CHECKIN_MINUTES === undefined) {
|
|
930
|
+
envObj.CLAUDE_CODE_GOAL_CHECKIN_MINUTES = '0';
|
|
931
|
+
}
|
|
932
|
+
const next = {
|
|
933
|
+
...existing,
|
|
934
|
+
env: envObj,
|
|
935
|
+
crossSessionInbound:
|
|
936
|
+
existing.crossSessionInbound !== undefined ? existing.crossSessionInbound : 'hold',
|
|
937
|
+
idleCompaction:
|
|
938
|
+
typeof existing.idleCompaction === 'boolean' ? existing.idleCompaction : false
|
|
939
|
+
};
|
|
940
|
+
fs.mkdirSync(path.dirname(localSettingsPath), { recursive: true });
|
|
941
|
+
atomicWriteFileSync(localSettingsPath, `${JSON.stringify(next, null, 2)}\n`);
|
|
942
|
+
return {
|
|
943
|
+
updated: true,
|
|
944
|
+
settingsLocalPath: localSettingsPath,
|
|
945
|
+
settings: next
|
|
946
|
+
};
|
|
947
|
+
}
|
|
948
|
+
|
|
949
|
+
/**
|
|
950
|
+
* Audits `.claude/settings.local.json` (and `.claude/settings.json`) for idle-drain exposure.
|
|
951
|
+
* Only triggers an advisory when `.claude/settings.local.json` (or explicit settings) contains
|
|
952
|
+
* an enabled idle check-in / auto-inbound / idleCompaction drain, or when `requireExplicitGuard` is true.
|
|
953
|
+
*
|
|
954
|
+
* @param {object} [options={}]
|
|
955
|
+
*/
|
|
956
|
+
export function auditClaudeIdleDrainSettings(options = {}) {
|
|
957
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
958
|
+
const localPath = path.join(baseCwd, '.claude', 'settings.local.json');
|
|
959
|
+
const sharedPath = path.join(baseCwd, '.claude', 'settings.json');
|
|
960
|
+
const readSafe = (p) => {
|
|
961
|
+
if (!fs.existsSync(p)) return null;
|
|
962
|
+
try {
|
|
963
|
+
const parsed = JSON.parse(fs.readFileSync(p, 'utf8'));
|
|
964
|
+
return parsed && typeof parsed === 'object' ? parsed : null;
|
|
965
|
+
} catch {
|
|
966
|
+
return null;
|
|
967
|
+
}
|
|
968
|
+
};
|
|
969
|
+
const local = readSafe(localPath);
|
|
970
|
+
const shared = readSafe(sharedPath);
|
|
971
|
+
if (!local && !shared && !options.requireExplicitGuard) {
|
|
972
|
+
return { triggered: false, issues: [], advisory: null };
|
|
973
|
+
}
|
|
974
|
+
const merged = { ...(shared || {}), ...(local || {}) };
|
|
975
|
+
const mergedEnv = { ...(shared?.env || {}), ...(local?.env || {}) };
|
|
976
|
+
const issues = [];
|
|
977
|
+
|
|
978
|
+
const checkinRaw = mergedEnv.CLAUDE_CODE_GOAL_CHECKIN_MINUTES;
|
|
979
|
+
if (checkinRaw !== undefined && String(checkinRaw) !== '0') {
|
|
980
|
+
issues.push(`CLAUDE_CODE_GOAL_CHECKIN_MINUTES=${checkinRaw} (set "0" to stop idle goal check-ins)`);
|
|
981
|
+
} else if (options.requireExplicitGuard && checkinRaw === undefined) {
|
|
982
|
+
issues.push('CLAUDE_CODE_GOAL_CHECKIN_MINUTES unset (recommend "0")');
|
|
983
|
+
}
|
|
984
|
+
|
|
985
|
+
if (merged.crossSessionInbound && merged.crossSessionInbound !== 'hold') {
|
|
986
|
+
issues.push(`crossSessionInbound="${merged.crossSessionInbound}" (set "hold" to prevent idle cache wakeups)`);
|
|
987
|
+
} else if (options.requireExplicitGuard && merged.crossSessionInbound === undefined) {
|
|
988
|
+
issues.push('crossSessionInbound unset (recommend "hold")');
|
|
989
|
+
}
|
|
990
|
+
|
|
991
|
+
if (merged.idleCompaction === true) {
|
|
992
|
+
issues.push('idleCompaction=true (set false to avoid background summarization burn)');
|
|
993
|
+
} else if (options.requireExplicitGuard && merged.idleCompaction === undefined) {
|
|
994
|
+
issues.push('idleCompaction unset (recommend false)');
|
|
995
|
+
}
|
|
996
|
+
|
|
997
|
+
if (issues.length === 0) {
|
|
998
|
+
return { triggered: false, issues: [], advisory: null };
|
|
999
|
+
}
|
|
1000
|
+
return {
|
|
1001
|
+
triggered: true,
|
|
1002
|
+
issues,
|
|
1003
|
+
advisory:
|
|
1004
|
+
`[Highbeam Quota Shield — Idle Drain Guard (#10)] ${issues.join('; ')}. ` +
|
|
1005
|
+
`Run "npx ctxtop shield --enable" to lock .claude/settings.local.json against background token drain.`
|
|
1006
|
+
};
|
|
1007
|
+
}
|
|
1008
|
+
|
|
1009
|
+
/**
|
|
1010
|
+
* Audits `.claude/agents/*.md` YAML frontmatter for missing or unsafe `autoCompactWindow` caps
|
|
1011
|
+
* (`<= 90000` on Haiku subagents, `<= 180000` on Sonnet/Opus/Gemini Pro subagents).
|
|
1012
|
+
*
|
|
1013
|
+
* @param {object} [options={}]
|
|
1014
|
+
*/
|
|
1015
|
+
export function auditClaudeAgentAutoCompactWindows(options = {}) {
|
|
1016
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
1017
|
+
const agentsDir = path.join(baseCwd, '.claude', 'agents');
|
|
1018
|
+
if (!fs.existsSync(agentsDir)) {
|
|
1019
|
+
return { triggered: false, unguardedAgents: [], advisory: null };
|
|
1020
|
+
}
|
|
1021
|
+
const unguardedAgents = [];
|
|
1022
|
+
try {
|
|
1023
|
+
const entries = fs.readdirSync(agentsDir, { withFileTypes: true });
|
|
1024
|
+
for (const entry of entries) {
|
|
1025
|
+
if (!entry.isFile() || !entry.name.endsWith('.md')) continue;
|
|
1026
|
+
const fullPath = path.join(agentsDir, entry.name);
|
|
1027
|
+
const raw = fs.readFileSync(fullPath, 'utf8');
|
|
1028
|
+
const fmMatch = raw.match(/^---\r?\n([\s\S]*?)\r?\n---/);
|
|
1029
|
+
const fm = fmMatch ? fmMatch[1] : '';
|
|
1030
|
+
const modelMatch = fm.match(/^\s*model\s*:\s*([^\r\n#]+)/im);
|
|
1031
|
+
const windowMatch = fm.match(/^\s*autoCompactWindow\s*:\s*(\d+)/im);
|
|
1032
|
+
const modelStr = modelMatch ? modelMatch[1].trim().replace(/^['"]|['"]$/g, '') : '';
|
|
1033
|
+
const isHaiku = /haiku/i.test(modelStr);
|
|
1034
|
+
const recommendedMax = isHaiku ? 90000 : 180000;
|
|
1035
|
+
const configuredWindow = windowMatch ? Number(windowMatch[1]) : null;
|
|
1036
|
+
if (configuredWindow === null || configuredWindow > recommendedMax) {
|
|
1037
|
+
unguardedAgents.push({
|
|
1038
|
+
file: `.claude/agents/${entry.name}`,
|
|
1039
|
+
model: modelStr || 'inherit',
|
|
1040
|
+
configuredWindow,
|
|
1041
|
+
recommendedMax
|
|
1042
|
+
});
|
|
1043
|
+
}
|
|
1044
|
+
}
|
|
1045
|
+
} catch {
|
|
1046
|
+
return { triggered: false, unguardedAgents: [], advisory: null };
|
|
1047
|
+
}
|
|
1048
|
+
|
|
1049
|
+
if (unguardedAgents.length === 0) {
|
|
1050
|
+
return { triggered: false, unguardedAgents: [], advisory: null };
|
|
1051
|
+
}
|
|
1052
|
+
const summary = unguardedAgents
|
|
1053
|
+
.slice(0, 4)
|
|
1054
|
+
.map(
|
|
1055
|
+
(a) =>
|
|
1056
|
+
`${a.file} (${a.configuredWindow === null ? 'missing' : a.configuredWindow} -> <=${a.recommendedMax})`
|
|
1057
|
+
)
|
|
1058
|
+
.join(', ');
|
|
1059
|
+
return {
|
|
1060
|
+
triggered: true,
|
|
1061
|
+
unguardedAgents,
|
|
1062
|
+
advisory:
|
|
1063
|
+
`[Highbeam Quota Shield — Pricing Cliff Cap (#7)] Subagent frontmatter missing safe autoCompactWindow: ${summary}. ` +
|
|
1064
|
+
`Pin autoCompactWindow: 90000 (Haiku 100K 5x cliff) or 180000 (200K 2x cliff) to prevent cliff overruns.`
|
|
1065
|
+
};
|
|
1066
|
+
}
|
|
1067
|
+
|
|
1068
|
+
/**
|
|
1069
|
+
* Item A2 (#3): Records a fast (<12ms) SHA-256 + assertion/skip count baseline of workspace test files
|
|
1070
|
+
* at `SessionStart` into `.agents/telemetry/<sessionId>.test_hashes.json`.
|
|
1071
|
+
* Strictly skips `packages/airlock/`, `node_modules/`, `.git/`, `.agents/`, and `.claude/`.
|
|
1072
|
+
*
|
|
1073
|
+
* @param {object} [options={}]
|
|
1074
|
+
*/
|
|
1075
|
+
export function snapshotWorkspaceTestHashes(options = {}) {
|
|
1076
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
1077
|
+
const sessionId = String(options.sessionId || 'default')
|
|
1078
|
+
.replace(/[^a-zA-Z0-9._-]/g, '_')
|
|
1079
|
+
.slice(0, 80);
|
|
1080
|
+
const maxFiles = Math.max(1, Number(options.maxFiles || 400));
|
|
1081
|
+
const deadlineMs = Date.now() + Number(options.budgetMs || 18);
|
|
1082
|
+
const skipDirs = new Set([
|
|
1083
|
+
'.git',
|
|
1084
|
+
'node_modules',
|
|
1085
|
+
'.agents',
|
|
1086
|
+
'.claude',
|
|
1087
|
+
'dist',
|
|
1088
|
+
'build',
|
|
1089
|
+
'out',
|
|
1090
|
+
'.next',
|
|
1091
|
+
'coverage',
|
|
1092
|
+
'airlock'
|
|
1093
|
+
]);
|
|
1094
|
+
const files = {};
|
|
1095
|
+
let scannedCount = 0;
|
|
1096
|
+
|
|
1097
|
+
const isTestName = (relPosix) =>
|
|
1098
|
+
/\.(?:test|spec)\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
|
|
1099
|
+
/(?:^|\/)(?:test|tests|__tests__)\/.*\.(?:[cm]?[jt]sx?|py|go|rs)$/i.test(relPosix) ||
|
|
1100
|
+
/_test\.(?:py|go)$/i.test(relPosix);
|
|
1101
|
+
|
|
1102
|
+
const walk = (dir, depth) => {
|
|
1103
|
+
if (depth > 4 || scannedCount >= maxFiles || Date.now() > deadlineMs) return;
|
|
1104
|
+
let entries;
|
|
1105
|
+
try {
|
|
1106
|
+
entries = fs.readdirSync(dir, { withFileTypes: true });
|
|
1107
|
+
} catch {
|
|
1108
|
+
return;
|
|
1109
|
+
}
|
|
1110
|
+
for (const entry of entries) {
|
|
1111
|
+
if (scannedCount >= maxFiles || Date.now() > deadlineMs) break;
|
|
1112
|
+
const fullPath = path.join(dir, entry.name);
|
|
1113
|
+
const relPosix = path.relative(baseCwd, fullPath).replace(/\\/g, '/');
|
|
1114
|
+
if (relPosix === 'packages/airlock' || relPosix.startsWith('packages/airlock/')) continue;
|
|
1115
|
+
if (entry.isDirectory()) {
|
|
1116
|
+
if (skipDirs.has(entry.name)) continue;
|
|
1117
|
+
walk(fullPath, depth + 1);
|
|
1118
|
+
} else if (entry.isFile() && isTestName(relPosix)) {
|
|
1119
|
+
try {
|
|
1120
|
+
const stat = fs.statSync(fullPath);
|
|
1121
|
+
if (stat.size > 512 * 1024) continue;
|
|
1122
|
+
const raw = fs.readFileSync(fullPath, 'utf8');
|
|
1123
|
+
const sha256 = crypto.createHash('sha256').update(raw).digest('hex');
|
|
1124
|
+
const assertionCount =
|
|
1125
|
+
(raw.match(/\b(?:assert(?:\.[a-zA-Z0-9_]+)?\s*\(|expect\s*\(|should\.|assert_eq!\s*\()/g) || []).length +
|
|
1126
|
+
(raw.match(/^\s*assert\s+\S+/gm) || []).length;
|
|
1127
|
+
const skipCount =
|
|
1128
|
+
(raw.match(/(?:\.(?:skip|todo)\s*\(|\b(?:xit|xdescribe|xtest)\s*\(|@pytest\.mark\.skip(?:if)?\b|#\[\s*ignore\b)/g) || []).length;
|
|
1129
|
+
files[relPosix] = {
|
|
1130
|
+
sha256,
|
|
1131
|
+
assertionCount,
|
|
1132
|
+
skipCount,
|
|
1133
|
+
bytes: stat.size
|
|
1134
|
+
};
|
|
1135
|
+
scannedCount += 1;
|
|
1136
|
+
} catch {
|
|
1137
|
+
// Skip unreadable file
|
|
1138
|
+
}
|
|
1139
|
+
}
|
|
1140
|
+
}
|
|
1141
|
+
};
|
|
1142
|
+
|
|
1143
|
+
walk(baseCwd, 0);
|
|
1144
|
+
const outPath = path.join(baseCwd, '.agents', 'telemetry', `${sessionId}.test_hashes.json`);
|
|
1145
|
+
try {
|
|
1146
|
+
fs.mkdirSync(path.dirname(outPath), { recursive: true });
|
|
1147
|
+
atomicWriteFileSync(
|
|
1148
|
+
outPath,
|
|
1149
|
+
`${JSON.stringify(
|
|
1150
|
+
{
|
|
1151
|
+
schemaVersion: '2026.11.1',
|
|
1152
|
+
sessionId,
|
|
1153
|
+
recordedAt: new Date().toISOString(),
|
|
1154
|
+
fileCount: scannedCount,
|
|
1155
|
+
files
|
|
1156
|
+
},
|
|
1157
|
+
null,
|
|
1158
|
+
2
|
|
1159
|
+
)}\n`
|
|
1160
|
+
);
|
|
1161
|
+
} catch {
|
|
1162
|
+
// Non-fatal on read-only FS
|
|
1163
|
+
}
|
|
1164
|
+
|
|
1165
|
+
return {
|
|
1166
|
+
snapshotPath: outPath,
|
|
1167
|
+
fileCount: scannedCount,
|
|
1168
|
+
files
|
|
1169
|
+
};
|
|
1170
|
+
}
|
|
1171
|
+
|
|
1172
|
+
/**
|
|
1173
|
+
* Item A5 (#15): Audits Claude Code `MEMORY.md` (`>200` lines or `>25,600` bytes `25KB` silent host truncation cap).
|
|
1174
|
+
*
|
|
1175
|
+
* @param {object} [options={}]
|
|
1176
|
+
*/
|
|
1177
|
+
export function auditClaudeAutoMemory(options = {}) {
|
|
1178
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
1179
|
+
const homeDir = options.homeDir || os.homedir();
|
|
1180
|
+
const candidates = [];
|
|
1181
|
+
|
|
1182
|
+
if (options.memoryFilePath) {
|
|
1183
|
+
candidates.push(path.resolve(options.memoryFilePath));
|
|
1184
|
+
}
|
|
1185
|
+
if (options.memoryDir) {
|
|
1186
|
+
candidates.push(path.join(path.resolve(options.memoryDir), 'MEMORY.md'));
|
|
1187
|
+
}
|
|
1188
|
+
candidates.push(path.join(baseCwd, '.claude', 'memory', 'MEMORY.md'));
|
|
1189
|
+
|
|
1190
|
+
// Resolve `~/.claude/projects/<projectSlug>/memory/MEMORY.md`
|
|
1191
|
+
const slugVariants = new Set([
|
|
1192
|
+
baseCwd.replace(/[:\\/]+/g, '-').replace(/^-+/, ''),
|
|
1193
|
+
`-${baseCwd.replace(/[:\\/]+/g, '-').replace(/^-+/, '')}`
|
|
1194
|
+
]);
|
|
1195
|
+
for (const slug of slugVariants) {
|
|
1196
|
+
candidates.push(path.join(homeDir, '.claude', 'projects', slug, 'memory', 'MEMORY.md'));
|
|
1197
|
+
}
|
|
1198
|
+
|
|
1199
|
+
const seen = new Set();
|
|
1200
|
+
const issues = [];
|
|
1201
|
+
let maxLines = 0;
|
|
1202
|
+
let maxBytes = 0;
|
|
1203
|
+
let inspectedPath = null;
|
|
1204
|
+
|
|
1205
|
+
for (const memPath of candidates) {
|
|
1206
|
+
const norm = memPath.replace(/\\/g, '/').toLowerCase();
|
|
1207
|
+
if (seen.has(norm) || !fs.existsSync(memPath)) continue;
|
|
1208
|
+
seen.add(norm);
|
|
1209
|
+
try {
|
|
1210
|
+
const buf = fs.readFileSync(memPath);
|
|
1211
|
+
const text = buf.toString('utf8');
|
|
1212
|
+
const lines = text.split(/\r?\n/).length;
|
|
1213
|
+
const bytes = buf.byteLength;
|
|
1214
|
+
inspectedPath = memPath;
|
|
1215
|
+
if (lines > maxLines) maxLines = lines;
|
|
1216
|
+
if (bytes > maxBytes) maxBytes = bytes;
|
|
1217
|
+
if (lines > 200 || bytes > 25600) {
|
|
1218
|
+
issues.push(
|
|
1219
|
+
`MEMORY.md (${lines} lines, ${(bytes / 1024).toFixed(1)}KB) exceeds Claude Code's 200-line / 25KB (25,600B) auto-memory cap — trailing lines are silently truncated`
|
|
1220
|
+
);
|
|
1221
|
+
}
|
|
1222
|
+
} catch {
|
|
1223
|
+
// Ignore unreadable candidate
|
|
1224
|
+
}
|
|
1225
|
+
}
|
|
1226
|
+
|
|
1227
|
+
if (issues.length === 0) {
|
|
1228
|
+
return { triggered: false, inspectedPath, maxLines, maxBytes, issues: [], advisory: null };
|
|
1229
|
+
}
|
|
1230
|
+
|
|
1231
|
+
return {
|
|
1232
|
+
triggered: true,
|
|
1233
|
+
inspectedPath,
|
|
1234
|
+
maxLines,
|
|
1235
|
+
maxBytes,
|
|
1236
|
+
issues,
|
|
1237
|
+
advisory:
|
|
1238
|
+
`[Highbeam Quota Shield — Auto-Memory Truncation Guard (#15)] ${issues.join('; ')}. ` +
|
|
1239
|
+
`Move detailed notes into topic files under memory/<topic>.md and keep MEMORY.md <= 200 lines / <= 25KB.`
|
|
1240
|
+
};
|
|
1241
|
+
}
|
|
1242
|
+
|
|
1243
|
+
/**
|
|
1244
|
+
* Item A8 (#14): Multimodal `.ipynb` Base64 Stripper & Unbounded `>10`-Page `.pdf` Read Blocker.
|
|
1245
|
+
*
|
|
1246
|
+
* - For `.ipynb`: If file > 256KB or contains `image/png` / `image/jpeg` / `image/webp` base64 blobs > 16KB,
|
|
1247
|
+
* writes a sanitized copy (with code/markdown/text preserved and base64 images stripped) to
|
|
1248
|
+
* `.claude/cache/sanitized_<name>.ipynb` (Claude `updatedInput` rewrite) or `.agents/tmp/sanitized_<name>.ipynb` (Antigravity).
|
|
1249
|
+
* - For `.pdf`: Counts `/Type /Page` objects; blocks un-paged reads (or ranges > 10 pages) when `pageCount > 10`.
|
|
1250
|
+
*
|
|
1251
|
+
* @param {object} [options={}]
|
|
1252
|
+
*/
|
|
1253
|
+
export function inspectAndSanitizeMultimodalRead(options = {}) {
|
|
1254
|
+
const platform = String(options.platform || 'claude').toLowerCase();
|
|
1255
|
+
const baseCwd = path.resolve(options.cwd || process.cwd());
|
|
1256
|
+
const rawFilePath = String(options.filePath || '').trim();
|
|
1257
|
+
if (!rawFilePath) return { action: 'allow' };
|
|
1258
|
+
|
|
1259
|
+
const resolved = path.isAbsolute(rawFilePath)
|
|
1260
|
+
? rawFilePath
|
|
1261
|
+
: path.resolve(baseCwd, rawFilePath);
|
|
1262
|
+
const relCheck = path.relative(baseCwd, resolved).replace(/\\/g, '/');
|
|
1263
|
+
if (relCheck === 'packages/airlock' || relCheck.startsWith('packages/airlock/')) {
|
|
1264
|
+
return { action: 'allow' };
|
|
1265
|
+
}
|
|
1266
|
+
|
|
1267
|
+
const normLower = resolved.replace(/\\/g, '/').toLowerCase();
|
|
1268
|
+
// Never re-intercept an already sanitized notebook!
|
|
1269
|
+
if (
|
|
1270
|
+
normLower.includes('/.claude/cache/sanitized_') ||
|
|
1271
|
+
normLower.includes('/.agents/tmp/sanitized_')
|
|
1272
|
+
) {
|
|
1273
|
+
return { action: 'allow' };
|
|
1274
|
+
}
|
|
1275
|
+
|
|
1276
|
+
if (!/\.ipynb$|\.pdf$/i.test(normLower) || !fs.existsSync(resolved)) {
|
|
1277
|
+
return { action: 'allow' };
|
|
1278
|
+
}
|
|
1279
|
+
|
|
1280
|
+
let stat;
|
|
1281
|
+
try {
|
|
1282
|
+
stat = fs.statSync(resolved);
|
|
1283
|
+
if (!stat.isFile()) return { action: 'allow' };
|
|
1284
|
+
} catch {
|
|
1285
|
+
return { action: 'allow' };
|
|
1286
|
+
}
|
|
1287
|
+
|
|
1288
|
+
if (normLower.endsWith('.pdf')) {
|
|
1289
|
+
let pageSpan = null;
|
|
1290
|
+
if (options.pages !== undefined && options.pages !== null && String(options.pages).trim() !== '') {
|
|
1291
|
+
const pagesStr = String(options.pages).trim();
|
|
1292
|
+
const rangeMatch = pagesStr.match(/^(\d+)\s*-\s*(\d+)$/);
|
|
1293
|
+
if (rangeMatch) {
|
|
1294
|
+
pageSpan = Math.abs(Number(rangeMatch[2]) - Number(rangeMatch[1])) + 1;
|
|
1295
|
+
} else if (/^\d+$/.test(pagesStr)) {
|
|
1296
|
+
pageSpan = 1;
|
|
1297
|
+
}
|
|
1298
|
+
} else if (options.hasPageBounds) {
|
|
1299
|
+
pageSpan = 10;
|
|
1300
|
+
}
|
|
1301
|
+
|
|
1302
|
+
try {
|
|
1303
|
+
const maxReadBytes = Math.min(stat.size, 16 * 1024 * 1024);
|
|
1304
|
+
const fd = fs.openSync(resolved, 'r');
|
|
1305
|
+
const buf = Buffer.allocUnsafe(maxReadBytes);
|
|
1306
|
+
fs.readSync(fd, buf, 0, maxReadBytes, 0);
|
|
1307
|
+
fs.closeSync(fd);
|
|
1308
|
+
const latin = buf.toString('latin1');
|
|
1309
|
+
const pageMatches = latin.match(/\/Type\s*\/Page\b(?!s)/g) || [];
|
|
1310
|
+
const pageCount = pageMatches.length;
|
|
1311
|
+
|
|
1312
|
+
if (pageCount > 10 && (pageSpan === null || pageSpan > 10)) {
|
|
1313
|
+
const savedTokens = Math.max(1500, (pageCount - 10) * 1500);
|
|
1314
|
+
return {
|
|
1315
|
+
action: 'deny',
|
|
1316
|
+
detectorId: 'DET-07',
|
|
1317
|
+
subType: 'UNPAGED_PDF_BLOCKED',
|
|
1318
|
+
pageCount,
|
|
1319
|
+
savedTokens,
|
|
1320
|
+
reason:
|
|
1321
|
+
`[DET-07 Multimodal PDF Guard (#14)] Unbounded read of ${pageCount}-page PDF "${path.basename(resolved)}" (>10-page cap). ` +
|
|
1322
|
+
`Pass an explicit <=10-page slice (e.g. pages: "1-10") to prevent ~${savedTokens.toLocaleString()} multimodal tokens of bloat.`
|
|
1323
|
+
};
|
|
1324
|
+
}
|
|
1325
|
+
} catch {
|
|
1326
|
+
return { action: 'allow' };
|
|
1327
|
+
}
|
|
1328
|
+
return { action: 'allow' };
|
|
1329
|
+
}
|
|
1330
|
+
|
|
1331
|
+
// `.ipynb` Notebook Base64 Image Sanitizer
|
|
1332
|
+
if (normLower.endsWith('.ipynb')) {
|
|
1333
|
+
try {
|
|
1334
|
+
const rawText = fs.readFileSync(resolved, 'utf8');
|
|
1335
|
+
const nb = JSON.parse(rawText);
|
|
1336
|
+
const cells = Array.isArray(nb?.cells) ? nb.cells : [];
|
|
1337
|
+
let strippedImages = 0;
|
|
1338
|
+
let strippedBytes = 0;
|
|
1339
|
+
|
|
1340
|
+
for (const cell of cells) {
|
|
1341
|
+
if (!cell || !Array.isArray(cell.outputs)) continue;
|
|
1342
|
+
for (const out of cell.outputs) {
|
|
1343
|
+
if (!out || !out.data || typeof out.data !== 'object') continue;
|
|
1344
|
+
for (const mime of ['image/png', 'image/jpeg', 'image/webp', 'image/svg+xml']) {
|
|
1345
|
+
const val = out.data[mime];
|
|
1346
|
+
if (!val) continue;
|
|
1347
|
+
const joined = Array.isArray(val) ? val.join('') : String(val);
|
|
1348
|
+
if (joined.length > 16384 || stat.size > 262144) {
|
|
1349
|
+
strippedImages += 1;
|
|
1350
|
+
strippedBytes += joined.length;
|
|
1351
|
+
delete out.data[mime];
|
|
1352
|
+
if (!out.data['text/plain']) {
|
|
1353
|
+
out.data['text/plain'] = [
|
|
1354
|
+
`[Highbeam Sanitized (#14): ${mime} base64 payload (${(joined.length / 1024).toFixed(1)} KB) stripped]`
|
|
1355
|
+
];
|
|
1356
|
+
}
|
|
1357
|
+
}
|
|
1358
|
+
}
|
|
1359
|
+
}
|
|
1360
|
+
}
|
|
1361
|
+
|
|
1362
|
+
if (strippedImages === 0 && stat.size <= 262144) {
|
|
1363
|
+
return { action: 'allow' };
|
|
1364
|
+
}
|
|
1365
|
+
|
|
1366
|
+
// If >256KB even without images, truncate oversized stream outputs >16KB per cell
|
|
1367
|
+
if (strippedImages === 0 && stat.size > 262144) {
|
|
1368
|
+
for (const cell of cells) {
|
|
1369
|
+
if (!cell || !Array.isArray(cell.outputs)) continue;
|
|
1370
|
+
for (const out of cell.outputs) {
|
|
1371
|
+
if (out && out.text) {
|
|
1372
|
+
const txt = Array.isArray(out.text) ? out.text.join('') : String(out.text);
|
|
1373
|
+
if (txt.length > 16384) {
|
|
1374
|
+
strippedBytes += txt.length - 4096;
|
|
1375
|
+
out.text = [
|
|
1376
|
+
`${txt.slice(0, 2048)}\n...[Highbeam Sanitized (#14): ${(txt.length / 1024).toFixed(1)} KB notebook output truncated]...\n${txt.slice(-2048)}`
|
|
1377
|
+
];
|
|
1378
|
+
}
|
|
1379
|
+
}
|
|
1380
|
+
}
|
|
1381
|
+
}
|
|
1382
|
+
}
|
|
1383
|
+
|
|
1384
|
+
if (strippedImages === 0 && strippedBytes === 0) {
|
|
1385
|
+
return { action: 'allow' };
|
|
1386
|
+
}
|
|
1387
|
+
|
|
1388
|
+
const safeBase = path.basename(resolved).replace(/[^a-zA-Z0-9._-]/g, '_');
|
|
1389
|
+
const cacheSubdir =
|
|
1390
|
+
platform === 'claude'
|
|
1391
|
+
? path.join(baseCwd, '.claude', 'cache')
|
|
1392
|
+
: path.join(baseCwd, '.agents', 'tmp');
|
|
1393
|
+
fs.mkdirSync(cacheSubdir, { recursive: true });
|
|
1394
|
+
const sanitizedPath = path.join(cacheSubdir, `sanitized_${safeBase}`);
|
|
1395
|
+
const sanitizedJson = `${JSON.stringify(nb, null, 1)}\n`;
|
|
1396
|
+
atomicWriteFileSync(sanitizedPath, sanitizedJson);
|
|
1397
|
+
const savedTokens = Math.max(100, Math.ceil(strippedBytes / 4));
|
|
1398
|
+
|
|
1399
|
+
return {
|
|
1400
|
+
action: platform === 'claude' ? 'rewrite' : 'deny',
|
|
1401
|
+
detectorId: 'DET-07',
|
|
1402
|
+
subType: 'IPYNB_BASE64_SANITIZED',
|
|
1403
|
+
sanitizedPath,
|
|
1404
|
+
strippedImages,
|
|
1405
|
+
strippedBytes,
|
|
1406
|
+
savedTokens,
|
|
1407
|
+
reason:
|
|
1408
|
+
`[Highbeam Multimodal Notebook Sanitizer (#14)] Stripped ${strippedImages} embedded base64 image(s) ` +
|
|
1409
|
+
`(${(strippedBytes / 1024).toFixed(1)} KB, ~${savedTokens.toLocaleString()} tokens saved; source "${path.basename(resolved)}" -> "${sanitizedPath}").`
|
|
1410
|
+
};
|
|
1411
|
+
} catch {
|
|
1412
|
+
return { action: 'allow' };
|
|
1413
|
+
}
|
|
1414
|
+
}
|
|
1415
|
+
|
|
1416
|
+
return { action: 'allow' };
|
|
1417
|
+
}
|