moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,159 @@
#!/usr/bin/env node
/**
* `claude-code-hooks``claude-code-hooks` — CLI entry for the @waggle/hive-mind-hooks-claude-code shim (was @hive-mind/claude-code-hooks pre-monorepo migration).
*
* claude-code-hooks install Patch ~/.claude/settings.json (additive merge).
* claude-code-hooks uninstall Restore the byte-identical pre-install state.
* claude-code-hooks verify Smoke-check the install + hive-mind-cli reachability.
*/
import { install, type InstallResult } from '../install.js';
import { uninstall, type UninstallResult } from '../uninstall.js';
import { verify, type VerifyResult } from '../verify.js';
type ParsedArgs = {
command: 'install' | 'uninstall' | 'verify' | 'help';
flags: Record<string, string | boolean>;
};
function parseArgs(argv: readonly string[]): ParsedArgs {
const [first, ...rest] = argv;
const valid = ['install', 'uninstall', 'verify'] as const;
const command = first === '-h' || first === '--help' || first === undefined
? 'help'
: valid.includes(first as typeof valid[number]) ? first as typeof valid[number] : 'help';
const flags: Record<string, string | boolean> = {};
for (let i = 0; i < rest.length; i += 1) {
const arg = rest[i];
if (!arg.startsWith('--')) continue;
const eq = arg.indexOf('=');
if (eq !== -1) {
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
} else {
const next = rest[i + 1];
if (next && !next.startsWith('--')) {
flags[arg.slice(2)] = next;
i += 1;
} else {
flags[arg.slice(2)] = true;
}
}
}
return { command: command as ParsedArgs['command'], flags };
}
function printHelp(): void {
process.stdout.write([
'Usage: claude-code-hooks <command> [options]',
'',
'Commands:',
' install Patch ~/.claude/settings.json (additive, with backup).',
' uninstall Restore the byte-identical pre-install settings.json.',
' verify Smoke-check the install + hive-mind-cli reachability.',
'',
'Options:',
' --help, -h Show this help.',
' --hooks-dir <PATH> Override compiled hooks directory (testing).',
' --hook-timeout <S> Override per-hook timeout in seconds (default 5).',
' --cli-path <PATH> Absolute path to the hive-mind-cli binary or its',
' compiled JS entry. Required on Windows (npm bin',
' is a .cmd shim) and recommended for production',
' installs. Threaded into every hook command.',
'',
'Repo: https://github.com/marolinik/hive-mind-clients',
'',
].join('\n'));
}
function printInstallSummary(result: InstallResult): void {
const lines: string[] = [
'hive-mind/claude-code-hooks: install',
` - settings: ${result.paths.settingsPath}`,
` - backup: ${result.backupPath}`,
` - pointer: ${result.pointerPath}`,
` - added hooks: ${result.installedHooks.join(', ')}`,
` - cli path: ${result.cliPath ?? '(default — hive-mind-cli on PATH)'}`,
'',
'Done. New Claude Code sessions will silently capture to hive-mind.',
'Run "claude-code-hooks verify" to inspect, "claude-code-hooks uninstall" to revert.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printUninstallSummary(result: UninstallResult): void {
const lines: string[] = [
'hive-mind/claude-code-hooks: uninstall',
` - settings: ${result.paths.settingsPath}`,
` - restored from: ${result.restoredFrom}`,
` - backup removed: ${result.backupRemoved ? 'yes' : 'no (kept on disk)'}`,
` - pointer removed: ${result.pointerRemoved ? 'yes' : 'no'}`,
'',
'Done. settings.json is byte-identical to pre-install state.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printVerifySummary(result: VerifyResult): void {
const lines: string[] = ['hive-mind/claude-code-hooks: verify'];
for (const c of result.checks) {
const tag = c.ok ? 'PASS' : 'FAIL';
const detail = c.detail ? ` — ${c.detail}` : '';
lines.push(` [${tag}] ${c.name}${detail}`);
}
lines.push('');
lines.push(result.ok ? 'All checks passed.' : 'One or more checks failed.');
lines.push('');
process.stdout.write(lines.join('\n'));
}
async function main(): Promise<void> {
const { command, flags } = parseArgs(process.argv.slice(2));
if (command === 'help') {
printHelp();
return;
}
const hooksDir = typeof flags['hooks-dir'] === 'string' ? flags['hooks-dir'] : undefined;
const hookTimeoutRaw = flags['hook-timeout'];
const hookTimeoutSeconds = typeof hookTimeoutRaw === 'string'
? Number.parseInt(hookTimeoutRaw, 10) || undefined
: undefined;
const cliPath = typeof flags['cli-path'] === 'string' ? flags['cli-path'] : undefined;
const baseOpts = {
moduleUrl: import.meta.url,
...(hooksDir ? { hooksDir } : {}),
};
try {
if (command === 'install') {
const installOpts = {
...baseOpts,
...(hookTimeoutSeconds !== undefined ? { hookTimeoutSeconds } : {}),
...(cliPath !== undefined ? { cliPath } : {}),
};
const result = await install(installOpts);
printInstallSummary(result);
return;
}
if (command === 'uninstall') {
const result = await uninstall(baseOpts);
printUninstallSummary(result);
return;
}
if (command === 'verify') {
const result = await verify(baseOpts);
printVerifySummary(result);
if (!result.ok) process.exit(1);
return;
}
} catch (err) {
process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
process.exit(1);
}
}
void main();

View File

@@ -0,0 +1,148 @@
/**
* Shared helpers for the four hook scripts.
*
* Hook scripts run as short-lived Node subprocesses spawned by Claude
* Code. The contract:
* - stdin : Claude Code writes a JSON event payload (may be empty
* on some hook events).
* - stdout : structured JSON for hooks that influence Claude Code
* behaviour (SessionStart context injection, etc.).
* - stderr : structured logger output (never blocks the host).
* - exit code : 0 always — silent capture must not break the IDE.
*
* On any internal error, hooks log the error and exit 0. The
* `runHook` helper wraps the user-supplied hook body with this
* fail-open contract.
*/
import { createCliBridge, createLogger, type CliBridge, type CliBridgeOptions, type Logger } from '@waggle/hive-mind-shim-core';
export interface HookContext {
bridge: CliBridge;
logger: Logger;
}
export interface HookRunOptions {
/** Component name for the logger. */
name: string;
/** Stdin reader override for tests. */
readStdin?: () => Promise<string>;
/** Stdout writer override for tests. */
writeStdout?: (s: string) => void;
/** Override exit; tests provide a no-op so they don't terminate vitest. */
exit?: (code: number) => void;
/** Logger override. */
logger?: Logger;
/** Bridge override (tests inject a mock with a fake spawnImpl). */
bridge?: CliBridge;
/** Override argv for tests; defaults to `process.argv.slice(2)`. */
argv?: readonly string[];
}
/**
* Parse `--cli-path <value>` from argv. Used by hook scripts to thread
* the install-time-pinned CLI binary path into createCliBridge so a
* single hook script works on POSIX (where `hive-mind-cli` is on PATH)
* and on Windows (where the npm `.cmd` shim cannot be exec'd directly).
*/
export function parseHookArgs(argv: readonly string[]): { cliPath?: string } {
const idx = argv.indexOf('--cli-path');
if (idx >= 0 && idx + 1 < argv.length) {
const value = argv[idx + 1];
if (typeof value === 'string' && value.length > 0) return { cliPath: value };
}
return {};
}
export interface HookHandler<TPayload = unknown, TStdoutPayload = unknown> {
parse(raw: unknown): TPayload;
run(payload: TPayload, ctx: HookContext): Promise<TStdoutPayload | undefined>;
}
const STDIN_READ_TIMEOUT_MS = 2000;
export async function readStdinAsString(timeoutMs: number = STDIN_READ_TIMEOUT_MS): Promise<string> {
if (process.stdin.isTTY) return '';
return new Promise<string>((resolve) => {
const chunks: Buffer[] = [];
let settled = false;
const timer = setTimeout(() => {
if (settled) return;
settled = true;
resolve(Buffer.concat(chunks).toString('utf-8'));
}, timeoutMs);
process.stdin.on('data', (c: Buffer) => chunks.push(c));
process.stdin.on('end', () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(Buffer.concat(chunks).toString('utf-8'));
});
process.stdin.on('error', () => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve(Buffer.concat(chunks).toString('utf-8'));
});
});
}
export function safeJsonParse(raw: string): unknown {
if (!raw || raw.trim().length === 0) return {};
try {
return JSON.parse(raw);
} catch {
return {};
}
}
export async function runHook<TPayload, TStdoutPayload>(
handler: HookHandler<TPayload, TStdoutPayload>,
opts: HookRunOptions,
): Promise<void> {
const logger = opts.logger ?? createLogger({ name: `claude-code-hooks/${opts.name}` });
const writeStdout = opts.writeStdout ?? ((s: string) => process.stdout.write(s));
const exit = opts.exit ?? ((c: number): void => { process.exit(c); });
const reader = opts.readStdin ?? readStdinAsString;
const argv = opts.argv ?? process.argv.slice(2);
const argvFlags = parseHookArgs(argv);
const bridgeOpts: CliBridgeOptions = { logger };
if (argvFlags.cliPath !== undefined) bridgeOpts.cli_path = argvFlags.cliPath;
const bridge = opts.bridge ?? createCliBridge(bridgeOpts);
try {
const raw = await reader();
const parsed = safeJsonParse(raw);
const payload = handler.parse(parsed);
const out = await handler.run(payload, { bridge, logger });
if (out !== undefined) {
writeStdout(JSON.stringify(out) + '\n');
}
exit(0);
} catch (err) {
logger.warn('hook failed open', {
hook: opts.name,
error: err instanceof Error ? err.message : String(err),
});
exit(0);
}
}
/**
* Best-effort accessor for nested string fields on opaque payloads.
* Returns undefined when the key path doesn't resolve to a non-empty string.
*/
export function pickStringField(payload: unknown, ...keys: string[]): string | undefined {
if (!payload || typeof payload !== 'object') return undefined;
const obj = payload as Record<string, unknown>;
for (const key of keys) {
const value = obj[key];
if (typeof value === 'string' && value.length > 0) return value;
}
return undefined;
}
export function pickStringFromObject(obj: Record<string, unknown>, key: string): string | undefined {
const v = obj[key];
return typeof v === 'string' && v.length > 0 ? v : undefined;
}

