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,132 @@
/**
* Codex EventAdapter + JsonRegisterSpec.
*
* Codex's hook event surface is effectively a clone of Claude Code's
* (`SessionStart` / `UserPromptSubmit` / `Stop` / `PreCompact`), so the
* adapter reuses CC's snake_case field keys (`prompt`, `session_id`,
* `cwd`, `response`, …) and adds codex-specific fallbacks:
* - Stop reads `last_assistant_message` in the response fallback list.
* - PreCompact carries `trigger` (`manual|auto`) — surfaced as the scope.
*
* Field-name casing is confirmed from docs, not a live payload, so codex
* additions are FALLBACKS layered after the CC keys rather than replacing
* them (spec §5.1 blocker note).
*
* The register shape uses codex's `{ matcher, hooks: [...] }` group with a
* `'startup|resume|clear|compact'` matcher for SessionStart; the marker is
* carried for byte-identical reversible uninstall, not for correctness.
*/
import {
pickStringField,
HIVE_MIND_MARKER_BASE,
type EventAdapter,
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}/codex-hooks`;
/** SessionStart matcher — fires on Codex session lifecycle transitions. */
export const SESSION_START_MATCHER = 'startup|resume|clear|compact';
/** Canonical lifecycle → Codex native event key (CC clone). */
export const CODEX_EVENT_NAME: Record<Lifecycle, string | undefined> = {
'session-start': 'SessionStart',
'user-prompt-submit': 'UserPromptSubmit',
'stop': 'Stop',
'pre-compact': 'PreCompact',
};
function asObject(payload: unknown): Record<string, unknown> | undefined {
return payload && typeof payload === 'object'
? (payload as Record<string, unknown>)
: undefined;
}
/** The Codex EventAdapter consumed by the shared lifecycle handler bodies. */
export const codexAdapter: EventAdapter = {
source: 'codex',
eventName: CODEX_EVENT_NAME,
extractCwd(payload): string | undefined {
return pickStringField(payload, 'cwd');
},
extractSessionId(payload): string | undefined {
return pickStringField(payload, 'session_id', 'sessionId');
},
extractPrompt(payload): string | undefined {
return pickStringField(payload, 'prompt', 'user_message');
},
extractResponse(payload): string | undefined {
// CC fallback list + codex addition `last_assistant_message`.
return pickStringField(
payload,
'response',
'assistant_message',
'last_assistant_message',
'transcript',
);
},
extractParent(payload): string | undefined {
return pickStringField(payload, 'parent_frame_id', 'prompt_frame_id');
},
// formatInject omitted ⇒ the shared SessionStart body uses CC's default
// hookSpecificOutput shape (codex honors the CC inject convention).
};
/**
* PreCompact `trigger` (`manual|auto`) accessor — codex surfaces the
* compaction trigger here. Exposed so verify/diagnostics can read it; the
* shared PreCompact body keys off the session scope, not the trigger.
*/
export function extractTrigger(payload: unknown): string | undefined {
return pickStringField(payload, 'trigger');
}
// ── JsonRegisterSpec (codex `{ matcher, hooks: [...] }` group shape) ────
interface CodexGroup {
matcher?: string;
hooks: Array<{ type: 'command'; command: string; timeout?: number }>;
_hiveMindShim?: string;
}
/**
* The Codex register spec for `jsonRegister`/`jsonUnregister`. Groups live
* under the top-level `hooks` key; SessionStart carries the lifecycle
* matcher, the other events omit it.
*/
export const codexRegisterSpec: JsonRegisterSpec = {
hooksKey: 'hooks',
eventName: CODEX_EVENT_NAME,
buildGroup(lifecycle: Lifecycle, command: string, timeout: number): Record<string, unknown> {
const group: CodexGroup = {
hooks: [{ type: 'command', command, timeout }],
_hiveMindShim: HIVE_MIND_MARKER,
};
if (lifecycle === 'session-start') group.matcher = SESSION_START_MATCHER;
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);
if (!g) return undefined;
const hooks = g['hooks'];
if (!Array.isArray(hooks) || hooks.length === 0) return undefined;
const first = asObject(hooks[0]);
const cmd = first?.['command'];
return typeof cmd === 'string' ? cmd : undefined;
},
};

View File

@@ -0,0 +1,164 @@
#!/usr/bin/env node
/**
* `codex-hooks` — CLI entry for the @waggle/hive-mind-hooks-codex shim.
*
* codex-hooks install Patch ~/.codex/hooks.json (additive, create-if-missing).
* codex-hooks uninstall Restore the byte-identical pre-install state (or remove
* the hooks.json we created).
* codex-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: codex-hooks <command> [options]',
'',
'Commands:',
' install Patch ~/.codex/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/codex-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)'}`,
'',
'One-time trust step required:',
' Run `/hooks` in Codex once to trust the hive-mind hooks before they execute.',
'',
'Done. New Codex sessions will silently capture to hive-mind.',
'Run "codex-hooks verify" to inspect, "codex-hooks uninstall" to revert.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printUninstallSummary(result: UninstallResult): void {
const lines: string[] = [
'hive-mind/codex-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'}`,
'',
'Done. 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/codex-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,34 @@
/**
* Codex PreCompact hook — fired just before Codex truncates context.
* Triggers `cleanup_frames` so superseded P/B frames merge before the
* native compaction step. Thin entrypoint over the shared handler body.
* Codex carries the compaction `trigger` (`manual|auto`) on the payload.
*/
import {
makePreCompactHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { codexAdapter } from '../adapter.js';
export async function runPreCompact(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makePreCompactHandler(codexAdapter), {
name: 'pre-compact',
loggerPrefix: 'codex-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,37 @@
/**
* Codex SessionStart hook — recalls the top-N most relevant frames from
* personal memory and injects them as additional context for the new
* Codex session. Thin entrypoint over the shared handler body.
*
* 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 { codexAdapter } from '../adapter.js';
export async function runSessionStart(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeSessionStartHandler(codexAdapter), {
name: 'session-start',
loggerPrefix: 'codex-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,35 @@
/**
* Codex 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; the adapter reads codex's
* `last_assistant_message` in the response fallback list.
*/
import {
makeStopHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { codexAdapter } from '../adapter.js';
export async function runStop(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeStopHandler(codexAdapter), {
name: 'stop',
loggerPrefix: 'codex-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,33 @@
/**
* Codex UserPromptSubmit hook — captures the user prompt as a temporary
* frame scoped to the current Codex session. Thin entrypoint over the
* shared handler body. No stdout output: pure side-effect on the .mind file.
*/
import {
makeUserPromptSubmitHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { codexAdapter } from '../adapter.js';
export async function runUserPromptSubmit(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeUserPromptSubmitHandler(codexAdapter), {
name: 'user-prompt-submit',
loggerPrefix: 'codex-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,49 @@
/**
* @waggle/hive-mind-hooks-codex — barrel export.
*
* OpenAI Codex silent-capture shim for hive-mind. The second reference
* shape: a CC-clone JSON installer built on @waggle/hive-mind-hooks-core,
* with create-if-missing semantics (codex's `~/.codex/hooks.json` is
* optional). Programmatic install / uninstall / verify lifecycle; most
* users invoke the `codex-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 {
CodexPaths,
ResolvePathsOptions,
HookBasename,
} from './paths.js';
export {
resolvePaths,
allHookBasenames,
backupPathFor,
hookCommandFor,
} from './paths.js';
export {
codexAdapter,
codexRegisterSpec,
extractTrigger,
CODEX_EVENT_NAME,
HIVE_MIND_MARKER,
SESSION_START_MATCHER,
} from './adapter.js';

