Skip to content

The agent that grows with you

fix(delegation): retain recovery transcript locators

funky-xamarin21e3fa6b85c2
diff --git a/tests/tools/test_delegation_recovery_diagnostics.py b/tests/tools/test_delegation_recovery_diagnostics.py
new file mode 100644
index 00000000000..79c5d1832fd
--- /dev/null
+++ b/tests/tools/test_delegation_recovery_diagnostics.py
@@ -0,0 +1,98 @@
+"""Public dispatch/restart diagnostics for an owner lost before any child finishes."""
+import json
+import os
+from pathlib import Path
+import subprocess
+import sys
+
+import pytest
+
+
[email protected]("split,missing_writer", [(False, False), (True, False), (True, True)])
+def test_unfinished_delegation_recovery_keeps_transcript_locator(tmp_path, split, missing_writer):
+ repo = str(Path(__file__).resolve().parents[2])
+ handle_path = tmp_path / "dispatch.json"
+ env = {**os.environ, "HERMES_HOME": str(tmp_path), "PYTHONPATH": repo,
+ "REPRO_HANDLE": str(handle_path), "REPRO_SPLIT": str(int(split)),
+ "REPRO_MISSING": str(int(missing_writer))}
+ (tmp_path / 'config.yaml').write_text('delegation:\n independent_completions: true\n', encoding='utf-8')
+ producer = r'''
+import json, os, threading
+from pathlib import Path
+from unittest.mock import MagicMock
+import tools.delegate_tool as dt
+parent = MagicMock()
+parent._delegate_depth = 0
+parent.session_id = "diagnostic-parent"
+parent._interrupt_requested = False
+parent._active_children = []
+parent._active_children_lock = None
+started = threading.Event()
+blocked = threading.Event()
+def child(**kw):
+ started.set()
+ blocked.wait(60)
+def build(**kw):
+ c = MagicMock()
+ c._delegate_role = "leaf"
+ c._subagent_id = "diagnostic-child"
+ return c
+creds = dict(model="m", provider=None, base_url=None, api_key=None,
+ api_mode=None, command=None, args=None)
+dt._build_child_agent = build
+dt._run_single_child = child
+dt._resolve_delegation_credentials = lambda *a, **k: creds
+if os.environ['REPRO_MISSING'] == '1':
+ import tools.delegation_live_log as live
+ original = live.create_live_transcripts
+ def missing(*args, **kwargs):
+ ident, writers, paths = original(*args, **kwargs)
+ writers[0] = None
+ return ident, writers, paths[1:]
+ live.create_live_transcripts = missing
+kwargs = {'tasks': [{'goal': 'first diagnostic task'}, {'goal': 'second diagnostic task'}]} if os.environ['REPRO_SPLIT'] == '1' else {'goal': 'unfinished diagnostic task'}
+handle = json.loads(dt.delegate_task(**kwargs, background=True, parent_agent=parent))
+assert handle["status"] == "dispatched", handle
+assert started.wait(10), "child did not start"
+Path(os.environ["REPRO_HANDLE"]).write_text(json.dumps(handle), encoding="utf-8")
+os._exit(0)
+'''
+ first = subprocess.run([sys.executable, "-c", producer], cwd=repo, env=env,
+ text=True, capture_output=True, timeout=30)
+ assert first.returncode == 0, first.stdout + first.stderr
+ handle = json.loads(handle_path.read_text(encoding="utf-8"))
+ transcripts = handle["live_transcripts"]
+ assert all(Path(path).is_file() for path in transcripts)
+ consumer = r'''
+import json, queue
+from tools import async_delegation as ad
+from tools.process_registry import format_process_notification
+q = queue.Queue()
+count = ad.restore_undelivered_completions(q)
+events = [q.get_nowait() for _ in range(count)]
+print(json.dumps([{"event": event, "message": format_process_notification(event)} for event in events]))
+'''
+ second = subprocess.run([sys.executable, "-c", consumer], cwd=repo, env=env,
+ text=True, capture_output=True, timeout=20)
+ assert second.returncode == 0, second.stdout + second.stderr
+ restored = json.loads(second.stdout.strip().splitlines()[-1])
+ assert len(restored) == (2 if split else 1)
+ by_index = {}
+ for item in restored:
+ event = item['event']
+ assert event["status"] == "unknown"
+ assert event["last_known_status"] == "running"
+ assert "running" in item["message"]
+ assert not event.get("summary")
+ paths = event['task_transcripts']
+ assert len(paths) <= 1
+ for index, path in paths.items():
+ assert path in item['message']
+ assert Path(path).name == f'task-{index}.log'
+ assert index not in by_index
+ by_index[index] = path
+ for path in transcripts:
+ assert (path in item['message']) == (path in paths.values())
+ 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.py
index 2de901dc48e..ddbd37921cb 100644
--- a/tools/async_delegation.py
+++ b/tools/async_delegation.py
@@ -141,7 +141,7 @@ def _persist_dispatch(record: Dict[str, Any]) -> None:
owner_started_at = None
task_payload = {
key: record.get(key)
- for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch", "task_indexes", *_ROUTING_KEYS)
+ for key in ("goal", "goals", "context", "toolsets", "role", "model", "is_batch", "task_indexes", "task_transcripts", *_ROUTING_KEYS)
if key in record}
with _DB_LOCK, _transaction() as conn:
conn.execute("""INSERT OR REPLACE INTO async_delegations
@@ -232,10 +232,10 @@ def recover_abandoned_delegations() -> int:
with _DB_LOCK, _transaction() as conn:
rows = conn.execute("""SELECT delegation_id, origin_session, origin_ui_session_id,
parent_session_id, dispatched_at, owner_pid,
- owner_started_at, task_json, origin_session_id, result_json
+ owner_started_at, task_json, origin_session_id, result_json, state
FROM async_delegations WHERE state IN ('running','finalizing')""").fetchall()
for row in rows:
- delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json = row
+ delegation_id, session_key, origin_ui, parent_id, dispatched_at, pid, started, task_json, origin_sid, result_json, last_state = row
if pid and _pid_exists(int(pid)) and (started is None or get_process_start_time(int(pid)) == int(started)):
continue
task = json.loads(task_json or "{}")
@@ -245,17 +245,18 @@ def recover_abandoned_delegations() -> int:
done = sum(1 for r in recovered_results if r.get("status") != "unknown")
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 {}}
event = {
"type": "async_delegation", "delegation_id": delegation_id, "session_key": session_key,
"origin_ui_session_id": origin_ui, "origin_session_id": origin_sid or "",
"parent_session_id": parent_id, "goal": task.get("goal", ""), "goals": task.get("goals"),
"context": task.get("context"), "toolsets": task.get("toolsets"), "role": task.get("role"),
"model": task.get("model"), "is_batch": bool(task.get("is_batch")),
- "status": "unknown", "summary": None, "error": error,
+ "status": "unknown", "summary": None, "error": error, **diagnostics,
**({"results": recovered_results} if recovered_results else {}),
"dispatched_at": dispatched_at, "completed_at": now,
**{k: task[k] for k in _ROUTING_KEYS if task.get(k)}}
- result = {"status": "unknown", "summary": None, "error": event["error"],
+ result = {"status": "unknown", "summary": None, "error": event["error"], **diagnostics,
**({"results": recovered_results} if recovered_results else {})}
conn.execute("""UPDATE async_delegations SET state='unknown', completed_at=?,
updated_at=?, event_json=?, result_json=?, delivery_state='pending'
@@ -542,6 +543,7 @@ def _dispatch_admitted(
origin_session_id: str, interrupt_fn: Optional[Callable[[], None]], max_async_children: int,
progress_fn: Optional[Callable[[], tuple]], capacity_error: str, slot_key: Optional[str] = None,
task_indexes: Optional[List[int]] = None,
+ task_transcripts: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""Shared dispatch core for single (``goals is None``) and batch units. Capacity check +
record insert happen under ONE lock hold so concurrent dispatches can't both pass the check
@@ -563,6 +565,7 @@ def _dispatch_admitted(
"status": "running", "dispatched_at": dispatched_at, "completed_at": None,
"interrupt_fn": interrupt_fn, **({"is_batch": True} if is_batch else {}), "progress_fn": progress_fn,
"slot_key": slot_key or delegation_id,
+ **({"task_transcripts": dict(task_transcripts)} if task_transcripts else {}),
# Which of the call's ``goals`` this unit runs (None = all of them).
**({"task_indexes": list(task_indexes)} if task_indexes is not None else {}),
# The one stale-monitor thread serves every profile and starts with an empty Context;
@@ -653,6 +656,7 @@ def dispatch_async_delegation_batch(
max_async_children: int = _DEFAULT_MAX_ASYNC_CHILDREN, delegation_id: Optional[str] = None,
progress_fn: Optional[Callable[[], tuple]] = None, slot_key: Optional[str] = None,
task_indexes: Optional[List[int]] = None,
+ task_transcripts: Optional[Dict[str, str]] = None,
) -> Dict[str, Any]:
"""Dispatch a fan-out unit (a whole batch, or one ``group`` of a delegate_task call) as ONE
background unit: ``runner`` runs its tasks and returns the combined ``{"results": [...],
@@ -670,7 +674,7 @@ def dispatch_async_delegation_batch(
parent_session_id=parent_session_id, runner=runner,
origin_ui_session_id=origin_ui_session_id, origin_session_id=origin_session_id,
interrupt_fn=interrupt_fn, max_async_children=max_async_children, progress_fn=progress_fn, slot_key=slot_key,
- task_indexes=task_indexes,
+ task_indexes=task_indexes, task_transcripts=task_transcripts,
capacity_error=(
f"Async delegation capacity reached ({max_async_children} running). Wait for one to finish "
"(its result will re-enter the chat), or raise delegation.max_concurrent_children in "
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index 6e8a5408e07..f836cfd6b03 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -398,6 +398,10 @@ def _dispatch_unit(unit: _Batch, unit_id: Optional[str], slot_key: Optional[str]
runner=lambda: _execute_and_aggregate(unit, honor_parent_interrupt=False),
interrupt_fn=_interrupt, delegation_id=unit_id, slot_key=slot_key,
task_indexes=[i for (i, _, _) in unit.children] if len(unit.children) < len(unit.task_list) else None,
+ # Persist locators before starting workers; live_paths omits failed writers and can be compressed.
+ task_transcripts={str(i): str(unit.live_writers[i].path) for i, _, _ in unit.children
+ if i < len(unit.live_writers) and unit.live_writers[i] is not None
+ and unit.live_writers[i].path is not None},
progress_fn=lambda: _batch_progress_token(child_agents), **routing,
)
diff --git a/tools/process_registry_notifications.py b/tools/process_registry_notifications.py
index 02288733ed9..d7d9e47c0b3 100644
--- a/tools/process_registry_notifications.py
+++ b/tools/process_registry_notifications.py
@@ -191,6 +191,11 @@ 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}")
if evt.get("error") and not results:
lines += ["--- ERROR ---", f"The batch did not complete successfully: {evt['error']}"]
return "\n".join(lines)