View File

@@ -0,0 +1,52 @@
/**
* PreCompact hook — fired just before Claude Code truncates context.
* Triggers `compact_memory` so superseded P/B frames merge before the
* native compaction step.
*/
import {
pickStringFromObject,
runHook,
type HookHandler,
type HookRunOptions,
} from './_shared.js';
interface PreCompactPayload {
scope: string | undefined;
}
export const preCompactHandler: HookHandler<PreCompactPayload, undefined> = {
parse(raw): PreCompactPayload {
const obj = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
const scope = pickStringFromObject(obj, 'session_id')
?? pickStringFromObject(obj, 'sessionId')
?? pickStringFromObject(obj, 'scope');
return { scope };
},
async run(payload, { bridge, logger }): Promise<undefined> {
// Commit 1.4: scope param is unused at the upstream level (cleanup_frames
// operates on the active workspace). We retain payload.scope on the
// parsed payload for future use (workspace-id selection in Wave 2).
const result = await bridge.cleanupFrames();
logger.debug('cleanup_frames done', { pruned: result.pruned, scope: payload.scope });
return undefined;
},
};
export async function runPreCompact(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(preCompactHandler, { name: 'pre-compact', ...opts });
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runPreCompact();
}

View File

@@ -0,0 +1,102 @@
/**
* SessionStart hook — recalls the top-N most relevant frames from
* personal memory and injects them as additional context for the new
* Claude Code session.
*
* IMPORTANT (Commit 1.4): there is no `switch_workspace` MCP tool,
* so this hook no longer attempts to switch the active workspace.
* Workspace targeting will arrive in Wave 2 via per-call `workspace`
* parameters once project-level workspace discovery is wired up.
*
* Output format follows Claude Code's hookSpecificOutput convention:
* { hookSpecificOutput: { hookEventName: 'SessionStart', additionalContext: <text> } }
*
* If hive-mind-cli is unreachable, the hook logs and exits 0 with no
* output — the session starts as it would have without the shim.
*/
import { recallPersonalAndWorkspace, type MemoryHit } from '@waggle/hive-mind-shim-core';
import {
pickStringFromObject,
runHook,
type HookHandler,
type HookRunOptions,
} from './_shared.js';
interface SessionStartPayload {
cwd: string;
sessionId?: string;
recallLimit: number;
}
interface SessionStartOutput {
hookSpecificOutput: {
hookEventName: 'SessionStart';
additionalContext: string;
};
}
const DEFAULT_RECALL_LIMIT = 20;
const PER_HIT_CONTENT_BUDGET = 240;
function formatHitsForContext(hits: readonly MemoryHit[]): string {
if (hits.length === 0) {
return 'hive-mind: no recalled frames for this workspace yet.';
}
const lines: string[] = [`hive-mind: top ${hits.length} recalled frames`];
for (const h of hits) {
const ts = h.created_at;
const importance = h.importance;
const from = h.from && h.from !== 'personal' ? ` [${h.from}]` : '';
const content = h.content.length > PER_HIT_CONTENT_BUDGET
? h.content.slice(0, PER_HIT_CONTENT_BUDGET) + '…'
: h.content;
lines.push(`- (${importance})${from} ${ts}: ${content}`);
}
return lines.join('\n');
}
export const sessionStartHandler: HookHandler<SessionStartPayload, SessionStartOutput> = {
parse(raw): SessionStartPayload {
const obj = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
const cwd = pickStringFromObject(obj, 'cwd') ?? process.cwd();
const sessionId = pickStringFromObject(obj, 'session_id')
?? pickStringFromObject(obj, 'sessionId');
const limitVal = obj['recall_limit'] ?? obj['recallLimit'];
const recallLimit = typeof limitVal === 'number' && limitVal > 0
? Math.floor(limitVal)
: DEFAULT_RECALL_LIMIT;
const result: SessionStartPayload = { cwd, recallLimit };
if (sessionId !== undefined) result.sessionId = sessionId;
return result;
},
async run(payload, { bridge, logger }): Promise<SessionStartOutput | undefined> {
logger.debug('recall starting', { limit: payload.recallLimit });
const hits = await recallPersonalAndWorkspace(bridge, '', { limit: payload.recallLimit });
logger.debug('recall complete', { hits: hits.length });
return {
hookSpecificOutput: {
hookEventName: 'SessionStart',
additionalContext: formatHitsForContext(hits),
},
};
},
};
export async function runSessionStart(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(sessionStartHandler, { name: 'session-start', ...opts });
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runSessionStart();
}

