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.
Files changed (89) hide show
  1. package/.antigravity-plugin/plugin.json +1 -1
  2. package/.claude-plugin/plugin.json +1 -1
  3. package/CHECKSUMS.sha256 +59 -42
  4. package/README.md +351 -330
  5. package/bin/ah-statusline.mjs +30 -0
  6. package/bin/ctxtop.mjs +330 -5
  7. package/config/default_flightcheck.json +19 -0
  8. package/config/modelCatalog.json +165 -0
  9. package/hooks/handlers/compact-lifecycle.mjs +323 -8
  10. package/hooks/handlers/config-change.mjs +402 -0
  11. package/hooks/handlers/hookIo.mjs +56 -0
  12. package/hooks/handlers/post-model-switch.mjs +111 -0
  13. package/hooks/handlers/post-tool-use.mjs +117 -16
  14. package/hooks/handlers/pre-model-switch.mjs +823 -24
  15. package/hooks/handlers/pre-tool-use.mjs +271 -4
  16. package/hooks/handlers/stop-gate.mjs +297 -11
  17. package/hooks/handlers/user-prompt-submit.mjs +224 -0
  18. package/hooks/hooks.json +50 -0
  19. package/hooks/post_tool_use.mjs +8 -0
  20. package/hooks/register.js +48 -9
  21. package/hooks/session_start.mjs +11 -1
  22. package/hooks/stop.mjs +11 -1
  23. package/package.json +11 -4
  24. package/packages/antigravity/package.json +1 -1
  25. package/packages/claude-code/package.json +1 -1
  26. package/packages/core/package.json +1 -1
  27. package/packages/engine-node/package.json +1 -1
  28. package/packages/mcp/package.json +1 -1
  29. package/packages/mcp/src/server.mjs +1 -1
  30. package/packages/pro/package.json +1 -1
  31. package/plugin.json +1 -1
  32. package/sidecars/horizon-daemon/server.mjs +38 -2
  33. package/skills/handoff/SKILL.md +8 -0
  34. package/src/adapters/antigravity/index.mjs +31 -1
  35. package/src/adapters/claude-code/index.mjs +40 -1
  36. package/src/cli/horizon_hud.mjs +254 -52
  37. package/src/config/modelCatalog.json +84 -0
  38. package/src/core/bucket_b_runtime.mjs +1200 -0
  39. package/src/core/constants.mjs +191 -4
  40. package/src/core/detectors_det01_to_16.mjs +54 -5
  41. package/src/core/doc_indexer.mjs +338 -0
  42. package/src/core/layer5_hygiene.mjs +118 -0
  43. package/src/core/parser.mjs +2 -1
  44. package/src/core/paths.mjs +3 -2
  45. package/src/core/rsl_clash_auditor.mjs +423 -0
  46. package/src/core/rsl_distiller.mjs +372 -0
  47. package/src/core/rsl_ledger.mjs +969 -0
  48. package/src/core/rsl_triage.mjs +909 -0
  49. package/src/core/session_auditor.mjs +658 -0
  50. package/src/core/shield_manager.mjs +1417 -0
  51. package/src/core/task_quota_router.mjs +1 -1
  52. package/src/core-isomorphic/coach/cacheGravityRouter.mjs +874 -47
  53. package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
  54. package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
  55. package/src/core-isomorphic/coach/ttlWatchdog.mjs +13 -6
  56. package/src/core-isomorphic/config/anthropicModelCatalog.json +404 -1
  57. package/src/core-isomorphic/config/catalogLoader.mjs +546 -46
  58. package/src/core-isomorphic/config/horizonConfig.mjs +47 -1
  59. package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +266 -0
  60. package/src/core-isomorphic/economics/cacheGravity.mjs +18 -0
  61. package/src/core-isomorphic/economics/cliffBreaker.mjs +98 -12
  62. package/src/core-isomorphic/economics/driftLatency.mjs +114 -0
  63. package/src/core-isomorphic/guards/bucketBAlphaBeta.mjs +860 -0
  64. package/src/core-isomorphic/guards/bucketBGamma.mjs +442 -0
  65. package/src/core-isomorphic/guards/bucketBHeuristics.mjs +37 -0
  66. package/src/core-isomorphic/guards/circuitBreakers.mjs +191 -191
  67. package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +154 -5
  68. package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +103 -11
  69. package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +311 -1
  70. package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
  71. package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +16 -0
  72. package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
  73. package/src/core-isomorphic/index.js +1 -0
  74. package/src/core-isomorphic/telemetry/telemetryBridge.mjs +36 -12
  75. package/src/core-isomorphic/ui/horizonPanelHtml.mjs +293 -237
  76. package/src/core-isomorphic/ui/modViews.mjs +35 -9
  77. package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
  78. package/src/diagnostics/doctorEngine.mjs +95 -3
  79. package/src/engine-node/db/probe.mjs +234 -2
  80. package/src/engine-node/index.mjs +3 -0
  81. package/src/engine-node/sensors/blindspots.mjs +13 -6
  82. package/src/hooks/antigravity_rsl_hook.mjs +250 -0
  83. package/src/hooks/claude_rsl_hook.mjs +288 -0
  84. package/src/hooks/post_invocation.mjs +196 -4
  85. package/src/hooks/pre_invocation.mjs +732 -22
  86. package/src/hooks/session_start.mjs +39 -1
  87. package/src/utils/modelSwitchTelemetry.mjs +308 -0
  88. package/src/utils/sessionCalibration.mjs +657 -0
  89. package/src/webview/horizon_panel.html +1325 -317
