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

@@ -1,16 +1,9 @@
/** /**
* Warm-Hive PR6b (B1) — LauncherApp A/B segmented toggle. * LauncherApp — detect, launch, watch and stop external AI tools.
* *
* Variation A · Launch = the existing live detect/launch UI (preserved). * Waggle Room tasks are hidden in v1 by the memory feature map (ADR-0002).
* Variation B · How memory is shared = a pure-UI explainer (flow diagram + * Most suites switch them on to keep the hidden code covered; the "v1 memory
* three cards + an explicitly-labelled provenance example, no live data). * features" suite checks the default.
*
* These tests assert the toggle wiring and that Variation B carries the
* static explainer content WITHOUT fabricating a live recall.
*
* Agent hooks, the explainer and Waggle Room tasks are hidden in v1 by the
* memory feature map (ADR-0002). Most suites switch them on to keep the hidden
* code covered; the "v1 memory features" suite checks the default.
*/ */
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest'; import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react'; import { render, screen, waitFor, cleanup, fireEvent, within } from '@testing-library/react';
@@ -20,7 +13,6 @@ const mocks = vi.hoisted(() => ({
detectTools: vi.fn(), detectTools: vi.fn(),
getToolProcesses: vi.fn(), getToolProcesses: vi.fn(),
launchTool: vi.fn(), launchTool: vi.fn(),
manageHooks: vi.fn(),
killTool: vi.fn(), killTool: vi.fn(),
runExternalToolTask: vi.fn(), runExternalToolTask: vi.fn(),
streamToolOutput: vi.fn(() => () => {}), streamToolOutput: vi.fn(() => () => {}),
@@ -43,8 +35,6 @@ const detectionResp = {
installed: true, installed: true,
installedPath: '/opt/homebrew/bin/claude', installedPath: '/opt/homebrew/bin/claude',
version: '2.4.0', version: '2.4.0',
hooksInstalled: true,
hookPointerPath: '/home/.claude/hooks',
}, },
], ],
}; };
@@ -55,7 +45,6 @@ beforeEach(() => {
mocks.adapter.detectTools.mockResolvedValue(detectionResp); mocks.adapter.detectTools.mockResolvedValue(detectionResp);
mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] }); mocks.adapter.getToolProcesses.mockResolvedValue({ processes: [] });
mocks.adapter.launchTool.mockResolvedValue({ ok: true, pid: 123 }); mocks.adapter.launchTool.mockResolvedValue({ ok: true, pid: 123 });
mocks.adapter.manageHooks.mockResolvedValue({ ok: true });
mocks.adapter.killTool.mockResolvedValue({ ok: true, pid: 123, reason: 'SIGTERM' }); mocks.adapter.killTool.mockResolvedValue({ ok: true, pid: 123, reason: 'SIGTERM' });
mocks.adapter.runExternalToolTask.mockResolvedValue({ mocks.adapter.runExternalToolTask.mockResolvedValue({
roomId: 'room-1', roomId: 'room-1',
@@ -67,7 +56,7 @@ afterEach(() => {
vi.clearAllMocks(); vi.clearAllMocks();
}); });
describe('LauncherApp · A/B toggle', () => { describe('LauncherApp · detection', () => {
it('repaints detected tools on return and refreshes silently', async () => { it('repaints detected tools on return and refreshes silently', async () => {
const first = render(<LauncherApp />); const first = render(<LauncherApp />);
expect(await screen.findByText('Claude Code')).toBeInTheDocument(); expect(await screen.findByText('Claude Code')).toBeInTheDocument();
@@ -79,54 +68,11 @@ describe('LauncherApp · A/B toggle', () => {
await waitFor(() => expect(mocks.adapter.detectTools.mock.calls.length).toBeGreaterThan(baseline)); await waitFor(() => expect(mocks.adapter.detectTools.mock.calls.length).toBeGreaterThan(baseline));
}); });
it('defaults to Variation A and renders the live launch UI', async () => { it('renders the live launch UI', async () => {
render(<LauncherApp />); render(<LauncherApp />);
// The detected tool from the live adapter appears (Variation A).
expect(await screen.findByText('Claude Code')).toBeInTheDocument(); expect(await screen.findByText('Claude Code')).toBeInTheDocument();
expect(screen.getByText(/optional prompt/i)).toBeInTheDocument(); expect(screen.getByText(/optional prompt/i)).toBeInTheDocument();
// Toggle exists with both tabs, A selected. expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
const launchTab = screen.getByRole('tab', { name: /^launch$/i });
const memTab = screen.getByRole('tab', { name: /how memory is shared/i });
expect(launchTab).toHaveAttribute('aria-selected', 'true');
expect(memTab).toHaveAttribute('aria-selected', 'false');
});
it('switches to Variation B and renders the explainer (flow + cards), hiding the live UI', async () => {
render(<LauncherApp />);
await screen.findByText('Claude Code');
fireEvent.click(screen.getByRole('tab', { name: /how memory is shared/i }));
expect(screen.getByRole('tab', { name: /how memory is shared/i })).toHaveAttribute('aria-selected', 'true');
// Explainer heading + flow nodes.
expect(screen.getByText(/how a launched agent shares the hive/i)).toBeInTheDocument();
expect(screen.getByText('The hive')).toBeInTheDocument();
expect(screen.getByText('hive-mind')).toBeInTheDocument();
// Three explainer cards.
expect(screen.getByText(/it recalls on start/i)).toBeInTheDocument();
expect(screen.getByText(/it commits as it works/i)).toBeInTheDocument();
expect(screen.getByText(/reversible & local/i)).toBeInTheDocument();
// The live launch UI (prompt box) is no longer mounted.
expect(screen.queryByText(/optional prompt/i)).not.toBeInTheDocument();
});
it('labels the provenance example as an example (no fabricated live recall)', async () => {
render(<LauncherApp />);
await screen.findByText('Claude Code');
fireEvent.click(screen.getByRole('tab', { name: /how memory is shared/i }));
const prov = screen.getByText(/remembered from Claude Code/i);
expect(prov).toHaveTextContent(/^example ·/i);
});
it('toggles back to Variation A and restores the live UI', async () => {
render(<LauncherApp />);
await screen.findByText('Claude Code');
fireEvent.click(screen.getByRole('tab', { name: /how memory is shared/i }));
expect(screen.queryByText(/optional prompt/i)).not.toBeInTheDocument();
fireEvent.click(screen.getByRole('tab', { name: /^launch$/i }));
expect(screen.getByRole('tab', { name: /^launch$/i })).toHaveAttribute('aria-selected', 'true');
await waitFor(() => expect(screen.getByText(/optional prompt/i)).toBeInTheDocument());
expect(screen.getByText('Claude Code')).toBeInTheDocument();
}); });
}); });
@@ -158,8 +104,6 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: '/usr/local/bin/codex', installedPath: '/usr/local/bin/codex',
version: '0.144.1', version: '0.144.1',
hooksInstalled: true,
hookPointerPath: '/home/.codex/hooks',
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: true, headlessTask: true,
@@ -175,8 +119,6 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: '/usr/local/bin/hermes', installedPath: '/usr/local/bin/hermes',
version: '1.0.0', version: '1.0.0',
hooksInstalled: true,
hookPointerPath: '/home/.hermes/hooks',
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: true, headlessTask: true,
@@ -192,8 +134,6 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: '/Applications/Cursor.app', installedPath: '/Applications/Cursor.app',
version: '1.0.0', version: '1.0.0',
hooksInstalled: true,
hookPointerPath: '/home/.cursor/hooks',
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: false, headlessTask: false,
@@ -209,8 +149,6 @@ describe('LauncherApp · captured tasks', () => {
installed: false, installed: false,
installedPath: null, installedPath: null,
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: true, headlessTask: true,
@@ -274,7 +212,7 @@ describe('LauncherApp · captured tasks', () => {
expect(onOpenRoom).toHaveBeenCalledWith('room-multi'); expect(onOpenRoom).toHaveBeenCalledWith('room-multi');
}); });
it('labels a roadmap tool and offers no launch, task, or hook actions', async () => { it('labels a roadmap tool and offers no launch or task actions', async () => {
mocks.adapter.detectTools.mockResolvedValue({ mocks.adapter.detectTools.mockResolvedValue({
platform: 'darwin', platform: 'darwin',
detectedAt: '2026-07-11T00:00:00.000Z', detectedAt: '2026-07-11T00:00:00.000Z',
@@ -283,12 +221,9 @@ describe('LauncherApp · captured tasks', () => {
displayName: 'Cursor', displayName: 'Cursor',
releaseStatus: 'roadmap', releaseStatus: 'roadmap',
launchable: false, launchable: false,
hookCapable: false,
installed: true, installed: true,
installedPath: '/Applications/Cursor.app', installedPath: '/Applications/Cursor.app',
version: '1.0.0', version: '1.0.0',
hooksInstalled: true,
hookPointerPath: '/home/.cursor/hooks',
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: false, headlessTask: false,
@@ -306,10 +241,8 @@ describe('LauncherApp · captured tasks', () => {
expect(within(card).getByText('Roadmap')).toBeInTheDocument(); expect(within(card).getByText('Roadmap')).toBeInTheDocument();
expect(within(card).getByText(/detection retained for compatibility/i)).toBeInTheDocument(); expect(within(card).getByText(/detection retained for compatibility/i)).toBeInTheDocument();
expect(within(card).queryByText('Detect only')).not.toBeInTheDocument(); expect(within(card).queryByText('Detect only')).not.toBeInTheDocument();
expect(within(card).queryByText('Hooks active')).not.toBeInTheDocument();
expect(within(card).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument(); expect(within(card).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
expect(within(card).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument(); expect(within(card).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
expect(within(card).queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
}); });
it('launches Hermes Desktop but excludes it and a broken CLI from captured teams', async () => { it('launches Hermes Desktop but excludes it and a broken CLI from captured teams', async () => {
@@ -323,8 +256,6 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: 'C:\\tools\\codex.exe', installedPath: 'C:\\tools\\codex.exe',
version: '0.144.1', version: '0.144.1',
hooksInstalled: true,
hookPointerPath: 'C:\\Users\\test\\.codex\\hooks.json',
launchable: true, launchable: true,
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
@@ -341,8 +272,6 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\bin\\hermes.cmd', installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\bin\\hermes.cmd',
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
launchable: false, launchable: false,
diagnostic: 'Hermes failed its --version health check.', diagnostic: 'Hermes failed its --version health check.',
capabilities: { capabilities: {
@@ -360,10 +289,7 @@ describe('LauncherApp · captured tasks', () => {
installed: true, installed: true,
installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\Hermes.exe', installedPath: 'C:\\Users\\test\\AppData\\Local\\hermes\\Hermes.exe',
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
launchable: true, launchable: true,
hookCapable: false,
capabilities: { capabilities: {
interactiveLaunch: true, interactiveLaunch: true,
headlessTask: false, headlessTask: false,
@@ -381,8 +307,6 @@ describe('LauncherApp · captured tasks', () => {
const desktopCard = await screen.findByTestId('launcher-tool-hermes-desktop'); const desktopCard = await screen.findByTestId('launcher-tool-hermes-desktop');
expect(within(desktopCard).getByRole('button', { name: /^launch$/i })).toBeInTheDocument(); expect(within(desktopCard).getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
expect(within(desktopCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument(); expect(within(desktopCard).queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
expect(within(desktopCard).queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
expect(within(desktopCard).getByText(/launch only/i)).toBeInTheDocument();
const cliCard = screen.getByTestId('launcher-tool-hermes'); const cliCard = screen.getByTestId('launcher-tool-hermes');
expect(within(cliCard).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument(); expect(within(cliCard).queryByRole('button', { name: /^launch$/i })).not.toBeInTheDocument();
@@ -395,31 +319,7 @@ describe('LauncherApp · captured tasks', () => {
}); });
}); });
describe('LauncherApp · hook cohort (#3)', () => { describe('LauncherApp · launch', () => {
it('offers hook actions for every real-hook tool (e.g. codex), not just claude-code', async () => {
// The 7 real-hook tools (claude-code, claude-desktop, codex,
// codex-desktop, cursor, hermes, openclaw) all ship a bin — the dock
// must expose hook install for each, mirroring the backend HOOKS_COHORT.
mocks.adapter.detectTools.mockResolvedValue({
platform: 'darwin',
detectedAt: '2026-06-29T00:00:00.000Z',
tools: [
{
id: 'codex',
displayName: 'Codex',
installed: true,
installedPath: '/usr/local/bin/codex',
version: '1.0.0',
hooksInstalled: false,
hookPointerPath: null,
},
],
});
render(<LauncherApp />);
expect(await screen.findByText('Codex')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /install hooks/i })).toBeInTheDocument();
});
it('offers launch for a detected third-party adapter and sends its raw prompt', async () => { it('offers launch for a detected third-party adapter and sends its raw prompt', async () => {
mocks.adapter.detectTools.mockResolvedValue({ mocks.adapter.detectTools.mockResolvedValue({
platform: 'linux', platform: 'linux',
@@ -431,10 +331,7 @@ describe('LauncherApp · hook cohort (#3)', () => {
installed: true, installed: true,
installedPath: '/usr/local/bin/foo', installedPath: '/usr/local/bin/foo',
version: '1.0.0', version: '1.0.0',
hooksInstalled: false,
hookPointerPath: null,
launchable: true, launchable: true,
hookCapable: false,
builtin: false, builtin: false,
acceptsInlinePrompt: true, acceptsInlinePrompt: true,
}, },
@@ -460,7 +357,6 @@ describe('LauncherApp · hook cohort (#3)', () => {
}), }),
); );
}); });
expect(screen.queryByRole('button', { name: /install hooks/i })).not.toBeInTheDocument();
expect(screen.queryByText(/launch and hook management arrive in Phase 4/i)).not.toBeInTheDocument(); expect(screen.queryByText(/launch and hook management arrive in Phase 4/i)).not.toBeInTheDocument();
}); });
@@ -476,10 +372,7 @@ describe('LauncherApp · hook cohort (#3)', () => {
installedPath: installedPath:
'C:\\Program Files\\WindowsApps\\OpenAI.Codex_26.623.19656.0_x64__2p2nqsd0c76g0\\app\\resources\\codex.exe', 'C:\\Program Files\\WindowsApps\\OpenAI.Codex_26.623.19656.0_x64__2p2nqsd0c76g0\\app\\resources\\codex.exe',
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
launchable: false, launchable: false,
hookCapable: true,
diagnostic: diagnostic:
'Codex was found in WindowsApps, but Windows blocks command-line launch from that app alias. Install a PATH CLI build of Codex or launch Codex from Start, then refresh.', 'Codex was found in WindowsApps, but Windows blocks command-line launch from that app alias. Install a PATH CLI build of Codex or launch Codex from Start, then refresh.',
}, },
@@ -495,163 +388,7 @@ describe('LauncherApp · hook cohort (#3)', () => {
expect(screen.queryByText(/adapter is not configured for launch/i)).not.toBeInTheDocument(); expect(screen.queryByText(/adapter is not configured for launch/i)).not.toBeInTheDocument();
}); });
it('shows actionable hook install stdout details such as the backup path', async () => { it('offers Claude Desktop launch from the shared manifest', async () => {
mocks.adapter.detectTools.mockResolvedValue({
...detectionResp,
tools: [
{
...detectionResp.tools[0],
hooksInstalled: false,
hookPointerPath: null,
},
],
});
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: true,
action: 'install',
stdout: 'settings backed up: /home/.claude/settings.json.hive-mind-backup.2026-07-08T19-00-00Z\ninstall complete',
stderr: '',
code: 0,
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /install hooks/i }));
expect(await screen.findByText(/Claude Code: install OK/i)).toBeInTheDocument();
expect(screen.getByText('Backup')).toBeInTheDocument();
expect(screen.getByText(/settings\.json\.hive-mind-backup/i)).toBeInTheDocument();
expect(screen.getByText('Recovery')).toBeInTheDocument();
expect(screen.queryByText(/^stdout:/i)).not.toBeInTheDocument();
});
it('shows hook failure stderr even when the route returns a generic error', async () => {
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: false,
action: 'verify',
stdout: '',
stderr: 'missing hook pointer: /home/.claude/settings.json',
code: 1,
error: 'verify failed',
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /^verify$/i }));
expect(await screen.findByText(/verify failed/i)).toBeInTheDocument();
expect(screen.getByText(/missing hook pointer/i)).toBeInTheDocument();
expect(screen.getByText(/settings\.json/i)).toBeInTheDocument();
});
it('summarizes long hook output instead of flooding the result panel', async () => {
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: false,
action: 'verify',
stdout: '',
stderr: [
'failure detail 1: missing hook pointer',
'failure detail 2: stale backup file',
'failure detail 3: cli not trusted',
'failure detail 4: config mismatch',
'failure detail 5: lifecycle skipped',
'failure detail 6: retry recommended',
'failure detail 7: noisy internal trace',
'failure detail 8: noisy internal trace',
].join('\n'),
code: 1,
error: 'verify failed',
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /^verify$/i }));
expect(await screen.findByText(/verify failed/i)).toBeInTheDocument();
expect(screen.getByText(/failure detail 1/i)).toBeInTheDocument();
expect(screen.getByText('More output')).toBeInTheDocument();
expect(screen.getByText(/2 additional hook output lines hidden/i)).toBeInTheDocument();
expect(screen.queryByText(/failure detail 8/i)).not.toBeInTheDocument();
expect(screen.getByText('Recovery')).toBeInTheDocument();
});
it('shows recovery guidance when hook verify fails without stdout or stderr', async () => {
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: false,
action: 'verify',
stdout: '',
stderr: '',
code: 1,
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /^verify$/i }));
expect(await screen.findByText(/verify failed \(exit 1\)/i)).toBeInTheDocument();
expect(screen.getByText(/no hook output was returned/i)).toBeInTheDocument();
expect(screen.getByText(/reinstall hooks/i)).toBeInTheDocument();
});
it('summarizes hook verify check failures instead of showing raw check output', async () => {
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: false,
action: 'verify',
stdout: [
'hive-mind/codex-hooks: verify',
' [PASS] hooks.json exists — /home/.codex/hooks.json',
' [FAIL] hook command trusted — manual approval required in Codex settings',
'One or more checks failed.',
].join('\n'),
stderr: '',
code: 1,
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /^verify$/i }));
expect(await screen.findByText(/verify failed \(exit 1\)/i)).toBeInTheDocument();
expect(screen.getByText('Check failed')).toBeInTheDocument();
expect(screen.getByText(/manual approval required in Codex settings/i)).toBeInTheDocument();
expect(screen.getByText('Recovery')).toBeInTheDocument();
expect(screen.queryByText(/\[FAIL\]/)).not.toBeInTheDocument();
});
it('labels hook uninstall restore and cleanup details without implying install state', async () => {
mocks.adapter.detectTools.mockResolvedValue({
...detectionResp,
tools: [
{
...detectionResp.tools[0],
hooksInstalled: true,
hookPointerPath: '/home/.codex/hive-mind-install.json',
},
],
});
mocks.adapter.manageHooks.mockResolvedValueOnce({
ok: true,
action: 'uninstall',
stdout: [
'hive-mind/codex-hooks: uninstall',
' - hooks.json: /home/.codex/hooks.json',
' - restored from: /home/.codex/hooks.json.hive-mind-backup.2026-07-08T19-00-00Z',
' - created removed: no',
' - backup removed: yes',
' - pointer removed: yes',
'Done. hooks.json is byte-identical to pre-install state.',
].join('\n'),
stderr: '',
code: 0,
});
render(<LauncherApp />);
fireEvent.click(await screen.findByRole('button', { name: /uninstall hooks/i }));
expect(await screen.findByText(/Claude Code: uninstall OK/i)).toBeInTheDocument();
expect(screen.getByText('Changed file')).toBeInTheDocument();
expect(screen.getByText('Restored from')).toBeInTheDocument();
expect(screen.getByText('Backup removed')).toBeInTheDocument();
expect(screen.getByText('Pointer removed')).toBeInTheDocument();
expect(screen.queryByText('Install pointer')).not.toBeInTheDocument();
});
it('offers Claude Desktop launch and hook management from the shared manifest', async () => {
mocks.adapter.detectTools.mockResolvedValue({ mocks.adapter.detectTools.mockResolvedValue({
platform: 'darwin', platform: 'darwin',
detectedAt: '2026-07-08T00:00:00.000Z', detectedAt: '2026-07-08T00:00:00.000Z',
@@ -662,8 +399,6 @@ describe('LauncherApp · hook cohort (#3)', () => {
installed: true, installed: true,
installedPath: '/Applications/Claude.app', installedPath: '/Applications/Claude.app',
version: '1.2.3', version: '1.2.3',
hooksInstalled: false,
hookPointerPath: null,
}, },
], ],
}); });
@@ -672,15 +407,11 @@ describe('LauncherApp · hook cohort (#3)', () => {
expect(await screen.findByText('Claude Desktop')).toBeInTheDocument(); expect(await screen.findByText('Claude Desktop')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /install hooks/i })).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^verify$/i })).toBeInTheDocument();
expect(screen.queryByText(/launch only/i)).not.toBeInTheDocument();
expect(screen.queryByText(/hooks are not supported for Claude Desktop yet/i)).not.toBeInTheDocument();
}); });
}); });
describe('LauncherApp · v1 memory features (ADR-0002)', () => { describe('LauncherApp · v1 memory features (ADR-0002)', () => {
it('hides hook controls, the memory-sharing explainer and Room tasks; launch stays', async () => { it('hides Room tasks; launch stays', async () => {
features.enabled = false; features.enabled = false;
mocks.adapter.detectTools.mockResolvedValue({ mocks.adapter.detectTools.mockResolvedValue({
platform: 'darwin', platform: 'darwin',
@@ -692,8 +423,6 @@ describe('LauncherApp · v1 memory features (ADR-0002)', () => {
installed: true, installed: true,
installedPath: '/usr/local/bin/codex', installedPath: '/usr/local/bin/codex',
version: '0.144.1', version: '0.144.1',
hooksInstalled: true,
hookPointerPath: '/home/.codex/hooks',
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true }, capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true },
permissionModes: ['read-only', 'workspace-write', 'native'], permissionModes: ['read-only', 'workspace-write', 'native'],
}, },
@@ -704,10 +433,6 @@ describe('LauncherApp · v1 memory features (ADR-0002)', () => {
expect(await screen.findByText('Codex CLI')).toBeInTheDocument(); expect(await screen.findByText('Codex CLI')).toBeInTheDocument();
expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument(); expect(screen.getByRole('button', { name: /^launch$/i })).toBeInTheDocument();
expect(screen.queryByRole('tablist', { name: /launcher view/i })).not.toBeInTheDocument();
expect(screen.queryByText(/hooks active/i)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /install hooks|uninstall hooks|^verify$/i })).not.toBeInTheDocument();
expect(screen.queryByText(/launch only|hook management is not supported/i)).not.toBeInTheDocument();
expect(screen.queryByRole('button', { name: /run task/i })).not.toBeInTheDocument(); expect(screen.queryByRole('button', { name: /run task/i })).not.toBeInTheDocument();
}); });
}); });

View File

@@ -3,28 +3,18 @@
* *
* Dock surface for the AI-OS tool launcher. Lists registered AI execution * Dock surface for the AI-OS tool launcher. Lists registered AI execution
* surfaces while keeping roadmap integrations visibly inert. Each card * surfaces while keeping roadmap integrations visibly inert. Each card
* includes detection status, hook-install status, * includes detection status and its supported actions (launch in the active
* and its supported actions: * workspace, watch, stop).
*
* Launch in workspace X / Install hooks / Verify hooks / Uninstall hooks
* *
* Adapter contract: * Adapter contract:
* adapter.detectTools() → /api/tools/detect * adapter.detectTools() → /api/tools/detect
* adapter.launchTool() → /api/tools/launch * adapter.launchTool() → /api/tools/launch
* adapter.manageHooks() → /api/tools/hooks
*
* Warm-Hive PR6b (B1): two views behind a segmented toggle —
* Variation A · Launch — the live detect/launch/hooks/processes UI (below).
* Variation B · How memory is shared — a pure-UI explainer (flow diagram +
* three cards + a provenance example). Static, no backend, mirrors
* docs/design_handoff_waggle_app/design-files/screens/launcher.html.
*/ */
import { useState, useEffect, useCallback, useMemo } from 'react'; import { useState, useEffect, useCallback, useMemo } from 'react';
import { import {
Rocket, RefreshCw, CheckCircle2, XCircle, AlertTriangle, Rocket, RefreshCw, CheckCircle2, XCircle, AlertTriangle,
Play, Download, ShieldCheck, Trash2, Loader2, MessageSquare, Square, Play, Loader2, MessageSquare, Square, Workflow,
Workflow, ArrowDownToLine, ArrowRight, ShieldCheck as ShieldCheckIcon, Hexagon,
} from 'lucide-react'; } from 'lucide-react';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
@@ -45,19 +35,15 @@ import {
} from '@waggle/shared'; } from '@waggle/shared';
// #5 — derived from the shared manifest registry (single source of truth), // #5 — derived from the shared manifest registry (single source of truth),
// replacing the hand-maintained local copies. LAUNCH_COHORT = launchable tools; // replacing the hand-maintained local copy. LAUNCH_COHORT = launchable tools.
// HOOKS_COHORT = tools whose hive-mind hook package ships a bin (hookCapable). // Mirrors the backend cohort, which derives from the same BUILTIN_TOOL_MANIFESTS.
// Hermes Desktop is intentionally excluded. Mirrors the backend cohorts, which
// derive from the same BUILTIN_TOOL_MANIFESTS.
const LAUNCH_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.launchable).map((m) => m.id); const LAUNCH_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.launchable).map((m) => m.id);
const HOOKS_COHORT = BUILTIN_TOOL_MANIFESTS.filter((m) => m.hookCapable).map((m) => m.id);
interface DetectedTool { interface DetectedTool {
id: string; id: string;
displayName: string; displayName: string;
releaseStatus?: ToolReleaseStatus; releaseStatus?: ToolReleaseStatus;
launchable?: boolean; launchable?: boolean;
hookCapable?: boolean;
builtin?: boolean; builtin?: boolean;
acceptsInlinePrompt?: boolean; acceptsInlinePrompt?: boolean;
capabilities?: ToolCapabilities; capabilities?: ToolCapabilities;
@@ -65,8 +51,6 @@ interface DetectedTool {
installed: boolean; installed: boolean;
installedPath: string | null; installedPath: string | null;
version: string | null; version: string | null;
hooksInstalled: boolean;
hookPointerPath: string | null;
diagnostic?: string; diagnostic?: string;
} }
@@ -76,10 +60,7 @@ interface DetectionResult {
tools: DetectedTool[]; tools: DetectedTool[];
} }
type ToolAction = 'launch' | 'run' | 'install' | 'verify' | 'uninstall'; type ToolAction = 'launch' | 'run';
/** Segmented-toggle view: A = the live launch UI; B = the memory-sharing explainer. */
type LauncherView = 'a' | 'b';
interface ActionState { interface ActionState {
toolId: string; toolId: string;
@@ -91,13 +72,6 @@ interface ActionResult {
action: ToolAction; action: ToolAction;
ok: boolean; ok: boolean;
message: string; message: string;
details?: ActionDetail[];
}
interface ActionDetail {
label: string;
value: string;
tone?: 'attention' | 'recovery';
} }
interface LauncherAppProps { interface LauncherAppProps {
@@ -115,16 +89,13 @@ export function resetLauncherRouteCache(): void {
launcherRouteCache.resetForTests(); launcherRouteCache.resetForTests();
} }
const HOOK_PATH_RE = /([A-Za-z]:\\[^\s]+|\/[^\s]+)/;
const MAX_VISIBLE_HOOK_DETAILS = 6;
const toolCanLaunch = (tool: DetectedTool): boolean => const toolCanLaunch = (tool: DetectedTool): boolean =>
tool.releaseStatus !== 'roadmap' tool.releaseStatus !== 'roadmap'
&& (tool.launchable ?? LAUNCH_COHORT.includes(tool.id)); && (tool.launchable ?? LAUNCH_COHORT.includes(tool.id));
const launchUnavailableMessage = (tool: DetectedTool): string => const launchUnavailableMessage = (tool: DetectedTool): string =>
tool.releaseStatus === 'roadmap' tool.releaseStatus === 'roadmap'
? 'Roadmap integration. Detection retained for compatibility; launch, tasks, and hooks are deferred.' ? 'Roadmap integration. Detection retained for compatibility; launch and tasks are deferred.'
: tool.installed && tool.diagnostic : tool.installed && tool.diagnostic
? 'Launch is blocked for this install. Follow the note above, then refresh.' ? 'Launch is blocked for this install. Follow the note above, then refresh.'
: 'Detection ready. This adapter is not configured for launch.'; : 'Detection ready. This adapter is not configured for launch.';
@@ -149,152 +120,9 @@ const toolCanRunCapturedTask = (tool: DetectedTool): boolean =>
tool.capabilities?.headlessTask === true && tool.capabilities?.headlessTask === true &&
(tool.permissionModes?.length ?? 0) > 0; (tool.permissionModes?.length ?? 0) > 0;
const hookDetailLabel = (rawLabel: string): string => {
const label = rawLabel.trim().toLowerCase();
if (label.includes('backup removed')) return 'Backup removed';
if (label.includes('pointer removed')) return 'Pointer removed';
if (label.includes('created removed')) return 'Created file removed';
if (label.includes('backup')) return 'Backup';
if (label.includes('pointer')) return 'Install pointer';
if (label.includes('restored')) return 'Restored from';
if (label.includes('settings') || label.includes('hooks.json') || label.includes('config')) return 'Changed file';
if (label.includes('added hooks')) return 'Hooks added';
if (label.includes('cli path')) return 'CLI path';
return rawLabel.trim().replace(/^\w/, (c) => c.toUpperCase());
};
const hookRecoveryDetail = (result?: { ok: boolean; action: ToolAction }): ActionDetail | null => {
if (!result) return null;
if (!result.ok) {
return {
label: 'Recovery',
value: result.action === 'verify'
? 'Run Install hooks for this tool, then Verify again. If it still fails, use Uninstall hooks to restore the previous config, then reinstall hooks.'
: 'Retry the action. If it repeats, use Uninstall hooks to restore the previous config, then install again.',
tone: 'recovery',
};
}
if (result.action === 'install') {
return {
label: 'Recovery',
value: 'Use Verify to inspect the install, or Uninstall hooks to restore the previous config.',
tone: 'recovery',
};
}
if (result.action === 'uninstall') {
return {
label: 'Recovery',
value: 'Previous hook config was restored, or the Waggle-created config was removed.',
tone: 'recovery',
};
}
return null;
};
const parseHookOutputDetails = (text: string | undefined, stream: 'stdout' | 'stderr'): ActionDetail[] => {
const lines = text?.trim().split(/\r?\n/).map((line) => line.trim()).filter(Boolean) ?? [];
const tone = stream === 'stderr' ? 'attention' : undefined;
return lines
.map((line): ActionDetail | null => {
const check = line.match(/^\[(PASS|FAIL)\]\s+(.+?)(?:\s+(?:\u2014|-)\s+(.+))?$/);
if (check) {
const failed = check[1] === 'FAIL';
const name = check[2].trim();
const detail = check[3]?.trim();
return {
label: failed ? 'Check failed' : 'Check passed',
value: detail ? `${name}: ${detail}` : name,
tone: failed ? 'attention' : tone,
};
}
const labeled = line.match(/^\s*-\s*([^:]+):\s*(.*)$/);
if (labeled) {
return {
label: hookDetailLabel(labeled[1]),
value: labeled[2].trim() || line,
tone,
};
}
if (/backup|backed up/i.test(line)) {
return {
label: 'Backup',
value: line.match(HOOK_PATH_RE)?.[1] ?? line,
tone,
};
}
if (stream === 'stderr') {
return { label: 'Needs attention', value: line, tone: 'attention' };
}
if (
/^hive-mind\/.+:\s/.test(line) ||
/^done\./i.test(line) ||
/^run "/i.test(line) ||
/^all checks passed\.$/i.test(line) ||
/^one or more checks failed\.$/i.test(line)
) {
return null;
}
return { label: 'Output', value: line };
})
.filter((detail): detail is ActionDetail => Boolean(detail));
};
const summarizeHookActionDetails = (details: ActionDetail[]): ActionDetail[] => {
const recoveryDetails = details.filter((detail) => detail.label === 'Recovery');
const outputDetails = details.filter((detail) => detail.label !== 'Recovery');
if (outputDetails.length <= MAX_VISIBLE_HOOK_DETAILS) return details;
const visibleOutput = outputDetails.slice(0, MAX_VISIBLE_HOOK_DETAILS);
const hiddenCount = outputDetails.length - visibleOutput.length;
const hiddenHasAttention = outputDetails
.slice(MAX_VISIBLE_HOOK_DETAILS)
.some((detail) => detail.tone === 'attention');
return [
...visibleOutput,
{
label: 'More output',
value: `${hiddenCount} additional hook output ${hiddenCount === 1 ? 'line' : 'lines'} hidden. Run the hook action from a terminal for full output.`,
tone: hiddenHasAttention ? 'attention' : undefined,
},
...recoveryDetails,
];
};
const hookActionDetails = (
stdout?: string,
stderr?: string,
result?: { ok: boolean; action: ToolAction },
): ActionDetail[] => {
const details = [
...parseHookOutputDetails(stdout, 'stdout'),
...parseHookOutputDetails(stderr, 'stderr'),
];
const recovery = hookRecoveryDetail(result);
if (recovery) {
details.push(recovery);
}
if (!result?.ok && details.length === 1 && recovery) {
details.unshift({
label: 'Needs attention',
value: 'No hook output was returned.',
tone: 'attention',
});
}
return summarizeHookActionDetails(details);
};
const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => { const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: LauncherAppProps = {}) => {
const [view, setView] = useState<LauncherView>('a'); // ADR-0002: Waggle Room is hidden in v1 (memory feature map). Launch, watch
// ADR-0002: agent memory hooks and Waggle Room are hidden in v1 (memory // and stop stay.
// feature map). Launch, watch and stop stay.
const hooksShown = hasMemoryFeature('agentHooks');
const roomShown = hasMemoryFeature('room'); const roomShown = hasMemoryFeature('room');
const cachedDetection = launcherRouteCache.read('tools'); const cachedDetection = launcherRouteCache.read('tools');
const [detection, setDetection] = useState<DetectionResult | null>(cachedDetection ?? null); const [detection, setDetection] = useState<DetectionResult | null>(cachedDetection ?? null);
@@ -435,67 +263,50 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
[pidsByTool], [pidsByTool],
); );
const doAction = useCallback( const launchSelectedTool = useCallback(
async (tool: DetectedTool, action: Exclude<ToolAction, 'run'>) => { async (tool: DetectedTool) => {
const action = 'launch';
setActiveAction({ toolId: tool.id, action }); setActiveAction({ toolId: tool.id, action });
setLastResult(null); setLastResult(null);
try { try {
if (action === 'launch') { if (!tool.installedPath) {
if (!tool.installedPath) {
setLastResult({
toolId: tool.id,
action,
ok: false,
message: 'Tool not installed. Cannot launch.',
});
return;
}
// If a prompt is set AND the tool has a known prompt-arg
// shape, pass it through as CLI args. Otherwise launch
// bare and the prompt textarea is silently ignored for
// that tool.
const args = promptArgsForTool(tool.id, prompt) ?? undefined;
const sendsRawPrompt = !args && tool.acceptsInlinePrompt === true && prompt.trim().length > 0;
const r = await adapter.launchTool({
id: tool.id,
installedPath: tool.installedPath,
workspaceId: activeWorkspaceId,
// Built-in tools send pre-computed args; a third-party adapter gets
// the raw prompt so the server can apply its promptArgTemplate (#5).
...(args ? { args } : (sendsRawPrompt ? { prompt } : {})),
...(watchMode ? { observe: true } : {}),
});
const promptNote = (args || sendsRawPrompt) ? ' with prompt' : '';
setLastResult({ setLastResult({
toolId: tool.id, toolId: tool.id,
action, action,
ok: r.ok, ok: false,
message: r.ok message: 'Tool not installed. Cannot launch.',
? `Launched ${tool.displayName}${promptNote} (pid ${r.pid})`
: (r.error ?? 'Launch failed'),
}); });
// Clear the prompt after a successful launch — avoid sending return;
// the same text twice by accident.
if (r.ok && (args || sendsRawPrompt)) setPrompt('');
// Watch mode (⌘K deep-link): auto-open the live output pane.
if (r.ok && watchMode) setOpenPaneToolId(tool.id);
} else {
const r = await adapter.manageHooks({ id: tool.id, action });
setLastResult({
toolId: tool.id,
action,
ok: r.ok,
message: r.ok
? `${tool.displayName}: ${action} OK`
: (r.error || r.stderr || `${action} failed (exit ${r.code})`),
details: hookActionDetails(r.stdout, r.stderr, { ok: r.ok, action }),
});
// Refresh detection after install/uninstall so hook status
// updates on screen without waiting for user click.
if (action === 'install' || action === 'uninstall') {
await refresh();
}
} }
// If a prompt is set AND the tool has a known prompt-arg
// shape, pass it through as CLI args. Otherwise launch
// bare and the prompt textarea is silently ignored for
// that tool.
const args = promptArgsForTool(tool.id, prompt) ?? undefined;
const sendsRawPrompt = !args && tool.acceptsInlinePrompt === true && prompt.trim().length > 0;
const r = await adapter.launchTool({
id: tool.id,
installedPath: tool.installedPath,
workspaceId: activeWorkspaceId,
// Built-in tools send pre-computed args; a third-party adapter gets
// the raw prompt so the server can apply its promptArgTemplate (#5).
...(args ? { args } : (sendsRawPrompt ? { prompt } : {})),
...(watchMode ? { observe: true } : {}),
});
const promptNote = (args || sendsRawPrompt) ? ' with prompt' : '';
setLastResult({
toolId: tool.id,
action,
ok: r.ok,
message: r.ok
? `Launched ${tool.displayName}${promptNote} (pid ${r.pid})`
: (r.error ?? 'Launch failed'),
});
// Clear the prompt after a successful launch — avoid sending
// the same text twice by accident.
if (r.ok && (args || sendsRawPrompt)) setPrompt('');
// Watch mode (⌘K deep-link): auto-open the live output pane.
if (r.ok && watchMode) setOpenPaneToolId(tool.id);
} catch (err) { } catch (err) {
setLastResult({ setLastResult({
toolId: tool.id, toolId: tool.id,
@@ -507,7 +318,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
setActiveAction(null); setActiveAction(null);
} }
}, },
[activeWorkspaceId, prompt, refresh, watchMode], [activeWorkspaceId, prompt, watchMode],
); );
const tools = useMemo<DetectedTool[]>(() => detection?.tools ?? [], [detection]); const tools = useMemo<DetectedTool[]>(() => detection?.tools ?? [], [detection]);
@@ -590,51 +401,22 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
return ( return (
<div className="flex flex-col h-full bg-background text-foreground"> <div className="flex flex-col h-full bg-background text-foreground">
{/* Header — title + A/B segmented toggle + (Variation A only) refresh */} {/* Header — title + refresh */}
<div className="flex items-center gap-3 px-3 py-2 border-b border-border/50"> <div className="flex items-center gap-3 px-3 py-2 border-b border-border/50">
<div className="flex items-center gap-2"> <div className="flex items-center gap-2">
<Rocket className="w-4 h-4" style={{ color: 'var(--honey)' }} /> <Rocket className="w-4 h-4" style={{ color: 'var(--honey)' }} />
<span className="text-sm font-display font-semibold">Tool Launcher</span> <span className="text-sm font-display font-semibold">Tool Launcher</span>
{view === 'a' && detection && ( {detection && (
<Badge variant="secondary" className="text-[11px] px-1.5 py-0 h-4"> <Badge variant="secondary" className="text-[11px] px-1.5 py-0 h-4">
{detection.platform} {detection.platform}
</Badge> </Badge>
)} )}
</div> </div>
{hooksShown && ( <Button type="button" variant="ghost" size="sm" onClick={refresh} aria-label="Refresh installed tools" className="h-7 w-7 p-0 ml-auto">
<div <RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
role="tablist" </Button>
aria-label="Launcher view"
className="inline-flex gap-1 p-[3px] rounded-[10px]"
style={{ background: 'var(--secondary, hsl(var(--secondary)))', border: '1px solid var(--line-soft)' }}
>
{(['a', 'b'] as LauncherView[]).map((v) => (
<button
key={v}
role="tab"
aria-selected={view === v}
onClick={() => setView(v)}
className={`text-[11.5px] font-display font-semibold px-2.5 py-1 rounded-md transition-colors whitespace-nowrap ${
view === v ? '' : 'text-muted-foreground hover:text-foreground'
}`}
style={view === v ? { background: 'var(--honey)', color: '#1a1407' } : undefined}
>
{v === 'a' ? 'Launch' : 'How memory is shared'}
</button>
))}
</div>
)}
{view === 'a' && (
<Button type="button" variant="ghost" size="sm" onClick={refresh} aria-label="Refresh installed tools" className="h-7 w-7 p-0 ml-auto">
<RefreshCw className={`w-3.5 h-3.5 ${loading ? 'animate-spin' : ''}`} />
</Button>
)}
</div> </div>
{view === 'b' && hooksShown ? (
<MemorySharingView />
) : (
<>
{/* Status bar */} {/* Status bar */}
{error && ( {error && (
<div className="flex items-center gap-2 px-3 py-2 bg-destructive/10 border-b border-destructive/30 text-[12px] text-destructive"> <div className="flex items-center gap-2 px-3 py-2 bg-destructive/10 border-b border-destructive/30 text-[12px] text-destructive">
@@ -670,25 +452,6 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
)} )}
<div className="min-w-0 flex-1"> <div className="min-w-0 flex-1">
<div>{lastResult.message}</div> <div>{lastResult.message}</div>
{lastResult.details?.length ? (
<div className="mt-1.5 space-y-1.5 text-[11px] leading-snug opacity-90">
{lastResult.details.map((detail, index) => (
<div key={`${detail.label}-${detail.value}-${index}`} className="min-w-0">
<div className="font-display text-[10px] font-semibold uppercase tracking-normal opacity-75">
{detail.label}
</div>
<div
className={[
detail.tone === 'recovery' ? 'font-sans' : 'font-mono',
'whitespace-pre-wrap break-all',
].join(' ')}
>
{detail.value}
</div>
</div>
))}
</div>
) : null}
</div> </div>
</div> </div>
)} )}
@@ -753,8 +516,6 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
)} )}
{tools.map((tool) => { {tools.map((tool) => {
const launchable = toolCanLaunch(tool); const launchable = toolCanLaunch(tool);
const hooksSupported = hooksShown && HOOKS_COHORT.includes(tool.id);
const launchOnly = hooksShown && launchable && !hooksSupported;
const isActive = activeAction?.toolId === tool.id; const isActive = activeAction?.toolId === tool.id;
return ( return (
<div <div
@@ -776,16 +537,6 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
Not installed Not installed
</Badge> </Badge>
)} )}
{hooksShown && tool.hooksInstalled && tool.releaseStatus !== 'roadmap' && (
<Badge variant="secondary" className="text-[10px] px-1.5 py-0 h-4" style={{ background: 'var(--honey-wash)', color: 'var(--honey)' }}>
Hooks active
</Badge>
)}
{launchOnly && (
<Badge variant="outline" className="text-[10px] px-1.5 py-0 h-4 text-muted-foreground">
Launch only
</Badge>
)}
{runningTools.has(tool.id) && ( {runningTools.has(tool.id) && (
<button <button
type="button" type="button"
@@ -831,7 +582,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
size="sm" size="sm"
variant="secondary" variant="secondary"
className="h-7 text-[11px]" className="h-7 text-[11px]"
onClick={() => doAction(tool, 'launch')} onClick={() => launchSelectedTool(tool)}
disabled={isActive} disabled={isActive}
> >
{isActive && activeAction?.action === 'launch' ? ( {isActive && activeAction?.action === 'launch' ? (
@@ -871,63 +622,7 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
Stop Stop
</Button> </Button>
)} )}
{hooksSupported && !tool.hooksInstalled && (
<Button
size="sm"
variant="secondary"
className="h-7 text-[11px]"
onClick={() => doAction(tool, 'install')}
disabled={isActive}
>
{isActive && activeAction?.action === 'install' ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Download className="w-3 h-3 mr-1" />
)}
Install hooks
</Button>
)}
{hooksSupported && (
<Button
size="sm"
variant="ghost"
className="h-7 text-[11px]"
onClick={() => doAction(tool, 'verify')}
disabled={isActive}
>
{isActive && activeAction?.action === 'verify' ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<ShieldCheck className="w-3 h-3 mr-1" />
)}
Verify
</Button>
)}
{hooksSupported && tool.hooksInstalled && (
<Button
size="sm"
variant="ghost"
className="h-7 text-[11px]"
style={{ color: 'var(--risk)' }}
onClick={() => doAction(tool, 'uninstall')}
disabled={isActive}
>
{isActive && activeAction?.action === 'uninstall' ? (
<Loader2 className="w-3 h-3 animate-spin mr-1" />
) : (
<Trash2 className="w-3 h-3 mr-1" />
)}
Uninstall hooks
</Button>
)}
</div> </div>
{launchOnly && (
<div className="text-[11px] text-muted-foreground">
{tool.id === 'hermes-desktop'
? 'Hook management is not supported for Hermes Desktop.'
: 'Hook management is not supported for this tool yet.'}
</div>
)}
{roomShown && taskToolId === tool.id && toolCanRunCapturedTask(tool) && ( {roomShown && taskToolId === tool.id && toolCanRunCapturedTask(tool) && (
<div <div
className="rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3" className="rounded-lg border border-primary/30 bg-primary/5 p-3 space-y-3"
@@ -1068,188 +763,8 @@ const LauncherApp = ({ activeWorkspaceId, workspaces = [], onOpenRoom }: Launche
})} })}
</div> </div>
</ScrollArea> </ScrollArea>
</>
)}
</div> </div>
); );
}; };
/**
* Variation B · How memory is shared — a pure-UI explainer. No backend, no
* adapter calls, no live data: a fixed flow diagram + three cards + one
* provenance example, mirroring launcher.html lines 147-181. The provenance
* example string is illustrative (a documentation example, not a real recall),
* so it carries an explicit "example" label — no fabricated live data.
*/
interface FlowNode {
tag: string;
title: string;
detail: React.ReactNode;
hive?: boolean;
}
const FLOW_NODES: readonly FlowNode[] = [
{
tag: 'You launch',
title: 'Claude Code',
detail: (
<>
opened from Waggle with
<br />
<span className="font-mono text-[10.5px]" style={{ color: 'var(--honey)' }}>
WAGGLE_WORKSPACE_ID
</span>
</>
),
},
{
tag: '5 lifecycle hooks',
title: 'hive-mind',
detail: <>session · prompt · stop · compact · tool</>,
},
{
tag: 'Your workspace',
title: 'The hive',
detail: (
<>
local SQLite memory
<br />
shared with Waggle
</>
),
hive: true,
},
];
interface ExplainerCard {
icon: typeof ArrowDownToLine;
title: string;
body: string;
}
const EXPLAINER_CARDS: readonly ExplainerCard[] = [
{
icon: ArrowDownToLine,
title: 'It recalls on start',
body: 'The agent opens already knowing this workspace: decisions, constraints, and context, pulled from the hive.',
},
{
icon: ArrowRight,
title: 'It commits as it works',
body: 'Every meaningful step is captured back into the hive, so Waggle and your next session see it too.',
},
{
icon: ShieldCheckIcon,
title: 'Reversible & local',
body: 'Hooks install and uninstall cleanly. Nothing leaves your machine; you can verify or remove them anytime.',
},
];
const MemorySharingView = () => {
return (
<ScrollArea className="flex-1 min-h-0">
<div className="max-w-[940px] mx-auto px-8 py-8 pb-16">
{/* Heading */}
<header className="mb-6">
<div
className="font-mono text-[11px] uppercase tracking-[0.14em] mb-3 flex items-center gap-2.5"
style={{ color: 'var(--honey)' }}
>
<span className="inline-block w-5 h-px" style={{ background: 'var(--honey-line)' }} aria-hidden="true" />
How memory is shared
</div>
<h1 className="text-[26px] font-display font-semibold tracking-tight leading-tight m-0 mb-2.5 text-foreground">
How a launched agent shares the hive
</h1>
<p className="text-[15px] text-muted-foreground leading-relaxed m-0 max-w-[64ch]">
When you launch from Waggle, the workspace&apos;s memory is wired into the external tool. No copy-paste, no
re-explaining. Its work comes back <b className="text-foreground font-medium">attributed</b>.
</p>
</header>
{/* Flow diagram + cards + provenance example */}
<div
className="rounded-2xl px-8 py-9 text-center"
style={{
border: '1px solid var(--line)',
background: 'radial-gradient(70% 90% at 50% 0%, var(--secondary, hsl(var(--secondary))), var(--bg-2))',
}}
>
{/* Flow row */}
<div className="flex items-center justify-center flex-wrap gap-y-3">
{FLOW_NODES.map((node, i) => (
<div key={node.title} className="flex items-center">
<div
className="rounded-xl px-4 py-4 min-w-[140px] max-w-[184px] text-left"
style={
node.hive
? {
border: '1px solid var(--honey-line)',
boxShadow: 'var(--honey-glow)',
background: 'linear-gradient(150deg, var(--secondary, hsl(var(--secondary))), var(--card, hsl(var(--card))))',
}
: { border: '1px solid var(--line-strong)', background: 'var(--card, hsl(var(--card)))' }
}
>
<div className="font-mono text-[9.5px] uppercase tracking-[0.12em] mb-1.5 text-[var(--text-tertiary)]">
{node.tag}
</div>
<div className="text-sm font-display font-semibold text-foreground">{node.title}</div>
<div className="text-[11.5px] text-muted-foreground mt-1 leading-snug">{node.detail}</div>
</div>
{i < FLOW_NODES.length - 1 && (
<div className="px-3 text-center shrink-0" style={{ color: 'var(--honey)' }} aria-hidden="true">
<ArrowRight className="w-5 h-5 mx-auto" />
<span className="block font-mono text-[9px] uppercase tracking-[0.1em] text-[var(--text-tertiary)]">
{i === 0 ? 'hooks' : 'recall + commit'}
</span>
</div>
)}
</div>
))}
</div>
{/* Three explainer cards */}
<div className="grid grid-cols-1 sm:grid-cols-3 gap-3.5 mt-7 text-left">
{EXPLAINER_CARDS.map((card) => {
const Icon = card.icon;
return (
<div
key={card.title}
className="rounded-xl p-4"
style={{ background: 'var(--card, hsl(var(--card)))', border: '1px solid var(--line-soft)' }}
>
<Icon className="w-[17px] h-[17px] mb-2.5" style={{ color: 'var(--honey)' }} aria-hidden="true" />
<b className="text-[13.5px] font-display font-semibold block mb-1.5 text-foreground">{card.title}</b>
<p className="m-0 text-[12.5px] text-muted-foreground leading-relaxed">{card.body}</p>
</div>
);
})}
</div>
{/* Provenance example — illustrative, explicitly labelled */}
<div
className="mt-5 inline-flex items-center gap-2 font-mono text-[11.5px] px-3 py-1.5 rounded-lg"
style={{
color: 'var(--intel)',
background: 'var(--intel-wash)',
border: '1px solid color-mix(in srgb, var(--intel) 28%, transparent)',
}}
title="Illustrative example of how a recall is attributed"
>
<Hexagon className="w-3.5 h-3.5" aria-hidden="true" />
<span>example · remembered from Claude Code · 14:22 · session a1f9</span>
</div>
</div>
<div className="mt-4 flex items-center gap-2 text-[12px] text-muted-foreground">
<Workflow className="w-3.5 h-3.5 shrink-0" aria-hidden="true" />
<span>This is how the wiring works. Switch to <b className="text-foreground/90 font-medium">Launch</b> to open an agent into this workspace.</span>
</div>
</div>
</ScrollArea>
);
};
export default LauncherApp; export default LauncherApp;

