fix(delegation): pin the child's brief through compaction; context first as a cacheable prefix

Review findings from unsupportedpastels and kshitijk4poor:

- A steered child lost its brief at its second compaction. The compactor stops
  protecting early turns after the first pass and restates the newest real user
  turn, which after a steer is the steer. A delegated child's first user turn
  is its whole brief (goal, context, output contract), so it is now always
  protected (ContextCompressor.pin_task_turn, set on every child). The head
  window methods move to context_compressor_window.py with it.
- Siblings given one context stopped reading it from cache: the goal came
  first, so the shared bytes started after the first difference. The first user
  turn is now "CONTEXT: ... TASK: <goal>", and the context is registered as the
  message's stable prefix, which gives it its own cache breakpoint on marker
  routes. Every brief is registered: a parent often sends one brief in separate
  calls, which a per-call "shared" test cannot see.
- Stale docs and comments that still placed the context in the system prompt.

Co-authored-by: unsupportedpastels <unsupportedpastels@users.noreply.github.com>
Co-authored-by: kshitijk4poor <kshitijk4poor@users.noreply.github.com>
This commit is contained in:
Teknium
2026-11-11 13:54:11 -08:00
parent f2c3b5a374
commit 69677b5829
11 changed files with 123 additions and 43 deletions

View File