View File

@@ -0,0 +1,129 @@
/**
* Stop hook — fired when an assistant turn completes. Summarizes the
* turn deterministically (no LLM call) and writes it as an `important`
* frame parented to the originating prompt frame when known.
*/
import {
classifyImportance,
encodeFrame,
maybeEmitDiscovery,
summarizeTurn,
type HookEvent,
} from '@waggle/hive-mind-shim-core';
import {
pickStringFromObject,
runHook,
type HookHandler,
type HookRunOptions,
} from './_shared.js';
interface StopPayload {
cwd: string;
sessionId: string;
response: string;
parent: string | undefined;
}
const SUMMARY_BUDGET_CHARS = 400;
export const stopHandler: HookHandler<StopPayload, undefined> = {
parse(raw): StopPayload {
const obj = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
const cwd = pickStringFromObject(obj, 'cwd') ?? process.cwd();
const sessionId = pickStringFromObject(obj, 'session_id')
?? pickStringFromObject(obj, 'sessionId')
?? 'default';
const response = pickStringFromObject(obj, 'response')
?? pickStringFromObject(obj, 'assistant_message')
?? pickStringFromObject(obj, 'transcript')
?? '';
const parent = pickStringFromObject(obj, 'parent_frame_id')
?? pickStringFromObject(obj, 'prompt_frame_id');
return { cwd, sessionId, response, parent };
},
async run(payload, { bridge, logger }): Promise<undefined> {
if (!payload.response) {
logger.debug('no response in payload, skipping save');
return undefined;
}
const summary = summarizeTurn(payload.response, { maxChars: SUMMARY_BUDGET_CHARS });
const rawImportance = classifyImportance(summary, { eventType: 'stop' });
const importance = rawImportance === 'critical' ? 'critical' : 'important';
const event: HookEvent = {
eventType: 'stop',
source: 'claude-code',
cwd: payload.cwd,
timestamp_iso: new Date().toISOString(),
payload: {
content: summary,
session_id: payload.sessionId,
},
};
const encodeOpts: { importance: typeof importance; parent?: string } = { importance };
if (payload.parent !== undefined) encodeOpts.parent = payload.parent;
const frame = encodeFrame(event, encodeOpts);
const result = await bridge.saveMemory(frame);
logger.debug('stop frame saved', {
id: result.id,
importance: frame.importance,
bytes: summary.length,
});
// AI-OS Phase 1E — opt-in v2 signal emission. Off by default so
// OSS consumers see no behavior change; flip WAGGLE_SIGNAL_EMIT=1
// (or any truthy value) to broadcast high/critical-importance
// stops to the local Waggle sidecar. Fails open (sidecar offline
// → null returned + stderr warning); never throws.
const emitFlag = process.env.WAGGLE_SIGNAL_EMIT;
if (emitFlag && emitFlag !== '0' && emitFlag.toLowerCase() !== 'false') {
// Map shim-core's Importance to maybeEmitDiscovery's emission
// scale. 'important' is the shim-core label for the
// emission-worthy threshold; the policy helper only fires on
// 'high' / 'critical'. 'temporary' / 'normal' do not emit.
const emitImportance =
rawImportance === 'critical' ? 'critical'
: rawImportance === 'important' ? 'high'
: rawImportance === 'normal' ? 'normal'
: 'low';
const emitted = await maybeEmitDiscovery(
'stop',
emitImportance,
{
tool: 'claude-code',
sessionId: payload.sessionId,
topic: summary.slice(0, 160),
summary,
frameId: result.id,
memoryWorkspace: result.workspace,
cwd: payload.cwd,
},
{ senderId: 'claude-code-hook' },
);
if (emitted) {
logger.debug('stop signal emitted', { id: emitted.id });
}
}
return undefined;
},
};
export async function runStop(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(stopHandler, { name: 'stop', ...opts });
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runStop();
}

