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,107 @@
/**
* OpenClaw EventAdapter.
*
* OpenClaw (`openclaw/openclaw`) exposes IN-PROCESS internal hooks: a hook is
* a directory `~/.openclaw/hooks/<name>/{HOOK.md, handler.js}` whose default
* export is `(event: InternalHookEvent) => Promise<void> | void`, run inside
* the gateway Node process. That is NOT the stdin-JSON / exit-0 subprocess
* model the other tools use, so openclaw drives the shared handler bodies via
* `makeOpenclawHandler` (hooks-core) rather than `runHook`.
*
* Event map — matched on the `(type, action)` PAIR, not a joined string
* (spec §5.5, source-verified):
* - SessionStart → `agent:bootstrap` (mutate `context.bootstrapFiles`)
* - UserPromptSubmit → `message:received` (context {from, content, channelId})
* - Stop → `message:sent` (0..N per turn — DEBOUNCED; non-replyable)
* - PreCompact → `session:compact:before`, BUT the runtime
* `event.action` is `'compact:before'` (the `session:` prefix is
* HOOK.md-only). `lifecycleForOpenclawEvent` in hooks-core matches the
* action suffix, so we declare the HOOK.md-style key here.
*
* `before_agent_finalize` is deliberately NOT used — it is a typed PLUGIN
* hook (a different subsystem), not an internal `HOOK.md` event. Stop is
* `message:sent` (debounced) instead.
*
* The `extract*` methods read OpenClaw's `event.context` shapes. Because the
* openclaw handler pre-extracts `event.context` into the shared
* extracted-payload shapes before calling the body, these extractors operate
* on that already-unwrapped `context` object.
*/
import {
pickStringField,
type EventAdapter,
type Lifecycle,
} from '@waggle/hive-mind-hooks-core';
/**
* Canonical lifecycle → OpenClaw native `type:action` key. The values are the
* joined keys; `makeOpenclawHandler` matches them against the runtime
* `(type, action)` pair (and, for PreCompact, on the action suffix because
* the runtime action drops the `session:` prefix).
*/
export const OPENCLAW_EVENT_NAME: Record<Lifecycle, string | undefined> = {
'session-start': 'agent:bootstrap',
'user-prompt-submit': 'message:received',
'stop': 'message:sent',
'pre-compact': 'session:compact:before',
};
/**
* Provenance marker stamped on frames captured at the OpenClaw gateway layer.
* OpenClaw can drive claude-code / codex as BACKENDS; if those backends also
* have hive-mind hooks installed the same conversation is captured twice. We
* stamp `openclaw-gateway` (+ the channel / session key, see the handler) so
* gateway captures are attributable. Cross-process dedup of the
* double-capture is a documented v0.1.0 limitation (README), deferred to a
* fast-follow.
*/
export const OPENCLAW_PROVENANCE = 'openclaw-gateway';
/** The OpenClaw EventAdapter consumed by the shared lifecycle handler bodies. */
export const openclawAdapter: EventAdapter = {
source: 'openclaw',
eventName: OPENCLAW_EVENT_NAME,
extractCwd(context): string | undefined {
return pickStringField(context, 'cwd', 'workingDirectory', 'working_directory');
},
extractSessionId(context): string | undefined {
// `channelId` is the most stable per-conversation key for gateway events;
// fall back to sessionKey / explicit session ids.
return pickStringField(
context,
'channelId',
'channel_id',
'sessionKey',
'session_key',
'sessionId',
'session_id',
);
},
extractPrompt(context): string | undefined {
// message:received carries the inbound text at context.content.
return pickStringField(context, 'content', 'message', 'text', 'prompt');
},
extractResponse(context): string | undefined {
// message:sent carries the outbound text at context.content / .text.
return pickStringField(context, 'content', 'text', 'response', 'message');
},
extractParent(context): string | undefined {
return pickStringField(context, 'parentId', 'parent_id', 'replyTo', 'reply_to');
},
/**
* SessionStart injects by MUTATING `event.context.bootstrapFiles` (handled
* in the openclaw handler, not via stdout). The body still calls
* `formatInject` to shape the recalled text; the handler reads the returned
* value and pushes it onto the mutable array.
*/
formatInject(additionalContext: string): unknown {
return { additionalContext };
},
};

View File

