From 1ee3e217305213c7c1e5fbe907c1214052ea30d7 Mon Sep 17 00:00:00 2001 From: Lorran Hippolyte Date: Wed, 8 Jul 2026 19:20:39 -0300 Subject: [PATCH 1/4] fix: prefer local dotcontext binary for hook dispatch, pin npx fallback Hook configs previously persisted `npx -y @dotcontext/cli@latest hook dispatch`, which spawns npx and re-resolves the `latest` dist-tag on every SessionStart/PostToolUse/Stop event. On busy sessions this produces a constant stream of short-lived Node processes and registry lookups on every file edit and shell command. The installer now writes `dotcontext hook dispatch --source ` when a global dotcontext binary is found on PATH, and otherwise falls back to npx pinned to the installed CLI version. Both forms are treated as current so installs do not churn configs; the legacy `@latest` form is upgraded on re-install. Co-Authored-By: Claude Fable 5 --- README.md | 4 +- .../src/content/docs/en/about/architecture.md | 2 +- .../docs/en/guides/using-with-hooks.md | 12 +- .../docs/pt-br/guides/hook-session-flow.md | 11 +- .../docs/pt-br/guides/using-with-hooks.md | 8 +- .../__tests__/hookInstallService.test.ts | 5 +- .../__tests__/hookInstallServices.test.ts | 19 +-- .../hooks/claudeCodeHookTemplates.ts | 63 +++++---- src/integrations/claude-code/hooks/index.ts | 1 + .../codex/hooks/codexHookTemplates.ts | 78 ++++++----- src/integrations/codex/hooks/index.ts | 1 + .../__tests__/hookDispatchCommands.test.ts | 114 +++++++++++++++++ .../shared/__tests__/hookSessionStore.test.ts | 9 +- .../shared/hookDispatchCommands.ts | 121 ++++++++++++++++-- src/integrations/shared/index.ts | 9 ++ 15 files changed, 367 insertions(+), 90 deletions(-) create mode 100644 src/integrations/shared/__tests__/hookDispatchCommands.test.ts diff --git a/README.md b/README.md index 73e31c73..b144ac2f 100644 --- a/README.md +++ b/README.md @@ -434,8 +434,8 @@ npx -y @dotcontext/cli@latest hook doctor codex --json | Host | Config | Dispatch | | --- | --- | --- | -| `claude-code` | `.claude/settings.json` | `npx -y @dotcontext/cli@latest hook dispatch --source claude-code` | -| `codex` | `.codex/hooks.json` or inline in `.codex/config.toml` | `npx -y @dotcontext/cli@latest hook dispatch --source codex` | +| `claude-code` | `.claude/settings.json` | `dotcontext hook dispatch --source claude-code` (falls back to `npx -y @dotcontext/cli@ ...` when no global binary is on PATH) | +| `codex` | `.codex/hooks.json` or inline in `.codex/config.toml` | `dotcontext hook dispatch --source codex` (same fallback) | | `pi` | `pi install npm:@dotcontext/pi` | In-process TypeScript extension | Codex-specific activation step: diff --git a/docs/src/content/docs/en/about/architecture.md b/docs/src/content/docs/en/about/architecture.md index 2e9b024a..3eef17a2 100644 --- a/docs/src/content/docs/en/about/architecture.md +++ b/docs/src/content/docs/en/about/architecture.md @@ -85,7 +85,7 @@ This is the surface an AI client (Claude Code, Cursor, Windsurf, and others) tal ### The integrations boundary -**Integrations** connect host lifecycle events to the harness without going through MCP. Claude Code and Codex CLI use shell dispatch (`npx -y @dotcontext/cli@latest hook dispatch`); Pi loads the `@dotcontext/pi` npm extension in-process. +**Integrations** connect host lifecycle events to the harness without going through MCP. Claude Code and Codex CLI use shell dispatch (`dotcontext hook dispatch`, with a version-pinned npx fallback when no global binary is on PATH); Pi loads the `@dotcontext/pi` npm extension in-process. Integrations call the harness only — they never import `cli` or `mcp`. See [using dotcontext with hooks](/guides/using-with-hooks/) and [using dotcontext with Pi](/guides/using-with-pi/). diff --git a/docs/src/content/docs/en/guides/using-with-hooks.md b/docs/src/content/docs/en/guides/using-with-hooks.md index 70b5fde9..33edbc87 100644 --- a/docs/src/content/docs/en/guides/using-with-hooks.md +++ b/docs/src/content/docs/en/guides/using-with-hooks.md @@ -90,12 +90,16 @@ Repeated trace append failures are recorded under `.context/runtime/hooks/trace- ## Claude Code -The installer writes `hooks` entries to Claude Code settings. Each entry runs: +The installer writes `hooks` entries to Claude Code settings. When a global `dotcontext` binary is on PATH, each entry runs it directly; otherwise the entry falls back to npx pinned to the installed CLI version: ```bash -npx -y @dotcontext/cli@latest hook dispatch --source claude-code +dotcontext hook dispatch --source claude-code +# or, when no global binary is available: +npx -y @dotcontext/cli@ hook dispatch --source claude-code ``` +Running the binary directly (or a pinned version) avoids re-resolving the npm `latest` tag on every SessionStart, PostToolUse, and Stop event. + Wired events (v1): | Event | Matcher | @@ -119,7 +123,9 @@ Start a Claude Code session in a repository with `.context/` initialized and con Codex hooks use the same dispatch command with `--source codex`: ```bash -npx -y @dotcontext/cli@latest hook dispatch --source codex +dotcontext hook dispatch --source codex +# or, when no global binary is available: +npx -y @dotcontext/cli@ hook dispatch --source codex ``` The installer writes either: diff --git a/docs/src/content/docs/pt-br/guides/hook-session-flow.md b/docs/src/content/docs/pt-br/guides/hook-session-flow.md index 4598da13..d2e289a9 100644 --- a/docs/src/content/docs/pt-br/guides/hook-session-flow.md +++ b/docs/src/content/docs/pt-br/guides/hook-session-flow.md @@ -24,13 +24,18 @@ Pi extension -> resposta in-process para Pi ``` -Para Claude Code e Codex CLI, o instalador escreve comandos shell que chamam: +Para Claude Code e Codex CLI, o instalador escreve comandos shell que preferem o binário global `dotcontext` quando presente no PATH, com fallback para npx pinado na versão instalada: ```bash -npx -y @dotcontext/cli@latest hook dispatch --source claude-code -npx -y @dotcontext/cli@latest hook dispatch --source codex +dotcontext hook dispatch --source claude-code +dotcontext hook dispatch --source codex +# ou, quando não há binário global disponível: +npx -y @dotcontext/cli@ hook dispatch --source claude-code +npx -y @dotcontext/cli@ hook dispatch --source codex ``` +Executar o binário direto (ou uma versão pinada) evita resolver a tag `latest` do npm a cada evento de SessionStart, PostToolUse e Stop. + Por padrão, a instalação de hooks é no projeto atual: ```bash diff --git a/docs/src/content/docs/pt-br/guides/using-with-hooks.md b/docs/src/content/docs/pt-br/guides/using-with-hooks.md index 0f12c02f..c2fcdfe1 100644 --- a/docs/src/content/docs/pt-br/guides/using-with-hooks.md +++ b/docs/src/content/docs/pt-br/guides/using-with-hooks.md @@ -80,7 +80,9 @@ Falhas repetidas de append trace são registradas em `.context/runtime/hooks/tra O instalador grava entradas `hooks` em `.claude/settings.json` por padrão. Cada entrada chama: ```bash -npx -y @dotcontext/cli@latest hook dispatch --source claude-code +dotcontext hook dispatch --source claude-code +# ou, quando não há binário global disponível: +npx -y @dotcontext/cli@ hook dispatch --source claude-code ``` Eventos configurados: @@ -98,7 +100,9 @@ Depois de instalar, reinicie o Claude Code. Em um projeto com `.context/` inicia Hooks do Codex usam o mesmo dispatch com `--source codex`: ```bash -npx -y @dotcontext/cli@latest hook dispatch --source codex +dotcontext hook dispatch --source codex +# ou, quando não há binário global disponível: +npx -y @dotcontext/cli@ hook dispatch --source codex ``` O instalador escreve uma destas configurações: diff --git a/src/cli/services/__tests__/hookInstallService.test.ts b/src/cli/services/__tests__/hookInstallService.test.ts index 4d9c805d..876cf398 100644 --- a/src/cli/services/__tests__/hookInstallService.test.ts +++ b/src/cli/services/__tests__/hookInstallService.test.ts @@ -7,6 +7,7 @@ import { resolveHookInstallHostSelection, } from '../hookInstallService'; import { CODEX_HOOK_TRUST_REMINDER } from '../../../integrations/codex'; +import { buildHookDispatchCommand } from '../../../integrations/shared'; import type { CLIInterface } from '../../../utils/cliUI'; const createMockUI = (): CLIInterface => ({ @@ -138,7 +139,7 @@ describe('HookInstallService', () => { const command = config.hooks.SessionStart[0].hooks[0]; expect(command.type).toBe('command'); - expect(command.command).toContain('npx -y @dotcontext/cli@latest hook dispatch --source claude-code'); + expect(command.command).toBe(buildHookDispatchCommand('claude-code')); }); it('supports dry-run mode for Claude Code', async () => { @@ -214,7 +215,7 @@ describe('HookInstallService', () => { expect(config).toContain('[features]'); expect(config).toContain('hooks = true'); expect(config).toContain('[[hooks.SessionStart]]'); - expect(config).toContain('npx -y @dotcontext/cli@latest hook dispatch --source codex'); + expect(config).toContain(buildHookDispatchCommand('codex')); }); it('prints Pi instructions and writes .mcp.json snippet', async () => { diff --git a/src/integrations/__tests__/hookInstallServices.test.ts b/src/integrations/__tests__/hookInstallServices.test.ts index af99bde6..cdd6f1d7 100644 --- a/src/integrations/__tests__/hookInstallServices.test.ts +++ b/src/integrations/__tests__/hookInstallServices.test.ts @@ -16,6 +16,7 @@ import { previewCodexHooks, } from '../codex'; import { + buildHookDispatchCommand, normalizeToolEvent, resolveHarnessHookFromHostEvent, } from '../shared'; @@ -132,7 +133,7 @@ describe('hook install services', () => { const written = await fs.readFile(configPath, 'utf8'); expect(written).toContain('[features]'); expect(written).toContain('hooks = true'); - expect(written).toContain('npx -y @dotcontext/cli@latest hook dispatch --source codex'); + expect(written).toContain(buildHookDispatchCommand('codex')); expect(written).toContain('[mcp_servers.dotcontext]'); }); @@ -192,9 +193,9 @@ describe('hook install services', () => { expect(result.action).toBe('skipped'); }); - it('upgrades legacy Claude Code hook commands to the current npx dispatch command', async () => { + it('upgrades legacy Claude Code hook commands to the current dispatch command', async () => { const configPath = path.join(tempDir, '.claude', 'settings.json'); - const legacyCommand = 'dotcontext hook dispatch --source claude-code'; + const legacyCommand = 'npx -y @dotcontext/cli@latest hook dispatch --source claude-code'; await fs.outputJson(configPath, { hooks: { SessionStart: [{ hooks: [{ type: 'command', command: legacyCommand }] }], @@ -211,19 +212,19 @@ describe('hook install services', () => { expect(result.action).toBe('updated'); const written = await fs.readJson(configPath); - expect(written.hooks.SessionStart[0].hooks[0].command).toContain( - 'npx -y @dotcontext/cli@latest hook dispatch --source claude-code' + expect(written.hooks.SessionStart[0].hooks[0].command).toBe( + buildHookDispatchCommand('claude-code') ); }); - it('upgrades legacy Codex TOML hook commands to the current npx dispatch command', async () => { + it('upgrades legacy Codex TOML hook commands to the current dispatch command', async () => { const configPath = path.join(tempDir, '.codex', 'config.toml'); await fs.outputFile( configPath, [ '[[hooks.SessionStart]]', 'matcher = "*"', - 'command = "dotcontext hook dispatch --source codex"', + 'command = "npx -y @dotcontext/cli@latest hook dispatch --source codex"', '', ].join('\n') ); @@ -237,8 +238,8 @@ describe('hook install services', () => { expect(result.action).toBe('updated'); const written = await fs.readFile(configPath, 'utf8'); - expect(written).toContain('npx -y @dotcontext/cli@latest hook dispatch --source codex'); - expect(written).not.toContain('command = "dotcontext hook dispatch --source codex"'); + expect(written).toContain(buildHookDispatchCommand('codex')); + expect(written).not.toContain('@latest'); }); it('previews Codex TOML append output', async () => { diff --git a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts index 6b527f05..58f016d6 100644 --- a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts +++ b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts @@ -1,7 +1,9 @@ import { + buildHookDispatchCommand, CLAUDE_CODE_HOOK_DISPATCH_COMMAND, isCurrentDotcontextHookDispatchCommand, isDotcontextHookDispatchCommand, + type ResolveHookDispatchCommandOptions, } from '../../shared/hookDispatchCommands'; export { CLAUDE_CODE_HOOK_DISPATCH_COMMAND }; @@ -18,35 +20,44 @@ export interface ClaudeCodeHookMatcherEntry { export type ClaudeCodeHookTemplate = ClaudeCodeHookMatcherEntry[]; +export function buildClaudeCodeHookTemplates( + command: string = buildHookDispatchCommand('claude-code') +): Record<'SessionStart' | 'PostToolUse' | 'Stop', ClaudeCodeHookTemplate> { + return { + SessionStart: [ + { + matcher: '*', + hooks: [{ type: 'command', command }], + }, + ], + PostToolUse: [ + { + matcher: '^Write$|^Edit$|^Bash$', + hooks: [{ type: 'command', command }], + }, + ], + Stop: [ + { + hooks: [{ type: 'command', command }], + }, + ], + }; +} + +/** + * Static template shape built with the pinned npx command. Prefer + * buildClaudeCodeHookTemplates() when writing configs so the command can + * resolve to the local dotcontext binary when it is available. + */ export const CLAUDE_CODE_HOOK_TEMPLATES: Record< 'SessionStart' | 'PostToolUse' | 'Stop', ClaudeCodeHookTemplate -> = { - SessionStart: [ - { - matcher: '*', - hooks: [{ type: 'command', command: CLAUDE_CODE_HOOK_DISPATCH_COMMAND }], - }, - ], - PostToolUse: [ - { - matcher: '^Write$|^Edit$|^Bash$', - hooks: [{ type: 'command', command: CLAUDE_CODE_HOOK_DISPATCH_COMMAND }], - }, - ], - Stop: [ - { - hooks: [{ type: 'command', command: CLAUDE_CODE_HOOK_DISPATCH_COMMAND }], - }, - ], -}; - -export function buildClaudeCodeHooksFragment(): Record { - return { - SessionStart: CLAUDE_CODE_HOOK_TEMPLATES.SessionStart, - PostToolUse: CLAUDE_CODE_HOOK_TEMPLATES.PostToolUse, - Stop: CLAUDE_CODE_HOOK_TEMPLATES.Stop, - }; +> = buildClaudeCodeHookTemplates(CLAUDE_CODE_HOOK_DISPATCH_COMMAND); + +export function buildClaudeCodeHooksFragment( + options?: ResolveHookDispatchCommandOptions +): Record { + return buildClaudeCodeHookTemplates(buildHookDispatchCommand('claude-code', options)); } export function isDotcontextClaudeCodeHookCommand(command: unknown): boolean { diff --git a/src/integrations/claude-code/hooks/index.ts b/src/integrations/claude-code/hooks/index.ts index 5681fee9..3328807e 100644 --- a/src/integrations/claude-code/hooks/index.ts +++ b/src/integrations/claude-code/hooks/index.ts @@ -19,5 +19,6 @@ export { export { CLAUDE_CODE_HOOK_TEMPLATES, CLAUDE_CODE_HOOK_DISPATCH_COMMAND, + buildClaudeCodeHookTemplates, buildClaudeCodeHooksFragment, } from './claudeCodeHookTemplates'; diff --git a/src/integrations/codex/hooks/codexHookTemplates.ts b/src/integrations/codex/hooks/codexHookTemplates.ts index 7ad617ea..d5bf963b 100644 --- a/src/integrations/codex/hooks/codexHookTemplates.ts +++ b/src/integrations/codex/hooks/codexHookTemplates.ts @@ -1,7 +1,9 @@ import { + buildHookDispatchCommand, CODEX_HOOK_DISPATCH_COMMAND, isCurrentDotcontextHookDispatchCommand, isDotcontextHookDispatchCommand, + type ResolveHookDispatchCommandOptions, } from '../../shared/hookDispatchCommands'; export { CODEX_HOOK_DISPATCH_COMMAND }; @@ -18,40 +20,51 @@ export interface CodexHookMatcherEntry { export type CodexHookTemplate = CodexHookMatcherEntry[]; +export function buildCodexHookTemplates( + command: string = buildHookDispatchCommand('codex') +): Record<'SessionStart' | 'PostToolUse' | 'Stop', CodexHookTemplate> { + return { + SessionStart: [ + { + matcher: '*', + hooks: [{ type: 'command', command }], + }, + ], + PostToolUse: [ + { + matcher: '^Write$|^Edit$|^Bash$', + hooks: [{ type: 'command', command }], + }, + ], + Stop: [ + { + matcher: '*', + hooks: [{ type: 'command', command }], + }, + ], + }; +} + +/** + * Static template shape built with the pinned npx command. Prefer + * buildCodexHookTemplates() when writing configs so the command can resolve + * to the local dotcontext binary when it is available. + */ export const CODEX_HOOK_TEMPLATES: Record< 'SessionStart' | 'PostToolUse' | 'Stop', CodexHookTemplate -> = { - SessionStart: [ - { - matcher: '*', - hooks: [{ type: 'command', command: CODEX_HOOK_DISPATCH_COMMAND }], - }, - ], - PostToolUse: [ - { - matcher: '^Write$|^Edit$|^Bash$', - hooks: [{ type: 'command', command: CODEX_HOOK_DISPATCH_COMMAND }], - }, - ], - Stop: [ - { - matcher: '*', - hooks: [{ type: 'command', command: CODEX_HOOK_DISPATCH_COMMAND }], - }, - ], -}; - -export function buildCodexHooksFragment(): Record { - return { - SessionStart: CODEX_HOOK_TEMPLATES.SessionStart, - PostToolUse: CODEX_HOOK_TEMPLATES.PostToolUse, - Stop: CODEX_HOOK_TEMPLATES.Stop, - }; +> = buildCodexHookTemplates(CODEX_HOOK_DISPATCH_COMMAND); + +export function buildCodexHooksFragment( + options?: ResolveHookDispatchCommandOptions +): Record { + return buildCodexHookTemplates(buildHookDispatchCommand('codex', options)); } -export function buildCodexHooksDocument(): { hooks: Record } { - return { hooks: buildCodexHooksFragment() }; +export function buildCodexHooksDocument( + options?: ResolveHookDispatchCommandOptions +): { hooks: Record } { + return { hooks: buildCodexHooksFragment(options) }; } export function isDotcontextCodexHookCommand(command: unknown): boolean { @@ -64,6 +77,7 @@ export function isCurrentCodexHookCommand(command: unknown): boolean { export interface BuildCodexTomlHookBlocksOptions { includeFeatures?: boolean; + command?: ResolveHookDispatchCommandOptions; } export function buildCodexTomlHookBlocks( @@ -75,7 +89,11 @@ export function buildCodexTomlHookBlocks( lines.push('[features]', 'hooks = true', ''); } - for (const [eventName, entries] of Object.entries(CODEX_HOOK_TEMPLATES)) { + const templates = buildCodexHookTemplates( + buildHookDispatchCommand('codex', options.command) + ); + + for (const [eventName, entries] of Object.entries(templates)) { for (const entry of entries) { lines.push(`[[hooks.${eventName}]]`); if (entry.matcher) { diff --git a/src/integrations/codex/hooks/index.ts b/src/integrations/codex/hooks/index.ts index 038ec197..09d63866 100644 --- a/src/integrations/codex/hooks/index.ts +++ b/src/integrations/codex/hooks/index.ts @@ -20,6 +20,7 @@ export { CODEX_HOOK_TEMPLATES, CODEX_HOOK_DISPATCH_COMMAND, CODEX_HOOK_TRUST_REMINDER, + buildCodexHookTemplates, buildCodexHooksDocument, buildCodexTomlHookBlocks, } from './codexHookTemplates'; diff --git a/src/integrations/shared/__tests__/hookDispatchCommands.test.ts b/src/integrations/shared/__tests__/hookDispatchCommands.test.ts new file mode 100644 index 00000000..ed7f619a --- /dev/null +++ b/src/integrations/shared/__tests__/hookDispatchCommands.test.ts @@ -0,0 +1,114 @@ +import * as fs from 'fs-extra'; +import * as os from 'os'; +import * as path from 'path'; + +import { + buildHookDispatchCommand, + CLAUDE_CODE_HOOK_DISPATCH_COMMAND, + CODEX_HOOK_DISPATCH_COMMAND, + getCanonicalHookDispatchCommands, + HOOK_DISPATCH_LOCAL_CLI, + HOOK_DISPATCH_PINNED_CLI, + isCurrentDotcontextHookDispatchCommand, + isDotcontextBinaryOnPath, + resolveHookDispatchCli, +} from '../hookDispatchCommands'; +import { VERSION } from '../../../version'; + +describe('hookDispatchCommands', () => { + let tempDir: string; + + beforeEach(async () => { + tempDir = await fs.mkdtemp(path.join(os.tmpdir(), 'dotcontext-dispatch-cmd-')); + }); + + afterEach(async () => { + await fs.remove(tempDir); + }); + + it('pins the npx fallback to the installed CLI version instead of @latest', () => { + expect(HOOK_DISPATCH_PINNED_CLI).toBe(`npx -y @dotcontext/cli@${VERSION} hook dispatch`); + expect(CLAUDE_CODE_HOOK_DISPATCH_COMMAND).not.toContain('@latest'); + expect(CODEX_HOOK_DISPATCH_COMMAND).not.toContain('@latest'); + }); + + describe('isDotcontextBinaryOnPath', () => { + it('detects a dotcontext executable on PATH', async () => { + await fs.outputFile(path.join(tempDir, 'dotcontext'), '#!/bin/sh\n'); + + expect(isDotcontextBinaryOnPath({ + env: { PATH: tempDir }, + platform: 'linux', + })).toBe(true); + }); + + it('detects Windows launcher variants', async () => { + await fs.outputFile(path.join(tempDir, 'dotcontext.cmd'), '@echo off\n'); + + expect(isDotcontextBinaryOnPath({ + env: { PATH: tempDir }, + platform: 'win32', + })).toBe(true); + }); + + it('returns false when the binary is absent', () => { + expect(isDotcontextBinaryOnPath({ + env: { PATH: tempDir }, + platform: 'linux', + })).toBe(false); + }); + + it('ignores directories that match the binary name', async () => { + await fs.ensureDir(path.join(tempDir, 'dotcontext')); + + expect(isDotcontextBinaryOnPath({ + env: { PATH: tempDir }, + platform: 'linux', + })).toBe(false); + }); + }); + + describe('resolveHookDispatchCli / buildHookDispatchCommand', () => { + it('prefers the local binary when it is on PATH', async () => { + await fs.outputFile(path.join(tempDir, 'dotcontext'), '#!/bin/sh\n'); + const options = { env: { PATH: tempDir }, platform: 'linux' as const }; + + expect(resolveHookDispatchCli(options)).toBe(HOOK_DISPATCH_LOCAL_CLI); + expect(buildHookDispatchCommand('claude-code', options)).toBe( + `${HOOK_DISPATCH_LOCAL_CLI} --source claude-code` + ); + }); + + it('falls back to the pinned npx command when the binary is absent', () => { + const options = { env: { PATH: tempDir }, platform: 'linux' as const }; + + expect(resolveHookDispatchCli(options)).toBe(HOOK_DISPATCH_PINNED_CLI); + expect(buildHookDispatchCommand('codex', options)).toBe( + `${HOOK_DISPATCH_PINNED_CLI} --source codex` + ); + }); + }); + + describe('isCurrentDotcontextHookDispatchCommand', () => { + it('accepts both canonical command forms', () => { + for (const command of getCanonicalHookDispatchCommands('claude-code')) { + expect(isCurrentDotcontextHookDispatchCommand(command, 'claude-code')).toBe(true); + } + }); + + it('rejects the legacy @latest command so installs upgrade it', () => { + expect(isCurrentDotcontextHookDispatchCommand( + 'npx -y @dotcontext/cli@latest hook dispatch --source claude-code', + 'claude-code' + )).toBe(false); + }); + + it('rejects commands for another source and non-strings', () => { + expect(isCurrentDotcontextHookDispatchCommand( + `${HOOK_DISPATCH_LOCAL_CLI} --source codex`, + 'claude-code' + )).toBe(false); + expect(isCurrentDotcontextHookDispatchCommand(undefined, 'codex')).toBe(false); + }); + }); +}); diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 795881b7..3115bb52 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -11,11 +11,14 @@ import { ensureHookHarnessSession, getHookHarnessSessionId, } from '../hookSessionStore'; +import { VERSION } from '../../../version'; describe('hookDispatchCommands', () => { - it('uses npx for shell hook dispatch', () => { - expect(CLAUDE_CODE_HOOK_DISPATCH_COMMAND).toContain('npx -y @dotcontext/cli@latest'); - expect(CODEX_HOOK_DISPATCH_COMMAND).toContain('npx -y @dotcontext/cli@latest'); + it('pins the npx dispatch command to the installed CLI version', () => { + expect(CLAUDE_CODE_HOOK_DISPATCH_COMMAND).toContain(`npx -y @dotcontext/cli@${VERSION}`); + expect(CODEX_HOOK_DISPATCH_COMMAND).toContain(`npx -y @dotcontext/cli@${VERSION}`); + expect(CLAUDE_CODE_HOOK_DISPATCH_COMMAND).not.toContain('@latest'); + expect(CODEX_HOOK_DISPATCH_COMMAND).not.toContain('@latest'); }); }); diff --git a/src/integrations/shared/hookDispatchCommands.ts b/src/integrations/shared/hookDispatchCommands.ts index 197c5a4f..13970009 100644 --- a/src/integrations/shared/hookDispatchCommands.ts +++ b/src/integrations/shared/hookDispatchCommands.ts @@ -1,14 +1,117 @@ -export const HOOK_DISPATCH_CLI = 'npx -y @dotcontext/cli@latest hook dispatch'; +import * as fs from 'fs'; +import * as path from 'path'; + +import { VERSION } from '../../version'; + +export type HookDispatchCommandSource = 'claude-code' | 'codex'; + +export const HOOK_DISPATCH_BINARY_NAME = 'dotcontext'; + +/** + * Dispatch command used when a `dotcontext` executable is available on PATH. + * Invoking the binary directly avoids spawning npx (and re-resolving the + * package) on every host lifecycle event. + */ +export const HOOK_DISPATCH_LOCAL_CLI = `${HOOK_DISPATCH_BINARY_NAME} hook dispatch`; + +/** + * Fallback dispatch command pinned to the version of the CLI that performed + * the install. Pinning avoids re-resolving the `latest` dist-tag from the npm + * registry on every hook invocation, which adds startup latency and registry + * traffic to every SessionStart/PostToolUse/Stop event. + */ +export const HOOK_DISPATCH_PINNED_CLI = `npx -y @dotcontext/cli@${VERSION} hook dispatch`; + +export const HOOK_DISPATCH_CLI = HOOK_DISPATCH_PINNED_CLI; export const CLAUDE_CODE_HOOK_DISPATCH_COMMAND = - `${HOOK_DISPATCH_CLI} --source claude-code`; + `${HOOK_DISPATCH_PINNED_CLI} --source claude-code`; export const CODEX_HOOK_DISPATCH_COMMAND = - `${HOOK_DISPATCH_CLI} --source codex`; + `${HOOK_DISPATCH_PINNED_CLI} --source codex`; + +export interface ResolveHookDispatchCommandOptions { + env?: NodeJS.ProcessEnv; + platform?: NodeJS.Platform; +} + +function candidateBinaryNames(platform: NodeJS.Platform): string[] { + if (platform === 'win32') { + return [ + `${HOOK_DISPATCH_BINARY_NAME}.cmd`, + `${HOOK_DISPATCH_BINARY_NAME}.exe`, + `${HOOK_DISPATCH_BINARY_NAME}.bat`, + HOOK_DISPATCH_BINARY_NAME, + ]; + } + + return [HOOK_DISPATCH_BINARY_NAME]; +} + +/** + * Detects a globally installed `dotcontext` executable by scanning PATH. + * Detection is filesystem-only so install stays fast and side-effect free. + */ +export function isDotcontextBinaryOnPath( + options: ResolveHookDispatchCommandOptions = {} +): boolean { + const env = options.env ?? process.env; + const platform = options.platform ?? process.platform; + const pathValue = env.PATH ?? env.Path ?? ''; + const directories = pathValue.split(path.delimiter).filter(Boolean); + const names = candidateBinaryNames(platform); + + for (const directory of directories) { + for (const name of names) { + try { + if (fs.statSync(path.join(directory, name)).isFile()) { + return true; + } + } catch { + // Missing or unreadable entries are expected while scanning PATH. + } + } + } + + return false; +} + +export function resolveHookDispatchCli( + options: ResolveHookDispatchCommandOptions = {} +): string { + return isDotcontextBinaryOnPath(options) + ? HOOK_DISPATCH_LOCAL_CLI + : HOOK_DISPATCH_PINNED_CLI; +} + +/** + * Resolves the dispatch command persisted into host hook configs. + * Prefers the local binary; falls back to version-pinned npx. + */ +export function buildHookDispatchCommand( + source: HookDispatchCommandSource, + options: ResolveHookDispatchCommandOptions = {} +): string { + return `${resolveHookDispatchCli(options)} --source ${source}`; +} + +/** + * Both command forms considered current for this CLI version. Configs using + * either form are treated as up to date so installs do not churn between the + * local-binary and pinned-npx variants when the environment changes. + */ +export function getCanonicalHookDispatchCommands( + source: HookDispatchCommandSource +): string[] { + return [ + `${HOOK_DISPATCH_LOCAL_CLI} --source ${source}`, + `${HOOK_DISPATCH_PINNED_CLI} --source ${source}`, + ]; +} export function isDotcontextHookDispatchCommand( command: unknown, - source: 'claude-code' | 'codex' + source: HookDispatchCommandSource ): boolean { if (typeof command !== 'string') { return false; @@ -20,11 +123,11 @@ export function isDotcontextHookDispatchCommand( export function isCurrentDotcontextHookDispatchCommand( command: unknown, - source: 'claude-code' | 'codex' + source: HookDispatchCommandSource ): boolean { - const expected = source === 'claude-code' - ? CLAUDE_CODE_HOOK_DISPATCH_COMMAND - : CODEX_HOOK_DISPATCH_COMMAND; + if (typeof command !== 'string') { + return false; + } - return command === expected; + return getCanonicalHookDispatchCommands(source).includes(command); } diff --git a/src/integrations/shared/index.ts b/src/integrations/shared/index.ts index a9b9a458..e3f15613 100644 --- a/src/integrations/shared/index.ts +++ b/src/integrations/shared/index.ts @@ -35,11 +35,20 @@ export { } from './mapHostHookResponse'; export { + HOOK_DISPATCH_BINARY_NAME, HOOK_DISPATCH_CLI, + HOOK_DISPATCH_LOCAL_CLI, + HOOK_DISPATCH_PINNED_CLI, CLAUDE_CODE_HOOK_DISPATCH_COMMAND, CODEX_HOOK_DISPATCH_COMMAND, + buildHookDispatchCommand, + getCanonicalHookDispatchCommands, + isDotcontextBinaryOnPath, isDotcontextHookDispatchCommand, isCurrentDotcontextHookDispatchCommand, + resolveHookDispatchCli, + type HookDispatchCommandSource, + type ResolveHookDispatchCommandOptions, } from './hookDispatchCommands'; export { From d5761333ff787f1ed794b07985274b53a9c3b8d5 Mon Sep 17 00:00:00 2001 From: Lorran Hippolyte Date: Fri, 10 Jul 2026 11:25:07 -0300 Subject: [PATCH 2/4] fix: address review findings on hook dispatch command resolution - Require execute permission (X_OK) on POSIX before treating a PATH entry named dotcontext as an installed binary, so a stray non-executable file cannot cause the installer to persist a dispatch command that fails at runtime. - Treat the local-binary dispatch command as current only while the binary is actually on PATH; the pinned-npx form stays always current. Re-running the installer now repairs configs left behind by a global uninstall instead of skipping them as up to date. - Rename BuildCodexTomlHookBlocksOptions.command to resolveOptions so the property does not read as the command string itself. Co-Authored-By: Claude Fable 5 --- .../hooks/claudeCodeHookTemplates.ts | 7 ++- .../codex/hooks/codexHookTemplates.ts | 11 +++-- .../__tests__/hookDispatchCommands.test.ts | 48 +++++++++++++++++-- .../shared/hookDispatchCommands.ts | 47 +++++++++++++----- 4 files changed, 92 insertions(+), 21 deletions(-) diff --git a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts index 58f016d6..ca4e764a 100644 --- a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts +++ b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts @@ -64,6 +64,9 @@ export function isDotcontextClaudeCodeHookCommand(command: unknown): boolean { return isDotcontextHookDispatchCommand(command, 'claude-code'); } -export function isCurrentClaudeCodeHookCommand(command: unknown): boolean { - return isCurrentDotcontextHookDispatchCommand(command, 'claude-code'); +export function isCurrentClaudeCodeHookCommand( + command: unknown, + options?: ResolveHookDispatchCommandOptions +): boolean { + return isCurrentDotcontextHookDispatchCommand(command, 'claude-code', options); } diff --git a/src/integrations/codex/hooks/codexHookTemplates.ts b/src/integrations/codex/hooks/codexHookTemplates.ts index d5bf963b..7216841a 100644 --- a/src/integrations/codex/hooks/codexHookTemplates.ts +++ b/src/integrations/codex/hooks/codexHookTemplates.ts @@ -71,13 +71,16 @@ export function isDotcontextCodexHookCommand(command: unknown): boolean { return isDotcontextHookDispatchCommand(command, 'codex'); } -export function isCurrentCodexHookCommand(command: unknown): boolean { - return isCurrentDotcontextHookDispatchCommand(command, 'codex'); +export function isCurrentCodexHookCommand( + command: unknown, + options?: ResolveHookDispatchCommandOptions +): boolean { + return isCurrentDotcontextHookDispatchCommand(command, 'codex', options); } export interface BuildCodexTomlHookBlocksOptions { includeFeatures?: boolean; - command?: ResolveHookDispatchCommandOptions; + resolveOptions?: ResolveHookDispatchCommandOptions; } export function buildCodexTomlHookBlocks( @@ -90,7 +93,7 @@ export function buildCodexTomlHookBlocks( } const templates = buildCodexHookTemplates( - buildHookDispatchCommand('codex', options.command) + buildHookDispatchCommand('codex', options.resolveOptions) ); for (const [eventName, entries] of Object.entries(templates)) { diff --git a/src/integrations/shared/__tests__/hookDispatchCommands.test.ts b/src/integrations/shared/__tests__/hookDispatchCommands.test.ts index ed7f619a..aded8cfb 100644 --- a/src/integrations/shared/__tests__/hookDispatchCommands.test.ts +++ b/src/integrations/shared/__tests__/hookDispatchCommands.test.ts @@ -34,7 +34,9 @@ describe('hookDispatchCommands', () => { describe('isDotcontextBinaryOnPath', () => { it('detects a dotcontext executable on PATH', async () => { - await fs.outputFile(path.join(tempDir, 'dotcontext'), '#!/bin/sh\n'); + const binaryPath = path.join(tempDir, 'dotcontext'); + await fs.outputFile(binaryPath, '#!/bin/sh\n'); + await fs.chmod(binaryPath, 0o755); expect(isDotcontextBinaryOnPath({ env: { PATH: tempDir }, @@ -42,6 +44,17 @@ describe('hookDispatchCommands', () => { })).toBe(true); }); + it('ignores a non-executable file named dotcontext on POSIX', async () => { + const binaryPath = path.join(tempDir, 'dotcontext'); + await fs.outputFile(binaryPath, 'not a binary\n'); + await fs.chmod(binaryPath, 0o644); + + expect(isDotcontextBinaryOnPath({ + env: { PATH: tempDir }, + platform: 'linux', + })).toBe(false); + }); + it('detects Windows launcher variants', async () => { await fs.outputFile(path.join(tempDir, 'dotcontext.cmd'), '@echo off\n'); @@ -70,7 +83,9 @@ describe('hookDispatchCommands', () => { describe('resolveHookDispatchCli / buildHookDispatchCommand', () => { it('prefers the local binary when it is on PATH', async () => { - await fs.outputFile(path.join(tempDir, 'dotcontext'), '#!/bin/sh\n'); + const binaryPath = path.join(tempDir, 'dotcontext'); + await fs.outputFile(binaryPath, '#!/bin/sh\n'); + await fs.chmod(binaryPath, 0o755); const options = { env: { PATH: tempDir }, platform: 'linux' as const }; expect(resolveHookDispatchCli(options)).toBe(HOOK_DISPATCH_LOCAL_CLI); @@ -90,12 +105,37 @@ describe('hookDispatchCommands', () => { }); describe('isCurrentDotcontextHookDispatchCommand', () => { - it('accepts both canonical command forms', () => { + it('accepts both canonical command forms when the binary is on PATH', async () => { + const binaryPath = path.join(tempDir, 'dotcontext'); + await fs.outputFile(binaryPath, '#!/bin/sh\n'); + await fs.chmod(binaryPath, 0o755); + const options = { env: { PATH: tempDir }, platform: 'linux' as const }; + for (const command of getCanonicalHookDispatchCommands('claude-code')) { - expect(isCurrentDotcontextHookDispatchCommand(command, 'claude-code')).toBe(true); + expect(isCurrentDotcontextHookDispatchCommand(command, 'claude-code', options)).toBe(true); } }); + it('treats the pinned form as current even without the binary on PATH', () => { + const options = { env: { PATH: tempDir }, platform: 'linux' as const }; + + expect(isCurrentDotcontextHookDispatchCommand( + `${HOOK_DISPATCH_PINNED_CLI} --source claude-code`, + 'claude-code', + options + )).toBe(true); + }); + + it('treats the local-binary form as stale when the binary left PATH', () => { + const options = { env: { PATH: tempDir }, platform: 'linux' as const }; + + expect(isCurrentDotcontextHookDispatchCommand( + `${HOOK_DISPATCH_LOCAL_CLI} --source claude-code`, + 'claude-code', + options + )).toBe(false); + }); + it('rejects the legacy @latest command so installs upgrade it', () => { expect(isCurrentDotcontextHookDispatchCommand( 'npx -y @dotcontext/cli@latest hook dispatch --source claude-code', diff --git a/src/integrations/shared/hookDispatchCommands.ts b/src/integrations/shared/hookDispatchCommands.ts index 13970009..d4e147f3 100644 --- a/src/integrations/shared/hookDispatchCommands.ts +++ b/src/integrations/shared/hookDispatchCommands.ts @@ -48,6 +48,26 @@ function candidateBinaryNames(platform: NodeJS.Platform): string[] { return [HOOK_DISPATCH_BINARY_NAME]; } +function isExecutableFile(filePath: string, platform: NodeJS.Platform): boolean { + try { + if (!fs.statSync(filePath).isFile()) { + return false; + } + + if (platform !== 'win32') { + // A regular file named dotcontext is not enough: hooks invoke it + // directly, so it must carry execute permission for this process. + fs.accessSync(filePath, fs.constants.X_OK); + } + + return true; + } catch { + // Missing, unreadable, or non-executable entries are expected while + // scanning PATH. + return false; + } +} + /** * Detects a globally installed `dotcontext` executable by scanning PATH. * Detection is filesystem-only so install stays fast and side-effect free. @@ -63,12 +83,8 @@ export function isDotcontextBinaryOnPath( for (const directory of directories) { for (const name of names) { - try { - if (fs.statSync(path.join(directory, name)).isFile()) { - return true; - } - } catch { - // Missing or unreadable entries are expected while scanning PATH. + if (isExecutableFile(path.join(directory, name), platform)) { + return true; } } } @@ -96,9 +112,9 @@ export function buildHookDispatchCommand( } /** - * Both command forms considered current for this CLI version. Configs using - * either form are treated as up to date so installs do not churn between the - * local-binary and pinned-npx variants when the environment changes. + * Both command forms recognized for this CLI version. The pinned-npx form is + * always current; the local-binary form is only current while a `dotcontext` + * executable is on PATH (see isCurrentDotcontextHookDispatchCommand). */ export function getCanonicalHookDispatchCommands( source: HookDispatchCommandSource @@ -123,11 +139,20 @@ export function isDotcontextHookDispatchCommand( export function isCurrentDotcontextHookDispatchCommand( command: unknown, - source: HookDispatchCommandSource + source: HookDispatchCommandSource, + options: ResolveHookDispatchCommandOptions = {} ): boolean { if (typeof command !== 'string') { return false; } - return getCanonicalHookDispatchCommands(source).includes(command); + if (command === `${HOOK_DISPATCH_PINNED_CLI} --source ${source}`) { + return true; + } + + // The local-binary form is only current while the binary is actually on + // PATH; otherwise re-running the installer must repair the config instead + // of skipping it as up to date. + return command === `${HOOK_DISPATCH_LOCAL_CLI} --source ${source}` + && isDotcontextBinaryOnPath(options); } From 8e501b8a39d15757a387db97e1024c1c6ebc4106 Mon Sep 17 00:00:00 2001 From: Lorran Hippolyte Date: Wed, 8 Jul 2026 19:29:20 -0300 Subject: [PATCH 3/4] fix: complete hook harness sessions at session end and sweep stale bindings MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit SessionStart created a durable harness session and bound it in host-sessions.json, but nothing ever completed it: the Stop dispatch only calls workflow-guide (and in Claude Code, Stop fires per response turn, not at session end), and bindings were never removed. Every host session left a forever-active session under .context/runtime/sessions/ and a permanent binding entry. The Claude Code template now wires SessionEnd, and dispatch completes the bound harness session and removes its binding on that event — non-blocking, and the binding is removed even when completion fails. SessionStart additionally sweeps bindings untouched for 24h, covering host sessions that ended without SessionEnd (crash, closed terminal, hosts without a session-end event). Binding reuse now touches updatedAt so resumed sessions are never treated as stale. Co-Authored-By: Claude Fable 5 --- .../docs/en/guides/using-with-hooks.md | 3 + .../docs/pt-br/guides/hook-session-flow.md | 3 +- .../docs/pt-br/guides/using-with-hooks.md | 3 + .../__tests__/hookDispatchService.test.ts | 188 ++++++++++++++++++ src/cli/services/hookDispatchService.ts | 39 +++- .../hooks/claudeCodeHookTemplates.ts | 9 +- .../shared/__tests__/hookSessionStore.test.ts | 144 ++++++++++++++ src/integrations/shared/hookSessionStore.ts | 154 +++++++++++++- src/integrations/shared/index.ts | 6 + 9 files changed, 538 insertions(+), 11 deletions(-) diff --git a/docs/src/content/docs/en/guides/using-with-hooks.md b/docs/src/content/docs/en/guides/using-with-hooks.md index 33edbc87..18ef1526 100644 --- a/docs/src/content/docs/en/guides/using-with-hooks.md +++ b/docs/src/content/docs/en/guides/using-with-hooks.md @@ -107,6 +107,9 @@ Wired events (v1): | `SessionStart` | `*` | | `PostToolUse` | `^Write$\|^Edit$\|^Bash$` | | `Stop` | `*` | +| `SessionEnd` | `*` | + +On `SessionEnd`, the dispatch completes the harness session bound to the host session and removes its binding, so `.context/runtime/sessions/` entries do not stay open forever. `SessionStart` also sweeps bindings older than 24 hours from host sessions that ended without a `SessionEnd` (crash, closed terminal). After install, restart Claude Code. On the next session start in a repo with `.context/`, you should see a compact bootstrap message injected into context. diff --git a/docs/src/content/docs/pt-br/guides/hook-session-flow.md b/docs/src/content/docs/pt-br/guides/hook-session-flow.md index d2e289a9..9b1ac9be 100644 --- a/docs/src/content/docs/pt-br/guides/hook-session-flow.md +++ b/docs/src/content/docs/pt-br/guides/hook-session-flow.md @@ -53,7 +53,8 @@ Use `--global` somente quando quiser escrever a configuração no diretório hom | Início da sessão | `SessionStart` | `context check` | Injeta readiness de `.context/`, ou uma dica de inicialização | | Início da sessão com contexto pronto | `SessionStart` | `harness createSession` + `context getMap` | Cria uma sessão durável e adiciona navegação compacta | | Depois de ferramenta | `PostToolUse` para `Write`, `Edit`, `Bash` | `harness appendTrace` | Registra `tool.use` em `trace.jsonl` | -| Fim da sessão | `Stop` | `workflow-guide` | Mostra próximos passos PREVC somente se há workflow ativo | +| Fim da resposta | `Stop` | `workflow-guide` | Mostra próximos passos PREVC somente se há workflow ativo | +| Fim da sessão | `SessionEnd` | `harness completeSession` + remoção do binding | Conclui a sessão durável do harness e limpa `host-sessions.json` | No fluxo padrão, hooks são não bloqueantes. Erro de trace, workflow ausente ou chamada reentrante de fim de sessão vira `{"continue": true}` para não quebrar a sessão do agente. diff --git a/docs/src/content/docs/pt-br/guides/using-with-hooks.md b/docs/src/content/docs/pt-br/guides/using-with-hooks.md index c2fcdfe1..759de810 100644 --- a/docs/src/content/docs/pt-br/guides/using-with-hooks.md +++ b/docs/src/content/docs/pt-br/guides/using-with-hooks.md @@ -92,6 +92,9 @@ Eventos configurados: | `SessionStart` | `*` | | `PostToolUse` | `^Write$\|^Edit$\|^Bash$` | | `Stop` | `*` | +| `SessionEnd` | `*` | + +No `SessionEnd`, o dispatch conclui a sessão do harness vinculada à sessão do host e remove o binding, para que entradas em `.context/runtime/sessions/` não fiquem abertas para sempre. O `SessionStart` também varre bindings com mais de 24 horas de sessões que terminaram sem `SessionEnd` (crash, terminal fechado). Depois de instalar, reinicie o Claude Code. Em um projeto com `.context/` inicializado, o próximo `SessionStart` deve injetar um resumo compacto de contexto. diff --git a/src/cli/services/__tests__/hookDispatchService.test.ts b/src/cli/services/__tests__/hookDispatchService.test.ts index 44525835..b77a54c3 100644 --- a/src/cli/services/__tests__/hookDispatchService.test.ts +++ b/src/cli/services/__tests__/hookDispatchService.test.ts @@ -6,6 +6,7 @@ import { PassThrough } from 'stream'; import { runHookDispatch } from '../hookDispatchService'; import { getHookHarnessSessionId, + listHookHarnessSessionBindings, saveHookHarnessSession, } from '../../../integrations/shared/hookSessionStore'; import { WorkflowService } from '../../../harness'; @@ -683,4 +684,191 @@ describe('HookDispatchService session lifecycle', () => { expect(stopResult.exitCode).toBe(0); expect(stopResult.output).toEqual({ continue: true }); }); + + it('completes the bound harness session on SessionEnd and removes the binding', async () => { + await createReadyContext(); + const sessionId = 'host-session-end'; + + const startStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'SessionStart', + }), + ]); + const startStdout = new PassThrough(); + startStdout.on('data', () => {}); + await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: startStdin, + stdout: startStdout, + }); + + const harnessSessionId = await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: sessionId, + }); + expect(harnessSessionId).toBeDefined(); + + const endStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'SessionEnd', + reason: 'exit', + }), + ]); + const endStdout = new PassThrough(); + endStdout.on('data', () => {}); + + const endResult = await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: endStdin, + stdout: endStdout, + }); + + expect(endResult.exitCode).toBe(0); + expect(endResult.output).toEqual({ continue: true }); + + const session = await fs.readJson(path.join( + tempDir, '.context', 'runtime', 'sessions', harnessSessionId!, 'session.json' + )); + expect(session.status).toBe('completed'); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: sessionId, + })).toBeUndefined(); + }); + + it('keeps SessionEnd non-blocking when no binding exists', async () => { + const endStdin = PassThrough.from([ + JSON.stringify({ + session_id: 'host-session-end-unbound', + cwd: tempDir, + hook_event_name: 'SessionEnd', + }), + ]); + const endStdout = new PassThrough(); + endStdout.on('data', () => {}); + + const endResult = await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: endStdin, + stdout: endStdout, + }); + + expect(endResult.exitCode).toBe(0); + expect(endResult.output).toEqual({ continue: true }); + }); + + it('does not complete the session during SessionEnd reentry', async () => { + await createReadyContext(); + const sessionId = 'host-session-end-reentry'; + + const startStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'SessionStart', + }), + ]); + const startStdout = new PassThrough(); + startStdout.on('data', () => {}); + await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: startStdin, + stdout: startStdout, + }); + + const endStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'SessionEnd', + session_end_active: true, + }), + ]); + const endStdout = new PassThrough(); + endStdout.on('data', () => {}); + + const endResult = await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: endStdin, + stdout: endStdout, + }); + + expect(endResult.exitCode).toBe(0); + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: sessionId, + })).toBeDefined(); + }); + + it('sweeps stale bindings from previous host sessions on SessionStart', async () => { + await createReadyContext(); + + const staleStdin = PassThrough.from([ + JSON.stringify({ + session_id: 'host-session-stale', + cwd: tempDir, + hook_event_name: 'SessionStart', + }), + ]); + const staleStdout = new PassThrough(); + staleStdout.on('data', () => {}); + await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: staleStdin, + stdout: staleStdout, + }); + + const staleHarnessSessionId = await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'host-session-stale', + }); + + const [staleBinding] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + await saveHookHarnessSession({ + ...staleBinding, + updatedAt: new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(), + }); + + const startStdin = PassThrough.from([ + JSON.stringify({ + session_id: 'host-session-new', + cwd: tempDir, + hook_event_name: 'SessionStart', + }), + ]); + const startStdout = new PassThrough(); + startStdout.on('data', () => {}); + await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: startStdin, + stdout: startStdout, + }); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'host-session-stale', + })).toBeUndefined(); + + const staleSession = await fs.readJson(path.join( + tempDir, '.context', 'runtime', 'sessions', staleHarnessSessionId!, 'session.json' + )); + expect(staleSession.status).toBe('completed'); + }); }); diff --git a/src/cli/services/hookDispatchService.ts b/src/cli/services/hookDispatchService.ts index 9b65fc6c..c5bd9f12 100644 --- a/src/cli/services/hookDispatchService.ts +++ b/src/cli/services/hookDispatchService.ts @@ -16,6 +16,7 @@ import type { ClaudeCodeHookInput } from '../../integrations/claude-code/hooks/m import { mapCodexResponse } from '../../integrations/codex/hooks/mapCodexResponse'; import type { CodexHookInput } from '../../integrations/codex/hooks/mapCodexEvent'; import { + completeHookHarnessSession, ensureHookHarnessSession, extractHarnessSessionId, finalizeHostHookOutput, @@ -25,6 +26,7 @@ import { resolveHookRepoRoot, resolveHarnessHookFromHostEvent, saveHookHarnessSession, + sweepStaleHookHarnessSessions, type HostHookOutput, } from '../../integrations/shared'; import { formatNavigationExcerpt } from '../../integrations/shared/formatNavigationExcerpt'; @@ -101,6 +103,9 @@ function canonicalizeHookEventName(hookEventName?: string): string | undefined { case 'subagentstop': case 'subagent_stop': return 'SubagentStop'; + case 'sessionend': + case 'session_end': + return 'SessionEnd'; default: return hookEventName; } @@ -304,7 +309,10 @@ async function dispatchShellHookEvent( throw new Error('Hook dispatch requires hook_event_name'); } - if ((hookEventName === 'Stop' || hookEventName === 'SubagentStop') && isSessionEndReentry(envelope)) { + if ( + (hookEventName === 'Stop' || hookEventName === 'SubagentStop' || hookEventName === 'SessionEnd') + && isSessionEndReentry(envelope) + ) { return { response: { ok: true, @@ -342,6 +350,16 @@ async function dispatchShellHookEvent( }); } + try { + await sweepStaleHookHarnessSessions(adapter, { + repoPath, + source, + currentHostSessionId: normalizedEvent.sessionId, + }); + } catch { + // Session hygiene must never make hook dispatch blocking. + } + navigationResponse = await adapter.handle({ tool: 'context', params: { @@ -456,6 +474,25 @@ async function dispatchShellHookEvent( }; } + if (hookEventName === 'SessionEnd') { + let completed = false; + if (normalizedEvent.sessionId) { + completed = await completeHookHarnessSession(adapter, { + repoPath, + source, + hostSessionId: normalizedEvent.sessionId, + }); + } + + return { + response: createHookDispatchSuccessResponse(source, { + handled: 'session_end', + completed, + }), + output: { continue: true }, + }; + } + if (hookEventName === 'Stop') { if (!(await hasActivePrevcWorkflow(repoPath))) { return { diff --git a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts index ca4e764a..da806039 100644 --- a/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts +++ b/src/integrations/claude-code/hooks/claudeCodeHookTemplates.ts @@ -22,7 +22,7 @@ export type ClaudeCodeHookTemplate = ClaudeCodeHookMatcherEntry[]; export function buildClaudeCodeHookTemplates( command: string = buildHookDispatchCommand('claude-code') -): Record<'SessionStart' | 'PostToolUse' | 'Stop', ClaudeCodeHookTemplate> { +): Record<'SessionStart' | 'PostToolUse' | 'Stop' | 'SessionEnd', ClaudeCodeHookTemplate> { return { SessionStart: [ { @@ -41,6 +41,11 @@ export function buildClaudeCodeHookTemplates( hooks: [{ type: 'command', command }], }, ], + SessionEnd: [ + { + hooks: [{ type: 'command', command }], + }, + ], }; } @@ -50,7 +55,7 @@ export function buildClaudeCodeHookTemplates( * resolve to the local dotcontext binary when it is available. */ export const CLAUDE_CODE_HOOK_TEMPLATES: Record< - 'SessionStart' | 'PostToolUse' | 'Stop', + 'SessionStart' | 'PostToolUse' | 'Stop' | 'SessionEnd', ClaudeCodeHookTemplate > = buildClaudeCodeHookTemplates(CLAUDE_CODE_HOOK_DISPATCH_COMMAND); diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 3115bb52..62a50b18 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -8,8 +8,13 @@ import { CODEX_HOOK_DISPATCH_COMMAND, } from '../hookDispatchCommands'; import { + completeHookHarnessSession, ensureHookHarnessSession, getHookHarnessSessionId, + listHookHarnessSessionBindings, + removeHookHarnessSession, + saveHookHarnessSession, + sweepStaleHookHarnessSessions, } from '../hookSessionStore'; import { VERSION } from '../../../version'; @@ -60,4 +65,143 @@ describe('hookSessionStore', () => { expect(stored).toBe(first); }); + + it('touches updatedAt when a binding is reused', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-touch'; + + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const staleTimestamp = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(); + const [binding] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + await saveHookHarnessSession({ ...binding, updatedAt: staleTimestamp }); + + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const [touched] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + expect(Date.parse(touched.updatedAt)).toBeGreaterThan(Date.parse(staleTimestamp)); + }); + + it('removes bindings and tolerates missing entries', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-remove'; + + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + await removeHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + })).toBeUndefined(); + + await expect(removeHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'never-bound', + })).resolves.toBeUndefined(); + }); + + it('completes the bound harness session and removes the binding', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-complete'; + + const harnessSessionId = await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const completed = await completeHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + expect(completed).toBe(true); + + const sessionPath = path.join( + tempDir, '.context', 'runtime', 'sessions', harnessSessionId, 'session.json' + ); + const session = await fs.readJson(sessionPath); + expect(session.status).toBe('completed'); + + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + })).toBeUndefined(); + }); + + it('returns false without a binding and never throws', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + + await expect(completeHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'never-bound', + })).resolves.toBe(false); + }); + + it('sweeps stale bindings but keeps fresh and current ones', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + + const staleSessionId = await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'stale-host', + }); + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'fresh-host', + }); + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'current-host', + }); + + const staleTimestamp = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(); + const bindings = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + const staleBinding = bindings.find((binding) => binding.hostSessionId === 'stale-host')!; + const currentBinding = bindings.find((binding) => binding.hostSessionId === 'current-host')!; + await saveHookHarnessSession({ ...staleBinding, updatedAt: staleTimestamp }); + await saveHookHarnessSession({ ...currentBinding, updatedAt: staleTimestamp }); + + const swept = await sweepStaleHookHarnessSessions(adapter, { + repoPath: tempDir, + source: 'claude-code', + currentHostSessionId: 'current-host', + }); + + expect(swept).toBe(1); + + const remaining = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + const remainingHosts = remaining.map((binding) => binding.hostSessionId).sort(); + expect(remainingHosts).toEqual(['current-host', 'fresh-host']); + + const staleSessionPath = path.join( + tempDir, '.context', 'runtime', 'sessions', staleSessionId, 'session.json' + ); + const staleSession = await fs.readJson(staleSessionPath); + expect(staleSession.status).toBe('completed'); + }); }); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 739ba127..0a480ff6 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -21,18 +21,33 @@ interface HookSessionStoreDocument { bindings: Record>; } +export type HookSessionAdapterParams = + | { + action: 'createSession'; + name: string; + metadata?: Record; + } + | { + action: 'completeSession'; + sessionId: string; + note?: string; + }; + export interface HookSessionAdapter { handle(event: { tool: 'harness'; - params: { - action: 'createSession'; - name: string; - metadata?: Record; - }; + params: HookSessionAdapterParams; source?: string; }): Promise; } +/** + * Bindings older than this are treated as leftovers from host sessions that + * ended without a SessionEnd hook (crash, closed terminal) and are completed + * during the next SessionStart sweep. + */ +export const STALE_HOOK_SESSION_MAX_AGE_MS = 24 * 60 * 60 * 1000; + function storeKey(source: ShellHookSource, hostSessionId: string): string { return `${source}:${hostSessionId}`; } @@ -91,9 +106,12 @@ export async function ensureHookHarnessSession( hostSessionId: string; } ): Promise { - const existing = await getHookHarnessSessionId(options); + const document = await readStore(options.repoPath); + const existing = document.bindings[options.source]?.[options.hostSessionId]; if (existing) { - return existing; + existing.updatedAt = new Date().toISOString(); + await writeStore(options.repoPath, document); + return existing.harnessSessionId; } const now = new Date().toISOString(); @@ -131,3 +149,125 @@ export async function ensureHookHarnessSession( export function hookSessionStoreKey(source: ShellHookSource, hostSessionId: string): string { return storeKey(source, hostSessionId); } + +export async function listHookHarnessSessionBindings( + repoPath: string, + source: ShellHookSource +): Promise { + const document = await readStore(repoPath); + return Object.values(document.bindings[source] ?? {}); +} + +export async function removeHookHarnessSession(options: { + repoPath: string; + source: ShellHookSource; + hostSessionId: string; +}): Promise { + const document = await readStore(options.repoPath); + const sourceBindings = document.bindings[options.source]; + if (!sourceBindings || !(options.hostSessionId in sourceBindings)) { + return; + } + + delete sourceBindings[options.hostSessionId]; + await writeStore(options.repoPath, document); +} + +/** + * Completes the harness session bound to a host session and removes the + * binding. Never throws: session hygiene must not break hook dispatch, and + * the binding is removed even when completion fails so stale bindings do not + * accumulate. + */ +export async function completeHookHarnessSession( + adapter: HookSessionAdapter, + options: { + repoPath: string; + source: ShellHookSource; + hostSessionId: string; + note?: string; + } +): Promise { + let harnessSessionId: string | undefined; + try { + harnessSessionId = await getHookHarnessSessionId(options); + } catch { + return false; + } + + if (!harnessSessionId) { + return false; + } + + let completed = false; + try { + const response = await adapter.handle({ + tool: 'harness', + params: { + action: 'completeSession', + sessionId: harnessSessionId, + note: options.note ?? 'Host session ended', + }, + source: options.source, + }); + completed = response.ok; + } catch { + completed = false; + } + + try { + await removeHookHarnessSession(options); + } catch { + // Binding cleanup must never make hook dispatch blocking. + } + + return completed; +} + +/** + * Completes and unbinds harness sessions whose bindings have not been touched + * within maxAgeMs. Covers host sessions that ended without a SessionEnd hook + * (crash, closed terminal), so runtime sessions do not stay open forever. + */ +export async function sweepStaleHookHarnessSessions( + adapter: HookSessionAdapter, + options: { + repoPath: string; + source: ShellHookSource; + currentHostSessionId?: string; + maxAgeMs?: number; + now?: Date; + } +): Promise { + const maxAgeMs = options.maxAgeMs ?? STALE_HOOK_SESSION_MAX_AGE_MS; + const cutoff = (options.now ?? new Date()).getTime() - maxAgeMs; + + let bindings: HookSessionBinding[]; + try { + bindings = await listHookHarnessSessionBindings(options.repoPath, options.source); + } catch { + return 0; + } + + let swept = 0; + for (const binding of bindings) { + if (binding.hostSessionId === options.currentHostSessionId) { + continue; + } + + const updatedAt = Date.parse(binding.updatedAt); + if (Number.isNaN(updatedAt) || updatedAt > cutoff) { + continue; + } + + await completeHookHarnessSession(adapter, { + repoPath: options.repoPath, + source: options.source, + hostSessionId: binding.hostSessionId, + note: 'Stale host session swept at SessionStart', + }); + swept += 1; + } + + return swept; +} diff --git a/src/integrations/shared/index.ts b/src/integrations/shared/index.ts index e3f15613..7204afb5 100644 --- a/src/integrations/shared/index.ts +++ b/src/integrations/shared/index.ts @@ -52,10 +52,16 @@ export { } from './hookDispatchCommands'; export { + completeHookHarnessSession, ensureHookHarnessSession, getHookHarnessSessionId, + listHookHarnessSessionBindings, + removeHookHarnessSession, saveHookHarnessSession, + STALE_HOOK_SESSION_MAX_AGE_MS, + sweepStaleHookHarnessSessions, type HookSessionAdapter, + type HookSessionAdapterParams, type HookSessionBinding, type ShellHookSource, } from './hookSessionStore'; From ec2b3912119d6c9f5a2aacccb6b0cf53aabdbb69 Mon Sep 17 00:00:00 2001 From: Lorran Hippolyte Date: Fri, 10 Jul 2026 11:33:01 -0300 Subject: [PATCH 4/4] fix: address review findings on hook session lifecycle - Keep the host->harness binding when completeSession fails transiently, so the SessionStart stale sweep retains a session id to retry instead of leaking a forever-active harness session. The binding is removed only on successful completion or when the harness session is confirmed missing. - Touch the binding's updatedAt on PostToolUse so long-lived host sessions that keep emitting tool events (without re-triggering SessionStart) are not swept as stale and completed while in use. Co-Authored-By: Claude Fable 5 --- .../docs/en/guides/using-with-hooks.md | 2 +- .../docs/pt-br/guides/hook-session-flow.md | 2 +- .../docs/pt-br/guides/using-with-hooks.md | 2 +- .../__tests__/hookDispatchService.test.ts | 49 +++++++++ src/cli/services/hookDispatchService.ts | 15 +++ .../shared/__tests__/hookSessionStore.test.ts | 103 ++++++++++++++++++ src/integrations/shared/hookSessionStore.ts | 46 ++++++-- src/integrations/shared/index.ts | 1 + 8 files changed, 209 insertions(+), 11 deletions(-) diff --git a/docs/src/content/docs/en/guides/using-with-hooks.md b/docs/src/content/docs/en/guides/using-with-hooks.md index 18ef1526..f6d06639 100644 --- a/docs/src/content/docs/en/guides/using-with-hooks.md +++ b/docs/src/content/docs/en/guides/using-with-hooks.md @@ -109,7 +109,7 @@ Wired events (v1): | `Stop` | `*` | | `SessionEnd` | `*` | -On `SessionEnd`, the dispatch completes the harness session bound to the host session and removes its binding, so `.context/runtime/sessions/` entries do not stay open forever. `SessionStart` also sweeps bindings older than 24 hours from host sessions that ended without a `SessionEnd` (crash, closed terminal). +On `SessionEnd`, the dispatch completes the harness session bound to the host session and removes its binding, so `.context/runtime/sessions/` entries do not stay open forever. If completion fails transiently, the binding is kept so a later sweep can retry; it is only removed once completion succeeds or the harness session is confirmed missing. `SessionStart` also sweeps bindings untouched for 24 hours from host sessions that ended without a `SessionEnd` (crash, closed terminal). `PostToolUse` refreshes the binding, so long-lived sessions that keep emitting tool events are not treated as stale. After install, restart Claude Code. On the next session start in a repo with `.context/`, you should see a compact bootstrap message injected into context. diff --git a/docs/src/content/docs/pt-br/guides/hook-session-flow.md b/docs/src/content/docs/pt-br/guides/hook-session-flow.md index 9b1ac9be..606efbdf 100644 --- a/docs/src/content/docs/pt-br/guides/hook-session-flow.md +++ b/docs/src/content/docs/pt-br/guides/hook-session-flow.md @@ -52,7 +52,7 @@ Use `--global` somente quando quiser escrever a configuração no diretório hom | --- | --- | --- | --- | | Início da sessão | `SessionStart` | `context check` | Injeta readiness de `.context/`, ou uma dica de inicialização | | Início da sessão com contexto pronto | `SessionStart` | `harness createSession` + `context getMap` | Cria uma sessão durável e adiciona navegação compacta | -| Depois de ferramenta | `PostToolUse` para `Write`, `Edit`, `Bash` | `harness appendTrace` | Registra `tool.use` em `trace.jsonl` | +| Depois de ferramenta | `PostToolUse` para `Write`, `Edit`, `Bash` | `harness appendTrace` + touch no binding | Registra `tool.use` em `trace.jsonl` e mantém o binding fresco para a varredura de stale | | Fim da resposta | `Stop` | `workflow-guide` | Mostra próximos passos PREVC somente se há workflow ativo | | Fim da sessão | `SessionEnd` | `harness completeSession` + remoção do binding | Conclui a sessão durável do harness e limpa `host-sessions.json` | diff --git a/docs/src/content/docs/pt-br/guides/using-with-hooks.md b/docs/src/content/docs/pt-br/guides/using-with-hooks.md index 759de810..c04d7b9f 100644 --- a/docs/src/content/docs/pt-br/guides/using-with-hooks.md +++ b/docs/src/content/docs/pt-br/guides/using-with-hooks.md @@ -94,7 +94,7 @@ Eventos configurados: | `Stop` | `*` | | `SessionEnd` | `*` | -No `SessionEnd`, o dispatch conclui a sessão do harness vinculada à sessão do host e remove o binding, para que entradas em `.context/runtime/sessions/` não fiquem abertas para sempre. O `SessionStart` também varre bindings com mais de 24 horas de sessões que terminaram sem `SessionEnd` (crash, terminal fechado). +No `SessionEnd`, o dispatch conclui a sessão do harness vinculada à sessão do host e remove o binding, para que entradas em `.context/runtime/sessions/` não fiquem abertas para sempre. Se a conclusão falhar de forma transitória, o binding é mantido para que uma varredura futura tente de novo; ele só é removido quando a conclusão tem sucesso ou a sessão do harness comprovadamente não existe mais. O `SessionStart` também varre bindings sem atividade há mais de 24 horas de sessões que terminaram sem `SessionEnd` (crash, terminal fechado). O `PostToolUse` atualiza o binding, então sessões longas que continuam emitindo eventos de ferramenta não são tratadas como obsoletas. Depois de instalar, reinicie o Claude Code. Em um projeto com `.context/` inicializado, o próximo `SessionStart` deve injetar um resumo compacto de contexto. diff --git a/src/cli/services/__tests__/hookDispatchService.test.ts b/src/cli/services/__tests__/hookDispatchService.test.ts index b77a54c3..f5804647 100644 --- a/src/cli/services/__tests__/hookDispatchService.test.ts +++ b/src/cli/services/__tests__/hookDispatchService.test.ts @@ -871,4 +871,53 @@ describe('HookDispatchService session lifecycle', () => { )); expect(staleSession.status).toBe('completed'); }); + + it('touches the binding on PostToolUse so active sessions are not swept as stale', async () => { + await createReadyContext(); + const sessionId = 'host-session-long-lived'; + + const startStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'SessionStart', + }), + ]); + const startStdout = new PassThrough(); + startStdout.on('data', () => {}); + await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: startStdin, + stdout: startStdout, + }); + + const staleTimestamp = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(); + const [binding] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + await saveHookHarnessSession({ ...binding, updatedAt: staleTimestamp }); + + const postStdin = PassThrough.from([ + JSON.stringify({ + session_id: sessionId, + cwd: tempDir, + hook_event_name: 'PostToolUse', + tool_name: 'Write', + tool_input: { file_path: 'README.md' }, + }), + ]); + const postStdout = new PassThrough(); + postStdout.on('data', () => {}); + + const postResult = await runHookDispatch({ + source: 'claude-code', + repoPath: tempDir, + stdin: postStdin, + stdout: postStdout, + }); + + expect(postResult.exitCode).toBe(0); + + const [touched] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + expect(Date.parse(touched.updatedAt)).toBeGreaterThan(Date.parse(staleTimestamp)); + }); }); diff --git a/src/cli/services/hookDispatchService.ts b/src/cli/services/hookDispatchService.ts index c5bd9f12..498ede8a 100644 --- a/src/cli/services/hookDispatchService.ts +++ b/src/cli/services/hookDispatchService.ts @@ -27,6 +27,7 @@ import { resolveHarnessHookFromHostEvent, saveHookHarnessSession, sweepStaleHookHarnessSessions, + touchHookHarnessSession, type HostHookOutput, } from '../../integrations/shared'; import { formatNavigationExcerpt } from '../../integrations/shared/formatNavigationExcerpt'; @@ -395,6 +396,20 @@ async function dispatchShellHookEvent( }) : undefined; + if (harnessSessionId && normalizedEvent.sessionId) { + try { + // Keep the binding fresh so long-lived sessions that only emit tool + // events are not completed by the SessionStart stale sweep. + await touchHookHarnessSession({ + repoPath, + source, + hostSessionId: normalizedEvent.sessionId, + }); + } catch { + // Session hygiene must never make hook dispatch blocking. + } + } + const mapped = resolveHarnessHookFromHostEvent(normalizedEvent, { repoPath, harnessSessionId, diff --git a/src/integrations/shared/__tests__/hookSessionStore.test.ts b/src/integrations/shared/__tests__/hookSessionStore.test.ts index 62a50b18..9cc5e94b 100644 --- a/src/integrations/shared/__tests__/hookSessionStore.test.ts +++ b/src/integrations/shared/__tests__/hookSessionStore.test.ts @@ -15,6 +15,8 @@ import { removeHookHarnessSession, saveHookHarnessSession, sweepStaleHookHarnessSessions, + touchHookHarnessSession, + type HookSessionAdapter, } from '../hookSessionStore'; import { VERSION } from '../../../version'; @@ -150,6 +152,107 @@ describe('hookSessionStore', () => { })).toBeUndefined(); }); + it('touches updatedAt for an existing binding and no-ops without one', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-tool-touch'; + + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const staleTimestamp = new Date(Date.now() - 3 * 24 * 60 * 60 * 1000).toISOString(); + const [binding] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + await saveHookHarnessSession({ ...binding, updatedAt: staleTimestamp }); + + await touchHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const [touched] = await listHookHarnessSessionBindings(tempDir, 'claude-code'); + expect(Date.parse(touched.updatedAt)).toBeGreaterThan(Date.parse(staleTimestamp)); + + await expect(touchHookHarnessSession({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId: 'never-bound', + })).resolves.toBeUndefined(); + }); + + it('keeps the binding when completion fails transiently so the sweep can retry', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-transient'; + + await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + const failingAdapter: HookSessionAdapter = { + handle: async () => ({ + ok: false, + source: 'claude-code', + error: { message: 'EBUSY: resource busy or locked' }, + }), + }; + + const completed = await completeHookHarnessSession(failingAdapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + expect(completed).toBe(false); + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + })).toBeDefined(); + + const retried = await completeHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + expect(retried).toBe(true); + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + })).toBeUndefined(); + }); + + it('removes the binding when the harness session is confirmed missing', async () => { + const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); + const hostSessionId = 'claude-host-missing'; + + const harnessSessionId = await ensureHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + await fs.remove(path.join(tempDir, '.context', 'runtime', 'sessions', harnessSessionId)); + + const completed = await completeHookHarnessSession(adapter, { + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + }); + + expect(completed).toBe(false); + expect(await getHookHarnessSessionId({ + repoPath: tempDir, + source: 'claude-code', + hostSessionId, + })).toBeUndefined(); + }); + it('returns false without a binding and never throws', async () => { const adapter = createHarnessHookAdapter({ repoPath: tempDir, source: 'claude-code' }); diff --git a/src/integrations/shared/hookSessionStore.ts b/src/integrations/shared/hookSessionStore.ts index 0a480ff6..50d1d825 100644 --- a/src/integrations/shared/hookSessionStore.ts +++ b/src/integrations/shared/hookSessionStore.ts @@ -150,6 +150,26 @@ export function hookSessionStoreKey(source: ShellHookSource, hostSessionId: stri return storeKey(source, hostSessionId); } +/** + * Marks a binding as recently active so long-lived host sessions that keep + * emitting tool events (but never re-trigger SessionStart) are not treated + * as stale by the SessionStart sweep. + */ +export async function touchHookHarnessSession(options: { + repoPath: string; + source: ShellHookSource; + hostSessionId: string; +}): Promise { + const document = await readStore(options.repoPath); + const binding = document.bindings[options.source]?.[options.hostSessionId]; + if (!binding) { + return; + } + + binding.updatedAt = new Date().toISOString(); + await writeStore(options.repoPath, document); +} + export async function listHookHarnessSessionBindings( repoPath: string, source: ShellHookSource @@ -173,11 +193,16 @@ export async function removeHookHarnessSession(options: { await writeStore(options.repoPath, document); } +function isMissingHarnessSessionMessage(message: string): boolean { + return message.includes('Harness session not found'); +} + /** * Completes the harness session bound to a host session and removes the - * binding. Never throws: session hygiene must not break hook dispatch, and - * the binding is removed even when completion fails so stale bindings do not - * accumulate. + * binding. Never throws: session hygiene must not break hook dispatch. + * The binding is removed only when completion succeeds or the session is + * confirmed missing; transient failures keep the binding so the SessionStart + * stale sweep can retry completion instead of leaking an active session. */ export async function completeHookHarnessSession( adapter: HookSessionAdapter, @@ -200,6 +225,7 @@ export async function completeHookHarnessSession( } let completed = false; + let sessionMissing = false; try { const response = await adapter.handle({ tool: 'harness', @@ -211,14 +237,18 @@ export async function completeHookHarnessSession( source: options.source, }); completed = response.ok; - } catch { + sessionMissing = !response.ok && isMissingHarnessSessionMessage(response.error.message); + } catch (error) { completed = false; + sessionMissing = error instanceof Error && isMissingHarnessSessionMessage(error.message); } - try { - await removeHookHarnessSession(options); - } catch { - // Binding cleanup must never make hook dispatch blocking. + if (completed || sessionMissing) { + try { + await removeHookHarnessSession(options); + } catch { + // Binding cleanup must never make hook dispatch blocking. + } } return completed; diff --git a/src/integrations/shared/index.ts b/src/integrations/shared/index.ts index 7204afb5..90429fa7 100644 --- a/src/integrations/shared/index.ts +++ b/src/integrations/shared/index.ts @@ -60,6 +60,7 @@ export { saveHookHarnessSession, STALE_HOOK_SESSION_MAX_AGE_MS, sweepStaleHookHarnessSessions, + touchHookHarnessSession, type HookSessionAdapter, type HookSessionAdapterParams, type HookSessionBinding,