View File

@@ -10,14 +10,12 @@ interface MissionControlAppProps {
/** /**
* AI-OS Phase 4 polish — compact inventory of installed AI tools at * AI-OS Phase 4 polish — compact inventory of installed AI tools at
* the top of Mission Control. One line: detected · installed · * the top of Mission Control. One line: detected · installed counts,
* hook-wired counts, with an "Open Launcher" button to jump to the * with an "Open Launcher" button to jump to the dedicated dock app.
* dedicated dock app.
*/ */
interface ToolInventoryCounts { interface ToolInventoryCounts {
detected: number; detected: number;
installed: number; installed: number;
hooked: number;
} }
const MissionControlApp = ({ onSpawnOpen }: MissionControlAppProps) => { const MissionControlApp = ({ onSpawnOpen }: MissionControlAppProps) => {
@@ -43,7 +41,6 @@ const MissionControlApp = ({ onSpawnOpen }: MissionControlAppProps) => {
setToolCounts({ setToolCounts({
detected: ts.length, detected: ts.length,
installed: ts.filter((t) => t.installed).length, installed: ts.filter((t) => t.installed).length,
hooked: ts.filter((t) => t.hooksInstalled).length,
}); });
} }
if (fleet.status === 'rejected') { if (fleet.status === 'rejected') {
@@ -104,8 +101,7 @@ const MissionControlApp = ({ onSpawnOpen }: MissionControlAppProps) => {
<Rocket className="w-3.5 h-3.5 text-amber-400 flex-shrink-0" /> <Rocket className="w-3.5 h-3.5 text-amber-400 flex-shrink-0" />
<span className="text-muted-foreground"> <span className="text-muted-foreground">
<span className="text-foreground font-medium">{toolCounts.detected}</span> tools known ·{' '} <span className="text-foreground font-medium">{toolCounts.detected}</span> tools known ·{' '}
<span className="text-emerald-400 font-medium">{toolCounts.installed}</span> installed ·{' '} <span className="text-emerald-400 font-medium">{toolCounts.installed}</span> installed
<span className="text-amber-300 font-medium">{toolCounts.hooked}</span> hook-wired
</span> </span>
<div className="flex-1" /> <div className="flex-1" />
<Button <Button

View File

@@ -955,35 +955,6 @@ describe('P1b auth gate', () => {
await expect(call(a)).rejects.toThrow(AdapterHttpError); await expect(call(a)).rejects.toThrow(AdapterHttpError);
}); });
it('manageHooks maps a non-2xx body into the { ok:false, stderr, code } envelope (not a throw)', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tools/hooks', () => jsonRes({ ok: false, action: 'install', stdout: '', stderr: 'permission denied', code: 1, error: 'install failed' }, 500)]]);
await expect(a.manageHooks({ id: 'claude-code', action: 'install' })).resolves.toMatchObject({
ok: false, stderr: 'permission denied', code: 1, error: 'install failed',
});
});
it('manageHooks preserves a structured hook failure without replacing it with HTTP status text', async () => {
const a = new LocalAdapter(BASE);
routeMock(fetchSpy, [['/api/tools/hooks', () => jsonRes({
ok: false,
action: 'verify',
packageName: '@waggle/hive-mind-hooks-claude-code',
stdout: '',
stderr: '',
code: 1,
}, 400)]]);
await expect(a.manageHooks({ id: 'claude-code', action: 'verify' })).resolves.toMatchObject({
ok: false,
action: 'verify',
stdout: '',
stderr: '',
code: 1,
error: undefined,
});
});
// ── Watchdog recovery + setServerUrl memo hygiene (review fixes) ───────── // ── Watchdog recovery + setServerUrl memo hygiene (review fixes) ─────────
it('after a hung-body timeout, the NEXT connect probes fresh (memo does not wedge re-arms)', async () => { it('after a hung-body timeout, the NEXT connect probes fresh (memo does not wedge re-arms)', async () => {

View File

@@ -3165,7 +3165,7 @@ class LocalAdapter {
}; };
// --- AI-OS launcher (Phase 2B) --- // --- AI-OS launcher (Phase 2B) ---
// detectTools/launchTool/manageHooks each surface the matching // detectTools/launchTool each surface the matching
// sidecar route. All are loopback-only and report only the user's // sidecar route. All are loopback-only and report only the user's
// own machine — no remote calls. // own machine — no remote calls.
@@ -3286,38 +3286,6 @@ class LocalAdapter {
}; };
} }
async manageHooks(payload: {
id: string;
action: 'install' | 'verify' | 'uninstall';
cliPath?: string;
}): Promise<{
ok: boolean;
action: string;
stdout: string;
stderr: string;
code: number;
error?: string;
}> {
// P1b D3: fetchRaw — hook-failure diagnostics (stderr/exit code) ride the error body.
const res = await this.fetchRaw('/api/tools/hooks', {
method: 'POST',
body: JSON.stringify(payload),
});
const body = await res.json().catch(() => ({}));
const hasHookEnvelope =
typeof body.ok === 'boolean' &&
typeof body.action === 'string' &&
typeof body.code === 'number';
return {
ok: res.ok && body.ok === true,
action: body.action ?? payload.action,
stdout: body.stdout ?? '',
stderr: body.stderr ?? '',
code: body.code ?? -1,
error: body.error ?? (res.ok || hasHookEnvelope ? undefined : `HTTP ${res.status}`),
};
}
/** /**
* P1b-SSE: shared EventSource lifecycle — token-attached, lazy-open, * P1b-SSE: shared EventSource lifecycle — token-attached, lazy-open,
* reconnecting. Fixes the three defects that made every stream dead in * reconnecting. Fixes the three defects that made every stream dead in

View File

@@ -6,7 +6,6 @@ import {
Lock, Activity, History, BarChart3, Users, Radio, Lock, Activity, History, BarChart3, Users, Radio,
Gauge, Monitor, LayoutGrid, Eye, Gauge, Monitor, LayoutGrid, Eye,
} from "lucide-react"; } from "lucide-react";
import { hasMemoryFeature } from "@/lib/memory-features";
/** /**
* Curated ⌘K catalog (design ref: design-files/screens/ia.html). * Curated ⌘K catalog (design ref: design-files/screens/ia.html).
@@ -67,7 +66,7 @@ export function buildCommandCatalog(ctx: CatalogContext): CatalogGroup[] {
const doGroup: CatalogCommand[] = [ const doGroup: CatalogCommand[] = [
{ id: "start-task", group: "do", name: "Start a task", subtitle: "new agent run", icon: Plus, action: "spawn" }, { id: "start-task", group: "do", name: "Start a task", subtitle: "new agent run", icon: Plus, action: "spawn" },
{ id: "launch-agent", group: "do", name: "Launch a coding agent", subtitle: hasMemoryFeature("agentHooks") ? "Claude Code · Cursor · Codex, sharing this hive" : "Claude Code · Cursor · Codex", icon: Rocket, to: "/launcher" }, { id: "launch-agent", group: "do", name: "Launch a coding agent", subtitle: "Claude Code · Cursor · Codex", icon: Rocket, to: "/launcher" },
{ id: "watch-agent", group: "do", name: "Watch a coding agent live", subtitle: "Claude Code · Cursor · Codex, live output", keywords: "observe pty terminal live output tail", icon: Eye, to: "/launcher?watch=1" }, { id: "watch-agent", group: "do", name: "Watch a coding agent live", subtitle: "Claude Code · Cursor · Codex, live output", keywords: "observe pty terminal live output tail", icon: Eye, to: "/launcher?watch=1" },
{ id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" }, { id: "settings", group: "do", name: "Settings", subtitle: "models · failover · permissions", icon: Settings, to: "/settings" },
]; ];

View File

@@ -3,10 +3,10 @@
* *
* v1 memory is facts, search and the user profile. The knowledge graph follows * v1 memory is facts, search and the user profile. The knowledge graph follows
* the server's memory capability map (`GET /api/memory/capabilities`), which * the server's memory capability map (`GET /api/memory/capabilities`), which
* reports it unavailable in v1. History import, wiki, coding-agent hooks, Room * reports it unavailable in v1. History import, wiki and Room are hidden in v1
* and the memory MCP server are hidden in v1 by decision, whatever the store * by decision, whatever the store supports. Their screens stay in the code and
* supports. Their screens stay in the code and every surface that offers one * every surface that offers one checks this module first. Coding-agent hooks
* checks this module first. * and the memory MCP server left with their packages (P2.2).
*/ */
import { useEffect, useSyncExternalStore } from 'react'; import { useEffect, useSyncExternalStore } from 'react';
import { adapter } from '@/lib/adapter'; import { adapter } from '@/lib/adapter';
@@ -19,12 +19,8 @@ export interface MemoryFeatures {
importHistory: boolean; importHistory: boolean;
/** Compiled wiki pages. */ /** Compiled wiki pages. */
wiki: boolean; wiki: boolean;
/** Memory hooks installed into Claude Code, Codex and other coding agents. */
agentHooks: boolean;
/** Waggle Room: coding agents started as a team that shares one Room. */ /** Waggle Room: coding agents started as a team that shares one Room. */
room: boolean; room: boolean;
/** The Waggle memory MCP server for other clients. */
memoryMcp: boolean;
} }
export type MemoryFeature = keyof MemoryFeatures; export type MemoryFeature = keyof MemoryFeatures;
@@ -33,9 +29,7 @@ export type MemoryFeature = keyof MemoryFeatures;
const HIDDEN_IN_V1: Readonly<Record<Exclude<MemoryFeature, 'knowledgeGraph'>, false>> = { const HIDDEN_IN_V1: Readonly<Record<Exclude<MemoryFeature, 'knowledgeGraph'>, false>> = {
importHistory: false, importHistory: false,
wiki: false, wiki: false,
agentHooks: false,
room: false, room: false,
memoryMcp: false,
}; };
let current: MemoryCapabilitiesResponse | null = null; let current: MemoryCapabilitiesResponse | null = null;

View File

@@ -6,7 +6,6 @@ const mocks = vi.hoisted(() => ({
detectTools: vi.fn(), detectTools: vi.fn(),
getToolProcesses: vi.fn(), getToolProcesses: vi.fn(),
launchTool: vi.fn(), launchTool: vi.fn(),
manageHooks: vi.fn(),
killTool: vi.fn(), killTool: vi.fn(),
}, },
})); }));

