github / github/copilot-cli

postToolUse hook additionalContext not injected into agent context window

Abierto
#2,980 2 comentarios 4 reacciones 0 asignados Ver en GitHub
area:context-memory area:plugins
Lenguaje dominante
Shell
Estrellas
11.2k
Forks
1.9k
Merge medio
14 h 16 min
PR fusionados (30 d)
6

Descripción

### Describe the bug

# Bug Report: `postToolUse` hook `additionalContext` not injected into agent context window

## Summary

When a `postToolUse` hook emits a JSON response containing an `additionalContext` field, the
Copilot CLI captures the hook output but does **not** forward the `additionalContext` value into
the agent's context window. As a result, the agent never sees lint diagnostics, warnings, or any
other feedback the hook intended to surface, and cannot self-correct.

---

## Environment

| Field | Value |
|---|---|
| CLI | GitHub Copilot CLI |
| OS | macOS (Darwin) |
| Hook type | `postToolUse` |
| Triggering tool | `create` (also expected to affect `edit`) |
| Hook script | any `postToolUse` hook emitting `{"additionalContext": "..."}` |

---

## Minimal Reproduction

### 1. Create the hook script

Save the following as `~/.copilot/hooks/post-tool-use-test.sh` and make it executable
(`chmod +x`):

```bash
#!/usr/bin/env bash
# Minimal postToolUse hook to reproduce the additionalContext injection bug.
# Emits additionalContext whenever the agent uses the 'create' tool.

input=$(cat)
tool_name=$(echo "${input}" | jq -r '.toolName // empty')

if [[ "${tool_name}" != "create" ]]; then
echo '{}'
exit 0
fi

# Emit additionalContext — this should be injected into the agent's context window.
echo '{"additionalContext": "HOOK FEEDBACK: This message should appear in the agent context."}'
```

### 2. Register the hook

In your Copilot CLI hooks configuration, register the script as a `postToolUse` hook:

```json
{
"hooks": [
{
"event": "postToolUse",
"command": "~/.copilot/hooks/post-tool-use-test.sh"
}
]
}
```

### 3. Trigger it

Start a Copilot CLI session and ask the agent to create any file:

> "Create a file called test.txt containing the word hello."

### 4. Observe the failure

- ✅ The hook runs (visible in debug logs via `--debug` flag).
- ✅ The hook stdout contains `{"additionalContext": "HOOK FEEDBACK: ..."}`.
- ❌ The agent's next response shows **no awareness** of the hook message.
It does not mention, react to, or incorporate `"HOOK FEEDBACK: ..."` in any way.

To confirm with debug logs, run with `--debug` and look for:

```
[hook stdout] {"additionalContext": "HOOK FEEDBACK: This message should appear in the agent context."}
```

This line will be present, proving the CLI received the output — but the agent never sees it.

---

## Expected Behavior

Per the documented `postToolUse` contract and the hook's own inline documentation:

> *"it emits `{"additionalContext": "..."}` so the Copilot CLI injects the ShellCheck diagnostics
> into the agent's context window, enabling self-correction."*

The `additionalContext` string should be injected into the agent's context window as a system
message or tool result annotation **after** the tool call completes, so the agent can:

- Read the diagnostic feedback.
- Self-correct its output (e.g., fix the linting issues before the task is considered done).

---

## Actual Behavior

The Copilot CLI runtime:

1. ✅ Spawns the hook process correctly.
2. ✅ Receives the hook's JSON stdout (confirmed via debug logs).
3. ❌ **Does NOT inject `additionalContext` into the agent's context window.**

The agent completes the task with no awareness that the hook ran or that it produced feedback.

### Relevant Debug Log Evidence

```
[hook stderr] bash-shellcheck hook: ShellCheck validation failed for /path/to/hello.sh
[hook stderr] [INFO] Linting: /path/to/hello.sh

In /path/to/hello.sh line 3:
echo $x
^-- SC2086 (info): Double quote to prevent globbing and word splitting.
^-- SC2250 (style): Prefer putting braces around variable references...
✗ /path/to/hello.sh failed

[hook stdout] {
"additionalContext": "[INFO] Linting: ... SC2086 ... SC2250 ... ✗ failed"
}
```

The CLI received `[hook stdout]` containing the populated `additionalContext` field, but the agent
received no message containing this content. The agent's next response showed no awareness of the
lint failure.

---

## Impact

- **Self-correction loop is broken.** The entire purpose of `additionalContext` in `postToolUse`
hooks is to enable agents to detect and fix their own mistakes automatically. This mechanism is
silently non-functional.
- **Silent failure.** There is no error, warning, or indication to the user or agent that
`additionalContext` was dropped. Users who build hooks relying on this feature will believe it
works (the hook runs, the JSON is correct) but the agent will never self-correct.
- **Plugin ecosystem impact.** Any plugin that relies on `postToolUse` + `additionalContext` for
agent feedback (linters, formatters, validators, security scanners) is affected.

---

## Root Cause Hypothesis

The Copilot CLI runtime correctly spawns `postToolUse` hooks and captures their stdout, but the
code path that reads the parsed JSON response and injects `additionalContext` into the agent's
next context turn appears to be missing or not wired up. The data is captured (visible in debug
logs) but never routed to the agent.

Likely location of the bug: the hook result post-processing step, where the runtime should take
`response.additionalContext` and append it to the agent's pending context before the next LLM
call.

---

## Suggested Fix

After a `postToolUse` hook completes, if the parsed JSON response contains a non-empty
`additionalContext` string, the runtime should inject it into the agent's context window — for
example as a system notification, a tool result annotation, or a synthetic user message — before
the agent produces its next response.

---

## Workaround

None available. The `additionalContext` field in `preToolUse` hooks does work (it can block tool
calls), but `postToolUse` has no equivalent workaround since it runs after the tool has already
executed.

### Affected version

_No response_

### Steps to reproduce the behavior

_No response_

### Expected behavior

_No response_

### Additional context

_No response_

Guía de contribución

Abrir la guía de contribución

Línea de trabajo

Comienza por la ruta de posprocesamiento del resultado del hook postToolUse descrita en el informe, usando la reproducción de create-tool y la salida de --debug para rastrear la respuesta analizada. Verifica que el valor additionalContext llegue al agente después de la llamada a la herramienta, también para edit, y confirma que el agente puede reaccionar a los comentarios del hook.

Escrito por el modelo de indexación a partir del texto del issue.

Evaluación

Stack tecnológico
shell
Área
cli
Tipo de issue
Error
Dificultad
4/5
Tiempo estimado
3-5 días
Estado de actividad
Tranquilo
Claridad
Bastante claro
Aptitud para principiantes
48/100

Recibe los nuevos issues en tu correo

Un resumen breve de issues de GitHub para principiantes.