Skip to content

Garry's Opinionated OpenClaw/Hermes Agent Brain

TypeScript

Skill resolver hook: start the worker first and skip the CLI dispatcher

garrytan2ec73f8857c9
diff --git a/src/cli.ts b/src/cli.ts
index 6c191a0a3a..228fda56b7 100755
--- a/src/cli.ts
+++ b/src/cli.ts
@@ -2,7 +2,8 @@
/**
* gbrain CLI entry point (`bun src/cli.ts`, the `gbrain` bin, the compiled
* binary). Runs the process-level setup, then answers the engine-free fast
- * paths (`--version`, `version`, bare `gbrain`, `--help`, `-h`) itself, or
+ * paths (`--version`, `version`, bare `gbrain`, `--help`, `-h`, and the
+ * skill-resolver hook lane's `hook user-prompt|session-start`) itself, or
* loads the dispatcher (src/cli/main.ts) with a dynamic import. The dispatcher
* pulls in every operation and command module, so the fast paths skip that
* import graph entirely. Every static import here is paid by every invocation:
@@ -23,19 +24,40 @@ import { withLocalScope } from './core/engine-scope-store.ts';
* run. Mirrors main()'s first branches after global-flag parsing; a parse
* error falls through so the dispatcher reports it exactly as before.
*/
-export function cliFastPath(argv: string[]): 'help' | 'version' | null {
- let command: string | undefined;
+export function cliFastPath(argv: string[], env: NodeJS.ProcessEnv = process.env): 'help' | 'version' | 'skill-resolver-lane' | null {
+ let rest: string[];
try {
- command = parseGlobalFlags(argv).rest[0];
+ rest = parseGlobalFlags(argv).rest;
} catch {
return null;
}
+ const command = rest[0];
if (!command || command === '--help' || command === '-h') return 'help';
if (command === '--version' || command === 'version') return 'version';
+ if (env.GBRAIN_HOOK_LANE === 'skill-resolver' && command === 'hook' && (rest[1] === 'user-prompt' || rest[1] === 'session-start')
+ && !rest.some(a => a === '--help' || a === '-h')) return 'skill-resolver-lane';
return null;
}
-async function runFastPath(path: 'help' | 'version'): Promise<void> {
+/**
+ * The skill-resolver lane as runHook runs it (kill switch, harness flag, the
+ * launcher's session directory) without the dispatcher's module graph. The
+ * lane's worker starts first, so its start-up runs beside the preflight and
+ * the lane's own module loading.
+ */
+async function runSkillResolverLaneFastPath(): Promise<void> {
+ const rest = parseGlobalFlags(process.argv.slice(2)).rest;
+ const event = rest[1]!;
+ if (event === 'user-prompt' && process.env.GBRAIN_HOOKS !== '0') (await import('./core/skills/resolver/lane-worker.ts')).startLaneWorker();
+ await runCliPreflight();
+ if (process.env.GBRAIN_HOOKS === '0') return;
+ (await import('./core/session-cwd.ts')).captureHookSessionCwd();
+ const h = rest.indexOf('--harness');
+ await (await import('./core/skills/resolver/hook-lane.ts')).runSkillResolverLane(event, h >= 0 && rest[h + 1] === 'codex' ? 'codex' : 'claude-code');
+}
+
+async function runFastPath(path: 'help' | 'version' | 'skill-resolver-lane'): Promise<void> {
+ if (path === 'skill-resolver-lane') return runSkillResolverLaneFastPath();
await runCliPreflight();
if (path === 'help') printHelp();
else console.log(`gbrain ${VERSION}`);
diff --git a/src/core/skills/resolver/build.ts b/src/core/skills/resolver/build.ts
index 48ed8b468b..bff6ca9b00 100644
--- a/src/core/skills/resolver/build.ts
+++ b/src/core/skills/resolver/build.ts
@@ -18,10 +18,11 @@ import { VERSION } from '../../../version.ts';
import { ResolverError } from './errors.ts';
import { ensureDir, readBounded, writeFileDurable } from './fsutil.ts';
import { CALIBRATION_SPLIT_SHA256, encodeIndex, HINT_CHARS, RANKER_ID, RANKER_VERSION, VARIANT_PARAMS, type Variant } from './index-format.ts';
+import { listCatalogs, readReceipt } from './catalog-files.ts';
import { acquireLease, holdsLease, releaseLease, tryAcquireLease } from './lock.ts';
import { catalogDir, catalogFile, resolverHome, skillIndexRoot, validCatalogName, assertCatalogName } from './paths.ts';
import { gcSessions, loadSession, sessionKey } from './session.ts';
-import { applyRouting, fingerprintChanged, readBundledSource, readDirSources, readJsonSource, type DirFingerprint, type SkillRecord, type SkippedSkill, type SourceRead } from './sources.ts';
+import { applyRouting, readBundledSource, readDirSources, readJsonSource, type DirFingerprint, type SkillRecord, type SkippedSkill, type SourceRead } from './sources.ts';
import { TOKENIZER_ID } from './tokenize.ts';
import { BLOCK_TOKEN_CAP, BLOCK_TOKENIZER, HARNESSES } from './block.ts';
import { readResolverSettings } from './config.ts';
@@ -30,7 +31,6 @@ export const RECEIPT_SCHEMA_VERSION = 1;
export const T_SHARE_ON = 0.25;
export const T_SHARE_KEEP = 0.2;
const BUILD_LEASE_MS = 120_000;
-const RECEIPT_CAP_BYTES = 32 * 1024 * 1024;
export interface BuildInput {
catalog: string;
@@ -95,14 +95,6 @@ export function catalogHash(skills: readonly SkillRecord[], skipped: readonly Sk
return sha(JSON.stringify({ v: 1, skills: rows, skipped: skips, routing_rows: routingRows, scope }));
}
-export function readReceipt(home: string, name: string): BuildReceipt | null {
- try {
- const b = readBounded(catalogFile(home, name, 'receipt.json'), RECEIPT_CAP_BYTES);
- if (b === 'too_large') return null;
- const r = JSON.parse(b.toString('utf8')) as BuildReceipt;
- return r && typeof r === 'object' && r.catalog && r.index ? r : null;
- } catch { return null; }
-}
export function chooseVariant(skills: readonly SkillRecord[], previous: Variant | undefined): { variant: Variant; share: number } {
const share = skills.length ? skills.filter(s => s.triggers.length || s.routing.length).length / skills.length : 0;
@@ -236,11 +228,6 @@ export async function buildSkillIndex(input: BuildInput, opts: { home?: string;
}
}
-export function listCatalogs(home: string): string[] {
- try {
- return readdirSync(skillIndexRoot(home)).filter(n => validCatalogName(n) && existsSync(join(skillIndexRoot(home), n, 'receipt.json'))).sort();
- } catch { return []; }
-}
export async function removeSkillIndex(name: string, opts: { home?: string } = {}): Promise<{ catalog: string; removed: boolean }> {
const home = opts.home ?? resolverHome();
@@ -312,14 +299,5 @@ export function sessionStatus(sessionId: string, opts: { home?: string; harness?
* directory and file entries from `cursor` (the routing file every time).
* `next` is 0 once the sweep has covered every entry.
*/
-export function dirFingerprintSlice(home: string, name: string, cursor: number, limit: number): { changed: boolean; next: number } {
- try {
- const f = JSON.parse(readFileSync(catalogFile(home, name, 'fingerprint.json'), 'utf8')) as { fingerprint: DirFingerprint; routing: [string, number, number] | null };
- const { dirs, files } = f.fingerprint;
- const total = dirs.length + files.length;
- const from = cursor > 0 && cursor < total ? cursor : 0;
- const to = Math.min(total, from + limit);
- const part: DirFingerprint = { dirs: dirs.slice(Math.min(from, dirs.length), Math.min(to, dirs.length)), files: files.slice(Math.max(0, from - dirs.length), Math.max(0, to - dirs.length)) };
- return { changed: fingerprintChanged(part, f.routing ?? undefined), next: to >= total ? 0 : to };
- } catch { return { changed: true, next: 0 }; }
-}
+
+export { listCatalogs, readReceipt };
diff --git a/src/core/skills/resolver/catalog-files.ts b/src/core/skills/resolver/catalog-files.ts
new file mode 100644
index 0000000000..eda2e0c775
--- /dev/null
+++ b/src/core/skills/resolver/catalog-files.ts
@@ -0,0 +1,54 @@
+/**
+ * The catalog files the turn path reads: a catalog's receipt, the list of
+ * built catalogs and the sliced stat freshness check over a directory
+ * catalog's fingerprint. It imports no source parser (no SKILL.md
+ * frontmatter, no YAML), so the hook lane's worker loads only what a turn
+ * needs; build.ts and sources.ts take these from here.
+ */
+import { existsSync, readdirSync, readFileSync, statSync } from 'node:fs';
+import { join } from 'node:path';
+import { readBounded } from './fsutil.ts';
+import { catalogFile, skillIndexRoot, validCatalogName } from './paths.ts';
+import type { BuildReceipt } from './build.ts';
+import type { DirFingerprint } from './sources.ts';
+
+const RECEIPT_CAP_BYTES = 32 * 1024 * 1024;
+
+export function readReceipt(home: string, name: string): BuildReceipt | null {
+ try {
+ const b = readBounded(catalogFile(home, name, 'receipt.json'), RECEIPT_CAP_BYTES);
+ if (b === 'too_large') return null;
+ const r = JSON.parse(b.toString('utf8')) as BuildReceipt;
+ return r && typeof r === 'object' && r.catalog && r.index ? r : null;
+ } catch { return null; }
+}
+
+export function listCatalogs(home: string): string[] {
+ try {
+ return readdirSync(skillIndexRoot(home)).filter(n => validCatalogName(n) && existsSync(join(skillIndexRoot(home), n, 'receipt.json'))).sort();
+ } catch { return []; }
+}
+
+/** Recheck a directory fingerprint by stat only (the turn-path freshness tier). */
+export function fingerprintChanged(fp: DirFingerprint, routing?: [string, number, number]): boolean {
+ try {
+ for (const [d, m] of fp.dirs) if (statSync(d).mtimeMs !== m) return true;
+ for (const [f, size, m] of fp.files) { const st = statSync(f); if (st.size !== size || st.mtimeMs !== m) return true; }
+ if (routing) { const st = statSync(routing[0]); if (st.size !== routing[1] || st.mtimeMs !== routing[2]) return true; }
+ return false;
+ } catch {
+ return true;
+ }
+}
+
+export function dirFingerprintSlice(home: string, name: string, cursor: number, limit: number): { changed: boolean; next: number } {
+ try {
+ const f = JSON.parse(readFileSync(catalogFile(home, name, 'fingerprint.json'), 'utf8')) as { fingerprint: DirFingerprint; routing: [string, number, number] | null };
+ const { dirs, files } = f.fingerprint;
+ const total = dirs.length + files.length;
+ const from = cursor > 0 && cursor < total ? cursor : 0;
+ const to = Math.min(total, from + limit);
+ const part: DirFingerprint = { dirs: dirs.slice(Math.min(from, dirs.length), Math.min(to, dirs.length)), files: files.slice(Math.max(0, from - dirs.length), Math.max(0, to - dirs.length)) };
+ return { changed: fingerprintChanged(part, f.routing ?? undefined), next: to >= total ? 0 : to };
+ } catch { return { changed: true, next: 0 }; }
+}
diff --git a/src/core/skills/resolver/hook-lane.ts b/src/core/skills/resolver/hook-lane.ts
index 33bf05f0e7..367f185b8e 100644
--- a/src/core/skills/resolver/hook-lane.ts
+++ b/src/core/skills/resolver/hook-lane.ts
@@ -13,7 +13,10 @@
* Deadline (50 ms from lane entry): the main thread does only async I/O (the
* config, stdin, the carriers, the commit) and every synchronous step (index
* and session reads, ranking, rendering) runs in a worker thread
- * (hook-worker.ts) that checks the deadline inside each stage. At the
+ * (hook-worker.ts) that checks the deadline inside each stage. The worker is
+ * started before that I/O (by the CLI's lane fast path, before the lane
+ * module even loads, else at lane entry), so its start-up overlaps it; a turn
+ * that ends before the worker is needed terminates it. At the
* deadline the main thread prints nothing and exits the process at once,
* abandoning the worker, and commits no dedupe state: a commit starts only
* after the block was written, on the main thread, before the deadline.
@@ -45,7 +48,7 @@ import { createHash } from 'node:crypto';
import { appendFile, mkdir, readFile, realpath, stat, truncate, unlink, writeFile } from 'node:fs/promises';
import { homedir } from 'node:os';
import { join } from 'node:path';
-import { Worker } from 'node:worker_threads';
+import type { Worker } from 'node:worker_threads';
import { spawn } from '../../spawn.ts';
import { claudeManagedSettingsPaths, claudeUserSettingsPath, codexHooksPath } from '../../bootstrap/host-specs.ts';
import { shellWords } from '../../setup/hook-launcher.ts';
@@ -53,7 +56,10 @@ import { isSkillResolverCommand, isSkillResolverEntry } from '../../setup/skill-
import { assertCatalogName, catalogFile, logsDir, resolverHome } from './paths.ts';
import { commitSessionAsync, sessionKey, type TurnDelta } from './session.ts';
import type { TurnOutput } from './resolve.ts';
-import type { LaneWorkerData } from './hook-worker.ts';
+import type { LaneWorkerTurn } from './hook-worker.ts';
+import { startLaneWorker } from './lane-worker.ts';
+
+export { WORKER_SRC_PATH } from './lane-worker.ts';
export const LANE_DEADLINE_MS = 50;
export const LANE_STDIN_CAP_BYTES = 256 * 1024;
@@ -66,14 +72,6 @@ const CONFIG_CAP_BYTES = 1024 * 1024;
const SPAWN_INTERVAL_MS = 60_000;
/** Time kept back from the worker's own deadline for delivery and the commit. */
const COMMIT_RESERVE_MS = 10;
-/**
- * The worker's entry. A compiled binary bundles src/ under a virtual root
- * (/$bunfs/root/, ~BUN on Windows) and carries hook-worker.ts as a second
- * entrypoint at its src-relative path (every release build passes it); the
- * bundle's own import.meta.url is the binary, so the path is taken from there.
- */
-export const WORKER_SRC_PATH = 'core/skills/resolver/hook-worker.ts';
-const workerEntry = (): string | URL => (/[\\/](\$bunfs|~BUN)[\\/]/.test(import.meta.url) ? Bun.main.replace(/[^\\/]*$/, '') + WORKER_SRC_PATH : new URL('./hook-worker.ts', import.meta.url));
export type LaneHarness = 'claude-code' | 'codex';
export const userCatalogName = (harness: LaneHarness) => `${harness}-user`;
@@ -219,7 +217,8 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,
try { home = resolverHome(env); } catch { return 0; }
const deadlineMs = io.deadlineMs ?? (Number(env.GBRAIN_TEST_SKILL_LANE_DEADLINE_MS) || LANE_DEADLINE_MS);
const elapsed = () => performance.now() - t0;
- const ctl = { expired: false, worker: null as Worker | null, logged: false };
+ const ctl: LaneCtl = { expired: false, worker: null, logged: false };
+ if (event === 'user-prompt') ctl.worker = startLaneWorker(env);
const log = (t: Turn) => appendLaneLog(home, { at: new Date().toISOString(), harness, event, outcome: t.outcome, ...(t.code ? { code: t.code } : {}), ms: Math.round(elapsed() * 10) / 10, ...(t.catalogs ? { catalogs: t.catalogs } : {}), ...(t.dropped_chars ? { dropped_chars: t.dropped_chars } : {}) });
let timer: ReturnType<typeof setTimeout> | undefined;
@@ -239,7 +238,9 @@ export async function runSkillResolverLane(event: string, harness: LaneHarness,
return 0;
}
-async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarness, home: string, env: NodeJS.ProcessEnv, io: LaneIo, ctl: { expired: boolean; worker: Worker | null; logged: boolean }, elapsed: () => number, deadlineMs: number): Promise<Turn> {
+interface LaneCtl { expired: boolean; worker: Worker | null; logged: boolean }
+
+async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHarness, home: string, env: NodeJS.ProcessEnv, io: LaneIo, ctl: LaneCtl, elapsed: () => number, deadlineMs: number): Promise<Turn> {
const settings = await readLaneSettings(home, env);
if (settings.state === 'absent') return { outcome: 'off' };
if (settings.state === 'unreadable') { ctl.logged = true; return { outcome: 'error', code: 'skill_resolver_config_unreadable' }; }
@@ -272,14 +273,12 @@ async function laneTurn(event: 'user-prompt' | 'session-start', harness: LaneHar
else if (project && settings.autoRebuild) await scheduleBuild(home, project.name, ['skills', 'index', 'build', '--catalog', project.name, '--dir', project.dir, '--scope', 'project', '--harness', harness], spawnFn);
}
+ const worker = ctl.worker;
+ if (!worker) return { outcome: 'error', code: 'skill_resolver_internal', catalogs };
const posted = await new Promise<{ output?: TurnOutput; pending?: { key: string; delta: TurnDelta } | null; error?: { code: string } }>((resolve) => {
- const worker = new Worker(workerEntry(), {
- workerData: { input: { message: prompt, harness, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS), stall: env.GBRAIN_TEST_SKILL_LANE_STALL } satisfies LaneWorkerData,
- });
- ctl.worker = worker;
- worker.unref();
worker.once('message', resolve);
worker.once('error', () => resolve({ error: { code: 'skill_resolver_internal' } }));
+ worker.postMessage({ input: { message: prompt, harness, ...(sessionId ? { session_id: sessionId } : {}) }, home, catalogs, deadlineMs: Math.max(1, deadlineMs - elapsed() - COMMIT_RESERVE_MS) } satisfies LaneWorkerTurn);
});
if (posted.error || !posted.output) return { outcome: 'error', code: posted.error?.code ?? 'skill_resolver_internal', catalogs };
const out = posted.output;
diff --git a/src/core/skills/resolver/hook-worker.ts b/src/core/skills/resolver/hook-worker.ts
index 2a08b25a94..c31b715d7a 100644
--- a/src/core/skills/resolver/hook-worker.ts
+++ b/src/core/skills/resolver/hook-worker.ts
@@ -2,8 +2,11 @@
* The hook lane's worker thread (hook-lane.ts): every synchronous step of a
* turn (reading the index and session state, ranking, rendering) runs here,
* so the lane's main thread keeps an event loop whose deadline timer can
- * always fire. It posts the prepared turn and its pending commit; it never
- * commits: the main thread does, after delivery and before the deadline.
+ * always fire. lane-worker.ts starts it before the lane's own I/O, so its
+ * start-up and module loading overlap the main thread's config, stdin and
+ * carrier reads; the turn arrives as one message. It posts the prepared
+ * turn and its pending commit; it never commits: the main thread does,
+ * after delivery and before the deadline.
*
* GBRAIN_TEST_SKILL_LANE_STALL (tests only) forces a slow stage: block
* (synchronous 10 s busy loop), hang (never answers), late (answers after
@@ -13,9 +16,11 @@
import { parentPort, workerData } from 'node:worker_threads';
import { resolveSkills } from './resolve.ts';
-export interface LaneWorkerData { input: unknown; home: string; catalogs: string[]; deadlineMs: number; stall?: string }
+export interface LaneWorkerData { stall?: string }
+export interface LaneWorkerTurn { input: unknown; home: string; catalogs: string[]; deadlineMs: number }
-const { input, home, catalogs, deadlineMs, stall } = workerData as LaneWorkerData;
+const { stall } = (workerData ?? {}) as LaneWorkerData;
+const { input, home, catalogs, deadlineMs } = await new Promise<LaneWorkerTurn>(resolve => parentPort!.once('message', resolve));
if (stall === 'block') { const end = Date.now() + 10_000; while (Date.now() < end) { /* forced synchronous stall */ } }
if (stall === 'hang') await new Promise(() => {});
diff --git a/src/core/skills/resolver/lane-worker.ts b/src/core/skills/resolver/lane-worker.ts
new file mode 100644
index 0000000000..38a104deb8
--- /dev/null
+++ b/src/core/skills/resolver/lane-worker.ts
@@ -0,0 +1,28 @@
+/**
+ * Starts the hook lane's worker thread (hook-worker.ts). The CLI's lane fast
+ * path (src/cli.ts) calls it before it loads the lane itself, so the worker's
+ * start-up and module loading run beside the CLI's; the lane then takes that
+ * worker instead of starting its own. It imports nothing but worker_threads.
+ *
+ * A compiled binary bundles src/ under a virtual root (/$bunfs/root/, ~BUN on
+ * Windows) and carries hook-worker.ts as a second entrypoint at its
+ * src-relative path (every release build passes it); the bundle's own
+ * import.meta.url is the binary, so the path is taken from there.
+ */
+import { Worker } from 'node:worker_threads';
+
+export const WORKER_SRC_PATH = 'core/skills/resolver/hook-worker.ts';
+const workerEntry = (): string | URL => (/[\\/](\$bunfs|~BUN)[\\/]/.test(import.meta.url) ? Bun.main.replace(/[^\\/]*$/, '') + WORKER_SRC_PATH : new URL('./hook-worker.ts', import.meta.url));
+
+let started: Worker | null = null;
+
+/** Start the worker (once per process). Null when it cannot start; the lane then reports skill_resolver_internal. */
+export function startLaneWorker(env: NodeJS.ProcessEnv = process.env): Worker | null {
+ if (started) return started;
+ try {
+ started = new Worker(workerEntry(), { workerData: { stall: env.GBRAIN_TEST_SKILL_LANE_STALL } });
+ started.unref();
+ started.on('error', () => {});
+ } catch { started = null; }
+ return started;
+}
diff --git a/src/core/skills/resolver/resolve.ts b/src/core/skills/resolver/resolve.ts
index 287e6e92e1..aac2240fd2 100644
--- a/src/core/skills/resolver/resolve.ts
+++ b/src/core/skills/resolver/resolve.ts
@@ -23,7 +23,8 @@ import { createHash } from 'node:crypto';
import { join } from 'node:path';
import { VERSION } from '../../../version.ts';
import { BLOCK_TOKEN_CAP, BLOCK_TOKENIZER, HARNESSES, renderBlock, type BlockLine } from './block.ts';
-import { dirFingerprintSlice, listCatalogs, readReceipt, type BuildReceipt } from './build.ts';
+import type { BuildReceipt } from './build.ts';
+import { dirFingerprintSlice, listCatalogs, readReceipt } from './catalog-files.ts';
import { readResolverSettings, validateSessionTokenBudget } from './config.ts';
import { ResolverError } from './errors.ts';
import { ensureDir, writeFileAtomic, writeFileDurable } from './fsutil.ts';
diff --git a/src/core/skills/resolver/sources.ts b/src/core/skills/resolver/sources.ts
index 6d929ccb64..339faca2b1 100644
--- a/src/core/skills/resolver/sources.ts
+++ b/src/core/skills/resolver/sources.ts
@@ -19,6 +19,7 @@ import { ResolverError } from './errors.ts';
import { readBounded, readHead } from './fsutil.ts';
import { boundBody, cleanText, parseSkillDoc, SKILL_FILE_CAP_BYTES } from './frontmatter.ts';
import { parseRoutingTable } from './routing.ts';
+export { fingerprintChanged } from './catalog-files.ts';
export const MAX_SKILLS = 10_000;
export const MAX_DIRS_VISITED = 100_000;
@@ -235,15 +236,3 @@ export function applyRouting(skills: SkillRecord[], path: string): { rows: numbe
}
return { rows: rows.length, unmatched, stat: [real, st.size, st.mtimeMs] };
}
-
-/** Recheck a directory fingerprint by stat only (the turn-path freshness tier). */
-export function fingerprintChanged(fp: DirFingerprint, routing?: [string, number, number]): boolean {
- try {
- for (const [d, m] of fp.dirs) if (statSync(d).mtimeMs !== m) return true;
- for (const [f, size, m] of fp.files) { const st = statSync(f); if (st.size !== size || st.mtimeMs !== m) return true; }
- if (routing) { const st = statSync(routing[0]); if (st.size !== routing[1] || st.mtimeMs !== routing[2]) return true; }
- return false;
- } catch {
- return true;
- }
-}
diff --git a/test/cli-fast-path.test.ts b/test/cli-fast-path.test.ts
index 4a44ced508..a67ad129e5 100644
--- a/test/cli-fast-path.test.ts
+++ b/test/cli-fast-path.test.ts
@@ -42,6 +42,18 @@ describe('cliFastPath mirrors main()\'s first branches', () => {
expect(cliFastPath(['--tools-json'])).toBeNull();
expect(cliFastPath(['--brain'])).toBeNull();
});
+
+ test('the skill-resolver hook lane takes its own fast path; other lanes, events and help forms go to the dispatcher', () => {
+ const lane = { GBRAIN_HOOK_LANE: 'skill-resolver' };
+ expect(cliFastPath(['hook', 'user-prompt'], lane)).toBe('skill-resolver-lane');
+ expect(cliFastPath(['hook', 'user-prompt', '--harness', 'codex'], lane)).toBe('skill-resolver-lane');
+ expect(cliFastPath(['hook', 'session-start'], lane)).toBe('skill-resolver-lane');
+ expect(cliFastPath(['hook', 'user-prompt'], {})).toBeNull();
+ expect(cliFastPath(['hook', 'user-prompt'], { GBRAIN_HOOK_LANE: 'turn-rule' })).toBeNull();
+ expect(cliFastPath(['hook', 'stop'], lane)).toBeNull();
+ expect(cliFastPath(['hook', 'user-prompt', '--help'], lane)).toBeNull();
+ expect(cliFastPath(['get', 'some/page'], lane)).toBeNull();
+ });
});
describe('import graphs', () => {
diff --git a/test/skill-resolver-hook-lane.test.ts b/test/skill-resolver-hook-lane.test.ts
index 5fd4ba63bd..6b153fb6a9 100644
--- a/test/skill-resolver-hook-lane.test.ts
+++ b/test/skill-resolver-hook-lane.test.ts
@@ -166,6 +166,28 @@ describe('skill-resolver lane: deadline, measured outside the process', () => {
}
});
+describe('skill-resolver lane: the CLI fast path keeps the hook contract', () => {
+ test('GBRAIN_HOOKS=0 silences the lane, whether exported or set in the env file the CLI preflight loads', async () => {
+ const b = box();
+ seedSkills(claudeSkills(b));
+ await setup(b, 'claude-code');
+ const cmd = wired(b, 'claude-code');
+ const turn = { prompt: 'please deploy the widget to staging', session_id: 'sess-off' };
+ const exported = await hook(b, cmd, turn, { ...WIDE, GBRAIN_HOOKS: '0' });
+ expect(exported.exitCode).toBe(0);
+ expect(exported.stdout).toBe('');
+ writeFileSync(join(b.home, '.gbrain', '.env'), 'GBRAIN_HOOKS=0\n');
+ const fromFile = await hook(b, cmd, turn, WIDE);
+ expect(fromFile.exitCode).toBe(0);
+ expect(fromFile.stdout).toBe('');
+ expect(laneLog(b)).toEqual([]);
+ expect(sessions(b)).toEqual([]);
+ rmSync(join(b.home, '.gbrain', '.env'));
+ const on = await hook(b, cmd, turn, WIDE);
+ expect(contextOf(on)).toContain('id: "deploy-widget"');
+ });
+});
+
describe('skill-resolver lane: fail open', () => {
test('lane off (no config): prints nothing and writes nothing', async () => {
const b = box();