moving
Some checks failed
Installer Smoke / installer-smoke (push) Has been cancelled

This commit is contained in:
Oleg Maslov
2026-09-02 10:10:29 +02:00
commit 0c3e2ead3b
3841 changed files with 970576 additions and 0 deletions

View File

@@ -0,0 +1,166 @@
/**
* Cursor EventAdapter + JsonRegisterSpec.
*
* Cursor's hook surface renames the four lifecycle events and degrades two
* of them relative to claude-code (spec §5.3):
* - SessionStart → `sessionStart`. The inject response is shaped
* `{ additional_context: text }` (a rename of CC's
* `hookSpecificOutput.additionalContext`), so `formatInject` overrides
* the default.
* - UserPromptSubmit → `beforeSubmitPrompt`. SAVE-ONLY — it cannot inject
* context (stdout is only `{ continue, user_message }`). The shared
* UserPromptSubmit body never injects, so no adapter change is needed;
* the README documents the degradation.
* - Stop → `stop`. The completed turn is delivered via the base field
* `transcript_path` (NOT inline), so `extractResponse` is ASYNC and
* reads the file off disk. It is defensive: tolerates a missing/empty
* path (transcripts disabled), does NOT assume JSONL, and fails open
* (returns undefined rather than throwing).
* - PreCompact → `preCompact`. Observational only — it cannot block or
* reorder, so `compact_memory` runs best-effort / fire-and-forget.
*
* The register shape is FLAT (`{ command, type:'command', timeout }`) under
* `hooks.<event>` arrays — unlike codex's `{ matcher, hooks:[...] }`
* wrapper. The marker is carried for byte-identical reversible uninstall.
*/
import { readFile } from 'node:fs/promises';
import {
pickStringField,
HIVE_MIND_MARKER_BASE,
type EventAdapter,
type ExtractContext,
type JsonRegisterSpec,
type Lifecycle,
} from '@waggle/hive-mind-hooks-core';
/** Per-tool marker stamped on every group we add — used by uninstall/verify. */
export const HIVE_MIND_MARKER = `${HIVE_MIND_MARKER_BASE}/cursor-hooks`;
/** Canonical lifecycle → Cursor native event key (field renames). */
export const CURSOR_EVENT_NAME: Record<Lifecycle, string | undefined> = {
'session-start': 'sessionStart',
'user-prompt-submit': 'beforeSubmitPrompt',
'stop': 'stop',
'pre-compact': 'preCompact',
};
function asObject(payload: unknown): Record<string, unknown> | undefined {
return payload && typeof payload === 'object'
? (payload as Record<string, unknown>)
: undefined;
}
/**
* Defensive transcript reader for Cursor's Stop event. Cursor writes the
* completed turn to a file referenced by the base `transcript_path` field
* rather than inlining it. We:
* - tolerate a missing/empty path (transcripts disabled) → undefined;
* - prefer the caller-supplied `ctx.readFile`, else use node fs;
* - do NOT assume a JSONL structure — the raw file text IS the response
* fallback (the shared summarizer is text-tolerant);
* - fail open: any read error returns undefined, never throws.
*/
async function readTranscript(
transcriptPath: string,
ctx: ExtractContext,
): Promise<string | undefined> {
try {
const text = ctx.readFile
? await ctx.readFile(transcriptPath)
: await readFile(transcriptPath, 'utf-8');
const trimmed = text.trim();
return trimmed.length > 0 ? trimmed : undefined;
} catch {
return undefined;
}
}
/** The Cursor EventAdapter consumed by the shared lifecycle handler bodies. */
export const cursorAdapter: EventAdapter = {
source: 'cursor',
eventName: CURSOR_EVENT_NAME,
extractCwd(payload): string | undefined {
return pickStringField(payload, 'cwd', 'workspace_root', 'workspaceRoot');
},
extractSessionId(payload): string | undefined {
return pickStringField(payload, 'conversation_id', 'conversationId', 'session_id', 'sessionId');
},
extractPrompt(payload): string | undefined {
return pickStringField(payload, 'prompt', 'user_message', 'text');
},
async extractResponse(payload, ctx): Promise<string | undefined> {
// Cursor delivers the completed turn via the base `transcript_path`
// field (read off disk), not inline. Fall back to any inline keys for
// forward-compat, then to the transcript file.
const inline = pickStringField(payload, 'response', 'assistant_message', 'transcript');
if (inline) return inline;
const transcriptPath = pickStringField(payload, 'transcript_path', 'transcriptPath');
if (!transcriptPath) return undefined;
return readTranscript(transcriptPath, ctx);
},
extractParent(payload): string | undefined {
return pickStringField(payload, 'parent_frame_id', 'prompt_frame_id');
},
/**
* Cursor's `sessionStart` inject response is `{ additional_context, env }`.
* We supply only `additional_context` (a rename of CC's
* `hookSpecificOutput.additionalContext`).
*/
formatInject(additionalContext: string): unknown {
return { additional_context: additionalContext };
},
};
// ── JsonRegisterSpec (cursor FLAT `{ command, type, timeout }` group) ────
interface CursorGroup {
command: string;
type: 'command';
timeout: number;
_hiveMindShim?: string;
}
/**
* The Cursor register spec for `jsonRegister`/`jsonUnregister`. Groups live
* under `hooks.<event>` arrays as FLAT command objects (no `{matcher,hooks}`
* wrapper). `ensureSkeleton` seeds `version: 1` on a fresh config.
*/
export const cursorRegisterSpec: JsonRegisterSpec = {
hooksKey: 'hooks',
eventName: CURSOR_EVENT_NAME,
buildGroup(_lifecycle: Lifecycle, command: string, timeout: number): Record<string, unknown> {
const group: CursorGroup = {
command,
type: 'command',
timeout,
_hiveMindShim: HIVE_MIND_MARKER,
};
return group as unknown as Record<string, unknown>;
},
isHiveGroup(group: unknown): boolean {
const g = asObject(group);
return !!g && g['_hiveMindShim'] === HIVE_MIND_MARKER;
},
groupCommand(group: unknown): string | undefined {
const g = asObject(group);
const cmd = g?.['command'];
return typeof cmd === 'string' ? cmd : undefined;
},
ensureSkeleton(root: Record<string, unknown>): Record<string, unknown> {
// Cursor's hooks.json skeleton is `{ version: 1, hooks: {} }`. Seed the
// version only when absent; never clobber a user-set version.
if (root['version'] === undefined) return { version: 1, ...root };
return root;
},
};

