ctxtop 0.0.0-stage → 4.0.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/.antigravity-plugin/plugin.json +36 -0
- package/.claude-plugin/plugin.json +18 -0
- package/CHECKSUMS.sha256 +149 -0
- package/LICENSE +27 -0
- package/README.md +330 -3
- package/SECURITY.md +22 -0
- package/agents/ah-flash-scout.md +25 -0
- package/assets/advanced_view_loaded_420px.png +0 -0
- package/assets/hero-demo.svg +188 -0
- package/assets/logo.svg +19 -0
- package/assets/simple_view_lean_420px.png +0 -0
- package/assets/simple_view_loaded_420px.png +0 -0
- package/assets/social-preview.svg +72 -0
- package/assets/zone_c_step3_shield_full.png +0 -0
- package/bin/ah-statusline.mjs +145 -0
- package/bin/cli.mjs +3 -0
- package/bin/ctxtop.mjs +1474 -0
- package/commands/cost-radar.md +11 -0
- package/commands/evolve.md +10 -0
- package/commands/handoff.md +10 -0
- package/commands/horizon.md +10 -0
- package/commands/inspect.md +10 -0
- package/commands/precheck.md +10 -0
- package/config/default_flightcheck.json +114 -0
- package/config/modelCatalog.json +620 -0
- package/config/platformQuirks.json +19 -0
- package/hooks/handlers/compact-lifecycle.mjs +262 -0
- package/hooks/handlers/hookIo.mjs +255 -0
- package/hooks/handlers/hookIpcClient.mjs +83 -0
- package/hooks/handlers/post-tool-use.mjs +265 -0
- package/hooks/handlers/pre-model-switch.mjs +249 -0
- package/hooks/handlers/pre-tool-use.mjs +365 -0
- package/hooks/handlers/stop-gate.mjs +240 -0
- package/hooks/handlers/user-prompt-submit.mjs +143 -0
- package/hooks/hooks.json +81 -0
- package/hooks/post_invocation.mjs +13 -0
- package/hooks/post_tool_use.mjs +17 -0
- package/hooks/pre_invocation.mjs +14 -0
- package/hooks/pre_tool_use.mjs +97 -0
- package/hooks/register.js +687 -0
- package/hooks/session_start.mjs +14 -0
- package/hooks/stop.mjs +13 -0
- package/hooks.json +56 -0
- package/package.json +103 -4
- package/packages/antigravity/package.json +14 -0
- package/packages/antigravity/src/index.mjs +1 -0
- package/packages/claude-code/package.json +14 -0
- package/packages/claude-code/src/index.mjs +2 -0
- package/packages/core/package.json +14 -0
- package/packages/core/src/index.mjs +1 -0
- package/packages/engine-node/package.json +14 -0
- package/packages/engine-node/src/index.mjs +1 -0
- package/packages/mcp/package.json +17 -0
- package/packages/mcp/src/server.mjs +396 -0
- package/packages/pro/LICENSE-COMMERCIAL.md +19 -0
- package/packages/pro/README-SIGNING.md +30 -0
- package/packages/pro/package.json +16 -0
- package/packages/pro/src/index.mjs +3 -0
- package/packages/pro/src/team_finops_pack.mjs +241 -0
- package/packages/pro/workers/polar_webhook_worker.mjs +215 -0
- package/plugin.json +36 -0
- package/rules/AGENTS.md +10 -0
- package/sidecars/horizon-daemon/ipcServer.mjs +24 -0
- package/sidecars/horizon-daemon/server.mjs +2002 -0
- package/sidecars/horizon-daemon/sidecar.json +19 -0
- package/skills/cost-radar/SKILL.md +21 -0
- package/skills/evolve/SKILL.md +21 -0
- package/skills/handoff/SKILL.md +42 -0
- package/skills/horizon/SKILL.md +17 -0
- package/skills/inspect/SKILL.md +18 -0
- package/skills/precheck/SKILL.md +44 -0
- package/src/adapters/antigravity/index.mjs +79 -0
- package/src/adapters/claude-code/index.mjs +155 -0
- package/src/cli/cost_radar.mjs +70 -0
- package/src/cli/doctor.mjs +351 -0
- package/src/cli/horizon_hud.mjs +686 -0
- package/src/cli/init.mjs +425 -0
- package/src/cli/postmortem.mjs +515 -0
- package/src/coach/cacheGravityRouter.mjs +12 -0
- package/src/config/modelCatalog.json +620 -0
- package/src/config/platformQuirks.json +19 -0
- package/src/core/action_queue.mjs +264 -0
- package/src/core/ag_bridge.mjs +346 -0
- package/src/core/atomic_io.mjs +124 -0
- package/src/core/baseline.mjs +607 -0
- package/src/core/blindspot_sensors.mjs +399 -0
- package/src/core/classifier.mjs +1757 -0
- package/src/core/coach/circuit_breakers.mjs +650 -0
- package/src/core/coach/contradiction_auditor.mjs +239 -0
- package/src/core/coach/effort_advisor.mjs +143 -0
- package/src/core/coach/handoff_hydrator.mjs +483 -0
- package/src/core/coach/progressive_checkpointer.mjs +551 -0
- package/src/core/coach/prompt_decomposer_coach.mjs +141 -0
- package/src/core/coach/reflector_queue.mjs +505 -0
- package/src/core/coach/saved_quota_ledger.mjs +615 -0
- package/src/core/coach/subagent_ipi_sanitizer.mjs +200 -0
- package/src/core/coach/subagent_phantom_auditor.mjs +261 -0
- package/src/core/coach/task_quota_router.mjs +955 -0
- package/src/core/coach/turn_zero_gate.mjs +574 -0
- package/src/core/compaction_coach.mjs +1126 -0
- package/src/core/config.mjs +214 -0
- package/src/core/constants.mjs +1800 -0
- package/src/core/detectors_det01_to_16.mjs +1474 -0
- package/src/core/episodic_memory.mjs +135 -0
- package/src/core/fts5_output_compressor.mjs +359 -0
- package/src/core/git_ledger.mjs +189 -0
- package/src/core/handoff_audit.mjs +558 -0
- package/src/core/history.mjs +221 -0
- package/src/core/hook_diagnostics.mjs +158 -0
- package/src/core/horizon_classifier.mjs +326 -0
- package/src/core/horizon_config.mjs +802 -0
- package/src/core/host_watchdog.mjs +200 -0
- package/src/core/layer5_hygiene.mjs +966 -0
- package/src/core/log_resolver.mjs +231 -0
- package/src/core/mcp_auditor.mjs +138 -0
- package/src/core/micro_skills_store.mjs +91 -0
- package/src/core/offenders.mjs +161 -0
- package/src/core/parser.mjs +1996 -0
- package/src/core/path_canonicalizer.mjs +73 -0
- package/src/core/paths.mjs +310 -0
- package/src/core/prefix_cache_shield.mjs +386 -0
- package/src/core/pro_license.mjs +385 -0
- package/src/core/prompt_rubric.mjs +518 -0
- package/src/core/pruner.mjs +433 -0
- package/src/core/quota.mjs +1860 -0
- package/src/core/rsi_instinct_engine.mjs +1197 -0
- package/src/core/sanitizer.mjs +121 -0
- package/src/core/session_forensics.mjs +303 -0
- package/src/core/session_timeline.mjs +358 -0
- package/src/core/settings.mjs +99 -0
- package/src/core/shared/detectors.mjs +1342 -0
- package/src/core/shared/fnv1a64.mjs +85 -0
- package/src/core/shared/handoff_schema.mjs +123 -0
- package/src/core/shared/index.mjs +5 -0
- package/src/core/shared/ipi_sanitizer.mjs +165 -0
- package/src/core/shared/micro_skills.mjs +1 -0
- package/src/core/shared/plugin_validator.mjs +202 -0
- package/src/core/shared/prompt_hygiene_governor.mjs +1 -0
- package/src/core/sidecar_store.mjs +302 -0
- package/src/core/sprint_metrics.mjs +366 -0
- package/src/core/sqlite_client.mjs +283 -0
- package/src/core/storage_doctor.mjs +358 -0
- package/src/core/subagents.mjs +609 -0
- package/src/core/swarm_topology.mjs +360 -0
- package/src/core/task_quota_router.mjs +1656 -0
- package/src/core/telemetry/cache_ttl_watchdog.mjs +284 -0
- package/src/core/telemetry/scope_lock_registry.mjs +578 -0
- package/src/core/telemetry/shadow_file_detector.mjs +291 -0
- package/src/core/telemetry/trajectory_watcher.mjs +259 -0
- package/src/core/timeline_svg.mjs +236 -0
- package/src/core/tool_surgeon.mjs +305 -0
- package/src/core/trajectory_stitcher.mjs +645 -0
- package/src/core/u_shaped_optimizer.mjs +789 -0
- package/src/core/wal_hygiene.mjs +233 -0
- package/src/core-isomorphic/catalog/detectorCatalog.mjs +558 -0
- package/src/core-isomorphic/catalog/index.mjs +1 -0
- package/src/core-isomorphic/coach/cacheGravityRouter.mjs +720 -0
- package/src/core-isomorphic/coach/microSkills.mjs +1 -0
- package/src/core-isomorphic/coach/promptHygieneGovernor.mjs +1 -0
- package/src/core-isomorphic/coach/repoCalibration.mjs +254 -0
- package/src/core-isomorphic/coach/savedQuotaLedger.mjs +527 -0
- package/src/core-isomorphic/coach/stateBatonHydrator.mjs +810 -0
- package/src/core-isomorphic/coach/ttlWatchdog.mjs +457 -0
- package/src/core-isomorphic/config/anthropicModelCatalog.json +203 -0
- package/src/core-isomorphic/config/catalogLoader.mjs +768 -0
- package/src/core-isomorphic/config/horizonConfig.mjs +1009 -0
- package/src/core-isomorphic/control/callTree.mjs +338 -0
- package/src/core-isomorphic/control/coachLatches.mjs +126 -0
- package/src/core-isomorphic/control/controlStateMachine.mjs +205 -0
- package/src/core-isomorphic/control/index.mjs +49 -0
- package/src/core-isomorphic/control/swarmWorktree.mjs +109 -0
- package/src/core-isomorphic/control/toolSuspension.mjs +197 -0
- package/src/core-isomorphic/diagnostics/drift_guard.mjs +382 -0
- package/src/core-isomorphic/diagnostics/index.mjs +9 -0
- package/src/core-isomorphic/diagnostics/micro_skills.mjs +471 -0
- package/src/core-isomorphic/diagnostics/prompt_hygiene_governor.mjs +622 -0
- package/src/core-isomorphic/economics/billingBlocks.mjs +251 -0
- package/src/core-isomorphic/economics/cacheGravity.mjs +351 -0
- package/src/core-isomorphic/economics/cliffBreaker.mjs +170 -0
- package/src/core-isomorphic/economics/driftLatency.mjs +319 -0
- package/src/core-isomorphic/economics/dualTtl.mjs +198 -0
- package/src/core-isomorphic/economics/index.mjs +47 -0
- package/src/core-isomorphic/economics/retentionRadar.mjs +348 -0
- package/src/core-isomorphic/guards/circuitBreakers.mjs +1202 -0
- package/src/core-isomorphic/guards/det01_03_shell_secret.mjs +1035 -0
- package/src/core-isomorphic/guards/det04_12_thrash_rot.mjs +480 -0
- package/src/core-isomorphic/guards/det13_20_mcp_scope.mjs +603 -0
- package/src/core-isomorphic/guards/losslessPostSanitizer.mjs +301 -0
- package/src/core-isomorphic/index.js +26 -0
- package/src/core-isomorphic/telemetry/otelExporter.mjs +187 -0
- package/src/core-isomorphic/telemetry/scopeLockRegistry.mjs +522 -0
- package/src/core-isomorphic/telemetry/sprintMetrics.mjs +327 -0
- package/src/core-isomorphic/telemetry/swarmTopology.mjs +152 -0
- package/src/core-isomorphic/telemetry/telemetryBridge.mjs +1132 -0
- package/src/core-isomorphic/ui/brailleSparkline.mjs +142 -0
- package/src/core-isomorphic/ui/costRadarSvg.mjs +276 -0
- package/src/core-isomorphic/ui/horizonGrid.mjs +475 -0
- package/src/core-isomorphic/ui/horizonPanelHtml.mjs +1181 -0
- package/src/core-isomorphic/ui/modViews.mjs +1478 -0
- package/src/core-isomorphic/ui/pdfReceiptGenerator.mjs +329 -0
- package/src/core-isomorphic/ustf/index.mjs +7 -0
- package/src/core-isomorphic/ustf/normalizer.mjs +512 -0
- package/src/core-isomorphic/ustf/schema.mjs +186 -0
- package/src/core-isomorphic/utils/runtime.mjs +962 -0
- package/src/demo/synthetic_states.mjs +661 -0
- package/src/diagnostics/bugReportGenerator.mjs +253 -0
- package/src/diagnostics/doctorEngine.mjs +203 -0
- package/src/engine-node/db/index.mjs +58 -0
- package/src/engine-node/db/jsonl_fallback.mjs +184 -0
- package/src/engine-node/db/probe.mjs +110 -0
- package/src/engine-node/db/sqlite_wrapper.mjs +122 -0
- package/src/engine-node/index.mjs +9 -0
- package/src/engine-node/ipc/client.mjs +447 -0
- package/src/engine-node/ipc/index.mjs +22 -0
- package/src/engine-node/ipc/protocol.mjs +177 -0
- package/src/engine-node/ipc/server.mjs +445 -0
- package/src/engine-node/offloader/index.mjs +6 -0
- package/src/engine-node/offloader/tool_offloader.mjs +241 -0
- package/src/engine-node/sensors/blindspots.mjs +369 -0
- package/src/engine-node/sensors/git_merge_tree.mjs +223 -0
- package/src/engine-node/sensors/index.mjs +7 -0
- package/src/hooks/portfolio_runtime.mjs +858 -0
- package/src/hooks/post_invocation.mjs +419 -0
- package/src/hooks/pre_invocation.mjs +1015 -0
- package/src/hooks/session_start.mjs +161 -0
- package/src/shims/agy_cli_compressor.mjs +705 -0
- package/src/shims/agy_git_guard.mjs +749 -0
- package/src/shims/ah_log_query.mjs +39 -0
- package/src/ui/costRadarSvg.mjs +6 -0
- package/src/ui/horizonGrid.mjs +1 -0
- package/src/ui/horizonPanelHtml.mjs +1 -0
- package/src/ui/horizon_panel.css +167 -0
- package/src/ui/horizon_panel.js +212 -0
- package/src/ui/modViews.mjs +1 -0
- package/src/utils/nodeIo.mjs +59 -0
- package/src/utils/runtime.mjs +1 -0
- package/src/webview/advanced_view.html +1808 -0
- package/src/webview/horizon_panel.html +11389 -0
- package/src/webview/registry.mjs +80 -0
- package/src/webview/simple_view.html +1370 -0
|
@@ -0,0 +1,262 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/handlers/compact-lifecycle.mjs
|
|
3
|
+
* Tier 2 Command Hook handler for `PreCompact`, `SessionStart[compact|resume|startup|clear|fork]`,
|
|
4
|
+
* and `PostCompact` (`ISS-034`, `ISS-035`, `ISS-036`).
|
|
5
|
+
*/
|
|
6
|
+
|
|
7
|
+
import {
|
|
8
|
+
handlePreCompactBatonFlush,
|
|
9
|
+
handleSessionStartHydration,
|
|
10
|
+
handlePostCompactFlush
|
|
11
|
+
} from '../../src/core-isomorphic/coach/stateBatonHydrator.mjs';
|
|
12
|
+
import { evaluateDet17AutoCompactionDeferral } from '../../src/core-isomorphic/guards/circuitBreakers.mjs';
|
|
13
|
+
import { loadHorizonConfig, resolveDetectorOverride } from '../../src/core-isomorphic/config/horizonConfig.mjs';
|
|
14
|
+
import { loadMicroSkillsRegistry, formatMicroSkillsBatonSnippet } from '../../src/core-isomorphic/coach/microSkills.mjs';
|
|
15
|
+
import { readTextSafe, resolvePath, getCwd } from '../../src/core-isomorphic/utils/runtime.mjs';
|
|
16
|
+
import {
|
|
17
|
+
isCliEntrypoint,
|
|
18
|
+
readStdinJsonAsync,
|
|
19
|
+
exitPassThrough,
|
|
20
|
+
exitDiagnosticZero,
|
|
21
|
+
exitWithStdoutJson
|
|
22
|
+
} from './hookIo.mjs';
|
|
23
|
+
|
|
24
|
+
/**
|
|
25
|
+
* Scans workspace instruction files (CLAUDE.md, .claude/CLAUDE.md, AGENTS.md)
|
|
26
|
+
* for token bloat (>4k tokens or >200 lines) and direct rule contradictions.
|
|
27
|
+
*
|
|
28
|
+
* @param {string} [cwd='']
|
|
29
|
+
* @param {object} [options={}]
|
|
30
|
+
* @returns {object}
|
|
31
|
+
*/
|
|
32
|
+
export function auditWorkspaceClaudeMd(cwd = '', options = {}) {
|
|
33
|
+
const root = cwd || getCwd(options);
|
|
34
|
+
const candidateFiles = ['CLAUDE.md', '.claude/CLAUDE.md', 'AGENTS.md'];
|
|
35
|
+
let totalTokens = 0;
|
|
36
|
+
let totalLines = 0;
|
|
37
|
+
const foundFiles = [];
|
|
38
|
+
const polarContradictions = [];
|
|
39
|
+
|
|
40
|
+
for (const rel of candidateFiles) {
|
|
41
|
+
const full = resolvePath(root, rel);
|
|
42
|
+
const content = readTextSafe(full, null, options);
|
|
43
|
+
if (typeof content === 'string' && content.length > 0) {
|
|
44
|
+
foundFiles.push(rel);
|
|
45
|
+
const lines = content.split(/\r?\n/).length;
|
|
46
|
+
totalLines += lines;
|
|
47
|
+
const tokens = Math.ceil(content.length / 3.8);
|
|
48
|
+
totalTokens += tokens;
|
|
49
|
+
|
|
50
|
+
if (
|
|
51
|
+
/always\s+use\s+(?:tabs|spaces)\b/i.test(content) &&
|
|
52
|
+
/never\s+use\s+(?:tabs|spaces)\b/i.test(content)
|
|
53
|
+
) {
|
|
54
|
+
polarContradictions.push('tabs vs spaces contradiction');
|
|
55
|
+
}
|
|
56
|
+
if (
|
|
57
|
+
/always\s+use\s+default\s+exports\b/i.test(content) &&
|
|
58
|
+
/never\s+use\s+default\s+exports\b/i.test(content)
|
|
59
|
+
) {
|
|
60
|
+
polarContradictions.push('Always vs NEVER use Default Exports contradiction');
|
|
61
|
+
}
|
|
62
|
+
if (
|
|
63
|
+
/always\s+use\s+semicolons\b/i.test(content) &&
|
|
64
|
+
/never\s+use\s+semicolons\b/i.test(content)
|
|
65
|
+
) {
|
|
66
|
+
polarContradictions.push('Always vs NEVER use semicolons contradiction');
|
|
67
|
+
}
|
|
68
|
+
}
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
const isBloated = totalTokens > 4000 || totalLines > 200 || polarContradictions.length > 0;
|
|
72
|
+
if (!isBloated) {
|
|
73
|
+
return { triggered: false };
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
const reasons = [];
|
|
77
|
+
if (totalTokens > 4000 || totalLines > 200) {
|
|
78
|
+
reasons.push(`Rules file bloat: ${Math.round(totalTokens / 1000)}k tokens across ${totalLines} lines (>4k tokens / >200 lines cap)`);
|
|
79
|
+
}
|
|
80
|
+
if (polarContradictions.length > 0) {
|
|
81
|
+
reasons.push(`Contradictions detected: ${polarContradictions.join('; ')}`);
|
|
82
|
+
}
|
|
83
|
+
|
|
84
|
+
const advisory = `[DET-09 / RSI-01 Static Rule Bloat Advisory] ${reasons.join('. ')}. Prune stale conventions or extract domain skills via /compact.`;
|
|
85
|
+
|
|
86
|
+
return {
|
|
87
|
+
triggered: true,
|
|
88
|
+
totalTokens,
|
|
89
|
+
totalLines,
|
|
90
|
+
foundFiles,
|
|
91
|
+
polarContradictions,
|
|
92
|
+
advisory
|
|
93
|
+
};
|
|
94
|
+
}
|
|
95
|
+
|
|
96
|
+
/**
|
|
97
|
+
* Evaluates a compaction / session-start lifecycle event (`pre`, `start`, or `post`).
|
|
98
|
+
* @param {object} event
|
|
99
|
+
* @param {object} [options={}]
|
|
100
|
+
*/
|
|
101
|
+
export function runCompactLifecycleHook(event = {}, options = {}) {
|
|
102
|
+
const inferredPhase =
|
|
103
|
+
event.hook_event_name === 'SessionStart'
|
|
104
|
+
? 'start'
|
|
105
|
+
: event.hook_event_name === 'PostCompact'
|
|
106
|
+
? 'post'
|
|
107
|
+
: event.hook_event_name === 'WorktreeCreate'
|
|
108
|
+
? 'worktree'
|
|
109
|
+
: 'pre';
|
|
110
|
+
const phase = String(options.phase || event.phase || inferredPhase).toLowerCase();
|
|
111
|
+
const cwdOptions = event.cwd && !options.cwd ? { ...options, cwd: event.cwd } : options;
|
|
112
|
+
|
|
113
|
+
if (phase === 'worktree' || event.hook_event_name === 'WorktreeCreate') {
|
|
114
|
+
return {
|
|
115
|
+
exitCode: 0,
|
|
116
|
+
stdout: '',
|
|
117
|
+
stderr: '',
|
|
118
|
+
result: {
|
|
119
|
+
ok: true,
|
|
120
|
+
hookEventName: 'WorktreeCreate',
|
|
121
|
+
passThrough: true
|
|
122
|
+
}
|
|
123
|
+
};
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
if (phase === 'pre' || event.hook_event_name === 'PreCompact') {
|
|
127
|
+
const det17 = evaluateDet17AutoCompactionDeferral({
|
|
128
|
+
trigger: event.trigger || 'auto',
|
|
129
|
+
midBatchEditInProgress: Boolean(event.midBatchEditInProgress),
|
|
130
|
+
unbalancedSyntaxDetected: Boolean(event.unbalancedSyntaxDetected),
|
|
131
|
+
cacheExpired: Boolean(event.cacheExpired),
|
|
132
|
+
cachedTokens: Number(event.cachedTokens ?? event.cached_tokens ?? 0)
|
|
133
|
+
});
|
|
134
|
+
if (det17.triggered) {
|
|
135
|
+
// ISS-034: Never emit invalid hookSpecificOutput.permissionDecision on PreCompact!
|
|
136
|
+
const stdoutJson = {
|
|
137
|
+
decision: 'block',
|
|
138
|
+
reason: det17.reason
|
|
139
|
+
};
|
|
140
|
+
return {
|
|
141
|
+
exitCode: 0,
|
|
142
|
+
stdout: JSON.stringify(stdoutJson),
|
|
143
|
+
stdoutJson,
|
|
144
|
+
stderr: '',
|
|
145
|
+
result: det17
|
|
146
|
+
};
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
const flushRes = handlePreCompactBatonFlush(event, cwdOptions);
|
|
150
|
+
return {
|
|
151
|
+
exitCode: 0,
|
|
152
|
+
stdout: '',
|
|
153
|
+
stderr: '',
|
|
154
|
+
result: flushRes
|
|
155
|
+
};
|
|
156
|
+
}
|
|
157
|
+
|
|
158
|
+
if (phase === 'start' || event.hook_event_name === 'SessionStart') {
|
|
159
|
+
const hydration = handleSessionStartHydration(event, cwdOptions);
|
|
160
|
+
const cwd = event.cwd || cwdOptions.cwd || '';
|
|
161
|
+
const ruleAudit = auditWorkspaceClaudeMd(cwd, cwdOptions);
|
|
162
|
+
const horizonConfig = options.horizonConfig || loadHorizonConfig(cwdOptions);
|
|
163
|
+
let microSkillsBaton = '';
|
|
164
|
+
if (resolveDetectorOverride('micro-skills', horizonConfig) !== 'off') {
|
|
165
|
+
const msReg = loadMicroSkillsRegistry(cwdOptions);
|
|
166
|
+
const formatted = formatMicroSkillsBatonSnippet(msReg);
|
|
167
|
+
microSkillsBaton = formatted.snippet || '';
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
let hookSpecificOutput = hydration.hookSpecificOutput || null;
|
|
171
|
+
const extraBlocks = [];
|
|
172
|
+
if (microSkillsBaton) extraBlocks.push(microSkillsBaton);
|
|
173
|
+
if (ruleAudit.triggered) extraBlocks.push(ruleAudit.advisory);
|
|
174
|
+
|
|
175
|
+
if (extraBlocks.length > 0) {
|
|
176
|
+
const joinedExtra = extraBlocks.join('\n\n');
|
|
177
|
+
if (!hookSpecificOutput) {
|
|
178
|
+
hookSpecificOutput = {
|
|
179
|
+
hookEventName: 'SessionStart',
|
|
180
|
+
additionalContext: joinedExtra
|
|
181
|
+
};
|
|
182
|
+
} else {
|
|
183
|
+
hookSpecificOutput.additionalContext = hookSpecificOutput.additionalContext
|
|
184
|
+
? `${hookSpecificOutput.additionalContext}\n\n${joinedExtra}`
|
|
185
|
+
: joinedExtra;
|
|
186
|
+
}
|
|
187
|
+
}
|
|
188
|
+
|
|
189
|
+
if (hookSpecificOutput) {
|
|
190
|
+
const stdoutJson = { hookSpecificOutput };
|
|
191
|
+
return {
|
|
192
|
+
exitCode: 0,
|
|
193
|
+
stdout: JSON.stringify(stdoutJson),
|
|
194
|
+
stdoutJson,
|
|
195
|
+
stderr: '',
|
|
196
|
+
result: {
|
|
197
|
+
...hydration,
|
|
198
|
+
ruleAudit,
|
|
199
|
+
microSkillsBaton
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
}
|
|
203
|
+
return {
|
|
204
|
+
exitCode: 0,
|
|
205
|
+
stdout: '',
|
|
206
|
+
stderr: '',
|
|
207
|
+
result: hydration
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
|
|
211
|
+
if (phase === 'post' || event.hook_event_name === 'PostCompact') {
|
|
212
|
+
const postRes = handlePostCompactFlush(event, cwdOptions);
|
|
213
|
+
return {
|
|
214
|
+
exitCode: 0,
|
|
215
|
+
stdout: '',
|
|
216
|
+
stderr: '',
|
|
217
|
+
result: postRes
|
|
218
|
+
};
|
|
219
|
+
}
|
|
220
|
+
|
|
221
|
+
return {
|
|
222
|
+
exitCode: 0,
|
|
223
|
+
stdout: '',
|
|
224
|
+
stderr: '',
|
|
225
|
+
result: null
|
|
226
|
+
};
|
|
227
|
+
}
|
|
228
|
+
|
|
229
|
+
/**
|
|
230
|
+
* CLI runner for `compact-lifecycle` (`ISS-035`).
|
|
231
|
+
* Non-blocking lifecycle hook: logs diagnostic to stderr and exits `0` on uncaught error.
|
|
232
|
+
*
|
|
233
|
+
* @param {object} [cliOptions={}]
|
|
234
|
+
*/
|
|
235
|
+
export async function executeCompactLifecycleCli(cliOptions = {}) {
|
|
236
|
+
const readPayload = cliOptions.readPayload || readStdinJsonAsync;
|
|
237
|
+
const runHook = cliOptions.runHook || runCompactLifecycleHook;
|
|
238
|
+
const ioOverride = cliOptions.ioOverride || {};
|
|
239
|
+
try {
|
|
240
|
+
const argv = cliOptions.argv || globalThis.process?.argv || [];
|
|
241
|
+
const phaseArg = argv.find((a) => String(a).startsWith('--phase='));
|
|
242
|
+
const explicitPhase = phaseArg ? String(phaseArg).split('=')[1] : undefined;
|
|
243
|
+
const payload = await readPayload(cliOptions.timeoutMs);
|
|
244
|
+
const res = runHook(payload, {
|
|
245
|
+
...(cliOptions.hookOptions || {}),
|
|
246
|
+
...(explicitPhase ? { phase: explicitPhase } : {})
|
|
247
|
+
});
|
|
248
|
+
if (res.stdout) {
|
|
249
|
+
exitWithStdoutJson(res.stdout, ioOverride);
|
|
250
|
+
} else {
|
|
251
|
+
exitPassThrough(ioOverride.exitFn);
|
|
252
|
+
}
|
|
253
|
+
} catch (err) {
|
|
254
|
+
exitDiagnosticZero(err?.message || String(err), 'CompactLifecycle', ioOverride);
|
|
255
|
+
}
|
|
256
|
+
}
|
|
257
|
+
|
|
258
|
+
if (isCliEntrypoint(import.meta.url)) {
|
|
259
|
+
executeCompactLifecycleCli().catch((err) => {
|
|
260
|
+
exitDiagnosticZero(err?.message || String(err), 'CompactLifecycle');
|
|
261
|
+
});
|
|
262
|
+
}
|
|
@@ -0,0 +1,255 @@
|
|
|
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
|
+
}
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* @file hooks/handlers/hookIpcClient.mjs
|
|
3
|
+
* Warm Micro-IPC Hook Dispatcher with Standalone Fallback (Features 29 & 30).
|
|
4
|
+
*
|
|
5
|
+
* Forwards PreToolUse and PostToolUse hook events to the warm Horizon Daemon IPC
|
|
6
|
+
* socket/pipe (<0.8ms SLA), automatically and silently falling back to standalone
|
|
7
|
+
* CLI evaluation within 15ms if the daemon is offline.
|
|
8
|
+
* Strictly 0 npm dependencies (uses only standard node:* built-ins).
|
|
9
|
+
*/
|
|
10
|
+
|
|
11
|
+
import { MicroIpcClient } from '../../src/engine-node/ipc/client.mjs';
|
|
12
|
+
import { runPreToolUseHook } from './pre-tool-use.mjs';
|
|
13
|
+
import { runPostToolUseHook } from './post-tool-use.mjs';
|
|
14
|
+
|
|
15
|
+
let sharedClient = null;
|
|
16
|
+
|
|
17
|
+
/**
|
|
18
|
+
* Returns or creates the shared MicroIpcClient instance for hook handlers.
|
|
19
|
+
*
|
|
20
|
+
* @param {object} [options]
|
|
21
|
+
* @returns {MicroIpcClient}
|
|
22
|
+
*/
|
|
23
|
+
export function getHookIpcClient(options = {}) {
|
|
24
|
+
if (!sharedClient || options.ipcPath) {
|
|
25
|
+
sharedClient = new MicroIpcClient({
|
|
26
|
+
connectTimeoutMs: options.connectTimeoutMs ?? 15,
|
|
27
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 500,
|
|
28
|
+
...options
|
|
29
|
+
});
|
|
30
|
+
}
|
|
31
|
+
return sharedClient;
|
|
32
|
+
}
|
|
33
|
+
|
|
34
|
+
/**
|
|
35
|
+
* Dispatches a PreToolUse hook invocation over warm Micro-IPC with fallback to local execution.
|
|
36
|
+
*
|
|
37
|
+
* @param {object} payload
|
|
38
|
+
* @param {object} [options]
|
|
39
|
+
* @returns {Promise<{ source: 'ipc' | 'fallback', result: object, fallbackReason?: string }>}
|
|
40
|
+
*/
|
|
41
|
+
export async function dispatchPreToolUseWithFallback(payload, options = {}) {
|
|
42
|
+
const client = getHookIpcClient(options);
|
|
43
|
+
return client.callWithFallback(
|
|
44
|
+
'hook.preToolUse',
|
|
45
|
+
payload,
|
|
46
|
+
async (p) => runPreToolUseHook(p, options),
|
|
47
|
+
{
|
|
48
|
+
connectTimeoutMs: options.connectTimeoutMs ?? 15,
|
|
49
|
+
requestTimeoutMs: options.requestTimeoutMs ?? 600000
|
|
50
|
+
}
|
|
51
|
+
);
|
|
52
|
+
}
|
|
53
|
+
|
|
54
|
+
/**
|
|
55
|
+
* Dispatches a PostToolUse hook invocation over warm Micro-IPC with fallback to local execution.
|
|
56
|
+
*
|
|
57
|
+
* @param {object} payload
|
|
58
|
+
* @param {object} [options]
|
|
59
|
+
* @returns {Promise<{ source: 'ipc' | 'fallback', result: object, fallbackReason?: string }>}
|
|
60
|
+
*/
|
|
61
|
+
export async function dispatchPostToolUseWithFallback(payload, options = {}) {
|
|
62
|
+
const client = getHookIpcClient(options);
|
|
63
|
+
return client.callWithFallback(
|
|
64
|
+
'hook.postToolUse',
|
|
65
|
+
payload,
|
|
66
|
+
async (p) => runPostToolUseHook(p, options),
|
|
67
|
+
{ connectTimeoutMs: options.connectTimeoutMs ?? 15 }
|
|
68
|
+
);
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
/**
|
|
72
|
+
* Closes and resets the shared MicroIpcClient instance.
|
|
73
|
+
*
|
|
74
|
+
* @returns {Promise<void>}
|
|
75
|
+
*/
|
|
76
|
+
export async function closeHookIpcClient() {
|
|
77
|
+
if (sharedClient) {
|
|
78
|
+
const client = sharedClient;
|
|
79
|
+
sharedClient = null;
|
|
80
|
+
await client.close();
|
|
81
|
+
}
|
|
82
|
+
}
|
|
83
|
+
|