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,106 @@
/**
* Hermes EventAdapter.
*
* Hermes (`NousResearch/hermes-agent`) exposes a SHELL-HOOKS system — a
* top-level `hooks:` block in `~/.hermes/config.yaml` whose entries spawn a
* configured `command` as an OS subprocess, pipe the event JSON to stdin,
* and read optional JSON back from stdout. That contract is structurally
* identical to shim-core's `runHook` (stdin-JSON / exit-0), so the three
* lifecycle handler bodies reuse `runHook` as-is.
*
* Hermes differs from claude-code in three source-verified ways (spec §5.4):
* - SessionStart is SPLIT across two native events — `on_session_start`
* (observer/no-op) AND `pre_llm_call` gated on `is_first_turn` (the
* inject seam). The register side wires BOTH keys (see yaml-merger.ts);
* the inject stdout shape is `{ "context": "..." }` (appended to the
* user message, NOT the system prompt, to preserve prefix cache), so
* `formatInject` returns `{ context: text }`.
* - UserPromptSubmit → `pre_llm_call`; the user text lives at
* `extra.user_message`.
* - Stop → `post_llm_call`; the assistant text lives at
* `extra.assistant_response`. (`on_session_finalize` is gateway-only —
* do NOT use it; `post_llm_call` is the dependable per-turn Stop signal.)
*
* There is NO PreCompact event — Hermes ships no compaction hook
* (`eventName['pre-compact'] = undefined`); the maintenance pass is
* approximated opt-in from Stop (`WAGGLE_HERMES_COMPACT_ON_STOP`, default
* off) — see `compact-on-stop.ts`. (`eventName['pre-compact']` stays
* `undefined`; we are NOT registering a hook.)
*
* Hermes events carry block/inject control purely via stdout JSON (no
* exit-code-2 contract). Our hooks are capture-only, so they emit `{}` or
* the SessionStart context and exit 0 — fully compatible with the shim.
*/
import {
pickStringField,
type EventAdapter,
type Lifecycle,
} from '@waggle/hive-mind-hooks-core';
/**
* Canonical lifecycle → Hermes native event key. SessionStart maps to
* `pre_llm_call` for the inject side; the observer-only `on_session_start`
* key is registered separately by the YAML merger (it cannot be expressed
* in this 1:1 map). `pre-compact` is `undefined` — Hermes has no compaction
* hook.
*/
export const HERMES_EVENT_NAME: Record<Lifecycle, string | undefined> = {
'session-start': 'pre_llm_call',
'user-prompt-submit': 'pre_llm_call',
'stop': 'post_llm_call',
'pre-compact': undefined,
};
/** Hermes observer-only SessionStart key, registered alongside `pre_llm_call`. */
export const HERMES_SESSION_START_OBSERVE_EVENT = 'on_session_start';
/**
* Read a string field nested under the Hermes `extra` envelope, falling
* back to top-level keys for forward-compat. Hermes delivers the turn
* payload under `extra.{user_message,assistant_response,...}`.
*/
function pickFromExtra(payload: unknown, ...keys: string[]): string | undefined {
if (payload && typeof payload === 'object') {
const extra = (payload as Record<string, unknown>)['extra'];
const fromExtra = pickStringField(extra, ...keys);
if (fromExtra) return fromExtra;
}
return pickStringField(payload, ...keys);
}
/** The Hermes EventAdapter consumed by the shared lifecycle handler bodies. */
export const hermesAdapter: EventAdapter = {
source: 'hermes',
eventName: HERMES_EVENT_NAME,
extractCwd(payload): string | undefined {
return pickFromExtra(payload, 'cwd', 'working_directory', 'workingDirectory');
},
extractSessionId(payload): string | undefined {
return pickFromExtra(payload, 'session_id', 'sessionId', 'conversation_id', 'conversationId');
},
extractPrompt(payload): string | undefined {
// pre_llm_call carries the user text at extra.user_message.
return pickFromExtra(payload, 'user_message', 'prompt');
},
extractResponse(payload): string | undefined {
// post_llm_call carries the assistant text at extra.assistant_response.
return pickFromExtra(payload, 'assistant_response', 'final_response', 'response');
},
extractParent(payload): string | undefined {
return pickFromExtra(payload, 'parent_frame_id', 'prompt_frame_id');
},
/**
* Hermes appends `pre_llm_call` stdout `{ "context": "..." }` to the
* user message (NOT the system prompt — preserves the prefix cache).
*/
formatInject(additionalContext: string): unknown {
return { context: additionalContext };
},
};

View File