@@ -0,0 +1,173 @@
#!/usr/bin/env node
/**
* `openclaw-hooks` — CLI entry for the @waggle/hive-mind-hooks-openclaw shim.
*
* openclaw-hooks install Write the managed ~/.openclaw/hooks/hive-mind/ dir
* + minimal-touch openclaw.json (create-if-missing).
* openclaw-hooks uninstall Remove the managed dir + restore the literal
* byte-identical openclaw.json (or remove it if created).
* openclaw-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: openclaw-hooks <command> [options]',
'',
'Commands:',
' install Write ~/.openclaw/hooks/hive-mind/ + minimal-touch openclaw.json (create-if-missing).',
' uninstall Remove the managed dir + restore the literal byte-identical openclaw.json (or remove it if created).',
' verify Smoke-check the install + hive-mind-cli reachability.',
'',
'Options:',
' --help, -h Show this help.',
' --handler-source <PATH> Override compiled handler.js source (testing).',
' --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 the hook entry env as',
' WAGGLE_HIVE_MIND_CLI.',
'',
'Repo: https://github.com/marolinik/waggle-os',
'',
].join('\n'));
}
function printInstallSummary(result: InstallResult): void {
const lines: string[] = [
'hive-mind/openclaw-hooks: install',
` - openclaw.json: ${result.paths.configPath}`,
` - backup: ${result.backupPath ?? '(none — openclaw.json created by us)'}`,
` - pointer: ${result.pointerPath}`,
` - hook dir: ${result.hookDir}`,
` - lifecycles: ${result.installedHooks.join(', ')}`,
` - touched keys: ${result.touchedKeys.join(', ')}`,
` - cli path: ${result.cliPath ?? '(default — hive-mind-cli on PATH)'}`,
'',
'Activation (IMPORTANT):',
' Hooks are OFF until the internal-hooks subsystem is on. The installer set',
' hooks.internal.enabled: true. If it is not honored, run:',
' openclaw hooks enable hive-mind',
'',
'Capture fidelity:',
' 4 events — SessionStart (agent:bootstrap, mutates bootstrapFiles),',
' UserPromptSubmit (message:received), Stop (message:sent — DEBOUNCED,',
' 0..N/turn, non-replyable), PreCompact (compact:before). The installed',
' handler.js resolving @waggle/* on a real OpenClaw install is the one',
' remaining live-install validation. Gateway capture can double-count when',
' OpenClaw drives a backend (CC/codex) that also has hooks — see README.',
'',
'Done. New OpenClaw sessions will silently capture to hive-mind.',
'Run "openclaw-hooks verify" to inspect, "openclaw-hooks uninstall" to revert.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printUninstallSummary(result: UninstallResult): void {
const lines: string[] = [
'hive-mind/openclaw-hooks: uninstall',
` - openclaw.json: ${result.paths.configPath}`,
` - hook dir removed: ${result.hookDirRemoved ? 'yes' : 'no (was absent)'}`,
` - restored from: ${result.restoredFrom ?? '(none — removed file we created)'}`,
` - created removed: ${result.createdRemoved ? 'yes' : 'no'}`,
` - backup removed: ${result.backupRemoved ? 'yes' : 'no (kept on disk)'}`,
` - pointer removed: ${result.pointerRemoved ? 'yes' : 'no'}`,
'',
'openclaw.json is byte-identical to pre-install state (or removed if we created it).',
'',
];
process.stdout.write(lines.join('\n'));
}
function printVerifySummary(result: VerifyResult): void {
const lines: string[] = ['hive-mind/openclaw-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 handlerSource = typeof flags['handler-source'] === 'string' ? flags['handler-source'] : undefined;
const cliPath = typeof flags['cli-path'] === 'string' ? flags['cli-path'] : undefined;
const baseOpts = {
moduleUrl: import.meta.url,
...(handlerSource ? { handlerSourcePath: handlerSource } : {}),
};
try {
if (command === 'install') {
const installOpts = {
...baseOpts,
...(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,227 @@
/**
* OpenClaw in-process hook handler — the default export the gateway loads.
*
* Unlike the stdin-JSON tools (codex / cursor / hermes), OpenClaw hooks are
* IN-PROCESS: the gateway dynamically `import()`s this file, grabs the default
* export, and registers it as an `InternalHookHandler`
* (`(event) => Promise<void> | void`, run inside the gateway event loop). So
* there is no `runHook` subprocess wrapper — this module maps `event.context`
* into the shared extracted-payload shapes and drives the SAME shared handler
* bodies via `makeOpenclawHandler` (hooks-core).
*
* The four lifecycle dispatches (recall+inject / save-temp / summarize+save /
* compact) are matched on the `(type, action)` PAIR by hooks-core. This module
* owns the OpenClaw-specific glue:
* - SessionStart injects by MUTATING `event.context.bootstrapFiles` (a
* mutable array the gateway reads back) — there is no stdout seam.
* - Stop (`message:sent`) fires 0..N per turn and is DEBOUNCED in
* `makeOpenclawHandler` (stopDebounceMs).
* - Provenance: every captured frame is attributed to `openclaw-gateway`
* (+ the channel/session key) so gateway captures are distinguishable
* from any backend (CC/codex) capture.
*
* FAIL-OPEN: the default export wraps the body and NEVER throws / never
* rejects — it always returns a resolved promise (spec §7.3 invariant 1). The
* gateway also wraps each handler in try/catch, but we do not rely on that as
* the only safety net.
*
* Live-install caveat (OQ-5): this file is shipped COMPILED (`dist/handler.js`)
* and copied into `~/.openclaw/hooks/hive-mind/handler.js`. Whether the
* installed `handler.js` resolves the `@waggle/*` runtime deps on a real
* OpenClaw install is the ONE remaining needs-a-live-install validation — the
* gateway must be able to `import()` a file that `require`s node_modules from
* this package's tree (or have the deps bundled). Documented in the README.
*/
import {
createCliBridge,
createLogger,
type CliBridgeOptions,
type MemoryHit,
} from '@waggle/hive-mind-shim-core';
import {
makeOpenclawHandler,
type HookContext,
type InternalHookEventLike,
type Lifecycle,
type OpenclawHandlerInput,
type PreCompactExtracted,
type SessionStartExtracted,
type StopExtracted,
type UserPromptExtracted,
} from '@waggle/hive-mind-hooks-core';
import { openclawAdapter, OPENCLAW_PROVENANCE } from './adapter.js';
/** Default Stop debounce: collapse the 0..N `message:sent` of a turn. */
const DEFAULT_STOP_DEBOUNCE_MS = 750;
const DEFAULT_RECALL_LIMIT = 20;
/**
* Minimal shape of OpenClaw's runtime `InternalHookEvent`. `bootstrapFiles` is
* the MUTABLE array the gateway reads back after `agent:bootstrap` to inject
* recalled context into the system prompt.
*/
interface OpenclawRuntimeContext {
cwd?: unknown;
workingDirectory?: unknown;
channelId?: unknown;
sessionKey?: unknown;
content?: unknown;
/** Mutable array of bootstrap file contents — the SessionStart inject seam. */
bootstrapFiles?: unknown;
[key: string]: unknown;
}
interface OpenclawRuntimeEvent extends InternalHookEventLike {
context?: OpenclawRuntimeContext;
}
function asContext(event: OpenclawRuntimeEvent): OpenclawRuntimeContext {
return event.context && typeof event.context === 'object' ? event.context : {};
}
/**
* Build a provenance-stamped session scope so gateway frames are attributable
* to `openclaw-gateway` and to the originating channel/session. This rides the
* frame's `session:` content prefix (frame-encoder), which is the only
* attribution channel the save_memory wire preserves.
*/
function provenanceScope(ctx: OpenclawRuntimeContext): string {
const sessionId = openclawAdapter.extractSessionId(ctx) ?? 'default';
return `${OPENCLAW_PROVENANCE}:${sessionId}`;
}
/** Resolve the lifecycle for an event using the adapter's event-name map. */
function lifecycleFor(event: OpenclawRuntimeEvent): Lifecycle | undefined {
const joined = `${event.type}:${event.action}`;
for (const lc of ['session-start', 'user-prompt-submit', 'stop', 'pre-compact'] as Lifecycle[]) {
const native = openclawAdapter.eventName[lc];
if (native === undefined) continue;
if (native === joined) return lc;
// PreCompact ONLY: runtime action is 'compact:before' while the HOOK.md key
// is 'session:compact:before' — accept the action-suffix match exclusively
// for pre-compact (an unrelated type with a colliding action must not map).
if (lc === 'pre-compact' && native.endsWith(`:${event.action}`) && event.type !== '') return lc;
}
return undefined;
}
/**
* Extract the lifecycle-specific payload from `event.context`, stamping the
* provenance scope as the session id so saved frames are attributable.
*/
function extractFor(
lifecycle: Lifecycle,
ctx: OpenclawRuntimeContext,
): SessionStartExtracted | UserPromptExtracted | StopExtracted | PreCompactExtracted {
const cwd = openclawAdapter.extractCwd(ctx) ?? process.cwd();
const scope = provenanceScope(ctx);
switch (lifecycle) {
case 'session-start':
return { cwd, sessionId: scope, recallLimit: DEFAULT_RECALL_LIMIT };
case 'user-prompt-submit':
return { prompt: openclawAdapter.extractPrompt(ctx) ?? '', cwd, sessionId: scope };
case 'stop': {
const responseRaw = openclawAdapter.extractResponse(ctx, {});
const response = typeof responseRaw === 'string' ? responseRaw : '';
const parent = openclawAdapter.extractParent(ctx);
const stop: StopExtracted = { cwd, sessionId: scope, response, parent };
return stop;
}
case 'pre-compact':
return { scope };
}
}
/** Build a CliBridge, honoring an install-pinned cli path from env. */
function buildBridge(): ReturnType<typeof createCliBridge> {
const logger = createLogger({ name: 'openclaw-hooks/handler' });
const cliPath = process.env.WAGGLE_HIVE_MIND_CLI;
const opts: CliBridgeOptions = { logger };
if (typeof cliPath === 'string' && cliPath.length > 0) opts.cli_path = cliPath;
return createCliBridge(opts);
}
const handler = makeOpenclawHandler(openclawAdapter, {
stopDebounceMs: DEFAULT_STOP_DEBOUNCE_MS,
});
/**
* The OpenClaw default export. Receives the runtime `InternalHookEvent`, maps
* `event.context` → the extracted payload, and drives the shared bodies.
*
* SessionStart is special-cased: the shared body returns the inject object
* (`{ additionalContext }`); we push that text onto the mutable
* `context.bootstrapFiles` array (the gateway's sanctioned injection seam)
* rather than emitting stdout.
*
* NEVER throws — always returns a resolved promise (fail-open).
*/
export default async function openclawHook(event: OpenclawRuntimeEvent): Promise<void> {
try {
const lifecycle = lifecycleFor(event);
if (lifecycle === undefined) return;
const ctx = asContext(event);
const extracted = extractFor(lifecycle, ctx);
// SessionStart: drive recall ourselves so we can mutate bootstrapFiles
// with the injected text (the shared body's stdout return is unused
// in-process).
if (lifecycle === 'session-start') {
await injectBootstrap(ctx, extracted as SessionStartExtracted);
return;
}
const input: OpenclawHandlerInput = { event, extracted };
const hookCtx: HookContext = { bridge: buildBridge(), logger: createLogger({ name: 'openclaw-hooks/handler' }) };
await handler.handle(input, hookCtx);
} catch {
// FAIL-OPEN: swallow — the gateway flow must never be affected.
}
}
/**
* Recall top-N frames and push the formatted text onto the mutable
* `context.bootstrapFiles` array (OpenClaw's sanctioned inject seam). Recall
* uses the same provenance scope so the injected context is attributable.
* Fails open.
*/
async function injectBootstrap(
ctx: OpenclawRuntimeContext,
extracted: SessionStartExtracted,
): Promise<void> {
const logger = createLogger({ name: 'openclaw-hooks/handler' });
try {
const bridge = buildBridge();
const hits: MemoryHit[] = await bridge.recallMemory('', {
limit: extracted.recallLimit,
scope: 'personal',
});
if (hits.length === 0) return;
const text = formatHits(hits);
const arr = ctx.bootstrapFiles;
if (Array.isArray(arr)) {
// Mutate the host-owned array in place — this IS the injection seam.
(arr as unknown[]).push(text);
} else {
// The host did not provide a mutable array; nothing to inject into.
logger.debug('agent:bootstrap had no bootstrapFiles array — skipping inject');
}
} catch {
// Fail-open: a recall failure must not block bootstrap.
}
}
const PER_HIT_BUDGET = 240;
function formatHits(hits: readonly MemoryHit[]): string {
const lines: string[] = [`hive-mind: top ${hits.length} recalled frames`];
for (const h of hits) {
const content = h.content.length > PER_HIT_BUDGET
? h.content.slice(0, PER_HIT_BUDGET) + '…'
: h.content;
lines.push(`- (${h.importance}) ${h.created_at}: ${content}`);
}
return lines.join('\n');
}

