Skip to content

The agent that grows with you

fix(delegation): surface the skipped home pin and prune the pinned root

liuhao1024573872302543
diff --git a/tests/tools/test_delegation_live_log.py b/tests/tools/test_delegation_live_log.py
index dd959500156..eba7e58fa02 100644
--- a/tests/tools/test_delegation_live_log.py
+++ b/tests/tools/test_delegation_live_log.py
@@ -312,6 +312,57 @@ def test_manifest_update_uses_same_explicit_home(tmp_path, monkeypatch):
assert manifest["tasks"][0]["status"] == "completed"
+def test_parent_without_session_db_warns_and_skips_pin(caplog):
+ """A parent with no _session_db cannot be pinned; the skip must be
+ observable (ambient fallback is the #91996 failure mode), not silent."""
+ import logging as _logging
+
+ from tools.delegate_tool import _parent_live_home
+
+ parent = MagicMock(spec=[]) # no _session_db attribute at all
+
+ with caplog.at_level(_logging.WARNING, logger="tools.delegate_tool"):
+ assert _parent_live_home(parent) is None
+ assert any("home pinning skipped" in r.getMessage() for r in caplog.records), (
+ "the ambient fallback must leave a warning trace"
+ )
+
+
+def test_parent_session_db_pins_home():
+ from tools.delegate_tool import _parent_live_home
+
+ parent = MagicMock(spec=["_session_db"])
+ parent._session_db.db_path = Path("/prof/state.db")
+
+ assert _parent_live_home(parent) == Path("/prof")
+
+
+def test_prune_sweeps_the_pinned_root_not_ambient(tmp_path, monkeypatch):
+ """Retention must clean where the dispatch writes: stale dirs under the
+ pinned home are removed by that home's dispatches; a stale dir under the
+ ambient root is NOT this dispatch's business."""
+ ambient_home = tmp_path / "ambient"
+ pinned_home = tmp_path / "pinned"
+ ambient_home.mkdir()
+ pinned_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(ambient_home))
+
+ stale_age = time.time() - (dll.LIVE_RETENTION_DAYS + 1) * 86400
+ stale_pinned = pinned_home / "cache" / "delegation" / "live" / "old-deleg"
+ stale_pinned.mkdir(parents=True)
+ os.utime(stale_pinned, (stale_age, stale_age))
+ stale_ambient = (
+ ambient_home / "cache" / "delegation" / "live" / "other-profile-deleg"
+ )
+ stale_ambient.mkdir(parents=True)
+ os.utime(stale_ambient, (stale_age, stale_age))
+
+ create_live_transcripts([{"goal": "sweep my own root"}], home=pinned_home)
+
+ assert not stale_pinned.exists(), "pinned home's own stale dir must be pruned"
+ assert stale_ambient.exists(), "ambient root is not this dispatch's root"
+
+
def test_manifest_includes_model_and_provider():
"""The manifest.json should record the model and provider used for the delegation."""
delegation_id, _writers, _paths = create_live_transcripts(
diff --git a/tools/delegate_tool.py b/tools/delegate_tool.py
index c9d6f93b862..bcf9c920d98 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -14,6 +14,7 @@ tool calls or reasoning.
import logging
import time
import weakref
+from pathlib import Path
from typing import Any, Dict, List, Optional
from tools.terminal_tool import set_approval_callback as _set_subagent_approval_cb # noqa: F401 (used via _ChildRun.await_child)
@@ -58,6 +59,27 @@ from tools.delegate_tool_results import ( # noqa: F401
_ROLES = frozenset({"leaf", "orchestrator"})
+
+def _parent_live_home(parent_agent: Any) -> Optional[Path]:
+ """Resolve the live transcripts' profile home from parent-owned state.
+
+ The parent's per-profile SessionDB sits directly under its profile home
+ (``<home>/state.db``), so the db path's parent IS the home. Returns None
+ when the parent exposes no SessionDB — the caller then falls back to the
+ ambient resolve, which is exactly the #91996 failure mode, so the skip is
+ logged rather than silent.
+ """
+ parent_db = getattr(getattr(parent_agent, "_session_db", None), "db_path", None)
+ if parent_db is not None:
+ return parent_db.parent
+ logger.warning(
+ "delegate_task: parent agent exposes no _session_db; live-transcript "
+ "home pinning skipped, falling back to ambient HERMES_HOME resolve "
+ "(transcripts may land in a different profile, #91996)"
+ )
+ return None
+
+
# Nested delegation is granted by depth/role in _build_child_agent, never by the
# model naming toolsets (there is no model-facing toolsets argument).
def _normalize_role(r: Optional[str]) -> str:
@@ -520,11 +542,9 @@ def delegate_task(
# and process-wide HERMES_HOME is unstable under concurrent
# multi-profile workers — either way transcripts could land in the
# wrong profile (#91996). state.db sits directly under the home, so
- # its parent IS the home; None falls back to today's ambient resolve.
- _live_home = None
- _parent_db = getattr(getattr(parent_agent, "_session_db", None), "db_path", None)
- if _parent_db is not None:
- _live_home = _parent_db.parent
+ # its parent IS the home; None falls back to today's ambient resolve
+ # (with a warning — that fallback is exactly the #91996 failure mode).
+ _live_home = _parent_live_home(parent_agent)
from tools.delegation_live_log import create_live_transcripts
live_deleg_id, live_writers, live_paths = create_live_transcripts(
@@ -543,6 +563,7 @@ def delegate_task(
batch = _Batch(
task_list, children, parent_agent, creds, context, top_role, max_children,
live_deleg_id, live_writers, live_paths, *origin, overall_start,
+ live_home=_live_home,
)
return _run_batch(batch, background)
diff --git a/tools/delegate_tool_dispatch.py b/tools/delegate_tool_dispatch.py
index 2d23e039199..9044c20766b 100644
--- a/tools/delegate_tool_dispatch.py
+++ b/tools/delegate_tool_dispatch.py
@@ -49,6 +49,7 @@ class _Batch:
# Set on per-group units carved out by ``_dispatch_background``; None for the whole batch / ungrouped units.
group: Optional[str] = None
unit_id: Optional[str] = None # the async registry id this unit runs under (``<call_id>-k`` for split calls)
+ live_home: Any = None # explicit profile home for transcripts/manifest (#91996); None = ambient resolve
def owner_kwargs(self) -> Dict[str, Any]:
"""Steer/stop authority of the originating session, passed to every child run."""
@@ -202,7 +203,7 @@ def _execute_and_aggregate(batch: _Batch, *, honor_parent_interrupt: bool = True
batch.live_writers[_idx].finalize(entry)
if _idx < len(batch.live_paths):
entry["live_transcript"] = batch.live_paths[_idx]
- update_manifest_statuses(batch.live_deleg_id, results)
+ update_manifest_statuses(batch.live_deleg_id, results, home=batch.live_home)
finish_delegation_unit(batch.task_list, results, background=not honor_parent_interrupt)
combined: Dict[str, Any] = {"results": results, "total_duration_seconds": total_duration}
diff --git a/tools/delegation_live_log.py b/tools/delegation_live_log.py
index c1b46d437f2..bd3e9d0c19b 100644
--- a/tools/delegation_live_log.py
+++ b/tools/delegation_live_log.py
@@ -244,10 +244,11 @@ def create_live_transcripts(
``home`` pins every transcript and the manifest to one explicit profile
home instead of an ambient resolve that raw thread boundaries can strip
- of its ContextVar override (#91996).
+ of its ContextVar override (#91996). Retention pruning runs against the
+ same resolved root, so pinned homes clean their own stale dirs.
"""
n = len(task_list)
- prune_stale_live_dirs() # best-effort; never raises
+ prune_stale_live_dirs(root=live_transcript_root(home)) # best-effort; never raises
with _best_effort("creation"):
# Same id shape as async_delegation's so the dir name matches the handle.
deleg_id = delegation_id or f"deleg_{uuid.uuid4().hex[:8]}"
@@ -270,6 +271,7 @@ def _manifest_path(delegation_id: str, home: Optional[Path] = None) -> Path:
def _write_manifest(delegation_id: str, task_list: List[Dict[str, Any]],
paths: List[str], model: Optional[str] = None,
+ provider: Optional[str] = None, home: Optional[Path] = None) -> None:
with _best_effort("manifest write"):
_dump_json(_manifest_path(delegation_id, home), {
"delegation_id": delegation_id, "started": time.strftime(_TIME_FMT),
@@ -302,15 +304,20 @@ def update_manifest_statuses(delegation_id: Optional[str],
_dump_json(mp, manifest)
-def prune_stale_live_dirs(max_age_days: int = LIVE_RETENTION_DAYS) -> int:
- """Remove live/<delegation_id> dirs older than the retention window. Best-effort."""
+def prune_stale_live_dirs(max_age_days: int = LIVE_RETENTION_DAYS, root: Optional[Path] = None) -> int:
+ """Remove live/<delegation_id> dirs older than the retention window. Best-effort.
+
+ ``root`` defaults to the ambient resolve; callers that pin transcripts to an
+ explicit home pass the same root so the prune sweeps where the writes actually
+ land (stale dirs under other profiles' roots stay those profiles' business).
+ """
removed = 0
with _best_effort("pruning"):
- root = live_transcript_root()
- if not root.is_dir():
+ root_dir = root if root is not None else live_transcript_root()
+ if not root_dir.is_dir():
return 0
cutoff = time.time() - max_age_days * 86400
- for child in root.iterdir():
+ for child in root_dir.iterdir():
try:
if child.is_dir() and child.stat().st_mtime < cutoff:
shutil.rmtree(child, ignore_errors=True)