View File

@@ -0,0 +1,72 @@
/**
* UserPromptSubmit hook — captures the user prompt as a temporary
* frame scoped to the current Claude Code session.
*
* No stdout output: this hook is purely a side-effect on the .mind file.
*/
import { encodeFrame, type HookEvent } from '@waggle/hive-mind-shim-core';
import {
pickStringFromObject,
runHook,
type HookHandler,
type HookRunOptions,
} from './_shared.js';
interface UserPromptSubmitPayload {
prompt: string;
cwd: string;
sessionId: string;
}
export const userPromptSubmitHandler: HookHandler<UserPromptSubmitPayload, undefined> = {
parse(raw): UserPromptSubmitPayload {
const obj = (raw && typeof raw === 'object') ? raw as Record<string, unknown> : {};
const prompt = pickStringFromObject(obj, 'prompt')
?? pickStringFromObject(obj, 'user_message')
?? '';
const cwd = pickStringFromObject(obj, 'cwd') ?? process.cwd();
const sessionId = pickStringFromObject(obj, 'session_id')
?? pickStringFromObject(obj, 'sessionId')
?? 'default';
return { prompt, cwd, sessionId };
},
async run(payload, { bridge, logger }): Promise<undefined> {
if (!payload.prompt) {
logger.debug('no prompt in payload, skipping save');
return undefined;
}
const event: HookEvent = {
eventType: 'user-prompt-submit',
source: 'claude-code',
cwd: payload.cwd,
timestamp_iso: new Date().toISOString(),
payload: {
content: payload.prompt,
session_id: payload.sessionId,
},
};
const frame = encodeFrame(event, { importance: 'temporary' });
const result = await bridge.saveMemory(frame);
logger.debug('prompt frame saved', { id: result.id, scope: frame.scope });
return undefined;
},
};
export async function runUserPromptSubmit(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(userPromptSubmitHandler, { name: 'user-prompt-submit', ...opts });
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runUserPromptSubmit();
}

View File

@@ -0,0 +1,51 @@
/**
* @waggle/hive-mind-hooks-claude-code — barrel export (was @hive-mind/claude-code-hooks pre-monorepo migration).
*
* Programmatic API for the install / uninstall / verify lifecycle.
* Most users invoke the CLI bin (`npx @hive-mind/claude-code-hooks ...`)
* but the same functions are exposed for embedding in other tooling.
*/
export type {
InstallOptions,
InstallResult,
} from './install.js';
export { install } from './install.js';
export type {
UninstallOptions,
UninstallResult,
} from './uninstall.js';
export { uninstall } from './uninstall.js';
export type {
VerifyOptions,
VerifyResult,
VerifyCheck,
} from './verify.js';
export { verify } from './verify.js';
export type {
ShimPaths,
ResolvePathsOptions,
HookBasename,
} from './paths.js';
export {
resolvePaths,
hookCommandFor,
backupPathFor,
allHookBasenames,
} from './paths.js';
export type {
ClaudeCodeSettings,
HookGroup,
HookEntrySpec,
} from './settings-merger.js';
export {
HIVE_MIND_MARKER,
HOOK_EVENT_BY_BASENAME,
defaultHookEntries,
hasHiveHooks,
mergeHiveHooks,
} from './settings-merger.js';

View File