View File

@@ -0,0 +1,60 @@
/**
* Builds the `HOOK.md` frontmatter the OpenClaw gateway reads to discover our
* managed hook directory.
*
* OpenClaw discovers a hook from `~/.openclaw/hooks/<name>/HOOK.md`: the
* frontmatter declares `metadata.openclaw.events[]` (the events the sibling
* `handler.js` default-export subscribes to), and the body is human docs.
*
* IMPORTANT (spec §5.5): the events[] array uses the HOOK.md-style names
* INCLUDING the `session:` prefix (`session:compact:before`), but the RUNTIME
* `event.action` drops it (`compact:before`). The handler matches on the
* action suffix, so declaring the prefixed form here is correct and the
* handler still fires.
*/
/** The OpenClaw internal events our handler subscribes to (HOOK.md form). */
export const HOOK_MD_EVENTS = [
'agent:bootstrap',
'message:received',
'message:sent',
'session:compact:before',
] as const;
/**
* Render the `HOOK.md` contents. `handlerFile` is the basename of the compiled
* handler the gateway will `import()` (`handler.js`).
*/
export function renderHookMd(handlerFile = 'handler.js'): string {
const eventsYaml = HOOK_MD_EVENTS.map((e) => ` - ${e}`).join('\n');
return [
'---',
'name: hive-mind',
'description: >-',
' hive-mind silent capture — routes OpenClaw gateway conversation episodes',
' into hive-mind frames via hive-mind-cli. Capture-only; fails open.',
'metadata:',
' openclaw:',
` handler: ${handlerFile}`,
' events:',
eventsYaml,
'---',
'',
'# hive-mind silent capture (OpenClaw)',
'',
'This managed hook is installed by `@waggle/hive-mind-hooks-openclaw`. It is',
'an **in-process** internal hook: the gateway loads the default export from',
`\`${handlerFile}\` and dispatches the events above to it.`,
'',
'Lifecycle mapping:',
'',
'- `agent:bootstrap` → recall + inject (mutates `context.bootstrapFiles`)',
'- `message:received` → save the inbound prompt as a temporary frame',
'- `message:sent` → summarize + save the outbound turn (debounced; 0..N/turn)',
'- `session:compact:before` → compaction maintenance (runtime action `compact:before`)',
'',
'Capture-only and fail-open: the handler never throws and never blocks the',
'gateway. Remove with `openclaw-hooks uninstall`.',
'',
].join('\n');
}