View File

@@ -40,7 +40,7 @@ afterEach(() => {
}); });
describe('memory feature map (v1 defaults)', () => { describe('memory feature map (v1 defaults)', () => {
it.each<MemoryFeature>(['knowledgeGraph', 'importHistory', 'wiki', 'agentHooks', 'room', 'memoryMcp'])( it.each<MemoryFeature>(['knowledgeGraph', 'importHistory', 'wiki', 'room'])(
'%s is hidden', '%s is hidden',
(feature) => { (feature) => {
expect(hasMemoryFeature(feature)).toBe(false); expect(hasMemoryFeature(feature)).toBe(false);
@@ -68,7 +68,7 @@ describe('memory feature map from the server capabilities', () => {
it('keeps import, wiki, hooks, Room and the memory MCP hidden whatever the store reports', () => { it('keeps import, wiki, hooks, Room and the memory MCP hidden whatever the store reports', () => {
setMemoryCapabilities(report(true)); setMemoryCapabilities(report(true));
for (const feature of ['importHistory', 'wiki', 'agentHooks', 'room', 'memoryMcp'] as const) { for (const feature of ['importHistory', 'wiki', 'room'] as const) {
expect(hasMemoryFeature(feature), feature).toBe(false); expect(hasMemoryFeature(feature), feature).toBe(false);
} }
}); });

View File

@@ -32,11 +32,11 @@ const WAGGLE_ENV_ALLOWLIST = new Set([
'WAGGLE_DANCE_TEAM_ID', 'WAGGLE_DANCE_URL', 'WAGGLE_RUN_TOKEN', 'WAGGLE_DANCE_TEAM_ID', 'WAGGLE_DANCE_URL', 'WAGGLE_RUN_TOKEN',
'WAGGLE_CLI_NODE_PATH', 'WAGGLE_CLI_ENTRY', 'WAGGLE_CLI_NODE_PATH', 'WAGGLE_CLI_ENTRY',
'WAGGLE_SIGNAL_EMIT', 'WAGGLE_SIDECAR_URL', '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 * Provider keys, credential helpers, proxy credentials, infrastructure
* secrets, and arbitrary ambient variables are never inherited. The caller * secrets, and arbitrary ambient variables are never inherited. The caller
* may add only the narrow Waggle metadata enumerated above. * may add only the narrow Waggle metadata enumerated above.

View File

@@ -457,18 +457,11 @@ export {
} from './tool-detection.js'; } from './tool-detection.js';
export { export {
launchTool, launchTool,
runHookCommand,
hookPackageFor,
resolveHookRuntime,
resolveWaggleRuntime, resolveWaggleRuntime,
type ToolLauncherDeps, type ToolLauncherDeps,
type LaunchOptions, type LaunchOptions,
type LaunchResult, type LaunchResult,
type ObservedHandle, type ObservedHandle,
type HookAction,
type HookCommandOptions,
type HookCommandResult,
type HookRuntimePaths,
type WaggleRuntimePaths, type WaggleRuntimePaths,
} from './tool-launcher.js'; } from './tool-launcher.js';
export { spawnSidecarOwnedProcess } from './sidecar-owned-process.js'; export { spawnSidecarOwnedProcess } from './sidecar-owned-process.js';

View File

@@ -2,12 +2,11 @@
* Tool detection — AI-OS Phase 0. * Tool detection — AI-OS Phase 0.
* *
* Detects which external AI tools (Claude Code, Cursor, Claude Desktop, …) * Detects which external AI tools (Claude Code, Cursor, Claude Desktop, …)
* are installed on the user's machine and whether their hive-mind hooks * are installed on the user's machine. Returns a stable envelope
* are wired up. Returns a stable envelope (`ToolDetectionResult` in * (`ToolDetectionResult` in @waggle/shared) consumed by:
* @waggle/shared) consumed by:
* *
* - the sidecar route GET /api/tools/detect (Phase 0) * - 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) * - the Mission Control inventory tile (Phase 4)
* *
* Design notes: * Design notes:
@@ -20,17 +19,12 @@
* resolves like `which`; on Windows like `where`. The shim takes * resolves like `which`; on Windows like `where`. The shim takes
* a logical name ('claude'), not a full path, so callers don't * a logical name ('claude'), not a full path, so callers don't
* need to know the per-platform extension (.cmd / .exe / none). * need to know the per-platform extension (.cmd / .exe / none).
* 3. Hook-install status follows the hive-mind shim-core convention: * 3. Detector functions are pure (`(deps) => Promise<DetectedTool>`)
* `~/<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>`)
* so they can be unit-tested individually and composed in parallel * so they can be unit-tested individually and composed in parallel
* by the orchestrator. * 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 { homedir, platform as osPlatform } from 'node:os';
import { posix as pathPosix, win32 as pathWin32 } from 'node:path'; import { posix as pathPosix, win32 as pathWin32 } from 'node:path';
import { execFile } from 'node:child_process'; import { execFile } from 'node:child_process';
@@ -126,11 +120,6 @@ export interface ToolDetectionDeps {
* top — `null` here means "could not determine". * top — `null` here means "could not determine".
*/ */
execVersion?: (binary: string, args: string[]) => Promise<string | null>; 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 * PATH lookup shim. Given a logical binary name ('claude'), returns
* the resolved absolute path or null. Production implementation uses * 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 * Env for the `which`/`where` lookup. Fail closed to the non-secret external
* process environment. On POSIX, merge the resolved login-shell * process environment. On POSIX, merge the resolved login-shell
@@ -310,7 +290,6 @@ interface ResolvedDeps {
cwd: string; cwd: string;
exists: (p: string) => Promise<boolean>; exists: (p: string) => Promise<boolean>;
execVersion: (binary: string, args: string[]) => Promise<string | null>; execVersion: (binary: string, args: string[]) => Promise<string | null>;
readJson: (p: string) => Promise<unknown>;
pathFromEnv: (name: string) => Promise<string | null>; pathFromEnv: (name: string) => Promise<string | null>;
windowsAppExecutables: () => Promise<WindowsAppExecutables>; windowsAppExecutables: () => Promise<WindowsAppExecutables>;
} }
@@ -325,7 +304,6 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
cwd: opts.cwd ?? process.cwd(), cwd: opts.cwd ?? process.cwd(),
exists: opts.exists ?? defaultExists, exists: opts.exists ?? defaultExists,
execVersion: opts.execVersion ?? defaultExecVersion, execVersion: opts.execVersion ?? defaultExecVersion,
readJson: opts.readJson ?? defaultReadJson,
pathFromEnv: pathFromEnv:
pathFromEnvOpt === undefined pathFromEnvOpt === undefined
? defaultPathFromEnv ? defaultPathFromEnv
@@ -342,140 +320,7 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
}; };
} }
// ── Hook status (shared across all tools) ─────────────────────────── // ── Platform roots ──────────────────────────────────────────────────
// 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);
}
function nonBlankEnv(deps: ResolvedDeps, name: string): string | null { function nonBlankEnv(deps: ResolvedDeps, name: string): string | null {
const value = deps.env[name]?.trim(); const value = deps.env[name]?.trim();
@@ -499,54 +344,6 @@ function hermesHome(deps: ResolvedDeps): string {
: joinForPlatform(deps.platform, deps.home, '.hermes'); : 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 ────────────────────────────────────────────── // ── Per-tool detectors ──────────────────────────────────────────────
/** /**
@@ -562,9 +359,7 @@ async function detectByPath(
id: string, id: string,
binaryName: string, binaryName: string,
deps: ResolvedDeps, deps: ResolvedDeps,
hookPointer: string,
displayName: string, displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> { ): Promise<DetectedTool> {
const base: DetectedTool = { const base: DetectedTool = {
id, id,
@@ -572,16 +367,11 @@ async function detectByPath(
installed: false, installed: false,
installedPath: null, installedPath: null,
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
}; };
const resolved = await deps.pathFromEnv(binaryName); const resolved = await deps.pathFromEnv(binaryName);
if (!resolved) return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) }; if (!resolved) return base;
if (!(await deps.exists(resolved))) { if (!(await deps.exists(resolved))) return base;
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
}
const versionRaw = await deps.execVersion(resolved, ['--version']); const versionRaw = await deps.execVersion(resolved, ['--version']);
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
const blockedWindowsAppsCodex = const blockedWindowsAppsCodex =
versionRaw === null && isBlockedWindowsAppsCodexPath(id, deps.platform, resolved); versionRaw === null && isBlockedWindowsAppsCodexPath(id, deps.platform, resolved);
return { return {
@@ -593,7 +383,6 @@ async function detectByPath(
diagnostic: blockedWindowsAppsCodex diagnostic: blockedWindowsAppsCodex
? CODEX_WINDOWS_APPS_DIAGNOSTIC ? CODEX_WINDOWS_APPS_DIAGNOSTIC
: versionRaw ? undefined : '--version exec failed', : versionRaw ? undefined : '--version exec failed',
...hookProbe,
}; };
} }
@@ -609,9 +398,7 @@ function hermesWindowsCandidatePaths(deps: ResolvedDeps): string[] {
async function detectHealthyWindowsHermes( async function detectHealthyWindowsHermes(
binaryName: string, binaryName: string,
deps: ResolvedDeps, deps: ResolvedDeps,
hookPointer: string,
displayName: string, displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> { ): Promise<DetectedTool> {
const pathCandidate = await deps.pathFromEnv(binaryName); const pathCandidate = await deps.pathFromEnv(binaryName);
const candidates = [pathCandidate, ...hermesWindowsCandidatePaths(deps)] const candidates = [pathCandidate, ...hermesWindowsCandidatePaths(deps)]
@@ -631,7 +418,6 @@ async function detectHealthyWindowsHermes(
installed: true, installed: true,
installedPath: candidate, installedPath: candidate,
version, version,
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
}; };
} }
} }
@@ -644,7 +430,6 @@ async function detectHealthyWindowsHermes(
version: null, version: null,
launchable: firstExisting ? false : undefined, launchable: firstExisting ? false : undefined,
diagnostic: firstExisting ? HERMES_WINDOWS_HEALTH_DIAGNOSTIC : undefined, diagnostic: firstExisting ? HERMES_WINDOWS_HEALTH_DIAGNOSTIC : undefined,
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
}; };
} }
@@ -750,9 +535,7 @@ async function detectByCandidates(
candidates: string[], candidates: string[],
deps: ResolvedDeps, deps: ResolvedDeps,
withVersion: boolean, withVersion: boolean,
hookPointer: string,
displayName: string, displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> { ): Promise<DetectedTool> {
const base: DetectedTool = { const base: DetectedTool = {
id, id,
@@ -760,15 +543,12 @@ async function detectByCandidates(
installed: false, installed: false,
installedPath: null, installedPath: null,
version: null, version: null,
hooksInstalled: false,
hookPointerPath: null,
}; };
for (const candidate of candidates) { for (const candidate of candidates) {
if (await deps.exists(candidate)) { if (await deps.exists(candidate)) {
const versionRaw = withVersion const versionRaw = withVersion
? await deps.execVersion(candidate, ['--version']) ? await deps.execVersion(candidate, ['--version'])
: null; : null;
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
return { return {
...base, ...base,
installed: true, installed: true,
@@ -776,11 +556,10 @@ async function detectByCandidates(
version: versionRaw, version: versionRaw,
diagnostic: diagnostic:
withVersion && versionRaw === null ? '--version exec failed' : undefined, withVersion && versionRaw === null ? '--version exec failed' : undefined,
...hookProbe,
}; };
} }
} }
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) }; return base;
} }
// ── Registry-driven detection ─────────────────────────────────────── // ── Registry-driven detection ───────────────────────────────────────
@@ -802,7 +581,6 @@ function withManifestMetadata(tool: DetectedTool, manifest: ToolManifest): Detec
...tool, ...tool,
releaseStatus: manifest.releaseStatus, releaseStatus: manifest.releaseStatus,
launchable: tool.launchable ?? manifest.launchable, launchable: tool.launchable ?? manifest.launchable,
hookCapable: manifest.hookCapable,
builtin: manifest.builtin === true, builtin: manifest.builtin === true,
acceptsInlinePrompt: Boolean(manifest.promptArgTemplate?.length), acceptsInlinePrompt: Boolean(manifest.promptArgTemplate?.length),
capabilities: manifest.capabilities, capabilities: manifest.capabilities,
@@ -815,18 +593,12 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
if (m.detect.kind === 'path') { if (m.detect.kind === 'path') {
if (m.id === 'hermes' && deps.platform === 'win32') { if (m.id === 'hermes' && deps.platform === 'win32') {
return withManifestMetadata( return withManifestMetadata(
await detectHealthyWindowsHermes( await detectHealthyWindowsHermes(m.detect.binaryName, deps, m.displayName),
m.detect.binaryName,
deps,
m.hookPointer,
m.displayName,
m.hookRoot,
),
m, m,
); );
} }
return withManifestMetadata( 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, m,
); );
} }
@@ -838,9 +610,7 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
candidates, candidates,
deps, deps,
/* withVersion */ false, /* withVersion */ false,
m.hookPointer,
m.displayName, m.displayName,
m.hookRoot,
), ),
m, m,
); );

View File

@@ -2,16 +2,13 @@
* AI-OS Phase 2A — tool launcher module. * AI-OS Phase 2A — tool launcher module.
* *
* Spawns external AI tools (Claude Code, Cursor, Claude Desktop, …) * Spawns external AI tools (Claude Code, Cursor, Claude Desktop, …)
* with workspace-context injection, and invokes the hive-mind hook * with workspace-context injection.
* installers (`npx @waggle/hive-mind-hooks-<tool> [install|verify|
* uninstall]`).
* *
* Design parallels `tool-detection.ts`: * Design parallels `tool-detection.ts`:
* - All process spawns go through injectable deps so tests are * - All process spawns go through injectable deps so tests are
* hermetic (no actual binaries launched). * hermetic (no actual binaries launched).
* - Production defaults use Node `child_process.spawn` (detached * - Production defaults use Node `child_process.spawn` (detached
* for launch, non-detached for the synchronous installer * launch, or piped stdio for observed launches).
* commands).
* - Cross-platform: the candidate-path resolution + workspace * - Cross-platform: the candidate-path resolution + workspace
* env conventions mirror what `tool-detection.ts` reports, so * env conventions mirror what `tool-detection.ts` reports, so
* the launch path comes from the detection result whenever * the launch path comes from the detection result whenever
@@ -23,30 +20,18 @@
* Spawn the tool detached. Returns the spawned PID + cwd or * Spawn the tool detached. Returns the spawned PID + cwd or
* an error reason. * 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: * Phase 2A scope:
* - Backend module + sidecar routes only. Frontend dock in 2B. * - Backend module + sidecar routes only. Frontend dock in 2B.
* - Launch is registry-validated: all built-ins plus launchable * - Launch is registry-validated: all built-ins plus launchable
* third-party adapters may be launched when the caller supplies the * third-party adapters may be launched when the caller supplies the
* runtime registry. * 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 { existsSync } from 'node:fs';
import { delimiter, dirname, join, resolve } from 'node:path'; import { delimiter, dirname, join, resolve } from 'node:path';
import { fileURLToPath } from 'node:url'; import { fileURLToPath } from 'node:url';
import { promisify } from 'node:util'; import type { ToolManifest } from '@waggle/shared';
import type { ToolId, ToolManifest } from '@waggle/shared';
import { BUILTIN_TOOL_MANIFESTS } from '@waggle/shared'; import { BUILTIN_TOOL_MANIFESTS } from '@waggle/shared';
import { import {
resolveToolCommandInvocation, resolveToolCommandInvocation,
@@ -58,19 +43,6 @@ import {
spawnSidecarOwnedProcess, spawnSidecarOwnedProcess,
} from './sidecar-owned-process.js'; } 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 ───────────────────────────────────────────────── // ── Injectable deps ─────────────────────────────────────────────────
/** Minimal, test-injectable view of a live observed process. */ /** Minimal, test-injectable view of a live observed process. */
@@ -109,15 +81,6 @@ export interface ToolLauncherDeps {
args: string[], args: string[],
options: { cwd?: string; env?: NodeJS.ProcessEnv }, options: { cwd?: string; env?: NodeJS.ProcessEnv },
) => { pid: number | null; error?: string; handle?: ObservedHandle }; ) => { 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 ──────────────────────────────────────────────────── // ── Default deps ────────────────────────────────────────────────────
@@ -208,42 +171,11 @@ export function resolveSpawnInvocation(
return resolveToolCommandInvocation(binary, args, platform); 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 { interface ResolvedDeps {
platform: NodeJS.Platform; platform: NodeJS.Platform;
baseEnv: NodeJS.ProcessEnv; baseEnv: NodeJS.ProcessEnv;
spawnDetached: NonNullable<ToolLauncherDeps['spawnDetached']>; spawnDetached: NonNullable<ToolLauncherDeps['spawnDetached']>;
spawnObserved: NonNullable<ToolLauncherDeps['spawnObserved']>; spawnObserved: NonNullable<ToolLauncherDeps['spawnObserved']>;
execCapture: NonNullable<ToolLauncherDeps['execCapture']>;
} }
function resolveDeps(opts: ToolLauncherDeps): ResolvedDeps { function resolveDeps(opts: ToolLauncherDeps): ResolvedDeps {
@@ -252,7 +184,6 @@ function resolveDeps(opts: ToolLauncherDeps): ResolvedDeps {
baseEnv: opts.baseEnv ?? process.env, baseEnv: opts.baseEnv ?? process.env,
spawnDetached: opts.spawnDetached ?? defaultSpawnDetached, spawnDetached: opts.spawnDetached ?? defaultSpawnDetached,
spawnObserved: opts.spawnObserved ?? defaultSpawnObserved, spawnObserved: opts.spawnObserved ?? defaultSpawnObserved,
execCapture: opts.execCapture ?? defaultExecCapture,
}; };
} }
@@ -418,40 +349,7 @@ export function launchTool(opts: LaunchOptions): LaunchResult {
}; };
} }
// ── Hook installer surface ────────────────────────────────────────── // ── Packaged collaboration CLI ──────────────────────────────────────
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;
}
export interface WaggleRuntimePaths { export interface WaggleRuntimePaths {
nodePath: string; nodePath: string;
@@ -464,42 +362,6 @@ interface RuntimeResolveDeps {
fileExists?: (path: string) => boolean; 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 { export function resolveWaggleRuntime(deps: RuntimeResolveDeps = {}): WaggleRuntimePaths | undefined {
const fileExists = deps.fileExists ?? existsSync; const fileExists = deps.fileExists ?? existsSync;
for (const root of runtimeNodeModulesRoots(deps.nodeModulesRoots)) { for (const root of runtimeNodeModulesRoots(deps.nodeModulesRoots)) {
@@ -518,73 +380,3 @@ function runtimeNodeModulesRoots(explicit?: string[]): string[] {
]; ];
return [...new Set(roots.map((candidate) => resolve(candidate)))]; 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,
};
}

View File

@@ -16,8 +16,6 @@ import type {
ToolTaskSpec, ToolTaskSpec,
} from '@waggle/shared'; } 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). // No path separators — for ids and binary names (PATH lookup).
const NAME_SAFE = /^[A-Za-z0-9._-]+$/; const NAME_SAFE = /^[A-Za-z0-9._-]+$/;
const TASK_PLACEHOLDERS = new Set([ const TASK_PLACEHOLDERS = new Set([
@@ -89,14 +87,12 @@ function validate(raw: unknown): ToolManifest | null {
if (!raw || typeof raw !== 'object') return null; if (!raw || typeof raw !== 'object') return null;
const o = raw as Record<string, unknown>; const o = raw as Record<string, unknown>;
const allowedKeys = new Set([ const allowedKeys = new Set([
'id', 'displayName', 'launchable', 'hookCapable', 'hookPointer', 'detect', 'id', 'displayName', 'launchable', 'detect', 'promptArgTemplate', 'task',
'promptArgTemplate', 'task',
]); ]);
if (Object.keys(o).some((key) => !allowedKeys.has(key))) return null; if (Object.keys(o).some((key) => !allowedKeys.has(key))) return null;
if (!safeStr(o.id, 64, NAME_SAFE)) 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.displayName !== 'string' || o.displayName.length < 1 || o.displayName.length > 80) return null;
if (typeof o.launchable !== 'boolean' || typeof o.hookCapable !== 'boolean') return null; if (typeof o.launchable !== 'boolean') return null;
if (!safeStr(o.hookPointer, 256, PATH_SAFE)) return null;
const d = o.detect as Record<string, unknown> | undefined; const d = o.detect as Record<string, unknown> | undefined;
// Third-party adapters may ONLY declare PATH detection (candidates = code-only). // Third-party adapters may ONLY declare PATH detection (candidates = code-only).
if (!d || d.kind !== 'path' || !safeStr(d.binaryName, 128, NAME_SAFE)) return null; 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, id: o.id as string,
displayName: o.displayName, displayName: o.displayName,
launchable: o.launchable, launchable: o.launchable,
hookCapable: o.hookCapable,
hookPointer: o.hookPointer as string,
detect: { kind: 'path', binaryName: d.binaryName as string }, detect: { kind: 'path', binaryName: d.binaryName as string },
...(promptArgTemplate ? { promptArgTemplate } : {}), ...(promptArgTemplate ? { promptArgTemplate } : {}),
capabilities: { capabilities: {

View File

@@ -767,8 +767,8 @@ describe('external adapter safety', () => {
it('loads only data-only generic task specs with known placeholders', () => { it('loads only data-only generic task specs with known placeholders', () => {
const base = { const base = {
id: 'safe-cli', displayName: 'Safe', launchable: true, hookCapable: false, id: 'safe-cli', displayName: 'Safe', launchable: true,
hookPointer: '.safe/hm.json', detect: { kind: 'path', binaryName: 'safe' }, detect: { kind: 'path', binaryName: 'safe' },
}; };
const deps = (value: unknown) => ({ const deps = (value: unknown) => ({
dir: '/fake', readDir: () => ['adapter.json'], readFile: () => JSON.stringify(value), 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". * 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. * simulate specific tools being installed.
*/ */
function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts { function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts {
@@ -32,10 +32,9 @@ function makeDeps(overrides: Partial<DetectOpts> = {}): DetectOpts {
platform: 'win32', platform: 'win32',
home: 'C:\\Users\\test', home: 'C:\\Users\\test',
env: {}, env: {},
cwd: 'D:\\projects\\waggle-os', cwd: 'C:\\work\\waggle',
exists: async () => false, exists: async () => false,
execVersion: async () => null, execVersion: async () => null,
readJson: async () => null,
pathFromEnv: () => null, pathFromEnv: () => null,
windowsAppExecutables: () => ({}), windowsAppExecutables: () => ({}),
// Hermetic: no third-party adapters unless a test injects them. // 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', () => { describe('detectInstalledTools', () => {
it('does not expose ambient secrets to the production version probe', async () => { it('does not expose ambient secrets to the production version probe', async () => {
const previousOpenAi = process.env.OPENAI_API_KEY; const previousOpenAi = process.env.OPENAI_API_KEY;
@@ -165,8 +87,6 @@ describe('detectInstalledTools', () => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo', displayName: 'Foo',
launchable: true, launchable: true,
hookCapable: false,
hookPointer: '.foo/hm.json',
detect: { kind: 'path', binaryName: 'foo' }, detect: { kind: 'path', binaryName: 'foo' },
promptArgTemplate: ['--print', '{prompt}'], promptArgTemplate: ['--print', '{prompt}'],
task: { task: {
@@ -188,7 +108,6 @@ describe('detectInstalledTools', () => {
expect(foo?.installed).toBe(true); expect(foo?.installed).toBe(true);
expect(foo?.installedPath).toBe('/usr/bin/foo'); expect(foo?.installedPath).toBe('/usr/bin/foo');
expect(foo?.launchable).toBe(true); expect(foo?.launchable).toBe(true);
expect(foo?.hookCapable).toBe(false);
expect(foo?.builtin).toBe(false); expect(foo?.builtin).toBe(false);
expect(foo?.acceptsInlinePrompt).toBe(true); expect(foo?.acceptsInlinePrompt).toBe(true);
expect(foo?.capabilities).toEqual({ expect(foo?.capabilities).toEqual({
@@ -225,12 +144,10 @@ describe('detectInstalledTools', () => {
expect(cursor).toMatchObject({ expect(cursor).toMatchObject({
releaseStatus: 'roadmap', releaseStatus: 'roadmap',
launchable: false, launchable: false,
hookCapable: false,
}); });
expect(openclaw).toMatchObject({ expect(openclaw).toMatchObject({
releaseStatus: 'roadmap', releaseStatus: 'roadmap',
launchable: false, launchable: false,
hookCapable: false,
}); });
}); });
@@ -247,7 +164,6 @@ describe('detectInstalledTools', () => {
expect(t.installed).toBe(false); expect(t.installed).toBe(false);
expect(t.installedPath).toBeNull(); expect(t.installedPath).toBeNull();
expect(t.version).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'); 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 () => { it('records a diagnostic when claude-code is installed but --version fails', async () => {
const installed = '/usr/local/bin/claude'; const installed = '/usr/local/bin/claude';
const result = await detectInstalledTools( const result = await detectInstalledTools(
@@ -574,25 +258,6 @@ describe('cursor detector', () => {
expect(t.installed).toBe(true); expect(t.installed).toBe(true);
expect(t.installedPath).toBe(installed); 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', () => { 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'); 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 () => { it('reports WindowsApps Codex as installed but not launchable when Windows blocks exec', async () => {
const installed = const installed =
'C:\\Program Files\\WindowsApps\\OpenAI.Codex_26.623.19656.0_x64__2p2nqsd0c76g0\\app\\resources\\codex.exe'; '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 hermesHome = 'D:\\Hermes Data';
const installed = `${hermesHome}\\hermes-agent\\venv\\Scripts\\hermes.exe`; 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({ const result = await detectInstalledTools(makeDeps({
env: { env: {
HERMES_HOME: hermesHome, HERMES_HOME: hermesHome,
LOCALAPPDATA: 'C:\\Users\\test\\AppData\\Local', 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, 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({ expect(result.tools.find((tool) => tool.id === 'hermes')).toMatchObject({
installed: true, installed: true,
installedPath: installed, installedPath: installed,
version: '0.18.2', 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 localAppData = 'E:\\Redirected\\Local';
const hermesHome = `${localAppData}\\hermes`; const hermesHome = `${localAppData}\\hermes`;
const installed = `${hermesHome}\\hermes-agent\\venv\\Scripts\\hermes.exe`; 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({ const result = await detectInstalledTools(makeDeps({
env: { LOCALAPPDATA: localAppData }, env: { LOCALAPPDATA: localAppData },
exists: async (candidate) => existsSet.has(candidate), exists: async (candidate) => candidate === installed,
execVersion: async (binary) => binary === installed ? '0.18.2' : null, 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({ expect(result.tools.find((tool) => tool.id === 'hermes')).toMatchObject({
installed: true, installed: true,
installedPath: installed, installedPath: installed,
version: '0.18.2', version: '0.18.2',
hooksInstalled: true,
hookPointerPath: pointer,
}); });
}); });
@@ -899,7 +526,6 @@ describe('extended-cohort detectors (Codex / Hermes / OpenClaw — Phase 4)', ()
installedPath: desktop, installedPath: desktop,
version: null, version: null,
launchable: true, launchable: true,
hookCapable: false,
capabilities: { interactiveLaunch: true, headlessTask: false }, capabilities: { interactiveLaunch: true, headlessTask: false },
}); });
expect(versionProbes).toContain(cli); expect(versionProbes).toContain(cli);

View File

@@ -1,7 +1,7 @@
/** /**
* AI-OS Phase 2A — tool launcher tests. * 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. * 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 { join, resolve } from 'node:path';
import { import {
launchTool, launchTool,
runHookCommand,
hookPackageFor,
HOOKS_COHORT,
createObservedHandle, createObservedHandle,
defaultSpawnObserved, defaultSpawnObserved,
resolveHookRuntime,
resolveSpawnInvocation, resolveSpawnInvocation,
type HookRuntimePaths, resolveWaggleRuntime,
type ToolLauncherDeps, type ToolLauncherDeps,
type ObservedHandle, type ObservedHandle,
} from '../src/tool-launcher.js'; } 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() { function captureSpawn() {
const calls: Array<{ const calls: Array<{
@@ -41,37 +37,6 @@ function captureSpawn() {
return { calls, spawnDetached }; 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 ────────────────────────────────────────────────────── // ── launchTool ──────────────────────────────────────────────────────
describe('launchTool', () => { describe('launchTool', () => {
@@ -238,8 +203,6 @@ describe('launchTool', () => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo CLI', displayName: 'Foo CLI',
launchable: true, launchable: true,
hookCapable: false,
hookPointer: '.foo/hive-mind-install.json',
detect: { kind: 'path', binaryName: 'foo' }, detect: { kind: 'path', binaryName: 'foo' },
builtin: false, builtin: false,
}; };
@@ -260,8 +223,6 @@ describe('launchTool', () => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo CLI', displayName: 'Foo CLI',
launchable: false, launchable: false,
hookCapable: false,
hookPointer: '.foo/hive-mind-install.json',
detect: { kind: 'path', binaryName: 'foo' }, detect: { kind: 'path', binaryName: 'foo' },
builtin: false, 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', () => { describe('launchTool observe mode', () => {
it('preserves a target signal receipt instead of exposing the supervisor exit code', () => { it('preserves a target signal receipt instead of exposing the supervisor exit code', () => {
const child = new EventEmitter() as ChildProcess; const child = new EventEmitter() as ChildProcess;
@@ -593,24 +404,25 @@ describe('launchTool observe mode', () => {
}); });
}); });
describe('resolveHookRuntime', () => { describe('resolveWaggleRuntime', () => {
it('resolves the CLI and hook bin from an explicit staged node_modules root', () => { it('resolves the collaboration CLI from an explicit staged node_modules root', () => {
const root = join('resources', 'node_modules'); const root = join('resources', 'node_modules');
const cliEntry = join(root, '@waggle', 'hive-mind-cli', 'dist', 'index.js'); 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 = resolveWaggleRuntime({
const runtime = resolveHookRuntime('codex', {
nodePath: join('resources', 'node'), nodePath: join('resources', 'node'),
nodeModulesRoots: [root], nodeModulesRoots: [root],
fileExists: (candidate) => candidate === resolve(cliEntry) || candidate === resolve(hookEntry), fileExists: (candidate) => candidate === resolve(cliEntry),
});
expect(runtime).toEqual({
nodePath: join('resources', 'node'),
cliEntry: resolve(cliEntry),
hookEntry: resolve(hookEntry),
}); });
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(); const { calls, spawnDetached } = captureSpawn();
launchTool({ launchTool({
id: 'claude-code', id: 'claude-code',

View File

@@ -12,7 +12,7 @@ function deps(files: Record<string, unknown>) {
describe('loadThirdPartyManifests', () => { describe('loadThirdPartyManifests', () => {
it('loads a valid PATH manifest, stamped builtin:false', () => { it('loads a valid PATH manifest, stamped builtin:false', () => {
const out = loadThirdPartyManifests(deps({ 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).toHaveLength(1);
expect(out[0]).toMatchObject({ id: 'foo-cli', builtin: false, detect: { kind: 'path', binaryName: 'foo' } }); 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)', () => { it('rejects detect.kind:candidates (code-only strategy)', () => {
const out = loadThirdPartyManifests(deps({ 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([]); expect(out).toEqual([]);
}); });
it('rejects shell-metachar / traversal in fields', () => { it('rejects shell-metachar / traversal in fields', () => {
const out = loadThirdPartyManifests(deps({ 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([]); expect(out).toEqual([]);
}); });
@@ -40,7 +40,7 @@ describe('loadThirdPartyManifests', () => {
const out = loadThirdPartyManifests({ const out = loadThirdPartyManifests({
dir: '/fake', dir: '/fake',
readDir: () => ['broken.json', 'ok.json'], 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']); 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', () => { it('merges a valid third-party PATH adapter', () => {
const reg = getToolRegistry(fakeLoaderDeps([ 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.find((m) => m.id === 'foo-cli')).toMatchObject({ builtin: false });
expect(reg.length).toBe(SUPPORTED_TOOLS.length + 1); expect(reg.length).toBe(SUPPORTED_TOOLS.length + 1);
@@ -24,7 +24,7 @@ describe('getToolRegistry', () => {
it('built-in id wins a third-party collision', () => { it('built-in id wins a third-party collision', () => {
const reg = getToolRegistry(fakeLoaderDeps([ 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'); const cc = reg.filter((m) => m.id === 'claude-code');
expect(cc).toHaveLength(1); expect(cc).toHaveLength(1);

View File

@@ -5,13 +5,11 @@ import { z } from 'zod';
import { import {
detectInstalledTools, detectInstalledTools,
launchTool, launchTool,
runHookCommand,
ToolProcessTracker, ToolProcessTracker,
ToolOutputBuffer, ToolOutputBuffer,
getToolRegistry, getToolRegistry,
type HookAction,
} from '@waggle/agent'; } from '@waggle/agent';
import { SUPPORTED_TOOLS, applyPromptArgTemplate, type ToolId, type ToolManifest } from '@waggle/shared'; import { applyPromptArgTemplate, type ToolManifest } from '@waggle/shared';
import { resolveWorkspaceExecutionRoot } from '../workspace-execution-root.js'; import { resolveWorkspaceExecutionRoot } from '../workspace-execution-root.js';
import { canonicalWorkspaceRoot } from '../workspace-turn-coordinator.js'; import { canonicalWorkspaceRoot } from '../workspace-turn-coordinator.js';
@@ -62,7 +60,7 @@ declare module 'fastify' {
} }
/** /**
* AI-OS — tool-detection + launcher + hook-management routes. * AI-OS — tool-detection + launcher routes.
* *
* Endpoints: * Endpoints:
* *
@@ -75,17 +73,11 @@ declare module 'fastify' {
* Spawn the tool detached with workspace-context env injection. * Spawn the tool detached with workspace-context env injection.
* (Phase 2A) * (Phase 2A)
* *
* POST /api/tools/hooks
* Body: { id, action: 'install' | 'verify' | 'uninstall', cliPath? }
* Run `npx @waggle/hive-mind-hooks-<id> <action>`.
* (Phase 2A)
*
* All routes are read-only by intent (detect) or surface only the * All routes are read-only by intent (detect) or surface only the
* user's own machine (launch/hooks). The local sidecar is loopback- * user's own machine (launch). The local sidecar is loopback-
* bound; tool detection is not sensitive. * bound; tool detection is not sensitive.
*/ */
const TOOL_ID_VALUES = SUPPORTED_TOOLS as readonly string[];
const TOOL_ID_SAFE = /^[A-Za-z0-9._-]+$/; const TOOL_ID_SAFE = /^[A-Za-z0-9._-]+$/;
const PROCESS_RECONCILE_INTERVAL_MS = 5_000; const PROCESS_RECONCILE_INTERVAL_MS = 5_000;
@@ -103,13 +95,6 @@ const launchBodySchema = z.object({
prompt: z.string().max(8000).optional(), prompt: z.string().max(8000).optional(),
}); });
const hooksBodySchema = z.object({
id: z.string().refine((s): s is ToolId => TOOL_ID_VALUES.includes(s), {
message: 'unknown tool id',
}),
action: z.enum(['install', 'verify', 'uninstall']),
}).strict();
const killBodySchema = z.object({ const killBodySchema = z.object({
pid: z.number().int().positive(), pid: z.number().int().positive(),
}); });
@@ -748,34 +733,6 @@ const toolsRoutesImpl: FastifyPluginAsync = async (server) => {
res.on('close', () => unsubscribe()); res.on('close', () => unsubscribe());
return reply; return reply;
}); });
// ── POST /api/tools/hooks (Phase 2A) ─────────────────────────────
server.post('/api/tools/hooks', async (request, reply) => {
const parsed = hooksBodySchema.safeParse(request.body);
if (!parsed.success) {
return reply
.code(400)
.send({ error: 'Validation failed', details: parsed.error.flatten() });
}
const body = parsed.data;
try {
const result = await runHookCommand({
id: body.id,
action: body.action as HookAction,
dataDir: server.localConfig.dataDir,
});
if (!result.ok) {
return reply.code(result.errorCode === 'hook_runtime_missing' ? 503 : 400).send(result);
}
return reply.code(200).send(result);
} catch (err) {
const message = err instanceof Error ? err.message : 'unknown error';
server.log.error({ err }, 'hook command failed');
return reply
.code(500)
.send({ error: 'hook command failed', message });
}
});
}; };
/** /**

View File

@@ -11,8 +11,6 @@ const manifest = (promptArgTemplate?: string[]): ToolManifest => ({
id: 'foo', id: 'foo',
displayName: 'Foo', displayName: 'Foo',
launchable: true, launchable: true,
hookCapable: false,
hookPointer: '.foo/hm.json',
detect: { kind: 'path', binaryName: 'foo' }, detect: { kind: 'path', binaryName: 'foo' },
...(promptArgTemplate ? { promptArgTemplate } : {}), ...(promptArgTemplate ? { promptArgTemplate } : {}),
builtin: false, builtin: false,

View File

@@ -26,8 +26,6 @@ function detectedTool(id: string, installed = true): DetectedTool {
installed, installed,
installedPath: installed ? `/tools/${id}` : null, installedPath: installed ? `/tools/${id}` : null,
version: installed ? '1.0.0' : null, version: installed ? '1.0.0' : null,
hooksInstalled: false,
hookPointerPath: null,
}; };
} }

View File

@@ -34,8 +34,6 @@ describe('external tool roadmap gate', () => {
installed: true, installed: true,
installedPath: 'C:\\tools\\openclaw.cmd', installedPath: 'C:\\tools\\openclaw.cmd',
version: 'test', version: 'test',
hooksInstalled: false,
hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', runner); server.decorate('externalToolRunner', runner);

View File

@@ -189,7 +189,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'codex', displayName: 'Codex CLI', installed: true, id: 'codex', displayName: 'Codex CLI', installed: true,
installedPath: 'C:\\trusted\\codex.cmd', version: 'test', installedPath: 'C:\\trusted\\codex.cmd', version: 'test',
hooksInstalled: true, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -418,7 +417,7 @@ describe('external tool run routes', () => {
} as never); } as never);
server.decorate('externalToolDetector', async () => ({ server.decorate('externalToolDetector', async () => ({
platform: 'win32', detectedAt: new Date().toISOString(), platform: 'win32', detectedAt: new Date().toISOString(),
tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'C:\\trusted\\codex.cmd', version: 'test', hooksInstalled: true, hookPointerPath: null }], tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'C:\\trusted\\codex.cmd', version: 'test' }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
calls.push({ calls.push({
@@ -551,10 +550,10 @@ describe('external tool run routes', () => {
server.decorate('externalToolDetector', async () => ({ server.decorate('externalToolDetector', async () => ({
platform: 'win32', detectedAt: new Date().toISOString(), platform: 'win32', detectedAt: new Date().toISOString(),
tools: [ tools: [
{ id: 'claude-code', displayName: 'Claude Code', installed: true, installedPath: 'claude.exe', version: 'test', hooksInstalled: true, hookPointerPath: null }, { id: 'claude-code', displayName: 'Claude Code', installed: true, installedPath: 'claude.exe', version: 'test' },
{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.exe', version: 'test', hooksInstalled: true, hookPointerPath: null }, { id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.exe', version: 'test' },
{ id: 'hermes', displayName: 'Hermes', installed: true, installedPath: 'hermes.exe', version: 'test', hooksInstalled: true, hookPointerPath: null }, { id: 'hermes', displayName: 'Hermes', installed: true, installedPath: 'hermes.exe', version: 'test' },
{ id: 'openclaw', displayName: 'OpenClaw', installed: true, installedPath: 'openclaw.exe', version: openClawVersion, hooksInstalled: true, hookPointerPath: null }, { id: 'openclaw', displayName: 'OpenClaw', installed: true, installedPath: 'openclaw.exe', version: openClawVersion },
], ],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -845,7 +844,7 @@ describe('external tool run routes', () => {
} as never); } as never);
server.decorate('externalToolDetector', async () => ({ server.decorate('externalToolDetector', async () => ({
platform: 'win32', detectedAt: new Date().toISOString(), platform: 'win32', detectedAt: new Date().toISOString(),
tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd', version: 'test', hooksInstalled: false, hookPointerPath: null }], tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd', version: 'test' }],
})); }));
server.decorate('externalToolRunner', async () => ({ server.decorate('externalToolRunner', async () => ({
status: 'failed', exitCode: 1, summary: 'Partial provider answer', stdoutTail: '', status: 'failed', exitCode: 1, summary: 'Partial provider answer', stdoutTail: '',
@@ -890,7 +889,7 @@ describe('external tool run routes', () => {
server.decorate('externalCollaborationRuntime', collaborationRuntime); server.decorate('externalCollaborationRuntime', collaborationRuntime);
server.decorate('externalToolDetector', async () => ({ server.decorate('externalToolDetector', async () => ({
platform: 'win32', detectedAt: new Date().toISOString(), platform: 'win32', detectedAt: new Date().toISOString(),
tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd', version: 'test', hooksInstalled: false, hookPointerPath: null }], tools: [{ id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd', version: 'test' }],
})); }));
server.decorate('externalToolRunner', (request) => new Promise<ExternalToolRunResult>((resolve) => { server.decorate('externalToolRunner', (request) => new Promise<ExternalToolRunResult>((resolve) => {
request.onEvent?.({ request.onEvent?.({
@@ -968,7 +967,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'codex', displayName: 'Codex CLI', installed: true, id: 'codex', displayName: 'Codex CLI', installed: true,
installedPath: 'codex.cmd', version: 'test', installedPath: 'codex.cmd', version: 'test',
hooksInstalled: false, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -1083,7 +1081,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'openclaw', displayName: 'OpenClaw', installed: true, id: 'openclaw', displayName: 'OpenClaw', installed: true,
installedPath: 'openclaw.cmd', version: 'test', installedPath: 'openclaw.cmd', version: 'test',
hooksInstalled: false, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', runner); server.decorate('externalToolRunner', runner);
@@ -1153,7 +1150,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'openclaw', displayName: 'OpenClaw', installed: true, id: 'openclaw', displayName: 'OpenClaw', installed: true,
installedPath: 'openclaw.cmd', version: 'test', installedPath: 'openclaw.cmd', version: 'test',
hooksInstalled: false, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -1380,7 +1376,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'openclaw', displayName: 'OpenClaw', installed: true, id: 'openclaw', displayName: 'OpenClaw', installed: true,
installedPath, version: binaryVersion, installedPath, version: binaryVersion,
hooksInstalled: false, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -1469,7 +1464,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'openclaw', displayName: 'OpenClaw', installed: true, id: 'openclaw', displayName: 'OpenClaw', installed: true,
installedPath: 'openclaw.cmd', version: 'test', installedPath: 'openclaw.cmd', version: 'test',
hooksInstalled: false, hookPointerPath: null,
}], }],
})); }));
server.decorate('externalToolRunner', async (request) => { server.decorate('externalToolRunner', async (request) => {
@@ -1571,7 +1565,6 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'openclaw' as const, displayName: 'OpenClaw', installed: true, id: 'openclaw' as const, displayName: 'OpenClaw', installed: true,
installedPath: 'openclaw.cmd', version: 'test', installedPath: 'openclaw.cmd', version: 'test',
hooksInstalled: false, hookPointerPath: null,
}], }],
}; };
}); });
@@ -1622,7 +1615,7 @@ describe('external tool run routes', () => {
platform: 'win32', detectedAt: new Date().toISOString(), platform: 'win32', detectedAt: new Date().toISOString(),
tools: [{ tools: [{
id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd', id: 'codex', displayName: 'Codex CLI', installed: true, installedPath: 'codex.cmd',
version: 'test', hooksInstalled: false, hookPointerPath: null, version: 'test',
}], }],
})); }));
server.decorate('externalToolRunner', async () => { server.decorate('externalToolRunner', async () => {
@@ -1678,7 +1671,7 @@ describe('external tool run routes', () => {
tools: [{ tools: [{
id: 'codex', displayName: 'Codex CLI', installed: true, id: 'codex', displayName: 'Codex CLI', installed: true,
installedPath: 'C:\\Program Files\\WindowsApps\\OpenAI.Codex\\resources\\codex.exe', installedPath: 'C:\\Program Files\\WindowsApps\\OpenAI.Codex\\resources\\codex.exe',
version: null, hooksInstalled: false, hookPointerPath: null, version: null,
launchable: false, diagnostic: 'The Store resource CLI cannot launch outside its package.', launchable: false, diagnostic: 'The Store resource CLI cannot launch outside its package.',
}], }],
})); }));

View File

@@ -1,12 +1,9 @@
/** /**
* AI-OS Phase 2A — integration tests for /api/tools/launch and * AI-OS Phase 2A — integration tests for /api/tools/launch.
* /api/tools/hooks.
* *
* The launch + hook routes call into `@waggle/agent`'s launchTool / * The launch route calls into `@waggle/agent`'s launchTool. To keep these
* runHookCommand. To keep these tests hermetic AND non-destructive * tests hermetic AND non-destructive (a real launch would start the tool on
* (`npx --yes @waggle/hive-mind-hooks-claude-code install` would * the test machine), we mock the launcher module at the module level.
* actually modify ~/.claude/settings.json on the test machine), we
* mock the launcher module at the module level.
* *
* The launcher unit tests (`packages/agent/tests/tool-launcher.test.ts`) * The launcher unit tests (`packages/agent/tests/tool-launcher.test.ts`)
* cover the actual spawn / exec paths with injected deps — this * cover the actual spawn / exec paths with injected deps — this
@@ -32,8 +29,6 @@ vi.mock('@waggle/agent', async (importOriginal) => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo CLI', displayName: 'Foo CLI',
launchable: true, launchable: true,
hookCapable: false,
hookPointer: '.foo/hive-mind-install.json',
detect: { kind: 'path' as const, binaryName: 'foo' }, detect: { kind: 'path' as const, binaryName: 'foo' },
promptArgTemplate: ['--print', '{prompt}'], promptArgTemplate: ['--print', '{prompt}'],
builtin: false, builtin: false,
@@ -50,8 +45,6 @@ vi.mock('@waggle/agent', async (importOriginal) => {
installed: true, installed: true,
installedPath: `/server-detected/${manifest.id}`, installedPath: `/server-detected/${manifest.id}`,
version: 'test', version: 'test',
hooksInstalled: false,
hookPointerPath: null,
})), })),
})), })),
launchTool: vi.fn((opts: { id: string; installedPath: string }) => ({ launchTool: vi.fn((opts: { id: string; installedPath: string }) => ({
@@ -59,22 +52,12 @@ vi.mock('@waggle/agent', async (importOriginal) => {
pid: 99999, pid: 99999,
executed: { binary: opts.installedPath, args: [] }, executed: { binary: opts.installedPath, args: [] },
})), })),
runHookCommand: vi.fn(
async (opts: { id: string; action: string }) => ({
ok: true,
action: opts.action,
packageName: `@waggle/hive-mind-hooks-${opts.id}`,
stdout: 'mock install output',
stderr: '',
code: 0,
}),
),
}; };
}); });
import { buildLocalServer } from '../src/local/index.js'; import { buildLocalServer } from '../src/local/index.js';
import { injectWithAuth } from './test-utils.js'; import { injectWithAuth } from './test-utils.js';
import { detectInstalledTools, launchTool, runHookCommand } from '@waggle/agent'; import { detectInstalledTools, launchTool } from '@waggle/agent';
import { loopbackSidecarUrl } from '../src/local/routes/tools.js'; import { loopbackSidecarUrl } from '../src/local/routes/tools.js';
import { resolveWorkspaceExecutionRoot } from '../src/local/workspace-execution-root.js'; import { resolveWorkspaceExecutionRoot } from '../src/local/workspace-execution-root.js';
@@ -240,7 +223,7 @@ describe('POST /api/tools/launch', () => {
tools: [{ tools: [{
id: 'codex', displayName: 'Codex CLI', installed: true, id: 'codex', displayName: 'Codex CLI', installed: true,
installedPath: 'C:\\Program Files\\WindowsApps\\OpenAI.Codex\\resources\\codex.exe', installedPath: 'C:\\Program Files\\WindowsApps\\OpenAI.Codex\\resources\\codex.exe',
version: null, hooksInstalled: false, hookPointerPath: null, version: null,
launchable: false, diagnostic: 'The Store resource CLI cannot launch outside its package.', launchable: false, diagnostic: 'The Store resource CLI cannot launch outside its package.',
}], }],
}); });
@@ -935,112 +918,14 @@ describe('POST /api/tools/hooks', () => {
if (tmpDir) cleanupDir(tmpDir); if (tmpDir) cleanupDir(tmpDir);
}); });
it('runs install action and returns 200 + stdout', async () => { it('is gone: coding-agent hooks are not part of the community edition (ADR-0002)', async () => {
vi.mocked(runHookCommand).mockClear();
const res = await injectWithAuth(server, { const res = await injectWithAuth(server, {
method: 'POST', method: 'POST',
url: '/api/tools/hooks', url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' }, headers: { 'content-type': 'application/json' },
payload: { id: 'claude-code', action: 'install' }, payload: { id: 'claude-code', action: 'install' },
}); });
expect(res.statusCode).toBe(200); expect(res.statusCode).toBe(404);
const body = res.json();
expect(body.ok).toBe(true);
expect(body.action).toBe('install');
expect(body.stdout).toBe('mock install output');
expect(runHookCommand).toHaveBeenCalledWith(
expect.objectContaining({ id: 'claude-code', action: 'install' }),
);
});
it('rejects a client-supplied CLI path instead of executing it', async () => {
vi.mocked(runHookCommand).mockClear();
const response = await injectWithAuth(server, {
method: 'POST',
url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: {
id: 'claude-code',
action: 'install',
cliPath: 'C:\\hive-mind-cli.js',
},
});
expect(response.statusCode).toBe(400);
expect(runHookCommand).not.toHaveBeenCalled();
});
it.each(['install', 'verify', 'uninstall'])(
'accepts action=%s',
async (action) => {
vi.mocked(runHookCommand).mockClear();
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: { id: 'cursor', action },
});
expect(res.statusCode).toBe(200);
expect(runHookCommand).toHaveBeenCalledWith(
expect.objectContaining({ id: 'cursor', action }),
);
},
);
it('rejects unknown action', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: { id: 'claude-code', action: 'destroy' },
});
expect(res.statusCode).toBe(400);
});
it('rejects unknown tool id', async () => {
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: { id: 'unknown-tool', action: 'install' },
});
expect(res.statusCode).toBe(400);
});
it('returns 400 when the underlying command fails', async () => {
vi.mocked(runHookCommand).mockResolvedValueOnce({
ok: false,
action: 'install',
packageName: '@waggle/hive-mind-hooks-claude-code',
stdout: '',
stderr: 'permission denied writing settings.json',
code: 1,
});
const res = await injectWithAuth(server, {
method: 'POST',
url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: { id: 'claude-code', action: 'install' },
});
expect(res.statusCode).toBe(400);
expect(res.json().stderr).toContain('permission denied');
});
it('returns 503 when the packaged hook runtime is missing', async () => {
vi.mocked(runHookCommand).mockResolvedValueOnce({
ok: false,
action: 'install',
packageName: '@waggle/hive-mind-hooks-claude-code',
stdout: '', stderr: '', code: -1,
errorCode: 'hook_runtime_missing',
error: 'runtime missing',
});
const res = await injectWithAuth(server, {
method: 'POST', url: '/api/tools/hooks',
headers: { 'content-type': 'application/json' },
payload: { id: 'claude-code', action: 'install' },
});
expect(res.statusCode).toBe(503);
expect(res.json().errorCode).toBe('hook_runtime_missing');
}); });
}); });

View File

@@ -25,8 +25,6 @@ vi.mock('@waggle/agent', async (importOriginal) => {
installed: true, installed: true,
installedPath: '/server-detected/claude-code', installedPath: '/server-detected/claude-code',
version: 'test', version: 'test',
hooksInstalled: false,
hookPointerPath: null,
}], }],
})), })),
launchTool: vi.fn((opts: { id: string; installedPath: string }) => ({ launchTool: vi.fn((opts: { id: string; installedPath: string }) => ({

View File

@@ -93,10 +93,8 @@ describe('GET /api/tools/detect', () => {
expect(t).toHaveProperty('installed'); expect(t).toHaveProperty('installed');
expect(t).toHaveProperty('installedPath'); expect(t).toHaveProperty('installedPath');
expect(t).toHaveProperty('version'); expect(t).toHaveProperty('version');
expect(t).toHaveProperty('hooksInstalled'); expect(t).not.toHaveProperty('hooksInstalled');
expect(t).toHaveProperty('hookPointerPath');
expect(typeof t.installed).toBe('boolean'); expect(typeof t.installed).toBe('boolean');
expect(typeof t.hooksInstalled).toBe('boolean');
} }
}); });

View File

@@ -2,8 +2,7 @@
* Tool Detection — shared types for AI-OS Phase 0. * Tool Detection — shared types for AI-OS Phase 0.
* *
* Mission: report which external AI tools are installed on the user's * Mission: report which external AI tools are installed on the user's
* machine, with version and hive-mind hook status. Foundation for the * machine, with version. Foundation for the launcher dock (Phase 2) and the
* launcher dock (Phase 2), hook auto-installer UX (Phase 2), and the
* Mission Control inventory tile (Phase 4). * Mission Control inventory tile (Phase 4).
* *
* The detection itself runs in the sidecar (agent package); these types * The detection itself runs in the sidecar (agent package); these types
@@ -11,7 +10,6 @@
* consume the same envelope without duplicating shapes. * consume the same envelope without duplicating shapes.
* *
* Out of scope for these types: * Out of scope for these types:
* - Hook installation (Phase 2)
* - Tool spawn / process management (Phase 2) * - Tool spawn / process management (Phase 2)
* - Workspace context injection (Phase 2) * - Workspace context injection (Phase 2)
*/ */
@@ -80,8 +78,7 @@ export type ToolReleaseStatus = 'supported' | 'roadmap';
/** /**
* AI-OS #5 — declarative descriptor for one external tool. The single source of * AI-OS #5 — declarative descriptor for one external tool. The single source of
* truth for the per-tool facts that used to be duplicated across SUPPORTED_TOOLS * truth for the per-tool facts that used to be duplicated across SUPPORTED_TOOLS
* / LAUNCH_COHORT / TOOL_DISPLAY_NAMES / HOOK_POINTER_BY_TOOL / HOOKS_COHORT / * / LAUNCH_COHORT / TOOL_DISPLAY_NAMES / the per-tool detectors. Built-ins live in BUILTIN_TOOL_MANIFESTS; third-party
* the per-tool detectors. Built-ins live in BUILTIN_TOOL_MANIFESTS; third-party
* adapters are loaded (data-only) from ~/.waggle/adapters/*.json. * adapters are loaded (data-only) from ~/.waggle/adapters/*.json.
*/ */
export interface ToolManifest { export interface ToolManifest {
@@ -90,10 +87,6 @@ export interface ToolManifest {
/** Omitted means supported; roadmap integrations remain detectable but inert. */ /** Omitted means supported; roadmap integrations remain detectable but inert. */
releaseStatus?: ToolReleaseStatus; releaseStatus?: ToolReleaseStatus;
launchable: boolean; launchable: boolean;
hookCapable: boolean;
/** Built-in-only pointer root; third-party adapters always use the user home. */
hookRoot?: 'user-home' | 'hermes-home';
hookPointer: string;
detect: ToolDetectSpec; detect: ToolDetectSpec;
/** /**
* Declarative inline-prompt arg template for THIRD-PARTY path adapters * Declarative inline-prompt arg template for THIRD-PARTY path adapters
@@ -112,13 +105,13 @@ export interface ToolManifest {
/** /**
* The canonical 8 built-in execution surfaces — the source of truth for their * The canonical 8 built-in execution surfaces — the source of truth for their
* per-tool data. * per-tool data.
* SUPPORTED_TOOLS (above) stays the `as const` type anchor; the cohort/name/ * SUPPORTED_TOOLS (above) stays the `as const` type anchor; the cohort and
* pointer consts derive from these manifests. * name consts derive from these manifests.
*/ */
export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [ export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [
{ {
id: 'claude-code', displayName: 'Claude Code', launchable: true, hookCapable: true, id: 'claude-code', displayName: 'Claude Code', launchable: true,
hookPointer: '.claude/hive-mind-install.json', detect: { kind: 'path', binaryName: 'claude' }, builtin: true, detect: { kind: 'path', binaryName: 'claude' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false },
task: { task: {
argvTemplate: ['-p', '--safe-mode', '--disable-slash-commands', '--max-budget-usd', '1.00', '--input-format', 'text', '--output-format', 'stream-json', '--verbose', '{accessArgs}'], argvTemplate: ['-p', '--safe-mode', '--disable-slash-commands', '--max-budget-usd', '1.00', '--input-format', 'text', '--output-format', 'stream-json', '--verbose', '{accessArgs}'],
@@ -133,18 +126,18 @@ export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [
}, },
}, },
{ {
id: 'claude-desktop', displayName: 'Claude Desktop', launchable: true, hookCapable: true, id: 'claude-desktop', displayName: 'Claude Desktop', launchable: true,
hookPointer: '.waggle/claude-desktop/hive-mind-install.json', detect: { kind: 'candidates' }, builtin: true, detect: { kind: 'candidates' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false },
}, },
{ {
id: 'cursor', displayName: 'Cursor', releaseStatus: 'roadmap', launchable: false, hookCapable: false, id: 'cursor', displayName: 'Cursor', releaseStatus: 'roadmap', launchable: false,
hookPointer: '.cursor/hive-mind-install.json', detect: { kind: 'candidates' }, builtin: true, detect: { kind: 'candidates' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false },
}, },
{ {
id: 'codex', displayName: 'Codex CLI', launchable: true, hookCapable: true, id: 'codex', displayName: 'Codex CLI', launchable: true,
hookPointer: '.codex/hive-mind-install.json', detect: { kind: 'path', binaryName: 'codex' }, builtin: true, detect: { kind: 'path', binaryName: 'codex' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false },
task: { task: {
argvTemplate: ['{accessArgs}', 'exec', '--ignore-user-config', '--ignore-rules', '--skip-git-repo-check', '--json', '--color', 'never', '-C', '{workspacePath}', '-'], argvTemplate: ['{accessArgs}', 'exec', '--ignore-user-config', '--ignore-rules', '--skip-git-repo-check', '--json', '--color', 'never', '-C', '{workspacePath}', '-'],
@@ -159,13 +152,13 @@ export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [
}, },
}, },
{ {
id: 'codex-desktop', displayName: 'Codex Desktop', launchable: true, hookCapable: true, id: 'codex-desktop', displayName: 'Codex Desktop', launchable: true,
hookPointer: '.codex/hive-mind-install.json', detect: { kind: 'candidates' }, builtin: true, detect: { kind: 'candidates' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false },
}, },
{ {
id: 'hermes', displayName: 'Hermes Agent CLI', launchable: true, hookCapable: true, id: 'hermes', displayName: 'Hermes Agent CLI', launchable: true,
hookRoot: 'hermes-home', hookPointer: 'hive-mind-install.json', detect: { kind: 'path', binaryName: 'hermes' }, builtin: true, detect: { kind: 'path', binaryName: 'hermes' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: false, resumable: true, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: false, resumable: true, liveWaggleDance: false },
task: { task: {
argvTemplate: ['chat', '-q', '{prompt}', '-Q', '--source', 'tool', '--ignore-rules', '--max-turns', '12', '--checkpoints'], argvTemplate: ['chat', '-q', '{prompt}', '-Q', '--source', 'tool', '--ignore-rules', '--max-turns', '12', '--checkpoints'],
@@ -175,13 +168,13 @@ export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [
}, },
}, },
{ {
id: 'hermes-desktop', displayName: 'Hermes Desktop', launchable: true, hookCapable: false, id: 'hermes-desktop', displayName: 'Hermes Desktop', launchable: true,
hookPointer: '', detect: { kind: 'candidates' }, builtin: true, detect: { kind: 'candidates' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: false, structuredProgress: false, resumable: false, liveWaggleDance: false },
}, },
{ {
id: 'openclaw', displayName: 'OpenClaw', releaseStatus: 'roadmap', launchable: false, hookCapable: false, id: 'openclaw', displayName: 'OpenClaw', releaseStatus: 'roadmap', launchable: false,
hookPointer: '.openclaw/hive-mind-install.json', detect: { kind: 'path', binaryName: 'openclaw' }, builtin: true, detect: { kind: 'path', binaryName: 'openclaw' }, builtin: true,
capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false }, capabilities: { interactiveLaunch: true, headlessTask: true, structuredProgress: true, resumable: true, liveWaggleDance: false },
task: { task: {
argvTemplate: ['agent', '--agent', '{agentId}', '--session-key', 'agent:{agentId}:waggle:{runId}', '--message-file', '{promptFile}', '--json', '--timeout', '{timeoutSeconds}'], argvTemplate: ['agent', '--agent', '{agentId}', '--session-key', 'agent:{agentId}:waggle:{runId}', '--message-file', '{promptFile}', '--json', '--timeout', '{timeoutSeconds}'],
@@ -193,10 +186,10 @@ export const BUILTIN_TOOL_MANIFESTS: readonly ToolManifest[] = [
] as const; ] as const;
/** /**
* Tools the launcher dock + hook installer support end-to-end. * Tools the launcher dock supports end-to-end.
* *
* Registered integrations can remain detectable for compatibility while * Registered integrations can remain detectable for compatibility while
* `releaseStatus: 'roadmap'` keeps them out of both launch and hook cohorts. * `releaseStatus: 'roadmap'` keeps them out of the launch cohort.
*/ */
export const LAUNCH_COHORT: readonly ToolId[] = export const LAUNCH_COHORT: readonly ToolId[] =
BUILTIN_TOOL_MANIFESTS.filter((m) => m.launchable).map((m) => m.id as ToolId); BUILTIN_TOOL_MANIFESTS.filter((m) => m.launchable).map((m) => m.id as ToolId);
@@ -225,11 +218,6 @@ export const TOOL_DISPLAY_NAMES = Object.fromEntries(
* - `installed` : true iff the binary was found at a known path. * - `installed` : true iff the binary was found at a known path.
* - `installedPath` : absolute path to the binary, or null. * - `installedPath` : absolute path to the binary, or null.
* - `version` : version string (best-effort; null if exec failed). * - `version` : version string (best-effort; null if exec failed).
* - `hooksInstalled` : true iff the hook pointer and its referenced rollback
* state are healthy; tools with active-config verification must also still
* contain their marker-tagged hook entries.
* - `hookPointerPath` : the pointer file we read (or attempted),
* for diagnostics.
* - `diagnostic` : optional human-readable reason for any * - `diagnostic` : optional human-readable reason for any
* partial-failure case (e.g. "claude-code installed but --version * partial-failure case (e.g. "claude-code installed but --version
* returned non-zero"). * returned non-zero").
@@ -242,8 +230,6 @@ export interface DetectedTool {
releaseStatus?: ToolReleaseStatus; releaseStatus?: ToolReleaseStatus;
/** True when the tool manifest allows launching from the dock. */ /** True when the tool manifest allows launching from the dock. */
launchable?: boolean; launchable?: boolean;
/** True when the tool manifest declares hook support. */
hookCapable?: boolean;
/** True for built-in execution surfaces; false for loaded adapters. */ /** True for built-in execution surfaces; false for loaded adapters. */
builtin?: boolean; builtin?: boolean;
/** True when the manifest can accept the launch prompt inline. */ /** True when the manifest can accept the launch prompt inline. */
@@ -255,8 +241,6 @@ export interface DetectedTool {
installed: boolean; installed: boolean;
installedPath: string | null; installedPath: string | null;
version: string | null; version: string | null;
hooksInstalled: boolean;
hookPointerPath: string | null;
diagnostic?: string; diagnostic?: string;
} }

View File

@@ -14,22 +14,13 @@ describe('BUILTIN_TOOL_MANIFESTS', () => {
} }
}); });
it('keeps roadmap integrations detectable but outside launch and hook cohorts', () => { it('keeps roadmap integrations detectable but outside the launch cohort', () => {
const roadmap = BUILTIN_TOOL_MANIFESTS.filter((m) => m.releaseStatus === 'roadmap'); const roadmap = BUILTIN_TOOL_MANIFESTS.filter((m) => m.releaseStatus === 'roadmap');
expect(roadmap.map((m) => m.id)).toEqual(['cursor', 'openclaw']); expect(roadmap.map((m) => m.id)).toEqual(['cursor', 'openclaw']);
for (const manifest of roadmap) { for (const manifest of roadmap) {
expect(manifest.launchable).toBe(false); expect(manifest.launchable).toBe(false);
expect(manifest.hookCapable).toBe(false);
} }
}); });
it('keeps desktop-only and roadmap surfaces out of the hook cohort', () => {
expect(BUILTIN_TOOL_MANIFESTS.filter((m) => !m.hookCapable).map((m) => m.id)).toEqual([
'cursor',
'hermes-desktop',
'openclaw',
]);
});
it('derives TOOL_DISPLAY_NAMES and the release-qualified launch cohort from manifests', () => { it('derives TOOL_DISPLAY_NAMES and the release-qualified launch cohort from manifests', () => {
expect(TOOL_DISPLAY_NAMES['claude-code']).toBe('Claude Code'); expect(TOOL_DISPLAY_NAMES['claude-code']).toBe('Claude Code');
expect(TOOL_DISPLAY_NAMES['codex']).toBe('Codex CLI'); expect(TOOL_DISPLAY_NAMES['codex']).toBe('Codex CLI');
@@ -44,14 +35,10 @@ describe('BUILTIN_TOOL_MANIFESTS', () => {
expect(cli).toMatchObject({ expect(cli).toMatchObject({
displayName: 'Hermes Agent CLI', displayName: 'Hermes Agent CLI',
hookCapable: true,
hookRoot: 'hermes-home',
hookPointer: 'hive-mind-install.json',
capabilities: { interactiveLaunch: true, headlessTask: true }, capabilities: { interactiveLaunch: true, headlessTask: true },
}); });
expect(desktop).toMatchObject({ expect(desktop).toMatchObject({
displayName: 'Hermes Desktop', displayName: 'Hermes Desktop',
hookCapable: false,
detect: { kind: 'candidates' }, detect: { kind: 'candidates' },
capabilities: { interactiveLaunch: true, headlessTask: false, resumable: false }, capabilities: { interactiveLaunch: true, headlessTask: false, resumable: false },
}); });

View File

@@ -85,7 +85,6 @@ type DetectedTool = {
installed: boolean; installed: boolean;
installedPath: string | null; installedPath: string | null;
launchable?: boolean; launchable?: boolean;
hookCapable?: boolean;
builtin?: boolean; builtin?: boolean;
capabilities?: { capabilities?: {
interactiveLaunch: boolean; interactiveLaunch: boolean;

View File

@@ -26,14 +26,6 @@ async function mockProcesses(page: Page): Promise<void> {
})); }));
} }
const HOOK_RENDER_CASES = [
{ id: 'claude-code', displayName: 'Claude Code', packageName: '@waggle/hive-mind-hooks-claude-code', configDir: '.claude', configFile: 'settings.json' },
{ id: 'claude-desktop', displayName: 'Claude Desktop', packageName: '@waggle/hive-mind-hooks-claude-desktop', configDir: '.waggle/claude-desktop', configFile: 'claude_desktop_config.json' },
{ id: 'codex', displayName: 'Codex CLI', packageName: '@waggle/hive-mind-hooks-codex', configDir: '.codex', configFile: 'hooks.json' },
{ id: 'codex-desktop', displayName: 'Codex Desktop', packageName: '@waggle/hive-mind-hooks-codex-desktop', configDir: '.codex', configFile: 'hooks.json' },
{ id: 'hermes', displayName: 'Hermes Agent', packageName: '@waggle/hive-mind-hooks-hermes', configDir: '.hermes', configFile: 'config.yaml' },
] as const;
test.describe('Launcher rendered states', () => { test.describe('Launcher rendered states', () => {
test('sidecar-offline detection shows an inline retry action', async ({ page }) => { test('sidecar-offline detection shows an inline retry action', async ({ page }) => {
let detectCalls = 0; let detectCalls = 0;
@@ -54,14 +46,11 @@ test.describe('Launcher rendered states', () => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo CLI', displayName: 'Foo CLI',
launchable: true, launchable: true,
hookCapable: false,
builtin: false, builtin: false,
acceptsInlinePrompt: true, acceptsInlinePrompt: true,
installed: true, installed: true,
installedPath: '/usr/local/bin/foo', installedPath: '/usr/local/bin/foo',
version: '1.0.0', version: '1.0.0',
hooksInstalled: false,
hookPointerPath: null,
}, },
], ],
}), }),
@@ -76,210 +65,7 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText(/sidecar may be offline/i)).not.toBeVisible(); await expect(page.getByText(/sidecar may be offline/i)).not.toBeVisible();
}); });
// Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002, test('third-party adapter renders launch state and sends its prompt', async ({ page }) => {
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('long hook stderr is summarized instead of flooding the rendered panel', async ({ page }) => {
await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
platform: 'linux',
detectedAt: '2026-07-08T00:00:00.000Z',
tools: [
{
id: 'codex',
displayName: 'Codex CLI',
launchable: true,
hookCapable: true,
builtin: true,
acceptsInlinePrompt: true,
installed: true,
installedPath: '/usr/local/bin/codex',
version: '1.0.0',
hooksInstalled: false,
hookPointerPath: null,
},
],
}),
}));
await page.route('**/api/tools/hooks', route => route.fulfill({
status: 400,
contentType: 'application/json',
body: JSON.stringify({
ok: false,
action: 'verify',
packageName: '@waggle/hive-mind-hooks-codex',
stdout: '',
stderr: [
'failure detail 1: missing hook pointer',
'failure detail 2: stale backup file',
'failure detail 3: cli not trusted',
'failure detail 4: config mismatch',
'failure detail 5: lifecycle skipped',
'failure detail 6: retry recommended',
'failure detail 7: noisy internal trace',
'failure detail 8: noisy internal trace',
].join('\n'),
code: 1,
error: 'verify failed',
}),
}));
await gotoLauncher(page);
await page.getByRole('button', { name: /^Verify$/ }).click();
await expect(page.getByText(/verify failed/i)).toBeVisible();
await expect(page.getByText('More output')).toBeVisible();
await expect(page.getByText(/2 additional hook output lines hidden/i)).toBeVisible();
await expect(page.getByText(/failure detail 8/i)).not.toBeVisible();
await expect(page.getByText('Recovery')).toBeVisible();
});
// Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('standard hook install output renders changed file, pointer, backup, and recovery labels', async ({ page }) => {
await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
platform: 'linux',
detectedAt: '2026-07-08T00:00:00.000Z',
tools: [
{
id: 'codex',
displayName: 'Codex CLI',
launchable: true,
hookCapable: true,
builtin: true,
acceptsInlinePrompt: true,
installed: true,
installedPath: '/usr/local/bin/codex',
version: '1.0.0',
hooksInstalled: false,
hookPointerPath: null,
},
],
}),
}));
await page.route('**/api/tools/hooks', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
ok: true,
action: 'install',
packageName: '@waggle/hive-mind-hooks-codex',
stdout: [
'hive-mind/codex-hooks: install',
' - hooks.json: /home/.codex/hooks.json',
' - install pointer: /home/.codex/hive-mind-install.json',
' - backup: /home/.codex/hooks.json.hive-mind-backup.2026-07-08T19-00-00Z',
'Done. Run "codex" once and approve the hook command if prompted.',
].join('\n'),
stderr: '',
code: 0,
}),
}));
await gotoLauncher(page);
await page.getByRole('button', { name: /install hooks/i }).click();
await expect(page.getByText(/Codex CLI: install OK/i)).toBeVisible();
await expect(page.getByText('Changed file', { exact: true })).toBeVisible();
await expect(page.getByText('/home/.codex/hooks.json', { exact: true })).toBeVisible();
await expect(page.getByText('Install pointer', { exact: true })).toBeVisible();
await expect(page.getByText('/home/.codex/hive-mind-install.json', { exact: true })).toBeVisible();
await expect(page.getByText('Backup', { exact: true })).toBeVisible();
await expect(page.getByText(/hooks\.json\.hive-mind-backup/i)).toBeVisible();
await expect(page.getByText('Recovery', { exact: true })).toBeVisible();
await expect(page.getByText(/hive-mind\/codex-hooks: install/i)).not.toBeVisible();
});
// Agent memory hooks are hidden in v1 by the memory feature map (ADR-0002,
// apps/web/src/lib/memory-features.ts). Re-enable with the agentHooks feature.
test.skip('all hook-capable tools render install, verify, and uninstall state transitions', async ({ page }) => {
const hookState = new Map(HOOK_RENDER_CASES.map(tool => [tool.id, false]));
await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
platform: 'linux',
detectedAt: '2026-07-09T00:00:00.000Z',
tools: HOOK_RENDER_CASES.map(tool => ({
id: tool.id,
displayName: tool.displayName,
launchable: true,
hookCapable: true,
builtin: true,
acceptsInlinePrompt: true,
installed: true,
installedPath: `/usr/local/bin/${tool.id}`,
version: '1.0.0',
hooksInstalled: hookState.get(tool.id) === true,
hookPointerPath: hookState.get(tool.id) === true
? `/home/${tool.configDir}/hive-mind-install.json`
: null,
})),
}),
}));
await page.route('**/api/tools/hooks', route => {
const body = route.request().postDataJSON() as { id: string; action: 'install' | 'verify' | 'uninstall' };
const tool = HOOK_RENDER_CASES.find(item => item.id === body.id);
if (!tool) {
return route.fulfill({
status: 400,
contentType: 'application/json',
body: JSON.stringify({ ok: false, action: body.action, error: 'unknown tool' }),
});
}
if (body.action === 'install') hookState.set(tool.id, true);
if (body.action === 'uninstall') hookState.set(tool.id, false);
return route.fulfill({
status: 200,
contentType: 'application/json',
body: JSON.stringify({
ok: true,
action: body.action,
packageName: tool.packageName,
stdout: body.action === 'verify'
? 'All checks passed.'
: [
`hive-mind/${tool.id}-hooks: ${body.action}`,
` - ${tool.configFile}: /home/${tool.configDir}/${tool.configFile}`,
` - install pointer: /home/${tool.configDir}/hive-mind-install.json`,
' - backup removed: yes',
'Done.',
].join('\n'),
stderr: '',
code: 0,
}),
});
});
await gotoLauncher(page);
for (const tool of HOOK_RENDER_CASES) {
const card = page.getByTestId(`launcher-tool-${tool.id}`);
await expect(card.getByText(tool.displayName, { exact: true })).toBeVisible();
await card.getByRole('button', { name: /install hooks/i }).click();
await expect(page.getByText(`${tool.displayName}: install OK`, { exact: true })).toBeVisible();
await expect(card.getByText('Hooks active', { exact: true })).toBeVisible();
await card.getByRole('button', { name: /^Verify$/ }).click();
await expect(page.getByText(`${tool.displayName}: verify OK`, { exact: true })).toBeVisible();
await card.getByRole('button', { name: /uninstall hooks/i }).click();
await expect(page.getByText(`${tool.displayName}: uninstall OK`, { exact: true })).toBeVisible();
await expect(card.getByText('Hooks active', { exact: true })).not.toBeVisible();
await expect(card.getByRole('button', { name: /install hooks/i })).toBeVisible();
}
});
test('third-party adapter renders launch-only state and sends its prompt', async ({ page }) => {
let launchPayload: unknown = null; let launchPayload: unknown = null;
await mockProcesses(page); await mockProcesses(page);
await page.route('**/api/tools/detect', route => route.fulfill({ await page.route('**/api/tools/detect', route => route.fulfill({
@@ -293,14 +79,11 @@ test.describe('Launcher rendered states', () => {
id: 'foo-cli', id: 'foo-cli',
displayName: 'Foo CLI', displayName: 'Foo CLI',
launchable: true, launchable: true,
hookCapable: false,
builtin: false, builtin: false,
acceptsInlinePrompt: true, acceptsInlinePrompt: true,
installed: true, installed: true,
installedPath: '/usr/local/bin/foo', installedPath: '/usr/local/bin/foo',
version: '2.1.0', version: '2.1.0',
hooksInstalled: false,
hookPointerPath: null,
}, },
], ],
}), }),
@@ -318,12 +101,7 @@ test.describe('Launcher rendered states', () => {
await expect(page.getByText('Foo CLI', { exact: true })).toBeVisible(); await expect(page.getByText('Foo CLI', { exact: true })).toBeVisible();
await expect(page.getByText(/v2\.1\.0/i)).toBeVisible(); await expect(page.getByText(/v2\.1\.0/i)).toBeVisible();
await expect(page.getByText(/Sent to:/i)).not.toBeVisible(); await expect(page.getByText(/Sent to:/i)).not.toBeVisible();
// Hooks are hidden in v1 (ADR-0002), so there is no "launch only" contrast.
await expect(page.getByText(/Launch only/i)).not.toBeVisible();
await expect(page.getByText(/Hook management is not supported for this tool yet/i)).not.toBeVisible();
await expect(page.getByRole('button', { name: /^Launch$/ })).toBeVisible(); await expect(page.getByRole('button', { name: /^Launch$/ })).toBeVisible();
await expect(page.getByRole('button', { name: /install hooks/i })).not.toBeVisible();
await expect(page.getByRole('button', { name: /^Verify$/ })).not.toBeVisible();
await page.getByLabel(/optional launch prompt/i).fill('summarize adapter context'); await page.getByLabel(/optional launch prompt/i).fill('summarize adapter context');
await expect(page.getByText('Sent to: Foo CLI', { exact: true })).toBeVisible(); await expect(page.getByText('Sent to: Foo CLI', { exact: true })).toBeVisible();