View File

@@ -0,0 +1,161 @@
/**
* Programmatic install entry point for the Codex hive-mind hooks.
*
* Steps:
* 1. Read existing `~/.codex/hooks.json` IF it exists (create-if-missing
* — codex's hooks.json is OPTIONAL, unlike CC's settings.json which
* must pre-exist).
* 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 into the `hooks`
* object (existing entries preserved verbatim) via `jsonRegister`.
* 4. Write the merged JSON back over `hooks.json`.
* 5. Drop a pointer file at `~/.codex/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 CodexPaths, type ResolvePathsOptions } from './paths.js';
import { codexRegisterSpec } from './adapter.js';
export interface InstallResult {
paths: CodexPaths;
/** 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: 'codex-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, codexRegisterSpec);
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 Codex hive-mind hook install lifecycle.
*
* Mirrors the frozen Wave 1 claude-code `paths.ts` shape, but targets
* Codex's standalone `~/.codex/hooks.json` (NOT `~/.codex/config.toml` —
* we stay out of the user's TOML and away from protected
* `notify`/`profile`/`model_providers` keys). The Windows-safe backup
* path + `--cli-path` quoting + hooks-dir resolution are reused verbatim
* from `@waggle/hive-mind-hooks-core` so codex 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 CodexPaths {
/** Codex config root (`~/.codex/`). */
codexDir: string;
/** `~/.codex/hooks.json` — the standalone hooks config (NOT config.toml). */
configPath: string;
/** `~/.codex/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 = {}): CodexPaths {
const home = opts.home ?? homedir();
const codexDir = join(home, '.codex');
const configPath = join(codexDir, 'hooks.json');
const pointerPath = join(codexDir, '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 { codexDir, configPath, pointerPath, hooksDir };
}
/** Re-export the shared Windows-safe helpers so codex modules read like CC. */
export { backupPathFor, hookCommandFor };