@@ -0,0 +1,183 @@
#!/usr/bin/env node
/**
* `hermes-hooks` — CLI entry for the @waggle/hive-mind-hooks-hermes shim.
*
* hermes-hooks install Patch ~/.hermes/config.yaml (additive, create-if-missing).
* hermes-hooks uninstall Restore the literal byte-identical pre-install state (or
* remove the config.yaml we created).
* hermes-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: hermes-hooks <command> [options]',
'',
'Commands:',
' install Patch ~/.hermes/config.yaml (additive, create-if-missing, with backup).',
' uninstall Restore the literal byte-identical pre-install config.yaml (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 60, cap 300).',
' --no-auto-accept Do NOT seed hooks_auto_accept: true. WARNING: under',
' headless / non-TTY launches the hooks then silently',
' never register unless HERMES_ACCEPT_HOOKS=1 is set.',
' --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/hermes-hooks: install',
` - config.yaml: ${result.paths.configPath}`,
` - backup: ${result.backupPath ?? '(none — config.yaml created by us)'}`,
` - pointer: ${result.pointerPath}`,
` - hook scripts: ${result.installedHooks.join(', ')}`,
` - events: ${result.registeredEvents.join(', ')}`,
` - auto-accept: ${result.autoAcceptSeeded ? 'seeded (hooks_auto_accept: true)' : 'not seeded'}`,
` - cli path: ${result.cliPath ?? '(default — hive-mind-cli on PATH)'}`,
'',
'Headless / gateway consent (IMPORTANT):',
result.autoAcceptSeeded
? ' hooks_auto_accept: true was written, so the hooks register under headless launch.'
: ' hooks_auto_accept was NOT seeded. Under a headless / non-TTY launch the hooks',
result.autoAcceptSeeded
? ' (Hermes keys consent on the exact command string; editing the target script is silently trusted.)'
: ' silently never register unless you set HERMES_ACCEPT_HOOKS=1 (or add hooks_auto_accept: true).',
'',
'Capture fidelity:',
' 3 events only — SessionStart (split: on_session_start + pre_llm_call/is_first_turn),',
' UserPromptSubmit (pre_llm_call), Stop (post_llm_call). NO PreCompact event (Hermes',
' ships no compaction hook). See the README Capture fidelity table.',
' Opt-in: set WAGGLE_HERMES_COMPACT_ON_STOP=1 to approximate the PreCompact',
' maintenance pass from the Stop hook (time-gated, default off).',
'',
'Done. New Hermes sessions will silently capture to hive-mind.',
'Run "hermes-hooks verify" to inspect, "hermes-hooks uninstall" to revert.',
'',
];
process.stdout.write(lines.join('\n'));
}
function printUninstallSummary(result: UninstallResult): void {
const lines: string[] = [
'hive-mind/hermes-hooks: uninstall',
` - config.yaml: ${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'}`,
'',
'config.yaml 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/hermes-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 noAutoAccept = flags['no-auto-accept'] === true;
const baseOpts = {
moduleUrl: import.meta.url,
...(hooksDir ? { hooksDir } : {}),
};
try {
if (command === 'install') {
const installOpts = {
...baseOpts,
...(hookTimeoutSeconds !== undefined ? { hookTimeoutSeconds } : {}),
...(cliPath !== undefined ? { cliPath } : {}),
...(noAutoAccept ? { autoAccept: false } : {}),
};
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,126 @@
/**
* Hermes opportunistic, time-gated compact-on-Stop (OQ-4).
*
* Hermes ships no PreCompact lifecycle event, so the `cleanup_frames`
* maintenance pass every other built hook binds to PreCompact never runs.
* This module approximates "occasional before-compaction maintenance" by
* running `bridge.cleanupFrames()` opportunistically from the per-turn Stop
* hook — OPT-IN, DEFAULT OFF (`WAGGLE_HERMES_COMPACT_ON_STOP`), so OSS
* consumers see zero behavior change unless they ask for it.
*
* Statelessness bridge: Hermes' Stop is delivered to a fresh Node subprocess
* every turn, so an "every N turns" counter is impossible without persistence.
* We compact at most once per time window, tracking the last-compact instant
* in a small file under `~/.hermes/`. Turns are sequential subprocesses
* (process N exits before N+1 starts) → no read/write race.
*
* Fail-open is sacred: `maybeCompactOnStop` NEVER throws and NEVER rejects;
* every IO path is wrapped + swallowed. The timestamp is written ON SUCCESS
* ONLY — a failed compact stays eligible to retry next turn rather than being
* locked out for a whole window.
*/
import { mkdir, readFile, writeFile } from 'node:fs/promises';
import { dirname, join } from 'node:path';
import type { HookContext } from '@waggle/hive-mind-hooks-core';
import { resolvePaths } from './paths.js';
/** Default compact window: at most once per 10 minutes. */
export const DEFAULT_WINDOW_MS = 600_000;
const STATE_BASENAME = '.hive-mind-last-compact';
/**
* Absolute path to the last-compact timestamp file, under the hermes config
* root (`~/.hermes/.hive-mind-last-compact`). `home` overrides $HOME for tests.
*/
export function compactStatePath(home?: string): string {
return join(resolvePaths({ home }).hermesDir, STATE_BASENAME);
}
/**
* Whether opt-in compact-on-Stop is enabled. Parsed exactly like
* `WAGGLE_SIGNAL_EMIT` in `runStopBody`: truthy unless unset / empty / '0' /
* 'false' (case-insensitive).
*/
export function isCompactEnabled(env: NodeJS.ProcessEnv = process.env): boolean {
const flag = env['WAGGLE_HERMES_COMPACT_ON_STOP'];
return flag != null && flag !== '' && flag !== '0' && flag.toLowerCase() !== 'false';
}
/**
* Resolve the compact window in ms. A test `overrideMs` wins; else
* `WAGGLE_HERMES_COMPACT_WINDOW_MIN` minutes when finite and > 0; else the
* 10-minute default.
*/
export function resolveWindowMs(
env: NodeJS.ProcessEnv = process.env,
overrideMs?: number,
): number {
if (overrideMs !== undefined) return overrideMs;
const raw = env['WAGGLE_HERMES_COMPACT_WINDOW_MIN'];
if (raw != null && raw !== '') {
const minutes = Number.parseFloat(raw);
if (Number.isFinite(minutes) && minutes > 0) return minutes * 60_000;
}
return DEFAULT_WINDOW_MS;
}
/**
* Read the persisted last-compact timestamp. Missing file / garbage / NaN →
* undefined ("never"). Fail-open: any error resolves to undefined.
*/
export async function readLastCompactTs(path: string): Promise<number | undefined> {
try {
const raw = await readFile(path, 'utf-8');
const ts = Number.parseInt(raw.trim(), 10);
return Number.isFinite(ts) ? ts : undefined;
} catch {
return undefined;
}
}
/**
* Persist the last-compact timestamp. mkdir-recursive the parent first (a bare
* writeFile would ENOENT every turn on a host where `~/.hermes/` doesn't exist
* yet, silently degrading the throttle to every-turn; mkdir-recursive is
* idempotent + cheap, and in a real install the dir already exists). The
* caller catches + swallows errors.
*/
export async function writeLastCompactTs(path: string, ts: number): Promise<void> {
await mkdir(dirname(path), { recursive: true });
await writeFile(path, String(ts));
}
export interface MaybeCompactOptions {
/** Injectable clock for tests; falls back to the system clock. */
now?: () => number;
/** $HOME override for the state file (tests). */
home?: string;
/** Compact window override in ms (tests); wins over the env var. */
windowMs?: number;
}
/**
* Opportunistically run the `cleanup_frames` maintenance pass, gated by the
* opt-in flag + a persisted time window. NEVER throws, NEVER rejects.
*/
export async function maybeCompactOnStop(
ctx: HookContext,
opts: MaybeCompactOptions = {},
): Promise<void> {
try {
if (!isCompactEnabled()) return;
const now = opts.now?.() ?? Date.now();
const path = compactStatePath(opts.home);
const last = await readLastCompactTs(path);
const windowMs = resolveWindowMs(process.env, opts.windowMs);
if (last !== undefined && now - last < windowMs) return;
await ctx.bridge.cleanupFrames();
await writeLastCompactTs(path, now);
} catch (err) {
ctx.logger.warn('compact-on-stop failed open', {
error: err instanceof Error ? err.message : String(err),
});
}
}

