ctxtop 0.0.0-stage → 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 +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +166 -0
- package/LICENSE +27 -0
- package/README.md +350 -2
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +175 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1799 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +133 -0
- package/config/modelCatalog.json +785 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +577 -0
- package/hooks/handlers/config-change.mjs +402 -0
- package/hooks/handlers/hookIo.mjs +311 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-model-switch.mjs +111 -0
- package/hooks/handlers/post-tool-use.mjs +366 -0
- package/hooks/handlers/pre-model-switch.mjs +1048 -0
- package/hooks/handlers/pre-tool-use.mjs +632 -0
- package/hooks/handlers/stop-gate.mjs +526 -0
- package/hooks/handlers/user-prompt-submit.mjs +367 -0
- package/hooks/hooks.json +131 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +25 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +726 -0
- package/hooks/session_start.mjs +24 -0
- package/hooks/stop.mjs +23 -0
- package/hooks.json +56 -0
- package/package.json +110 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2038 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +50 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +109 -0
- package/src/adapters/claude-code/index.mjs +194 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +888 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +704 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/bucket_b_runtime.mjs +1200 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1987 -0
- package/src/core/detectors_det01_to_16.mjs +1523 -0
- package/src/core/doc_indexer.mjs +338 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +1084 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1997 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +311 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/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/sanitizer.mjs +121 -0
- package/src/core/session_auditor.mjs +658 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/shield_manager.mjs +1417 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +1547 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/resumeToolsetAuditor.mjs +321 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/smartCompactAdvisor.mjs +305 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +464 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +606 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +1268 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1055 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +888 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +369 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +256 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +433 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/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 +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1184 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +572 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +913 -0
- package/src/core-isomorphic/guards/docIndexCore.mjs +446 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +317 -0
- package/src/core-isomorphic/guards/slopsquatGate.mjs +551 -0
- package/src/core-isomorphic/index.js +27 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1156 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1237 -0
- package/src/core-isomorphic/ui/modViews.mjs +1504 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/claudeHookCapabilities.mjs +396 -0
- package/src/diagnostics/doctorEngine.mjs +295 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +342 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +12 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +376 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/antigravity_rsl_hook.mjs +250 -0
- package/src/hooks/claude_rsl_hook.mjs +288 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +611 -0
- package/src/hooks/pre_invocation.mjs +1725 -0
- package/src/hooks/session_start.mjs +199 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/modelSwitchTelemetry.mjs +308 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/utils/sessionCalibration.mjs +657 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +12397 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,402 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/handlers/config-change.mjs
|
|
3
|
+
* Tier 2 Command Hook handler for Claude Code `ConfigChange` (`#1 MID_SESSION_CACHE_BUST`).
|
|
4
|
+
*
|
|
5
|
+
* Guards warm prompt-cache prefixes (`cachedTokens > 25,000`, `ttlSeconds > 0`) against
|
|
6
|
+
* mid-session settings/plugin/MCP mutations that trigger full uncached prefix rewrites:
|
|
7
|
+
* - `/effort` / `effortLevel` on Anthropic models without unified effort-invariant caching
|
|
8
|
+
* - `fastMode` toggle on warm prefix
|
|
9
|
+
* - `mcpServers` / `enabledPlugins` / `plugins` / `tools` (`tools_changed` prefix bust)
|
|
10
|
+
* - Mid-session `model` downshift (`Opus -> Sonnet`), queuing `pendingDownshiftModel`
|
|
11
|
+
* until `PostCompact` so the downshift executes at $0 cold-cache penalty.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { readLiveStateSnapshot } from '../../src/core-isomorphic/telemetry/telemetryBridge.mjs';
|
|
15
|
+
import {
|
|
16
|
+
computeTotalPromptTokens,
|
|
17
|
+
isKnownCatalogModel,
|
|
18
|
+
normalizeModelId,
|
|
19
|
+
resolveEffectiveRates
|
|
20
|
+
} from '../../src/core-isomorphic/config/catalogLoader.mjs';
|
|
21
|
+
import { loadHorizonConfig, resolveDetectorOverride } from '../../src/core-isomorphic/config/horizonConfig.mjs';
|
|
22
|
+
import {
|
|
23
|
+
CacheGravityRouter,
|
|
24
|
+
FLIGHT_MODES,
|
|
25
|
+
getEffortMutationCacheCapability,
|
|
26
|
+
isSilentOrOffMode,
|
|
27
|
+
normalizeFlightMode
|
|
28
|
+
} from '../../src/core-isomorphic/coach/cacheGravityRouter.mjs';
|
|
29
|
+
import {
|
|
30
|
+
readBreakerStateSnapshot,
|
|
31
|
+
writeBreakerStateSnapshot
|
|
32
|
+
} from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
|
|
33
|
+
import { recordInterventionSavings } from '../../src/core-isomorphic/coach/savedQuotaLedger.mjs';
|
|
34
|
+
import {
|
|
35
|
+
isCliEntrypoint,
|
|
36
|
+
readStdinJsonAsync,
|
|
37
|
+
exitPassThrough,
|
|
38
|
+
exitDiagnosticZero,
|
|
39
|
+
exitWithStdoutJson
|
|
40
|
+
} from './hookIo.mjs';
|
|
41
|
+
|
|
42
|
+
export const WARM_CACHE_CONFIG_GUARD_FLOOR_TOKENS = 25_000;
|
|
43
|
+
|
|
44
|
+
const CACHE_BUSTING_KEY_PATTERNS = [
|
|
45
|
+
{ regex: /^(?:effort|effortLevel|reasoningEffort|thinkingBudget)$/i, kind: 'effort' },
|
|
46
|
+
{ regex: /^(?:fastMode|fast_mode)$/i, kind: 'fastMode' },
|
|
47
|
+
{ regex: /^(?:mcpServers|mcp_servers|enabledPlugins|plugins|tools)$/i, kind: 'tools_changed' },
|
|
48
|
+
{ regex: /^(?:model|defaultModel)$/i, kind: 'model' }
|
|
49
|
+
];
|
|
50
|
+
|
|
51
|
+
function classifyConfigMutation(event = {}) {
|
|
52
|
+
const rawKey = String(
|
|
53
|
+
event.setting_key || event.settingKey || event.key || event.source || ''
|
|
54
|
+
).trim();
|
|
55
|
+
for (const entry of CACHE_BUSTING_KEY_PATTERNS) {
|
|
56
|
+
if (entry.regex.test(rawKey)) {
|
|
57
|
+
return { busting: true, kind: entry.kind, key: rawKey };
|
|
58
|
+
}
|
|
59
|
+
}
|
|
60
|
+
const sourceStr = String(event.source || '').toLowerCase();
|
|
61
|
+
if (sourceStr.includes('plugin') || sourceStr.includes('mcp')) {
|
|
62
|
+
return { busting: true, kind: 'tools_changed', key: rawKey || sourceStr };
|
|
63
|
+
}
|
|
64
|
+
return { busting: false, kind: null, key: rawKey };
|
|
65
|
+
}
|
|
66
|
+
|
|
67
|
+
function isOpusToSonnetDownshift(oldModel = '', newModel = '') {
|
|
68
|
+
const prev = normalizeModelId(oldModel);
|
|
69
|
+
const next = normalizeModelId(newModel);
|
|
70
|
+
return prev.includes('opus') && next.includes('sonnet');
|
|
71
|
+
}
|
|
72
|
+
|
|
73
|
+
/**
|
|
74
|
+
* Evaluates a Claude Code `ConfigChange` hook payload against warm-cache gravity.
|
|
75
|
+
*
|
|
76
|
+
* @param {object} [event={}]
|
|
77
|
+
* @param {object} [options={}]
|
|
78
|
+
*/
|
|
79
|
+
export function runConfigChangeHook(event = {}, options = {}) {
|
|
80
|
+
const sessionId = event.session_id || event.sessionId || 'default';
|
|
81
|
+
const cwdOptions = event.cwd && !options.cwd ? { ...options, cwd: event.cwd } : options;
|
|
82
|
+
const horizonConfig = options.horizonConfig || loadHorizonConfig(cwdOptions);
|
|
83
|
+
const liveState = options.telemetryState || readLiveStateSnapshot(sessionId, cwdOptions) || {};
|
|
84
|
+
|
|
85
|
+
const effectiveMode = normalizeFlightMode(
|
|
86
|
+
event.mode || options.mode || liveState.flightMode || horizonConfig.flightMode || 'COACH'
|
|
87
|
+
);
|
|
88
|
+
const detOverride = resolveDetectorOverride('DET-09', horizonConfig);
|
|
89
|
+
|
|
90
|
+
if (isSilentOrOffMode(effectiveMode) || detOverride === 'off') {
|
|
91
|
+
return {
|
|
92
|
+
exitCode: 0,
|
|
93
|
+
stdout: '',
|
|
94
|
+
stderr: '',
|
|
95
|
+
verdict: { triggered: false, decision: 'allow', reason: null }
|
|
96
|
+
};
|
|
97
|
+
}
|
|
98
|
+
|
|
99
|
+
const classification = classifyConfigMutation(event);
|
|
100
|
+
if (!classification.busting) {
|
|
101
|
+
return {
|
|
102
|
+
exitCode: 0,
|
|
103
|
+
stdout: '',
|
|
104
|
+
stderr: '',
|
|
105
|
+
verdict: { triggered: false, decision: 'allow', reason: null }
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
|
|
109
|
+
if (
|
|
110
|
+
event.old_value !== undefined &&
|
|
111
|
+
event.new_value !== undefined &&
|
|
112
|
+
JSON.stringify(event.old_value) === JSON.stringify(event.new_value)
|
|
113
|
+
) {
|
|
114
|
+
return {
|
|
115
|
+
exitCode: 0,
|
|
116
|
+
stdout: '',
|
|
117
|
+
stderr: '',
|
|
118
|
+
verdict: { triggered: false, decision: 'allow', reason: 'Unchanged config value.' }
|
|
119
|
+
};
|
|
120
|
+
}
|
|
121
|
+
|
|
122
|
+
const cachedTokens = Math.max(
|
|
123
|
+
0,
|
|
124
|
+
Number(
|
|
125
|
+
event.cached_tokens ??
|
|
126
|
+
event.cachedTokens ??
|
|
127
|
+
liveState?.contextWindow?.cachedTokens ??
|
|
128
|
+
liveState?.contextWindow?.cacheReadTokens ??
|
|
129
|
+
0
|
|
130
|
+
)
|
|
131
|
+
);
|
|
132
|
+
const ttlSeconds = Number(
|
|
133
|
+
event.ttl_remaining_seconds ??
|
|
134
|
+
event.ttlRemainingSeconds ??
|
|
135
|
+
liveState?.promptCache?.ttlSeconds ??
|
|
136
|
+
300
|
|
137
|
+
);
|
|
138
|
+
const cacheWarm =
|
|
139
|
+
ttlSeconds > 0 &&
|
|
140
|
+
Boolean(event.cache_warm ?? event.cacheWarm ?? liveState?.promptCache?.warm ?? cachedTokens > 0);
|
|
141
|
+
const floorTokens = Number(
|
|
142
|
+
options.warmCacheFloorTokens ?? WARM_CACHE_CONFIG_GUARD_FLOOR_TOKENS
|
|
143
|
+
);
|
|
144
|
+
|
|
145
|
+
if (!cacheWarm || cachedTokens < floorTokens) {
|
|
146
|
+
return {
|
|
147
|
+
exitCode: 0,
|
|
148
|
+
stdout: '',
|
|
149
|
+
stderr: '',
|
|
150
|
+
verdict: {
|
|
151
|
+
triggered: false,
|
|
152
|
+
decision: 'allow',
|
|
153
|
+
cachedTokens,
|
|
154
|
+
reason: 'Cache cold or below warm-prefix guard floor.'
|
|
155
|
+
}
|
|
156
|
+
};
|
|
157
|
+
}
|
|
158
|
+
|
|
159
|
+
const currentModel = String(
|
|
160
|
+
event.old_model ||
|
|
161
|
+
(classification.kind === 'model' ? event.old_value : null) ||
|
|
162
|
+
event.model ||
|
|
163
|
+
liveState.modelId ||
|
|
164
|
+
'claude-opus-5-5'
|
|
165
|
+
);
|
|
166
|
+
|
|
167
|
+
// Gemini thinking-level changes preserve implicit cache; only Anthropic/Claude effort changes bust cached history
|
|
168
|
+
if (classification.kind === 'effort' && /gemini/i.test(currentModel)) {
|
|
169
|
+
return {
|
|
170
|
+
exitCode: 0,
|
|
171
|
+
stdout: '',
|
|
172
|
+
stderr: '',
|
|
173
|
+
verdict: {
|
|
174
|
+
triggered: false,
|
|
175
|
+
decision: 'allow',
|
|
176
|
+
reason: 'Gemini thinking-level adjustments preserve implicit prefix cache.'
|
|
177
|
+
}
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
// Item 1.2: Unknown model -> explicit unknownModel state (zero $ figures, no price-based hold, one-line advisory)
|
|
182
|
+
if (!isKnownCatalogModel(currentModel, cwdOptions)) {
|
|
183
|
+
const effortClause =
|
|
184
|
+
classification.kind === 'effort' ? ' (effort cache behavior unverified for this model)' : '';
|
|
185
|
+
const msg = `[Highbeam DET-09 Advisory] Prices are unknown for ${currentModel}${effortClause}; skipping price-based guard.`;
|
|
186
|
+
const stdoutJson = {
|
|
187
|
+
systemMessage: msg,
|
|
188
|
+
hookSpecificOutput: {
|
|
189
|
+
hookEventName: 'ConfigChange',
|
|
190
|
+
additionalContext: msg
|
|
191
|
+
}
|
|
192
|
+
};
|
|
193
|
+
return {
|
|
194
|
+
exitCode: 0,
|
|
195
|
+
stdout: JSON.stringify(stdoutJson),
|
|
196
|
+
stdoutJson,
|
|
197
|
+
stderr: '',
|
|
198
|
+
verdict: {
|
|
199
|
+
detectorId: 'DET-09',
|
|
200
|
+
triggered: false,
|
|
201
|
+
kind: classification.kind,
|
|
202
|
+
key: classification.key,
|
|
203
|
+
decision: 'allow',
|
|
204
|
+
advisory: true,
|
|
205
|
+
unknownModel: true,
|
|
206
|
+
cachedTokens,
|
|
207
|
+
avoidedRewritePenaltyUSD: null,
|
|
208
|
+
effortCacheCapability:
|
|
209
|
+
classification.kind === 'effort'
|
|
210
|
+
? getEffortMutationCacheCapability(currentModel, cwdOptions)
|
|
211
|
+
: null,
|
|
212
|
+
reason: msg
|
|
213
|
+
}
|
|
214
|
+
};
|
|
215
|
+
}
|
|
216
|
+
|
|
217
|
+
// Item 3: DET-09 effort capability matrix (stay silent on measured cache-preserving models like Sonnet 5.5 / Opus 5.5)
|
|
218
|
+
const normalizedCurrentModel = normalizeModelId(currentModel);
|
|
219
|
+
const effortCap =
|
|
220
|
+
classification.kind === 'effort'
|
|
221
|
+
? getEffortMutationCacheCapability(normalizedCurrentModel, cwdOptions)
|
|
222
|
+
: null;
|
|
223
|
+
|
|
224
|
+
if (effortCap && effortCap.invalidatesCache === 'no') {
|
|
225
|
+
return {
|
|
226
|
+
exitCode: 0,
|
|
227
|
+
stdout: '',
|
|
228
|
+
stderr: '',
|
|
229
|
+
verdict: {
|
|
230
|
+
detectorId: 'DET-09',
|
|
231
|
+
triggered: false,
|
|
232
|
+
kind: classification.kind,
|
|
233
|
+
key: classification.key,
|
|
234
|
+
decision: 'allow',
|
|
235
|
+
advisory: false,
|
|
236
|
+
cachedTokens,
|
|
237
|
+
avoidedRewritePenaltyUSD: 0,
|
|
238
|
+
effortCacheCapability: effortCap,
|
|
239
|
+
reason: null
|
|
240
|
+
}
|
|
241
|
+
};
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
const totalPromptTokens = Math.max(
|
|
245
|
+
cachedTokens,
|
|
246
|
+
computeTotalPromptTokens(liveState.contextWindow || { cacheReadTokens: cachedTokens })
|
|
247
|
+
);
|
|
248
|
+
const ttlTier = liveState?.promptCache?.ttlTier === '1h' ? '1h' : '5m';
|
|
249
|
+
const rates = resolveEffectiveRates(normalizedCurrentModel, totalPromptTokens, cwdOptions);
|
|
250
|
+
const writeRate = ttlTier === '1h' ? rates.write1hPer1M : rates.write5mPer1M;
|
|
251
|
+
const avoidedRewritePenaltyUSD = Number(
|
|
252
|
+
Math.max(0, (cachedTokens / 1_000_000) * (writeRate - rates.readPer1M)).toFixed(6)
|
|
253
|
+
);
|
|
254
|
+
|
|
255
|
+
const router = new CacheGravityRouter({ mode: effectiveMode, ...cwdOptions });
|
|
256
|
+
const priorSnap = readBreakerStateSnapshot(sessionId, cwdOptions) || {};
|
|
257
|
+
if (Array.isArray(priorSnap.queuedMutations)) {
|
|
258
|
+
router.mutationQueue.items = [...priorSnap.queuedMutations];
|
|
259
|
+
}
|
|
260
|
+
|
|
261
|
+
let nextPendingDownshift = priorSnap.pendingDownshiftModel || null;
|
|
262
|
+
let nextPendingDownshiftRecord = priorSnap.pending_downshift || null;
|
|
263
|
+
const newValStr =
|
|
264
|
+
typeof event.new_value === 'string'
|
|
265
|
+
? event.new_value
|
|
266
|
+
: JSON.stringify(event.new_value ?? '');
|
|
267
|
+
|
|
268
|
+
if (classification.kind === 'model' && isOpusToSonnetDownshift(normalizedCurrentModel, newValStr)) {
|
|
269
|
+
nextPendingDownshift = normalizeModelId(newValStr);
|
|
270
|
+
nextPendingDownshiftRecord = {
|
|
271
|
+
fromModel: normalizedCurrentModel,
|
|
272
|
+
toModel: nextPendingDownshift,
|
|
273
|
+
recordedAt: new Date().toISOString()
|
|
274
|
+
};
|
|
275
|
+
}
|
|
276
|
+
|
|
277
|
+
router.mutationQueue.enqueue({
|
|
278
|
+
type: classification.kind,
|
|
279
|
+
key: classification.key,
|
|
280
|
+
value: event.new_value,
|
|
281
|
+
cachedTokens,
|
|
282
|
+
avoidedRewritePenaltyUSD,
|
|
283
|
+
reason: `Deferred ${classification.kind} change (${classification.key}) until PostCompact`
|
|
284
|
+
});
|
|
285
|
+
|
|
286
|
+
if (options.persistState !== false && Boolean(event.cwd || options.cwd || options.breakerStatePath)) {
|
|
287
|
+
writeBreakerStateSnapshot(
|
|
288
|
+
sessionId,
|
|
289
|
+
{
|
|
290
|
+
...priorSnap,
|
|
291
|
+
updatedAt: Date.now(),
|
|
292
|
+
pendingDownshiftModel: nextPendingDownshift,
|
|
293
|
+
pending_downshift: nextPendingDownshiftRecord,
|
|
294
|
+
queuedMutations: router.mutationQueue.toJSON()
|
|
295
|
+
},
|
|
296
|
+
cwdOptions
|
|
297
|
+
);
|
|
298
|
+
}
|
|
299
|
+
|
|
300
|
+
const shouldBlock = effectiveMode === FLIGHT_MODES.AUTO_PILOT || detOverride === 'block';
|
|
301
|
+
const downshiftHint = nextPendingDownshift
|
|
302
|
+
? ` Queued pending_downshift -> ${nextPendingDownshift} for next compaction.`
|
|
303
|
+
: ' Wait for /compact or spawn an isolated subagent instead.';
|
|
304
|
+
const effortLabel =
|
|
305
|
+
effortCap?.invalidatesCache === 'unknown'
|
|
306
|
+
? ' (unverified for this model)'
|
|
307
|
+
: effortCap?.provenance
|
|
308
|
+
? ` (${effortCap.provenance})`
|
|
309
|
+
: '';
|
|
310
|
+
const message =
|
|
311
|
+
`[Highbeam Quota Shield — Warm-Cache Config Bust (${classification.kind})${effortLabel}] ` +
|
|
312
|
+
`Changing "${classification.key}" while ${cachedTokens.toLocaleString()} tokens are warm on ${normalizedCurrentModel} ` +
|
|
313
|
+
`invalidates the prompt cache prefix (+$${avoidedRewritePenaltyUSD.toFixed(4)} cold rewrite tax).` +
|
|
314
|
+
downshiftHint;
|
|
315
|
+
|
|
316
|
+
if (
|
|
317
|
+
shouldBlock &&
|
|
318
|
+
avoidedRewritePenaltyUSD > 0 &&
|
|
319
|
+
options.recordLedger !== false &&
|
|
320
|
+
Boolean(event.cwd || options.cwd || options.ledgerPath || options.recordLedger)
|
|
321
|
+
) {
|
|
322
|
+
recordInterventionSavings(
|
|
323
|
+
{
|
|
324
|
+
sessionId,
|
|
325
|
+
category: 'DET_09_CONFIG_CACHE_SHIELD',
|
|
326
|
+
modelId: normalizedCurrentModel,
|
|
327
|
+
savedTokens: cachedTokens,
|
|
328
|
+
savedUSD: avoidedRewritePenaltyUSD,
|
|
329
|
+
dedupeId: `${classification.kind}:${classification.key}:${cachedTokens}`,
|
|
330
|
+
detail: `Held warm-prefix ${classification.kind} mutation (${cachedTokens.toLocaleString()} tok)`
|
|
331
|
+
},
|
|
332
|
+
cwdOptions
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
const verdict = {
|
|
337
|
+
detectorId: 'DET-09',
|
|
338
|
+
triggered: true,
|
|
339
|
+
kind: classification.kind,
|
|
340
|
+
key: classification.key,
|
|
341
|
+
decision: shouldBlock ? 'block' : 'allow',
|
|
342
|
+
advisory: !shouldBlock,
|
|
343
|
+
cachedTokens,
|
|
344
|
+
avoidedRewritePenaltyUSD,
|
|
345
|
+
effortCacheCapability: effortCap,
|
|
346
|
+
pendingDownshiftModel: nextPendingDownshift,
|
|
347
|
+
pending_downshift: nextPendingDownshiftRecord,
|
|
348
|
+
reason: message
|
|
349
|
+
};
|
|
350
|
+
|
|
351
|
+
if (shouldBlock) {
|
|
352
|
+
const stdoutJson = {
|
|
353
|
+
decision: 'block',
|
|
354
|
+
reason: message
|
|
355
|
+
};
|
|
356
|
+
return {
|
|
357
|
+
exitCode: 0,
|
|
358
|
+
stdout: JSON.stringify(stdoutJson),
|
|
359
|
+
stdoutJson,
|
|
360
|
+
stderr: '',
|
|
361
|
+
verdict
|
|
362
|
+
};
|
|
363
|
+
}
|
|
364
|
+
|
|
365
|
+
const stdoutJson = {
|
|
366
|
+
systemMessage: message,
|
|
367
|
+
hookSpecificOutput: {
|
|
368
|
+
hookEventName: 'ConfigChange',
|
|
369
|
+
additionalContext: message
|
|
370
|
+
}
|
|
371
|
+
};
|
|
372
|
+
return {
|
|
373
|
+
exitCode: 0,
|
|
374
|
+
stdout: JSON.stringify(stdoutJson),
|
|
375
|
+
stdoutJson,
|
|
376
|
+
stderr: '',
|
|
377
|
+
verdict
|
|
378
|
+
};
|
|
379
|
+
}
|
|
380
|
+
|
|
381
|
+
export async function executeConfigChangeCli(cliOptions = {}) {
|
|
382
|
+
const readPayload = cliOptions.readPayload || readStdinJsonAsync;
|
|
383
|
+
const runHook = cliOptions.runHook || runConfigChangeHook;
|
|
384
|
+
const ioOverride = cliOptions.ioOverride || {};
|
|
385
|
+
try {
|
|
386
|
+
const payload = await readPayload(cliOptions.timeoutMs);
|
|
387
|
+
const res = runHook(payload, { persistState: true, ...(cliOptions.hookOptions || {}) });
|
|
388
|
+
if (res.stdout) {
|
|
389
|
+
exitWithStdoutJson(res.stdout, ioOverride);
|
|
390
|
+
} else {
|
|
391
|
+
exitPassThrough(ioOverride.exitFn);
|
|
392
|
+
}
|
|
393
|
+
} catch (err) {
|
|
394
|
+
exitDiagnosticZero(err?.message || String(err), 'ConfigChange', ioOverride);
|
|
395
|
+
}
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
if (isCliEntrypoint(import.meta.url)) {
|
|
399
|
+
executeConfigChangeCli().catch((err) => {
|
|
400
|
+
exitDiagnosticZero(err?.message || String(err), 'ConfigChange');
|
|
401
|
+
});
|
|
402
|
+
}
|
|
@@ -0,0 +1,311 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/handlers/hookIo.mjs
|
|
3
|
+
* Shared stdin JSON reader, `realpathSync` CLI entrypoint resolver, and Claude Code hook
|
|
4
|
+
* exit/JSON contract emitter (`ISS-032`, `ISS-034`, `ISS-035`).
|
|
5
|
+
*
|
|
6
|
+
* Contract:
|
|
7
|
+
* - Pass-through: exit `0` with empty stdout.
|
|
8
|
+
* - Hard block (`exit 2`): write concise diagnostic to `stderr` and exit `2` with EMPTY stdout.
|
|
9
|
+
* - Structured decision (`exit 0` JSON): write valid top-level or `hookSpecificOutput` JSON to `stdout` and exit `0`.
|
|
10
|
+
* - Non-blocking lifecycle error: write diagnostic to `stderr` and exit `0`.
|
|
11
|
+
* - Never register veto exit-2 logic on `WorktreeCreate` or `PermissionRequest`.
|
|
12
|
+
*/
|
|
13
|
+
|
|
14
|
+
import { fs, path, fileURLToPath } from '../../src/utils/nodeIo.mjs';
|
|
15
|
+
|
|
16
|
+
/**
|
|
17
|
+
* Checks whether the current module is being executed directly as the CLI entrypoint,
|
|
18
|
+
* normalizing symlinks (`npx`, `.bin/*`, junctions) via `fs.realpathSync` (`ISS-032`, `ISS-035`).
|
|
19
|
+
*
|
|
20
|
+
* @param {string} importMetaUrl
|
|
21
|
+
* @param {string} [argv1=globalThis.process?.argv?.[1]]
|
|
22
|
+
* @returns {boolean}
|
|
23
|
+
*/
|
|
24
|
+
export function isCliEntrypoint(importMetaUrl, argv1 = globalThis.process?.argv?.[1]) {
|
|
25
|
+
if (!importMetaUrl || !argv1) return false;
|
|
26
|
+
try {
|
|
27
|
+
const modulePath = fileURLToPath(importMetaUrl);
|
|
28
|
+
const targetPath = path.resolve(String(argv1));
|
|
29
|
+
try {
|
|
30
|
+
return fs.realpathSync(modulePath) === fs.realpathSync(targetPath);
|
|
31
|
+
} catch {
|
|
32
|
+
return path.normalize(modulePath) === path.normalize(targetPath);
|
|
33
|
+
}
|
|
34
|
+
} catch {
|
|
35
|
+
return false;
|
|
36
|
+
}
|
|
37
|
+
}
|
|
38
|
+
|
|
39
|
+
/**
|
|
40
|
+
* Reads all stdin synchronously (fd 0) when piped, returning `{}` immediately on TTY or empty stdin.
|
|
41
|
+
* Throws a `SyntaxError` on non-empty malformed JSON unless `options.allowMalformed` is `true` (`ISS-061`).
|
|
42
|
+
*
|
|
43
|
+
* @param {{ allowMalformed?: boolean }} [options={}]
|
|
44
|
+
* @returns {object}
|
|
45
|
+
*/
|
|
46
|
+
export function readStdinJson(options = {}) {
|
|
47
|
+
if (!fs || globalThis.process?.stdin?.isTTY) return {};
|
|
48
|
+
let raw = '';
|
|
49
|
+
try {
|
|
50
|
+
raw = fs.readFileSync(0, 'utf8').trim();
|
|
51
|
+
} catch {
|
|
52
|
+
return {};
|
|
53
|
+
}
|
|
54
|
+
if (!raw) return {};
|
|
55
|
+
try {
|
|
56
|
+
const parsed = JSON.parse(raw);
|
|
57
|
+
if (!parsed || typeof parsed !== 'object' || Array.isArray(parsed)) {
|
|
58
|
+
if (options?.allowMalformed) return {};
|
|
59
|
+
throw new SyntaxError('Stdin JSON payload must be a JSON object');
|
|
60
|
+
}
|
|
61
|
+
return parsed;
|
|
62
|
+
} catch (err) {
|
|
63
|
+
if (options?.allowMalformed) return {};
|
|
64
|
+
throw err;
|
|
65
|
+
}
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Reads piped stdin JSON asynchronously with a bounded timeout (`ISS-035`, `ISS-061`).
|
|
70
|
+
* Resolves `{}` cleanly without hanging if stdin is a TTY or empty/stalled without bytes,
|
|
71
|
+
* and rejects with `SyntaxError` when non-empty stdin is malformed non-object JSON
|
|
72
|
+
* (unless `options.allowMalformed === true`) so guard hooks fail CLOSED (`exit 2`)
|
|
73
|
+
* while advisory hooks fail SAFE (`exit 0`).
|
|
74
|
+
*
|
|
75
|
+
* @param {number} [timeoutMs=2000]
|
|
76
|
+
* @param {any} [stdinStream=globalThis.process?.stdin]
|
|
77
|
+
* @param {{ allowMalformed?: boolean }} [options={}]
|
|
78
|
+
* @returns {Promise<object>}
|
|
79
|
+
*/
|
|
80
|
+
export function readStdinJsonAsync(
|
|
81
|
+
timeoutMs = 2000,
|
|
82
|
+
stdinStream = globalThis.process?.stdin,
|
|
83
|
+
options = {}
|
|
84
|
+
) {
|
|
85
|
+
return new Promise((resolve, reject) => {
|
|
86
|
+
if (!stdinStream || stdinStream.isTTY) {
|
|
87
|
+
resolve({});
|
|
88
|
+
return;
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
let raw = '';
|
|
92
|
+
let settled = false;
|
|
93
|
+
|
|
94
|
+
const cleanupStream = () => {
|
|
95
|
+
clearTimeout(timer);
|
|
96
|
+
try {
|
|
97
|
+
stdinStream.removeListener('data', onData);
|
|
98
|
+
stdinStream.removeListener('end', onEnd);
|
|
99
|
+
stdinStream.removeListener('error', onError);
|
|
100
|
+
if (typeof stdinStream.pause === 'function') stdinStream.pause();
|
|
101
|
+
if (typeof stdinStream.unref === 'function') stdinStream.unref();
|
|
102
|
+
} catch {
|
|
103
|
+
// Ignore stream cleanup errors
|
|
104
|
+
}
|
|
105
|
+
};
|
|
106
|
+
|
|
107
|
+
const finishResolve = (parsedValue) => {
|
|
108
|
+
if (settled) return;
|
|
109
|
+
settled = true;
|
|
110
|
+
cleanupStream();
|
|
111
|
+
resolve(parsedValue);
|
|
112
|
+
};
|
|
113
|
+
|
|
114
|
+
const finishReject = (err) => {
|
|
115
|
+
if (settled) return;
|
|
116
|
+
settled = true;
|
|
117
|
+
cleanupStream();
|
|
118
|
+
reject(err);
|
|
119
|
+
};
|
|
120
|
+
|
|
121
|
+
const settleFromRaw = () => {
|
|
122
|
+
const trimmed = raw.trim();
|
|
123
|
+
if (!trimmed) {
|
|
124
|
+
finishResolve({});
|
|
125
|
+
return;
|
|
126
|
+
}
|
|
127
|
+
try {
|
|
128
|
+
const obj = JSON.parse(trimmed);
|
|
129
|
+
if (!obj || typeof obj !== 'object' || Array.isArray(obj)) {
|
|
130
|
+
if (options?.allowMalformed) {
|
|
131
|
+
finishResolve({});
|
|
132
|
+
return;
|
|
133
|
+
}
|
|
134
|
+
finishReject(new SyntaxError('Malformed stdin JSON payload: expected JSON object'));
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
finishResolve(obj);
|
|
138
|
+
} catch (err) {
|
|
139
|
+
if (options?.allowMalformed) {
|
|
140
|
+
finishResolve({});
|
|
141
|
+
return;
|
|
142
|
+
}
|
|
143
|
+
finishReject(
|
|
144
|
+
new SyntaxError(`Malformed stdin JSON payload: ${err?.message || String(err)}`)
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
};
|
|
148
|
+
|
|
149
|
+
const onData = (chunk) => {
|
|
150
|
+
raw += typeof chunk === 'string' ? chunk : Buffer.from(chunk).toString('utf8');
|
|
151
|
+
};
|
|
152
|
+
const onEnd = () => settleFromRaw();
|
|
153
|
+
const onError = () => finishResolve({});
|
|
154
|
+
|
|
155
|
+
const timer = setTimeout(() => {
|
|
156
|
+
settleFromRaw();
|
|
157
|
+
}, Math.max(10, Number(timeoutMs) || 2000));
|
|
158
|
+
|
|
159
|
+
if (typeof timer.unref === 'function') {
|
|
160
|
+
timer.unref();
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
try {
|
|
164
|
+
if (typeof stdinStream.setEncoding === 'function') {
|
|
165
|
+
stdinStream.setEncoding('utf8');
|
|
166
|
+
}
|
|
167
|
+
stdinStream.on('data', onData);
|
|
168
|
+
stdinStream.on('end', onEnd);
|
|
169
|
+
stdinStream.on('error', onError);
|
|
170
|
+
if (typeof stdinStream.resume === 'function') {
|
|
171
|
+
stdinStream.resume();
|
|
172
|
+
}
|
|
173
|
+
} catch {
|
|
174
|
+
finishResolve({});
|
|
175
|
+
}
|
|
176
|
+
});
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
/**
|
|
180
|
+
* Exits `0` silently with empty stdout (pass-through).
|
|
181
|
+
*
|
|
182
|
+
* @param {Function} [exitFn=globalThis.process?.exit]
|
|
183
|
+
*/
|
|
184
|
+
export function exitPassThrough(exitFn = globalThis.process?.exit) {
|
|
185
|
+
exitFn?.(0);
|
|
186
|
+
}
|
|
187
|
+
|
|
188
|
+
/**
|
|
189
|
+
* Writes a non-blocking diagnostic message to `stderr` and exits `0` (`ISS-035`).
|
|
190
|
+
*
|
|
191
|
+
* @param {string} reason
|
|
192
|
+
* @param {string} [hookEventName='Hook']
|
|
193
|
+
* @param {{ stderrWrite?: Function, exitFn?: Function }} [ioOverride={}]
|
|
194
|
+
*/
|
|
195
|
+
export function exitDiagnosticZero(reason, hookEventName = 'Hook', ioOverride = {}) {
|
|
196
|
+
const writeStderr =
|
|
197
|
+
ioOverride.stderrWrite ||
|
|
198
|
+
ioOverride.writeStderr ||
|
|
199
|
+
((s) => globalThis.process?.stderr?.write?.(s));
|
|
200
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
201
|
+
const msg = String(reason || 'Unexpected hook diagnostic').trim();
|
|
202
|
+
writeStderr(`[Highbeam ${hookEventName} Diagnostic] ${msg}\n`);
|
|
203
|
+
exitFn?.(0);
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
/**
|
|
207
|
+
* Exits `2` with concise diagnostic on `stderr` and strictly empty `stdout`.
|
|
208
|
+
* Never used on `WorktreeCreate` or `PermissionRequest`.
|
|
209
|
+
*
|
|
210
|
+
* @param {string} reason
|
|
211
|
+
* @param {string} [hookEventName='PreToolUse']
|
|
212
|
+
* @param {{ stderrWrite?: Function, writeStderr?: Function, exitFn?: Function }} [ioOverride={}]
|
|
213
|
+
*/
|
|
214
|
+
export function exitHardBlockStderr(reason, hookEventName = 'PreToolUse', ioOverride = {}) {
|
|
215
|
+
const writeStderr =
|
|
216
|
+
ioOverride.stderrWrite ||
|
|
217
|
+
ioOverride.writeStderr ||
|
|
218
|
+
((s) => globalThis.process?.stderr?.write?.(s));
|
|
219
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
220
|
+
|
|
221
|
+
if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
|
|
222
|
+
exitPassThrough(exitFn);
|
|
223
|
+
return;
|
|
224
|
+
}
|
|
225
|
+
const msg = String(reason || 'Blocked by Highbeam circuit breaker').trim();
|
|
226
|
+
writeStderr(`${msg}\n`);
|
|
227
|
+
exitFn?.(2);
|
|
228
|
+
}
|
|
229
|
+
|
|
230
|
+
/**
|
|
231
|
+
* Emits a serialized JSON string or object to `stdout` and exits `0`.
|
|
232
|
+
*
|
|
233
|
+
* @param {string | object} payload
|
|
234
|
+
* @param {{ stdoutWrite?: Function, writeStdout?: Function, exitFn?: Function }} [ioOverride={}]
|
|
235
|
+
*/
|
|
236
|
+
export function exitWithStdoutJson(payload, ioOverride = {}) {
|
|
237
|
+
const writeStdout =
|
|
238
|
+
ioOverride.stdoutWrite ||
|
|
239
|
+
ioOverride.writeStdout ||
|
|
240
|
+
((s) => globalThis.process?.stdout?.write?.(s));
|
|
241
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
242
|
+
const serialized = typeof payload === 'string' ? payload : JSON.stringify(payload);
|
|
243
|
+
writeStdout(`${serialized}\n`);
|
|
244
|
+
exitFn?.(0);
|
|
245
|
+
}
|
|
246
|
+
|
|
247
|
+
/**
|
|
248
|
+
* Emits a structured `{ hookSpecificOutput }` JSON object to `stdout` and exits `0`.
|
|
249
|
+
*
|
|
250
|
+
* @param {object} hookSpecificOutput
|
|
251
|
+
* @param {{ stdoutWrite?: Function, exitFn?: Function }} [ioOverride={}]
|
|
252
|
+
*/
|
|
253
|
+
export function exitWithHookSpecificOutput(hookSpecificOutput, ioOverride = {}) {
|
|
254
|
+
exitWithStdoutJson({ hookSpecificOutput }, ioOverride);
|
|
255
|
+
}
|
|
256
|
+
|
|
257
|
+
/**
|
|
258
|
+
* Arms a self-timeout fail-closed watchdog below host hook kill deadline (`FM-8`).
|
|
259
|
+
* When triggered before `disarm()`, invokes `onTimeout()` and exits `2` via stderr.
|
|
260
|
+
*
|
|
261
|
+
* @param {object} [options={}]
|
|
262
|
+
*/
|
|
263
|
+
export function armFailClosedWatchdog(options = {}) {
|
|
264
|
+
const timeoutMs = Math.max(50, Math.min(4500, Number(options.timeoutMs) || 3500));
|
|
265
|
+
const hookEventName = options.hookEventName || 'PreToolUse';
|
|
266
|
+
const ioOverride = options.ioOverride || {};
|
|
267
|
+
const exitFn = ioOverride.exitFn || globalThis.process?.exit;
|
|
268
|
+
const stderrWrite =
|
|
269
|
+
ioOverride.stderrWrite ||
|
|
270
|
+
ioOverride.writeStderr ||
|
|
271
|
+
((s) => globalThis.process?.stderr?.write?.(s));
|
|
272
|
+
let settled = false;
|
|
273
|
+
let timedOut = false;
|
|
274
|
+
|
|
275
|
+
const timer = setTimeout(() => {
|
|
276
|
+
if (settled) return;
|
|
277
|
+
settled = true;
|
|
278
|
+
timedOut = true;
|
|
279
|
+
try {
|
|
280
|
+
if (typeof options.onTimeout === 'function') {
|
|
281
|
+
options.onTimeout({ timeoutMs, hookEventName });
|
|
282
|
+
}
|
|
283
|
+
} catch {
|
|
284
|
+
// ignore timeout callback failure and still fail closed
|
|
285
|
+
}
|
|
286
|
+
const msg = String(
|
|
287
|
+
options.reason ||
|
|
288
|
+
`[Hook Watchdog] ${hookEventName} exceeded ${timeoutMs}ms internal deadline; failing closed (exit 2).`
|
|
289
|
+
).trim();
|
|
290
|
+
if (hookEventName === 'WorktreeCreate' || hookEventName === 'PermissionRequest') {
|
|
291
|
+
exitFn?.(0);
|
|
292
|
+
return;
|
|
293
|
+
}
|
|
294
|
+
stderrWrite?.(`${msg}\n`);
|
|
295
|
+
exitFn?.(2);
|
|
296
|
+
}, timeoutMs);
|
|
297
|
+
|
|
298
|
+
if (typeof timer.unref === 'function') {
|
|
299
|
+
timer.unref();
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
return {
|
|
303
|
+
timeoutMs,
|
|
304
|
+
isTimedOut: () => timedOut,
|
|
305
|
+
disarm: () => {
|
|
306
|
+
if (settled) return;
|
|
307
|
+
settled = true;
|
|
308
|
+
clearTimeout(timer);
|
|
309
|
+
}
|
|
310
|
+
};
|
|
311
|
+
}
|