View File

@@ -0,0 +1,86 @@
/**
* @waggle/hive-mind-hooks-openclaw — barrel export.
*
* OpenClaw silent-capture shim for hive-mind. Unlike the stdin-JSON tools
* (codex / cursor / hermes), OpenClaw hooks are IN-PROCESS TypeScript: a hook
* is a directory `~/.openclaw/hooks/hive-mind/{HOOK.md, handler.js}` whose
* default export the gateway loads and runs inside its own Node process. So
* the installer writes that managed dir + minimally touches the JSON5 config,
* and the handler drives the shared lifecycle bodies via
* `makeOpenclawHandler` (hooks-core) rather than `runHook`.
*
* Four events (matched on the `(type, action)` PAIR):
* - SessionStart → `agent:bootstrap` (mutates `context.bootstrapFiles`)
* - UserPromptSubmit → `message:received`
* - Stop → `message:sent` (0..N/turn — DEBOUNCED; non-replyable)
* - PreCompact → `session:compact:before` (runtime action `compact:before`)
*
* JSON5 round-trip is lossy, so reversibility relies on the literal
* byte-identical backup + a recorded managed-dir removal. Programmatic
* install / uninstall / verify lifecycle; most users invoke the
* `openclaw-hooks` bin. The in-process `handler.ts` default export is the
* `./handler` subpath export.
*/
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 {
OpenclawPaths,
ResolvePathsOptions,
HookBasename,
} from './paths.js';
export {
resolvePaths,
allHookBasenames,
backupPathFor,
hookCommandFor,
HIVE_HOOK_DIR_NAME,
HIVE_HOOK_ENTRY_KEY,
} from './paths.js';
export {
openclawAdapter,
OPENCLAW_EVENT_NAME,
OPENCLAW_PROVENANCE,
} from './adapter.js';
export type {
HiveEntryEnv,
RegisterOptions,
} from './json5-merger.js';
export {
parseConfig,
serializeConfig,
jsonRegister,
jsonUnregister,
hasHiveEntries,
HIVE_ENTRY_KEY,
HOOKS_KEY,
} from './json5-merger.js';
export {
renderHookMd,
HOOK_MD_EVENTS,
} from './hook-md.js';
// The in-process handler default export (the gateway loads this). Re-exported
// for tests + programmatic drive; the gateway loads the COMPILED copy from
// `~/.openclaw/hooks/hive-mind/handler.js`.
export { default as openclawHook } from './handler.js';

View File