@@ -0,0 +1,154 @@
/**
* Programmatic install entry point.
*
* Steps:
* 1. Read existing `~/.claude/settings.json` (must exist + be valid JSON).
* 2. Write a byte-identical backup at
* `~/.claude/settings.json.hive-mind-backup.<timestamp>`.
* 3. Compute the four hive-mind hook command strings (absolute paths
* to compiled `dist/hooks/*.js`).
* 4. Additively merge the four hook groups into the settings object
* (existing entries preserved verbatim).
* 5. Write the merged JSON back over `settings.json`.
* 6. Drop a pointer file at `~/.claude/hive-mind-install.json` so a
* future `uninstall` knows which backup to restore.
*
* Round-trip guarantee: the pre-install settings.json content equals
* the byte-identical content written to the backup. `uninstall` simply
* copies the backup over.
*/
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { dirname } from 'node:path';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import {
defaultHookEntries,
mergeHiveHooks,
type ClaudeCodeSettings,
} from './settings-merger.js';
import {
backupPathFor,
hookCommandFor,
resolvePaths,
type ResolvePathsOptions,
type ShimPaths,
} from './paths.js';
export interface InstallResult {
paths: ShimPaths;
backupPath: string;
pointerPath: string;
installedHooks: readonly string[];
alreadyInstalled: boolean;
/** The cli_path embedded in hook commands (undefined = default lookup at runtime). */
cliPath?: string;
}
export interface InstallOptions extends ResolvePathsOptions {
/** Per-hook timeout, seconds. Default 5. */
hookTimeoutSeconds?: number;
/** Override clock for deterministic tests. */
now?: () => Date;
/** Logger override. */
logger?: Logger;
/**
* Absolute path to the hive-mind-cli binary or its compiled JS entry.
* Required on Windows (npm bin shim is `.cmd` and can't be exec'd
* without a shell). Recommended for any production install where
* `hive-mind-cli` may not be on PATH at hook invocation time.
* Threaded into every hook command as `--cli-path "<path>"`.
*/
cliPath?: string;
}
const DEFAULT_HOOK_TIMEOUT_S = 5;
async function ensureDir(p: string): Promise<void> {
if (!existsSync(p)) await mkdir(p, { recursive: true });
}
export async function install(opts: InstallOptions = {}): Promise<InstallResult> {
const log = opts.logger ?? createLogger({ name: 'claude-code-hooks/install' });
// Use install.ts's own URL for hooks-dir derivation so that callers
// (e.g. the bin script in `src/bin/`) don't accidentally point us at
// `dist/bin/hooks/` instead of `dist/hooks/`. opts.hooksDir always
// wins when explicitly supplied.
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const now = opts.now ?? ((): Date => new Date());
log.info('install starting', { settings: paths.settingsPath, hooksDir: paths.hooksDir });
if (!existsSync(paths.settingsPath)) {
throw new Error(
`expected Claude Code settings at ${paths.settingsPath}, file not found. ` +
`Run Claude Code at least once before installing this shim.`,
);
}
const originalContent = await readFile(paths.settingsPath, 'utf-8');
let parsed: ClaudeCodeSettings;
try {
parsed = JSON.parse(originalContent) as ClaudeCodeSettings;
} catch (err) {
throw new Error(
`failed to parse existing ${paths.settingsPath} as JSON: ` +
(err instanceof Error ? err.message : String(err)),
);
}
await ensureDir(dirname(paths.pointerPath));
const backupPath = backupPathFor(paths.settingsPath, now().toISOString());
await writeFile(backupPath, originalContent, 'utf-8');
log.info('settings backed up', { backupPath });
const cliPath = normalizeCliPath(opts.cliPath);
const entries = defaultHookEntries(
paths.hooksDir,
opts.hookTimeoutSeconds ?? DEFAULT_HOOK_TIMEOUT_S,
hookCommandFor,
cliPath,
);
const merged = mergeHiveHooks(parsed, entries);
const mergedJson = JSON.stringify(merged, null, 2) + '\n';
await writeFile(paths.settingsPath, mergedJson, 'utf-8');
const pointer: Record<string, unknown> = {
version: '0.1.0',
installed_at: now().toISOString(),
settings_backup: backupPath,
hooks_dir: paths.hooksDir,
installed_hooks: entries.map((e) => e.basename),
cli_path: cliPath ?? null,
};
await writeFile(paths.pointerPath, JSON.stringify(pointer, null, 2) + '\n', 'utf-8');
log.info('install complete', { added: entries.length, cliPath: cliPath ?? '(PATH lookup)' });
const result: InstallResult = {
paths,
backupPath,
pointerPath: paths.pointerPath,
installedHooks: entries.map((e) => e.basename),
alreadyInstalled: false,
};
if (cliPath !== undefined) result.cliPath = cliPath;
return result;
}
function normalizeCliPath(input: string | undefined): string | undefined {
if (input === undefined) return undefined;
const trimmed = input.trim();
if (trimmed.length === 0) return undefined;
// Reject embedded double-quotes — they would break the
// `--cli-path "<value>"` quoting in the generated hook command.
if (trimmed.includes('"')) {
throw new Error(
`--cli-path value must not contain double-quote characters; got: ${trimmed.slice(0, 80)}`,
);
}
return trimmed;
}

View File

