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
56 changes: 52 additions & 4 deletions core/harness/hooks/execution.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,10 @@
import asyncio
import json
import os
import tempfile
import time
from dataclasses import dataclass
from pathlib import Path
from typing import Any

from core.agent_runtime.processes import (
Expand Down Expand Up @@ -137,6 +139,46 @@ def _trimmed_reason(reason: Any) -> str | None:
return trimmed or None


#: Hook context goes straight into the transcript, so one chatty hook can spend
#: the whole window before the model has even seen the request. Cap it, and keep
#: the full text on disk instead of silently dropping it: a truncated hook that
#: still shows *where* the rest went is debuggable, a silently shortened one is
#: not. ~10k characters is roughly 2.5k tokens.
_CONTEXT_CHAR_LIMIT = 10_000


def _spill_context(text: str) -> str | None:
"""Save the full hook output to a private file, returning its path."""

try:
directory = Path(tempfile.gettempdir()) / "deepcode-hook-output"
directory.mkdir(mode=0o700, parents=True, exist_ok=True)
fd, name = tempfile.mkstemp(prefix="hook-", suffix=".txt", dir=directory)
with os.fdopen(fd, "w", encoding="utf-8", errors="replace") as handle:
handle.write(text)
# mkstemp already creates 0600; keep it explicit for non-POSIX backends.
os.chmod(name, 0o600)
return name
except OSError: # pragma: no cover - platform dependent
return None


def _bounded_context(text: Any) -> str | None:
"""``additionalContext``, capped, with the overflow spilled to a file."""

trimmed = _trimmed_reason(text)
if trimmed is None or len(trimmed) <= _CONTEXT_CHAR_LIMIT:
return trimmed
head = trimmed[:_CONTEXT_CHAR_LIMIT]
path = _spill_context(trimmed)
if path is None: # pragma: no cover - spill failure degrades to truncation
return f"{head}\n\n[hook output truncated at {_CONTEXT_CHAR_LIMIT} characters]"
return (
f"{head}\n\n[hook output truncated at {_CONTEXT_CHAR_LIMIT} characters; "
f"full text saved to {path}]"
)


@dataclass(slots=True)
class _Universal:
continue_processing: bool = True
Expand Down Expand Up @@ -173,7 +215,9 @@ def _block_from_decision(obj: dict, event_label: str) -> HandlerDecision:
dec.block_reason = reason
hook_specific = obj.get("hookSpecificOutput")
if isinstance(hook_specific, dict):
dec.additional_context = _trimmed_reason(hook_specific.get("additionalContext"))
dec.additional_context = _bounded_context(
hook_specific.get("additionalContext")
)
return dec


Expand Down Expand Up @@ -212,7 +256,7 @@ def _decode_pre_tool_use(obj: dict) -> HandlerDecision:
else:
dec.block = True
dec.block_reason = reason
dec.additional_context = _trimmed_reason(hs.get("additionalContext"))
dec.additional_context = _bounded_context(hs.get("additionalContext"))
return dec


Expand All @@ -221,7 +265,9 @@ def _decode_additional_context_only(obj: dict) -> HandlerDecision:
dec = HandlerDecision()
hook_specific = obj.get("hookSpecificOutput")
if isinstance(hook_specific, dict):
dec.additional_context = _trimmed_reason(hook_specific.get("additionalContext"))
dec.additional_context = _bounded_context(
hook_specific.get("additionalContext")
)
return dec


Expand Down Expand Up @@ -320,7 +366,9 @@ def parse_handler_output(event_name: str, result: CommandResult) -> HandlerDecis
)
# Plain-text stdout becomes context for the context events; ignored else.
if event_name in _TEXT_CONTEXT_EVENTS:
return HandlerDecision(status="completed", additional_context=stripped)
return HandlerDecision(
status="completed", additional_context=_bounded_context(stripped)
)
return HandlerDecision(status="completed")

decoder = _DECODERS.get(event_name)
Expand Down
42 changes: 42 additions & 0 deletions tests/test_hook_output_spill.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
"""Hook context is capped, and the overflow is recoverable rather than lost."""

from __future__ import annotations

from pathlib import Path

from core.harness.hooks import execution


def test_short_context_passes_through_unchanged() -> None:
assert execution._bounded_context(" build is green ") == "build is green"


def test_empty_context_is_none() -> None:
assert execution._bounded_context(" ") is None
assert execution._bounded_context(None) is None


def test_long_context_is_capped_and_spilled() -> None:
limit = execution._CONTEXT_CHAR_LIMIT
payload = "x" * (limit + 500)
bounded = execution._bounded_context(payload)
assert bounded is not None
assert len(bounded) < len(payload)
assert bounded.startswith("x" * limit)
assert "truncated at" in bounded
assert "full text saved to" in bounded

# The path in the message must be the file that holds the whole payload.
marker = "full text saved to "
path = Path(bounded.split(marker, 1)[1].rstrip("]"))
assert path.is_file()
assert path.read_text(encoding="utf-8") == payload


def test_truncation_keeps_the_prefix_the_hook_emitted() -> None:
prefix = "SUMMARY: 3 files changed\n"
bounded = execution._bounded_context(
prefix + "y" * (execution._CONTEXT_CHAR_LIMIT * 2)
)
assert bounded is not None
assert bounded.startswith(prefix)
Loading