Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 2 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<installed version> ...` 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:
Expand Down
2 changes: 1 addition & 1 deletion docs/src/content/docs/en/about/architecture.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/).

Expand Down
15 changes: 12 additions & 3 deletions docs/src/content/docs/en/guides/using-with-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -90,19 +90,26 @@ 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@<installed version> 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 |
| --- | --- |
| `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. 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.

Expand All @@ -119,7 +126,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@<installed version> hook dispatch --source codex
```

The installer writes either:
Expand Down
16 changes: 11 additions & 5 deletions docs/src/content/docs/pt-br/guides/hook-session-flow.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<versão instalada> hook dispatch --source claude-code
npx -y @dotcontext/cli@<versão instalada> 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
Expand All @@ -47,8 +52,9 @@ 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 |
| 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` |

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.

Expand Down
11 changes: 9 additions & 2 deletions docs/src/content/docs/pt-br/guides/using-with-hooks.md
Original file line number Diff line number Diff line change
Expand Up @@ -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@<versão instalada> hook dispatch --source claude-code
```

Eventos configurados:
Expand All @@ -90,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. 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.

Expand All @@ -98,7 +103,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@<versão instalada> hook dispatch --source codex
```

O instalador escreve uma destas configurações:
Expand Down
237 changes: 237 additions & 0 deletions src/cli/services/__tests__/hookDispatchService.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { PassThrough } from 'stream';
import { runHookDispatch } from '../hookDispatchService';
import {
getHookHarnessSessionId,
listHookHarnessSessionBindings,
saveHookHarnessSession,
} from '../../../integrations/shared/hookSessionStore';
import { WorkflowService } from '../../../harness';
Expand Down Expand Up @@ -683,4 +684,240 @@ 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');
});

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));
});
});
Loading
Loading