@@ -0,0 +1,93 @@
/**
* Filesystem path helpers for Claude Code shim install/uninstall.
*
* Centralized so tests can mock the home directory and dist directory
* without poking process.env or import.meta.url internals.
*/
import { homedir } from 'node:os';
import { fileURLToPath } from 'node:url';
import { dirname, join, resolve } from 'node:path';
export interface ShimPaths {
/** Claude Code config root (`~/.claude/`). */
claudeDir: string;
/** `~/.claude/settings.json`. */
settingsPath: string;
/** `~/.claude/hive-mind-install.json` — pointer to the active backup. */
pointerPath: string;
/** Directory where compiled hook scripts live (dist/hooks/). */
hooksDir: string;
}
export interface ResolvePathsOptions {
/** Override $HOME for tests. */
home?: string;
/** Override the URL used to locate dist/hooks (defaults to import.meta.url at runtime). */
moduleUrl?: string;
/** Override hooks directory directly (wins over moduleUrl). */
hooksDir?: string;
}
const HOOK_BASENAMES = [
'session-start',
'user-prompt-submit',
'stop',
'pre-compact',
] as const;
export type HookBasename = typeof HOOK_BASENAMES[number];
export function allHookBasenames(): readonly HookBasename[] {
return HOOK_BASENAMES;
}
function defaultHooksDirFromUrl(moduleUrl: string): string {
// Compiled location: <pkg>/dist/<somefile>.js — caller passes its own
// import.meta.url, dirname gives <pkg>/dist/, join gives <pkg>/dist/hooks.
// We resolve once more so the path is absolute and platform-normalized.
const dir = dirname(fileURLToPath(moduleUrl));
return resolve(dir, 'hooks');
}
export function resolvePaths(opts: ResolvePathsOptions = {}): ShimPaths {
const home = opts.home ?? homedir();
const claudeDir = join(home, '.claude');
const settingsPath = join(claudeDir, 'settings.json');
const pointerPath = join(claudeDir, 'hive-mind-install.json');
let hooksDir: string;
if (opts.hooksDir) {
hooksDir = resolve(opts.hooksDir);
} else if (opts.moduleUrl) {
hooksDir = defaultHooksDirFromUrl(opts.moduleUrl);
} else {
// Fallback: the consumer didn't pass moduleUrl — best we can do is
// assume CWD/dist/hooks. install.ts always passes moduleUrl so this
// only kicks in for ad-hoc test use.
hooksDir = resolve(process.cwd(), 'dist', 'hooks');
}
return { claudeDir, settingsPath, pointerPath, hooksDir };
}
export function hookCommandFor(
hooksDir: string,
basename: HookBasename,
cliPath?: string,
): string {
const scriptPath = join(hooksDir, `${basename}.js`);
// Quote paths so spaces in user home dir (Windows: "C:\Users\Marko Markovic\")
// don't fragment the command. Claude Code parses this string with shell rules.
const cliFlag = cliPath && cliPath.length > 0 ? ` --cli-path "${cliPath}"` : '';
const configuredNode = process.env.WAGGLE_HOOK_NODE_PATH?.trim();
if (configuredNode?.includes('"')) throw new Error('WAGGLE_HOOK_NODE_PATH cannot contain double quotes');
const nodeCommand = configuredNode ? `"${configuredNode}"` : 'node';
return `${nodeCommand} "${scriptPath}"${cliFlag}`;
}
export function backupPathFor(settingsPath: string, isoTimestamp: string): string {
// Replace ":" and "." with "-" so timestamp is filesystem-safe on Windows.
const stamp = isoTimestamp.replace(/[:.]/g, '-');
return `${settingsPath}.hive-mind-backup.${stamp}`;
}

View File

@@ -0,0 +1,130 @@
/**
* Pure-functional helpers for additively merging hive-mind hook entries
* into a Claude Code `settings.json` object.
*
* Design contract:
* - `mergeHiveHooks(settings, entries)` returns a new object; the
* caller-supplied settings are NEVER mutated in place.
* - Existing hook entries are preserved verbatim (preserves Marko's
* gsd-context-monitor.js etc.).
* - hive-mind entries are tagged with the marker key `_hiveMindShim:
* "@hive-mind/claude-code-hooks"` on the group so a future install
* can detect duplicates / upgrade in place.
*/
import { allHookBasenames, type HookBasename } from './paths.js';
export const HIVE_MIND_MARKER = '@hive-mind/claude-code-hooks';
export type HookGroup = {
hooks: Array<{
type: 'command';
command: string;
timeout?: number;
}>;
matcher?: string;
/** Marker our installer drops on every group it adds, used by uninstall. */
_hiveMindShim?: string;
};
export type ClaudeCodeSettings = Record<string, unknown> & {
hooks?: Record<string, HookGroup[]>;
};
/** Maps our four canonical hook basenames to the Claude Code `hooks.<event>` key. */
export const HOOK_EVENT_BY_BASENAME: Record<HookBasename, string> = {
'session-start': 'SessionStart',
'user-prompt-submit': 'UserPromptSubmit',
'stop': 'Stop',
'pre-compact': 'PreCompact',
};
export interface HookEntrySpec {
basename: HookBasename;
command: string;
timeout?: number;
}
function buildGroup(spec: HookEntrySpec): HookGroup {
const group: HookGroup = {
hooks: [{
type: 'command',
command: spec.command,
...(spec.timeout !== undefined ? { timeout: spec.timeout } : {}),
}],
_hiveMindShim: HIVE_MIND_MARKER,
};
return group;
}
function isHiveGroup(group: HookGroup | undefined): boolean {
return !!group && group._hiveMindShim === HIVE_MIND_MARKER;
}
/**
* Returns a NEW settings object with hive-mind hook entries appended to
* each Claude Code event array. Existing entries are preserved.
*
* If a hive-mind entry for a given event is already present (matching
* marker AND command path), it is replaced in place rather than
* duplicated — supports re-running install for upgrades.
*/
export function mergeHiveHooks(
settings: ClaudeCodeSettings | undefined,
entries: readonly HookEntrySpec[],
): ClaudeCodeSettings {
// Deep-copy starting structure (settings + settings.hooks + each event array).
const next: ClaudeCodeSettings = settings ? { ...settings } : {};
const nextHooks: Record<string, HookGroup[]> = next.hooks ? { ...next.hooks } : {};
for (const spec of entries) {
const eventKey = HOOK_EVENT_BY_BASENAME[spec.basename];
const existingArr = nextHooks[eventKey] ? [...nextHooks[eventKey]] : [];
const newGroup = buildGroup(spec);
let replaced = false;
for (let i = 0; i < existingArr.length; i += 1) {
const g = existingArr[i];
if (isHiveGroup(g) && g.hooks[0]?.command === spec.command) {
existingArr[i] = newGroup;
replaced = true;
break;
}
}
if (!replaced) existingArr.push(newGroup);
nextHooks[eventKey] = existingArr;
}
next.hooks = nextHooks;
return next;
}
/**
* Detect whether a settings object already has hive-mind hooks installed.
* True iff at least one event array has a group bearing the marker.
*/
export function hasHiveHooks(settings: ClaudeCodeSettings | undefined): boolean {
if (!settings || !settings.hooks) return false;
for (const groups of Object.values(settings.hooks)) {
if (Array.isArray(groups) && groups.some(isHiveGroup)) return true;
}
return false;
}
/**
* Build the canonical 4-entry spec list for the four hooks we install,
* given the hooksDir and a shared timeout.
*/
export function defaultHookEntries(
hooksDir: string,
timeoutSeconds: number,
cmdBuilder: (hooksDir: string, basename: HookBasename, cliPath?: string) => string,
cliPath?: string,
): HookEntrySpec[] {
return allHookBasenames().map((basename) => ({
basename,
command: cmdBuilder(hooksDir, basename, cliPath),
timeout: timeoutSeconds,
}));
}