@@ -0,0 +1,168 @@
/**
* Programmatic install entry point for the OpenClaw hive-mind hooks.
*
* OpenClaw hooks are IN-PROCESS, so install is structurally different from the
* stdin-JSON tools: we WRITE A MANAGED HOOK DIRECTORY and only minimally touch
* the JSON5 config.
*
* Steps:
* 1. Read existing `~/.openclaw/openclaw.json` IF it exists (create-if-missing
* — the config is OPTIONAL on a fresh install). Strict JSON first, JSON5
* fallback.
* 2. If it pre-existed, write a LITERAL byte-identical backup; if absent,
* skip the backup and record `created_by_us=true`. (JSON5 round-trip is
* lossy — comments / trailing commas are dropped — so reversibility relies
* on the literal backup, not a re-serialized diff.)
* 3. Write the managed hook DIRECTORY
* `~/.openclaw/hooks/hive-mind/{HOOK.md, handler.js}` — HOOK.md declares
* our events, handler.js is the compiled in-process default export COPIED
* from this package's dist/.
* 4. Minimal-touch edit of openclaw.json: flip `hooks.internal.enabled=true`
* + add `hooks.internal.entries["hive-mind"]={enabled:true, env?}` via
* `jsonRegister`. Existing config preserved verbatim.
* 5. Write the merged config back over openclaw.json.
* 6. Drop a pointer at `~/.openclaw/hive-mind-install.json` recording the
* created dir + touched keys (pointer.extra) so uninstall removes exactly
* what we added (and restores openclaw.json from the byte-identical
* backup, or removes it if we created it).
*/
import { readFile, writeFile, mkdir, copyFile } 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 {
backupByteIdentical,
normalizeCliPath,
writePointer,
type InstallPointer,
} from '@waggle/hive-mind-hooks-core';
import {
resolvePaths,
HIVE_HOOK_DIR_NAME,
HIVE_HOOK_ENTRY_KEY,
type OpenclawPaths,
type ResolvePathsOptions,
} from './paths.js';
import { parseConfig, serializeConfig, jsonRegister } from './json5-merger.js';
import { renderHookMd } from './hook-md.js';
export interface InstallResult {
paths: OpenclawPaths;
/** The literal byte-identical backup written when openclaw.json pre-existed, else null. */
backupPath: string | null;
pointerPath: string;
/** The managed hook dir we created (`~/.openclaw/hooks/hive-mind/`). */
hookDir: string;
/** Lifecycle names the single handler dispatches. */
installedHooks: readonly string[];
/** openclaw.json keys we touched (recorded in pointer.extra). */
touchedKeys: readonly string[];
/** True when openclaw.json did NOT pre-exist and we created it. */
createdByUs: boolean;
/** The cli_path embedded in the entry env (undefined = default lookup at runtime). */
cliPath?: string;
}
export interface InstallOptions extends ResolvePathsOptions {
/** 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). Threaded into the hook entry env as `WAGGLE_HIVE_MIND_CLI` so the
* in-process handler's CliBridge uses it.
*/
cliPath?: string;
/** Extra env to attach to the hook entry (e.g. WAGGLE_WORKSPACE_ID). */
env?: Record<string, string>;
}
const POINTER_VERSION = '0.1.0';
const TOUCHED_KEYS = ['hooks.internal.enabled', `hooks.internal.entries.${HIVE_HOOK_ENTRY_KEY}`] as const;
const LIFECYCLE_NAMES = ['session-start', 'user-prompt-submit', 'stop', 'pre-compact'] as const;
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: 'openclaw-hooks/install' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.handlerSourcePath !== undefined
? { handlerSourcePath: opts.handlerSourcePath }
: { moduleUrl: import.meta.url }),
});
const now = opts.now ?? ((): Date => new Date());
log.info('install starting', { config: paths.configPath, hookDir: paths.hiveHookDir });
// Read existing config if present; create-if-missing otherwise.
let existingConfig: Record<string, unknown> | undefined;
const preExisted = existsSync(paths.configPath);
if (preExisted) {
existingConfig = parseConfig(await readFile(paths.configPath, 'utf-8'));
}
await ensureDir(paths.openclawDir);
await ensureDir(dirname(paths.pointerPath));
// Literal byte-identical backup of the original config (no-op when absent).
const { backupPath } = await backupByteIdentical(paths.configPath, now().toISOString());
if (backupPath) log.info('openclaw.json backed up', { backupPath });
// Write the managed hook dir: HOOK.md + the compiled handler.js (copied from
// this package's dist/). We COPY rather than reference so the gateway loads a
// stable file even if this package is removed (the handler still requires the
// @waggle/* deps at runtime — the OQ-5 live-install caveat, see README).
await ensureDir(paths.hiveHookDir);
await writeFile(paths.hookMdPath, renderHookMd('handler.js'), 'utf-8');
if (!existsSync(paths.handlerSourcePath)) {
throw new Error(
`compiled handler not found at ${paths.handlerSourcePath}. ` +
`Build the package (tsc --build) before installing.`,
);
}
await copyFile(paths.handlerSourcePath, paths.installedHandlerPath);
// Minimal-touch config edit.
const cliPath = normalizeCliPath(opts.cliPath);
const env: Record<string, string> = { ...(opts.env ?? {}) };
if (cliPath !== undefined) env['WAGGLE_HIVE_MIND_CLI'] = cliPath;
const merged = jsonRegister(existingConfig, Object.keys(env).length > 0 ? { env } : {});
await writeFile(paths.configPath, serializeConfig(merged), 'utf-8');
const createdByUs = !preExisted;
const pointer: InstallPointer = {
version: POINTER_VERSION,
installed_at: now().toISOString(),
config_path: paths.configPath,
settings_backup: backupPath,
created_by_us: createdByUs,
hooks_dir: paths.hiveHookDir,
installed_hooks: LIFECYCLE_NAMES,
cli_path: cliPath ?? null,
extra: {
hook_dir_name: HIVE_HOOK_DIR_NAME,
touched_keys: TOUCHED_KEYS,
},
};
await writePointer(paths.pointerPath, pointer);
log.info('install complete', { createdByUs, hookDir: paths.hiveHookDir, cliPath: cliPath ?? '(PATH lookup)' });
const result: InstallResult = {
paths,
backupPath,
pointerPath: paths.pointerPath,
hookDir: paths.hiveHookDir,
installedHooks: LIFECYCLE_NAMES,
touchedKeys: TOUCHED_KEYS,
createdByUs,
};
if (cliPath !== undefined) result.cliPath = cliPath;
return result;
}

View File

