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,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();
}