Browse Source

Merge pull request #682 from mhenke/feat/hook-registry-session-lifecycle

refactor(hooks): simplify hook dispatch, fix session ID bug, centralize cleanup
Alvin 1 month ago
parent
commit
db992db08e

+ 801 - 0
docs/superpowers/plans/2026-07-06-hook-registry-session-lifecycle.md

@@ -0,0 +1,801 @@
+# HookRegistry + SessionLifecycle Implementation Plan
+
+> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
+
+**Goal:** Eliminate manual hook wiring, scattered session.deleted cleanup, and the reversed-priority session ID bug.
+
+**Architecture:** Three-phase build: (1) `extractSessionId` utility replacing 8 duplicated sites, (2) `SessionLifecycle` coordinator owning cleanup callbacks + signaling channel with timestamp TTL, (3) `HookRegistry` for all async hook dispatch.
+
+**Tech Stack:** TypeScript, Bun, Biome
+
+## Global Constraints
+
+- Line width: 80 chars, 2-space indent, trailing commas
+- No explicit `any` (linter warning)
+- Biome organizes imports, run `bun run check:ci` before commit
+- Commit after every green test run, wait for user "proceed" at each task boundary
+
+---
+## File Structure
+
+### New files
+| File | Responsibility |
+|------|---------------|
+| `src/utils/extract-session-id.ts` | `extractSessionId(info, sessionID)` — priority `info?.id ?? sessionID` |
+| `src/utils/extract-session-id.test.ts` | Tests for priority, null/undefined, edge cases |
+| `src/hooks/session-lifecycle.ts` | `SessionLifecycle` class — cleanup callback registry + signaling channel with timestamp TTL |
+| `src/hooks/session-lifecycle.test.ts` | Tests for cleanup registration/dispatch, signaling, TTL expiry |
+| `src/hooks/hook-registry.ts` | `HookRegistry` class — ordered dispatcher with late-registration warning |
+| `src/hooks/hook-registry.test.ts` | Tests for registration order, late-registration, no-op dispatch |
+
+### Modified files
+| File | Changes |
+|------|---------|
+| `src/index.ts` | Delete `let` hook declarations, use `const` inside try, register with HookRegistry, replace manual dispatch with `registry.dispatch()`, wire SessionLifecycle for session.deleted |
+| `src/hooks/post-file-tool-nudge/index.ts` | Accept `SessionLifecycle`, delegate Sets to coordinator, use `extractSessionId`, remove `event()` method, remove `hasPendingSession` export |
+| `src/hooks/phase-reminder/index.ts` | Accept `SessionLifecycle` param, import `hasPendingSession` from `session-lifecycle` |
+| `src/hooks/task-session-manager/index.ts` | Use `extractSessionId`, register cleanup callback with coordinator |
+| `src/hooks/foreground-fallback/index.ts` | Accept `SessionLifecycle`, register cleanup callback, use `extractSessionId` |
+| `src/hooks/post-file-tool-nudge/index.test.ts` | Pass coordinator to factory |
+| `src/hooks/phase-reminder/index.test.ts` | Pass coordinator to factory, update `hasPendingSession` import |
+| `src/hooks/task-session-manager/index.test.ts` | Verify cleanup through coordinator |
+| `src/multiplexer/session-manager.ts` | Use `extractSessionId` (line 610) |
+
+---
+### Task 0: Baseline test run
+
+- [ ] **Step 1: Run baseline tests**
+
+Run: `bun test`
+Expected: 1367 pass, 0 fail
+
+- [ ] **Step 2: Record output reference**
+
+---
+### Task 1: `src/utils/extract-session-id.ts`
+
+**Files:**
+- Create: `src/utils/extract-session-id.ts`
+- Create: `src/utils/extract-session-id.test.ts`
+- Modify: `src/index.ts` (lines 889, 897)
+- Modify: `src/multiplexer/session-manager.ts` (line 610)
+- Modify: `src/hooks/task-session-manager/index.ts` (lines 582, 635, 659, 693)
+- Modify: `src/hooks/foreground-fallback/index.ts` (line 236)
+- Modify: `src/hooks/post-file-tool-nudge/index.ts` (line 77 — reversed priority)
+
+**Interfaces:**
+- Produces: `export function extractSessionId(info: { id?: string } | undefined | null, sessionID: string | undefined | null): string | undefined`
+
+- [ ] **Step 1: Create the utility**
+
+```typescript
+export function extractSessionId(
+  info: { id?: string } | undefined | null,
+  sessionID: string | undefined | null,
+): string | undefined {
+  return info?.id ?? sessionID;
+}
+```
+
+- [ ] **Step 2: Create tests**
+
+```typescript
+import { describe, expect, test } from 'bun:test';
+import { extractSessionId } from './extract-session-id';
+
+describe('extractSessionId', () => {
+  test('prefers info.id over sessionID', () => {
+    expect(extractSessionId({ id: 'i' }, 's')).toBe('i');
+  });
+
+  test('falls back to sessionID when info.id missing', () => {
+    expect(extractSessionId({}, 's')).toBe('s');
+    expect(extractSessionId({ id: undefined }, 's')).toBe('s');
+  });
+
+  test('returns undefined when both missing', () => {
+    expect(extractSessionId(undefined, undefined)).toBeUndefined();
+    expect(extractSessionId(null, null)).toBeUndefined();
+    expect(extractSessionId({}, undefined)).toBeUndefined();
+  });
+
+  test('handles null info', () => {
+    expect(extractSessionId(null, 's')).toBe('s');
+  });
+});
+```
+
+- [ ] **Step 3: Run test to verify it fails**
+
+Run: `bun test src/utils/extract-session-id.test.ts`
+Expected: FAIL (module not found)
+
+- [ ] **Step 4: Replace all 8 manual extraction sites**
+
+Each `props?.info?.id ?? props?.sessionID` → `extractSessionId(props?.info, props?.sessionID)`.
+
+Fix the reversed-priority site at `src/hooks/post-file-tool-nudge/index.ts:77`:
+```typescript
+input.event.properties?.sessionID ?? input.event.properties?.info?.id
+```
+→
+```typescript
+extractSessionId(
+  input.event.properties?.info,
+  input.event.properties?.sessionID,
+)
+```
+
+Deduplicate the two adjacent `session.deleted` blocks in `src/index.ts:885-905` into one block using `extractSessionId`.
+
+- [ ] **Step 5: Run all tests**
+
+Run: `bun test`
+Expected: Same count as baseline, all pass
+
+- [ ] **Step 6: Commit**
+
+```bash
+git add src/utils/extract-session-id.ts src/utils/extract-session-id.test.ts src/index.ts src/multiplexer/session-manager.ts src/hooks/task-session-manager/index.ts src/hooks/foreground-fallback/index.ts src/hooks/post-file-tool-nudge/index.ts
+bun run check:ci
+git commit -m "feat: add extractSessionId utility, fix reversed-priority session ID bug"
+```
+
+---
+### Task 2: SessionLifecycle coordinator class + tests
+
+**Files:**
+- Create: `src/hooks/session-lifecycle.ts`
+- Create: `src/hooks/session-lifecycle.test.ts`
+
+**Interfaces:**
+- Produces:
+```typescript
+export class SessionLifecycle {
+  static readonly PENDING_TTL_MS: number;
+  constructor(log: (msg: string, meta?: Record<string, unknown>) => void);
+  onSessionDeleted(callback: (sessionId: string) => void): void;
+  dispatchSessionDeleted(sessionId: string): void;
+  markPending(sessionId: string): void;
+  /** Returns true only once per markPending call. */
+  consumePending(sessionId: string): boolean;
+  hasPendingSession(sessionId: string): boolean;
+  clearSession(sessionId: string): void;
+}
+```
+
+- [ ] **Step 1: Create the class**
+
+```typescript
+// src/hooks/session-lifecycle.ts
+export class SessionLifecycle {
+  static readonly PENDING_TTL_MS = 5 * 60 * 1000;
+
+  #cleanupCallbacks: Array<(sessionId: string) => void> = [];
+  #pendingSessionIds = new Set<string>();
+  #everPendingSessionIds = new Set<string>();
+  #pendingTimestamps = new Map<string, number>();
+  #log: (msg: string, meta?: Record<string, unknown>) => void;
+
+  constructor(
+    log: (msg: string, meta?: Record<string, unknown>) => void,
+  ) {
+    this.#log = log;
+  }
+
+  onSessionDeleted(callback: (sessionId: string) => void): void {
+    this.#cleanupCallbacks.push(callback);
+  }
+
+  dispatchSessionDeleted(sessionId: string): void {
+    for (const cb of this.#cleanupCallbacks) {
+      try {
+        cb(sessionId);
+      } catch (error) {
+        this.#log(
+          `[session-lifecycle] cleanup callback failed for session ${sessionId}`,
+          { error },
+        );
+      }
+    }
+  }
+
+  markPending(sessionId: string): void {
+    this.#pendingSessionIds.add(sessionId);
+    this.#everPendingSessionIds.add(sessionId);
+    this.#pendingTimestamps.set(sessionId, Date.now());
+  }
+
+  /** Atomic — only one caller gets true per markPending call. */
+  consumePending(sessionId: string): boolean {
+    const had = this.#pendingSessionIds.has(sessionId);
+    this.#pendingSessionIds.delete(sessionId);
+    this.#pendingTimestamps.delete(sessionId);
+    return had;
+  }
+
+  hasPendingSession(sessionId: string): boolean {
+    const ts = this.#pendingTimestamps.get(sessionId);
+    if (ts && Date.now() - ts > SessionLifecycle.PENDING_TTL_MS) {
+      this.#pendingTimestamps.delete(sessionId);
+      this.#pendingSessionIds.delete(sessionId);
+      return false;
+    }
+    return (
+      this.#everPendingSessionIds.has(sessionId)
+      && !this.#pendingSessionIds.has(sessionId)
+    );
+  }
+
+  clearSession(sessionId: string): void {
+    this.#pendingSessionIds.delete(sessionId);
+    this.#everPendingSessionIds.delete(sessionId);
+    this.#pendingTimestamps.delete(sessionId);
+  }
+}
+```
+
+- [ ] **Step 2: Create tests**
+
+```typescript
+import { describe, expect, test } from 'bun:test';
+import { SessionLifecycle } from './session-lifecycle';
+
+const noop = () => {};
+
+describe('SessionLifecycle', () => {
+  test('dispatchSessionDeleted runs callbacks in order', () => {
+    const lc = new SessionLifecycle(noop);
+    const ran: string[] = [];
+    lc.onSessionDeleted((id) => ran.push(`a:${id}`));
+    lc.onSessionDeleted((id) => ran.push(`b:${id}`));
+    lc.dispatchSessionDeleted('s1');
+    expect(ran).toEqual(['a:s1', 'b:s1']);
+  });
+
+  test('dispatchSessionDeleted continues after callback error', () => {
+    const lc = new SessionLifecycle(() => {});
+    const ran: string[] = [];
+    lc.onSessionDeleted(() => { throw new Error('fail'); });
+    lc.onSessionDeleted((id) => ran.push(id));
+    lc.dispatchSessionDeleted('s1');
+    expect(ran).toEqual(['s1']);
+  });
+
+  test('consumePending is atomic', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    expect(lc.consumePending('s1')).toBe(true);
+    expect(lc.consumePending('s1')).toBe(false);
+  });
+
+  test('hasPendingSession after consume', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    lc.consumePending('s1');
+    expect(lc.hasPendingSession('s1')).toBe(true);
+  });
+
+  test('hasPendingSession false for unknown session', () => {
+    const lc = new SessionLifecycle(noop);
+    expect(lc.hasPendingSession('s1')).toBe(false);
+  });
+
+  test('clearSession removes all state', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    lc.consumePending('s1');
+    lc.clearSession('s1');
+    expect(lc.hasPendingSession('s1')).toBe(false);
+  });
+});
+```
+
+- [ ] **Step 3: Run tests**
+
+Run: `bun test src/hooks/session-lifecycle.test.ts`
+Expected: PASS
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add src/hooks/session-lifecycle.ts src/hooks/session-lifecycle.test.ts
+bun run check:ci
+git commit -m "feat: add SessionLifecycle coordinator"
+```
+
+---
+### Task 3: Update hooks to use SessionLifecycle + extractSessionId
+
+**Files:**
+- Modify: `src/hooks/post-file-tool-nudge/index.ts`
+- Modify: `src/hooks/post-file-tool-nudge/index.test.ts`
+- Modify: `src/hooks/phase-reminder/index.ts`
+- Modify: `src/hooks/phase-reminder/index.test.ts`
+- Modify: `src/hooks/task-session-manager/index.ts`
+- Modify: `src/hooks/task-session-manager/index.test.ts`
+- Modify: `src/hooks/foreground-fallback/index.ts`
+
+**Interfaces:**
+- Consumes: `SessionLifecycle` from `../session-lifecycle`, `extractSessionId` from `../../utils/extract-session-id`
+
+- [ ] **Step 1: Update post-file-tool-nudge/index.ts**
+
+Remove module-scoped Sets, `hasPendingSession` export, and `event()` method (only handled session.deleted). Accept `coordinator?: SessionLifecycle` in factory options. Cleanup is handled via coordinator callback. Use `coordinator.markPending()` and `coordinator.consumePending()` instead of module-scoped Sets.
+
+```typescript
+import { PHASE_REMINDER } from '../../config/constants';
+import type { SessionLifecycle } from '../session-lifecycle';
+
+const FILE_TOOLS = new Set(['Read', 'read', 'Write', 'write']);
+
+interface PostFileToolNudgeOptions {
+  shouldInject?: (sessionID: string) => boolean;
+  coordinator?: SessionLifecycle;
+}
+
+export function createPostFileToolNudgeHook(
+  options: PostFileToolNudgeOptions = {},
+) {
+  const { coordinator } = options;
+
+  if (coordinator) {
+    coordinator.onSessionDeleted(
+      (sid) => coordinator.clearSession(sid),
+    );
+  }
+
+  return {
+    'tool.execute.after': async (
+      input: { tool: string; sessionID?: string; callID?: string },
+    ): Promise<void> => {
+      if (!FILE_TOOLS.has(input.tool) || !input.sessionID) return;
+      coordinator?.markPending(input.sessionID);
+    },
+    'experimental.chat.system.transform': async (
+      input: { sessionID?: string },
+      output: { system: string[] },
+    ): Promise<void> => {
+      if (!input.sessionID || !coordinator?.consumePending(input.sessionID)) {
+        return;
+      }
+      if (options.shouldInject && !options.shouldInject(input.sessionID)) {
+        return;
+      }
+      output.system.push(PHASE_REMINDER);
+    },
+  };
+}
+```
+
+Note `_output` param removed from `tool.execute.after` since it was unused (was `_output: unknown`).
+
+- [ ] **Step 2: Update phase-reminder/index.ts**
+
+Accept `coordinator?: SessionLifecycle` parameter. Import `hasPendingSession` from the coordinator instead of `../post-file-tool-nudge`. Remove the `import { hasPendingSession }` line.
+
+```typescript
+import type { SessionLifecycle } from '../session-lifecycle';
+
+export function createPhaseReminderHook(
+  coordinator?: SessionLifecycle,
+) {
+  return {
+    'experimental.chat.messages.transform': async (
+      _input: Record<string, never>,
+      output: { messages?: unknown },
+    ): Promise<void> => {
+      // ... existing logic ...
+      if (sessionId && coordinator?.hasPendingSession(sessionId)) {
+        return;
+      }
+      // ... rest unchanged ...
+    },
+  };
+}
+```
+
+- [ ] **Step 3: Update task-session-manager/index.ts**
+
+All 4 `info?.id ?? sessionID` sites are already replaced with `extractSessionId` (Task 1). The `session.deleted` case in `.event()` (lines 691-721) is replaced by registering a cleanup callback with the coordinator. Add `coordinator?: SessionLifecycle` to factory options.
+
+```typescript
+interface TaskSessionManagerOptions {
+  // ... existing options ...
+  coordinator?: SessionLifecycle;
+}
+```
+
+Register cleanup in the factory:
+```typescript
+if (options.coordinator) {
+  options.coordinator.onSessionDeleted((sessionId) => {
+    backgroundJobBoard.drop(sessionId);
+    backgroundJobBoard.clearParent(sessionId);
+    terminalJobsInjectedByParent.delete(sessionId);
+    taskContextTracker.clearSession(sessionId);
+    taskContextTracker.prune(backgroundJobBoard);
+    pendingCallTracker.clearSession(sessionId);
+  });
+}
+```
+
+The `session.deleted` case in `.event()` is reduced to just logging (no cleanup ops):
+```typescript
+if (input.event.type !== 'session.deleted') return;
+const sessionId = extractSessionId(
+  input.event.properties?.info,
+  input.event.properties?.sessionID,
+);
+if (!sessionId) return;
+log('[task-session-manager] session.deleted observed', { sessionID: sessionId });
+return;
+```
+
+- [ ] **Step 4: Update foreground-fallback/index.ts**
+
+Accept `coordinator?: SessionLifecycle` in the constructor. Register cleanup callbacks. Use `extractSessionId` (already done in Task 1).
+
+```typescript
+constructor(
+  // ... existing params ...
+  private coordinator?: SessionLifecycle,
+) {
+  if (coordinator) {
+    coordinator.onSessionDeleted((id) => {
+      this.sessionModel.delete(id);
+      this.sessionAgent.delete(id);
+      this.sessionTried.delete(id);
+      this.inProgress.delete(id);
+      this.lastTrigger.delete(id);
+      this.lastTriggerModel.delete(id);
+      this.sessionRetries.delete(id);
+    });
+  }
+  // ... rest of constructor ...
+}
+```
+
+The `session.deleted` case in `handleEvent` (lines 226-247) is reduced to logging:
+```typescript
+case 'session.deleted': {
+  const props = event.properties as
+    | { sessionID?: string; info?: { id?: string } }
+    | undefined;
+  const id = extractSessionId(props?.info, props?.sessionID);
+  if (id) {
+    log('[foreground-fallback] session.deleted observed', { sessionID: id });
+  }
+  break;
+}
+```
+
+- [ ] **Step 5: Update post-file-tool-nudge tests**
+
+Each test that creates hooks with `createPostFileToolNudgeHook()` now needs a shared coordinator:
+
+```typescript
+import { SessionLifecycle } from '../session-lifecycle';
+
+test('records pending session on Read tool', async () => {
+  const coordinator = new SessionLifecycle(() => {});
+  const hook = createPostFileToolNudgeHook({ coordinator });
+  // ... rest same ...
+});
+```
+
+The "composed" test (line 153) needs a coordinator shared between both hooks:
+
+```typescript
+test('composed: phase-reminder skips when post-file-tool-nudge handles system', async () => {
+  const coordinator = new SessionLifecycle(() => {});
+  const nudgeHook = createPostFileToolNudgeHook({ coordinator });
+  const phaseHook = createPhaseReminderHook(coordinator);
+  // ... rest same ...
+});
+```
+
+- [ ] **Step 6: Update phase-reminder tests**
+
+Tests that call `createPhaseReminderHook()` now pass the coordinator:
+```typescript
+const coordinator = new SessionLifecycle(() => {});
+const phaseHook = createPhaseReminderHook(coordinator);
+```
+
+Import changes: `hasPendingSession` no longer needs to be imported from `../post-file-tool-nudge` — it's on the coordinator instance.
+
+- [ ] **Step 7: Update task-session-manager tests**
+
+If any test verifies cleanup via `.event()` with `session.deleted`, it now needs to verify cleanup through the coordinator callback instead. The `event()` method no longer performs cleanup ops.
+
+- [ ] **Step 8: Run all tests**
+
+Run: `bun test`
+Expected: All pass
+
+- [ ] **Step 9: Commit**
+
+```bash
+git add src/hooks/post-file-tool-nudge/ src/hooks/phase-reminder/ src/hooks/task-session-manager/ src/hooks/foreground-fallback/
+bun run check:ci
+git commit -m "refactor: migrate hooks to SessionLifecycle coordinator"
+```
+
+---
+### Task 4: Wire SessionLifecycle into src/index.ts
+
+**Files:**
+- Modify: `src/index.ts`
+
+- [ ] **Step 1: Instantiate SessionLifecycle before hook factories**
+
+Inside the `try` block, before any hook factory calls:
+```typescript
+const sessionLifecycle = new SessionLifecycle(log);
+```
+
+- [ ] **Step 2: Pass coordinator to hook factories**
+
+`postFileToolNudgeHook = createPostFileToolNudgeHook({
+  shouldInject: (sessionID) => sessionAgentMap.get(sessionID) === 'orchestrator',
+  coordinator: sessionLifecycle,
+});`
+
+`taskSessionManagerHook = createTaskSessionManagerHook(ctx, { /* ...existing... */, coordinator: sessionLifecycle });`
+
+`phaseReminderHook = createPhaseReminderHook(sessionLifecycle);`
+
+`ForegroundFallbackManager` constructor: add `sessionLifecycle` as a parameter.
+
+- [ ] **Step 3: Add session.deleted dispatch via coordinator**
+
+In the `event` handler, add a dispatch block for `session.deleted`:
+```typescript
+if (input.event.type === 'session.deleted') {
+  const props = input.event.properties as ...;
+  const sessionID = extractSessionId(props?.info, props?.sessionID);
+  if (sessionID) {
+    sessionLifecycle.dispatchSessionDeleted(sessionID);
+  }
+}
+```
+
+- [ ] **Step 4: Run tests**
+
+Run: `bun test`
+Expected: All pass
+
+- [ ] **Step 5: Commit**
+
+```bash
+git add src/index.ts
+bun run check:ci
+git commit -m "feat: wire SessionLifecycle coordinator into plugin"
+```
+
+---
+### Task 5: HookRegistry class + tests
+
+**Files:**
+- Create: `src/hooks/hook-registry.ts`
+- Create: `src/hooks/hook-registry.test.ts`
+
+**Interfaces:**
+- Produces:
+```typescript
+export class HookRegistry {
+  register(hookPoint: string, handler: (i: unknown, o: unknown) => Promise<void>): void;
+  dispatch(hookPoint: string, input: unknown, output: unknown): Promise<void>;
+  handlers(hookPoint: string): ReadonlyArray<(i: unknown, o: unknown) => Promise<void>>;
+}
+```
+
+- [ ] **Step 1: Create the class**
+
+```typescript
+export class HookRegistry {
+  #handlers = new Map<
+    string,
+    Array<(input: unknown, output: unknown) => Promise<void>>
+  >();
+  #firedHookPoints = new Set<string>();
+
+  register(
+    hookPoint: string,
+    handler: (input: unknown, output: unknown) => Promise<void>,
+  ): void {
+    if (this.#firedHookPoints.has(hookPoint)) {
+      console.warn(
+        `[hook-registry] "${hookPoint}" already dispatched; late registration may miss events`,
+      );
+    }
+    const group = this.#handlers.get(hookPoint);
+    if (group) {
+      group.push(handler);
+    } else {
+      this.#handlers.set(hookPoint, [handler]);
+    }
+  }
+
+  async dispatch(
+    hookPoint: string,
+    input: unknown,
+    output: unknown,
+  ): Promise<void> {
+    this.#firedHookPoints.add(hookPoint);
+    const group = this.#handlers.get(hookPoint);
+    if (!group) return;
+    for (const handler of group) {
+      await handler(input, output);
+    }
+  }
+
+  handlers(
+    hookPoint: string,
+  ): ReadonlyArray<(input: unknown, output: unknown) => Promise<void>> {
+    return this.#handlers.get(hookPoint) ?? [];
+  }
+}
+```
+
+- [ ] **Step 2: Create tests**
+
+```typescript
+import { describe, expect, test } from 'bun:test';
+import { HookRegistry } from './hook-registry';
+
+describe('HookRegistry', () => {
+  test('dispatch runs handlers in registration order', async () => {
+    const r = new HookRegistry();
+    const order: number[] = [];
+    r.register('test', async () => { order.push(1); });
+    r.register('test', async () => { order.push(2); });
+    await r.dispatch('test', {}, {});
+    expect(order).toEqual([1, 2]);
+  });
+
+  test('unregistered hook point is no-op', async () => {
+    const r = new HookRegistry();
+    await r.dispatch('none', {}, {});
+  });
+
+  test('handlers returns empty for unregistered point', () => {
+    const r = new HookRegistry();
+    expect(r.handlers('x')).toEqual([]);
+  });
+
+  test('dispatch passes input and output to handlers', async () => {
+    const r = new HookRegistry();
+    const captured: unknown[] = [];
+    r.register('test', async (i, o) => { captured.push(i, o); });
+    await r.dispatch('test', { a: 1 }, { b: 2 });
+    expect(captured).toEqual([{ a: 1 }, { b: 2 }]);
+  });
+});
+```
+
+- [ ] **Step 3: Run tests**
+
+Run: `bun test src/hooks/hook-registry.test.ts`
+Expected: PASS
+
+- [ ] **Step 4: Commit**
+
+```bash
+git add src/hooks/hook-registry.ts src/hooks/hook-registry.test.ts
+bun run check:ci
+git commit -m "feat: add HookRegistry for ordered handler dispatch"
+```
+
+---
+### Task 6: Wire HookRegistry into src/index.ts (biggest task)
+
+**Files:**
+- Modify: `src/index.ts`
+
+Goal: Replace manual `let` declarations + per-hook dispatch with `registry.dispatch()` calls.
+
+- [ ] **Step 1: Understand the current pattern**
+
+Currently the plugin function has:
+1. ~15 `let xHook: ReturnType<...>` declarations outside try (lines 138-153)
+2. Factory calls inside try (lines 271-322) that assign to those variables
+3. 5 dispatch blocks in the return object (lines 910-1186) that call hook methods individually
+
+- [ ] **Step 2: Convert pattern**
+
+Replace:
+```typescript
+let phaseReminderHook: ReturnType<typeof createPhaseReminderHook>;
+// ... in try block ...
+phaseReminderHook = createPhaseReminderHook(sessionLifecycle);
+// ... in return block ...
+await phaseReminderHook['experimental.chat.messages.transform'](input, typedOutput);
+```
+
+With:
+```typescript
+// In try block:
+const phaseReminder = createPhaseReminderHook(sessionLifecycle);
+hookRegistry.register(
+  'experimental.chat.messages.transform',
+  (i, o) => phaseReminder['experimental.chat.messages.transform'](i, o as any),
+);
+// ... repeat for other hooks ...
+```
+
+Note: The `hookRegistry` is instantiated inside the try block. The return block only needs closure on `hookRegistry`, not on individual hook instances.
+
+- [ ] **Step 3: Map each hook point to its dispatches**
+
+| Hook point | Hooks that implement it |
+|---|---|
+| `experimental.chat.messages.transform` | taskSessionManager, phaseReminder, filterAvailableSkills |
+| `experimental.chat.system.transform` | postFileToolNudge |
+| `tool.execute.before` | applyPatch, taskSessionManager |
+| `tool.execute.after` | delegateTaskRetry, jsonErrorRecovery, postFileToolNudge, taskSessionManager |
+| `command.execute.before` | deepworkCommand, reflectCommand, loopCommand |
+| `event` | foregroundFallback, taskSessionManager (session.idle/status/error only — no longer session.deleted) |
+| `chat.headers` | chatHeaders (sync, stays manual) |
+
+- [ ] **Step 4: Replace each dispatch block in the return object**
+
+Each becomes:
+```typescript
+'experimental.chat.messages.transform':
+  (input, output) => hookRegistry.dispatch('experimental.chat.messages.transform', input, output),
+```
+
+Note: `event` handler is special — it still dispatches to non-hook consumers (multiplexer, companion, autoUpdateChecker, interview). Only the hook portions go through the registry.
+
+- [ ] **Step 5: Delete unused `let` declarations**
+
+Remove the hook variable `let` declarations from the outer scope (lines 138-153). Keep non-hook `let` declarations (managers, boards, tools).
+
+- [ ] **Step 6: Delete unused imports**
+
+Remove any `ReturnType<typeof createXHook>` from imports that are no longer used as types.
+
+- [ ] **Step 7: Run tests**
+
+Run: `bun test`
+Expected: All 1367+ pass
+
+- [ ] **Step 8: Commit**
+
+```bash
+git add src/index.ts
+bun run check:ci
+git commit -m "refactor: wire HookRegistry, delete manual hook dispatching"
+```
+
+---
+### Task 7: Final verification
+
+- [ ] **Step 1: Run full test suite**
+
+Run: `bun test`
+Expected: All pass, same count as baseline
+
+- [ ] **Step 2: Run typecheck**
+
+Run: `bun run typecheck`
+Expected: No errors
+
+- [ ] **Step 3: Run linter**
+
+Run: `bun run check:ci`
+Expected: No errors
+
+- [ ] **Step 4: Update codemap if needed**
+
+Check if `src/hooks/codemap.md` needs updating to reflect the new registry + coordinator architecture.
+
+- [ ] **Step 5: Final commit**
+
+```bash
+git add -A
+bun run check:ci
+git commit -m "chore: final cleanup after HookRegistry+SessionLifecycle migration"
+```

+ 232 - 0
docs/superpowers/specs/2026-07-06-hook-registry-session-lifecycle-design.md

@@ -0,0 +1,232 @@
+# HookRegistry + SessionLifecycle Coordinator
+
+**Category:** enhancement
+**Author:** mhenke
+**Date:** 2026-07-06
+**Issue:** #675
+**Status:** approved
+
+## Problem
+
+Four verified problems in the hooks architecture of `oh-my-opencode-slim`:
+
+1. **Manual wiring friction.** Adding a new hook requires touching 6-10 locations: export from `src/hooks/index.ts`, import in `src/index.ts`, variable declaration, factory call, and a dispatch call for each hook point. Verified at `src/index.ts:6-34` (imports), `138-153` (declarations), `271-322` (factory calls), `820-1186` (dispatch sites). 13 hooks currently exist; this friction scales linearly.
+
+2. **Scattered session.deleted cleanup.** Three hooks each implement their own cleanup:
+   - `task-session-manager`: 6 ops at `src/hooks/task-session-manager/index.ts:715-720`
+   - `foreground-fallback`: 7 ops at `src/hooks/foreground-fallback/index.ts:238-244`
+   - `post-file-tool-nudge`: 2 ops at `src/hooks/post-file-tool-nudge/index.ts:79-80`
+   A new stateful hook that forgets `session.deleted` leaks memory silently.
+
+3. **Reversed-priority session ID bug.** `info?.id ?? sessionID` is duplicated 8 times across 4 files. One location (`src/hooks/post-file-tool-nudge/index.ts:77`) uses the reversed priority `sessionID ?? info?.id`. During session transitions when both fields differ, this picks the wrong session ID, causing missed cleanup or stale pending state.
+
+4. **Module-scoped Sets with no TTL.** `post-file-tool-nudge` owns `pendingSessionIds` and `everPendingSessionIds` at module scope. `phase-reminder` imports `hasPendingSession` from `post-file-tool-nudge` (`src/hooks/phase-reminder/index.ts:10`). Consumption is a side effect of `.delete()`. If the handler throws or is skipped, the session stays pending forever.
+
+## Solution
+
+Three modules:
+
+### 1. `src/utils/extract-session-id.ts`
+
+Single function that replaces all 8 manual extractions:
+
+```typescript
+export function extractSessionId(
+  info: { id?: string } | undefined | null,
+  sessionID: string | undefined | null,
+): string | undefined {
+  return info?.id ?? sessionID;
+}
+```
+
+- Priority: `info?.id` wins over `sessionID` (matches the 7 correct locations).
+- Located in `src/utils/` because `src/multiplexer/session-manager.ts:610` also uses it.
+- Fixes the reversed-priority bug at `post-file-tool-nudge/index.ts:77`.
+- Also deduplicates the two adjacent `session.deleted` blocks in `src/index.ts:885-905`.
+
+### 2. `src/hooks/session-lifecycle.ts` — SessionLifecycle coordinator
+
+Two responsibilities:
+
+**Cleanup callback registry.** Stateful hooks register a callback instead of implementing their own `session.deleted` handler. The coordinator runs all registered callbacks when `dispatchSessionDeleted(sessionId)` is called. If a callback throws, the error is logged and the remaining callbacks still run — one failure does not block others.
+
+```typescript
+class SessionLifecycle {
+  #cleanupCallbacks: Array<(sessionId: string) => void> = [];
+  #pendingSessionIds = new Set<string>();
+  #everPendingSessionIds = new Set<string>();
+  #pendingTimestamps = new Map<string, number>();
+
+  static readonly PENDING_TTL_MS = 5 * 60 * 1000;
+
+  // -- Cleanup API --
+  onSessionDeleted(callback: (sessionId: string) => void): void;
+  dispatchSessionDeleted(sessionId: string): void;
+
+  // -- Signaling API --
+  /** Mark sessionId as having pending file-tool state. */
+  markPending(sessionId: string): void;
+  /**
+   * Atomically consume pending state for sessionId.
+   * Returns true if this call consumed the pending state,
+   * false if it was already consumed or never pending.
+   * Only one caller will get true per markPending call.
+   */
+  consumePending(sessionId: string): boolean;
+  /** True if sessionId had pending state that was consumed (checked with TTL). */
+  hasPendingSession(sessionId: string): boolean;
+  /** Remove all state for sessionId (called on session.deleted). */
+  clearSession(sessionId: string): void;
+}
+```
+
+**Pending-session signaling channel.** The module-scoped Sets from `post-file-tool-nudge` move here. TTL uses timestamp + lazy expiry on read (no `setTimeout`, no timer lifecycle bugs):
+
+```typescript
+hasPendingSession(sessionId: string): boolean {
+  const ts = this.#pendingTimestamps.get(sessionId);
+  if (ts && Date.now() - ts > SessionLifecycle.PENDING_TTL_MS) {
+    this.#pendingTimestamps.delete(sessionId);
+    this.#pendingSessionIds.delete(sessionId);
+    return false;
+  }
+  return this.#everPendingSessionIds.has(sessionId)
+    && !this.#pendingSessionIds.has(sessionId);
+}
+
+dispatchSessionDeleted(sessionId: string): void {
+  for (const callback of this.#cleanupCallbacks) {
+    try {
+      callback(sessionId);
+    } catch (error) {
+      log.error(`cleanup callback failed for session ${sessionId}`, error);
+    }
+  }
+}
+```
+
+Hooks that use it:
+- `task-session-manager`: registers 6 cleanup ops as one callback
+- `foreground-fallback`: registers 7 cleanup ops as one callback
+- `post-file-tool-nudge`: registers cleanup of pending state; imports `markPending`, `consumePending` from coordinator
+- `phase-reminder`: imports `hasPendingSession` from coordinator instead of `../post-file-tool-nudge` — and nothing else. No need for `markPending` or `consumePending`.
+
+The coordinator is instantiated in `src/index.ts` before hook factories that need it, passed as a parameter.
+
+### 3. `src/hooks/hook-registry.ts` — HookRegistry
+
+Simple ordered handler registry:
+
+```typescript
+class HookRegistry {
+  #handlers = new Map<string, Array<(input: unknown, output: unknown) => Promise<void>>>();
+  #firedHookPoints = new Set<string>();
+
+  register(
+    hookPoint: string,
+    handler: (input: unknown, output: unknown) => Promise<void>,
+  ): void {
+    if (this.#firedHookPoints.has(hookPoint)) {
+      log.warn(`hook "${hookPoint}" already dispatched; late registration may miss events`);
+    }
+    // ...
+  }
+
+  dispatch(hookPoint: string, input: unknown, output: unknown): Promise<void>;
+  getHandlers(hookPoint: string): ReadonlyArray<...>;
+}
+```
+
+Loose typing (`(input: unknown, output: unknown)`) is intentional — typed wrappers per hook point would add ceremony without proportional value for a codebase where call sites are already close to the cast. If typing becomes painful, add typed wrapper methods.
+
+- Registration order = dispatch order.
+- All async hook points dispatch through the registry.
+- `chat.headers` at `src/index.ts:980` stays manual (sync property, not async). A comment at the dispatch site explains why.
+- Non-hook event handling (multiplexer, companion, interview, preset, depthTracker) stays manual.
+
+Touch-point reduction for adding a new hook:
+- Export from `src/hooks/index.ts`: still required
+- Import in `src/index.ts`: still required
+- Variable declaration: **removed**
+- Factory call: still required
+- Registration: **added** (`registry.register(hookPoint, handler)`)
+- Dispatch-site wiring: **removed**
+
+Net: ~3 touch points eliminated. Dispatch code shrinks from ~121 lines to a few `registry.dispatch()` calls.
+
+## Changes by file
+
+### Phase 0: Baseline
+
+Run `bun test` and record the output. This ensures regressions in Phase 3 can be bisected.
+
+### Phase 1: `src/utils/extract-session-id.ts` (new)
+
+- Create file with `extractSessionId` function.
+- Tests in `src/utils/extract-session-id.test.ts`.
+
+### Phase 2: `src/hooks/session-lifecycle.ts` (new)
+
+- Create file with `SessionLifecycle` class.
+- Tests in `src/hooks/session-lifecycle.test.ts`.
+
+### Phase 2: Update hooks
+
+- `src/hooks/post-file-tool-nudge/index.ts`: delete module-scoped Sets, delete `hasPendingSession` export, delete reversed-priority `sessionID ?? info?.id`, use `extractSessionId`, add `coordinator: SessionLifecycle` param to factory, register cleanup callback.
+- `src/hooks/phase-reminder/index.ts`: import `hasPendingSession` from `session-lifecycle` instead of `../post-file-tool-nudge`.
+- `src/hooks/task-session-manager/index.ts`: replace 4 `info?.id ?? sessionID` with `extractSessionId`. Replace inline cleanup with coordinator callback registration.
+- `src/hooks/foreground-fallback/index.ts`: replace `info?.id ?? sessionID` with `extractSessionId`. Replace inline cleanup with coordinator callback registration.
+
+### Phase 3: `src/hooks/hook-registry.ts` (new)
+
+- Create file with `HookRegistry` class.
+- Tests in `src/hooks/hook-registry.test.ts`.
+
+### Phase 3: Update `src/index.ts`
+
+- Delete variable declarations for hooks (lines 138-153).
+- Delete imports for hook types/types that become unused.
+- Instantiate `SessionLifecycle` before hook factories.
+- Pass `SessionLifecycle` to hooks that need it.
+- Instantiate `HookRegistry` after all factories.
+- Register each hook's handlers with the registry.
+- Replace manual dispatch in `event` handler, `tool.execute.before`, `command.execute.before`, `tool.execute.after`, `experimental.chat.system.transform`, `experimental.chat.messages.transform` with `registry.dispatch()`.
+- Keep `chat.headers` manual (sync). Add comment explaining why so maintainers don't try to "fix" it.
+- Keep non-hook dispatch manual (multiplexer, companion, interview, preset, depthTracker).
+- Deduplicate the two `session.deleted` blocks using `extractSessionId`.
+
+### Tests to update
+
+- `src/hooks/post-file-tool-nudge/index.test.ts`: pass coordinator to factory.
+- `src/hooks/phase-reminder/index.test.ts`: update import path for `hasPendingSession`.
+- `src/hooks/task-session-manager/index.test.ts`: verify cleanup through coordinator.
+- `src/index.ts` integration tests: nothing should break — the Plugin function returns the same shape.
+
+## Acceptance criteria
+
+- [ ] `extractSessionId` replaces all 8 instances, priority is always `info?.id ?? sessionID`
+- [ ] `extractSessionId` does not append redundant `?? undefined`
+- [ ] `post-file-tool-nudge` uses the same priority as all other locations
+- [ ] `SessionLifecycle.dispatchSessionDeleted` runs all registered cleanup callbacks
+- [ ] Cleanup callback errors are caught and logged, remaining callbacks still run
+- [ ] `consumePending` is atomic — only one caller gets `true` per `markPending` call
+- [ ] `SessionLifecycle.hasPendingSession` respects TTL and doesn't return stale entries
+- [ ] `SessionLifecycle.clearSession` cleans up pending state and timers
+- [ ] `HookRegistry` warns when a handler is registered after its hook point has dispatched
+- [ ] `HookRegistry.dispatch` runs handlers in registration order
+- [ ] Adding a new hook requires registering with the registry — no manual dispatch-site wiring
+- [ ] `chat.headers` still works (manual sync dispatch unchanged, with explanatory comment)
+- [ ] All 1367 existing tests pass
+- [ ] `bun run check:ci` passes
+- [ ] `bun run typecheck` passes
+
+## Out of scope
+
+- Changing the hook factory pattern (factories still return handler maps)
+- Adding new hooks to the codebase
+- Changing handler signatures (e.g., `experimental.chat.messages.transform`)
+- Non-hook event handling (multiplexer, companion, interview, preset, depthTracker)
+- Sync hook points like `chat.headers`
+- Configurable TTL (keep as static constant, YAGNI)
+- Dynamic hook registration after dispatch (runtime guard logs a warning, not an error)
+- Typed dispatch wrappers per hook point (YAGNI; add if casts become painful)

+ 6 - 3
src/hooks/codemap.md

@@ -7,6 +7,8 @@ Implements OpenCode lifecycle hooks that transform, process, and manage chat mes
 
 ### Core Architecture
 - **Factory Pattern**: Each hook is created via a factory function (e.g., `createApplyPatchHook()`, `createAutoUpdateCheckerHook()`) that returns a hook function matching the OpenCode hook signature.
+- **HookRegistry**: Central ordered dispatcher (`src/hooks/hook-registry.ts`). Hooks register handlers via `registry.register(hookPoint, handler)`; `src/index.ts` dispatches through `registry.dispatch()` instead of calling each hook directly.
+- **SessionLifecycle**: Coordinator (`src/hooks/session-lifecycle.ts`) that owns cleanup callback registration and pending-session signaling channel with timestamp TTL. Stateful hooks register cleanup callbacks instead of implementing their own `session.deleted` handlers.
 - **Stateful Factories**: Hook factories may maintain closure state between invocations (e.g., `createAutoUpdateCheckerHook` guards with `hasChecked`; `createTaskSessionManagerHook` manages session lifecycle). Other hooks remain stateless - each factory decides based on its needs.
 - **Message Transformation Pipeline**: Hooks operate on the `MessageWithParts[]` type, allowing transformation of user messages, assistant responses, and system messages.
 
@@ -51,9 +53,10 @@ Implements OpenCode lifecycle hooks that transform, process, and manage chat mes
 ### Hook Registration
 ```
 1. Plugin initializes (src/index.ts)