@@ -4550,34 +4550,6 @@ Write only the summary body. Do not include any preamble or prefix."""
idx += 1
return idx
def _restart_handoff_probe_bounds(self, messages: list[dict[str, Any]]) -> tuple[int, int]:
"""Return the bounded transcript region that can indicate restart decay."""
if not messages or self.protect_first_n <= 0:
return 0, 0
first_non_system = 1 if messages[0].get("role") == "system" else 0
return first_non_system, min(len(messages), first_non_system + self.protect_first_n + _RESTART_HANDOFF_PROBE_EXTRA_MESSAGES)
def _effective_protect_first_n(self, messages: Optional[list[dict[str, Any]]] = None) -> int:
"""``protect_first_n``, decayed to 0 once the session has been compressed so early turns don't fossilize.
After a restart the decayed state is inferred from handoff summaries in the resumed head."""
if self.compression_count >= 1 or self._previous_summary:
return 0
if messages and self.protect_first_n > 0:
# Probe only the early resumed-handoff shape; summary-like tail content must not decay protection.
probe_start, probe_end = self._restart_handoff_probe_bounds(messages)
if any(map(self._is_context_summary_message, messages[probe_start:probe_end])):
return 0
return self.protect_first_n
def _protect_head_size(self, messages: list[dict[str, Any]]) -> int:
"""Head messages to protect: the system prompt (if present) plus the decaying ``protect_first_n`` extra rows.
The ``protect_first_n`` portion DECAYS after the first compression (see _effective_protect_first_n)
so early user turns don't fossilize across repeated compactions (#11996).
"""
head = 1 if messages and messages[0].get("role") == "system" else 0
return head + self._effective_protect_first_n(messages)
def _align_boundary_backward(self, messages: list[dict[str, Any]], idx: int) -> int:
"""Pull a compress-end boundary back so a tool group is not split (orphaned tail results would be dropped)."""
if idx <= 0 or idx >= len(messages):

View File

@@ -10,11 +10,51 @@ from agent.context_compressor_tail import tail_cut_progress_floor
from agent.prepared_compaction import PreparedCompaction, PreparedSummary
def _restart_probe_extra() -> int:
from agent.context_compressor import _RESTART_HANDOFF_PROBE_EXTRA_MESSAGES
return _RESTART_HANDOFF_PROBE_EXTRA_MESSAGES
class CompactionWindowMixin:
"""Window planning shared by compress() and the background pass."""
# Set by agent_init when compression.prepare_ahead is on; None leaves compress() inline as before.
prepared_compaction: Optional[PreparedCompaction] = None
# Set on delegated children (tools/delegate_tool.py): their first user turn is the whole brief.
pin_task_turn: bool = False
def _restart_handoff_probe_bounds(self, messages: list[dict[str, Any]]) -> tuple[int, int]:
"""Return the bounded transcript region that can indicate restart decay."""
if not messages or self.protect_first_n <= 0:
return 0, 0
first_non_system = 1 if messages[0].get("role") == "system" else 0
return first_non_system, min(len(messages), first_non_system + self.protect_first_n + _restart_probe_extra())
def _effective_protect_first_n(self, messages: Optional[list[dict[str, Any]]] = None) -> int:
"""``protect_first_n``, decayed to 0 once the session has been compressed so early turns don't fossilize.
After a restart the decayed state is inferred from handoff summaries in the resumed head.
A delegated child's first user turn is its whole brief (goal, context, output contract), so it
never decays: a steer would otherwise become the turn compaction restates, and the brief goes
into the summary."""
if self.pin_task_turn:
return 1
if self.compression_count >= 1 or self._previous_summary:
return 0
if messages and self.protect_first_n > 0:
# Probe only the early resumed-handoff shape; summary-like tail content must not decay protection.
probe_start, probe_end = self._restart_handoff_probe_bounds(messages)
if any(map(self._is_context_summary_message, messages[probe_start:probe_end])):
return 0
return self.protect_first_n
def _protect_head_size(self, messages: list[dict[str, Any]]) -> int:
"""Head messages to protect: the system prompt (if present) plus the decaying ``protect_first_n`` extra rows.
The ``protect_first_n`` portion DECAYS after the first compression (see _effective_protect_first_n)
so early user turns don't fossilize across repeated compactions (#11996).
"""
head = 1 if messages and messages[0].get("role") == "system" else 0
return head + self._effective_protect_first_n(messages)
def _compress_window(self, messages: list[dict[str, Any]]) -> tuple[int, int]:
"""Return ``(compress_start, compress_end)`` for the summarizable middle."""

View File

@@ -728,7 +728,8 @@ class ResponsesApiTransport(ProviderTransport):
params: instructions: str — system prompt (extracted from messages[0] if not given)
reasoning_config: dict | None — {effort, enabled} session_id: str | None — transcript/session id;
drives the Codex ``session_id`` header, and is the cache-scope fallback when no ``cache_scope_id``
drives the Codex ``session_id`` header (a delegated child sends its siblings' shared scope there
instead, see ``prompt_cache_scope.sibling_cache_scope``), and is the cache-scope fallback when no ``cache_scope_id``
is given cache_scope_id: str | None — rotation-stable logical scope id (compression-lineage root;
see agent/prompt_cache_scope.py). Preferred over session_id when deriving the prompt_cache_key
content hash and the xAI x-grok-conv-id header; the Codex x-client-request-id header mirrors the

View File

@@ -24,7 +24,7 @@ os.makedirs(home); os.makedirs(ws)
isolate_host(root, home)
NONCE = uuid.uuid4().hex[:10]
with open(os.path.join(home, "config.yaml"), "w") as f:
f.write("delegation:\n max_iterations: 14\n")
f.write("delegation:\n max_iterations: 14\n max_concurrent_children: 10\n")
# A per-run SOUL line keeps every other live session's cache entries out of this run.
with open(os.path.join(home, "SOUL.md"), "w") as f:
f.write(f"You are Hermes. Probe run {NONCE}.\n")
@@ -73,6 +73,13 @@ def _ends_with(final, marker):
return str(final or "").rstrip().endswith(marker)
SHARED_BRIEF = ("The parent is auditing the numbers in this repo. End your final reply with the exact word AUDIT-OK.\n"
+ open(os.path.join(TREE, "AGENTS.md")).read()[:13000])
if os.environ.get("SC_SHARED") == "1": # one long brief for every child, different goals
CHILDREN = [(n, SHARED_BRIEF, f, w, "AUDIT-OK") for n, _, f, w, _ in CHILDREN]
if os.environ.get("SC_WIDE"): # N children in one batch, same brief shape, distinct files
CHILDREN = [(f"W{i}", CHILDREN[i % 3][1], CHILDREN[i % 3][2], CHILDREN[i % 3][3], CHILDREN[i % 3][4])
for i in range(int(os.environ["SC_WIDE"]))]
GOAL = "Use the terminal to list this directory, then read {}.txt and reply with the number in it."
if os.environ.get("SC_LONG") == "1": # several rounds per child, to see in-session reads past the shared prefix
GOAL = ("Run these one per terminal call, in this order, never combined: `ls -la`, `cat alpha.txt`, `cat beta.txt`, "
@@ -80,12 +87,13 @@ if os.environ.get("SC_LONG") == "1": # several rounds per child, to see in-sess
"Then reply with the number in {}.txt.")
if os.environ.get("SC_PARALLEL") == "1": # one batch: do concurrent siblings under one scope still cache in-session?
raw = delegate_task(tasks=[{"goal": GOAL.format(c[2]), "context": c[1]} for c in CHILDREN], parent_agent=parent)
print(raw[:300], file=sys.stderr) if not raw.lstrip().startswith("{") else None
results = json.loads(raw).get("results") or []
by_sid = {}
for c in calls:
by_sid.setdefault(c["sid"], []).append((c["prompt"], c["cache_read"]))
rec = {"arm": ARM, "route": PROVIDER, "model": MODEL, "parallel": True, "nonce": NONCE,
"task_ok": [c[3] in str(r.get("summary") or "") for c, r in zip(CHILDREN, results)],
"task_ok": [c[3] in str(r.get("summary") or "") for c, r in zip(CHILDREN, results)], "n_children": len(CHILDREN),
"context_followed": [_ends_with(r.get("summary"), c[4]) for c, r in zip(CHILDREN, results)],
"n_results": len(results), "finals": [str(r.get("summary") or "")[-200:] for r in results],
"calls": list(by_sid.values())}

View File

@@ -70,8 +70,8 @@ def test_local_review_reviews_the_stored_conversation_once_the_cached_agent_is_g
assert 'Review started' in json.dumps(result), (focus, result)
def reviewer(request):
# The reviewer's first user turn is its goal, then the context the command passes.
return any(str(m.get('content') or '').startswith('Review: ' + focus) for m in request.get('messages', []))
# The reviewer's first user turn is the context the command passes, then its goal.
return any(str(m.get('content') or '').endswith('\n\nTASK:\nReview: ' + focus) for m in request.get('messages', []))
await async_wait_until(lambda: any(reviewer(r) for r in peer.requests[before:]), timeout=45,
what=f'the {focus} reviewer reaching the model')
request = next(r for r in peer.requests[before:] if reviewer(r))

View File

@@ -32,8 +32,7 @@ def test_siblings_send_one_system_prompt_and_get_their_context_in_the_user_turn(
assert first["tools"] == second["tools"]
assert "auditing numbers" not in str(first["messages"][0])
task = first["messages"][1]
assert task["role"] == "user" and task["content"].startswith("count the files")
assert "The parent is auditing numbers." in task["content"]
assert task["role"] == "user" and task["content"] == "CONTEXT:\nThe parent is auditing numbers.\n\nTASK:\ncount the files"
assert "The parent is fixing the gateway." in second["messages"][1]["content"]
@@ -72,6 +71,51 @@ def test_schema_correction_turn_carries_the_contract_even_after_a_compaction():
assert len(entry["tool_trace"]) == 10
def test_a_shared_brief_is_one_cacheable_prefix_for_every_sibling():
"""Siblings given one context send it as the same leading bytes, as their own marked part on a marker route."""
from agent.prompt_caching import apply_anthropic_cache_control
from tools.delegate_tool_progress import child_task_message
brief = "Repo layout and rules: " + "x" * 2000
one, two = (child_task_message(goal, brief) for goal in ("find the bug", "write the test"))
def first_user_parts(content):
planned = apply_anthropic_cache_control([{"role": "system", "content": "sys"}, {"role": "user", "content": content}])
return planned[1]["content"]
parts_one, parts_two = first_user_parts(one), first_user_parts(two)
assert parts_one[0] == parts_two[0] and brief in parts_one[0]["text"] and "cache_control" in parts_one[0]
assert parts_one[1]["text"].endswith("find the bug")
assert first_user_parts(child_task_message("lone task", None))[0]["text"] == "lone task"
def test_a_steered_child_keeps_its_brief_through_a_second_compaction():
"""After a steer, compaction restates the steer as the in-flight turn; the brief must not go into the summary."""
from unittest.mock import patch
from agent.context_compressor import ContextCompressor
from agent.prompt_builder import steer_user_row
brief = "CONTEXT:\nRULE-IN-THE-MIDDLE " + "detail " * 300 + "\n\nTASK:\ncount the files"
rounds = []
for i in range(30):
cid = f"c{i}"
rounds += [{"role": "assistant", "content": "", "tool_calls": [{"id": cid, "type": "function",
"function": {"name": "terminal", "arguments": "{}"}}]},
{"role": "tool", "tool_call_id": cid, "content": "output " * 200}]
messages = [{"role": "system", "content": "sys"}, {"role": "user", "content": brief}] + rounds[:26]
messages += [steer_user_row("also check the tests")] + rounds[26:]
with patch("agent.context_compressor.get_model_context_length", return_value=100000):
child = ContextCompressor(model="test", quiet_mode=True, protect_first_n=3, protect_last_n=4)
child.pin_task_turn = True
child.compression_count = 1 # the steer lands after an earlier compaction
with patch("agent.context_compressor.call_llm", side_effect=RuntimeError("no provider")):
out = child.compress(messages)
assert any(m.get("role") == "user" and m.get("content") == brief for m in out)
def test_codex_siblings_share_the_session_header_the_backend_caches_under():
from agent.chat_completion_helpers import _build_api_kwargs_for_mode
from run_agent import AIAgent

View File

@@ -182,7 +182,7 @@ def _child_compression_cap_tokens(raw) -> int | None:
def _apply_child_compression_cap(child, delegation_cfg: dict) -> None:
"""Optional absolute cap on the child's compaction trigger, ``delegation.compression_threshold_tokens``
"""Pin the child's brief through compaction, then the optional absolute cap on its compaction trigger, ``delegation.compression_threshold_tokens``
(lower of it and any global ``compression.threshold_tokens``). Off by default: a 1M-window child
compacts where its parent does. The compressor applies the cap on first window resolution, which
happens after construction, so setting it here is exactly equivalent to config."""
@@ -191,6 +191,7 @@ def _apply_child_compression_cap(child, delegation_cfg: dict) -> None:
cc = getattr(child, "context_compressor", None)
if not isinstance(cc, ContextCompressor):
return
cc.pin_task_turn = True # the brief (goal, context, output contract) is the first user turn
cap = _child_compression_cap_tokens((delegation_cfg or {}).get("compression_threshold_tokens"))
if cap is None:
return

