The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
feat(delegation): recovery event carries transcript tails and owner git state
teknium1a2b6f5324520
diff --git a/tests/tools/test_delegation_recovery_diagnostics.py b/tests/tools/test_delegation_recovery_diagnostics.pyindex 21339bcb177..7fbdbc0f080 100644--- a/tests/tools/test_delegation_recovery_diagnostics.py+++ b/tests/tools/test_delegation_recovery_diagnostics.py@@ -93,5 +93,13 @@ print(json.dumps([{"event": event, "message": format_process_notification(event)by_index[index] = pathfor path in transcripts:assert (path in item['message']) == (path in paths.values())+ # #116000: the event itself carries what the parent needs to continue — the verbatim+ # transcript tail per task and the owner's git state — on both renderers (single/batch).+ tails = event.get("transcript_tails") or {}+ assert set(tails) == set(paths)+ for index, tail in tails.items():+ assert "kickoff" in tail and tail in item["message"]+ assert "uncommitted file(s)" in event["git_state_hint"]+ assert event["git_state_hint"] in item["message"]assert set(by_index) == ({'1'} if missing_writer else {'0', '1'} if split else {'0'})assert set(by_index.values()) == set(transcripts)diff --git a/tools/async_delegation.py b/tools/async_delegation.pyindex 6ca34ba6d27..65186f44e5b 100644--- a/tools/async_delegation.py+++ b/tools/async_delegation.py@@ -143,6 +143,10 @@ def _persist_dispatch(record: Dict[str, Any]) -> None:key: record.get(key)for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch", "task_indexes", "task_transcripts", *_ROUTING_KEYS)if key in record}+ try: # where the children's terminals started; lets recovery add a git-state hint+ task_payload["owner_cwd"] = os.getcwd()+ except OSError:+ passwith _DB_LOCK, _transaction() as conn:conn.execute("""INSERT OR REPLACE INTO async_delegations(delegation_id, origin_session, origin_ui_session_id,@@ -248,6 +252,13 @@ def recover_abandoned_delegations() -> int:error = (f"Delegation owner exited before the unit finished; {done}/{len(recovered_results)} child ""results were recorded and are included below, the rest are unknown.")diagnostics = {"last_known_status": last_state, "task_transcripts": task.get("task_transcripts") or {}}+ # Verbatim transcript tails + a git snapshot of the owner's cwd, so the parent can+ # continue or re-dispatch from the event alone instead of opening files (#116000).+ from tools.async_delegation_recovery_hints import git_state_hint, transcript_tails+ if tails := transcript_tails(diagnostics["task_transcripts"]):+ diagnostics["transcript_tails"] = tails+ if hint := git_state_hint(task.get("owner_cwd")):+ diagnostics["git_state_hint"] = hintevent = {"type": "async_delegation", "delegation_id": delegation_id, "session_key": session_key,"origin_ui_session_id": origin_ui, "origin_session_id": origin_sid or "",diff --git a/tools/async_delegation_recovery_hints.py b/tools/async_delegation_recovery_hints.pynew file mode 100644index 00000000000..7426ed3587d--- /dev/null+++ b/tools/async_delegation_recovery_hints.py@@ -0,0 +1,62 @@+"""Forensic hints attached to an abandoned-delegation recovery event.++When the owner process dies (OOM-kill, crash) before a background child records a+terminal result, the recovery event used to carry only "outcome unknown" plus the+transcript paths — the parent then had to open files to find out where the child+got to. These helpers put the last lines of each live transcript and a one-line git+snapshot of the owner's working directory INTO the event so the parent can decide+whether to continue or re-dispatch without forensics. Everything here is best-effort+and bounded: a missing file, a non-git cwd or a slow git never fails recovery.+"""++from __future__ import annotations++import os+import subprocess+from typing import Dict, Optional++TAIL_LINES = 20+TAIL_CHARS = 2_000+_GIT_TIMEOUT_S = 5+++def transcript_tail(path: str, *, lines: int = TAIL_LINES, chars: int = TAIL_CHARS) -> Optional[str]:+ """Last ``lines`` lines (at most ``chars`` characters) of a live transcript; None when unreadable."""+ try:+ with open(path, "rb") as fh:+ fh.seek(0, os.SEEK_END)+ size = fh.tell()+ fh.seek(max(0, size - chars * 4)) # a few bytes per char of headroom; bounded read+ raw = fh.read().decode("utf-8", errors="replace")+ except OSError:+ return None+ tail = "\n".join(raw.splitlines()[-lines:]).strip()+ if len(tail) > chars:+ tail = "…" + tail[-chars:]+ return tail or None+++def transcript_tails(paths: Dict[str, str]) -> Dict[str, str]:+ return {index: tail for index, path in (paths or {}).items() if (tail := transcript_tail(path))}+++def git_state_hint(cwd: Optional[str]) -> Optional[str]:+ """``branch @ sha (N uncommitted file(s))`` for the owner's cwd; None when not a git checkout."""+ if not cwd or not os.path.isdir(cwd):+ return None++ def run(*args: str) -> Optional[str]:+ try:+ out = subprocess.run(["git", "-C", cwd, *args], capture_output=True, text=True,+ stdin=subprocess.DEVNULL, timeout=_GIT_TIMEOUT_S)+ except (OSError, subprocess.SubprocessError):+ return None+ return out.stdout if out.returncode == 0 else None++ head = run("log", "-1", "--format=%h %s")+ if head is None:+ return None+ branch = (run("rev-parse", "--abbrev-ref", "HEAD") or "?").strip()+ status = run("status", "--porcelain")+ dirty = len(status.splitlines()) if status is not None else "?"+ return f"{branch} @ {head.strip()} ({dirty} uncommitted file(s)) in {cwd}"diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.pyindex e6ebb1b5925..5301fcc640c 100644--- a/tools/process_registry_notifications.py+++ b/tools/process_registry_notifications.py@@ -175,6 +175,23 @@ def _format_task_failure_notice(evt: dict, deleg_id: str) -> str:return "\n".join(line for line in lines if line)+def _recovery_lines(evt: dict) -> "list[str]":+ """Owner-died recovery diagnostics (``recover_abandoned_delegations``): last persisted+ status, per-task transcript paths, their verbatim tails and the owner's git state."""+ if not evt.get("last_known_status"):+ return []+ lines = [f"Last persisted unit status: {evt['last_known_status']} (before owner exit; not current liveness). "+ "Unrecorded outcomes remain unknown; inspect evidence before retrying side effects."]+ tails = evt.get("transcript_tails") or {}+ for index, path in (evt.get("task_transcripts") or {}).items():+ lines.append(f"Task index {index} transcript (may be incomplete): {path}")+ if tails.get(index):+ lines += [f"--- last lines of task {index} transcript ---", tails[index], "--- end ---"]+ if evt.get("git_state_hint"):+ lines.append(f"Owner working tree at recovery: {evt['git_state_hint']}")+ return lines++def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> str:"""Consolidated block for a delegate_task fan-out that finished as one unit."""results, goals = evt.get("results") or [], evt.get("goals") or []@@ -191,11 +208,7 @@ def _format_batch_delegation(evt: dict, deleg_id: str, completed_at: float) -> s"on siblings, end your turn after acting on this one.",completed_at, with_goal=False)lines[-1] += f" Total duration: {evt.get('total_duration_seconds', evt.get('duration_seconds', '?'))}s"- if evt.get("last_known_status"):- lines.append(f"Last persisted unit status: {evt['last_known_status']} (before owner exit; not current liveness). "- "Unrecorded outcomes remain unknown; inspect evidence before retrying side effects.")- for index, path in (evt.get("task_transcripts") or {}).items():- lines.append(f"Task index {index} transcript (may be incomplete): {path}")+ lines += _recovery_lines(evt)if evt.get("error") and not results:lines += ["--- ERROR ---", f"The batch did not complete successfully: {evt['error']}"]return "\n".join(lines)@@ -277,9 +290,10 @@ def _format_async_delegation(evt: dict) -> str:else:if status == "interrupted":lines.append("The subagent was interrupted before completing" + (f": {error}" if error else "."))- else: # error / timeout / failed+ else: # error / timeout / failed / unknown (owner died)lines.append(f"The subagent did not complete successfully (status={status})." + (f"\n{error}" if error else ""))+ lines += _recovery_lines(evt)if summary:lines += ["Partial output:", summary]return "\n".join(lines)