@@ -0,0 +1,172 @@
/**
* Bespoke JSON5 codec + minimal-touch register/unregister for OpenClaw's
* `~/.openclaw/openclaw.json`.
*
* OpenClaw's config is JSON5 (comments, trailing commas, `$include` merges,
* `${ENV}` substitution). Naive `JSON.parse`→`JSON.stringify` DESTROYS user
* comments and trailing commas, so we do NOT re-serialize the whole file for
* fidelity. Instead:
* - the actual hook IMPLEMENTATION lives in a managed DIRECTORY
* (`~/.openclaw/hooks/hive-mind/{HOOK.md, handler.js}`), written by
* install.ts;
* - this module performs a MINIMAL-TOUCH edit of openclaw.json — flip
* `hooks.internal.enabled = true` and add an
* `hooks.internal.entries["hive-mind"] = { enabled: true }` entry — so the
* gateway discovers + activates our hook dir;
* - reversibility relies on the LITERAL byte-identical backup the installer
* writes (install-core `backupByteIdentical` / `restoreFromBackup`), NOT
* on re-serialization fidelity. This module only produces the merged
* object we WRITE on install.
*
* Parse priority: strict `JSON.parse` FIRST (fast, exact), then `JSON5.parse`
* fallback (tolerates comments / trailing commas). Both fail → throw so the
* installer fails loudly rather than clobbering a user config.
*
* Immutability: every function returns a NEW config object and never mutates
* its input (mirrors the `jsonRegister` contract).
*/
import JSON5 from 'json5';
/** Logical entry key under `hooks.internal.entries` identifying our hook. */
export const HIVE_ENTRY_KEY = 'hive-mind';
/** Top-level JSON5 key holding the hooks subsystem. */
export const HOOKS_KEY = 'hooks';
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
/**
* Parse an `openclaw.json` string into a plain object. Returns `{}` for an
* empty/whitespace string (create-if-missing). Tries strict JSON first, then
* JSON5; throws only if BOTH fail.
*/
export function parseConfig(raw: string): Record<string, unknown> {
if (!raw || raw.trim().length === 0) return {};
let parsed: unknown;
try {
parsed = JSON.parse(raw);
} catch {
try {
parsed = JSON5.parse(raw);
} catch (err) {
throw new Error(
'failed to parse ~/.openclaw/openclaw.json as JSON or JSON5: ' +
(err instanceof Error ? err.message : String(err)),
);
}
}
const record = asRecord(parsed);
// A top-level scalar/array doc is not a valid openclaw config shape; treat
// it as empty rather than crashing (the original bytes are backed up
// regardless, so nothing is lost on uninstall).
return record ?? {};
}
/**
* Serialize a config object back to JSON (2-space, trailing newline). NOTE:
* this is LOSSY for JSON5 sources (comments / trailing commas are dropped) —
* which is exactly why uninstall restores the literal byte-identical backup
* instead of re-serializing. We use plain `JSON.stringify` (not JSON5) so the
* written file is valid strict JSON, which OpenClaw's JSON5 parser also
* accepts.
*/
export function serializeConfig(config: Record<string, unknown>): string {
return JSON.stringify(config, null, 2) + '\n';
}
/** The minimal env block our entry carries (workspace context for the handler). */
export interface HiveEntryEnv {
[key: string]: string;
}
export interface RegisterOptions {
/** Optional env to attach to the entry (e.g. WAGGLE_WORKSPACE_ID). */
env?: HiveEntryEnv;
}
/**
* Returns a NEW config object with the internal-hooks subsystem enabled and a
* marker entry pointing the gateway at our managed `hive-mind` hook dir.
* Existing config (including any other `hooks.internal.entries`) is preserved
* verbatim. Re-running install replaces OUR entry in place (idempotent
* upgrade) rather than duplicating.
*
* Touched keys (recorded by the caller in the pointer.extra so uninstall —
* the rare backup-less path — knows exactly what to strip):
* - hooks.internal.enabled = true
* - hooks.internal.entries["hive-mind"] = { enabled: true, env? }
*/
export function jsonRegister(
config: Record<string, unknown> | undefined,
opts: RegisterOptions = {},
): Record<string, unknown> {
const next: Record<string, unknown> = config ? { ...config } : {};
const hooks = asRecord(next[HOOKS_KEY]);
const nextHooks: Record<string, unknown> = hooks ? { ...hooks } : {};
const internal = asRecord(nextHooks['internal']);
const nextInternal: Record<string, unknown> = internal ? { ...internal } : {};
nextInternal['enabled'] = true;
const entries = asRecord(nextInternal['entries']);
const nextEntries: Record<string, unknown> = entries ? { ...entries } : {};
const entry: Record<string, unknown> = { enabled: true };
if (opts.env && Object.keys(opts.env).length > 0) entry['env'] = { ...opts.env };
nextEntries[HIVE_ENTRY_KEY] = entry;
nextInternal['entries'] = nextEntries;
nextHooks['internal'] = nextInternal;
next[HOOKS_KEY] = nextHooks;
return next;
}
/**
* Returns a NEW config object with our `hive-mind` entry removed from
* `hooks.internal.entries`. Leaves `hooks.internal.enabled` as-is (other hooks
* may rely on it — minimal-touch). Non-hive entries preserved verbatim. Never
* mutates input.
*
* Note: uninstall normally restores the literal byte-identical backup, so this
* is used for verify/diagnostics and the (rare) backup-less path.
*/
export function jsonUnregister(
config: Record<string, unknown> | undefined,
): Record<string, unknown> {
const next: Record<string, unknown> = config ? { ...config } : {};
const hooks = asRecord(next[HOOKS_KEY]);
if (!hooks) return next;
const nextHooks: Record<string, unknown> = { ...hooks };
const internal = asRecord(nextHooks['internal']);
if (!internal) {
next[HOOKS_KEY] = nextHooks;
return next;
}
const nextInternal: Record<string, unknown> = { ...internal };
const entries = asRecord(nextInternal['entries']);
if (entries) {
const nextEntries: Record<string, unknown> = { ...entries };
delete nextEntries[HIVE_ENTRY_KEY];
nextInternal['entries'] = nextEntries;
}
nextHooks['internal'] = nextInternal;
next[HOOKS_KEY] = nextHooks;
return next;
}
/** True iff `hooks.internal.entries["hive-mind"]` is present. */
export function hasHiveEntries(config: Record<string, unknown> | undefined): boolean {
if (!config) return false;
const hooks = asRecord(config[HOOKS_KEY]);
const internal = asRecord(hooks?.['internal']);
const entries = asRecord(internal?.['entries']);
return !!entries && Object.prototype.hasOwnProperty.call(entries, HIVE_ENTRY_KEY);
}

