The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(delegation): fork forced copies from complete output before the budget
Teknium322a249c252f
diff --git a/tests/tools/test_delegated_output_redaction.py b/tests/tools/test_delegated_output_redaction.pyindex 83bc37b222f..5716e112554 100644--- a/tests/tools/test_delegated_output_redaction.py+++ b/tests/tools/test_delegated_output_redaction.py@@ -213,3 +213,39 @@ def test_parent_copy_honours_opt_out_while_persisted_copies_stay_forced(with ad._transaction() as conn:row = conn.execute("SELECT event_json,result_json FROM async_delegations").fetchone()assert SECRET not in "".join(row)+++def test_forced_copies_are_projected_from_complete_output_before_the_parent_budget(+ tmp_path, monkeypatch+):+ """Opt-out + budget: the trimmed parent tail can start after a PEM BEGIN marker; the+ memory/durable copies must still hide the key body, and the spill must stay valid JSON."""+ monkeypatch.setattr("agent.redact._redact_enabled", lambda: False)+ monkeypatch.setattr(delegate, "_load_config", lambda: {"max_summary_chars": 2000})+ body = "\n".join("MC4CAQAwBQYDK2VwBCIEI" + chr(65 + i) * 43 for i in range(4))+ pem = "-----BEGIN PRIVATE KEY-----\n" + body + "\n-----END PRIVATE KEY-----\n"+ tail = pem[pem.index("KEY-----\n") :] + "ordinary ending\n" * 10+ tail += "x" * (500 - len(tail)) # the parent's 500-char tail starts inside the BEGIN line+ summaries = ["ordinary explanation\n" * 200 + pem[: pem.index("KEY-----\n")] + tail,+ json.dumps({"env": "OPENAI_API_KEY=" + SECRET, "pad": "z" * 3000, "n": 2})]+ parent = _Parent()+ entries = [{"task_index": i, "status": "completed", "summary": s} for i, s in enumerate(summaries)]+ entries[1]["schema_valid"] = True+ schema_child = SimpleNamespace(_delegate_output_schema={"type": "object"})+ results._finalize_child_results(+ entries, [{"goal": "a"}, {"goal": "b"}], [(0, {}, None), (1, {}, schema_child)], parent+ )++ assert all(e["summary_truncated"] for e in entries) and body in entries[0]["summary"]+ memory = parent._memory_manager.on_delegation.call_args_list[0].kwargs["result"]+ assert body[-43:] not in memory+ spilled = json.loads(Path(entries[1]["summary_full_path"]).read_text(encoding="utf-8-sig"))+ assert spilled["n"] == 2 and SECRET not in spilled["env"]++ record, target = {**_record(), "is_batch": True}, queue.Queue()+ monkeypatch.setattr(process_registry, "completion_queue", target)+ ad._push_completion_event(record, {"results": entries}, "completed")+ assert body in target.get_nowait()["results"][0]["summary"]+ with ad._transaction() as conn:+ row = conn.execute("SELECT event_json,result_json FROM async_delegations").fetchone()+ assert body[-43:] not in "".join(row) and SECRET not in "".join(row)diff --git a/tools/delegate_tool_results.py b/tools/delegate_tool_results.pyindex b9de015592c..a1ef3533fa7 100644--- a/tools/delegate_tool_results.py+++ b/tools/delegate_tool_results.py@@ -7,8 +7,9 @@ import jsonimport threadingfrom typing import Any, Dict, List, Optionalfrom urllib.parse import urlsplit, urlunsplit-from agent.redact import redact_for_egress-from tools.delegation_redaction import redact_child_result, redact_child_text, redact_child_value+from tools.delegation_redaction import (+ parent_copy, redact_child_result, redact_child_text, redact_child_value, redact_summary,+)logger = logging.getLogger("tools.delegate_tool") # log-record parity with the origin module@@ -182,8 +183,9 @@ def _spill_summary_to_file(task_index: int, summary: str) -> Optional[str]:from tools.spill_safety import write_text_exclusive# Exclusive symlink-refusing create; not private because cache/delegation is bind-mounted read-only into# remote backends whose container UID must be able to read it.- # Forced: the spill file persists and is bind-mounted into remote backends.- write_text_exclusive(path, redact_for_egress(summary), private=False)+ # ``summary`` is already the forced, structure-preserving projection (_trim_summary_with_footer); a+ # second whole-text pass here would eat JSON delimiters and corrupt a valid structured answer.+ write_text_exclusive(path, summary, private=False)return str(path)except Exception as exc:logger.debug("Failed to spill subagent summary to file: %s", exc)@@ -193,8 +195,20 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple["""``(model_text, spill_path)`` for one over-budget summary: a ~75% head / ~25% tail window snapped to lineboundaries (so the opening AND the closing outcomes/files-changed/issues both survive), the full text spilledto disk, and a footer giving the exact ``read_file offset=`` for the omitted middle."""- # ``summary`` is the parent's copy (already scrubbed per the user's setting in _finalize_child_results);- # the spill write below is forced regardless.+ # ``summary`` is the parent's copy (scrubbed per the user's setting in _finalize_child_results), carrying the+ # forced projection of the COMPLETE output. The spill file and the forced (memory/hook/ledger) excerpt are cut+ # from that projection: trimming the opt-out copy first can drop a PEM BEGIN marker and leave an unrecognizable+ # key body behind. Direct callers pass plain text: project it here (idempotent on already-forced text).+ forced = redact_child_text(summary) if hasattr(summary, "forced") else redact_summary(summary, True, True)+ spill_path = _spill_summary_to_file(task_index, forced)+ if spill_path:+ # Agent-visible path: the parent's read_file runs inside the active backend (#81984, #77015).+ from tools.credential_files import to_agent_visible_cache_path+ spill_path = to_agent_visible_cache_path(spill_path)+ model_text = _head_tail_with_footer(str(summary), cap, spill_path)+ return parent_copy(model_text, _head_tail_with_footer(forced, cap, spill_path)), spill_path++def _head_tail_with_footer(summary: str, cap: int, spill_path: Optional[str]) -> str:original_len = len(summary)head_budget = int(cap * 0.75)tail_budget = cap - head_budget@@ -205,12 +219,6 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[nl = tail.find("\n")if 0 <= nl < tail_budget * 0.5:tail = tail[nl + 1:]-- spill_path = _spill_summary_to_file(task_index, summary)- if spill_path:- # Agent-visible path: the parent's read_file runs inside the active backend (#81984, #77015).- from tools.credential_files import to_agent_visible_cache_path- spill_path = to_agent_visible_cache_path(spill_path)footer_lines = ["", "─" * 8 + " [SUMMARY TRUNCATED] " + "─" * 8,f"Showing {len(head):,} chars (head) + {len(tail):,} chars (tail) "@@ -227,7 +235,7 @@ def _trim_summary_with_footer(summary: str, cap: int, task_index: int) -> tuple[else:footer_lines.append("Full output could not be stored to disk; the head+tail above is all that was preserved.")footer_lines.append("─" * 37)- return head + "\n\n[... middle omitted — see footer ...]\n\n" + tail + "\n".join(footer_lines), spill_path+ return head + "\n\n[... middle omitted — see footer ...]\n\n" + tail + "\n".join(footer_lines)def _parent_prompt_size_tokens(parent_agent) -> Optional[int]:"""The parent's current prompt size: the aggregator's own last ``prompt_tokens`` (pre-MoA-fold), else@@ -406,9 +414,15 @@ def _finalize_child_results(with _parent_finalization_lock(parent_agent):child_by_index = {index: child for index, _task, child in children}for entry in results:- child = child_by_index.get(entry.get("task_index"))- # The parent's own copy honours security.redact_secrets=false; spill/memory/hooks force their own scrub.- entry.update(redact_child_result(entry, getattr(child, "_delegate_output_schema", None), force=False))+ schema = getattr(child_by_index.get(entry.get("task_index")), "_delegate_output_schema", None)+ # Fork the forced, structure-preserving projection from the COMPLETE output before the parent budget+ # trims anything; spill/memory/hooks/the durable row read it. The parent's own copy honours+ # security.redact_secrets=false.+ summary = entry.get("summary")+ forced = redact_summary(summary, isinstance(schema, dict) or "schema_valid" in entry, True)+ entry.update(redact_child_result(entry, schema, force=False))+ if isinstance(summary, str) and isinstance(entry.get("summary"), str):+ entry["summary"] = parent_copy(entry["summary"], forced)_apply_summary_budget(results, parent_agent)_notify_memory_manager(results, task_list, child_by_index, parent_agent)_rollup_children_cost(parent_agent, _fire_subagent_stop_hooks(results, child_by_index, parent_agent))diff --git a/tools/delegation_redaction.py b/tools/delegation_redaction.pyindex e5ab7c7d185..5a58977675a 100644--- a/tools/delegation_redaction.py+++ b/tools/delegation_redaction.py@@ -52,8 +52,29 @@ _RESULT_METADATA = frozenset()+class _ParentCopy(str):+ """The parent's own (opt-out) text carrying the forced projection of the same output.++ The forced copy is made from the complete output *before* the parent's copy is+ budget-trimmed: a head/tail cut can drop a PEM ``BEGIN`` marker and leave a key body+ the text redactor no longer recognizes. Persistent/external sinks read ``forced``."""++ forced: str+++def parent_copy(text: str, forced: str) -> str:+ """``text`` for the parent, remembering ``forced`` for persistent sinks (plain str when equal)."""+ if text == forced:+ return text+ carrier = _ParentCopy(text)+ carrier.forced = forced+ return carrier++def redact_child_text(text: Any, *, force: bool = True) -> str:"""Scrub one child-produced string. ``force=False`` honours the user's opt-out."""+ if isinstance(text, _ParentCopy): # already projected; forced sinks take the pre-trim projection+ return text.forced if force else textif force or _redact._redact_enabled():return redact_for_egress(text)try: # opted out: vault values only (still a hard boundary)@@ -103,13 +124,15 @@ def redact_child_value(value: Any, *, force: bool = True, _depth: int = 0) -> Anreturn REDACTION_UNAVAILABLE-def _redact_summary(summary: Any, structured: bool, force: bool) -> Any:+def redact_summary(summary: Any, structured: bool, force: bool) -> Any:"""Structured (schema) summaries are redacted per value and re-serialized: a textpass can eat JSON delimiters (``KEY=***`` swallowing the closing quote and comma)and break an answer that was valid. The JSON is located with the validator's ownextraction grammar (code fence / surrounding prose), so every wrapper the validatoraccepts stays accepted; the wrapper text gets the text pass. Unchanged output keepsits original formatting; anything without a parseable candidate gets the text pass."""+ if isinstance(summary, _ParentCopy):+ return redact_child_text(summary, force=force)if structured and isinstance(summary, str):from tools.delegation_output_schema import extract_json_candidate@@ -147,7 +170,7 @@ def redact_child_result(result: dict[str, Any], output_schema=None, *, force: bofor entry in value]elif key == "summary":- cleaned[key] = _redact_summary(value, structured, force)+ cleaned[key] = redact_summary(value, structured, force)else:cleaned[key] = (value if key in _RESULT_METADATA else redact_child_value(value, force=force)