View File

@@ -0,0 +1,98 @@
/**
* Programmatic uninstall entry point.
*
* Round-trip guarantee: after uninstall, `~/.claude/settings.json` is
* byte-identical to the pre-install state. We achieve this by reading
* the backup the installer wrote and copying it back. Uninstall refuses
* to delete the backup unless the in-place readback matches the backup
* content.
*/
import { readFile, writeFile, unlink } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import { resolvePaths, type ResolvePathsOptions, type ShimPaths } from './paths.js';
export interface UninstallResult {
paths: ShimPaths;
restoredFrom: string;
pointerRemoved: boolean;
backupRemoved: boolean;
}
export interface UninstallOptions extends ResolvePathsOptions {
logger?: Logger;
/** If false, leaves the backup file in place after restore. Default true. */
cleanupBackup?: boolean;
}
interface InstallPointer {
version: string;
installed_at: string;
settings_backup: string;
hooks_dir: string;
installed_hooks: readonly string[];
}
function isPointer(value: unknown): value is InstallPointer {
if (!value || typeof value !== 'object') return false;
const v = value as Record<string, unknown>;
return typeof v['settings_backup'] === 'string';
}
export async function uninstall(opts: UninstallOptions = {}): Promise<UninstallResult> {
const log = opts.logger ?? createLogger({ name: 'claude-code-hooks/uninstall' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const cleanup = opts.cleanupBackup ?? true;
if (!existsSync(paths.pointerPath)) {
throw new Error(
`no install pointer found at ${paths.pointerPath}. ` +
`Was @hive-mind/claude-code-hooks ever installed for this user?`,
);
}
const pointerRaw = await readFile(paths.pointerPath, 'utf-8');
const pointerJson: unknown = JSON.parse(pointerRaw);
if (!isPointer(pointerJson)) {
throw new Error(`install pointer at ${paths.pointerPath} is malformed`);
}
const pointer = pointerJson;
if (!existsSync(pointer.settings_backup)) {
throw new Error(
`backup file referenced by ${paths.pointerPath} is missing: ${pointer.settings_backup}`,
);
}
const backupContent = await readFile(pointer.settings_backup, 'utf-8');
await writeFile(paths.settingsPath, backupContent, 'utf-8');
// Round-trip verification: read what we just wrote and compare bytes.
const verify = await readFile(paths.settingsPath, 'utf-8');
if (verify !== backupContent) {
throw new Error(
`uninstall verification failed: ${paths.settingsPath} content differs ` +
`from backup ${pointer.settings_backup}. Backup was NOT removed; ` +
`restore manually if needed.`,
);
}
log.info('settings restored byte-identical', { settings: paths.settingsPath });
let backupRemoved = false;
if (cleanup) {
await unlink(pointer.settings_backup);
backupRemoved = true;
}
await unlink(paths.pointerPath);
return {
paths,
restoredFrom: pointer.settings_backup,
pointerRemoved: true,
backupRemoved,
};
}

View File

@@ -0,0 +1,175 @@
/**
* Smoke-check the install: settings exist + parse + reference live
* hook scripts, and hive-mind-cli answers a `--help` probe.
*
* Probe priority for `cli_path`:
* 1. Explicit `opts.cliPath` (caller override)
* 2. `cli_path` recorded in `~/.claude/hive-mind-install.json` (set
* at install time via `--cli-path`)
* 3. Bare `'hive-mind-cli'` on PATH
*/
import { readFile, access } from 'node:fs/promises';
import { constants, existsSync } from 'node:fs';
import { spawn } from 'node:child_process';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import { resolvePaths, allHookBasenames, type ResolvePathsOptions } from './paths.js';
import {
HIVE_MIND_MARKER,
HOOK_EVENT_BY_BASENAME,
type ClaudeCodeSettings,
type HookGroup,
} from './settings-merger.js';
export interface VerifyCheck {
name: string;
ok: boolean;
detail?: string;
}
export interface VerifyResult {
ok: boolean;
checks: VerifyCheck[];
}
export interface VerifyOptions extends ResolvePathsOptions {
logger?: Logger;
/** Override hive-mind-cli executable name. Default 'hive-mind-cli'. */
cliPath?: string;
/** Test hook for spawn. */
spawnImpl?: typeof spawn;
}
async function fileReadable(p: string): Promise<boolean> {
try { await access(p, constants.R_OK); return true; } catch { return false; }
}
function findHiveGroup(groups: HookGroup[] | undefined, command: string): HookGroup | undefined {
if (!Array.isArray(groups)) return undefined;
return groups.find((g) => g._hiveMindShim === HIVE_MIND_MARKER && g.hooks[0]?.command === command);
}
function isJsPath(p: string): boolean {
return p.endsWith('.js') || p.endsWith('.mjs') || p.endsWith('.cjs');
}
function probeCliVersion(
cliPath: string,
spawnImpl: typeof spawn,
timeoutMs: number,
): Promise<{ ok: boolean; output: string }> {
return new Promise((resolve) => {
let settled = false;
// If cliPath is a JS file, run via Node directly so .js paths work
// cross-platform without needing a shell to launch npm bin shims.
const command = isJsPath(cliPath) ? process.execPath : cliPath;
const args = isJsPath(cliPath) ? [cliPath, '--help'] : ['--help'];
const child = spawnImpl(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try { child.kill('SIGTERM'); } catch { /* gone */ }
resolve({ ok: false, output: 'timed out probing hive-mind-cli' });
}, timeoutMs);
child.stdout?.on('data', (c: Buffer) => stdout.push(c));
child.stderr?.on('data', (c: Buffer) => stderr.push(c));
child.on('error', (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve({ ok: false, output: err instanceof Error ? err.message : String(err) });
});
child.on('exit', (code) => {
if (settled) return;
settled = true;
clearTimeout(timer);
const out = Buffer.concat(stdout).toString('utf-8').slice(0, 200);
const err = Buffer.concat(stderr).toString('utf-8').slice(0, 200);
resolve({ ok: code === 0, output: code === 0 ? out : err });
});
});
}
export async function verify(opts: VerifyOptions = {}): Promise<VerifyResult> {
const log = opts.logger ?? createLogger({ name: 'claude-code-hooks/verify' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const checks: VerifyCheck[] = [];
// 1. settings.json exists and parses
if (!existsSync(paths.settingsPath)) {
checks.push({ name: 'settings.json exists', ok: false, detail: paths.settingsPath });
return { ok: false, checks };
}
checks.push({ name: 'settings.json exists', ok: true, detail: paths.settingsPath });
let parsed: ClaudeCodeSettings;
try {
parsed = JSON.parse(await readFile(paths.settingsPath, 'utf-8')) as ClaudeCodeSettings;
checks.push({ name: 'settings.json parses as JSON', ok: true });
} catch (err) {
checks.push({
name: 'settings.json parses as JSON',
ok: false,
detail: err instanceof Error ? err.message : String(err),
});
return { ok: false, checks };
}
// 2. each hive hook entry is present and points to an existing dist file
for (const basename of allHookBasenames()) {
const eventKey = HOOK_EVENT_BY_BASENAME[basename];
const groups = parsed.hooks?.[eventKey];
const expectedCmdSuffix = `${basename}.js`;
const found = Array.isArray(groups)
? groups.find((g) => g._hiveMindShim === HIVE_MIND_MARKER && g.hooks[0]?.command.includes(expectedCmdSuffix))
: undefined;
if (!found) {
checks.push({ name: `hooks.${eventKey} contains hive-mind entry`, ok: false });
continue;
}
checks.push({ name: `hooks.${eventKey} contains hive-mind entry`, ok: true });
// Best-effort: extract path from `node "<path>"` and check file exists.
const m = found.hooks[0]?.command.match(/node "([^"]+)"/);
if (m && m[1]) {
const ok = await fileReadable(m[1]);
checks.push({
name: `${basename}.js readable on disk`,
ok,
detail: m[1],
});
}
// Also confirm we located the entry under the right top-level group key
void findHiveGroup;
}
// 3. hive-mind-cli responds to --help.
// Prefer a path recorded by install (--cli-path flag) if present.
let cliPathFromPointer: string | undefined;
if (existsSync(paths.pointerPath)) {
try {
const pointerObj = JSON.parse(await readFile(paths.pointerPath, 'utf-8')) as Record<string, unknown>;
const pointerCliPath = pointerObj['cli_path'];
if (typeof pointerCliPath === 'string' && pointerCliPath.length > 0) {
cliPathFromPointer = pointerCliPath;
}
} catch { /* pointer unreadable — fall through */ }
}
const cliPath = opts.cliPath ?? cliPathFromPointer ?? 'hive-mind-cli';
const spawnImpl = opts.spawnImpl ?? spawn;
const probe = await probeCliVersion(cliPath, spawnImpl, 4000);
checks.push({
name: 'hive-mind-cli reachable',
ok: probe.ok,
detail: cliPathFromPointer ? `${probe.output} (pinned: ${cliPath})` : probe.output,
});
const ok = checks.every((c) => c.ok);
log.info('verify complete', { ok, total: checks.length, failed: checks.filter((c) => !c.ok).length });
return { ok, checks };
}