View File

@@ -0,0 +1,169 @@
#!/usr/bin/env node
/**
* `cursor-hooks` — CLI entry for the @waggle/hive-mind-hooks-cursor shim.
*
* cursor-hooks install Patch ~/.cursor/hooks.json (additive, create-if-missing).
* cursor-hooks uninstall Restore the byte-identical pre-install state (or remove
* the hooks.json we created).
* cursor-hooks verify Smoke-check the install + hive-mind-cli reachability.
*/
import { install, type InstallResult } from '../install.js';
import { uninstall, type UninstallResult } from '../uninstall.js';
import { verify, type VerifyResult } from '../verify.js';
type ParsedArgs = {
command: 'install' | 'uninstall' | 'verify' | 'help';
flags: Record<string, string | boolean>;
};
function parseArgs(argv: readonly string[]): ParsedArgs {
const [first, ...rest] = argv;
const valid = ['install', 'uninstall', 'verify'] as const;
const command = first === '-h' || first === '--help' || first === undefined
? 'help'
: valid.includes(first as typeof valid[number]) ? first as typeof valid[number] : 'help';
const flags: Record<string, string | boolean> = {};
for (let i = 0; i < rest.length; i += 1) {
const arg = rest[i];
if (!arg.startsWith('--')) continue;
const eq = arg.indexOf('=');
if (eq !== -1) {
flags[arg.slice(2, eq)] = arg.slice(eq + 1);
} else {
const next = rest[i + 1];
if (next && !next.startsWith('--')) {
flags[arg.slice(2)] = next;
i += 1;
} else {
flags[arg.slice(2)] = true;
}
}
}
return { command: command as ParsedArgs['command'], flags };
}
function printHelp(): void {
process.stdout.write([
'Usage: cursor-hooks <command> [options]',
'',
'Commands:',
' install Patch ~/.cursor/hooks.json (additive, create-if-missing, with backup).',
' uninstall Restore the byte-identical pre-install hooks.json (or remove it if created).',
' verify Smoke-check the install + hive-mind-cli reachability.',
'',
'Options:',
' --help, -h Show this help.',
' --hooks-dir <PATH> Override compiled hooks directory (testing).',
' --hook-timeout <S> Override per-hook timeout in seconds (default 5).',
' --cli-path <PATH> Absolute path to the hive-mind-cli binary or its',
' compiled JS entry. Required on Windows (npm bin',
' is a .cmd shim) and recommended for production',
' installs. Threaded into every hook command.',
'',
'Repo: https://github.com/marolinik/waggle-os',
'',
].join('\n'));
}
function printInstallSummary(result: InstallResult): void {
const lines: string[] = [
'hive-mind/cursor-hooks: install',
` - hooks.json: ${result.paths.configPath}`,
` - backup: ${result.backupPath ?? '(none — hooks.json created by us)'}`,
` - pointer: ${result.pointerPath}`,
` - added hooks: ${result.installedHooks.join(', ')}`,
` - cli path: ${result.cliPath ?? '(default — hive-mind-cli on PATH)'}`,
'',
'Restart required:',
' Restart Cursor for hive-mind hooks to take effect.',
'',
'Note: cursor degrades two events — beforeSubmitPrompt saves only (no',
'inject) and preCompact is observational (best-effort). See the README',
'Capture fidelity table.',
'',
'Done. New Cursor sessions will silently capture to hive-mind.',
'Run "cursor-hooks verify" to inspect, "cursor-hooks uninstall" to revert.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printUninstallSummary(result: UninstallResult): void {
const lines: string[] = [
'hive-mind/cursor-hooks: uninstall',
` - hooks.json: ${result.paths.configPath}`,
` - restored from: ${result.restoredFrom ?? '(none — removed file we created)'}`,
` - created removed: ${result.createdRemoved ? 'yes' : 'no'}`,
` - backup removed: ${result.backupRemoved ? 'yes' : 'no (kept on disk)'}`,
` - pointer removed: ${result.pointerRemoved ? 'yes' : 'no'}`,
'',
'Restart Cursor for the change to take effect.',
'hooks.json is byte-identical to pre-install state (or removed if we created it).',
'',
];
process.stdout.write(lines.join('\n'));
}
function printVerifySummary(result: VerifyResult): void {
const lines: string[] = ['hive-mind/cursor-hooks: verify'];
for (const c of result.checks) {
const tag = c.ok ? 'PASS' : 'FAIL';
const detail = c.detail ? ` — ${c.detail}` : '';
lines.push(` [${tag}] ${c.name}${detail}`);
}
lines.push('');
lines.push(result.ok ? 'All checks passed.' : 'One or more checks failed.');
lines.push('');
process.stdout.write(lines.join('\n'));
}
async function main(): Promise<void> {
const { command, flags } = parseArgs(process.argv.slice(2));
if (command === 'help') {
printHelp();
return;
}
const hooksDir = typeof flags['hooks-dir'] === 'string' ? flags['hooks-dir'] : undefined;
const hookTimeoutRaw = flags['hook-timeout'];
const hookTimeoutSeconds = typeof hookTimeoutRaw === 'string'
? Number.parseInt(hookTimeoutRaw, 10) || undefined
: undefined;
const cliPath = typeof flags['cli-path'] === 'string' ? flags['cli-path'] : undefined;
const baseOpts = {
moduleUrl: import.meta.url,
...(hooksDir ? { hooksDir } : {}),
};
try {
if (command === 'install') {
const installOpts = {
...baseOpts,
...(hookTimeoutSeconds !== undefined ? { hookTimeoutSeconds } : {}),
...(cliPath !== undefined ? { cliPath } : {}),
};
const result = await install(installOpts);
printInstallSummary(result);
return;
}
if (command === 'uninstall') {
const result = await uninstall(baseOpts);
printUninstallSummary(result);
return;
}
if (command === 'verify') {
const result = await verify(baseOpts);
printVerifySummary(result);
if (!result.ok) process.exit(1);
return;
}
} catch (err) {
process.stderr.write(`error: ${err instanceof Error ? err.message : String(err)}\n`);
process.exit(1);
}
}
void main();

View File

@@ -0,0 +1,38 @@
/**
* Cursor preCompact hook — fired around Cursor's context truncation.
* Triggers `cleanup_frames` so superseded P/B frames merge before the
* native compaction step. Thin entrypoint over the shared handler body.
*
* DEGRADED (spec §5.3): cursor's `preCompact` is OBSERVATIONAL only — it
* cannot block or reorder, so "run compact_memory BEFORE the host
* truncates" is best-effort, not guaranteed-before. `cleanup_frames` runs
* fire-and-forget; if hive-mind-cli is unreachable the hook exits 0.
*/
import {
makePreCompactHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { cursorAdapter } from '../adapter.js';
export async function runPreCompact(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makePreCompactHandler(cursorAdapter), {
name: 'pre-compact',
loggerPrefix: 'cursor-hooks',
...opts,
});
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runPreCompact();
}

View File

@@ -0,0 +1,39 @@
/**
* Cursor sessionStart hook — recalls the top-N most relevant frames from
* personal memory and injects them as additional context for the new
* Cursor session. Thin entrypoint over the shared handler body. The cursor
* adapter's `formatInject` shapes the inject response as
* `{ additional_context: text }` (cursor's `sessionStart` convention).
*
* If hive-mind-cli is unreachable, the hook logs and exits 0 with no
* output (fail-open) — the session starts as it would have without the
* shim.
*/
import {
makeSessionStartHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { cursorAdapter } from '../adapter.js';
export async function runSessionStart(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeSessionStartHandler(cursorAdapter), {
name: 'session-start',
loggerPrefix: 'cursor-hooks',
...opts,
});
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runSessionStart();
}

View File

@@ -0,0 +1,40 @@
/**
* Cursor stop hook — fired when an assistant turn completes. Summarizes the
* turn deterministically (no LLM call) and writes it as an `important`
* frame parented to the originating prompt frame when known. Thin
* entrypoint over the shared handler body.
*
* DEGRADED (spec §5.3): cursor delivers the completed turn via the base
* field `transcript_path` (NOT inline). The cursor adapter's
* `extractResponse` is async, reads that file defensively (tolerates a
* missing path when transcripts are disabled, does not assume JSONL), and
* fails open — returning undefined rather than throwing.
*/
import {
makeStopHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { cursorAdapter } from '../adapter.js';
export async function runStop(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeStopHandler(cursorAdapter), {
name: 'stop',
loggerPrefix: 'cursor-hooks',
...opts,
});
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runStop();
}

View File

@@ -0,0 +1,39 @@
/**
* Cursor beforeSubmitPrompt hook — captures the user prompt as a temporary
* frame scoped to the current Cursor session. Thin entrypoint over the
* shared handler body.
*
* DEGRADED (spec §5.3): cursor's `beforeSubmitPrompt` is SAVE-ONLY — its
* stdout is only `{ continue, user_message }`, so it cannot inject recalled
* context. hive-mind's UserPromptSubmit only persists, so this is fully
* compatible; the hook emits no stdout and is a pure side-effect on the
* .mind file.
*/
import {
makeUserPromptSubmitHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { cursorAdapter } from '../adapter.js';
export async function runUserPromptSubmit(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeUserPromptSubmitHandler(cursorAdapter), {
name: 'user-prompt-submit',
loggerPrefix: 'cursor-hooks',
...opts,
});
}
const isMain = (() => {
try {
if (typeof process.argv[1] !== 'string') return false;
const url = new URL(`file://${process.argv[1].replace(/\\/g, '/')}`);
return url.href === import.meta.url;
} catch {
return false;
}
})();
if (isMain) {
void runUserPromptSubmit();
}

View File

@@ -0,0 +1,50 @@
/**
* @waggle/hive-mind-hooks-cursor — barrel export.
*
* Cursor silent-capture shim for hive-mind. A JSON installer built on
* @waggle/hive-mind-hooks-core, with create-if-missing semantics (cursor's
* `~/.cursor/hooks.json` is optional, and is a SEPARATE file from Cursor's
* `settings.json`). Field-renamed events (sessionStart / beforeSubmitPrompt
* / stop / preCompact) with two degraded events (beforeSubmitPrompt is
* save-only; preCompact is observational; Stop reads the turn from
* `transcript_path`). Programmatic install / uninstall / verify lifecycle;
* most users invoke the `cursor-hooks` bin.
*/
export type {
InstallOptions,
InstallResult,
} from './install.js';
export { install } from './install.js';
export type {
UninstallOptions,
UninstallResult,
} from './uninstall.js';
export { uninstall } from './uninstall.js';
export type {
VerifyOptions,
VerifyResult,
VerifyCheck,
} from './verify.js';
export { verify } from './verify.js';
export type {
CursorPaths,
ResolvePathsOptions,
HookBasename,
} from './paths.js';
export {
resolvePaths,
allHookBasenames,
backupPathFor,
hookCommandFor,
} from './paths.js';
export {
cursorAdapter,
cursorRegisterSpec,
CURSOR_EVENT_NAME,
HIVE_MIND_MARKER,
} from './adapter.js';

View File

@@ -0,0 +1,164 @@
/**
* Programmatic install entry point for the Cursor hive-mind hooks.
*
* Steps:
* 1. Read existing `~/.cursor/hooks.json` IF it exists (create-if-missing
* — cursor's hooks.json is OPTIONAL on a fresh install). It is a
* SEPARATE file from Cursor's `settings.json`; we never touch editor
* preferences.
* 2. If it pre-existed, write a byte-identical backup; if absent, skip
* the backup and record `created_by_us=true`.
* 3. Additively merge the four hive-mind hook groups (flat
* `{ command, type, timeout }` shape) into `hooks.<event>` arrays via
* `jsonRegister`. A fresh config is seeded `{ version: 1, hooks: {} }`
* by the spec's `ensureSkeleton`. Existing entries preserved verbatim.
* 4. Write the merged JSON back over `hooks.json`.
* 5. Drop a pointer file at `~/.cursor/hive-mind-install.json` so a future
* `uninstall` knows whether to restore the backup or delete the file
* we created.
*
* Round-trip guarantee (pre-existed case): the pre-install hooks.json
* content equals the byte-identical backup; `uninstall` restores it.
* Created case: `uninstall` deletes the file we created (no orphan).
*/
import { readFile, writeFile, mkdir } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { dirname } from 'node:path';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import {
backupByteIdentical,
hookCommandFor,
hookScriptPath,
jsonRegister,
normalizeCliPath,
writePointer,
type InstallPointer,
type JsonRegisterEntry,
type Lifecycle,
} from '@waggle/hive-mind-hooks-core';
import { resolvePaths, allHookBasenames, type CursorPaths, type ResolvePathsOptions } from './paths.js';
import { cursorRegisterSpec } from './adapter.js';
export interface InstallResult {
paths: CursorPaths;
/** The byte-identical backup written when hooks.json pre-existed, else null. */
backupPath: string | null;
pointerPath: string;
installedHooks: readonly string[];
/** True when hooks.json did NOT pre-exist and we created it. */
createdByUs: boolean;
/** The cli_path embedded in hook commands (undefined = default lookup at runtime). */
cliPath?: string;
}
export interface InstallOptions extends ResolvePathsOptions {
/** Per-hook timeout, seconds. Default 5. */
hookTimeoutSeconds?: number;
/** Override clock for deterministic tests. */
now?: () => Date;
/** Logger override. */
logger?: Logger;
/**
* Absolute path to the hive-mind-cli binary or its compiled JS entry.
* Required on Windows (npm bin shim is `.cmd` and can't be exec'd
* without a shell). Threaded into every hook command as
* `--cli-path "<path>"`.
*/
cliPath?: string;
}
const DEFAULT_HOOK_TIMEOUT_S = 5;
const POINTER_VERSION = '0.1.0';
/** Canonical lifecycle for each hook basename (basenames mirror lifecycle ids). */
const LIFECYCLE_BY_BASENAME: Record<string, Lifecycle> = {
'session-start': 'session-start',
'user-prompt-submit': 'user-prompt-submit',
'stop': 'stop',
'pre-compact': 'pre-compact',
};
async function ensureDir(p: string): Promise<void> {
if (!existsSync(p)) await mkdir(p, { recursive: true });
}
export async function install(opts: InstallOptions = {}): Promise<InstallResult> {
const log = opts.logger ?? createLogger({ name: 'cursor-hooks/install' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const now = opts.now ?? ((): Date => new Date());
log.info('install starting', { config: paths.configPath, hooksDir: paths.hooksDir });
// Read the existing config if present; create-if-missing otherwise.
let existingConfig: Record<string, unknown> | undefined;
const preExisted = existsSync(paths.configPath);
if (preExisted) {
const originalContent = await readFile(paths.configPath, 'utf-8');
try {
const parsed: unknown = JSON.parse(originalContent);
existingConfig = parsed && typeof parsed === 'object' && !Array.isArray(parsed)
? (parsed as Record<string, unknown>)
: {};
} catch (err) {
throw new Error(
`failed to parse existing ${paths.configPath} as JSON: ` +
(err instanceof Error ? err.message : String(err)),
);
}
}
await ensureDir(dirname(paths.pointerPath));
// Byte-identical backup of the original config (no-op when absent).
const { backupPath, preExisted: backedUp } = await backupByteIdentical(
paths.configPath,
now().toISOString(),
);
if (backedUp) log.info('hooks.json backed up', { backupPath });
const cliPath = normalizeCliPath(opts.cliPath);
const timeout = opts.hookTimeoutSeconds ?? DEFAULT_HOOK_TIMEOUT_S;
const basenames = allHookBasenames();
const entries: JsonRegisterEntry[] = basenames.map((basename) => ({
lifecycle: LIFECYCLE_BY_BASENAME[basename],
command: hookCommandFor(hookScriptPath(paths.hooksDir, basename), cliPath),
timeout,
}));
const merged = jsonRegister(existingConfig, entries, cursorRegisterSpec);
const mergedJson = JSON.stringify(merged, null, 2) + '\n';
await writeFile(paths.configPath, mergedJson, 'utf-8');
const createdByUs = !preExisted;
const pointer: InstallPointer = {
version: POINTER_VERSION,
installed_at: now().toISOString(),
config_path: paths.configPath,
settings_backup: backupPath,
created_by_us: createdByUs,
hooks_dir: paths.hooksDir,
installed_hooks: basenames,
cli_path: cliPath ?? null,
};
await writePointer(paths.pointerPath, pointer);
log.info('install complete', {
added: entries.length,
createdByUs,
cliPath: cliPath ?? '(PATH lookup)',
});
const result: InstallResult = {
paths,
backupPath,
pointerPath: paths.pointerPath,
installedHooks: basenames,
createdByUs,
};
if (cliPath !== undefined) result.cliPath = cliPath;
return result;
}

View File

@@ -0,0 +1,73 @@
/**
* Filesystem path helpers for the Cursor hive-mind hook install lifecycle.
*
* Mirrors the Codex `paths.ts` shape, but targets Cursor's standalone
* `~/.cursor/hooks.json` (JSON) — a SEPARATE file from Cursor's
* `settings.json` (editor prefs); we never touch editor preferences. The
* Windows-safe backup path + `--cli-path` quoting + hooks-dir resolution
* are reused verbatim from `@waggle/hive-mind-hooks-core` so cursor reads
* like the reference.
*/
import { homedir } from 'node:os';
import { join, resolve } from 'node:path';
import {
backupPathFor,
hookCommandFor,
hooksDirFromModuleUrl,
} from '@waggle/hive-mind-hooks-core';
export interface CursorPaths {
/** Cursor config root (`~/.cursor/`). */
cursorDir: string;
/** `~/.cursor/hooks.json` — the standalone hooks config (NOT settings.json). */
configPath: string;
/** `~/.cursor/hive-mind-install.json` — pointer to the active backup. */
pointerPath: string;
/** Directory where compiled hook scripts live (`dist/hooks/`). */
hooksDir: string;
}
export interface ResolvePathsOptions {
/** Override $HOME for tests. */
home?: string;
/** Override the URL used to locate dist/hooks (defaults to import.meta.url at runtime). */
moduleUrl?: string;
/** Override hooks directory directly (wins over moduleUrl). */
hooksDir?: string;
}
const HOOK_BASENAMES = [
'session-start',
'user-prompt-submit',
'stop',
'pre-compact',
] as const;
export type HookBasename = typeof HOOK_BASENAMES[number];
export function allHookBasenames(): readonly HookBasename[] {
return HOOK_BASENAMES;
}
export function resolvePaths(opts: ResolvePathsOptions = {}): CursorPaths {
const home = opts.home ?? homedir();
const cursorDir = join(home, '.cursor');
const configPath = join(cursorDir, 'hooks.json');
const pointerPath = join(cursorDir, 'hive-mind-install.json');
let hooksDir: string;
if (opts.hooksDir) {
hooksDir = resolve(opts.hooksDir);
} else if (opts.moduleUrl) {
hooksDir = hooksDirFromModuleUrl(opts.moduleUrl);
} else {
// Fallback for ad-hoc test use — install.ts always passes moduleUrl.
hooksDir = resolve(process.cwd(), 'dist', 'hooks');
}
return { cursorDir, configPath, pointerPath, hooksDir };
}
/** Re-export the shared Windows-safe helpers so cursor modules read like CC. */
export { backupPathFor, hookCommandFor };

View File

@@ -0,0 +1,76 @@
/**
* Programmatic uninstall entry point for the Cursor hive-mind hooks.
*
* Round-trip guarantee:
* - `created_by_us=false` (hooks.json pre-existed): restore the
* byte-identical backup the installer wrote; refuse to delete the
* backup unless the in-place readback matches.
* - `created_by_us=true` (we created hooks.json): delete the file we
* created — never orphan it, never leave a backup behind.
*
* Both branches are handled by the shared `restoreFromBackup` primitive.
*/
import { unlink } from 'node:fs/promises';
import { existsSync } from 'node:fs';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import {
readPointer,
restoreFromBackup,
} from '@waggle/hive-mind-hooks-core';
import { resolvePaths, type CursorPaths, type ResolvePathsOptions } from './paths.js';
export interface UninstallResult {
paths: CursorPaths;
/** Backup restored from, or null when we deleted a file we created. */
restoredFrom: string | null;
/** True when created_by_us=true and we removed the config we created. */
createdRemoved: boolean;
pointerRemoved: boolean;
backupRemoved: boolean;
}
export interface UninstallOptions extends ResolvePathsOptions {
logger?: Logger;
/** If false, leaves the backup file in place after restore. Default true. */
cleanupBackup?: boolean;
}
export async function uninstall(opts: UninstallOptions = {}): Promise<UninstallResult> {
const log = opts.logger ?? createLogger({ name: 'cursor-hooks/uninstall' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const cleanup = opts.cleanupBackup ?? true;
if (!existsSync(paths.pointerPath)) {
throw new Error(
`no install pointer found at ${paths.pointerPath}. ` +
`Was @waggle/hive-mind-hooks-cursor ever installed for this user?`,
);
}
const pointer = await readPointer(paths.pointerPath);
const restore = await restoreFromBackup({
configPath: paths.configPath,
pointer,
cleanupBackup: cleanup,
});
if (restore.createdRemoved) {
log.info('cursor hooks.json removed (created by us)', { config: paths.configPath });
} else {
log.info('cursor hooks.json restored byte-identical', { config: paths.configPath });
}
await unlink(paths.pointerPath);
return {
paths,
restoredFrom: restore.restoredFrom,
createdRemoved: restore.createdRemoved,
pointerRemoved: true,
backupRemoved: restore.backupRemoved,
};
}

View File

@@ -0,0 +1,162 @@
/**
* Smoke-check the Cursor install: hooks.json exists + parses + references
* live hook scripts, and hive-mind-cli answers a `--help` probe. Plus the
* cursor-specific advisory (spec §5.3 / §6.2): editing `hooks.json` likely
* needs a Cursor restart for the hooks to take effect.
*
* Probe priority for `cli_path`:
* 1. Explicit `opts.cliPath` (caller override)
* 2. `cli_path` recorded in `~/.cursor/hive-mind-install.json`
* 3. Bare `'hive-mind-cli'` on PATH
*/
import { readFile, access } from 'node:fs/promises';
import { constants, existsSync } from 'node:fs';
import { join } from 'node:path';
import { spawn } from 'node:child_process';
import { createLogger, type Logger } from '@waggle/hive-mind-shim-core';
import { hasHiveEntries } from '@waggle/hive-mind-hooks-core';
import { resolvePaths, allHookBasenames, type ResolvePathsOptions } from './paths.js';
import { cursorRegisterSpec } from './adapter.js';
export interface VerifyCheck {
name: string;
ok: boolean;
detail?: string;
}
export interface VerifyResult {
ok: boolean;
checks: VerifyCheck[];
}
export interface VerifyOptions extends ResolvePathsOptions {
logger?: Logger;
/** Override hive-mind-cli executable name. Default 'hive-mind-cli'. */
cliPath?: string;
/** Test hook for spawn. */
spawnImpl?: typeof spawn;
}
async function fileReadable(p: string): Promise<boolean> {
try { await access(p, constants.R_OK); return true; } catch { return false; }
}
function isJsPath(p: string): boolean {
return p.endsWith('.js') || p.endsWith('.mjs') || p.endsWith('.cjs');
}
function probeCliVersion(
cliPath: string,
spawnImpl: typeof spawn,
timeoutMs: number,
): Promise<{ ok: boolean; output: string }> {
return new Promise((resolve) => {
let settled = false;
const command = isJsPath(cliPath) ? process.execPath : cliPath;
const args = isJsPath(cliPath) ? [cliPath, '--help'] : ['--help'];
const child = spawnImpl(command, args, { stdio: ['ignore', 'pipe', 'pipe'] });
const stdout: Buffer[] = [];
const stderr: Buffer[] = [];
const timer = setTimeout(() => {
if (settled) return;
settled = true;
try { child.kill('SIGTERM'); } catch { /* gone */ }
resolve({ ok: false, output: 'timed out probing hive-mind-cli' });
}, timeoutMs);
child.stdout?.on('data', (c: Buffer) => stdout.push(c));
child.stderr?.on('data', (c: Buffer) => stderr.push(c));
child.on('error', (err) => {
if (settled) return;
settled = true;
clearTimeout(timer);
resolve({ ok: false, output: err instanceof Error ? err.message : String(err) });
});
child.on('exit', (code) => {
if (settled) return;
settled = true;
clearTimeout(timer);
const out = Buffer.concat(stdout).toString('utf-8').slice(0, 200);
const err = Buffer.concat(stderr).toString('utf-8').slice(0, 200);
resolve({ ok: code === 0, output: code === 0 ? out : err });
});
});
}
export async function verify(opts: VerifyOptions = {}): Promise<VerifyResult> {
const log = opts.logger ?? createLogger({ name: 'cursor-hooks/verify' });
const paths = resolvePaths({
...(opts.home !== undefined ? { home: opts.home } : {}),
...(opts.hooksDir !== undefined ? { hooksDir: opts.hooksDir } : { moduleUrl: import.meta.url }),
});
const checks: VerifyCheck[] = [];
// 1. hooks.json exists and parses.
if (!existsSync(paths.configPath)) {
checks.push({ name: 'hooks.json exists', ok: false, detail: paths.configPath });
return { ok: false, checks };
}
checks.push({ name: 'hooks.json exists', ok: true, detail: paths.configPath });
let parsed: Record<string, unknown>;
try {
const raw: unknown = JSON.parse(await readFile(paths.configPath, 'utf-8'));
parsed = raw && typeof raw === 'object' && !Array.isArray(raw)
? (raw as Record<string, unknown>)
: {};
checks.push({ name: 'hooks.json parses as JSON', ok: true });
} catch (err) {
checks.push({
name: 'hooks.json parses as JSON',
ok: false,
detail: err instanceof Error ? err.message : String(err),
});
return { ok: false, checks };
}
// 2. hive-mind entries present.
checks.push({
name: 'hooks.json contains hive-mind entries',
ok: hasHiveEntries(parsed, cursorRegisterSpec),
});
// 3. each hive hook entry points at an existing dist file.
for (const basename of allHookBasenames()) {
const scriptPath = join(paths.hooksDir, `${basename}.js`);
const ok = await fileReadable(scriptPath);
checks.push({ name: `${basename}.js readable on disk`, ok, detail: scriptPath });
}
// 4. Cursor restart advisory (informational — editing hooks.json needs a
// Cursor restart for the hooks to take effect; reload semantics are
// unverified across 1.7.x).
checks.push({
name: 'Cursor restart (after install/uninstall)',
ok: true,
detail: 'Restart Cursor for hive-mind hooks to take effect.',
});
// 5. hive-mind-cli responds to --help (prefer install-pinned --cli-path).
let cliPathFromPointer: string | undefined;
if (existsSync(paths.pointerPath)) {
try {
const pointerObj = JSON.parse(await readFile(paths.pointerPath, 'utf-8')) as Record<string, unknown>;
const pointerCliPath = pointerObj['cli_path'];
if (typeof pointerCliPath === 'string' && pointerCliPath.length > 0) {
cliPathFromPointer = pointerCliPath;
}
} catch { /* pointer unreadable — fall through */ }
}
const cliPath = opts.cliPath ?? cliPathFromPointer ?? 'hive-mind-cli';
const spawnImpl = opts.spawnImpl ?? spawn;
const probe = await probeCliVersion(cliPath, spawnImpl, 4000);
checks.push({
name: 'hive-mind-cli reachable',
ok: probe.ok,
detail: cliPathFromPointer ? `${probe.output} (pinned: ${cliPath})` : probe.output,
});
const ok = checks.every((c) => c.ok);
log.info('verify complete', { ok, total: checks.length, failed: checks.filter((c) => !c.ok).length });
return { ok, checks };
}