refactor: remove coding-agent hook management (P2.2)
The hooks for Claude Code, Codex and the other agents ran the hive-mind-hooks-* packages, which left the repository; ADR-0002 hides the feature in v1. Remove the hook installer surface from the tool launcher, the POST /api/tools/hooks route, the hook status probe in tool detection, and the hook fields of the tool manifest and detection envelope (hookCapable, hookRoot, hookPointer, hooksInstalled, hookPointerPath). Third-party adapter manifests no longer accept the hook fields. In the web UI, remove the hidden hook actions and the "How memory is shared" explainer from the Launcher, adapter.manageHooks, the hook-wired count in Mission Control and the agentHooks and memoryMcp memory feature flags. Launch, watch and stop are unchanged; the roadmap tool note no longer mentions hooks.
This commit is contained in:
@@ -32,11 +32,11 @@ const WAGGLE_ENV_ALLOWLIST = new Set([
|
||||
'WAGGLE_DANCE_TEAM_ID', 'WAGGLE_DANCE_URL', 'WAGGLE_RUN_TOKEN',
|
||||
'WAGGLE_CLI_NODE_PATH', 'WAGGLE_CLI_ENTRY',
|
||||
'WAGGLE_SIGNAL_EMIT', 'WAGGLE_SIDECAR_URL',
|
||||
'WAGGLE_HOOK_NODE_PATH', 'HIVE_MIND_DATA_DIR', 'NO_COLOR',
|
||||
'HIVE_MIND_DATA_DIR', 'NO_COLOR',
|
||||
]);
|
||||
|
||||
/**
|
||||
* Build a fail-closed environment for user-installed AI tools and hook bins.
|
||||
* Build a fail-closed environment for user-installed AI tools.
|
||||
* Provider keys, credential helpers, proxy credentials, infrastructure
|
||||
* secrets, and arbitrary ambient variables are never inherited. The caller
|
||||
* may add only the narrow Waggle metadata enumerated above.
|
||||
|
||||
@@ -457,18 +457,11 @@ export {
|
||||
} from './tool-detection.js';
|
||||
export {
|
||||
launchTool,
|
||||
runHookCommand,
|
||||
hookPackageFor,
|
||||
resolveHookRuntime,
|
||||
resolveWaggleRuntime,
|
||||
type ToolLauncherDeps,
|
||||
type LaunchOptions,
|
||||
type LaunchResult,
|
||||
type ObservedHandle,
|
||||
type HookAction,
|
||||
type HookCommandOptions,
|
||||
type HookCommandResult,
|
||||
type HookRuntimePaths,
|
||||
type WaggleRuntimePaths,
|
||||
} from './tool-launcher.js';
|
||||
export { spawnSidecarOwnedProcess } from './sidecar-owned-process.js';
|
||||
|
||||
@@ -2,12 +2,11 @@
|
||||
* Tool detection — AI-OS Phase 0.
|
||||
*
|
||||
* Detects which external AI tools (Claude Code, Cursor, Claude Desktop, …)
|
||||
* are installed on the user's machine and whether their hive-mind hooks
|
||||
* are wired up. Returns a stable envelope (`ToolDetectionResult` in
|
||||
* @waggle/shared) consumed by:
|
||||
* are installed on the user's machine. Returns a stable envelope
|
||||
* (`ToolDetectionResult` in @waggle/shared) consumed by:
|
||||
*
|
||||
* - the sidecar route GET /api/tools/detect (Phase 0)
|
||||
* - the launcher dock + hook-installer UX (Phase 2)
|
||||
* - the launcher dock (Phase 2)
|
||||
* - the Mission Control inventory tile (Phase 4)
|
||||
*
|
||||
* Design notes:
|
||||
@@ -20,17 +19,12 @@
|
||||
* resolves like `which`; on Windows like `where`. The shim takes
|
||||
* a logical name ('claude'), not a full path, so callers don't
|
||||
* need to know the per-platform extension (.cmd / .exe / none).
|
||||
* 3. Hook-install status follows the hive-mind shim-core convention:
|
||||
* `~/<tool-config-dir>/hive-mind-install.json` is the pointer
|
||||
* written at install time. We additionally verify that the
|
||||
* `backup` field still points to an existing file — otherwise the
|
||||
* pointer is stale and the install is effectively rolled back.
|
||||
* 4. Detector functions are pure (`(deps) => Promise<DetectedTool>`)
|
||||
* 3. Detector functions are pure (`(deps) => Promise<DetectedTool>`)
|
||||
* so they can be unit-tested individually and composed in parallel
|
||||
* by the orchestrator.
|
||||
*/
|
||||
|
||||
import { access, constants, readFile } from 'node:fs/promises';
|
||||
import { access, constants } from 'node:fs/promises';
|
||||
import { homedir, platform as osPlatform } from 'node:os';
|
||||
import { posix as pathPosix, win32 as pathWin32 } from 'node:path';
|
||||
import { execFile } from 'node:child_process';
|
||||
@@ -126,11 +120,6 @@ export interface ToolDetectionDeps {
|
||||
* top — `null` here means "could not determine".
|
||||
*/
|
||||
execVersion?: (binary: string, args: string[]) => Promise<string | null>;
|
||||
/**
|
||||
* Read a JSON file. Returns parsed value, or null on any failure
|
||||
* (missing, malformed, permission denied).
|
||||
*/
|
||||
readJson?: (p: string) => Promise<unknown>;
|
||||
/**
|
||||
* PATH lookup shim. Given a logical binary name ('claude'), returns
|
||||
* the resolved absolute path or null. Production implementation uses
|
||||
@@ -182,15 +171,6 @@ export async function defaultExecVersion(
|
||||
}
|
||||
}
|
||||
|
||||
async function defaultReadJson(p: string): Promise<unknown> {
|
||||
try {
|
||||
const raw = await readFile(p, 'utf8');
|
||||
return JSON.parse(raw);
|
||||
} catch {
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* Env for the `which`/`where` lookup. Fail closed to the non-secret external
|
||||
* process environment. On POSIX, merge the resolved login-shell
|
||||
@@ -310,7 +290,6 @@ interface ResolvedDeps {
|
||||
cwd: string;
|
||||
exists: (p: string) => Promise<boolean>;
|
||||
execVersion: (binary: string, args: string[]) => Promise<string | null>;
|
||||
readJson: (p: string) => Promise<unknown>;
|
||||
pathFromEnv: (name: string) => Promise<string | null>;
|
||||
windowsAppExecutables: () => Promise<WindowsAppExecutables>;
|
||||
}
|
||||
@@ -325,7 +304,6 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
|
||||
cwd: opts.cwd ?? process.cwd(),
|
||||
exists: opts.exists ?? defaultExists,
|
||||
execVersion: opts.execVersion ?? defaultExecVersion,
|
||||
readJson: opts.readJson ?? defaultReadJson,
|
||||
pathFromEnv:
|
||||
pathFromEnvOpt === undefined
|
||||
? defaultPathFromEnv
|
||||
@@ -342,140 +320,7 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
|
||||
};
|
||||
}
|
||||
|
||||
// ── Hook status (shared across all tools) ───────────────────────────
|
||||
|
||||
// Hook-pointer paths + roots come from each tool's ToolManifest (the registry —
|
||||
// #5), so third-party adapters and the Claude Desktop MCP bridge need no map.
|
||||
|
||||
interface HookProbe {
|
||||
hooksInstalled: boolean;
|
||||
hookPointerPath: string | null;
|
||||
}
|
||||
|
||||
const CLAUDE_CODE_HOOKS = [
|
||||
['SessionStart', 'session-start'],
|
||||
['UserPromptSubmit', 'user-prompt-submit'],
|
||||
['Stop', 'stop'],
|
||||
['PreCompact', 'pre-compact'],
|
||||
] as const;
|
||||
|
||||
function objectRecord(value: unknown): Record<string, unknown> | null {
|
||||
return value !== null && typeof value === 'object' && !Array.isArray(value)
|
||||
? value as Record<string, unknown>
|
||||
: null;
|
||||
}
|
||||
|
||||
function tokenizeHookCommand(command: string): string[] | null {
|
||||
if (/[\r\n\0]/.test(command)) return null;
|
||||
|
||||
const tokens: string[] = [];
|
||||
let index = 0;
|
||||
while (index < command.length) {
|
||||
while (command[index] === ' ' || command[index] === '\t') index += 1;
|
||||
if (index >= command.length) break;
|
||||
|
||||
if (command[index] === '"') {
|
||||
const end = command.indexOf('"', index + 1);
|
||||
if (end === -1 || end === index + 1) return null;
|
||||
const token = command.slice(index + 1, end);
|
||||
if (/[$`%!]/.test(token)) return null;
|
||||
tokens.push(token);
|
||||
index = end + 1;
|
||||
if (index < command.length && command[index] !== ' ' && command[index] !== '\t') return null;
|
||||
continue;
|
||||
}
|
||||
|
||||
const start = index;
|
||||
while (index < command.length && command[index] !== ' ' && command[index] !== '\t') {
|
||||
if (/['";&|<>`^#$%!*?()[\]{}]/.test(command[index])) return null;
|
||||
index += 1;
|
||||
}
|
||||
if (index === start) return null;
|
||||
tokens.push(command.slice(start, index));
|
||||
}
|
||||
|
||||
return tokens;
|
||||
}
|
||||
|
||||
function isAbsolutePathForPlatform(platform: NodeJS.Platform, candidate: string): boolean {
|
||||
return platform === 'win32'
|
||||
? pathWin32.isAbsolute(candidate)
|
||||
: pathPosix.isAbsolute(candidate);
|
||||
}
|
||||
|
||||
function normalizedHookPath(platform: NodeJS.Platform, candidate: string): string {
|
||||
const normalized = platform === 'win32' ? candidate.replace(/\\/g, '/') : candidate;
|
||||
return platform === 'win32' ? normalized.toLowerCase() : normalized;
|
||||
}
|
||||
|
||||
function isNodeExecutable(platform: NodeJS.Platform, candidate: string): boolean {
|
||||
const normalized = platform === 'win32' ? candidate.toLowerCase() : candidate;
|
||||
const allowedBasenames = platform === 'win32' ? ['node', 'node.exe'] : ['node'];
|
||||
if (allowedBasenames.includes(normalized)) return true;
|
||||
if (!isAbsolutePathForPlatform(platform, candidate)) return false;
|
||||
const basename = platform === 'win32'
|
||||
? pathWin32.basename(candidate).toLowerCase()
|
||||
: pathPosix.basename(candidate);
|
||||
return allowedBasenames.includes(basename);
|
||||
}
|
||||
|
||||
function isClaudeCodeHookCommand(
|
||||
command: string,
|
||||
basename: string,
|
||||
platform: NodeJS.Platform,
|
||||
): boolean {
|
||||
const tokens = tokenizeHookCommand(command);
|
||||
if (!tokens || (tokens.length !== 2 && tokens.length !== 4)) return false;
|
||||
if (!isNodeExecutable(platform, tokens[0])) return false;
|
||||
if (!isAbsolutePathForPlatform(platform, tokens[1])) return false;
|
||||
if (tokens.length === 4) {
|
||||
if (tokens[2] !== '--cli-path' || !isAbsolutePathForPlatform(platform, tokens[3])) return false;
|
||||
}
|
||||
|
||||
const scriptPath = normalizedHookPath(platform, tokens[1]);
|
||||
const expected = `/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`;
|
||||
const normalizedExpected = platform === 'win32' ? expected.toLowerCase() : expected;
|
||||
return scriptPath.endsWith(normalizedExpected);
|
||||
}
|
||||
|
||||
function hasActiveClaudeCodeHooks(settings: unknown, platform: NodeJS.Platform): boolean {
|
||||
const settingsRecord = objectRecord(settings);
|
||||
const hooks = objectRecord(settingsRecord?.hooks);
|
||||
if (!hooks) return false;
|
||||
|
||||
return CLAUDE_CODE_HOOKS.every(([eventName, basename]) => {
|
||||
const groups = hooks[eventName];
|
||||
if (!Array.isArray(groups)) return false;
|
||||
return groups.some((group) => {
|
||||
const groupRecord = objectRecord(group);
|
||||
if (!groupRecord) return false;
|
||||
const entries = groupRecord.hooks;
|
||||
if (!Array.isArray(entries)) return false;
|
||||
return entries.some((entry) => {
|
||||
const entryRecord = objectRecord(entry);
|
||||
const command = entryRecord?.command;
|
||||
return entryRecord?.type === 'command'
|
||||
&& typeof command === 'string'
|
||||
&& isClaudeCodeHookCommand(command, basename, platform);
|
||||
});
|
||||
});
|
||||
});
|
||||
}
|
||||
|
||||
async function activeClaudeCodeHooksHealthy(deps: ResolvedDeps): Promise<boolean> {
|
||||
const settingsPath = joinForPlatform(deps.platform, deps.home, '.claude', 'settings.json');
|
||||
if (!(await deps.exists(settingsPath))) return false;
|
||||
return hasActiveClaudeCodeHooks(await deps.readJson(settingsPath), deps.platform);
|
||||
}
|
||||
|
||||
async function activeHooksHealthy(
|
||||
pointerHealthy: boolean,
|
||||
toolId: string | undefined,
|
||||
deps: ResolvedDeps,
|
||||
): Promise<boolean> {
|
||||
if (!pointerHealthy) return false;
|
||||
return toolId !== 'claude-code' || activeClaudeCodeHooksHealthy(deps);
|
||||
}
|
||||
// ── Platform roots ──────────────────────────────────────────────────
|
||||
|
||||
function nonBlankEnv(deps: ResolvedDeps, name: string): string | null {
|
||||
const value = deps.env[name]?.trim();
|
||||
@@ -499,54 +344,6 @@ function hermesHome(deps: ResolvedDeps): string {
|
||||
: joinForPlatform(deps.platform, deps.home, '.hermes');
|
||||
}
|
||||
|
||||
async function probeHooks(
|
||||
rel: string,
|
||||
deps: ResolvedDeps,
|
||||
hookRoot: ToolManifest['hookRoot'] = 'user-home',
|
||||
toolId?: string,
|
||||
): Promise<HookProbe> {
|
||||
if (!rel) return { hooksInstalled: false, hookPointerPath: null };
|
||||
const root = hookRoot === 'hermes-home' ? hermesHome(deps) : deps.home;
|
||||
const pointerPath = joinForPlatform(deps.platform, root, rel);
|
||||
if (!(await deps.exists(pointerPath))) {
|
||||
return { hooksInstalled: false, hookPointerPath: null };
|
||||
}
|
||||
const parsed = await deps.readJson(pointerPath);
|
||||
if (!parsed || typeof parsed !== 'object') {
|
||||
return { hooksInstalled: false, hookPointerPath: pointerPath };
|
||||
}
|
||||
const pointer = parsed as Record<string, unknown>;
|
||||
// Current installers use settings_backup. Keep the legacy `backup` alias so
|
||||
// older installs remain detectable during upgrade.
|
||||
const backup = Object.hasOwn(pointer, 'settings_backup')
|
||||
? pointer.settings_backup
|
||||
: pointer.backup;
|
||||
const hooksDir = pointer.hooks_dir;
|
||||
const hooksDirValid = hooksDir === undefined || hooksDir === null
|
||||
? true
|
||||
: typeof hooksDir === 'string' && hooksDir.length > 0 && await deps.exists(hooksDir);
|
||||
if (!hooksDirValid) return { hooksInstalled: false, hookPointerPath: pointerPath };
|
||||
if (typeof backup === 'string' && backup.length > 0) {
|
||||
return {
|
||||
hooksInstalled: await activeHooksHealthy(await deps.exists(backup), toolId, deps),
|
||||
hookPointerPath: pointerPath,
|
||||
};
|
||||
}
|
||||
// Create-if-missing adapters correctly have no backup. Their pointer is
|
||||
// healthy only while the config they created still exists.
|
||||
if (backup === null && pointer.created_by_us === true && typeof pointer.config_path === 'string') {
|
||||
return {
|
||||
hooksInstalled: await activeHooksHealthy(
|
||||
await deps.exists(pointer.config_path),
|
||||
toolId,
|
||||
deps,
|
||||
),
|
||||
hookPointerPath: pointerPath,
|
||||
};
|
||||
}
|
||||
return { hooksInstalled: false, hookPointerPath: pointerPath };
|
||||
}
|
||||
|
||||
// ── Per-tool detectors ──────────────────────────────────────────────
|
||||
|
||||
/**
|
||||
@@ -562,9 +359,7 @@ async function detectByPath(
|
||||
id: string,
|
||||
binaryName: string,
|
||||
deps: ResolvedDeps,
|
||||
hookPointer: string,
|
||||
displayName: string,
|
||||
hookRoot?: ToolManifest['hookRoot'],
|
||||
): Promise<DetectedTool> {
|
||||
const base: DetectedTool = {
|
||||
id,
|
||||
@@ -572,16 +367,11 @@ async function detectByPath(
|
||||
installed: false,
|
||||
installedPath: null,
|
||||
version: null,
|
||||
hooksInstalled: false,
|
||||
hookPointerPath: null,
|
||||
};
|
||||
const resolved = await deps.pathFromEnv(binaryName);
|
||||
if (!resolved) return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
|
||||
if (!(await deps.exists(resolved))) {
|
||||
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
|
||||
}
|
||||
if (!resolved) return base;
|
||||
if (!(await deps.exists(resolved))) return base;
|
||||
const versionRaw = await deps.execVersion(resolved, ['--version']);
|
||||
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
|
||||
const blockedWindowsAppsCodex =
|
||||
versionRaw === null && isBlockedWindowsAppsCodexPath(id, deps.platform, resolved);
|
||||
return {
|
||||
@@ -593,7 +383,6 @@ async function detectByPath(
|
||||
diagnostic: blockedWindowsAppsCodex
|
||||
? CODEX_WINDOWS_APPS_DIAGNOSTIC
|
||||
: versionRaw ? undefined : '--version exec failed',
|
||||
...hookProbe,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -609,9 +398,7 @@ function hermesWindowsCandidatePaths(deps: ResolvedDeps): string[] {
|
||||
async function detectHealthyWindowsHermes(
|
||||
binaryName: string,
|
||||
deps: ResolvedDeps,
|
||||
hookPointer: string,
|
||||
displayName: string,
|
||||
hookRoot?: ToolManifest['hookRoot'],
|
||||
): Promise<DetectedTool> {
|
||||
const pathCandidate = await deps.pathFromEnv(binaryName);
|
||||
const candidates = [pathCandidate, ...hermesWindowsCandidatePaths(deps)]
|
||||
@@ -631,7 +418,6 @@ async function detectHealthyWindowsHermes(
|
||||
installed: true,
|
||||
installedPath: candidate,
|
||||
version,
|
||||
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
|
||||
};
|
||||
}
|
||||
}
|
||||
@@ -644,7 +430,6 @@ async function detectHealthyWindowsHermes(
|
||||
version: null,
|
||||
launchable: firstExisting ? false : undefined,
|
||||
diagnostic: firstExisting ? HERMES_WINDOWS_HEALTH_DIAGNOSTIC : undefined,
|
||||
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
|
||||
};
|
||||
}
|
||||
|
||||
@@ -750,9 +535,7 @@ async function detectByCandidates(
|
||||
candidates: string[],
|
||||
deps: ResolvedDeps,
|
||||
withVersion: boolean,
|
||||
hookPointer: string,
|
||||
displayName: string,
|
||||
hookRoot?: ToolManifest['hookRoot'],
|
||||
): Promise<DetectedTool> {
|
||||
const base: DetectedTool = {
|
||||
id,
|
||||
@@ -760,15 +543,12 @@ async function detectByCandidates(
|
||||
installed: false,
|
||||
installedPath: null,
|
||||
version: null,
|
||||
hooksInstalled: false,
|
||||
hookPointerPath: null,
|
||||
};
|
||||
for (const candidate of candidates) {
|
||||
if (await deps.exists(candidate)) {
|
||||
const versionRaw = withVersion
|
||||
? await deps.execVersion(candidate, ['--version'])
|
||||
: null;
|
||||
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
|
||||
return {
|
||||
...base,
|
||||
installed: true,
|
||||
@@ -776,11 +556,10 @@ async function detectByCandidates(
|
||||
version: versionRaw,
|
||||
diagnostic:
|
||||
withVersion && versionRaw === null ? '--version exec failed' : undefined,
|
||||
...hookProbe,
|
||||
};
|
||||
}
|
||||
}
|
||||
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
|
||||
return base;
|
||||
}
|
||||
|
||||
// ── Registry-driven detection ───────────────────────────────────────
|
||||
@@ -802,7 +581,6 @@ function withManifestMetadata(tool: DetectedTool, manifest: ToolManifest): Detec
|
||||
...tool,
|
||||
releaseStatus: manifest.releaseStatus,
|
||||
launchable: tool.launchable ?? manifest.launchable,
|
||||
hookCapable: manifest.hookCapable,
|
||||
builtin: manifest.builtin === true,
|
||||
acceptsInlinePrompt: Boolean(manifest.promptArgTemplate?.length),
|
||||
capabilities: manifest.capabilities,
|
||||
@@ -815,18 +593,12 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
|
||||
if (m.detect.kind === 'path') {
|
||||
if (m.id === 'hermes' && deps.platform === 'win32') {
|
||||
return withManifestMetadata(
|
||||
await detectHealthyWindowsHermes(
|
||||
m.detect.binaryName,
|
||||
deps,
|
||||
m.hookPointer,
|
||||
m.displayName,
|
||||
m.hookRoot,
|
||||
),
|
||||
await detectHealthyWindowsHermes(m.detect.binaryName, deps, m.displayName),
|
||||
m,
|
||||
);
|
||||
}
|
||||
return withManifestMetadata(
|
||||
await detectByPath(m.id, m.detect.binaryName, deps, m.hookPointer, m.displayName, m.hookRoot),
|
||||
await detectByPath(m.id, m.detect.binaryName, deps, m.displayName),
|
||||
m,
|
||||
);
|
||||
}
|
||||
@@ -838,9 +610,7 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
|
||||
candidates,
|
||||
deps,
|
||||
/* withVersion */ false,
|
||||
m.hookPointer,
|
||||
m.displayName,
|
||||
m.hookRoot,
|
||||
),
|
||||
m,
|
||||
);
|
||||
|
||||
@@ -2,16 +2,13 @@
|
||||
* AI-OS Phase 2A — tool launcher module.
|
||||
*
|
||||
* Spawns external AI tools (Claude Code, Cursor, Claude Desktop, …)
|
||||
* with workspace-context injection, and invokes the hive-mind hook
|
||||
* installers (`npx @waggle/hive-mind-hooks-<tool> [install|verify|
|
||||
* uninstall]`).
|
||||
* with workspace-context injection.
|
||||
*
|
||||
* Design parallels `tool-detection.ts`:
|
||||
* - All process spawns go through injectable deps so tests are
|
||||
* hermetic (no actual binaries launched).
|
||||
* - Production defaults use Node `child_process.spawn` (detached
|
||||
* for launch, non-detached for the synchronous installer
|
||||
* commands).
|
||||
* launch, or piped stdio for observed launches).
|
||||
* - Cross-platform: the candidate-path resolution + workspace
|
||||
* env conventions mirror what `tool-detection.ts` reports, so
|
||||
* the launch path comes from the detection result whenever
|
||||
@@ -23,30 +20,18 @@
|
||||
* Spawn the tool detached. Returns the spawned PID + cwd or
|
||||
* an error reason.
|
||||
*
|
||||
* installHooks({id, cliPath?, ...})
|
||||
* Invoke `npx @waggle/hive-mind-hooks-<id> install [--cli-path
|
||||
* <path>]`. Captures stdout/stderr.
|
||||
*
|
||||
* verifyHooks / uninstallHooks
|
||||
* Same as installHooks but the second positional arg is
|
||||
* `verify` / `uninstall`.
|
||||
*
|
||||
* Phase 2A scope:
|
||||
* - Backend module + sidecar routes only. Frontend dock in 2B.
|
||||
* - Launch is registry-validated: all built-ins plus launchable
|
||||
* third-party adapters may be launched when the caller supplies the
|
||||
* runtime registry.
|
||||
* - HOOK install/verify/uninstall is restricted to HOOKS_COHORT:
|
||||
* those tools have hook packages that ship a real bin. Hook actions
|
||||
* therefore route through HOOKS_COHORT, not the launchable registry.
|
||||
*/
|
||||
|
||||
import { spawn, execFile, type ChildProcess } from 'node:child_process';
|
||||
import { spawn, type ChildProcess } from 'node:child_process';
|
||||
import { existsSync } from 'node:fs';
|
||||
import { delimiter, dirname, join, resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { promisify } from 'node:util';
|
||||
import type { ToolId, ToolManifest } from '@waggle/shared';
|
||||
import type { ToolManifest } from '@waggle/shared';
|
||||
import { BUILTIN_TOOL_MANIFESTS } from '@waggle/shared';
|
||||
import {
|
||||
resolveToolCommandInvocation,
|
||||
@@ -58,19 +43,6 @@ import {
|
||||
spawnSidecarOwnedProcess,
|
||||
} from './sidecar-owned-process.js';
|
||||
|
||||
const execFileAsync = promisify(execFile);
|
||||
|
||||
/**
|
||||
* Tools whose hive-mind integration package ships a real `bin` and can
|
||||
* therefore be installed/verified/uninstalled by the bundled runtime. All
|
||||
* seven built-ins qualify: Claude Desktop registers the waggle-memory MCP
|
||||
* bridge, while the other six install lifecycle hooks. Hook code paths gate on
|
||||
* THIS cohort, not LAUNCH_COHORT, so the UI never offers a hook action that the
|
||||
* runtime cannot fulfil.
|
||||
*/
|
||||
export const HOOKS_COHORT: readonly ToolId[] =
|
||||
BUILTIN_TOOL_MANIFESTS.filter((m) => m.hookCapable).map((m) => m.id as ToolId);
|
||||
|
||||
// ── Injectable deps ─────────────────────────────────────────────────
|
||||
|
||||
/** Minimal, test-injectable view of a live observed process. */
|
||||
@@ -109,15 +81,6 @@ export interface ToolLauncherDeps {
|
||||
args: string[],
|
||||
options: { cwd?: string; env?: NodeJS.ProcessEnv },
|
||||
) => { pid: number | null; error?: string; handle?: ObservedHandle };
|
||||
/**
|
||||
* Synchronous-style exec with captured stdout/stderr. Production
|
||||
* uses promisified execFile with a timeout. Returns null on error.
|
||||
*/
|
||||
execCapture?: (
|
||||
binary: string,
|
||||
args: string[],
|
||||
options?: { timeoutMs?: number; env?: NodeJS.ProcessEnv },
|
||||
) => Promise<{ stdout: string; stderr: string; code: number } | null>;
|
||||
}
|
||||
|
||||
// ── Default deps ────────────────────────────────────────────────────
|
||||
@@ -208,42 +171,11 @@ export function resolveSpawnInvocation(
|
||||
return resolveToolCommandInvocation(binary, args, platform);
|
||||
}
|
||||
|
||||
async function defaultExecCapture(
|
||||
binary: string,
|
||||
args: string[],
|
||||
options?: { timeoutMs?: number; env?: NodeJS.ProcessEnv },
|
||||
): Promise<{ stdout: string; stderr: string; code: number } | null> {
|
||||
try {
|
||||
const invocation = resolveToolCommandInvocation(binary, args);
|
||||
const { stdout, stderr } = await execFileAsync(invocation.binary, invocation.args, {
|
||||
timeout: options?.timeoutMs ?? 30000,
|
||||
env: options?.env,
|
||||
shell: false,
|
||||
windowsVerbatimArguments: invocation.windowsVerbatimArguments === true,
|
||||
maxBuffer: 4 * 1024 * 1024,
|
||||
});
|
||||
return { stdout, stderr, code: 0 };
|
||||
} catch (err: unknown) {
|
||||
if (err && typeof err === 'object' && 'code' in err) {
|
||||
const e = err as { stdout?: string; stderr?: string; code?: number | string };
|
||||
const code = typeof e.code === 'number' ? e.code : 1;
|
||||
return {
|
||||
stdout: e.stdout ?? '',
|
||||
stderr:
|
||||
e.stderr ?? (err instanceof Error ? err.message : String(err)),
|
||||
code,
|
||||
};
|
||||
}
|
||||
return null;
|
||||
}
|
||||
}
|
||||
|
||||
interface ResolvedDeps {
|
||||
platform: NodeJS.Platform;
|
||||
baseEnv: NodeJS.ProcessEnv;
|
||||
spawnDetached: NonNullable<ToolLauncherDeps['spawnDetached']>;
|
||||
spawnObserved: NonNullable<ToolLauncherDeps['spawnObserved']>;
|
||||
execCapture: NonNullable<ToolLauncherDeps['execCapture']>;
|
||||
}
|
||||
|
||||
function resolveDeps(opts: ToolLauncherDeps): ResolvedDeps {
|
||||
@@ -252,7 +184,6 @@ function resolveDeps(opts: ToolLauncherDeps): ResolvedDeps {
|
||||
baseEnv: opts.baseEnv ?? process.env,
|
||||
spawnDetached: opts.spawnDetached ?? defaultSpawnDetached,
|
||||
spawnObserved: opts.spawnObserved ?? defaultSpawnObserved,
|
||||
execCapture: opts.execCapture ?? defaultExecCapture,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -418,40 +349,7 @@ export function launchTool(opts: LaunchOptions): LaunchResult {
|
||||
};
|
||||
}
|
||||
|
||||
// ── Hook installer surface ──────────────────────────────────────────
|
||||
|
||||
export type HookAction = 'install' | 'verify' | 'uninstall';
|
||||
|
||||
export interface HookCommandOptions {
|
||||
/** The tool whose hooks to manage. */
|
||||
id: ToolId;
|
||||
/** install / verify / uninstall. */
|
||||
action: HookAction;
|
||||
/** Waggle data root injected into hook memory commands. */
|
||||
dataDir?: string;
|
||||
/** Server-resolved runtime override for tests/embedded hosts. */
|
||||
runtime?: HookRuntimePaths;
|
||||
/** Test deps overrides. */
|
||||
deps?: ToolLauncherDeps;
|
||||
}
|
||||
|
||||
export interface HookCommandResult {
|
||||
ok: boolean;
|
||||
action: HookAction;
|
||||
packageName: string;
|
||||
stdout: string;
|
||||
stderr: string;
|
||||
/** Process exit code (0 = success). */
|
||||
code: number;
|
||||
error?: string;
|
||||
errorCode?: 'hook_runtime_missing';
|
||||
}
|
||||
|
||||
export interface HookRuntimePaths {
|
||||
nodePath: string;
|
||||
cliEntry: string;
|
||||
hookEntry: string;
|
||||
}
|
||||
// ── Packaged collaboration CLI ──────────────────────────────────────
|
||||
|
||||
export interface WaggleRuntimePaths {
|
||||
nodePath: string;
|
||||
@@ -464,42 +362,6 @@ interface RuntimeResolveDeps {
|
||||
fileExists?: (path: string) => boolean;
|
||||
}
|
||||
|
||||
const HOOK_BIN_BY_TOOL: Partial<Record<ToolId, string>> = {
|
||||
'claude-code': 'dist/bin/claude-code-hooks-cli.js',
|
||||
'claude-desktop': 'dist/bin/claude-desktop-hooks.js',
|
||||
codex: 'dist/bin/codex-hooks.js',
|
||||
'codex-desktop': 'dist/bin/codex-desktop-hooks.js',
|
||||
cursor: 'dist/bin/cursor-hooks.js',
|
||||
hermes: 'dist/bin/hermes-hooks.js',
|
||||
openclaw: 'dist/bin/openclaw-hooks.js',
|
||||
};
|
||||
|
||||
/**
|
||||
* Map ToolId → npm package name of the hive-mind hook installer.
|
||||
* Exported so callers (and tests) can reason about the same string
|
||||
* the installer uses.
|
||||
*/
|
||||
export function hookPackageFor(id: ToolId): string {
|
||||
return `@waggle/hive-mind-hooks-${id}`;
|
||||
}
|
||||
|
||||
export function resolveHookRuntime(
|
||||
id: ToolId,
|
||||
deps: RuntimeResolveDeps = {},
|
||||
): HookRuntimePaths | undefined {
|
||||
const fileExists = deps.fileExists ?? existsSync;
|
||||
const hookRelative = HOOK_BIN_BY_TOOL[id];
|
||||
if (!hookRelative) return undefined;
|
||||
for (const root of runtimeNodeModulesRoots(deps.nodeModulesRoots)) {
|
||||
const cliEntry = join(root, '@waggle', 'hive-mind-cli', 'dist', 'index.js');
|
||||
const hookEntry = join(root, '@waggle', `hive-mind-hooks-${id}`, ...hookRelative.split('/'));
|
||||
if (fileExists(cliEntry) && fileExists(hookEntry)) {
|
||||
return { nodePath: deps.nodePath ?? process.execPath, cliEntry, hookEntry };
|
||||
}
|
||||
}
|
||||
return undefined;
|
||||
}
|
||||
|
||||
export function resolveWaggleRuntime(deps: RuntimeResolveDeps = {}): WaggleRuntimePaths | undefined {
|
||||
const fileExists = deps.fileExists ?? existsSync;
|
||||
for (const root of runtimeNodeModulesRoots(deps.nodeModulesRoots)) {
|
||||
@@ -518,73 +380,3 @@ function runtimeNodeModulesRoots(explicit?: string[]): string[] {
|
||||
];
|
||||
return [...new Set(roots.map((candidate) => resolve(candidate)))];
|
||||
}
|
||||
|
||||
/**
|
||||
* Run `npx @waggle/hive-mind-hooks-<id> <install|verify|uninstall>`.
|
||||
*
|
||||
* Captures stdout/stderr/exitCode. Failure returns ok=false but the
|
||||
* full output is still in the result so the UI can show it to the
|
||||
* user (the hook installers emit human-readable progress).
|
||||
*
|
||||
* On Windows, callers SHOULD provide `cliPath` for `install` —
|
||||
* see the claude-code hook README for why.
|
||||
*/
|
||||
export async function runHookCommand(
|
||||
opts: HookCommandOptions,
|
||||
): Promise<HookCommandResult> {
|
||||
if (!HOOKS_COHORT.includes(opts.id)) {
|
||||
return {
|
||||
ok: false,
|
||||
action: opts.action,
|
||||
packageName: hookPackageFor(opts.id),
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
code: -1,
|
||||
error: `Hook management for '${opts.id}' is not supported — no built-in hook runtime is registered for this tool.`,
|
||||
};
|
||||
}
|
||||
const deps = resolveDeps(opts.deps ?? {});
|
||||
const runtime = opts.runtime ?? resolveHookRuntime(opts.id);
|
||||
if (!runtime) {
|
||||
return {
|
||||
ok: false,
|
||||
action: opts.action,
|
||||
packageName: hookPackageFor(opts.id),
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
code: -1,
|
||||
errorCode: 'hook_runtime_missing',
|
||||
error: 'The packaged hook runtime is missing. Reinstall Waggle or run the hook-runtime staging step.',
|
||||
};
|
||||
}
|
||||
const args = [runtime.hookEntry, opts.action];
|
||||
if (opts.action === 'install' || (opts.action === 'verify' && opts.id === 'openclaw')) {
|
||||
args.push('--cli-path', runtime.cliEntry);
|
||||
}
|
||||
const result = await deps.execCapture(runtime.nodePath, args, {
|
||||
timeoutMs: 60000,
|
||||
env: buildExternalProcessEnv(deps.baseEnv, {
|
||||
WAGGLE_HOOK_NODE_PATH: runtime.nodePath,
|
||||
...(opts.dataDir ? { HIVE_MIND_DATA_DIR: opts.dataDir } : {}),
|
||||
}, deps.platform),
|
||||
});
|
||||
if (!result) {
|
||||
return {
|
||||
ok: false,
|
||||
action: opts.action,
|
||||
packageName: hookPackageFor(opts.id),
|
||||
stdout: '',
|
||||
stderr: '',
|
||||
code: -1,
|
||||
error: 'exec failed (binary not found or unknown error)',
|
||||
};
|
||||
}
|
||||
return {
|
||||
ok: result.code === 0,
|
||||
action: opts.action,
|
||||
packageName: hookPackageFor(opts.id),
|
||||
stdout: result.stdout,
|
||||
stderr: result.stderr,
|
||||
code: result.code,
|
||||
};
|
||||
}
|
||||
|
||||
@@ -16,8 +16,6 @@ import type {
|
||||
ToolTaskSpec,
|
||||
} from '@waggle/shared';
|
||||
|
||||
// Allows `/ \ . _ -` for relative pointer paths; rejects everything else.
|
||||
const PATH_SAFE = /^[A-Za-z0-9._/\\-]+$/;
|
||||
// No path separators — for ids and binary names (PATH lookup).
|
||||
const NAME_SAFE = /^[A-Za-z0-9._-]+$/;
|
||||
const TASK_PLACEHOLDERS = new Set([
|
||||
@@ -89,14 +87,12 @@ function validate(raw: unknown): ToolManifest | null {
|
||||
if (!raw || typeof raw !== 'object') return null;
|
||||
const o = raw as Record<string, unknown>;
|
||||
const allowedKeys = new Set([
|
||||
'id', 'displayName', 'launchable', 'hookCapable', 'hookPointer', 'detect',
|
||||
'promptArgTemplate', 'task',
|
||||
'id', 'displayName', 'launchable', 'detect', 'promptArgTemplate', 'task',
|
||||
]);
|
||||
if (Object.keys(o).some((key) => !allowedKeys.has(key))) return null;
|
||||
if (!safeStr(o.id, 64, NAME_SAFE)) return null;
|
||||
if (typeof o.displayName !== 'string' || o.displayName.length < 1 || o.displayName.length > 80) return null;
|
||||
if (typeof o.launchable !== 'boolean' || typeof o.hookCapable !== 'boolean') return null;
|
||||
if (!safeStr(o.hookPointer, 256, PATH_SAFE)) return null;
|
||||
if (typeof o.launchable !== 'boolean') return null;
|
||||
const d = o.detect as Record<string, unknown> | undefined;
|
||||
// Third-party adapters may ONLY declare PATH detection (candidates = code-only).
|
||||
if (!d || d.kind !== 'path' || !safeStr(d.binaryName, 128, NAME_SAFE)) return null;
|
||||
@@ -115,8 +111,6 @@ function validate(raw: unknown): ToolManifest | null {
|
||||
id: o.id as string,
|
||||
displayName: o.displayName,
|
||||
launchable: o.launchable,
|
||||
hookCapable: o.hookCapable,
|
||||
hookPointer: o.hookPointer as string,
|
||||
detect: { kind: 'path', binaryName: d.binaryName as string },
|
||||
...(promptArgTemplate ? { promptArgTemplate } : {}),
|
||||
capabilities: {
|
||||
|
||||
@@ -767,8 +767,8 @@ describe('external adapter safety', () => {
|
||||
|
||||
it('loads only data-only generic task specs with known placeholders', () => {
|
||||
const base = {
|
||||
id: 'safe-cli', displayName: 'Safe', launchable: true, hookCapable: false,
|
||||
hookPointer: '.safe/hm.json', detect: { kind: 'path', binaryName: 'safe' },
|
||||
id: 'safe-cli', displayName: 'Safe', launchable: true,
|
||||
detect: { kind: 'path', binaryName: 'safe' },
|
||||
};
|
||||
const deps = (value: unknown) => ({
|
||||
dir: '/fake', readDir: () => ['adapter.json'], readFile: () => JSON.stringify(value),
|
||||
|
||||
@@ -1,134 +0,0 @@
|
||||
/**
|
||||
* AI-OS Phase 4 — HOOKS_COHORT regression (R8-001 / R8-002 / R8-003).
|
||||
*
|
||||
* Bug (R8-001): hook install/verify/uninstall was gated on LAUNCH_COHORT,
|
||||
* but at the time only @waggle/hive-mind-hooks-claude-code
|
||||
* shipped a `bin`; the other hook packages were Wave 2/3 `export {}` stubs
|
||||
* with no bin, so `npx @waggle/hive-mind-hooks-<id>` ALWAYS failed for the
|
||||
* user. HOOKS_COHORT fixed this by gating hook actions on the tools whose
|
||||
* package actually ships a bin and is release-supported. Roadmap packages may
|
||||
* remain installed in the repository without being exposed to users.
|
||||
*
|
||||
* The existing tool-launcher tests mock execCapture and only assert the
|
||||
* npx command SHAPE, so the binless-stub failure was invisible. These
|
||||
* are STATIC tests that:
|
||||
* 1. ground HOOKS_COHORT against the real on-disk hook packages
|
||||
* (a tool is hook-capable iff its package.json declares a bin),
|
||||
* 2. prove runHookCommand REFUSES unsupported tools without invoking exec,
|
||||
* 3. prove the real targets still route through.
|
||||
*/
|
||||
|
||||
import { describe, it, expect } from 'vitest';
|
||||
import { existsSync, readFileSync } from 'node:fs';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { dirname, join } from 'node:path';
|
||||
import {
|
||||
runHookCommand,
|
||||
HOOKS_COHORT,
|
||||
type HookRuntimePaths,
|
||||
type ToolLauncherDeps,
|
||||
} from '../src/tool-launcher.js';
|
||||
import { BUILTIN_TOOL_MANIFESTS, LAUNCH_COHORT, type ToolId } from '@waggle/shared';
|
||||
|
||||
// packages/agent/tests → packages/
|
||||
const PACKAGES_DIR = join(dirname(fileURLToPath(import.meta.url)), '..', '..');
|
||||
|
||||
function hookPackageHasBin(id: ToolId): boolean {
|
||||
const pkgPath = join(PACKAGES_DIR, `hive-mind-hooks-${id}`, 'package.json');
|
||||
if (!existsSync(pkgPath)) return false;
|
||||
const pkg = JSON.parse(readFileSync(pkgPath, 'utf8')) as { bin?: unknown };
|
||||
return pkg.bin != null && Object.keys(pkg.bin as object).length > 0;
|
||||
}
|
||||
|
||||
function runtimeFor(id: ToolId): HookRuntimePaths {
|
||||
return {
|
||||
nodePath: '/resources/node',
|
||||
cliEntry: '/resources/node_modules/@waggle/hive-mind-cli/dist/index.js',
|
||||
hookEntry: `/resources/node_modules/@waggle/hive-mind-hooks-${id}/dist/bin/hooks.js`,
|
||||
};
|
||||
}
|
||||
|
||||
describe('HOOKS_COHORT grounding (R8-001)', () => {
|
||||
it('contains ONLY tools whose hook package ships a real bin', () => {
|
||||
for (const id of HOOKS_COHORT) {
|
||||
expect(
|
||||
hookPackageHasBin(id),
|
||||
`${id} is in HOOKS_COHORT but its hook package has no bin`,
|
||||
).toBe(true);
|
||||
}
|
||||
});
|
||||
|
||||
it('contains every release-supported tool that ships a real hook bin', () => {
|
||||
const realTargets = BUILTIN_TOOL_MANIFESTS
|
||||
.filter((manifest) => manifest.releaseStatus !== 'roadmap')
|
||||
.map((manifest) => manifest.id as ToolId)
|
||||
.filter((id) => hookPackageHasBin(id));
|
||||
expect([...HOOKS_COHORT].sort()).toEqual([...realTargets].sort());
|
||||
});
|
||||
|
||||
it('matches the current release-supported real-bin cohort (snapshot tripwire)', () => {
|
||||
expect([...HOOKS_COHORT].sort()).toEqual(['claude-code', 'claude-desktop', 'codex', 'codex-desktop', 'hermes']);
|
||||
});
|
||||
|
||||
it('keeps roadmap hook packages on disk but outside the supported cohort', () => {
|
||||
for (const id of ['cursor', 'openclaw'] as const) {
|
||||
expect(hookPackageHasBin(id)).toBe(true);
|
||||
expect(HOOKS_COHORT).not.toContain(id);
|
||||
}
|
||||
});
|
||||
|
||||
it('is a subset of LAUNCH_COHORT (all hook targets are launchable)', () => {
|
||||
for (const id of HOOKS_COHORT) {
|
||||
expect(LAUNCH_COHORT).toContain(id);
|
||||
}
|
||||
expect(HOOKS_COHORT.length).toBeLessThanOrEqual(LAUNCH_COHORT.length);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runHookCommand refuses unsupported tools (R8-002)', () => {
|
||||
it('does not invoke exec for an unsupported tool id', async () => {
|
||||
const fakeId = 'not-a-real-tool' as ToolId;
|
||||
let invoked = false;
|
||||
const execCapture: NonNullable<ToolLauncherDeps['execCapture']> = async () => {
|
||||
invoked = true;
|
||||
return { stdout: 'ok', stderr: '', code: 0 };
|
||||
};
|
||||
|
||||
const result = await runHookCommand({
|
||||
id: fakeId,
|
||||
action: 'install',
|
||||
deps: { execCapture },
|
||||
});
|
||||
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).toContain('not supported');
|
||||
expect(invoked).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describe('runHookCommand still routes the real target (regression guard)', () => {
|
||||
it('invokes the packaged bin for claude-code install', async () => {
|
||||
const calls: string[][] = [];
|
||||
const execCapture: NonNullable<ToolLauncherDeps['execCapture']> = async (
|
||||
_binary,
|
||||
args,
|
||||
) => {
|
||||
calls.push(args);
|
||||
return { stdout: 'Done.', stderr: '', code: 0 };
|
||||
};
|
||||
const result = await runHookCommand({
|
||||
id: 'claude-code',
|
||||
action: 'install',
|
||||
runtime: runtimeFor('claude-code'),
|
||||
deps: { execCapture },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls).toHaveLength(1);
|
||||
expect(calls[0]).toEqual([
|
||||
runtimeFor('claude-code').hookEntry,
|
||||
'install',
|
||||
'--cli-path',
|
||||
runtimeFor('claude-code').cliEntry,
|
||||
]);
|
||||
});
|
||||
});
|
||||
@@ -24,7 +24,7 @@ type DetectOpts = ToolDetectionDeps & {
|
||||
|
||||
/**
|
||||
* Build a deps object that defaults to "nothing exists anywhere".
|
||||
* Tests selectively override `exists` / `execVersion` / `readJson` to
|
||||
* Tests selectively override `exists` / `execVersion` to
|
||||
* simulate specific tools being installed.
|
||||
*/
|
||||
function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts {
|
||||
@@ -32,10 +32,9 @@ function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts {
|
||||
platform: 'win32',
|
||||
home: 'C:\\Users\\test',
|
||||
env: {},
|
||||
cwd: 'D:\\projects\\waggle-os',
|
||||
cwd: 'C:\\work\\waggle',
|
||||
exists: async () => false,
|
||||
execVersion: async () => null,
|
||||
readJson: async () => null,
|
||||
pathFromEnv: () => null,
|
||||
windowsAppExecutables: () => ({}),
|
||||
// Hermetic: no third-party adapters unless a test injects them.
|
||||
@@ -44,83 +43,6 @@ function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts {
|
||||
};
|
||||
}
|
||||
|
||||
type ClaudeHookCommandBuilder = (basename: string, scriptPath: string) => string;
|
||||
|
||||
function activeClaudeHookSettings(
|
||||
commandBuilder: ClaudeHookCommandBuilder = (_basename, scriptPath) => `node "${scriptPath}"`,
|
||||
) {
|
||||
const group = (basename: string) => [{
|
||||
_hiveMindShim: '@hive-mind/claude-code-hooks',
|
||||
hooks: [{
|
||||
type: 'command',
|
||||
command: commandBuilder(
|
||||
basename,
|
||||
`/opt/waggle/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`,
|
||||
),
|
||||
}],
|
||||
}];
|
||||
return {
|
||||
hooks: {
|
||||
SessionStart: group('session-start'),
|
||||
UserPromptSubmit: group('user-prompt-submit'),
|
||||
Stop: group('stop'),
|
||||
PreCompact: group('pre-compact'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function markerStrippedClaudeHookSettings(
|
||||
packageName = 'hive-mind-hooks-claude-code',
|
||||
commandBuilder: ClaudeHookCommandBuilder = (_basename, scriptPath) => `node "${scriptPath}"`,
|
||||
entryType = 'command',
|
||||
) {
|
||||
const group = (basename: string) => [{
|
||||
hooks: [{
|
||||
type: entryType,
|
||||
command: commandBuilder(
|
||||
basename,
|
||||
`D:\\Waggle\\packages\\${packageName}\\dist\\hooks\\${basename}.js`,
|
||||
),
|
||||
}],
|
||||
}];
|
||||
return {
|
||||
hooks: {
|
||||
SessionStart: group('session-start'),
|
||||
UserPromptSubmit: group('user-prompt-submit'),
|
||||
Stop: group('stop'),
|
||||
PreCompact: group('pre-compact'),
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
async function detectClaudeHookStatus(
|
||||
settingsValue: unknown,
|
||||
platform: NodeJS.Platform = 'win32',
|
||||
): Promise<boolean | undefined> {
|
||||
const windows = platform === 'win32';
|
||||
const home = windows ? 'C:\\Users\\test' : '/Users/test';
|
||||
const installed = windows ? `${home}\\AppData\\Roaming\\npm\\claude.cmd` : '/usr/local/bin/claude';
|
||||
const pointer = windows ? `${home}\\.claude\\hive-mind-install.json` : `${home}/.claude/hive-mind-install.json`;
|
||||
const backup = windows
|
||||
? `${home}\\.claude\\settings.json.hive-mind-backup.X`
|
||||
: `${home}/.claude/settings.json.hive-mind-backup.X`;
|
||||
const settings = windows ? `${home}\\.claude\\settings.json` : `${home}/.claude/settings.json`;
|
||||
const existsSet = new Set([installed, pointer, backup, settings]);
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
platform,
|
||||
home,
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 2.1.214',
|
||||
readJson: async (candidate) => {
|
||||
if (candidate === pointer) return { settings_backup: backup };
|
||||
if (candidate === settings) return settingsValue;
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
return result.tools.find((tool) => tool.id === 'claude-code')?.hooksInstalled;
|
||||
}
|
||||
|
||||
describe('detectInstalledTools', () => {
|
||||
it('does not expose ambient secrets to the production version probe', async () => {
|
||||
const previousOpenAi = process.env.OPENAI_API_KEY;
|
||||
@@ -165,8 +87,6 @@ describe('detectInstalledTools', () => {
|
||||
id: 'foo-cli',
|
||||
displayName: 'Foo',
|
||||
launchable: true,
|
||||
hookCapable: false,
|
||||
hookPointer: '.foo/hm.json',
|
||||
detect: { kind: 'path', binaryName: 'foo' },
|
||||
promptArgTemplate: ['--print', '{prompt}'],
|
||||
task: {
|
||||
@@ -188,7 +108,6 @@ describe('detectInstalledTools', () => {
|
||||
expect(foo?.installed).toBe(true);
|
||||
expect(foo?.installedPath).toBe('/usr/bin/foo');
|
||||
expect(foo?.launchable).toBe(true);
|
||||
expect(foo?.hookCapable).toBe(false);
|
||||
expect(foo?.builtin).toBe(false);
|
||||
expect(foo?.acceptsInlinePrompt).toBe(true);
|
||||
expect(foo?.capabilities).toEqual({
|
||||
@@ -225,12 +144,10 @@ describe('detectInstalledTools', () => {
|
||||
expect(cursor).toMatchObject({
|
||||
releaseStatus: 'roadmap',
|
||||
launchable: false,
|
||||
hookCapable: false,
|
||||
});
|
||||
expect(openclaw).toMatchObject({
|
||||
releaseStatus: 'roadmap',
|
||||
launchable: false,
|
||||
hookCapable: false,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -247,7 +164,6 @@ describe('detectInstalledTools', () => {
|
||||
expect(t.installed).toBe(false);
|
||||
expect(t.installedPath).toBeNull();
|
||||
expect(t.version).toBeNull();
|
||||
expect(t.hooksInstalled).toBe(false);
|
||||
}
|
||||
});
|
||||
|
||||
@@ -295,238 +211,6 @@ describe('claude-code detector', () => {
|
||||
expect(t.version).toBe('1.2.3');
|
||||
});
|
||||
|
||||
it('reports hooksInstalled=true when the pointer, backup, and active Claude hooks are healthy', async () => {
|
||||
const installed = '/usr/local/bin/claude';
|
||||
const home = '/Users/test';
|
||||
const pointer = '/Users/test/.claude/hive-mind-install.json';
|
||||
const backup = '/Users/test/.claude/settings.json.hive-mind-backup.X';
|
||||
const settings = '/Users/test/.claude/settings.json';
|
||||
const existsSet = new Set([installed, pointer, backup, settings]);
|
||||
|
||||
const result = await detectInstalledTools(
|
||||
makeDeps({
|
||||
platform: 'darwin',
|
||||
home,
|
||||
exists: async (p) => existsSet.has(p),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 1.2.3',
|
||||
readJson: async (p) => {
|
||||
if (p === pointer) return { settings_backup: backup };
|
||||
if (p === settings) return activeClaudeHookSettings();
|
||||
return null;
|
||||
},
|
||||
}),
|
||||
);
|
||||
const t = result.tools.find((x) => x.id === 'claude-code')!;
|
||||
expect(t.hooksInstalled).toBe(true);
|
||||
expect(t.hookPointerPath).toBe(pointer);
|
||||
});
|
||||
|
||||
it('keeps hooksInstalled=true after Claude strips private markers from Waggle hook groups', async () => {
|
||||
const installed = 'C:\\Users\\test\\AppData\\Roaming\\npm\\claude.cmd';
|
||||
const pointer = 'C:\\Users\\test\\.claude\\hive-mind-install.json';
|
||||
const backup = 'C:\\Users\\test\\.claude\\settings.json.hive-mind-backup.X';
|
||||
const settings = 'C:\\Users\\test\\.claude\\settings.json';
|
||||
const existsSet = new Set([installed, pointer, backup, settings]);
|
||||
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 2.1.214',
|
||||
readJson: async (candidate) => {
|
||||
if (candidate === pointer) return { settings_backup: backup };
|
||||
if (candidate === settings) return markerStrippedClaudeHookSettings();
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
expect(result.tools.find((tool) => tool.id === 'claude-code')?.hooksInstalled).toBe(true);
|
||||
});
|
||||
|
||||
it.each([
|
||||
[
|
||||
'a pinned mixed-case Node executable, hook path, and cli path',
|
||||
(_basename: string, scriptPath: string) => {
|
||||
const spacedPath = scriptPath.replace('D:\\Waggle', 'D:\\Program Files\\Waggle').toUpperCase();
|
||||
return `"C:\\Program Files\\nodejs\\node.EXE" "${spacedPath}" --cli-path "D:\\Program Files\\Hive Mind\\cli.JS"`;
|
||||
},
|
||||
],
|
||||
[
|
||||
'safe unquoted absolute paths without spaces',
|
||||
(_basename: string, scriptPath: string) => `C:\\Node\\node.exe ${scriptPath} --cli-path D:\\HiveMind\\cli.js`,
|
||||
],
|
||||
])('accepts marker-stripped hooks using %s', async (_label, commandBuilder) => {
|
||||
expect(await detectClaudeHookStatus(
|
||||
markerStrippedClaudeHookSettings('hive-mind-hooks-claude-code', commandBuilder),
|
||||
)).toBe(true);
|
||||
});
|
||||
|
||||
it('accepts a canonical marker-stripped POSIX command', async () => {
|
||||
const settings = markerStrippedClaudeHookSettings(
|
||||
'hive-mind-hooks-claude-code',
|
||||
(basename) =>
|
||||
`"/usr/local/bin/node" "/opt/waggle/hive-mind-hooks-claude-code/dist/hooks/${basename}.js" --cli-path "/opt/waggle/hive-mind-cli.js"`,
|
||||
);
|
||||
expect(await detectClaudeHookStatus(settings, 'linux')).toBe(true);
|
||||
});
|
||||
|
||||
it('finds the canonical command entry when Claude preserves another entry first', async () => {
|
||||
const settings = markerStrippedClaudeHookSettings();
|
||||
for (const groups of Object.values(settings.hooks)) {
|
||||
groups[0].hooks.unshift({ type: 'prompt', command: 'not executable' });
|
||||
}
|
||||
expect(await detectClaudeHookStatus(settings)).toBe(true);
|
||||
});
|
||||
|
||||
it.each<Array<[string, ClaudeHookCommandBuilder]>>([
|
||||
['echo text', (_basename, scriptPath) => `echo "${scriptPath}"`],
|
||||
['a Node wrapper comment', (_basename, scriptPath) => `node "D:\\wrapper.js" --comment "${scriptPath}"`],
|
||||
['a cmd wrapper', (_basename, scriptPath) => `cmd /c node "${scriptPath}"`],
|
||||
['a PowerShell wrapper', (_basename, scriptPath) => `powershell -Command node "${scriptPath}"`],
|
||||
['node -e text', (_basename, scriptPath) => `node -e "${scriptPath}"`],
|
||||
['a backup extension', (_basename, scriptPath) => `node "${scriptPath}.bak"`],
|
||||
['the wrong hook basename', (_basename, scriptPath) => `node "${scriptPath.replace(/[^\\]+\.js$/, 'other.js')}"`],
|
||||
['an unknown argument', (_basename, scriptPath) => `node "${scriptPath}" --verbose`],
|
||||
['a shell AND chain', (_basename, scriptPath) => `node "${scriptPath}" && echo done`],
|
||||
['a shell semicolon chain', (_basename, scriptPath) => `node "${scriptPath}"; echo done`],
|
||||
['a shell pipe', (_basename, scriptPath) => `node "${scriptPath}" | tee out`],
|
||||
['a shell redirect', (_basename, scriptPath) => `node "${scriptPath}" > out`],
|
||||
['a newline command', (_basename, scriptPath) => `node "${scriptPath}"\necho done`],
|
||||
['an unmatched quote', (_basename, scriptPath) => `node "${scriptPath}`],
|
||||
[
|
||||
'an unquoted path with spaces',
|
||||
(_basename, scriptPath) => `node ${scriptPath.replace('D:\\Waggle', 'D:\\Program Files\\Waggle')}`,
|
||||
],
|
||||
])('rejects marker-stripped hook commands containing %s', async (_label, commandBuilder) => {
|
||||
expect(await detectClaudeHookStatus(
|
||||
markerStrippedClaudeHookSettings('hive-mind-hooks-claude-code', commandBuilder),
|
||||
)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects a canonical-looking entry whose type is not command', async () => {
|
||||
expect(await detectClaudeHookStatus(
|
||||
markerStrippedClaudeHookSettings(
|
||||
'hive-mind-hooks-claude-code',
|
||||
(_basename, scriptPath) => `node "${scriptPath}"`,
|
||||
'prompt',
|
||||
),
|
||||
)).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects an arbitrary same-basename script even when the Waggle marker is present', async () => {
|
||||
const settings = activeClaudeHookSettings(
|
||||
(basename) => `node "C:\\malware\\${basename}.js"`,
|
||||
);
|
||||
expect(await detectClaudeHookStatus(settings)).toBe(false);
|
||||
});
|
||||
|
||||
it.each<Array<[string, ClaudeHookCommandBuilder]>>([
|
||||
[
|
||||
'quoted command substitution',
|
||||
(basename) => `node "/tmp/$(echo owned)/hive-mind-hooks-claude-code/dist/hooks/${basename}.js"`,
|
||||
],
|
||||
[
|
||||
'quoted backtick substitution',
|
||||
(basename) => `node "/tmp/` + '`echo owned`' + `/hive-mind-hooks-claude-code/dist/hooks/${basename}.js"`,
|
||||
],
|
||||
[
|
||||
'unquoted command substitution',
|
||||
(basename) => `node /tmp/$(echo)/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`,
|
||||
],
|
||||
[
|
||||
'an unquoted glob',
|
||||
(basename) => `node /opt/*/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`,
|
||||
],
|
||||
])('rejects POSIX hook paths containing %s', async (_label, commandBuilder) => {
|
||||
const settings = markerStrippedClaudeHookSettings(
|
||||
'hive-mind-hooks-claude-code',
|
||||
commandBuilder,
|
||||
);
|
||||
expect(await detectClaudeHookStatus(settings, 'linux')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects node.exe as a POSIX hook executable', async () => {
|
||||
const settings = markerStrippedClaudeHookSettings(
|
||||
'hive-mind-hooks-claude-code',
|
||||
(basename) =>
|
||||
`/usr/local/bin/node.exe /opt/waggle/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`,
|
||||
);
|
||||
expect(await detectClaudeHookStatus(settings, 'linux')).toBe(false);
|
||||
});
|
||||
|
||||
it('rejects marker-stripped hook commands from a lookalike package', async () => {
|
||||
const installed = 'C:\\Users\\test\\AppData\\Roaming\\npm\\claude.cmd';
|
||||
const pointer = 'C:\\Users\\test\\.claude\\hive-mind-install.json';
|
||||
const backup = 'C:\\Users\\test\\.claude\\settings.json.hive-mind-backup.X';
|
||||
const settings = 'C:\\Users\\test\\.claude\\settings.json';
|
||||
const existsSet = new Set([installed, pointer, backup, settings]);
|
||||
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 2.1.214',
|
||||
readJson: async (candidate) => {
|
||||
if (candidate === pointer) return { settings_backup: backup };
|
||||
if (candidate === settings) {
|
||||
return markerStrippedClaudeHookSettings('hive-mind-hooks-claude-code-copy');
|
||||
}
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
expect(result.tools.find((tool) => tool.id === 'claude-code')?.hooksInstalled).toBe(false);
|
||||
});
|
||||
|
||||
it('reports hooksInstalled=false when a stale pointer survives but active Claude hooks are gone', async () => {
|
||||
const installed = '/usr/local/bin/claude';
|
||||
const pointer = '/Users/test/.claude/hive-mind-install.json';
|
||||
const backup = '/Users/test/.claude/settings.json.hive-mind-backup.X';
|
||||
const settings = '/Users/test/.claude/settings.json';
|
||||
const existsSet = new Set([installed, pointer, backup, settings]);
|
||||
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
platform: 'darwin',
|
||||
home: '/Users/test',
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 1.2.3',
|
||||
readJson: async (candidate) => {
|
||||
if (candidate === pointer) return { settings_backup: backup };
|
||||
if (candidate === settings) return { hooks: {} };
|
||||
return null;
|
||||
},
|
||||
}));
|
||||
|
||||
expect(result.tools.find((tool) => tool.id === 'claude-code')).toMatchObject({
|
||||
hooksInstalled: false,
|
||||
hookPointerPath: pointer,
|
||||
});
|
||||
});
|
||||
|
||||
it('reports hooksInstalled=false when the pointer exists but its backup is gone (partial rollback)', async () => {
|
||||
const installed = '/usr/local/bin/claude';
|
||||
const home = '/Users/test';
|
||||
const pointer = '/Users/test/.claude/hive-mind-install.json';
|
||||
const existsSet = new Set([installed, pointer]); // backup deliberately missing
|
||||
|
||||
const result = await detectInstalledTools(
|
||||
makeDeps({
|
||||
platform: 'darwin',
|
||||
home,
|
||||
exists: async (p) => existsSet.has(p),
|
||||
pathFromEnv: () => installed,
|
||||
execVersion: async () => 'claude 1.2.3',
|
||||
readJson: async (p) =>
|
||||
p === pointer
|
||||
? { settings_backup: '/Users/test/.claude/settings.json.hive-mind-backup.X' }
|
||||
: null,
|
||||
}),
|
||||
);
|
||||
const t = result.tools.find((x) => x.id === 'claude-code')!;
|
||||
expect(t.hooksInstalled).toBe(false);
|
||||
expect(t.hookPointerPath).toBe(pointer);
|
||||
});
|
||||
|
||||
it('records a diagnostic when claude-code is installed but --version fails', async () => {
|
||||
const installed = '/usr/local/bin/claude';
|
||||
const result = await detectInstalledTools(
|
||||
@@ -574,25 +258,6 @@ describe('cursor detector', () => {
|
||||
expect(t.installed).toBe(true);
|
||||
expect(t.installedPath).toBe(installed);
|
||||
});
|
||||
|
||||
it('reports cursor hooks installed when pointer file is present and valid', async () => {
|
||||
const installed = '/Applications/Cursor.app/Contents/MacOS/Cursor';
|
||||
const pointer = '/Users/test/.cursor/hive-mind-install.json';
|
||||
const backup = '/Users/test/.cursor/settings.json.hive-mind-backup.X';
|
||||
const existsSet = new Set([installed, pointer, backup]);
|
||||
|
||||
const result = await detectInstalledTools(
|
||||
makeDeps({
|
||||
platform: 'darwin',
|
||||
home: '/Users/test',
|
||||
exists: async (p) => existsSet.has(p),
|
||||
readJson: async (p) => (p === pointer ? { settings_backup: backup } : null),
|
||||
}),
|
||||
);
|
||||
const t = result.tools.find((x) => x.id === 'cursor')!;
|
||||
expect(t.hooksInstalled).toBe(true);
|
||||
expect(t.hookPointerPath).toBe(pointer);
|
||||
});
|
||||
});
|
||||
|
||||
describe('claude-desktop detector', () => {
|
||||
@@ -687,28 +352,6 @@ describe('extended-cohort detectors (Codex / Hermes / OpenClaw — Phase 4)', ()
|
||||
expect(t.version).toBe('codex 0.5.0');
|
||||
});
|
||||
|
||||
it('recognizes a healthy create-if-missing hook install with no backup', async () => {
|
||||
const installed = '/usr/local/bin/codex';
|
||||
const pointer = '/Users/test/.codex/hive-mind-install.json';
|
||||
const configPath = '/Users/test/.codex/hooks.json';
|
||||
const hooksDir = '/waggle/runtime/codex/hooks';
|
||||
const existsSet = new Set([installed, pointer, configPath, hooksDir]);
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
platform: 'darwin', home: '/Users/test',
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
pathFromEnv: (name) => name === 'codex' ? installed : null,
|
||||
execVersion: async () => 'codex 0.5.0',
|
||||
readJson: async (candidate) => candidate === pointer ? {
|
||||
settings_backup: null,
|
||||
created_by_us: true,
|
||||
config_path: configPath,
|
||||
hooks_dir: hooksDir,
|
||||
installed_hooks: ['session-start'],
|
||||
} : null,
|
||||
}));
|
||||
expect(result.tools.find((tool) => tool.id === 'codex')?.hooksInstalled).toBe(true);
|
||||
});
|
||||
|
||||
it('reports WindowsApps Codex as installed but not launchable when Windows blocks exec', async () => {
|
||||
const installed =
|
||||
'C:\\Program Files\\WindowsApps\\OpenAI.Codex_26.623.19656.0_x64__2p2nqsd0c76g0\\app\\resources\\codex.exe';
|
||||
@@ -764,55 +407,39 @@ describe('extended-cohort detectors (Codex / Hermes / OpenClaw — Phase 4)', ()
|
||||
});
|
||||
});
|
||||
|
||||
it('uses the direct HERMES_HOME Windows executable fallback and hook pointer', async () => {
|
||||
it('uses the direct HERMES_HOME Windows executable fallback', async () => {
|
||||
const hermesHome = 'D:\\Hermes Data';
|
||||
const installed = `${hermesHome}\\hermes-agent\\venv\\Scripts\\hermes.exe`;
|
||||
const pointer = `${hermesHome}\\hive-mind-install.json`;
|
||||
const backup = `${hermesHome}\\config.yaml.hive-mind-backup.X`;
|
||||
const existsSet = new Set([installed, pointer, backup]);
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
env: {
|
||||
HERMES_HOME: hermesHome,
|
||||
LOCALAPPDATA: 'C:\\Users\\test\\AppData\\Local',
|
||||
},
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
exists: async (candidate) => candidate === installed,
|
||||
execVersion: async (binary) => binary === installed ? '0.18.2' : null,
|
||||
readJson: async (candidate) => candidate === pointer
|
||||
? { settings_backup: backup }
|
||||
: null,
|
||||
}));
|
||||
|
||||
expect(result.tools.find((tool) => tool.id === 'hermes')).toMatchObject({
|
||||
installed: true,
|
||||
installedPath: installed,
|
||||
version: '0.18.2',
|
||||
hooksInstalled: true,
|
||||
hookPointerPath: pointer,
|
||||
});
|
||||
});
|
||||
|
||||
it('uses redirected LOCALAPPDATA for the Windows CLI fallback and hook pointer', async () => {
|
||||
it('uses redirected LOCALAPPDATA for the Windows CLI fallback', async () => {
|
||||
const localAppData = 'E:\\Redirected\\Local';
|
||||
const hermesHome = `${localAppData}\\hermes`;
|
||||
const installed = `${hermesHome}\\hermes-agent\\venv\\Scripts\\hermes.exe`;
|
||||
const pointer = `${hermesHome}\\hive-mind-install.json`;
|
||||
const configPath = `${hermesHome}\\config.yaml`;
|
||||
const existsSet = new Set([installed, pointer, configPath]);
|
||||
const result = await detectInstalledTools(makeDeps({
|
||||
env: { LOCALAPPDATA: localAppData },
|
||||
exists: async (candidate) => existsSet.has(candidate),
|
||||
exists: async (candidate) => candidate === installed,
|
||||
execVersion: async (binary) => binary === installed ? '0.18.2' : null,
|
||||
readJson: async (candidate) => candidate === pointer
|
||||
? { settings_backup: null, created_by_us: true, config_path: configPath }
|
||||
: null,
|
||||
}));
|
||||
|
||||
expect(result.tools.find((tool) => tool.id === 'hermes')).toMatchObject({
|
||||
installed: true,
|
||||
installedPath: installed,
|
||||
version: '0.18.2',
|
||||
hooksInstalled: true,
|
||||
hookPointerPath: pointer,
|
||||
});
|
||||
});
|
||||
|
||||
@@ -899,7 +526,6 @@ describe('extended-cohort detectors (Codex / Hermes / OpenClaw — Phase 4)', ()
|
||||
installedPath: desktop,
|
||||
version: null,
|
||||
launchable: true,
|
||||
hookCapable: false,
|
||||
capabilities: { interactiveLaunch: true, headlessTask: false },
|
||||
});
|
||||
expect(versionProbes).toContain(cli);
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
/**
|
||||
* AI-OS Phase 2A — tool launcher tests.
|
||||
*
|
||||
* TDD coverage for launchTool() + runHookCommand(). All process
|
||||
* TDD coverage for launchTool(). All process
|
||||
* spawns are injected so the test never actually executes a binary.
|
||||
*/
|
||||
|
||||
@@ -11,18 +11,14 @@ import { describe, it, expect, vi } from 'vitest';
|
||||
import { join, resolve } from 'node:path';
|
||||
import {
|
||||
launchTool,
|
||||
runHookCommand,
|
||||
hookPackageFor,
|
||||
HOOKS_COHORT,
|
||||
createObservedHandle,
|
||||
defaultSpawnObserved,
|
||||
resolveHookRuntime,
|
||||
resolveSpawnInvocation,
|
||||
type HookRuntimePaths,
|
||||
resolveWaggleRuntime,
|
||||
type ToolLauncherDeps,
|
||||
type ObservedHandle,
|
||||
} from '../src/tool-launcher.js';
|
||||
import { BUILTIN_TOOL_MANIFESTS, type ToolId, type ToolManifest } from '@waggle/shared';
|
||||
import type { ToolId, ToolManifest } from '@waggle/shared';
|
||||
|
||||
function captureSpawn() {
|
||||
const calls: Array<{
|
||||
@@ -41,37 +37,6 @@ function captureSpawn() {
|
||||
return { calls, spawnDetached };
|
||||
}
|
||||
|
||||
function captureExec(
|
||||
result: { stdout: string; stderr: string; code: number } | null = {
|
||||
stdout: 'ok',
|
||||
stderr: '',
|
||||
code: 0,
|
||||
},
|
||||
) {
|
||||
const calls: Array<{
|
||||
binary: string;
|
||||
args: string[];
|
||||
options?: { timeoutMs?: number; env?: NodeJS.ProcessEnv };
|
||||
}> = [];
|
||||
const execCapture: NonNullable<ToolLauncherDeps['execCapture']> = async (
|
||||
binary,
|
||||
args,
|
||||
options,
|
||||
) => {
|
||||
calls.push({ binary, args, options });
|
||||
return result;
|
||||
};
|
||||
return { calls, execCapture };
|
||||
}
|
||||
|
||||
function testHookRuntime(id: ToolId = 'claude-code'): HookRuntimePaths {
|
||||
return {
|
||||
nodePath: '/waggle/resources/node',
|
||||
cliEntry: '/waggle/resources/node_modules/@waggle/hive-mind-cli/dist/index.js',
|
||||
hookEntry: `/waggle/resources/node_modules/@waggle/hive-mind-hooks-${id}/dist/bin/${id}-hooks.js`,
|
||||
};
|
||||
}
|
||||
|
||||
// ── launchTool ──────────────────────────────────────────────────────
|
||||
|
||||
describe('launchTool', () => {
|
||||
@@ -238,8 +203,6 @@ describe('launchTool', () => {
|
||||
id: 'foo-cli',
|
||||
displayName: 'Foo CLI',
|
||||
launchable: true,
|
||||
hookCapable: false,
|
||||
hookPointer: '.foo/hive-mind-install.json',
|
||||
detect: { kind: 'path', binaryName: 'foo' },
|
||||
builtin: false,
|
||||
};
|
||||
@@ -260,8 +223,6 @@ describe('launchTool', () => {
|
||||
id: 'foo-cli',
|
||||
displayName: 'Foo CLI',
|
||||
launchable: false,
|
||||
hookCapable: false,
|
||||
hookPointer: '.foo/hive-mind-install.json',
|
||||
detect: { kind: 'path', binaryName: 'foo' },
|
||||
builtin: false,
|
||||
};
|
||||
@@ -343,156 +304,6 @@ describe('launchTool — self-enabling signal env', () => {
|
||||
});
|
||||
});
|
||||
|
||||
// ── runHookCommand ──────────────────────────────────────────────────
|
||||
|
||||
describe('runHookCommand', () => {
|
||||
it('invokes the packaged hook bin through bundled Node for install', async () => {
|
||||
const { calls, execCapture } = captureExec();
|
||||
const runtime = testHookRuntime();
|
||||
const result = await runHookCommand({
|
||||
id: 'claude-code',
|
||||
action: 'install',
|
||||
runtime,
|
||||
dataDir: '/waggle-data',
|
||||
deps: {
|
||||
baseEnv: {
|
||||
LOCALAPPDATA: 'C:\\Redirected\\Local',
|
||||
HERMES_HOME: 'D:\\Hermes Data',
|
||||
OPENAI_API_KEY: 'must-not-cross',
|
||||
},
|
||||
execCapture,
|
||||
},
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls[0].binary).toBe(runtime.nodePath);
|
||||
expect(calls[0].args).toEqual([
|
||||
runtime.hookEntry,
|
||||
'install',
|
||||
'--cli-path',
|
||||
runtime.cliEntry,
|
||||
]);
|
||||
expect(calls[0].options?.env).toMatchObject({
|
||||
LOCALAPPDATA: 'C:\\Redirected\\Local',
|
||||
HERMES_HOME: 'D:\\Hermes Data',
|
||||
WAGGLE_HOOK_NODE_PATH: runtime.nodePath,
|
||||
HIVE_MIND_DATA_DIR: '/waggle-data',
|
||||
});
|
||||
expect(calls[0].options?.env?.OPENAI_API_KEY).toBeUndefined();
|
||||
});
|
||||
|
||||
it('pins the packaged CLI for install but not verify or uninstall', async () => {
|
||||
const { calls, execCapture } = captureExec();
|
||||
const runtime = testHookRuntime();
|
||||
await runHookCommand({ id: 'claude-code', action: 'install', runtime, deps: { execCapture } });
|
||||
await runHookCommand({ id: 'claude-code', action: 'verify', runtime, deps: { execCapture } });
|
||||
await runHookCommand({ id: 'claude-code', action: 'uninstall', runtime, deps: { execCapture } });
|
||||
expect(calls.map((call) => call.args)).toEqual([
|
||||
[runtime.hookEntry, 'install', '--cli-path', runtime.cliEntry],
|
||||
[runtime.hookEntry, 'verify'],
|
||||
[runtime.hookEntry, 'uninstall'],
|
||||
]);
|
||||
});
|
||||
|
||||
it('captures stdout, stderr, and code on success', async () => {
|
||||
const { execCapture } = captureExec({
|
||||
stdout: 'Done.',
|
||||
stderr: '',
|
||||
code: 0,
|
||||
});
|
||||
const result = await runHookCommand({
|
||||
id: 'claude-code',
|
||||
action: 'install',
|
||||
runtime: testHookRuntime(),
|
||||
deps: { execCapture },
|
||||
});
|
||||
expect(result.ok).toBe(true);
|
||||
expect(result.stdout).toBe('Done.');
|
||||
expect(result.code).toBe(0);
|
||||
});
|
||||
|
||||
it('reports ok=false on non-zero exit', async () => {
|
||||
const { execCapture } = captureExec({
|
||||
stdout: '',
|
||||
stderr: 'Failed to write settings.json',
|
||||
code: 1,
|
||||
});
|
||||
const result = await runHookCommand({
|
||||
id: 'claude-code',
|
||||
action: 'install',
|
||||
runtime: testHookRuntime(),
|
||||
deps: { execCapture },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.stderr).toContain('Failed');
|
||||
});
|
||||
|
||||
it('reports ok=false with diagnostic when exec returns null', async () => {
|
||||
const execCapture: NonNullable<ToolLauncherDeps['execCapture']> = async () =>
|
||||
null;
|
||||
const result = await runHookCommand({
|
||||
id: 'claude-code',
|
||||
action: 'install',
|
||||
runtime: testHookRuntime(),
|
||||
deps: { execCapture },
|
||||
});
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).toContain('exec failed');
|
||||
});
|
||||
|
||||
// R8-001: hook management is gated on the release-supported HOOKS_COHORT.
|
||||
it.each<ToolId>(['claude-code', 'claude-desktop', 'codex', 'codex-desktop', 'hermes'])(
|
||||
'routes the hook command for HOOKS_COHORT tool (%s)',
|
||||
async (id) => {
|
||||
const { calls, execCapture } = captureExec();
|
||||
const runtime = testHookRuntime(id);
|
||||
const result = await runHookCommand({ id, action: 'install', runtime, deps: { execCapture } });
|
||||
expect(result.ok).toBe(true);
|
||||
expect(calls[0].args).toEqual([runtime.hookEntry, 'install', '--cli-path', runtime.cliEntry]);
|
||||
},
|
||||
);
|
||||
|
||||
it.each<ToolId>(['cursor', 'openclaw'])(
|
||||
'refuses hook commands for roadmap tool %s without invoking exec',
|
||||
async (id) => {
|
||||
const { calls, execCapture } = captureExec();
|
||||
const result = await runHookCommand({ id, action: 'install', deps: { execCapture } });
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).toContain('not supported');
|
||||
expect(calls).toHaveLength(0);
|
||||
},
|
||||
);
|
||||
|
||||
it('refuses hook command for an unsupported tool id without invoking exec', async () => {
|
||||
const fakeId = 'not-a-real-tool' as ToolId;
|
||||
const { calls, execCapture } = captureExec();
|
||||
const result = await runHookCommand({ id: fakeId, action: 'install', deps: { execCapture } });
|
||||
expect(result.ok).toBe(false);
|
||||
expect(result.error).toContain('not supported');
|
||||
expect(calls).toHaveLength(0);
|
||||
});
|
||||
|
||||
it('fails closed when the packaged runtime payload cannot be resolved', () => {
|
||||
expect(resolveHookRuntime('claude-code', { nodeModulesRoots: ['/missing'], fileExists: () => false })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('HOOKS_COHORT derivation (#5)', () => {
|
||||
it('equals the hook-capable manifests and includes claude-desktop', () => {
|
||||
const expected = BUILTIN_TOOL_MANIFESTS.filter((m) => m.hookCapable).map((m) => m.id).sort();
|
||||
expect([...HOOKS_COHORT].sort()).toEqual(expected);
|
||||
expect(HOOKS_COHORT).toContain('claude-desktop');
|
||||
});
|
||||
});
|
||||
|
||||
describe('hookPackageFor', () => {
|
||||
it.each<ToolId>(['claude-code', 'claude-desktop', 'cursor'])(
|
||||
'returns @waggle/hive-mind-hooks-%s',
|
||||
(id) => {
|
||||
expect(hookPackageFor(id)).toBe(`@waggle/hive-mind-hooks-${id}`);
|
||||
},
|
||||
);
|
||||
});
|
||||
|
||||
describe('launchTool observe mode', () => {
|
||||
it('preserves a target signal receipt instead of exposing the supervisor exit code', () => {
|
||||
const child = new EventEmitter() as ChildProcess;
|
||||
@@ -593,24 +404,25 @@ describe('launchTool observe mode', () => {
|
||||
});
|
||||
});
|
||||
|
||||
describe('resolveHookRuntime', () => {
|
||||
it('resolves the CLI and hook bin from an explicit staged node_modules root', () => {
|
||||
describe('resolveWaggleRuntime', () => {
|
||||
it('resolves the collaboration CLI from an explicit staged node_modules root', () => {
|
||||
const root = join('resources', 'node_modules');
|
||||
const cliEntry = join(root, '@waggle', 'hive-mind-cli', 'dist', 'index.js');
|
||||
const hookEntry = join(root, '@waggle', 'hive-mind-hooks-codex', 'dist', 'bin', 'codex-hooks.js');
|
||||
const runtime = resolveHookRuntime('codex', {
|
||||
const runtime = resolveWaggleRuntime({
|
||||
nodePath: join('resources', 'node'),
|
||||
nodeModulesRoots: [root],
|
||||
fileExists: (candidate) => candidate === resolve(cliEntry) || candidate === resolve(hookEntry),
|
||||
});
|
||||
expect(runtime).toEqual({
|
||||
nodePath: join('resources', 'node'),
|
||||
cliEntry: resolve(cliEntry),
|
||||
hookEntry: resolve(hookEntry),
|
||||
fileExists: (candidate) => candidate === resolve(cliEntry),
|
||||
});
|
||||
expect(runtime).toEqual({ nodePath: join('resources', 'node'), cliEntry: resolve(cliEntry) });
|
||||
});
|
||||
|
||||
it('injects the canonical Waggle data root for hook memory', () => {
|
||||
it('fails closed when the collaboration CLI is not staged', () => {
|
||||
expect(resolveWaggleRuntime({ nodeModulesRoots: ['/missing'], fileExists: () => false })).toBeUndefined();
|
||||
});
|
||||
});
|
||||
|
||||
describe('launchTool collaboration env', () => {
|
||||
it('injects the canonical Waggle data root', () => {
|
||||
const { calls, spawnDetached } = captureSpawn();
|
||||
launchTool({
|
||||
id: 'claude-code',
|
||||
|
||||
@@ -12,7 +12,7 @@ function deps(files: Record<string, unknown>) {
|
||||
describe('loadThirdPartyManifests', () => {
|
||||
it('loads a valid PATH manifest, stamped builtin:false', () => {
|
||||
const out = loadThirdPartyManifests(deps({
|
||||
'foo.json': { id: 'foo-cli', displayName: 'Foo', launchable: true, hookCapable: false, hookPointer: '.foo/hm.json', detect: { kind: 'path', binaryName: 'foo' } },
|
||||
'foo.json': { id: 'foo-cli', displayName: 'Foo', launchable: true, detect: { kind: 'path', binaryName: 'foo' } },
|
||||
}));
|
||||
expect(out).toHaveLength(1);
|
||||
expect(out[0]).toMatchObject({ id: 'foo-cli', builtin: false, detect: { kind: 'path', binaryName: 'foo' } });
|
||||
@@ -20,14 +20,14 @@ describe('loadThirdPartyManifests', () => {
|
||||
|
||||
it('rejects detect.kind:candidates (code-only strategy)', () => {
|
||||
const out = loadThirdPartyManifests(deps({
|
||||
'bad.json': { id: 'bad', displayName: 'B', launchable: true, hookCapable: false, hookPointer: '.b/hm.json', detect: { kind: 'candidates' } },
|
||||
'bad.json': { id: 'bad', displayName: 'B', launchable: true, detect: { kind: 'candidates' } },
|
||||
}));
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
|
||||
it('rejects shell-metachar / traversal in fields', () => {
|
||||
const out = loadThirdPartyManifests(deps({
|
||||
'evil.json': { id: 'evil', displayName: 'E', launchable: true, hookCapable: false, hookPointer: '../../etc/passwd', detect: { kind: 'path', binaryName: 'foo; rm -rf /' } },
|
||||
'evil.json': { id: '../evil', displayName: 'E', launchable: true, detect: { kind: 'path', binaryName: 'foo; rm -rf /' } },
|
||||
}));
|
||||
expect(out).toEqual([]);
|
||||
});
|
||||
@@ -40,7 +40,7 @@ describe('loadThirdPartyManifests', () => {
|
||||
const out = loadThirdPartyManifests({
|
||||
dir: '/fake',
|
||||
readDir: () => ['broken.json', 'ok.json'],
|
||||
readFile: (p: string) => (p.includes('broken') ? '{not json' : JSON.stringify({ id: 'ok-cli', displayName: 'OK', launchable: true, hookCapable: false, hookPointer: '.ok/hm.json', detect: { kind: 'path', binaryName: 'ok' } })),
|
||||
readFile: (p: string) => (p.includes('broken') ? '{not json' : JSON.stringify({ id: 'ok-cli', displayName: 'OK', launchable: true, detect: { kind: 'path', binaryName: 'ok' } })),
|
||||
});
|
||||
expect(out.map((m) => m.id)).toEqual(['ok-cli']);
|
||||
});
|
||||
|
||||
@@ -16,7 +16,7 @@ describe('getToolRegistry', () => {
|
||||
|
||||
it('merges a valid third-party PATH adapter', () => {
|
||||
const reg = getToolRegistry(fakeLoaderDeps([
|
||||
{ id: 'foo-cli', displayName: 'Foo', launchable: true, hookCapable: false, hookPointer: '.foo/hm.json', detect: { kind: 'path', binaryName: 'foo' } },
|
||||
{ id: 'foo-cli', displayName: 'Foo', launchable: true, detect: { kind: 'path', binaryName: 'foo' } },
|
||||
]));
|
||||
expect(reg.find((m) => m.id === 'foo-cli')).toMatchObject({ builtin: false });
|
||||
expect(reg.length).toBe(SUPPORTED_TOOLS.length + 1);
|
||||
@@ -24,7 +24,7 @@ describe('getToolRegistry', () => {
|
||||
|
||||
it('built-in id wins a third-party collision', () => {
|
||||
const reg = getToolRegistry(fakeLoaderDeps([
|
||||
{ id: 'claude-code', displayName: 'HIJACK', launchable: true, hookCapable: false, hookPointer: '.x/hm.json', detect: { kind: 'path', binaryName: 'x' } },
|
||||
{ id: 'claude-code', displayName: 'HIJACK', launchable: true, detect: { kind: 'path', binaryName: 'x' } },
|
||||
]));
|
||||
const cc = reg.filter((m) => m.id === 'claude-code');
|
||||
expect(cc).toHaveLength(1);
|
||||
|
||||
Reference in New Issue
Block a user