View File

@@ -0,0 +1,90 @@
/**
* Hermes session-start hook — recalls the top-N most relevant frames from
* personal memory and injects them as additional context for the new Hermes
* session. Thin entrypoint over the shared SessionStart handler body.
*
* Hermes SPLITS SessionStart across two native events, and this ONE compiled
* script is registered under BOTH (spec §5.4):
* - `on_session_start` — observer-only (fires once per new session; its
* return value is ignored by Hermes).
* - `pre_llm_call` — the inject seam, but ONLY on the first turn.
*
* Because the same script fires on every `pre_llm_call` (not just turn 1),
* it gates on the payload's `is_first_turn` flag: when the host indicates a
* non-first turn, the script emits nothing (the per-turn save is handled by
* the separate user-prompt-submit hook). On the first turn (or when the flag
* is absent — e.g. the `on_session_start` observer payload), it recalls +
* injects via the hermes adapter's `formatInject` (`{ context: text }`).
*
* Fail-open: if hive-mind-cli is unreachable the hook logs and exits 0 with
* no output — the session starts as it would have without the shim.
*/
import {
makeSessionStartHandler,
readStdinAsString,
runHook,
safeJsonParse,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { hermesAdapter } from '../adapter.js';
/**
* True unless the host explicitly marks this as a non-first turn. Hermes
* sets `extra.is_first_turn=false` on subsequent `pre_llm_call`s; the
* `on_session_start` observer payload omits the flag, so absence ⇒ inject.
*/
function isFirstTurn(raw: unknown): boolean {
if (raw && typeof raw === 'object') {
const obj = raw as Record<string, unknown>;
const extra = obj['extra'];
const flag = (extra && typeof extra === 'object'
? (extra as Record<string, unknown>)['is_first_turn']
: undefined) ?? obj['is_first_turn'];
if (flag === false) return false;
}
return true;
}
export async function runSessionStart(opts: Partial<HookRunOptions> = {}): Promise<void> {
// Read stdin ONCE, then honor Hermes's is_first_turn inject gating without
// changing the shared handler body. On a non-first turn we exit 0 with no
// output (so the host pipe drains and the session is never blocked); the
// per-turn save is owned by the separate user-prompt-submit hook.
const exit = opts.exit ?? ((c: number): void => { process.exit(c); });
let raw: string;
try {
const reader = opts.readStdin ?? readStdinAsString;
raw = await reader();
if (!isFirstTurn(safeJsonParse(raw))) {
exit(0);
return;
}
} catch {
// Fail-open: a throwing stdin read must never escape to the host
// (mirrors runHook's exit-0-always contract for the pre-gate path).
exit(0);
return;
}
return runHook(makeSessionStartHandler(hermesAdapter), {
name: 'session-start',
loggerPrefix: 'hermes-hooks',
...opts,
// Re-feed the already-read payload so runHook does not block on a
// drained stdin.
readStdin: async () => raw,
});
}
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,68 @@
/**
* Hermes 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.
*
* Native event: `post_llm_call` (fires once per turn after the loop
* completes, only if a final response was produced and the turn was not
* interrupted — the dependable per-turn Stop signal for a single-shot CLI
* run). The assistant text arrives at `extra.assistant_response`; the hermes
* adapter's `extractResponse` reads it. NOTE: `on_session_finalize` is the
* gateway-only path and is deliberately NOT used.
*
* Capture-only: emits no stdout (Hermes block/inject is via stdout JSON,
* not exit codes); fails open on any error and exits 0.
*/
import {
makeStopHandler,
runHook,
type HookRunOptions,
} from '@waggle/hive-mind-hooks-core';
import { hermesAdapter } from '../adapter.js';
import { maybeCompactOnStop } from '../compact-on-stop.js';
export interface HermesStopOptions extends Partial<HookRunOptions> {
/** Injectable clock for the compact gate (tests). */
now?: () => number;
/** $HOME override for the compact state file (tests). */
home?: string;
/** Compact window override in ms (tests). */
compactWindowMs?: number;
}
export async function runStop(opts: HermesStopOptions = {}): Promise<void> {
const { now, home, compactWindowMs, ...runOpts } = opts;
const base = makeStopHandler(hermesAdapter);
const handler: typeof base = {
parse: base.parse,
async run(payload, ctx) {
// Primary save first — unchanged. If this throws, the compact step is
// skipped and the throw lands in runHook's fail-open catch (exit 0).
await base.run(payload, ctx);
// Best-effort maintenance layered after the save. Never throws/rejects,
// so it cannot affect the already-completed save or the exit code.
await maybeCompactOnStop(ctx, { now, home, windowMs: compactWindowMs });
return undefined;
},
};
return runHook(handler, {
name: 'stop',
loggerPrefix: 'hermes-hooks',
...runOpts,
});
}
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,44 @@
/**
* Hermes user-prompt-submit hook — captures the user prompt as a temporary
* frame scoped to the current Hermes session. Thin entrypoint over the
* shared handler body.
*
* Native event: `pre_llm_call` (fires once per turn before the tool loop).
* The user text arrives at `extra.user_message`; the hermes adapter's
* `extractPrompt` reads it. This hook is registered alongside the
* session-start inject hook on the same `pre_llm_call` event — the two are
* independent: session-start injects only on the first turn, this one saves
* on every turn.
*
* Save-only: Hermes block/inject control flows through stdout JSON (no
* exit-code-2 contract), and this hook is capture-only — it 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 { hermesAdapter } from '../adapter.js';
export async function runUserPromptSubmit(opts: Partial<HookRunOptions> = {}): Promise<void> {
return runHook(makeUserPromptSubmitHandler(hermesAdapter), {
name: 'user-prompt-submit',
loggerPrefix: 'hermes-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,85 @@
/**
* @waggle/hive-mind-hooks-hermes — barrel export.
*
* Hermes silent-capture shim for hive-mind. A bespoke-YAML installer built
* on @waggle/hive-mind-hooks-core, with create-if-missing semantics
* (Hermes's `~/.hermes/config.yaml` is optional). Targets the SHELL-HOOKS
* system (the top-level `hooks:` block) — NOT the gateway dir-hooks nor the
* in-process plugin hooks.
*
* Three events only (NO PreCompact — Hermes ships no compaction hook):
* - SessionStart is SPLIT across `on_session_start` (observer) and
* `pre_llm_call` (inject, gated `is_first_turn`).
* - UserPromptSubmit → `pre_llm_call`.
* - Stop → `post_llm_call`.
*
* Because Hermes has no PreCompact event, the `cleanup_frames` maintenance
* pass is approximated OPT-IN from the per-turn Stop hook
* (`WAGGLE_HERMES_COMPACT_ON_STOP`, default off; time-gated by
* `WAGGLE_HERMES_COMPACT_WINDOW_MIN`) — see `compact-on-stop.ts`.
*
* YAML round-trip is lossy, so reversibility relies on the literal
* byte-identical backup written at install time. Programmatic install /
* uninstall / verify lifecycle; most users invoke the `hermes-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 {
HermesPaths,
ResolvePathsOptions,
HookBasename,
} from './paths.js';
export {
resolvePaths,
allHookBasenames,
backupPathFor,
hookCommandFor,
} from './paths.js';
export {
hermesAdapter,
HERMES_EVENT_NAME,
HERMES_SESSION_START_OBSERVE_EVENT,
} from './adapter.js';
export type { MaybeCompactOptions } from './compact-on-stop.js';
export {
maybeCompactOnStop,
compactStatePath,
isCompactEnabled,
resolveWindowMs,
DEFAULT_WINDOW_MS,
} from './compact-on-stop.js';
export type {
HermesHookEntry,
HermesRegisterEntry,
} from './yaml-merger.js';
export {
parseConfig,
serializeConfig,
yamlRegister,
yamlUnregister,
hasHiveEntries,
isHiveEntry,
HIVE_MIND_MARKER,
HOOKS_KEY,
} from './yaml-merger.js';

View File

@@ -0,0 +1,200 @@
/**
* Programmatic install entry point for the Hermes hive-mind hooks.
*
* Steps:
* 1. Read existing `~/.hermes/config.yaml` IF it exists (create-if-missing
* — config.yaml is OPTIONAL on a fresh install). We touch ONLY the
* top-level `hooks:` block (the SHELL-HOOKS system).
* 2. If it pre-existed, write a LITERAL byte-identical backup; if absent,
* skip the backup and record `created_by_us=true`. (YAML round-trip is
* lossy, so reversibility relies on the literal backup, not a
* re-serialized diff.)
* 3. Additively register the hive-mind shell hooks into the `hooks:`
* block via `yamlRegister`. SessionStart is SPLIT across two native
* events: `on_session_start` (observer) and `pre_llm_call` (inject,
* gated `is_first_turn`). UserPromptSubmit also rides `pre_llm_call`;
* Stop rides `post_llm_call`. Existing entries preserved verbatim.
* 4. Optionally seed `hooks_auto_accept: true` so the hooks register under
* headless / non-TTY launches (Hermes's first-use consent allow-list
* otherwise silently never registers them).
* 5. Write the merged YAML back over `config.yaml`.
* 6. Drop a pointer file at `~/.hermes/hive-mind-install.json` so a future
* `uninstall` knows whether to restore the backup or delete the file
* we created.
*/
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,
normalizeCliPath,
writePointer,
type InstallPointer,
} from '@waggle/hive-mind-hooks-core';
import { resolvePaths, type HermesPaths, type ResolvePathsOptions } from './paths.js';
import {
parseConfig,
serializeConfig,
yamlRegister,
type HermesRegisterEntry,
} from './yaml-merger.js';
import { HERMES_SESSION_START_OBSERVE_EVENT } from './adapter.js';
export interface InstallResult {
paths: HermesPaths;
/** The literal byte-identical backup written when config.yaml pre-existed, else null. */
backupPath: string | null;
pointerPath: string;
/** Hook basenames whose scripts are referenced (session-start / user-prompt-submit / stop). */
installedHooks: readonly string[];
/** Native Hermes event keys we registered entries under (recorded in pointer.extra). */
registeredEvents: readonly string[];
/** True when config.yaml did NOT pre-exist and we created it. */
createdByUs: boolean;
/** True when `hooks_auto_accept: true` was seeded into the config. */
autoAcceptSeeded: 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 60 (Hermes default), hard cap 300. */
hookTimeoutSeconds?: number;
/**
* Seed `hooks_auto_accept: true` into config.yaml so the hooks register
* under headless / non-TTY launches. Default true — without it (or
* `HERMES_ACCEPT_HOOKS=1`) the hooks silently never register. Set false
* to manage consent yourself.
*/
autoAccept?: boolean;
/** 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 = 60;
const HOOK_TIMEOUT_CAP_S = 300;
const POINTER_VERSION = '0.1.0';
async function ensureDir(p: string): Promise<void> {
if (!existsSync(p)) await mkdir(p, { recursive: true });
}
/**
* Build the hermes register entries from the resolved hook script paths.
* SessionStart is SPLIT: the session-start script registers under BOTH
* `on_session_start` (observer) and `pre_llm_call` (inject). The
* user-prompt-submit script also rides `pre_llm_call`; stop rides
* `post_llm_call`.
*/
function buildEntries(hooksDir: string, cliPath: string | undefined, timeout: number): HermesRegisterEntry[] {
const sessionStartCmd = hookCommandFor(hookScriptPath(hooksDir, 'session-start'), cliPath);
const userPromptCmd = hookCommandFor(hookScriptPath(hooksDir, 'user-prompt-submit'), cliPath);
const stopCmd = hookCommandFor(hookScriptPath(hooksDir, 'stop'), cliPath);
return [
// SessionStart observer side — fires once per new session.
{ eventKey: HERMES_SESSION_START_OBSERVE_EVENT, command: sessionStartCmd, timeout },
// SessionStart inject side — fires on pre_llm_call, gated is_first_turn.
{ eventKey: 'pre_llm_call', command: sessionStartCmd, timeout },
// UserPromptSubmit — also rides pre_llm_call (every turn).
{ eventKey: 'pre_llm_call', command: userPromptCmd, timeout },
// Stop — post_llm_call (turn end).
{ eventKey: 'post_llm_call', command: stopCmd, timeout },
];
}
export async function install(opts: InstallOptions = {}): Promise<InstallResult> {
const log = opts.logger ?? createLogger({ name: 'hermes-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());
const autoAccept = opts.autoAccept ?? true;
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');
existingConfig = parseConfig(originalContent);
}
await ensureDir(dirname(paths.pointerPath));
// Literal byte-identical backup of the original config (no-op when absent).
// Uninstall restores THESE exact bytes — YAML re-serialization is lossy.
const { backupPath, preExisted: backedUp } = await backupByteIdentical(
paths.configPath,
now().toISOString(),
);
if (backedUp) log.info('config.yaml backed up', { backupPath });
const cliPath = normalizeCliPath(opts.cliPath);
const requested = opts.hookTimeoutSeconds ?? DEFAULT_HOOK_TIMEOUT_S;
const timeout = Math.min(Math.max(1, Math.floor(requested)), HOOK_TIMEOUT_CAP_S);
const entries = buildEntries(paths.hooksDir, cliPath, timeout);
let merged = yamlRegister(existingConfig, entries);
let autoAcceptSeeded = false;
if (autoAccept && merged['hooks_auto_accept'] !== true) {
merged = { ...merged, hooks_auto_accept: true };
autoAcceptSeeded = true;
}
const mergedYaml = serializeConfig(merged);
await writeFile(paths.configPath, mergedYaml, 'utf-8');
const registeredEvents = [...new Set(entries.map((e) => e.eventKey))];
const basenames = ['session-start', 'user-prompt-submit', 'stop'] as const;
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,
extra: {
registered_events: registeredEvents,
auto_accept_seeded: autoAcceptSeeded,
},
};
await writePointer(paths.pointerPath, pointer);
log.info('install complete', {
registeredEvents,
createdByUs,
autoAcceptSeeded,
cliPath: cliPath ?? '(PATH lookup)',
});
const result: InstallResult = {
paths,
backupPath,
pointerPath: paths.pointerPath,
installedHooks: basenames,
registeredEvents,
createdByUs,
autoAcceptSeeded,
};
if (cliPath !== undefined) result.cliPath = cliPath;
return result;
}

View File

@@ -0,0 +1,81 @@
/**
* Filesystem path helpers for the Hermes hive-mind hook install lifecycle.
*
* Mirrors the Codex/Cursor `paths.ts` shape, but targets Hermes's
* `~/.hermes/config.yaml` (the path `hermes_cli/config.py get_config_path`
* resolves to). We touch ONLY the top-level `hooks:` block (the SHELL-HOOKS
* system) — never the gateway dir-hooks (`~/.hermes/hooks/<name>/`) nor the
* in-process plugin hooks. Hermes ships only THREE lifecycle hooks (there is
* no PreCompact event), so the basename set omits `pre-compact`.
*
* The Windows-safe backup path + `--cli-path` quoting + hooks-dir resolution
* are reused verbatim from `@waggle/hive-mind-hooks-core` so hermes 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 HermesPaths {
/** Hermes config root (`~/.hermes/`). */
hermesDir: string;
/** `~/.hermes/config.yaml` — the shell-hooks config (top-level `hooks:`). */
configPath: string;
/** `~/.hermes/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;
}
/**
* Hermes ships THREE lifecycle hooks only — there is genuinely no
* compaction hook to bind (confirmed absent in `VALID_HOOKS`), so
* `pre-compact` is intentionally omitted.
*/
const HOOK_BASENAMES = [
'session-start',
'user-prompt-submit',
'stop',
] as const;
export type HookBasename = typeof HOOK_BASENAMES[number];
export function allHookBasenames(): readonly HookBasename[] {
return HOOK_BASENAMES;
}
export function resolvePaths(opts: ResolvePathsOptions = {}): HermesPaths {
const home = opts.home ?? homedir();
const hermesDir = join(home, '.hermes');
const configPath = join(hermesDir, 'config.yaml');
const pointerPath = join(hermesDir, '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 { hermesDir, configPath, pointerPath, hooksDir };
}
/** Re-export the shared Windows-safe helpers so hermes modules read like CC. */
export { backupPathFor, hookCommandFor };

View File

@@ -0,0 +1,79 @@
/**
* Programmatic uninstall entry point for the Hermes hive-mind hooks.
*
* Round-trip guarantee:
* - `created_by_us=false` (config.yaml pre-existed): restore the LITERAL
* byte-identical backup the installer wrote; refuse to delete the backup
* unless the in-place readback matches. (YAML re-serialization is lossy,
* so we restore the original BYTES — comments and key ordering are
* preserved exactly because we never touch the re-serialized merge on
* this path.)
* - `created_by_us=true` (we created config.yaml): 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 HermesPaths, type ResolvePathsOptions } from './paths.js';
export interface UninstallResult {
paths: HermesPaths;
/** 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: 'hermes-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-hermes 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('hermes config.yaml removed (created by us)', { config: paths.configPath });
} else {
log.info('hermes config.yaml 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 Hermes install: config.yaml exists + parses + carries
* hive-mind entries that reference live hook scripts, and hive-mind-cli
* answers a `--help` probe. Plus the hermes-specific consent advisory
* (spec §5.4 / §6.2): under headless / non-TTY launches the hooks register
* only if `hooks_auto_accept: true` (or `HERMES_ACCEPT_HOOKS=1`) is set,
* otherwise Hermes's first-use consent allow-list silently never registers
* them.
*
* Probe priority for `cli_path`:
* 1. Explicit `opts.cliPath` (caller override)
* 2. `cli_path` recorded in `~/.hermes/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 { resolvePaths, allHookBasenames, type ResolvePathsOptions } from './paths.js';
import { parseConfig, hasHiveEntries } from './yaml-merger.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: 'hermes-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. config.yaml exists and parses.
if (!existsSync(paths.configPath)) {
checks.push({ name: 'config.yaml exists', ok: false, detail: paths.configPath });
return { ok: false, checks };
}
checks.push({ name: 'config.yaml exists', ok: true, detail: paths.configPath });
let parsed: Record<string, unknown>;
try {
parsed = parseConfig(await readFile(paths.configPath, 'utf-8'));
checks.push({ name: 'config.yaml parses as YAML', ok: true });
} catch (err) {
checks.push({
name: 'config.yaml parses as YAML',
ok: false,
detail: err instanceof Error ? err.message : String(err),
});
return { ok: false, checks };
}
// 2. hive-mind entries present in the hooks: block.
checks.push({
name: 'config.yaml contains hive-mind hook entries',
ok: hasHiveEntries(parsed),
});
// 3. each hive hook script exists on disk (3 scripts — no pre-compact).
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. consent advisory — headless launches need auto-accept or env.
const autoAccept = parsed['hooks_auto_accept'] === true;
checks.push({
name: 'headless consent configured',
ok: autoAccept,
detail: autoAccept
? 'hooks_auto_accept: true is set — hooks register under headless launch.'
: 'set hooks_auto_accept: true (or HERMES_ACCEPT_HOOKS=1) or hooks silently never register under headless / non-TTY launch.',
});
// 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 };
}

View File

@@ -0,0 +1,186 @@
/**
* Bespoke YAML codec + additive register/unregister for the Hermes
* shell-hooks `config.yaml`.
*
* Hermes's hook config is NOT JSON — it is a top-level `hooks:` block in
* `~/.hermes/config.yaml`, so it cannot use the shared `jsonRegister`
* helper. This module is the hermes-only equivalent: parse/serialize via
* the `yaml` dep, and additively merge marker-tagged hive entries into the
* `hooks:` block while preserving the user's existing entries verbatim.
*
* Reversibility note: YAML re-serialization is NOT byte-identical (comments
* and key ordering are lost on round-trip), so uninstall does NOT rely on
* re-serializing a diff. Instead the installer writes a LITERAL
* byte-identical backup of the original `config.yaml` and uninstall restores
* those exact bytes (see install-core `backupByteIdentical` /
* `restoreFromBackup`). This module only produces the merged YAML we WRITE
* on install; the marker just lets re-install dedup our own entries in
* place rather than duplicating them.
*
* Marker strategy: YAML comments do not survive a parse→serialize round
* trip, so the marker is a STRUCTURAL sentinel key (`_hive_mind`) stamped on
* each entry we add, backed up by a recognizable command-path prefix. We
* detect our own entries by the sentinel; dedup matches on (eventKey,
* command).
*
* Immutability: every function returns a NEW config object and never
* mutates its input (mirrors the `jsonRegister` contract).
*/
import { parse as parseYaml, stringify as stringifyYaml } from 'yaml';
/** Structural marker stamped on every hook entry we add. */
export const HIVE_MIND_MARKER = '@hive-mind/hermes-hooks';
/** Top-level YAML key holding the shell-hooks map. */
export const HOOKS_KEY = 'hooks';
/**
* A single Hermes shell-hook entry. Hermes honors `command` + `timeout`
* on lifecycle events; `matcher` is honored ONLY on pre/post_tool_call and
* is stripped-with-warning elsewhere, so we never set it on our events.
*/
export interface HermesHookEntry {
command: string;
timeout?: number;
/** Structural marker so re-install/uninstall can find our own entries. */
_hive_mind?: string;
}
/** One entry to register: which native event key, plus the command + timeout. */
export interface HermesRegisterEntry {
/** Native Hermes event key, e.g. 'on_session_start' / 'pre_llm_call' / 'post_llm_call'. */
eventKey: string;
command: string;
timeout: number;
}
function asRecord(value: unknown): Record<string, unknown> | undefined {
return value && typeof value === 'object' && !Array.isArray(value)
? (value as Record<string, unknown>)
: undefined;
}
function asEntryArray(value: unknown): Record<string, unknown>[] {
return Array.isArray(value) ? (value as Record<string, unknown>[]) : [];
}
/** True iff a parsed hook entry carries our structural marker. */
export function isHiveEntry(entry: unknown): boolean {
const e = asRecord(entry);
return !!e && e['_hive_mind'] === HIVE_MIND_MARKER;
}
function entryCommand(entry: unknown): string | undefined {
const e = asRecord(entry);
const cmd = e?.['command'];
return typeof cmd === 'string' ? cmd : undefined;
}
/**
* Parse a `config.yaml` string into a plain object. Returns `{}` for an
* empty/whitespace string (create-if-missing). Throws on malformed YAML so
* the installer fails loudly rather than silently clobbering a user config.
*/
export function parseConfig(raw: string): Record<string, unknown> {
if (!raw || raw.trim().length === 0) return {};
let parsed: unknown;
try {
parsed = parseYaml(raw);
} catch (err) {
throw new Error(
'failed to parse ~/.hermes/config.yaml as YAML: ' +
(err instanceof Error ? err.message : String(err)),
);
}
const record = asRecord(parsed);
// A top-level scalar/array YAML doc is not a valid hermes config shape;
// treat it as empty rather than crashing (the original bytes are backed
// up regardless, so nothing is lost).
return record ?? {};
}
/** Serialize a config object back to YAML text (trailing newline). */
export function serializeConfig(config: Record<string, unknown>): string {
const text = stringifyYaml(config);
return text.endsWith('\n') ? text : text + '\n';
}
/**
* Returns a NEW config object with hive-mind shell-hook entries registered
* under each supplied native event key. Existing non-hive entries are
* preserved verbatim. A hive entry for the same (eventKey, command) is
* replaced in place rather than duplicated, so re-running install upgrades
* cleanly.
*/
export function yamlRegister(
config: Record<string, unknown> | undefined,
entries: readonly HermesRegisterEntry[],
): Record<string, unknown> {
const next: Record<string, unknown> = config ? { ...config } : {};
const existingHooks = asRecord(next[HOOKS_KEY]);
const nextHooks: Record<string, unknown> = existingHooks ? { ...existingHooks } : {};
for (const entry of entries) {
const arr = asEntryArray(nextHooks[entry.eventKey]).slice();
const newEntry: HermesHookEntry = {
command: entry.command,
timeout: entry.timeout,
_hive_mind: HIVE_MIND_MARKER,
};
let replaced = false;
for (let i = 0; i < arr.length; i += 1) {
if (isHiveEntry(arr[i]) && entryCommand(arr[i]) === entry.command) {
arr[i] = newEntry as unknown as Record<string, unknown>;
replaced = true;
break;
}
}
if (!replaced) arr.push(newEntry as unknown as Record<string, unknown>);
nextHooks[entry.eventKey] = arr;
}
next[HOOKS_KEY] = nextHooks;
return next;
}
/**
* Returns a NEW config object with all marker-tagged hive entries stripped
* from every event array. Non-hive entries are preserved verbatim; empty
* event arrays are left in place (minimal-touch). Never mutates input.
*
* Note: uninstall normally restores the literal byte-identical backup, so
* this is used for verify/diagnostics and for the (rare) backup-less path.
*/
export function yamlUnregister(
config: Record<string, unknown> | undefined,
): Record<string, unknown> {
const next: Record<string, unknown> = config ? { ...config } : {};
const existingHooks = asRecord(next[HOOKS_KEY]);
if (!existingHooks) return next;
const nextHooks: Record<string, unknown> = {};
for (const [eventKey, value] of Object.entries(existingHooks)) {
const arr = asEntryArray(value);
if (arr.length === 0) {
nextHooks[eventKey] = value;
continue;
}
nextHooks[eventKey] = arr.filter((e) => !isHiveEntry(e));
}
next[HOOKS_KEY] = nextHooks;
return next;
}
/** True iff at least one event array carries a marker-tagged hive entry. */
export function hasHiveEntries(config: Record<string, unknown> | undefined): boolean {
if (!config) return false;
const hooks = asRecord(config[HOOKS_KEY]);
if (!hooks) return false;
for (const value of Object.values(hooks)) {
if (asEntryArray(value).some((e) => isHiveEntry(e))) return true;
}
return false;
}