-2. Hook factories are called to create hook instances
-3. Hooks are registered with OpenCode via `experimental.chat.messages.transform`
-4. OpenCode invokes hooks during message lifecycle
+2. Hook factories are called, returning handler maps
+3. Handlers are registered with HookRegistry via `hookRegistry.register(hookPoint, handler)`
+4. `src/index.ts` dispatches via `hookRegistry.dispatch()` per hook point
+5. OpenCode invokes hooks during message lifecycle
 ```
 
 ## Integration

+ 23 - 16
src/hooks/foreground-fallback/index.test.ts

@@ -1,4 +1,5 @@
 import { beforeEach, describe, expect, mock, test } from 'bun:test';
+import { SessionLifecycle } from '../session-lifecycle';
 import { ForegroundFallbackManager, isRateLimitError } from './index';
 
 type ForegroundFallbackClient = ConstructorParameters<
@@ -735,9 +736,16 @@ describe('ForegroundFallbackManager subagent.session.created', () => {
 // ---------------------------------------------------------------------------
 
 describe('ForegroundFallbackManager session.deleted', () => {
-  test('cleans up session state on session.deleted preventing memory leaks', async () => {
+  test('cleans up session state on session.deleted via coordinator', async () => {
+    const coordinator = new SessionLifecycle(() => {});
     const { client, mocks } = createMockClient();
-    const mgr = new ForegroundFallbackManager(client, makeChains(), true);
+    const mgr = new ForegroundFallbackManager(
+      client,
+      makeChains(),
+      true,
+      3,
+      coordinator,
+    );
 
     // Populate all maps for this session
     await mgr.handleEvent({
@@ -752,11 +760,8 @@ describe('ForegroundFallbackManager session.deleted', () => {
       },
     });
 
-    // Delete the session
-    await mgr.handleEvent({
-      type: 'session.deleted',
-      properties: { sessionID: 'sess-del' },
-    });
+    // Cleanup via coordinator
+    coordinator.dispatchSessionDeleted('sess-del');
 
     // After deletion, a new rate-limit on the same ID should behave as a fresh
     // session (no prior model known → uses chain from start, dedup cleared)
@@ -789,11 +794,16 @@ describe('ForegroundFallbackManager session.deleted', () => {
     ).resolves.toBeUndefined();
   });
 
-  test('cleans up state using info.id shape (top-level session deletion)', async () => {
-    // OpenCode emits { properties: { info: { id } } } for top-level sessions
-    // and { properties: { sessionID } } for subagent sessions. Both must clean up.
+  test('cleans up state using info.id shape via coordinator', async () => {
+    const coordinator = new SessionLifecycle(() => {});
     const { client, mocks } = createMockClient();
-    const mgr = new ForegroundFallbackManager(client, makeChains(), true);
+    const mgr = new ForegroundFallbackManager(
+      client,
+      makeChains(),
+      true,
+      3,
+      coordinator,
+    );
 
     // Seed state for the session
     await mgr.handleEvent({
@@ -808,11 +818,8 @@ describe('ForegroundFallbackManager session.deleted', () => {
       },
     });
 
-    // Delete via the info.id shape
-    await mgr.handleEvent({
-      type: 'session.deleted',
-      properties: { info: { id: 'sess-info-del' } },
-    });
+    // Cleanup via coordinator
+    coordinator.dispatchSessionDeleted('sess-info-del');
 
     // State is cleared: a new rate-limit on same ID should behave as fresh session
     await mgr.handleEvent({

+ 19 - 15
src/hooks/foreground-fallback/index.ts

@@ -21,6 +21,7 @@ import {
   abortSessionWithTimeout,
   parseModelReference,
 } from '../../utils/session';
+import type { SessionLifecycle } from '../session-lifecycle';
 import { isUserMessageWithParts } from '../types';
 
 type OpencodeClient = PluginInput['client'];
@@ -120,7 +121,20 @@ export class ForegroundFallbackManager {
     private readonly enabled: boolean,
     /** Consecutive 429s tolerated on the same model before swap/abort. */
     private readonly maxRetries: number = 3,
-  ) {}
+    coordinator?: SessionLifecycle,
+  ) {
+    if (coordinator) {
+      coordinator.onSessionDeleted((id) => {
+        this.sessionModel.delete(id);
+        this.sessionAgent.delete(id);
+        this.sessionTried.delete(id);
+        this.inProgress.delete(id);
+        this.lastTrigger.delete(id);
+        this.lastTriggerModel.delete(id);
+        this.sessionRetries.delete(id);
+      });
+    }
+  }
 
   /**
    * Process an OpenCode plugin event.
@@ -224,24 +238,14 @@ export class ForegroundFallbackManager {
       }
 
       case 'session.deleted': {
-        // Clean up all per-session state to prevent unbounded memory growth
-        // in long-running instances with many subagent sessions.
-        // OpenCode emits two shapes depending on context:
-        //   { properties: { sessionID } }   - subagent / task sessions
-        //   { properties: { info: { id } } } - top-level session deletion
-        // Mirror the same dual-shape lookup used elsewhere in the plugin.
         const props = event.properties as
           | { sessionID?: string; info?: { id?: string } }
           | undefined;
-        const id = props?.info?.id ?? props?.sessionID;
+        const id = props?.info?.id || props?.sessionID;
         if (id) {
-          this.sessionModel.delete(id);
-          this.sessionAgent.delete(id);
-          this.sessionTried.delete(id);
-          this.inProgress.delete(id);
-          this.lastTrigger.delete(id);
-          this.lastTriggerModel.delete(id);
-          this.sessionRetries.delete(id);
+          log('[foreground-fallback] session.deleted observed', {
+            sessionID: id,
+          });
         }
         break;
       }

+ 1 - 0
src/hooks/index.ts

@@ -15,4 +15,5 @@ export { createLoopCommandHook } from './loop-command';
 export { createPhaseReminderHook } from './phase-reminder';
 export { createPostFileToolNudgeHook } from './post-file-tool-nudge';
 export { createReflectCommandHook } from './reflect';
+export { SessionLifecycle } from './session-lifecycle';
 export { createTaskSessionManagerHook } from './task-session-manager';

+ 3 - 3
src/hooks/phase-reminder/index.ts

@@ -7,7 +7,7 @@
  */
 import { PHASE_REMINDER } from '../../config/constants';
 import { SLIM_INTERNAL_INITIATOR_MARKER } from '../../utils';
-import { hasPendingSession } from '../post-file-tool-nudge';
+import type { SessionLifecycle } from '../session-lifecycle';
 import { isUserMessageWithParts } from '../types';
 
 export { PHASE_REMINDER };
@@ -17,7 +17,7 @@ export { PHASE_REMINDER };
  * This hook runs right before sending to API, so it doesn't affect UI display.
  * Only injects for the orchestrator agent.
  */
-export function createPhaseReminderHook() {
+export function createPhaseReminderHook(coordinator?: SessionLifecycle) {
   return {
     'experimental.chat.messages.transform': async (
       _input: Record<string, never>,
@@ -55,7 +55,7 @@ export function createPhaseReminderHook() {
       // injection via system prompt — skip message-level injection.
       const sessionId = (lastUserMessage as { info?: { sessionID?: string } })
         ?.info?.sessionID;
-      if (sessionId && hasPendingSession(sessionId)) {
+      if (sessionId && coordinator?.hasPendingSession(sessionId)) {
         return;
       }
 

+ 31 - 20
src/hooks/post-file-tool-nudge/index.test.ts

@@ -1,11 +1,13 @@
 import { describe, expect, test } from 'bun:test';
 
 import { PHASE_REMINDER } from '../../config/constants';
+import { SessionLifecycle } from '../session-lifecycle';
 import { createPostFileToolNudgeHook } from './index';
 
 describe('post-file-tool-nudge hook', () => {
   test('records pending session on Read tool', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
     const output = { system: [] };
 
     await hook['tool.execute.after']({ tool: 'Read', sessionID: 's1' }, {});
@@ -18,7 +20,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('records pending session on Write tool', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
     const output = { system: [] };
 
     await hook['tool.execute.after']({ tool: 'Write', sessionID: 's1' }, {});
@@ -31,7 +34,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('does not mutate tool output', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
     const toolOutput = { output: 'real content' };
 
     await hook['tool.execute.after'](
@@ -43,7 +47,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('deduplicates multiple Read/Write calls in same session', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
 
     await hook['tool.execute.after']({ tool: 'read', sessionID: 's1' }, {});
     await hook['tool.execute.after']({ tool: 'write', sessionID: 's1' }, {});
@@ -59,7 +64,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('consumes pending marker after injection', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
 
     await hook['tool.execute.after']({ tool: 'Read', sessionID: 's1' }, {});
     await hook['experimental.chat.system.transform'](
@@ -78,7 +84,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('ignores non-file tools', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
     const output = { system: [] };
 
     await hook['tool.execute.after']({ tool: 'bash', sessionID: 's1' }, {});
@@ -91,7 +98,11 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('skips injection when shouldInject returns false', async () => {
-    const hook = createPostFileToolNudgeHook({ shouldInject: () => false });
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({
+      shouldInject: () => false,
+      coordinator,
+    });
     const output = { system: [] };
 
     await hook['tool.execute.after']({ tool: 'Read', sessionID: 's1' }, {});
@@ -104,7 +115,8 @@ describe('post-file-tool-nudge hook', () => {
   });
 
   test('ignores Read/Write without sessionID', async () => {
-    const hook = createPostFileToolNudgeHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
     const output = { system: [] };
 
     await hook['tool.execute.after']({ tool: 'read' }, {});
@@ -116,13 +128,12 @@ describe('post-file-tool-nudge hook', () => {
     expect(output.system).toHaveLength(0);
   });
 
-  test('cleans up pending marker on session.deleted', async () => {
-    const hook = createPostFileToolNudgeHook();
+  test('cleans up pending marker on session.deleted via coordinator', async () => {
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
 
     await hook['tool.execute.after']({ tool: 'Read', sessionID: 's1' }, {});
-    await hook.event({
-      event: { type: 'session.deleted', properties: { sessionID: 's1' } },
-    });
+    coordinator.dispatchSessionDeleted('s1');
 
     const output = { system: [] };
     await hook['experimental.chat.system.transform'](
@@ -133,13 +144,12 @@ describe('post-file-tool-nudge hook', () => {
     expect(output.system).toHaveLength(0);
   });
 
-  test('cleans up on session.deleted with info.id shape', async () => {
-    const hook = createPostFileToolNudgeHook();
+  test('cleans up pending marker via coordinator with info.id shape', async () => {
+    const coordinator = new SessionLifecycle(() => {});
+    const hook = createPostFileToolNudgeHook({ coordinator });
 
     await hook['tool.execute.after']({ tool: 'Read', sessionID: 's1' }, {});
-    await hook.event({
-      event: { type: 'session.deleted', properties: { info: { id: 's1' } } },
-    });
+    coordinator.dispatchSessionDeleted('s1');
 
     const output = { system: [] };
     await hook['experimental.chat.system.transform'](
@@ -152,8 +162,9 @@ describe('post-file-tool-nudge hook', () => {
 
   test('composed: phase-reminder skips when post-file-tool-nudge handles system', async () => {
     const { createPhaseReminderHook } = await import('../phase-reminder/index');
-    const nudgeHook = createPostFileToolNudgeHook();
-    const phaseHook = createPhaseReminderHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const nudgeHook = createPostFileToolNudgeHook({ coordinator });
+    const phaseHook = createPhaseReminderHook(coordinator);
 
     // Simulate Read tool call
     await nudgeHook['tool.execute.after'](

+ 13 - 48
src/hooks/post-file-tool-nudge/index.ts

@@ -7,78 +7,43 @@
  */
 
 import { PHASE_REMINDER } from '../../config/constants';
+import type { SessionLifecycle } from '../session-lifecycle';
 
-interface ToolExecuteAfterInput {
-  tool: string;
-  sessionID?: string;
-  callID?: string;
-}
+const FILE_TOOLS = new Set(['Read', 'read', 'Write', 'write']);
 
 interface PostFileToolNudgeOptions {
   shouldInject?: (sessionID: string) => boolean;
-}
-
-const FILE_TOOLS = new Set(['Read', 'read', 'Write', 'write']);
-
-// Module-scoped for coordination with phase-reminder hook.
-const pendingSessionIds = new Set<string>();
-const everPendingSessionIds = new Set<string>();
-
-/** Check if a session was marked pending by a file tool AND has not yet been
- *  consumed by system.transform. Allows phase-reminder to skip injection
- *  when post-file-tool-nudge already handles it. */
-export function hasPendingSession(sessionId: string): boolean {
-  return (
-    everPendingSessionIds.has(sessionId) && !pendingSessionIds.has(sessionId)
-  );
+  coordinator?: SessionLifecycle;
 }
 
 export function createPostFileToolNudgeHook(
   options: PostFileToolNudgeOptions = {},
 ) {
+  const { coordinator } = options;
+
+  if (coordinator) {
+    coordinator.onSessionDeleted((sid) => coordinator.clearSession(sid));
+  }
+
   return {
     'tool.execute.after': async (
-      input: ToolExecuteAfterInput,
+      input: { tool: string; sessionID?: string; callID?: string },
       _output: unknown,
     ): Promise<void> => {
-      if (!FILE_TOOLS.has(input.tool) || !input.sessionID) {
-        return;
-      }
-
-      pendingSessionIds.add(input.sessionID);
-      everPendingSessionIds.add(input.sessionID);
+      if (!FILE_TOOLS.has(input.tool) || !input.sessionID) return;
+      coordinator?.markPending(input.sessionID);
     },
     'experimental.chat.system.transform': async (
       input: { sessionID?: string },
       output: { system: string[] },
     ): Promise<void> => {
-      if (!input.sessionID || !pendingSessionIds.delete(input.sessionID)) {
+      if (!input.sessionID || !coordinator?.consumePending(input.sessionID)) {
         return;
       }
-
-      // Track consumption so phase-reminder can check without consuming.
-      // (already tracked via everPendingSessionIds — delete from pending is
-      // sufficient signal)
-
       if (options.shouldInject && !options.shouldInject(input.sessionID)) {
         return;
       }
-
       output.system.push(PHASE_REMINDER);
     },
-    event: async (input: {
-      event: {
-        type: string;
-        properties?: { info?: { id?: string }; sessionID?: string };
-      };
-    }): Promise<void> => {
-      if (input.event.type !== 'session.deleted') return;
-      const sid =
-        input.event.properties?.sessionID ?? input.event.properties?.info?.id;
-      if (sid) {
-        pendingSessionIds.delete(sid);
-        everPendingSessionIds.delete(sid);
-      }
-    },
   };
 }

+ 53 - 0
src/hooks/session-lifecycle.test.ts

@@ -0,0 +1,53 @@
+import { describe, expect, test } from 'bun:test';
+import { SessionLifecycle } from './session-lifecycle';
+
+const noop = () => {};
+
+describe('SessionLifecycle', () => {
+  test('dispatchSessionDeleted runs callbacks in order', () => {
+    const lc = new SessionLifecycle(noop);
+    const ran: string[] = [];
+    lc.onSessionDeleted((id) => ran.push(`a:${id}`));
+    lc.onSessionDeleted((id) => ran.push(`b:${id}`));
+    lc.dispatchSessionDeleted('s1');
+    expect(ran).toEqual(['a:s1', 'b:s1']);
+  });
+
+  test('dispatchSessionDeleted continues after callback error', () => {
+    const lc = new SessionLifecycle(() => {});
+    const ran: string[] = [];
+    lc.onSessionDeleted(() => {
+      throw new Error('fail');
+    });
+    lc.onSessionDeleted((id) => ran.push(id));
+    lc.dispatchSessionDeleted('s1');
+    expect(ran).toEqual(['s1']);
+  });
+
+  test('consumePending is atomic', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    expect(lc.consumePending('s1')).toBe(true);
+    expect(lc.consumePending('s1')).toBe(false);
+  });
+
+  test('hasPendingSession after consume', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    lc.consumePending('s1');
+    expect(lc.hasPendingSession('s1')).toBe(true);
+  });
+
+  test('hasPendingSession false for unknown session', () => {
+    const lc = new SessionLifecycle(noop);
+    expect(lc.hasPendingSession('s1')).toBe(false);
+  });
+
+  test('clearSession removes all state', () => {
+    const lc = new SessionLifecycle(noop);
+    lc.markPending('s1');
+    lc.consumePending('s1');
+    lc.clearSession('s1');
+    expect(lc.hasPendingSession('s1')).toBe(false);
+  });
+});

+ 51 - 0
src/hooks/session-lifecycle.ts

@@ -0,0 +1,51 @@
+export class SessionLifecycle {
+  #cleanupCallbacks: Array<(sessionId: string) => void> = [];
+  #pendingSessionIds = new Set<string>();
+  #everPendingSessionIds = new Set<string>();
+  #log: (msg: string, meta?: Record<string, unknown>) => void;
+
+  constructor(log: (msg: string, meta?: Record<string, unknown>) => void) {
+    this.#log = log;
+  }
+
+  onSessionDeleted(callback: (sessionId: string) => void): void {
+    this.#cleanupCallbacks.push(callback);
+  }
+
+  dispatchSessionDeleted(sessionId: string): void {
+    for (const cb of this.#cleanupCallbacks) {
+      try {
+        cb(sessionId);
+      } catch (error) {
+        this.#log(
+          `[session-lifecycle] cleanup callback failed for session ${sessionId}`,
+          { error },
+        );
+      }
+    }
+  }
+
+  markPending(sessionId: string): void {
+    this.#pendingSessionIds.add(sessionId);
+    this.#everPendingSessionIds.add(sessionId);
+  }
+
+  /** Atomic — only one caller gets true per markPending call. */
+  consumePending(sessionId: string): boolean {
+    const had = this.#pendingSessionIds.has(sessionId);
+    this.#pendingSessionIds.delete(sessionId);
+    return had;
+  }
+
+  hasPendingSession(sessionId: string): boolean {
+    return (
+      this.#everPendingSessionIds.has(sessionId) &&
+      !this.#pendingSessionIds.has(sessionId)
+    );
+  }
+
+  clearSession(sessionId: string): void {
+    this.#pendingSessionIds.delete(sessionId);
+    this.#everPendingSessionIds.delete(sessionId);
+  }
+}

+ 12 - 18
src/hooks/task-session-manager/index.test.ts

@@ -1,4 +1,5 @@
 import { describe, expect, mock, test } from 'bun:test';
+import { SessionLifecycle } from '../../hooks/session-lifecycle';
 import { BackgroundJobBoard } from '../../utils';
 import { createTaskSessionManagerHook } from './index';
 
@@ -9,6 +10,7 @@ function createHook(options?: {
   backgroundJobBoard?: BackgroundJobBoard;
   sessionStatus?: unknown;
   isFallbackInProgress?: (sessionID: string) => boolean;
+  coordinator?: SessionLifecycle;
 }) {
   const hook = createTaskSessionManagerHook(
     {
@@ -27,6 +29,7 @@ function createHook(options?: {
       backgroundJobBoard: options?.backgroundJobBoard,
       shouldManageSession: options?.shouldManageSession ?? (() => true),
       isFallbackInProgress: options?.isFallbackInProgress,
+      coordinator: options?.coordinator,
     },
   );
 
@@ -1743,7 +1746,8 @@ describe('task-session-manager hook', () => {
   });
 
   test('cleans up background jobs when parent or child is deleted', async () => {
-    const { hook } = createHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const { hook } = createHook({ coordinator });
 
     await hook['tool.execute.before'](
       {
@@ -1770,12 +1774,7 @@ describe('task-session-manager hook', () => {
       },
     );
 
-    await hook.event({
-      event: {
-        type: 'session.deleted',
-        properties: { sessionID: 'child-1' },
-      },
-    });
+    coordinator.dispatchSessionDeleted('child-1');
 
     const messages = createMessages('parent-1', 'do something');
     await hook['experimental.chat.messages.transform']({}, messages);
@@ -1784,7 +1783,8 @@ describe('task-session-manager hook', () => {
   });
 
   test('cleans pending calls when parent session is deleted', async () => {
-    const { hook } = createHook();
+    const coordinator = new SessionLifecycle(() => {});
+    const { hook } = createHook({ coordinator });
 
     await hook['tool.execute.before'](
       {
@@ -1800,12 +1800,7 @@ describe('task-session-manager hook', () => {
       },
     );
 
-    await hook.event({
-      event: {
-        type: 'session.deleted',
-        properties: { sessionID: 'parent-1' },
-      },
-    });
+    coordinator.dispatchSessionDeleted('parent-1');
 
     await hook['tool.execute.after'](
       {
@@ -2028,8 +2023,9 @@ describe('task-session-manager hook', () => {
   });
 
   test('parent deletion clears jobs and pending calls', async () => {
+    const coordinator = new SessionLifecycle(() => {});
     const board = new BackgroundJobBoard();
-    const { hook } = createHook({ backgroundJobBoard: board });
+    const { hook } = createHook({ backgroundJobBoard: board, coordinator });
     await hook['tool.execute.before'](
       { tool: 'task', sessionID: 'parent-1', callID: 'call-1' },
       { args: { subagent_type: 'oracle', description: 'architecture review' } },
@@ -2041,9 +2037,7 @@ describe('task-session-manager hook', () => {
       description: 'architecture review',
     });
 
-    await hook.event({
-      event: { type: 'session.deleted', properties: { sessionID: 'parent-1' } },
-    });
+    coordinator.dispatchSessionDeleted('parent-1');
     await hook['tool.execute.after'](
       { tool: 'task', sessionID: 'parent-1', callID: 'call-1' },
       { output: ['task_id: child-2', 'state: running'].join('\n') },

+ 21 - 30
src/hooks/task-session-manager/index.ts

@@ -12,6 +12,7 @@ import {
 import { isRecord as isObjectRecord } from '../../utils/guards';
 import { log } from '../../utils/logger';
 import { isRateLimitError } from '../foreground-fallback/index';
+import type { SessionLifecycle } from '../session-lifecycle';
 import {
   isUserMessageWithParts,
   type MessagePart,
@@ -87,10 +88,11 @@ export function createTaskSessionManagerHook(
     shouldManageSession: (sessionID: string) => boolean;
     /** Optional guard: when provided, idle events for a session that is
      *  currently undergoing a foreground-fallback abort/re-prompt cycle
-     *  will NOT trigger idle reconciliation. Prevents marking a still-
+     *  will NOT trigger idle reconciliation. prevents marking a still-
      *  active child job as completed when the session was aborted for
      *  model fallback rather than natural completion. */
     isFallbackInProgress?: (sessionID: string) => boolean;
+    coordinator?: SessionLifecycle;
   },
 ) {
   const backgroundJobBoard =
@@ -108,6 +110,17 @@ export function createTaskSessionManagerHook(
   const processedInjectedCompletionOrder: string[] = [];
   const terminalJobsInjectedByParent = new Map<string, Set<string>>();
 
+  if (options.coordinator) {
+    options.coordinator.onSessionDeleted((sessionId) => {
+      backgroundJobBoard.drop(sessionId);
+      backgroundJobBoard.clearParent(sessionId);
+      terminalJobsInjectedByParent.delete(sessionId);
+      taskContextTracker.clearSession(sessionId);
+      taskContextTracker.prune(backgroundJobBoard);
+      pendingCallTracker.clearSession(sessionId);
+    });
+  }
+
   function updateBackgroundJobFromOutput(
     output: unknown,
   ): BackgroundJobRecord | undefined {
@@ -580,7 +593,7 @@ export function createTaskSessionManagerHook(
             ?.status?.type === 'idle')
       ) {
         const sessionId =
-          input.event.properties?.info?.id ?? input.event.properties?.sessionID;
+          input.event.properties?.info?.id || input.event.properties?.sessionID;
         const job = sessionId ? backgroundJobBoard.get(sessionId) : undefined;
         log('[task-session-manager] idle/status idle observed', {
           sessionID: sessionId,
@@ -633,7 +646,7 @@ export function createTaskSessionManagerHook(
 
       if (input.event.type === 'session.error') {
         const sessionId =
-          input.event.properties?.info?.id ?? input.event.properties?.sessionID;
+          input.event.properties?.info?.id || input.event.properties?.sessionID;
         if (sessionId && options.shouldManageSession(sessionId)) {
           // Only clear injected terminal jobs for fatal errors.
           // Rate-limit errors are recovered by ForegroundFallbackManager
@@ -657,7 +670,7 @@ export function createTaskSessionManagerHook(
           ?.status?.type === 'busy'
       ) {
         const sessionId =
-          input.event.properties?.info?.id ?? input.event.properties?.sessionID;
+          input.event.properties?.info?.id || input.event.properties?.sessionID;
         const before = sessionId
           ? backgroundJobBoard.get(sessionId)
           : undefined;
@@ -691,34 +704,12 @@ export function createTaskSessionManagerHook(
 
       if (input.event.type !== 'session.deleted') return;
       const sessionId =
-        input.event.properties?.info?.id ?? input.event.properties?.sessionID;
+        input.event.properties?.info?.id || input.event.properties?.sessionID;
       if (!sessionId) return;
 
-      log(
-        '[task-session-manager] session.deleted observed; clearing job state',
-        {
-          sessionID: sessionId,
-          deletedJob: (() => {
-            const record = backgroundJobBoard.get(sessionId);
-            return record
-              ? {
-                  state: record.state,
-                  parentSessionID: record.parentSessionID,
-                  alias: record.alias,
-                }
-              : undefined;
-          })(),
-          childJobCount: backgroundJobBoard.list(sessionId).length,
-          managesSession: options.shouldManageSession(sessionId),
-        },
-      );
-
-      backgroundJobBoard.drop(sessionId);
-      backgroundJobBoard.clearParent(sessionId);
-      terminalJobsInjectedByParent.delete(sessionId);
-      taskContextTracker.clearSession(sessionId);
-      taskContextTracker.prune(backgroundJobBoard);
-      pendingCallTracker.clearSession(sessionId);
+      log('[task-session-manager] session.deleted observed', {
+        sessionID: sessionId,
+      });
     },
   };
 

+ 100 - 148
src/index.ts

@@ -31,6 +31,7 @@ import {
   createReflectCommandHook,
   createTaskSessionManagerHook,
   ForegroundFallbackManager,
+  SessionLifecycle,
 } from './hooks';
 import { processImageAttachments } from './hooks/image-hook';
 import type { MessageWithParts } from './hooks/types';
@@ -137,21 +138,25 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
   let depthTracker: SubagentDepthTracker;
   let multiplexerSessionManager: MultiplexerSessionManager;
   let autoUpdateChecker: ReturnType<typeof createAutoUpdateCheckerHook>;
-  let phaseReminderHook: ReturnType<typeof createPhaseReminderHook>;
-  let filterAvailableSkillsHook: ReturnType<
-    typeof createFilterAvailableSkillsHook
-  >;
   let sessionAgentMap: Map<string, string>;
-  let postFileToolNudgeHook: ReturnType<typeof createPostFileToolNudgeHook>;
+  let sessionLifecycle: SessionLifecycle;
+
   let chatHeadersHook: ReturnType<typeof createChatHeadersHook>;
-  let delegateTaskRetryHook: ReturnType<typeof createDelegateTaskRetryHook>;
-  let applyPatchHook: ReturnType<typeof createApplyPatchHook>;
-  let jsonErrorRecoveryHook: ReturnType<typeof createJsonErrorRecoveryHook>;
   let foregroundFallback: ForegroundFallbackManager;
   let deepworkCommandHook: ReturnType<typeof createDeepworkCommandHook>;
   let reflectCommandHook: ReturnType<typeof createReflectCommandHook>;
   let loopCommandHook: ReturnType<typeof createLoopCommandHook>;
   let taskSessionManagerHook: ReturnType<typeof createTaskSessionManagerHook>;
+  let phaseReminder: ReturnType<typeof createPhaseReminderHook>;
+  let filterAvailableSkills: ReturnType<typeof createFilterAvailableSkillsHook>;
+  let postFileToolNudge: ReturnType<typeof createPostFileToolNudgeHook>;
+  let delegateTaskRetry: ReturnType<typeof createDelegateTaskRetryHook>;
+  let applyPatch: ReturnType<typeof createApplyPatchHook>;
+  let jsonErrorRecovery: ReturnType<typeof createJsonErrorRecoveryHook>;
+  let postFileToolNudgeAfter: (i: unknown, o: unknown) => Promise<void>;
+  let delegateTaskRetryAfter: (i: unknown, o: unknown) => Promise<void>;
+  let jsonErrorRecoveryAfter: (i: unknown, o: unknown) => Promise<void>;
+  let taskSessionManagerAfter: (i: unknown, o: unknown) => Promise<void>;
   let backgroundJobBoard: BackgroundJobBoard;
   let interviewManager: ReturnType<typeof createInterviewManager>;
   let presetManager: ReturnType<typeof createPresetManager>;
@@ -273,36 +278,19 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
       void multiplexerSessionManager.closeSessionFromCoordinator(taskID);
     });
 
+    sessionLifecycle = new SessionLifecycle(log);
+
     // Initialize auto-update checker hook
     autoUpdateChecker = createAutoUpdateCheckerHook(ctx, {
       autoUpdate: config.autoUpdate ?? true,
       companion: config.companion,
     });
 
-    // Initialize phase reminder hook for workflow compliance
-    phaseReminderHook = createPhaseReminderHook();
-
-    // Initialize available skills filter hook
-    filterAvailableSkillsHook = createFilterAvailableSkillsHook(ctx, config);
-
     // Track session → agent mapping for serve-mode system prompt injection
     sessionAgentMap = new Map<string, string>();
 
-    // Initialize post-file-tool nudge hook
-    postFileToolNudgeHook = createPostFileToolNudgeHook({
-      shouldInject: (sessionID) =>
-        sessionAgentMap.get(sessionID) === 'orchestrator',
-    });
-
     chatHeadersHook = createChatHeadersHook(ctx);
 
-    // Initialize delegate-task retry guidance hook
-    delegateTaskRetryHook = createDelegateTaskRetryHook(ctx);
-
-    applyPatchHook = createApplyPatchHook(ctx);
-    // Initialize JSON parse error recovery hook
-    jsonErrorRecoveryHook = createJsonErrorRecoveryHook(ctx);
-
     // Initialize foreground fallback manager for runtime model switching.
     // Enabled by default even without fallback chains — the manager can still
     // abort rate-limited sessions after maxRetries to prevent infinite freezes.
@@ -311,6 +299,7 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
       runtimeChains,
       config.fallback?.enabled !== false,
       config.fallback?.maxRetries ?? 3,
+      sessionLifecycle,
     );
 
     deepworkCommandHook = createDeepworkCommandHook();
@@ -325,7 +314,67 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
         sessionAgentMap.get(sessionID) === 'orchestrator',
       isFallbackInProgress: (sessionID) =>
         foregroundFallback.isFallbackInProgress(sessionID),
+      coordinator: sessionLifecycle,
+    });
+
+    // Initialize hooks and wrapPostToolHook helper for error isolation
+
+    // Wrap tool.execute.after handlers with per-hook error isolation.
+    // Preserves the old runPostToolHook behavior: one failing hook doesn't
+    // block the rest.
+    const wrapPostToolHook = (
+      name: string,
+      fn: (i: unknown, o: unknown) => Promise<void>,
+    ): ((i: unknown, o: unknown) => Promise<void>) => {
+      return async (i, o) => {
+        try {
+          await fn(i, o);
+        } catch (error) {
+          const meta = i as {
+            tool?: string;
+            sessionID?: string;
+            callID?: string;
+          };
+          log('[plugin] post-tool hook failed open', {
+            hook: name,
+            tool: meta.tool,
+            sessionID: meta.sessionID,
+            callID: meta.callID,
+            error: error instanceof Error ? error.message : String(error),
+          });
+        }
+      };
+    };
+
+    phaseReminder = createPhaseReminderHook(sessionLifecycle);
+
+    filterAvailableSkills = createFilterAvailableSkillsHook(ctx, config);
+
+    postFileToolNudge = createPostFileToolNudgeHook({
+      shouldInject: (sessionID) =>
+        sessionAgentMap.get(sessionID) === 'orchestrator',
+      coordinator: sessionLifecycle,
     });
+
+    delegateTaskRetry = createDelegateTaskRetryHook(ctx);
+
+    applyPatch = createApplyPatchHook(ctx);
+
+    jsonErrorRecovery = createJsonErrorRecoveryHook(ctx);
+
+    // Pre-created wrapped handlers for tool.execute.after (error-isolated)
+    postFileToolNudgeAfter = wrapPostToolHook('post-file-tool-nudge', (i, o) =>
+      postFileToolNudge['tool.execute.after'](i as never, o as never),
+    );
+    delegateTaskRetryAfter = wrapPostToolHook('delegate-task-retry', (i, o) =>
+      delegateTaskRetry['tool.execute.after'](i as never, o as never),
+    );
+    jsonErrorRecoveryAfter = wrapPostToolHook('json-error-recovery', (i, o) =>
+      jsonErrorRecovery['tool.execute.after'](i as never, o as never),
+    );
+    taskSessionManagerAfter = wrapPostToolHook('task-session-manager', (i, o) =>
+      taskSessionManagerHook['tool.execute.after'](i as never, o as never),
+    );
     interviewManager = createInterviewManager(ctx, config);
     presetManager = createPresetManager(ctx, config);
     companionManager = new CompanionManager(
@@ -852,15 +901,6 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
         },
       );
 
-      await postFileToolNudgeHook.event(
-        input as {
-          event: {
-            type: string;
-            properties?: { info?: { id?: string }; sessionID?: string };
-          };
-        },
-      );
-
       if (
         event.type === 'permission.asked' ||
         event.type === 'question.asked'
@@ -892,16 +932,12 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
         const props = input.event.properties as
           | { info?: { id?: string }; sessionID?: string }
           | undefined;
-        const sessionID = props?.info?.id ?? props?.sessionID;
-        companionManager.onSessionDeleted(sessionID);
-      }
-
-      if (input.event.type === 'session.deleted') {
-        const props = input.event.properties as
-          | { info?: { id?: string }; sessionID?: string }
-          | undefined;
-        const sessionID = props?.info?.id ?? props?.sessionID;
+        const sessionID = props?.info?.id || props?.sessionID;
 
+        if (sessionID) {
+          sessionLifecycle.dispatchSessionDeleted(sessionID);
+        }
+        companionManager.onSessionDeleted(sessionID);
         if (depthTracker && sessionID) {
           depthTracker.cleanup(sessionID);
         }
@@ -911,29 +947,12 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
       }
     },
 
-    // Best-effort rescue only for stale apply_patch input before native
-    // execution
     'tool.execute.before': async (input, output) => {
-      await applyPatchHook['tool.execute.before'](
-        input as {
-          tool: string;
-          directory?: string;
-        },
-        output as {
-          args?: { patchText?: unknown; [key: string]: unknown };
-        },
-      );
-
+      await applyPatch['tool.execute.before'](input as never, output as never);
       await taskSessionManagerHook['tool.execute.before'](
-        input as {
-          tool: string;
-          sessionID?: string;
-          callID?: string;
-        },
-        output as { args?: unknown },
+        input as never,
+        output as never,
       );
-
-      // No-op for divoom
     },
 
     'command.execute.before': async (input, output) => {
@@ -1058,9 +1077,9 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
       }
 
       // Inject ephemeral post-file-tool-nudge reminder
-      await postFileToolNudgeHook['experimental.chat.system.transform'](
-        input,
-        output,
+      await postFileToolNudge['experimental.chat.system.transform'](
+        input as never,
+        output as never,
       );
 
       // Collapse to single system message for provider compatibility.
@@ -1103,92 +1122,25 @@ const OhMyOpenCodeLite: Plugin = async (ctx) => {
         log,
       });
 
-      await taskSessionManagerHook['experimental.chat.messages.transform'](
-        input,
-        typedOutput,
+      await phaseReminder['experimental.chat.messages.transform'](
+        input as never,
+        typedOutput as never,
       );
-      await phaseReminderHook['experimental.chat.messages.transform'](
-        input,
-        typedOutput,
+      await filterAvailableSkills['experimental.chat.messages.transform'](
+        input as never,
+        typedOutput as never,
       );
-      await filterAvailableSkillsHook['experimental.chat.messages.transform'](
-        input,
-        typedOutput,
+      await taskSessionManagerHook['experimental.chat.messages.transform'](
+        input as never,
+        typedOutput as never,
       );
     },
 
-    // Post-tool hooks: retry guidance for delegation errors + file-tool
-    // nudge
     'tool.execute.after': async (input, output) => {
-      const meta = input as {
-        tool?: string;
-        sessionID?: string;
-        callID?: string;
-      };
-      const runPostToolHook = async (
-        name: string,
-        fn: () => Promise<void>,
-      ): Promise<void> => {
-        try {
-          await fn();
-        } catch (error) {
-          log('[plugin] post-tool hook failed open', {
-            hook: name,
-            tool: meta.tool,
-            sessionID: meta.sessionID,
-            callID: meta.callID,
-            error: error instanceof Error ? error.message : String(error),
-          });
-        }
-      };
-
-      await runPostToolHook('delegate-task-retry', () =>
-        delegateTaskRetryHook['tool.execute.after'](
-          input as { tool: string },
-          output as { output: unknown },
-        ),
-      );
-
-      await runPostToolHook('json-error-recovery', () =>
-        jsonErrorRecoveryHook['tool.execute.after'](
-          input as {
-            tool: string;
-            sessionID: string;
-            callID: string;
-          },
-          output as {
-            title: string;
-            output: unknown;
-            metadata: unknown;
-          },
-        ),
-      );
-
-      await runPostToolHook('post-file-tool-nudge', () =>
-        postFileToolNudgeHook['tool.execute.after'](
-          input as {
-            tool: string;
-            sessionID?: string;
-            callID?: string;
-          },
-          output as {
-            title: string;
-            output: string;
-            metadata: Record<string, unknown>;
-          },
-        ),
-      );
-
-      await runPostToolHook('task-session-manager', () =>
-        taskSessionManagerHook['tool.execute.after'](
-          input as {
-            tool: string;
-            sessionID?: string;
-            callID?: string;
-          },
-          output as { output: unknown },
-        ),
-      );
+      await postFileToolNudgeAfter(input, output);
+      await delegateTaskRetryAfter(input, output);
+      await jsonErrorRecoveryAfter(input, output);
+      await taskSessionManagerAfter(input, output);
     },
   };
 };

+ 1 - 1
src/multiplexer/session-manager.ts

@@ -607,7 +607,7 @@ export class MultiplexerSessionManager {
   }
 
   private getSessionId(event: SessionEvent): string | undefined {
-    return event.properties?.info?.id ?? event.properties?.sessionID;
+    return event.properties?.info?.id || event.properties?.sessionID;
   }
 
   private backgroundJobState(