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

@@ -2,12 +2,11 @@
* Tool detection — AI-OS Phase 0.
*
* Detects which external AI tools (Claude Code, Cursor, Claude Desktop, …)
* are installed on the user's machine and whether their hive-mind hooks
* are wired up. Returns a stable envelope (`ToolDetectionResult` in
* @waggle/shared) consumed by:
* are installed on the user's machine. Returns a stable envelope
* (`ToolDetectionResult` in @waggle/shared) consumed by:
*
* - the sidecar route GET /api/tools/detect (Phase 0)
* - the launcher dock + hook-installer UX (Phase 2)
* - the launcher dock (Phase 2)
* - the Mission Control inventory tile (Phase 4)
*
* Design notes:
@@ -20,17 +19,12 @@
* resolves like `which`; on Windows like `where`. The shim takes
* a logical name ('claude'), not a full path, so callers don't
* need to know the per-platform extension (.cmd / .exe / none).
* 3. Hook-install status follows the hive-mind shim-core convention:
* `~/<tool-config-dir>/hive-mind-install.json` is the pointer
* written at install time. We additionally verify that the
* `backup` field still points to an existing file — otherwise the
* pointer is stale and the install is effectively rolled back.
* 4. Detector functions are pure (`(deps) => Promise<DetectedTool>`)
* 3. Detector functions are pure (`(deps) => Promise<DetectedTool>`)
* so they can be unit-tested individually and composed in parallel
* by the orchestrator.
*/
import { access, constants, readFile } from 'node:fs/promises';
import { access, constants } from 'node:fs/promises';
import { homedir, platform as osPlatform } from 'node:os';
import { posix as pathPosix, win32 as pathWin32 } from 'node:path';
import { execFile } from 'node:child_process';
@@ -126,11 +120,6 @@ export interface ToolDetectionDeps {
* top — `null` here means "could not determine".
*/
execVersion?: (binary: string, args: string[]) => Promise<string | null>;
/**
* Read a JSON file. Returns parsed value, or null on any failure
* (missing, malformed, permission denied).
*/
readJson?: (p: string) => Promise<unknown>;
/**
* PATH lookup shim. Given a logical binary name ('claude'), returns
* the resolved absolute path or null. Production implementation uses
@@ -182,15 +171,6 @@ export async function defaultExecVersion(
}
}
async function defaultReadJson(p: string): Promise<unknown> {
try {
const raw = await readFile(p, 'utf8');
return JSON.parse(raw);
} catch {
return null;
}
}
/**
* Env for the `which`/`where` lookup. Fail closed to the non-secret external
* process environment. On POSIX, merge the resolved login-shell
@@ -310,7 +290,6 @@ interface ResolvedDeps {
cwd: string;
exists: (p: string) => Promise<boolean>;
execVersion: (binary: string, args: string[]) => Promise<string | null>;
readJson: (p: string) => Promise<unknown>;
pathFromEnv: (name: string) => Promise<string | null>;
windowsAppExecutables: () => Promise<WindowsAppExecutables>;
}
@@ -325,7 +304,6 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
cwd: opts.cwd ?? process.cwd(),
exists: opts.exists ?? defaultExists,
execVersion: opts.execVersion ?? defaultExecVersion,
readJson: opts.readJson ?? defaultReadJson,
pathFromEnv:
pathFromEnvOpt === undefined
? defaultPathFromEnv
@@ -342,140 +320,7 @@ function resolveDeps(opts: ToolDetectionDeps): ResolvedDeps {
};
}
// ── Hook status (shared across all tools) ───────────────────────────
// Hook-pointer paths + roots come from each tool's ToolManifest (the registry —
// #5), so third-party adapters and the Claude Desktop MCP bridge need no map.
interface HookProbe {
hooksInstalled: boolean;
hookPointerPath: string | null;
}
const CLAUDE_CODE_HOOKS = [
['SessionStart', 'session-start'],
['UserPromptSubmit', 'user-prompt-submit'],
['Stop', 'stop'],
['PreCompact', 'pre-compact'],
] as const;
function objectRecord(value: unknown): Record<string, unknown> | null {
return value !== null && typeof value === 'object' && !Array.isArray(value)
? value as Record<string, unknown>
: null;
}
function tokenizeHookCommand(command: string): string[] | null {
if (/[\r\n\0]/.test(command)) return null;
const tokens: string[] = [];
let index = 0;
while (index < command.length) {
while (command[index] === ' ' || command[index] === '\t') index += 1;
if (index >= command.length) break;
if (command[index] === '"') {
const end = command.indexOf('"', index + 1);
if (end === -1 || end === index + 1) return null;
const token = command.slice(index + 1, end);
if (/[$`%!]/.test(token)) return null;
tokens.push(token);
index = end + 1;
if (index < command.length && command[index] !== ' ' && command[index] !== '\t') return null;
continue;
}
const start = index;
while (index < command.length && command[index] !== ' ' && command[index] !== '\t') {
if (/['";&|<>`^#$%!*?()[\]{}]/.test(command[index])) return null;
index += 1;
}
if (index === start) return null;
tokens.push(command.slice(start, index));
}
return tokens;
}
function isAbsolutePathForPlatform(platform: NodeJS.Platform, candidate: string): boolean {
return platform === 'win32'
? pathWin32.isAbsolute(candidate)
: pathPosix.isAbsolute(candidate);
}
function normalizedHookPath(platform: NodeJS.Platform, candidate: string): string {
const normalized = platform === 'win32' ? candidate.replace(/\\/g, '/') : candidate;
return platform === 'win32' ? normalized.toLowerCase() : normalized;
}
function isNodeExecutable(platform: NodeJS.Platform, candidate: string): boolean {
const normalized = platform === 'win32' ? candidate.toLowerCase() : candidate;
const allowedBasenames = platform === 'win32' ? ['node', 'node.exe'] : ['node'];
if (allowedBasenames.includes(normalized)) return true;
if (!isAbsolutePathForPlatform(platform, candidate)) return false;
const basename = platform === 'win32'
? pathWin32.basename(candidate).toLowerCase()
: pathPosix.basename(candidate);
return allowedBasenames.includes(basename);
}
function isClaudeCodeHookCommand(
command: string,
basename: string,
platform: NodeJS.Platform,
): boolean {
const tokens = tokenizeHookCommand(command);
if (!tokens || (tokens.length !== 2 && tokens.length !== 4)) return false;
if (!isNodeExecutable(platform, tokens[0])) return false;
if (!isAbsolutePathForPlatform(platform, tokens[1])) return false;
if (tokens.length === 4) {
if (tokens[2] !== '--cli-path' || !isAbsolutePathForPlatform(platform, tokens[3])) return false;
}
const scriptPath = normalizedHookPath(platform, tokens[1]);
const expected = `/hive-mind-hooks-claude-code/dist/hooks/${basename}.js`;
const normalizedExpected = platform === 'win32' ? expected.toLowerCase() : expected;
return scriptPath.endsWith(normalizedExpected);
}
function hasActiveClaudeCodeHooks(settings: unknown, platform: NodeJS.Platform): boolean {
const settingsRecord = objectRecord(settings);
const hooks = objectRecord(settingsRecord?.hooks);
if (!hooks) return false;
return CLAUDE_CODE_HOOKS.every(([eventName, basename]) => {
const groups = hooks[eventName];
if (!Array.isArray(groups)) return false;
return groups.some((group) => {
const groupRecord = objectRecord(group);
if (!groupRecord) return false;
const entries = groupRecord.hooks;
if (!Array.isArray(entries)) return false;
return entries.some((entry) => {
const entryRecord = objectRecord(entry);
const command = entryRecord?.command;
return entryRecord?.type === 'command'
&& typeof command === 'string'
&& isClaudeCodeHookCommand(command, basename, platform);
});
});
});
}
async function activeClaudeCodeHooksHealthy(deps: ResolvedDeps): Promise<boolean> {
const settingsPath = joinForPlatform(deps.platform, deps.home, '.claude', 'settings.json');
if (!(await deps.exists(settingsPath))) return false;
return hasActiveClaudeCodeHooks(await deps.readJson(settingsPath), deps.platform);
}
async function activeHooksHealthy(
pointerHealthy: boolean,
toolId: string | undefined,
deps: ResolvedDeps,
): Promise<boolean> {
if (!pointerHealthy) return false;
return toolId !== 'claude-code' || activeClaudeCodeHooksHealthy(deps);
}
// ── Platform roots ──────────────────────────────────────────────────
function nonBlankEnv(deps: ResolvedDeps, name: string): string | null {
const value = deps.env[name]?.trim();
@@ -499,54 +344,6 @@ function hermesHome(deps: ResolvedDeps): string {
: joinForPlatform(deps.platform, deps.home, '.hermes');
}
async function probeHooks(
rel: string,
deps: ResolvedDeps,
hookRoot: ToolManifest['hookRoot'] = 'user-home',
toolId?: string,
): Promise<HookProbe> {
if (!rel) return { hooksInstalled: false, hookPointerPath: null };
const root = hookRoot === 'hermes-home' ? hermesHome(deps) : deps.home;
const pointerPath = joinForPlatform(deps.platform, root, rel);
if (!(await deps.exists(pointerPath))) {
return { hooksInstalled: false, hookPointerPath: null };
}
const parsed = await deps.readJson(pointerPath);
if (!parsed || typeof parsed !== 'object') {
return { hooksInstalled: false, hookPointerPath: pointerPath };
}
const pointer = parsed as Record<string, unknown>;
// Current installers use settings_backup. Keep the legacy `backup` alias so
// older installs remain detectable during upgrade.
const backup = Object.hasOwn(pointer, 'settings_backup')
? pointer.settings_backup
: pointer.backup;
const hooksDir = pointer.hooks_dir;
const hooksDirValid = hooksDir === undefined || hooksDir === null
? true
: typeof hooksDir === 'string' && hooksDir.length > 0 && await deps.exists(hooksDir);
if (!hooksDirValid) return { hooksInstalled: false, hookPointerPath: pointerPath };
if (typeof backup === 'string' && backup.length > 0) {
return {
hooksInstalled: await activeHooksHealthy(await deps.exists(backup), toolId, deps),
hookPointerPath: pointerPath,
};
}
// Create-if-missing adapters correctly have no backup. Their pointer is
// healthy only while the config they created still exists.
if (backup === null && pointer.created_by_us === true && typeof pointer.config_path === 'string') {
return {
hooksInstalled: await activeHooksHealthy(
await deps.exists(pointer.config_path),
toolId,
deps,
),
hookPointerPath: pointerPath,
};
}
return { hooksInstalled: false, hookPointerPath: pointerPath };
}
// ── Per-tool detectors ──────────────────────────────────────────────
/**
@@ -562,9 +359,7 @@ async function detectByPath(
id: string,
binaryName: string,
deps: ResolvedDeps,
hookPointer: string,
displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> {
const base: DetectedTool = {
id,
@@ -572,16 +367,11 @@ async function detectByPath(
installed: false,
installedPath: null,
version: null,
hooksInstalled: false,
hookPointerPath: null,
};
const resolved = await deps.pathFromEnv(binaryName);
if (!resolved) return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
if (!(await deps.exists(resolved))) {
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
}
if (!resolved) return base;
if (!(await deps.exists(resolved))) return base;
const versionRaw = await deps.execVersion(resolved, ['--version']);
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
const blockedWindowsAppsCodex =
versionRaw === null && isBlockedWindowsAppsCodexPath(id, deps.platform, resolved);
return {
@@ -593,7 +383,6 @@ async function detectByPath(
diagnostic: blockedWindowsAppsCodex
? CODEX_WINDOWS_APPS_DIAGNOSTIC
: versionRaw ? undefined : '--version exec failed',
...hookProbe,
};
}
@@ -609,9 +398,7 @@ function hermesWindowsCandidatePaths(deps: ResolvedDeps): string[] {
async function detectHealthyWindowsHermes(
binaryName: string,
deps: ResolvedDeps,
hookPointer: string,
displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> {
const pathCandidate = await deps.pathFromEnv(binaryName);
const candidates = [pathCandidate, ...hermesWindowsCandidatePaths(deps)]
@@ -631,7 +418,6 @@ async function detectHealthyWindowsHermes(
installed: true,
installedPath: candidate,
version,
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
};
}
}
@@ -644,7 +430,6 @@ async function detectHealthyWindowsHermes(
version: null,
launchable: firstExisting ? false : undefined,
diagnostic: firstExisting ? HERMES_WINDOWS_HEALTH_DIAGNOSTIC : undefined,
...(await probeHooks(hookPointer, deps, hookRoot, 'hermes')),
};
}
@@ -750,9 +535,7 @@ async function detectByCandidates(
candidates: string[],
deps: ResolvedDeps,
withVersion: boolean,
hookPointer: string,
displayName: string,
hookRoot?: ToolManifest['hookRoot'],
): Promise<DetectedTool> {
const base: DetectedTool = {
id,
@@ -760,15 +543,12 @@ async function detectByCandidates(
installed: false,
installedPath: null,
version: null,
hooksInstalled: false,
hookPointerPath: null,
};
for (const candidate of candidates) {
if (await deps.exists(candidate)) {
const versionRaw = withVersion
? await deps.execVersion(candidate, ['--version'])
: null;
const hookProbe = await probeHooks(hookPointer, deps, hookRoot, id);
return {
...base,
installed: true,
@@ -776,11 +556,10 @@ async function detectByCandidates(
version: versionRaw,
diagnostic:
withVersion && versionRaw === null ? '--version exec failed' : undefined,
...hookProbe,
};
}
}
return { ...base, ...(await probeHooks(hookPointer, deps, hookRoot, id)) };
return base;
}
// ── Registry-driven detection ───────────────────────────────────────
@@ -802,7 +581,6 @@ function withManifestMetadata(tool: DetectedTool, manifest: ToolManifest): Detec
...tool,
releaseStatus: manifest.releaseStatus,
launchable: tool.launchable ?? manifest.launchable,
hookCapable: manifest.hookCapable,
builtin: manifest.builtin === true,
acceptsInlinePrompt: Boolean(manifest.promptArgTemplate?.length),
capabilities: manifest.capabilities,
@@ -815,18 +593,12 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
if (m.detect.kind === 'path') {
if (m.id === 'hermes' && deps.platform === 'win32') {
return withManifestMetadata(
await detectHealthyWindowsHermes(
m.detect.binaryName,
deps,
m.hookPointer,
m.displayName,
m.hookRoot,
),
await detectHealthyWindowsHermes(m.detect.binaryName, deps, m.displayName),
m,
);
}
return withManifestMetadata(
await detectByPath(m.id, m.detect.binaryName, deps, m.hookPointer, m.displayName, m.hookRoot),
await detectByPath(m.id, m.detect.binaryName, deps, m.displayName),
m,
);
}
@@ -838,9 +610,7 @@ async function detectFromManifest(m: ToolManifest, deps: ResolvedDeps): Promise<
candidates,
deps,
/* withVersion */ false,
m.hookPointer,
m.displayName,
m.hookRoot,
),
m,
);