View File

@@ -0,0 +1,120 @@
/**
* Filesystem path helpers for the OpenClaw hive-mind hook install lifecycle.
*
* OpenClaw differs structurally from the stdin-JSON tools (codex / cursor /
* hermes): its hooks are IN-PROCESS TypeScript. A hook is a DIRECTORY
* `~/.openclaw/hooks/<name>/{HOOK.md, handler.js}` that the gateway discovers
* and dynamically `import()`s. Config (`~/.openclaw/openclaw.json`, JSON5)
* only flips the internal-hooks subsystem on and references the dir.
*
* So this module resolves THREE roots the JSON tools don't have:
* - the managed hook DIRECTORY we write (`~/.openclaw/hooks/hive-mind/`),
* - the compiled `handler.js` we COPY into that dir at install time,
* - the `HOOK.md` we write alongside it.
*
* The Windows-safe backup path + `--cli-path` quoting are reused verbatim
* from `@waggle/hive-mind-hooks-core` so openclaw reads like the reference.
*/
import { homedir } from 'node:os';
import { dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url';
import { backupPathFor, hookCommandFor } from '@waggle/hive-mind-hooks-core';
/** Name of the managed hook directory we create under `~/.openclaw/hooks/`. */
export const HIVE_HOOK_DIR_NAME = 'hive-mind';
/** Logical hook entry key under `hooks.internal.entries`. */
export const HIVE_HOOK_ENTRY_KEY = 'hive-mind';
export interface OpenclawPaths {
/** OpenClaw config root (`~/.openclaw/`). */
openclawDir: string;
/** `~/.openclaw/openclaw.json` — the JSON5 config (internal-hooks subsystem). */
configPath: string;
/** `~/.openclaw/hive-mind-install.json` — pointer to the active backup + created dir. */
pointerPath: string;
/** `~/.openclaw/hooks/` — OpenClaw's hook-discovery root. */
hooksRoot: string;
/** `~/.openclaw/hooks/hive-mind/` — the managed hook dir WE write. */
hiveHookDir: string;
/** `~/.openclaw/hooks/hive-mind/HOOK.md` — frontmatter declaring our events. */
hookMdPath: string;
/** `~/.openclaw/hooks/hive-mind/handler.js` — the compiled handler we copy in. */
installedHandlerPath: string;
/** Source of the self-contained handler bundle in THIS package's `dist/`. */
handlerSourcePath: string;
}
export interface ResolvePathsOptions {
/** Override $HOME for tests. */
home?: string;
/** Override the URL used to locate dist/ (defaults to import.meta.url at runtime). */
moduleUrl?: string;
/** Override the compiled-handler source path directly (wins over moduleUrl). */
handlerSourcePath?: string;
}
/**
* OpenClaw's four internal lifecycle hooks. Unlike the stdin tools these are
* NOT separate compiled scripts — one `handler.js` default-export dispatches
* all four by `(type, action)`. The basenames here name the LIFECYCLE for
* pointer bookkeeping + verify, not separate files on disk.
*/
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;
}
/**
* Resolve the self-contained handler bundle shipped in this package's `dist/`.
* The compiled install module lives at `<pkg>/dist/<file>.js`; dirname gives
* `<pkg>/dist/`, so `handler.bundle.cjs` is a sibling.
*/
function handlerSourceFromModuleUrl(moduleUrl: string): string {
const dir = dirname(fileURLToPath(moduleUrl));
return resolve(dir, 'handler.bundle.cjs');
}
export function resolvePaths(opts: ResolvePathsOptions = {}): OpenclawPaths {
const home = opts.home ?? homedir();
const openclawDir = join(home, '.openclaw');
const configPath = join(openclawDir, 'openclaw.json');
const pointerPath = join(openclawDir, 'hive-mind-install.json');
const hooksRoot = join(openclawDir, 'hooks');
const hiveHookDir = join(hooksRoot, HIVE_HOOK_DIR_NAME);
const hookMdPath = join(hiveHookDir, 'HOOK.md');
const installedHandlerPath = join(hiveHookDir, 'handler.js');
let handlerSourcePath: string;
if (opts.handlerSourcePath) {
handlerSourcePath = resolve(opts.handlerSourcePath);
} else if (opts.moduleUrl) {
handlerSourcePath = handlerSourceFromModuleUrl(opts.moduleUrl);
} else {
// Fallback for ad-hoc test use — install.ts always passes moduleUrl.
handlerSourcePath = resolve(process.cwd(), 'dist', 'handler.bundle.cjs');
}
return {
openclawDir,
configPath,
pointerPath,
hooksRoot,
hiveHookDir,
hookMdPath,
installedHandlerPath,
handlerSourcePath,
};
}
/** Re-export the shared Windows-safe helpers so openclaw modules read like CC. */
export { backupPathFor, hookCommandFor };

View File