@@ -18,6 +18,8 @@ import {
18
18
  writeLiveStateSnapshot
19
19
  } from '../src/core-isomorphic/telemetry/telemetryBridge.mjs';
20
20
  import { renderStatusLine } from '../src/core-isomorphic/ui/modViews.mjs';
21
+ import { inspectClaudeBinaryCapabilities } from '../src/diagnostics/claudeHookCapabilities.mjs';
22
+ import { getRslLedgerPath, getRslSummary } from '../src/core/rsl_ledger.mjs';
21
23
 
22
24
  /**
23
25
  * Programmatic entrypoint for the `statusLine` bridge.
@@ -42,6 +44,34 @@ export function executeStatusLineBridge(payload = {}, options = {}) {
42
44
  const sessionId = payload.session_id || payload.sessionId || 'default';
43
45
  const currentState = readLiveStateSnapshot(sessionId, options);
44
46
  const nextState = ingestStatusLinePayload(currentState, payload, options);
47
+ if (!currentState.hostCapabilities && options.checkCapabilities !== false) {
48
+ const cap = inspectClaudeBinaryCapabilities({
49
+ cwd: payload.cwd || options.cwd,
50
+ claudeBinPath: options.claudeBinPath,
51
+ probeVersion: false
52
+ });
53
+ nextState.hostCapabilities = cap.found
54
+ ? {
55
+ found: true,
56
+ claudeVersion: cap.claudeVersion,
57
+ preModelSwitchSupported: cap.preModelSwitchSupported,
58
+ supportsAskDecision: cap.supportsAskDecision,
59
+ preEffortChangeSupported: cap.preEffortChangeSupported,
60
+ contractValid: cap.contractValid,
61
+ warning: cap.warning
62
+ }
63
+ : { found: false };
64
+ }
65
+ const rslCwd = payload.cwd || options.cwd;
66
+ if (options.rsl) {
67
+ nextState.rsl = options.rsl;
68
+ } else if (rslCwd && (options.includeRsl === true || fs.existsSync(getRslLedgerPath(rslCwd)))) {
69
+ try {
70
+ nextState.rsl = getRslSummary(rslCwd, options);
71
+ } catch {
72
+ // Fail open for statusline
73
+ }
74
+ }
45
75
  const persisted = writeLiveStateSnapshot(nextState.sessionId, nextState, options);
46
76
 
47
77
  const envCols = Number(globalThis.process?.env?.AH_COLUMNS || 0);
package/bin/ctxtop.mjs CHANGED
@@ -94,8 +94,22 @@ import {
94
94
  inspectHookDiagnostics,
95
95
  runDoctorDiagnostics
96
96
  } from '../src/diagnostics/doctorEngine.mjs';
97
+ import { inspectClaudeBinaryCapabilities } from '../src/diagnostics/claudeHookCapabilities.mjs';
97
98
  import { installPlugin, runLiveOrDemoCli } from '../src/cli/init.mjs';
98
99
  import { executeStatusLineBridge, runStatusLineCli } from './ah-statusline.mjs';
100
+ import { runSessionAudit, formatSessionAuditReport } from '../src/core/session_auditor.mjs';
101
+ import { configureShield, getShieldStatus } from '../src/core/shield_manager.mjs';
102
+ import { buildContrastiveDigest, sanitizeRslSessionId } from '../src/core/rsl_triage.mjs';
103
+ import { distillContrastiveDigest } from '../src/core/rsl_distiller.mjs';
104
+ import {
105
+ getRslLedgerPath,
106
+ getRslSummary,
107
+ ingestDistilledHeuristics,
108
+ promoteHeuristic,
109
+ pruneHeuristic,
110
+ auditWorkspaceRuleClashes,
111
+ buildConsolidatedSpecMarkdown
112
+ } from '../src/core/rsl_ledger.mjs';
99
113
 
100
114
  export { inspectHookDiagnostics, runDoctorDiagnostics };
101
115
 
@@ -113,7 +127,7 @@ export const LEAN_POST_TOOL_USE_MATCHER =
113
127
  'Bash|PowerShell|Task|Agent|WebFetch|mcp__.*';
114
128
 
115
129
  const AH_HANDLER_REGEX =
116
- /hooks[\\/]handlers[\\/](pre-tool-use|post-tool-use|pre-model-switch|compact-lifecycle|stop-gate)\.mjs/i;
130
+ /hooks[\\/]handlers[\\/](pre-tool-use|post-tool-use|pre-model-switch|post-model-switch|compact-lifecycle|stop-gate|user-prompt-submit|config-change)\.mjs/i;
117
131
  const AH_STATUSLINE_REGEX = /ah-statusline\.mjs/i;
118
132
  const AH_MOD_REGISTER_REGEX = /(?:^|[\\/])hooks[\\/]register\.js$|^\.\/register\.js$/i;
119
133
 
@@ -155,6 +169,7 @@ export function buildCanonicalAhHooks(options = {}) {
155
169
  const handlerPrefix = `${rootPrefix}/hooks/handlers`;
156
170
  const preMatcher = options.leanHooks ? LEAN_PRE_TOOL_USE_MATCHER : PRE_TOOL_USE_MATCHER;
157
171
  const postMatcher = options.leanHooks ? LEAN_POST_TOOL_USE_MATCHER : POST_TOOL_USE_MATCHER;
172
+ const includePostModelSwitch = options.includePostModelSwitch !== false;
158
173
 
159
174
  return {
160
175
  PreToolUse: [
@@ -189,6 +204,20 @@ export function buildCanonicalAhHooks(options = {}) {
189
204
  ]
190
205
  }
191
206
  ],
207
+ ...(includePostModelSwitch
208
+ ? {
209
+ PostModelSwitch: [
210
+ {
211
+ hooks: [
212
+ {
213
+ type: 'command',
214
+ command: `node "${handlerPrefix}/post-model-switch.mjs"`
215
+ }
216
+ ]
217
+ }
218
+ ]
219
+ }
220
+ : {}),
192
221
  PreCompact: [
193
222
  {
194
223
  hooks: [
@@ -229,6 +258,46 @@ export function buildCanonicalAhHooks(options = {}) {
229
258
  }
230
259
  ]
231
260
  }
261
+ ],
262
+ UserPromptSubmit: [
263
+ {
264
+ hooks: [
265
+ {
266
+ type: 'command',
267
+ command: `node "${handlerPrefix}/user-prompt-submit.mjs"`
268
+ }
269
+ ]
270
+ }
271
+ ],
272
+ ConfigChange: [
273
+ {
274
+ hooks: [
275
+ {
276
+ type: 'command',
277
+ command: `node "${handlerPrefix}/config-change.mjs"`
278
+ }
279
+ ]
280
+ }
281
+ ],
282
+ InstructionsLoaded: [
283
+ {
284
+ hooks: [
285
+ {
286
+ type: 'command',
287
+ command: `node "${handlerPrefix}/compact-lifecycle.mjs" --phase=instructions`
288
+ }
289
+ ]
290
+ }
291
+ ],
292
+ SessionEnd: [
293
+ {
294
+ hooks: [
295
+ {
296
+ type: 'command',
297
+ command: `node "${handlerPrefix}/stop-gate.mjs" --phase=end`
298
+ }
299
+ ]
300
+ }
232
301
  ]
233
302
  };
234
303
  }
@@ -330,10 +399,30 @@ export function installAttentionHorizon(options = {}) {
330
399
 
331
400
  const useLeanHooks =
332
401
  options.leanHooks !== undefined ? Boolean(options.leanHooks) : !Boolean(options.fullHooks);
402
+ let includePostModelSwitch =
403
+ options.includePostModelSwitch !== undefined ? Boolean(options.includePostModelSwitch) : true;
404
+ const omittedUnsupportedHooks = [];
405
+ if (
406
+ options.includePostModelSwitch === undefined &&
407
+ options.checkBinaryCapabilities !== false
408
+ ) {
409
+ const caps = inspectClaudeBinaryCapabilities({
410
+ ...options,
411
+ cwd,
412
+ probeVersion: false,
413
+ recordDiagnostic: false,
414
+ writeCache: false
415
+ });
416
+ if (caps.found === true && caps.postModelSwitchSupported === false) {
417
+ includePostModelSwitch = false;
418
+ omittedUnsupportedHooks.push('PostModelSwitch');
419
+ }
420
+ }
333
421
  const canonicalHooks = buildCanonicalAhHooks({
334
422
  usePluginRootVar: false,
335
423
  pkgRoot,
336
- leanHooks: useLeanHooks
424
+ leanHooks: useLeanHooks,
425
+ includePostModelSwitch
337
426
  });
338
427
  for (const [eventName, ahEntries] of Object.entries(canonicalHooks)) {
339
428
  const existingList = Array.isArray(currentSettings.hooks[eventName])
@@ -395,6 +484,7 @@ export function installAttentionHorizon(options = {}) {
395
484
  settingsPath,
396
485
  backupPath,
397
486
  gitExcludeUpdated: gitExclude.updated,
487
+ omittedUnsupportedHooks,
398
488
  settings: currentSettings
399
489
  };
400
490
  }
@@ -664,7 +754,7 @@ export function executeInitSubcommand(args = [], options = {}) {
664
754
  targetParts.length === 2 && !isMcp ? targetParts.join(' & ') : targetParts.join(', ');
665
755
 
666
756
  const lines = [
667
- `\x1b[1m\x1b[38;5;51m⚡ Highbeam (ctxtop v4.0.0) — Zero-Config Unified Installer\x1b[0m`,
757
+ `\x1b[1m\x1b[38;5;51m⚡ Highbeam (ctxtop v4.1.0) — Zero-Config Unified Installer\x1b[0m`,
668
758
  ` • Target Harnesses : ${targetLabel}`,
669
759
  ` • Installation Scope: ${isWorkspace ? 'Workspace' : 'Global'}${isDryRun ? ' [DRY RUN]' : ''}`
670
760
  ];
@@ -746,7 +836,7 @@ export function runCli(args = [], options = {}) {
746
836
  const scope = isGlobal ? 'global' : 'project';
747
837
 
748
838
  if (args.includes('--version') || args.includes('-v') || subcommand === 'version') {
749
- return { exitCode: 0, output: '4.0.0', data: { version: '4.0.0' } };
839
+ return { exitCode: 0, output: '4.1.0', data: { version: '4.1.0' } };
750
840
  }
751
841
 
752
842
  if (subcommand === 'inspect') {
@@ -1363,9 +1453,18 @@ export function runCli(args = [], options = {}) {
1363
1453
  return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1364
1454
  }
1365
1455
  const hookDiag = res.hookDiagnostics || { recentErrorCount: 0, recentErrors: [] };
1456
+ const ccCap = res.claudeCapabilities;
1366
1457
  const lines = [
1367
1458
  `[Highbeam Doctor] Status: ${res.ok ? 'HEALTHY' : 'ISSUES DETECTED'}`,
1368
- ...res.checks.map((c) => ` [${c.ok ? 'PASS' : 'FAIL'}] ${c.id}: ${c.detail}`),
1459
+ ...res.checks.map((c) => {
1460
+ const badge = c.status || (c.ok ? 'PASS' : 'FAIL');
1461
+ return ` [${badge}] ${c.id}: ${c.detail}`;
1462
+ }),
1463
+ ...(ccCap?.found
1464
+ ? [
1465
+ ` [${ccCap.contractValid ? 'PASS' : 'WARN'}] claude_pre_model_switch: Claude Code ${ccCap.claudeVersion || 'unknown'} | PreModelSwitch=${ccCap.preModelSwitchSupported} | ask=${ccCap.supportsAskDecision} | PreEffortChange=${ccCap.preEffortChangeSupported}`
1466
+ ]
1467
+ : []),
1369
1468
  ` [${hookDiag.recentErrorCount > 0 ? 'WARN' : 'PASS'}] hook_diagnostics: ${hookDiag.recentErrorCount} recent non-fatal error(s)`
1370
1469
  ];
1371
1470
  for (const errEntry of hookDiag.recentErrors) {
@@ -1380,6 +1479,226 @@ export function runCli(args = [], options = {}) {
1380
1479
  return runStatusLineCli(args.slice(1));
1381
1480
  }
1382
1481
 
1482
+ if (subcommand === 'audit') {
1483
+ const platIdx = args.indexOf('--platform');
1484
+ const platform =
1485
+ platIdx !== -1 && args[platIdx + 1]
1486
+ ? String(args[platIdx + 1]).toLowerCase()
1487
+ : (options.platform || 'all');
1488
+ const daysIdx = args.indexOf('--days');
1489
+ const days =
1490
+ daysIdx !== -1 && args[daysIdx + 1]
1491
+ ? Number(args[daysIdx + 1])
1492
+ : (options.days || 7);
1493
+ const limitIdx = args.indexOf('--limit');
1494
+ const limit =
1495
+ limitIdx !== -1 && args[limitIdx + 1]
1496
+ ? Number(args[limitIdx + 1])
1497
+ : (options.limit || 10);
1498
+
1499
+ const auditRes = runSessionAudit({
1500
+ ...options,
1501
+ platform,
1502
+ days,
1503
+ limit
1504
+ });
1505
+ if (isJson) {
1506
+ return { exitCode: 0, output: JSON.stringify(auditRes, null, 2), data: auditRes };
1507
+ }
1508
+ return { exitCode: 0, output: formatSessionAuditReport(auditRes), data: auditRes };
1509
+ }
1510
+
1511
+ if (subcommand === 'rsl') {
1512
+ const action = String(args[1] || 'status').toLowerCase();
1513
+ const readFlag = (flag, fallback) => {
1514
+ const idx = args.indexOf(flag);
1515
+ return idx !== -1 && args[idx + 1] ? String(args[idx + 1]) : fallback;
1516
+ };
1517
+ const wsRoot = path.resolve(readFlag('--cwd', options.cwd || process.cwd()));
1518
+ const platform = readFlag('--platform', options.platform || 'all').toLowerCase();
1519
+
1520
+ if (action === 'status') {
1521
+ const summary = { ok: true, platform, ...getRslSummary(wsRoot, options) };
1522
+ if (isJson) {
1523
+ return { exitCode: 0, output: JSON.stringify(summary, null, 2), data: summary };
1524
+ }
1525
+ const memNote = summary.claudeMemoryAudit?.triggered
1526
+ ? `WARN (${summary.claudeMemoryAudit.maxLines}L / ${Math.round(summary.claudeMemoryAudit.maxBytes / 1024)}KB)`
1527
+ : 'OK';
1528
+ const lines = [
1529
+ `[Highbeam RSL] Dual-Platform Self-Learning Status (platform=${platform})`,
1530
+ ` Active Carriers : ${summary.activeRules} rules · ${summary.activeSkills} skills · ${summary.promotedHooks} promoted hooks`,
1531
+ ` Rule Budget : ${summary.ruleBudgetTokens}/${summary.ruleBudgetMaxTokens} tokens (${summary.ruleBudgetPct}%)`,
1532
+ ` Rule Clashes : ${summary.clashCount || 0} conflict(s)${summary.quarantinedCount ? ` (${summary.quarantinedCount} quarantined)` : ''}`,
1533
+ ` Lifecycle Stats : ${summary.prunedCount} pruned · ${summary.taintedSessions} tainted sessions`,
1534
+ ` Claude Memory : ${memNote}`,
1535
+ ...((summary.activeClashes || []).map((c) => ` [RULE_CONFLICT] ${c.reason}`))
1536
+ ];
1537
+ return { exitCode: 0, output: lines.join('\n'), data: summary };
1538
+ }
1539
+
1540
+ if (action === 'list') {
1541
+ const includeAll = args.includes('--all') || Boolean(options.all);
1542
+ const summary = getRslSummary(wsRoot, { ...options, includeAll });
1543
+ const payload = { ok: true, includeAll, count: summary.items.length, items: summary.items };
1544
+ if (isJson) {
1545
+ return { exitCode: 0, output: JSON.stringify(payload, null, 2), data: payload };
1546
+ }
1547
+ const lines = [`[Highbeam RSL] Heuristics (${payload.count} item(s), all=${includeAll}):`];
1548
+ for (const it of summary.items) {
1549
+ lines.push(` - ${it.slug} [${it.carrier}] importance=${it.importance} status=${it.status} hook=${Boolean(it.promotedHook)}`);
1550
+ }
1551
+ return { exitCode: 0, output: lines.join('\n'), data: payload };
1552
+ }
1553
+
1554
+ if (action === 'run') {
1555
+ const mode = readFlag('--mode', options.mode || 'local').toLowerCase();
1556
+ let sessionId = readFlag('--session', options.sessionId || '');
1557
+ if (!sessionId) {
1558
+ const telemetryDir = path.join(wsRoot, '.agents', 'telemetry');
1559
+ if (fs.existsSync(telemetryDir)) {
1560
+ const candidates = fs.readdirSync(telemetryDir)
1561
+ .filter((f) => f.endsWith('.rsl_steps.jsonl'))
1562
+ .map((f) => ({ name: f.replace(/\.rsl_steps\.jsonl$/, ''), mtime: fs.statSync(path.join(telemetryDir, f)).mtimeMs }))
1563
+ .sort((a, b) => b.mtime - a.mtime);
1564
+ if (candidates[0]) sessionId = candidates[0].name;
1565
+ }
1566
+ }
1567
+ sessionId = sanitizeRslSessionId(sessionId || 'default');
1568
+ const resolvedPlatform = platform === 'auto' || platform === 'all'
1569
+ ? (options.transcriptPath && String(options.transcriptPath).includes('.claude') ? 'claude' : 'antigravity')
1570
+ : platform;
1571
+ const digest = buildContrastiveDigest(
1572
+ {
1573
+ conversationId: sessionId,
1574
+ session_id: sessionId,
1575
+ cwd: wsRoot,
1576
+ workspacePaths: [wsRoot],
1577
+ transcriptPath: readFlag('--transcript', options.transcriptPath || ''),
1578
+ artifactDirectoryPath: readFlag('--artifacts', options.artifactDirectoryPath || '')
1579
+ },
1580
+ { ...options, cwd: wsRoot, platform: resolvedPlatform }
1581
+ );
1582
+ const distillation = digest.triggered
1583
+ ? distillContrastiveDigest(digest, { mode, sdkRunner: options.sdkRunner })
1584
+ : { is_valid_learning: false, mode, heuristics: [] };
1585
+ const ledgerResult = (digest.tainted || digest.triggered || fs.existsSync(getRslLedgerPath(wsRoot)))
1586
+ ? ingestDistilledHeuristics(wsRoot, distillation, digest, options)
1587
+ : null;
1588
+ const summary = getRslSummary(wsRoot, options);
1589
+ const res = {
1590
+ ok: !digest.tainted,
1591
+ sessionId,
1592
+ platform: resolvedPlatform,
1593
+ mode: distillation.mode || mode,
1594
+ digest,
1595
+ distillation,
1596
+ ledgerResult,
1597
+ summary
1598
+ };
1599
+ if (isJson) {
1600
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1601
+ }
1602
+ const msg = digest.tainted
1603
+ ? `[Highbeam RSL] Session ${sessionId} flagged ${digest.status} (${digest.taintDetails.join('; ')}) — extraction aborted.`
1604
+ : `[Highbeam RSL] Session ${sessionId} distilled (${res.mode}): +${ledgerResult?.added?.length || 0} added, ${ledgerResult?.upvoted?.length || 0} upvoted, ${ledgerResult?.pruned?.length || 0} pruned.`;
1605
+ return { exitCode: res.ok ? 0 : 1, output: msg, data: res };
1606
+ }
1607
+
1608
+ if (action === 'promote' || action === 'prune') {
1609
+ const slug = args[2] && !args[2].startsWith('-') ? args[2] : (options.slug || '');
1610
+ if (!slug) {
1611
+ const errRes = { ok: false, error: `Missing <slug> for rsl ${action}` };
1612
+ return {
1613
+ exitCode: 1,
1614
+ output: isJson ? JSON.stringify(errRes, null, 2) : `[Highbeam RSL] ERROR: ${errRes.error}`,
1615
+ data: errRes
1616
+ };
1617
+ }
1618
+ const res = action === 'promote'
1619
+ ? promoteHeuristic(wsRoot, slug, options)
1620
+ : pruneHeuristic(wsRoot, slug, options);
1621
+ if (isJson) {
1622
+ return { exitCode: res.ok ? 0 : 1, output: JSON.stringify(res, null, 2), data: res };
1623
+ }
1624
+ return {
1625
+ exitCode: res.ok ? 0 : 1,
1626
+ output: res.ok
1627
+ ? `[Highbeam RSL] ${action === 'promote' ? 'Promoted' : 'Pruned'} heuristic "${res.slug}" across .agents/ and .claude/`
1628
+ : `[Highbeam RSL] ERROR: ${res.error}`,
1629
+ data: res
1630
+ };
1631
+ }
1632
+
1633
+ const helpRsl = 'Usage: ctxtop rsl <status|list|run|promote <slug>|prune <slug>> [--platform all|antigravity|claude] [--mode local|sdk] [--json]';
1634
+ return {
1635
+ exitCode: 1,
1636
+ output: isJson ? JSON.stringify({ ok: false, error: `Unknown rsl action: ${action}` }, null, 2) : helpRsl,
1637
+ data: { ok: false }
1638
+ };
1639
+ }
1640
+
1641
+ if (subcommand === 'shield' || subcommand === 'status') {
1642
+ const platIdx = args.indexOf('--platform');
1643
+ const platform =
1644
+ platIdx !== -1 && args[platIdx + 1]
1645
+ ? String(args[platIdx + 1]).toLowerCase()
1646
+ : (options.platform || 'all');
1647
+ const linesIdx = args.indexOf('--max-lines');
1648
+ const maxUnslicedLines =
1649
+ linesIdx !== -1 && args[linesIdx + 1] ? Number(args[linesIdx + 1]) : options.maxUnslicedLines;
1650
+
1651
+ let action = 'status';
1652
+ if (subcommand === 'shield') {
1653
+ if (args.includes('--enable') || args[1] === 'enable') action = 'enable';
1654
+ else if (args.includes('--disable') || args[1] === 'disable') action = 'disable';
1655
+ else action = 'status';
1656
+ }
1657
+
1658
+ const res =
1659
+ subcommand === 'status'
1660
+ ? { ok: true, action: 'status', platform, ...getShieldStatus({ ...options }) }
1661
+ : configureShield({
1662
+ ...options,
1663
+ action,
1664
+ platform,
1665
+ ...(maxUnslicedLines ? { maxUnslicedLines } : {})
1666
+ });
1667
+
1668
+ if (isJson) {
1669
+ return { exitCode: res.ok === false ? 1 : 0, output: JSON.stringify(res, null, 2), data: res };
1670
+ }
1671
+ const lines = [
1672
+ `[Highbeam Shield] Status: ${res.enabled ? 'ACTIVE' : 'PASSIVE'} (action=${res.action}, platform=${platform})`,
1673
+ ` Targets : Antigravity=${res.platforms.antigravity ? 'ON' : 'OFF'} (hooks=${res.hooksConfigured.antigravity}) | Claude=${res.platforms.claude ? 'ON' : 'OFF'} (hooks=${res.hooksConfigured.claude})`,
1674
+ ` Read Threshold: >${res.maxUnslicedLines} lines default | >${res.cliffMaxUnslicedLines} lines near pricing cliff`,
1675
+ ` Session ROI : +${res.roi.tokensSaved.toLocaleString('en-US')} tok saved ($${res.roi.dollarsSaved.toFixed(2)} USD) | ${res.roi.readsBlocked} oversized reads indexed`,
1676
+ ...(res.selfTest ? [` Self-Test : ${res.selfTest.detail}`] : [])
1677
+ ];
1678
+ return { exitCode: res.ok === false ? 1 : 0, output: lines.join('\n'), data: res };
1679
+ }
1680
+
1681
+ if (subcommand === 'handoff') {
1682
+ const readFlag = (flag, fallback) => {
1683
+ const idx = args.indexOf(flag);
1684
+ return idx !== -1 && args[idx + 1] ? String(args[idx + 1]) : fallback;
1685
+ };
1686
+ const wsRoot = path.resolve(readFlag('--cwd', options.cwd || process.cwd()));
1687
+ const sessionId = readFlag('--session', options.sessionId || '');
1688
+ const result = buildConsolidatedSpecMarkdown(wsRoot, { sessionId });
1689
+ let outputPath = null;
1690
+ if (args.includes('--write') || Boolean(options.write)) {
1691
+ outputPath = path.join(wsRoot, '.agents', 'telemetry', 'CONSOLIDATED_SPEC.md');
1692
+ writeTextAtomic(outputPath, `${result.consolidatedMarkdown}\n`);
1693
+ }
1694
+ const payload = { ...result, ...(outputPath ? { outputPath } : {}) };
1695
+ return {
1696
+ exitCode: 0,
1697
+ output: isJson ? JSON.stringify(payload, null, 2) : payload.consolidatedMarkdown,
1698
+ data: payload
1699
+ };
1700
+ }
1701
+
1383
1702
  if (args.includes('--demo') || args.includes('--demo-animate') || args.includes('--roast') || args.includes('--serve')) {
1384
1703
  return runLiveOrDemoCli(options);
1385
1704
  }
@@ -1387,6 +1706,7 @@ export function runCli(args = [], options = {}) {
1387
1706
  const knownSubcommands = new Set([
1388
1707
  'init', 'install', 'uninstall', 'config', 'cost-radar', 'radar', 'panel',
1389
1708
  'receipt', 'doctor', 'statusline', 'inspect', 'control', 'postmortem',
1709
+ 'audit', 'shield', 'status', 'rsl', 'handoff',
1390
1710
  'license', 'pro', 'roast',
1391
1711
  '--help', '-h', 'help', '--version', '-v', 'version'
1392
1712
  ]);
@@ -1397,6 +1717,11 @@ export function runCli(args = [], options = {}) {
1397
1717
  'Usage: ctxtop <command> [options]',
1398
1718
  'Commands:',
1399
1719
  ' init [--antigravity | --claude | --all | --workspace | --dry-run] Zero-config dual-host installer',
1720
+ ' audit [--platform all|antigravity|claude] [--days 7] [--json] Zero-write historical Sludge Tax & ROI audit',
1721
+ ' shield <--enable | --disable | --status> [--platform all|...] Toggle Active Context Shield & read-index guard',
1722
+ ' rsl <status|list|run|promote|prune> [--platform ...] [--json] Dual-platform RSL post-mortem & rule ledger',
1723
+ ' handoff [--consolidate] [--session <id>] [--write] [--json] Consolidate sharded spec constraints & diff',
1724
+ ' status [--platform all|antigravity|claude] [--json] Show Shield & Session ROI status',
1400
1725
  ' install [--global | --project] Merge Claude Code hooks & statusLine',
1401
1726
  ' uninstall [--global | --project] Remove Highbeam hooks',
1402
1727
  ' doctor [--diagnostic | --json] Verify contracts or emit zero-PII report',
@@ -19,6 +19,7 @@
19
19
  "None"
20
20
  ],
21
21
  "handoff_audit_enabled": true,
22
+ "smartCompactBoundarySuggest": false,
22
23
  "deprecated_paths": [
23
24
  "**/legacy/**",
24
25
  "**/deprecated/**",
@@ -40,15 +41,24 @@
40
41
  "claude-fable-5.2": 1000000,
41
42
  "claude-fable-5-1": 1000000,
42
43
  "claude-fable-5.1": 1000000,
44
+ "claude-fable-5": 1000000,
45
+ "claude-opus-5": 1000000,
46
+ "claude-sonnet-5": 1000000,
47
+ "claude-opus-4-8": 1000000,
48
+ "claude-opus-4.8": 1000000,
49
+ "claude-opus-4-7": 1000000,
50
+ "claude-opus-4.7": 1000000,
43
51
  "claude-opus-4-6": 200000,
44
52
  "claude-opus-4.6": 200000,
45
53
  "claude-opus-4-5": 200000,
46
54
  "claude-opus-4.5": 200000,
47
55
  "claude-opus-4-1": 200000,
56
+ "claude-opus-4-0": 200000,
48
57
  "claude-sonnet-4-6": 200000,
49
58
  "claude-sonnet-4.6": 200000,
50
59
  "claude-sonnet-4-5": 200000,
51
60
  "claude-sonnet-4.5": 200000,
61
+ "claude-sonnet-4-0": 200000,
52
62
  "claude-haiku-4-5": 200000,
53
63
  "claude-haiku-4.5": 200000,
54
64
  "claude-3-5-sonnet": 200000,
@@ -80,16 +90,25 @@
80
90
  "claude-fable-5.2": 8.00,
81
91
  "claude-fable-5-1": 10.00,
82
92
  "claude-fable-5.1": 10.00,
93
+ "claude-fable-5": 10.00,
94
+ "claude-opus-5": 5.00,
95
+ "claude-sonnet-5": 2.00,
96
+ "claude-opus-4-8": 5.00,
97
+ "claude-opus-4.8": 5.00,
98
+ "claude-opus-4-7": 5.00,
99
+ "claude-opus-4.7": 5.00,
83
100
  "claude-opus-4-6": 5.00,
84
101
  "claude-opus-4.6": 5.00,
85
102
  "claude-opus-4-6-thinking": 5.00,
86
103
  "claude-opus-4-5": 5.00,
87
104
  "claude-opus-4.5": 5.00,
88
105
  "claude-opus-4-1": 15.00,
106
+ "claude-opus-4-0": 15.00,
89
107
  "claude-sonnet-4-6": 3.00,
90
108
  "claude-sonnet-4.6": 3.00,
91
109
  "claude-sonnet-4-5": 3.00,
92
110
  "claude-sonnet-4.5": 3.00,
111
+ "claude-sonnet-4-0": 3.00,
93
112
  "claude-haiku-4-5": 1.00,
94
113
  "claude-haiku-4.5": 1.00,
95
114
  "claude-3-5-sonnet": 3.00,