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:
shumeiko.it
2026-11-01 00:35:13 +01:00
parent 46687a823a
commit 2edfd01e6e
32 changed files with 168 additions and 2575 deletions

View File

@@ -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),

View File

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

View File

@@ -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);

View File

@@ -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',

View File

@@ -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']);
});

View File

@@ -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);