View File

@@ -1,7 +1,7 @@
"""Prompt-cache warm-up gate for batch subagents (``delegation.prefix_stagger_seconds``).
Siblings in one batch send the same tools[] and system-prompt scaffold; only the goal (their first user
turn) and, when tasks carry different ``context``, the tail of the system prompt differ. Launched together,
Siblings in one batch send the same tools[] and system prompt; only their first user turn (context, then
goal) differs. Launched together,
every child's first request misses the provider cache and pays the full prefix. A provider cache entry is
readable once the writing response starts streaming, so the gate lets the batch's first child (the leader)
run at once and holds the siblings that share its route until the leader's first response has started, it

View File

@@ -217,8 +217,21 @@ def _build_child_system_prompt(
return "\n".join(parts)
def child_task_message(goal: str, context: Optional[str]) -> str:
"""The child's first user turn: the goal, then the parent's context for it."""
return f"{goal}\n\nCONTEXT:\n{context}" if context and context.strip() else goal
"""The child's first user turn: the parent's context, then the goal.
Context first, so siblings given one brief send the same leading bytes, and registered as the
message's stable prefix, which gives it a cache breakpoint of its own on marker routes. Every
brief is registered: a parent often sends one brief in separate calls, which a per-call
"shared" test cannot see. Scaffolds in use are refreshed on every request, so a wide fan-out
evicts only idle ones (one re-write when that session resumes).
"""
if not (context and context.strip()):
return goal
from agent.prompt_cache_boundary import register_stable_prefix
prefix = f"CONTEXT:\n{context}\n\nTASK:\n"
register_stable_prefix(prefix)
return prefix + goal
def _resolve_workspace_hint(parent_agent) -> Optional[str]:

View File

@@ -107,7 +107,8 @@ def validate_output(text: str, schema: dict[str, Any]) -> tuple[bool, list[str]]
def build_retry_message(errors: list[str]) -> str:
"""Single bounded retry turn: errors verbatim, schema deliberately NOT re-pasted."""
"""Single bounded retry turn: errors verbatim. The caller appends the contract itself, because a
compaction of a long first turn can leave the original one only in a summary."""
error_block = "\n".join(f"- {e}" for e in errors)
return ("Your previous final response was rejected by the output contract "
"validator. Validation errors:\n" f"{error_block}\n\n"

View File

@@ -85,7 +85,7 @@ Subagents start with a **completely fresh conversation**. They have zero knowled
One exception: when the parent has a resolved workspace directory, every subagent's system prompt embeds that workspace's **project context files** (`.hermes.md` > AGENTS.md chain > CLAUDE.md > `.cursorrules` — the same discovery, priority, and size caps as the main agent's system prompt; SOUL.md is excluded). Subagents working in a repo operate under the repo's own conventions without having to rediscover them.
The `goal` and `context` arrive as the subagent's first user message. Its system prompt carries nothing task-specific, so the subagents of one parent send an identical prompt prefix and can read each other's prompt cache.
The `context` and `goal` arrive as the subagent's first user message, context first. Its system prompt carries nothing task-specific, so the subagents of one parent send an identical prompt prefix and can read each other's prompt cache, including a context they share. That first message is kept verbatim through context compression.
This means the parent agent must pass **everything** the subagent needs in the call:
@@ -104,7 +104,7 @@ delegate_task(
)
```
The subagent receives a focused system prompt built from your goal and context, instructing it to complete the task and provide a structured summary of what it did, what it found, any files modified, and any issues encountered.
The subagent's first message is your context followed by the goal. Its system prompt instructs it to complete the task and provide a structured summary of what it did, what it found, any files modified, and any issues encountered.
### Forwarding Images to a Subagent