@@ -0,0 +1,98 @@
/**
* Programmatic uninstall entry point for the OpenClaw hive-mind hooks.
*
* Removes EXACTLY what install added:
* 1. Delete the managed hook DIRECTORY `~/.openclaw/hooks/hive-mind/`
* (HOOK.md + handler.js) recorded in the pointer.
* 2. Restore `~/.openclaw/openclaw.json`:
* - `created_by_us=false` (config pre-existed): restore the LITERAL
* byte-identical backup the installer wrote; refuse to delete the
* backup unless the in-place readback matches. (JSON5 re-serialization
* is lossy, so we restore the original BYTES — comments and trailing
* commas are preserved exactly because we never touch the re-serialized
* merge on this path.)
* - `created_by_us=true` (we created openclaw.json): delete the file we
* created — never orphan it, never leave a backup behind.
* 3. Remove the pointer.
*
* The config restore/delete is handled by the shared `restoreFromBackup`
* primitive; the hook-dir removal is openclaw-specific.
*/
import { unlink, rm } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import { readPointer, restoreFromBackup } from '@waggle/hive-mind-hooks-core';
import { resolvePaths, type OpenclawPaths, type ResolvePathsOptions } from './paths.js';
export interface UninstallResult {
paths: OpenclawPaths;
/** Backup restored from, or null when we deleted a file we created. */
restoredFrom: string | null;
/** True when created_by_us=true and we removed the config we created. */
createdRemoved: boolean;
/** True when the managed hook dir was removed. */
hookDirRemoved: boolean;
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;
}
export async function uninstall(opts: UninstallOptions = {}): Promise<UninstallResult> {
const log = opts.logger ?? createLogger({ name: 'openclaw-hooks/uninstall' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.handlerSourcePath !== undefined
? { handlerSourcePath: opts.handlerSourcePath }
: { moduleUrl: import.meta.url }),
});
const cleanup = opts.cleanupBackup ?? true;
if (!existsSync(paths.pointerPath)) {
throw new Error(
`no install pointer found at ${paths.pointerPath}. ` +
`Was @waggle/hive-mind-hooks-openclaw ever installed for this user?`,
);
}
const pointer = await readPointer(paths.pointerPath);
// 1. Remove the managed hook dir we created. Prefer the pointer's recorded
// hooks_dir; fall back to the resolved path.
const hookDir = pointer.hooks_dir ?? paths.hiveHookDir;
let hookDirRemoved = false;
if (existsSync(hookDir)) {
await rm(hookDir, { recursive: true, force: true });
hookDirRemoved = true;
log.info('managed hook dir removed', { hookDir });
}
// 2. Restore / delete openclaw.json via the shared primitive.
const restore = await restoreFromBackup({
configPath: paths.configPath,
pointer,
cleanupBackup: cleanup,
});
if (restore.createdRemoved) {
log.info('openclaw.json removed (created by us)', { config: paths.configPath });
} else {
log.info('openclaw.json restored byte-identical', { config: paths.configPath });
}
// 3. Remove the pointer.
await unlink(paths.pointerPath);
return {
paths,
restoredFrom: restore.restoredFrom,
createdRemoved: restore.createdRemoved,
hookDirRemoved,
pointerRemoved: true,
backupRemoved: restore.backupRemoved,
};
}

View File

@@ -0,0 +1,179 @@
/**
* Smoke-check the OpenClaw install: openclaw.json exists + parses (JSON/JSON5)
* + carries the hive-mind internal-hooks entry with the subsystem enabled, the
* managed hook dir + HOOK.md + handler.js exist on disk, and hive-mind-cli
* answers a `--help` probe. Plus the openclaw-specific activation advisory
* (spec §5.5 / §6.2): hooks are OFF until `hooks.internal.enabled=true`.
*
* Probe priority for `cli_path`:
* 1. Explicit `opts.cliPath` (caller override)
* 2. `cli_path` recorded in `~/.openclaw/hive-mind-install.json`
* 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, type ResolvePathsOptions } from './paths.js';
import { parseConfig, hasHiveEntries, HOOKS_KEY } from './json5-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 isJsPath(p: string): boolean {
return p.endsWith('.js') || p.endsWith('.mjs') || p.endsWith('.cjs');
}
function internalEnabled(config: Record<string, unknown>): boolean {
const hooks = config[HOOKS_KEY];
if (!hooks || typeof hooks !== 'object') return false;
const internal = (hooks as Record<string, unknown>)['internal'];
if (!internal || typeof internal !== 'object') return false;
return (internal as Record<string, unknown>)['enabled'] === true;
}
function probeCliVersion(
cliPath: string,
spawnImpl: typeof spawn,
timeoutMs: number,
): Promise<{ ok: boolean; output: string }> {
return new Promise((resolve) => {
let settled = false;
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: 'openclaw-hooks/verify' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.handlerSourcePath !== undefined
? { handlerSourcePath: opts.handlerSourcePath }
: { moduleUrl: import.meta.url }),
});
const checks: VerifyCheck[] = [];
// 1. openclaw.json exists and parses.
if (!existsSync(paths.configPath)) {
checks.push({ name: 'openclaw.json exists', ok: false, detail: paths.configPath });
return { ok: false, checks };
}
checks.push({ name: 'openclaw.json exists', ok: true, detail: paths.configPath });
let parsed: Record<string, unknown>;
try {
parsed = parseConfig(await readFile(paths.configPath, 'utf-8'));
checks.push({ name: 'openclaw.json parses as JSON/JSON5', ok: true });
} catch (err) {
checks.push({
name: 'openclaw.json parses as JSON/JSON5',
ok: false,
detail: err instanceof Error ? err.message : String(err),
});
return { ok: false, checks };
}
// 2. hive-mind internal-hooks entry present.
checks.push({
name: 'openclaw.json contains the hive-mind internal-hooks entry',
ok: hasHiveEntries(parsed),
});
// 3. internal hooks subsystem enabled (hooks are OFF otherwise).
const enabled = internalEnabled(parsed);
checks.push({
name: 'internal hooks subsystem enabled',
ok: enabled,
detail: enabled
? 'hooks.internal.enabled: true — the hive-mind hook is active.'
: 'set hooks.internal.enabled: true (or run `openclaw hooks enable hive-mind`) — hooks are OFF until opted in.',
});
// 4. managed hook dir + HOOK.md + compiled handler exist on disk.
checks.push({
name: 'managed hook dir exists',
ok: existsSync(paths.hiveHookDir),
detail: paths.hiveHookDir,
});
checks.push({
name: 'HOOK.md readable on disk',
ok: await fileReadable(paths.hookMdPath),
detail: paths.hookMdPath,
});
checks.push({
name: 'handler.js readable on disk',
ok: await fileReadable(paths.installedHandlerPath),
detail: paths.installedHandlerPath,
});
// 5. hive-mind-cli responds to --help (prefer install-pinned --cli-path).
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 };
}