From f3e23828400cf5da2a9af722a70ce00be1dae22e Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:04:00 +0000 Subject: [PATCH 1/2] fix(agent): fail closed when a blocking hook's payload, handler, matcher or filter fails --- .../blocking-hooks-fail-closed-on-errors.md | 5 + packages/agent/README.md | 9 + packages/agent/src/lib/hooks-emit.ts | 50 ++++- packages/agent/src/lib/hooks-manager.ts | 12 +- packages/agent/src/lib/hooks-types.ts | 14 +- packages/agent/src/lib/model-result.ts | 12 +- .../tests/unit/hooks-contract-fixes.test.ts | 206 ++++++++++++++++++ .../agent/tests/unit/hooks-manager.test.ts | 4 +- .../tests/unit/model-result-hooks.test.ts | 40 ++++ 9 files changed, 340 insertions(+), 12 deletions(-) create mode 100644 .changeset/blocking-hooks-fail-closed-on-errors.md diff --git a/.changeset/blocking-hooks-fail-closed-on-errors.md b/.changeset/blocking-hooks-fail-closed-on-errors.md new file mode 100644 index 00000000..9e91c885 --- /dev/null +++ b/.changeset/blocking-hooks-fail-closed-on-errors.md @@ -0,0 +1,5 @@ +--- +"@openrouter/agent": patch +--- + +Fail closed when a blocking hook fails. Outside strict mode, a `PreToolUse` or `UserPromptSubmit` emit used to report `blocked: false` when its payload failed validation, and a throwing handler, matcher or filter (or a handler returning an invalid result) was logged and skipped, so a crashing deny guard let the tool run. These cases now stop the chain and return `blocked: true` with a new `blockReason` field; the tool gets the usual blocked output and does not run. Non-blocking hooks keep logging and continuing, and `throwOnHandlerError: true` still re-throws. diff --git a/packages/agent/README.md b/packages/agent/README.md index dfa694df..36a839f9 100644 --- a/packages/agent/README.md +++ b/packages/agent/README.md @@ -903,6 +903,15 @@ Handlers for a hook run sequentially in registration order. continues. Construct the manager with `new HooksManager(custom, { throwOnHandlerError: true })` to propagate errors instead (useful in tests). +- **Blocking hooks fail closed**: `PreToolUse` and `UserPromptSubmit` don't + skip failures, because the failing handler may be the guard that would + have blocked. If the payload fails validation, a handler, matcher or + filter throws, a handler returns an invalid result, or the chain is + aborted before every handler ran, the emit returns `blocked: true` with a + `blockReason` (the error itself is only logged). A blocked `PreToolUse` + gives the model the usual blocked tool output with that reason and the + tool does not run; a blocked `UserPromptSubmit` rejects the call. Other + hooks keep the log-and-continue policy above. **Async fire-and-forget handlers** diff --git a/packages/agent/src/lib/hooks-emit.ts b/packages/agent/src/lib/hooks-emit.ts index 7a050717..07e80dcd 100644 --- a/packages/agent/src/lib/hooks-emit.ts +++ b/packages/agent/src/lib/hooks-emit.ts @@ -67,6 +67,13 @@ function isPlainMutableObject(value: unknown): value is Record * `abortInflight()` has a deterministic effect on the chain itself (not just * on handlers that happen to consult the signal). For hooks with a block * field, bailing out before every handler ran reports `blocked: true`. + * - Fail closed for blocking hooks: for a hook with a block field + * (PreToolUse, UserPromptSubmit), a throwing handler, matcher or filter, + * or a handler result that fails `options.resultSchema`, stops the chain + * with `blocked: true` and a `blockReason` instead of being logged and + * skipped, because the failing handler may be the guard that would have + * blocked. Other hooks keep log-and-continue. Strict mode + * (`throwOnHandlerError`) still re-throws. * * Payload isolation: the initial payload is shallow-cloned before entering the * chain so mutation piping (via {@link HOOK_BEHAVIOR}) doesn't mutate the @@ -98,12 +105,22 @@ export async function executeHandlerChain( } as P) : initialPayload; let blocked = false; + let blockReason: string | undefined; let mutated = false; // Per-hook mutation/block behavior. Hooks absent from the table (all // observation-only hooks and every custom hook) collect results without // altering the payload or short-circuiting. const behavior = (HOOK_BEHAVIOR as Partial>)[options.hookName]; + const failsClosed = behavior?.blockField !== undefined; + // Blocking hooks route every handler/matcher/filter/result failure through + // the catch blocks below so it can fail closed instead of being skipped. + const gateOptions: ExecuteChainOptions = failsClosed + ? { + ...options, + throwOnHandlerError: true, + } + : options; for (let i = 0; i < entries.length; i++) { // Cooperative abort: bail out of the chain when abortInflight() has fired. @@ -113,8 +130,9 @@ export async function executeHandlerChain( // A hook that can block (PreToolUse, UserPromptSubmit) fails closed: // the handlers left unrun may include the guard that would have // blocked, so an aborted chain must not read as an approval. - if (behavior?.blockField) { + if (failsClosed) { blocked = true; + blockReason = `Blocked: ${options.hookName} hook chain was aborted before every handler ran`; } break; } @@ -127,14 +145,28 @@ export async function executeHandlerChain( // Matcher and filter checks run under the same error policy as handlers: // in non-strict mode a throwing user-supplied matcher function or filter // is logged and the entry skipped, instead of crashing the whole chain. - const gate = evaluateEntryGate(entry, currentPayload, i, options); + let gate: 'run' | 'skip'; + try { + gate = evaluateEntryGate(entry, currentPayload, i, gateOptions); + } catch (error) { + if (options.throwOnHandlerError) { + throw error; + } + console.warn( + `[HooksManager] Matcher/filter for handler ${i} of hook "${options.hookName}" threw; failing closed:`, + error, + ); + blocked = true; + blockReason = `Blocked: ${options.hookName} hook matcher/filter for handler ${i} threw`; + break; + } if (gate === 'skip') { continue; } try { const returnValue = await entry.handler(currentPayload, context); - const outcome = classifyHandlerReturn(returnValue, i, options); + const outcome = classifyHandlerReturn(returnValue, i, gateOptions); if (outcome.kind === 'async') { // Fire-and-forget: track the (optional) work promise for drain/timeout. @@ -169,6 +201,15 @@ export async function executeHandlerChain( if (options.throwOnHandlerError) { throw error; } + if (failsClosed) { + console.warn( + `[HooksManager] Handler ${i} for hook "${options.hookName}" failed; failing closed:`, + error, + ); + blocked = true; + blockReason = `Blocked: ${options.hookName} hook handler ${i} failed`; + break; + } console.warn(`[HooksManager] Handler ${i} for hook "${options.hookName}" threw:`, error); } } @@ -178,6 +219,9 @@ export async function executeHandlerChain( pending, finalPayload: currentPayload, blocked, + ...(blockReason !== undefined && { + blockReason, + }), mutated, }; } diff --git a/packages/agent/src/lib/hooks-manager.ts b/packages/agent/src/lib/hooks-manager.ts index 2405de0d..e464ed39 100644 --- a/packages/agent/src/lib/hooks-manager.ts +++ b/packages/agent/src/lib/hooks-manager.ts @@ -5,6 +5,7 @@ import { BUILT_IN_HOOK_NAMES, BUILT_IN_HOOKS } from './hooks-schemas.js'; import type { BuiltInHookDefinitions, EmitResult, + HookBehavior, HookDefinition, HookEntry, HookHandler, @@ -12,6 +13,7 @@ import type { HooksManagerOptions, LifecycleHookContext, } from './hooks-types.js'; +import { HOOK_BEHAVIOR } from './hooks-types.js'; //#region Types @@ -194,11 +196,19 @@ export class HooksManager> { throw err; } console.warn(err.message); + // A blocking hook (PreToolUse, UserPromptSubmit) fails closed: its + // guards never ran, so the emit must not read as an approval. + const failsClosed = + (HOOK_BEHAVIOR as Partial>)[hookName]?.blockField !== + undefined; return { results: [], pending: [], finalPayload: chainPayload, - blocked: false, + blocked: failsClosed, + ...(failsClosed && { + blockReason: `Blocked: ${hookName} hook payload failed validation`, + }), mutated: false, }; } diff --git a/packages/agent/src/lib/hooks-types.ts b/packages/agent/src/lib/hooks-types.ts index 55a95f4e..5891d52d 100644 --- a/packages/agent/src/lib/hooks-types.ts +++ b/packages/agent/src/lib/hooks-types.ts @@ -121,11 +121,19 @@ export interface EmitResult { /** The payload after all mutation piping has been applied. */ readonly finalPayload: P; /** - * True if any handler triggered a block/reject short-circuit, or if the - * chain of a blocking hook (PreToolUse, UserPromptSubmit) was aborted - * before every handler ran. + * True if any handler triggered a block/reject short-circuit, or if a + * blocking hook (PreToolUse, UserPromptSubmit) failed closed: its chain + * was aborted before every handler ran, its payload failed validation, or + * (outside strict mode) a handler, matcher or filter threw or a handler + * returned an invalid result. */ readonly blocked: boolean; + /** + * Why a blocking hook failed closed. Set only in the fail-closed cases + * listed on `blocked`; a handler's own block/reject reason stays in + * `results`. Error details are logged, not included here. + */ + readonly blockReason?: string; /** * True if any handler's result actually piped a mutation into the payload * (e.g. PreToolUse `mutatedInput`, UserPromptSubmit `mutatedPrompt`). diff --git a/packages/agent/src/lib/model-result.ts b/packages/agent/src/lib/model-result.ts index bf39a6f6..4fc0ce94 100644 --- a/packages/agent/src/lib/model-result.ts +++ b/packages/agent/src/lib/model-result.ts @@ -1598,7 +1598,10 @@ export class ModelResult< // Every entry in `results` passed the PreToolUseResult schema (see // EmitResult.results invariant), so no structural re-narrowing needed. const block = preResult.results.find((r) => r.block)?.block; - const reason = typeof block === 'string' ? block : 'Blocked by PreToolUse hook'; + const reason = + typeof block === 'string' + ? block + : (preResult.blockReason ?? 'Blocked by PreToolUse hook'); return { type: 'hook_blocked', toolCall, @@ -2722,7 +2725,8 @@ export class ModelResult< if (preResult.blocked) { const block = preResult.results.find((result) => result.block)?.block; - const reason = typeof block === 'string' ? block : 'Blocked by PreToolUse hook'; + const reason = + typeof block === 'string' ? block : (preResult.blockReason ?? 'Blocked by PreToolUse hook'); this.preparedToolCalls.set(toolCall.id, { type: 'blocked', reason, @@ -2950,7 +2954,9 @@ export class ModelResult< if (emit.blocked) { // Every entry in `results` passed the UserPromptSubmitResult schema. const reject = emit.results.find((r) => r.reject)?.reject; - throw new Error(typeof reject === 'string' ? reject : 'Prompt rejected by hook'); + throw new Error( + typeof reject === 'string' ? reject : (emit.blockReason ?? 'Prompt rejected by hook'), + ); } if (!emit.mutated) { diff --git a/packages/agent/tests/unit/hooks-contract-fixes.test.ts b/packages/agent/tests/unit/hooks-contract-fixes.test.ts index e9d5885e..4655de1a 100644 --- a/packages/agent/tests/unit/hooks-contract-fixes.test.ts +++ b/packages/agent/tests/unit/hooks-contract-fixes.test.ts @@ -519,3 +519,209 @@ describe('blocking hooks fail closed when the chain is aborted', () => { expect(result.blocked).toBe(false); }); }); + +describe('blocking hooks fail closed when a handler or payload fails', () => { + const preToolUsePayload = { + toolName: 't', + toolInput: {}, + }; + const emitContext = { + toolName: 't', + }; + + it('blocks PreToolUse when a handler throws', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + manager.on('PreToolUse', { + handler: () => { + throw new Error('policy service unavailable'); + }, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: PreToolUse hook handler 0 failed'); + }); + + it('stops the PreToolUse chain at the throwing handler', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + const later = vi.fn(); + manager.on('PreToolUse', { + handler: () => { + throw new Error('boom'); + }, + }); + manager.on('PreToolUse', { + handler: later, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(result.blocked).toBe(true); + expect(later).not.toHaveBeenCalled(); + }); + + it('blocks PreToolUse when a matcher function throws', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + const handler = vi.fn(); + manager.on('PreToolUse', { + matcher: () => { + throw new Error('bad matcher'); + }, + handler, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(handler).not.toHaveBeenCalled(); + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: PreToolUse hook matcher/filter for handler 0 threw'); + }); + + it('blocks PreToolUse when a filter throws', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + manager.on('PreToolUse', { + filter: () => { + throw new Error('bad filter'); + }, + handler: () => {}, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: PreToolUse hook matcher/filter for handler 0 threw'); + }); + + it('blocks PreToolUse when a handler returns an invalid result', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + manager.on('PreToolUse', { + handler: () => + ({ + block: 42, + }) as never, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: PreToolUse hook handler 0 failed'); + }); + + it('blocks UserPromptSubmit when a handler throws', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + manager.on('UserPromptSubmit', { + handler: () => { + throw new Error('moderation down'); + }, + }); + + const result = await manager.emit('UserPromptSubmit', { + prompt: 'hi', + }); + + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: UserPromptSubmit hook handler 0 failed'); + }); + + it('blocks PreToolUse when the payload fails validation', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + const handler = vi.fn(); + manager.on('PreToolUse', { + handler, + }); + + const result = await manager.emit( + 'PreToolUse', + { + toolName: 't', + toolInput: 'not an object', + } as never, + emitContext, + ); + + expect(handler).not.toHaveBeenCalled(); + expect(result.blocked).toBe(true); + expect(result.blockReason).toBe('Blocked: PreToolUse hook payload failed validation'); + }); + + it('reports a reason when a blocking chain is aborted', async () => { + const manager = new HooksManager(); + manager.on('PreToolUse', { + handler: () => { + manager.abortInflight('shutdown'); + }, + }); + manager.on('PreToolUse', { + handler: () => {}, + }); + + const result = await manager.emit('PreToolUse', preToolUsePayload, emitContext); + + expect(result.blocked).toBe(true); + expect(result.blockReason).toContain('aborted'); + }); + + it('keeps log-and-continue for non-blocking hooks', async () => { + const warn = vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + const later = vi.fn(); + manager.on('PostToolUse', { + handler: () => { + throw new Error('telemetry down'); + }, + }); + manager.on('PostToolUse', { + handler: later, + }); + + const result = await manager.emit( + 'PostToolUse', + { + toolName: 't', + toolInput: {}, + toolOutput: 'ok', + durationMs: 1, + }, + emitContext, + ); + + expect(later).toHaveBeenCalledOnce(); + expect(result.blocked).toBe(false); + expect(result.blockReason).toBeUndefined(); + expect(warn).toHaveBeenCalled(); + }); + + it('keeps blocked false for a non-blocking hook with an invalid payload', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const manager = new HooksManager(); + + const result = await manager.emit('PostToolUse', { + toolName: 1, + } as never); + + expect(result.blocked).toBe(false); + }); + + it('still rethrows in strict mode', async () => { + const manager = new HooksManager(undefined, { + throwOnHandlerError: true, + }); + manager.on('PreToolUse', { + handler: () => { + throw new Error('strict boom'); + }, + }); + + await expect(manager.emit('PreToolUse', preToolUsePayload, emitContext)).rejects.toThrow( + 'strict boom', + ); + }); +}); diff --git a/packages/agent/tests/unit/hooks-manager.test.ts b/packages/agent/tests/unit/hooks-manager.test.ts index 5a97e536..96e81e2f 100644 --- a/packages/agent/tests/unit/hooks-manager.test.ts +++ b/packages/agent/tests/unit/hooks-manager.test.ts @@ -361,7 +361,7 @@ describe('HooksManager', () => { ).rejects.toThrow('Invalid payload for hook "PreToolUse"'); }); - it('default mode logs and short-circuits when payload is invalid', async () => { + it('default mode logs and fails closed when a blocking hook payload is invalid', async () => { const warnSpy = vi.spyOn(console, 'warn').mockImplementation(() => {}); const manager = new HooksManager(); const handler = vi.fn(); @@ -377,7 +377,7 @@ describe('HooksManager', () => { expect(warnSpy).toHaveBeenCalled(); expect(handler).not.toHaveBeenCalled(); expect(result.results).toEqual([]); - expect(result.blocked).toBe(false); + expect(result.blocked).toBe(true); warnSpy.mockRestore(); }); diff --git a/packages/agent/tests/unit/model-result-hooks.test.ts b/packages/agent/tests/unit/model-result-hooks.test.ts index 751144b5..e2fe3496 100644 --- a/packages/agent/tests/unit/model-result-hooks.test.ts +++ b/packages/agent/tests/unit/model-result-hooks.test.ts @@ -278,6 +278,46 @@ describe('ModelResult hooks integration', () => { expect(fail).not.toHaveBeenCalled(); }); + it('returns hook_blocked without running the tool when a PreToolUse handler throws', async () => { + vi.spyOn(console, 'warn').mockImplementation(() => {}); + const hooks = new HooksManager(); + hooks.on('PreToolUse', { + handler: () => { + throw new Error('policy service unavailable'); + }, + }); + + const execSpy = vi.fn(); + const tool = makeAutoTool('guarded', () => { + execSpy(); + return { + shouldNotRun: true, + }; + }); + const m = buildModelResult({ + tools: [ + tool, + ] as const, + hooks, + }); + + const result = await internal(m).runToolWithHooks( + tool, + { + id: 'call_g', + name: 'guarded', + arguments: {}, + }, + { + numberOfTurns: 1, + }, + ); + + expect(result.type).toBe('hook_blocked'); + expect(result.reason).toBe('Blocked: PreToolUse hook handler 0 failed'); + expect(execSpy).not.toHaveBeenCalled(); + }); + it('fires PostToolUseFailure when the tool throws', async () => { const hooks = new HooksManager(); const fail = vi.fn(); From 040e99a2f47d2a9c941a64ba2d670f6bf7130394 Mon Sep 17 00:00:00 2001 From: Devin AI <158243242+devin-ai-integration[bot]@users.noreply.github.com> Date: Mon, 30 Nov 2026 16:06:59 +0000 Subject: [PATCH 2/2] refactor(agent): split entry evaluation out of executeHandlerChain to keep its complexity under the gate --- packages/agent/src/lib/hooks-emit.ts | 188 ++++++++++++++++----------- 1 file changed, 113 insertions(+), 75 deletions(-) diff --git a/packages/agent/src/lib/hooks-emit.ts b/packages/agent/src/lib/hooks-emit.ts index 07e80dcd..4cfe022d 100644 --- a/packages/agent/src/lib/hooks-emit.ts +++ b/packages/agent/src/lib/hooks-emit.ts @@ -113,14 +113,6 @@ export async function executeHandlerChain( // altering the payload or short-circuiting. const behavior = (HOOK_BEHAVIOR as Partial>)[options.hookName]; const failsClosed = behavior?.blockField !== undefined; - // Blocking hooks route every handler/matcher/filter/result failure through - // the catch blocks below so it can fail closed instead of being skipped. - const gateOptions: ExecuteChainOptions = failsClosed - ? { - ...options, - throwOnHandlerError: true, - } - : options; for (let i = 0; i < entries.length; i++) { // Cooperative abort: bail out of the chain when abortInflight() has fired. @@ -142,75 +134,39 @@ export async function executeHandlerChain( continue; } - // Matcher and filter checks run under the same error policy as handlers: - // in non-strict mode a throwing user-supplied matcher function or filter - // is logged and the entry skipped, instead of crashing the whole chain. - let gate: 'run' | 'skip'; - try { - gate = evaluateEntryGate(entry, currentPayload, i, gateOptions); - } catch (error) { - if (options.throwOnHandlerError) { - throw error; - } - console.warn( - `[HooksManager] Matcher/filter for handler ${i} of hook "${options.hookName}" threw; failing closed:`, - error, - ); + const outcome = await runEntry(entry, currentPayload, context, i, options, failsClosed); + if (outcome.kind === 'failed') { blocked = true; - blockReason = `Blocked: ${options.hookName} hook matcher/filter for handler ${i} threw`; + blockReason = outcome.reason; break; } - if (gate === 'skip') { + if (outcome.kind === 'async') { + // Fire-and-forget: track the (optional) work promise for drain/timeout. + if (outcome.trackedWork !== undefined) { + pending.push(outcome.trackedWork); + } + continue; + } + if (outcome.kind === 'skip') { + // Matcher/filter rejected the entry, void return, or a failure of a + // non-blocking hook in non-strict mode. continue; } - try { - const returnValue = await entry.handler(currentPayload, context); - const outcome = classifyHandlerReturn(returnValue, i, gateOptions); - - if (outcome.kind === 'async') { - // Fire-and-forget: track the (optional) work promise for drain/timeout. - if (outcome.trackedWork !== undefined) { - pending.push(outcome.trackedWork); - } - continue; - } - if (outcome.kind === 'skip') { - // Void return, or result-schema validation failed in non-strict mode. - continue; - } - - const result = outcome.result; - results.push(result); + const result = outcome.result; + results.push(result); - // Apply mutation piping -- only hooks with declared mutations participate. - if (behavior?.mutations) { - const applied = applyMutations(currentPayload, result, behavior.mutations); - if (applied !== currentPayload) { - currentPayload = applied; - mutated = true; - } - } + // Apply mutation piping -- only hooks with declared mutations participate. + const applied = applyMutations(currentPayload, result, behavior?.mutations); + if (applied !== currentPayload) { + currentPayload = applied; + mutated = true; + } - // Short-circuit on the hook's declared block field. - if (behavior?.blockField && isBlockTriggered(result, behavior.blockField)) { - blocked = true; - break; - } - } catch (error) { - if (options.throwOnHandlerError) { - throw error; - } - if (failsClosed) { - console.warn( - `[HooksManager] Handler ${i} for hook "${options.hookName}" failed; failing closed:`, - error, - ); - blocked = true; - blockReason = `Blocked: ${options.hookName} hook handler ${i} failed`; - break; - } - console.warn(`[HooksManager] Handler ${i} for hook "${options.hookName}" threw:`, error); + // Short-circuit on the hook's declared block field. + if (behavior?.blockField && isBlockTriggered(result, behavior.blockField)) { + blocked = true; + break; } } @@ -232,14 +188,16 @@ export async function executeHandlerChain( * Matchers fail closed: if a matcher is registered and no toolName is * available for this emit, the handler is skipped rather than invoked * globally. A throwing matcher function or filter is re-thrown in strict - * mode, or logged and treated as a skip otherwise. + * mode; otherwise it is logged and treated as a skip, or as `fail` for a + * blocking hook so the chain fails closed. */ function evaluateEntryGate( entry: HookEntry, payload: P, index: number, options: ExecuteChainOptions, -): 'run' | 'skip' { + failsClosed: boolean, +): 'run' | 'skip' | 'fail' { try { // Matcher first; the filter must not run when the matcher already // rejected the entry (filters can be effectful or expensive). @@ -255,10 +213,86 @@ function evaluateEntryGate( throw error; } console.warn( - `[HooksManager] Matcher/filter for handler ${index} of hook "${options.hookName}" threw:`, + `[HooksManager] Matcher/filter for handler ${index} of hook "${options.hookName}" threw${failsClosed ? '; failing closed' : ''}:`, error, ); - return 'skip'; + return failsClosed ? 'fail' : 'skip'; + } +} + +type EntryOutcome = + | HandlerReturnOutcome + | { + kind: 'failed'; + reason: string; + }; + +/** + * Evaluate an entry's matcher/filter and, when it passes, run its handler. + * Matcher and filter checks run under the same error policy as handlers: + * in non-strict mode a throwing user-supplied matcher function or filter is + * logged and the entry skipped (or, for blocking hooks, reported as `failed` + * so the chain fails closed), instead of crashing the whole chain. + */ +async function runEntry( + entry: HookEntry, + payload: P, + context: LifecycleHookContext, + index: number, + options: ExecuteChainOptions, + failsClosed: boolean, +): Promise> { + const gate = evaluateEntryGate(entry, payload, index, options, failsClosed); + if (gate === 'skip') { + return { + kind: 'skip', + }; + } + if (gate === 'fail') { + return { + kind: 'failed', + reason: `Blocked: ${options.hookName} hook matcher/filter for handler ${index} threw`, + }; + } + return runHandler(entry, payload, context, index, options, failsClosed); +} + +/** + * Run one handler and classify its return value under the chain's error + * policy. A throw or an invalid result is re-thrown in strict mode; otherwise + * it is logged and reported as `failed` for blocking hooks (so the chain + * fails closed) or `skip` for every other hook. + */ +async function runHandler( + entry: HookEntry, + payload: P, + context: LifecycleHookContext, + index: number, + options: ExecuteChainOptions, + failsClosed: boolean, +): Promise> { + try { + const returnValue = await entry.handler(payload, context); + return classifyHandlerReturn(returnValue, index, { + ...options, + throwOnHandlerError: options.throwOnHandlerError || failsClosed, + }); + } catch (error) { + if (options.throwOnHandlerError) { + throw error; + } + console.warn( + `[HooksManager] Handler ${index} for hook "${options.hookName}" failed${failsClosed ? '; failing closed' : ''}:`, + error, + ); + return failsClosed + ? { + kind: 'failed', + reason: `Blocked: ${options.hookName} hook handler ${index} failed`, + } + : { + kind: 'skip', + }; } } @@ -410,8 +444,12 @@ function isUnrefable(handle: unknown): handle is { /** * Apply mutation fields from a result onto the current payload. */ -function applyMutations(payload: P, result: R, mutationMap: Record): P { - if (typeof result !== 'object' || result === null) { +function applyMutations( + payload: P, + result: R, + mutationMap: Record | undefined, +): P { + if (mutationMap === undefined || typeof result !== 'object' || result === null) { return payload; }