View File

@@ -0,0 +1,76 @@
/**
* Programmatic uninstall entry point for the Codex 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 CodexPaths, type ResolvePathsOptions } from './paths.js';
export interface UninstallResult {
paths: CodexPaths;
/** 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: 'codex-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-codex 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('codex hooks.json removed (created by us)', { config: paths.configPath });
} else {
log.info('codex 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,181 @@
/**
* Smoke-check the Codex install: hooks.json exists + parses + references
* live hook scripts, and hive-mind-cli answers a `--help` probe. Plus two
* codex-specific surfacings (spec §5.1 / §6.2):
* - the one-time `/hooks` trust step is required for non-managed Codex
* hooks to execute (surfaced as an advisory check, not a hard fail);
* - admin lockdown `allow_managed_hooks_only = true` in
* `~/.codex/requirements.toml` SUPPRESSES user hooks, so install would
* silently no-op — surfaced as a failing check.
*
* Probe priority for `cli_path`:
* 1. Explicit `opts.cliPath` (caller override)
* 2. `cli_path` recorded in `~/.codex/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 { codexRegisterSpec } 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: 'codex-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, codexRegisterSpec),
});
// 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. admin lockdown: allow_managed_hooks_only suppresses user hooks.
const requirementsPath = join(paths.codexDir, 'requirements.toml');
if (existsSync(requirementsPath)) {
try {
const toml = await readFile(requirementsPath, 'utf-8');
const locked = /allow_managed_hooks_only\s*=\s*true/.test(toml);
checks.push({
name: 'allow_managed_hooks_only lockdown',
ok: !locked,
detail: locked
? 'requirements.toml sets allow_managed_hooks_only = true — user hooks are suppressed; install will silently no-op.'
: 'not locked',
});
} catch { /* unreadable — skip */ }
}
// 5. /hooks trust step advisory (informational — non-managed Codex hooks
// require a one-time `/hooks` trust before they execute).
checks.push({
name: '/hooks trust step (run once in Codex)',
ok: true,
detail: 'Run `/hooks` in Codex once to trust the hive-mind hooks.',
});
// 6. 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 };
}