Skip to content

The agent that grows with you

fix(delegation): pin live transcripts to the parent's profile home

liuhao1024a45b5dba92bd
diff --git a/tests/tools/test_delegation_live_log.py b/tests/tools/test_delegation_live_log.py
index 5bc98225798..dd959500156 100644
--- a/tests/tools/test_delegation_live_log.py
+++ b/tests/tools/test_delegation_live_log.py
@@ -248,6 +248,70 @@ def test_manifest_goal_is_redacted():
assert "deploy using" in goal, "redaction must not blank the goal entirely"
+# ---------------------------------------------------------------------------
+# Explicit profile home (#91996)
+# ---------------------------------------------------------------------------
+
+def test_explicit_home_pins_transcripts_across_raw_thread_boundary(tmp_path, monkeypatch):
+ """Ambient resolve falls through to process HERMES_HOME when the session's
+ ContextVar override is dropped by a raw threading.Thread boundary; an
+ explicit home keeps transcripts + manifest under the originating profile."""
+ from hermes_constants import reset_hermes_home_override, set_hermes_home_override
+
+ process_home = tmp_path / "process-default"
+ session_home = tmp_path / "session-profile"
+ process_home.mkdir()
+ session_home.mkdir()
+
+ monkeypatch.setenv("HERMES_HOME", str(process_home))
+ token = set_hermes_home_override(session_home)
+ out = {}
+ try:
+ def worker():
+ _id, _writers, paths = create_live_transcripts(
+ [{"goal": "profile-pinned repro"}], home=session_home,
+ )
+ out["paths"] = paths
+
+ t = threading.Thread(target=worker)
+ t.start()
+ t.join()
+ finally:
+ reset_hermes_home_override(token)
+
+ expected_root = session_home / "cache" / "delegation" / "live"
+ assert out["paths"], "transcripts were created"
+ for p in out["paths"]:
+ assert Path(p).is_relative_to(expected_root), p
+ deleg_dir = Path(out["paths"][0]).parent
+ manifest = json.loads((deleg_dir / "manifest.json").read_text(encoding="utf-8"))
+ assert manifest["task_count"] == 1
+
+
+def test_manifest_update_uses_same_explicit_home(tmp_path, monkeypatch):
+ """update_manifest_statuses must resolve the manifest through the same
+ explicit home create used, or the status write is silently lost."""
+ ambient_home = tmp_path / "other-profile"
+ ambient_home.mkdir()
+ monkeypatch.setenv("HERMES_HOME", str(ambient_home))
+
+ home = tmp_path / "own-profile"
+ home.mkdir()
+
+ deleg_id, writers, paths = create_live_transcripts(
+ [{"goal": "pin me"}], home=home,
+ )
+ update_manifest_statuses(
+ deleg_id,
+ [{"task_index": 0, "status": "completed"}],
+ home=home,
+ )
+ manifest = json.loads(
+ (Path(paths[0]).parent / "manifest.json").read_text(encoding="utf-8")
+ )
+ assert manifest["tasks"][0]["status"] == "completed"
+
+
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 f091afdeb0a..c9d6f93b862 100644
--- a/tools/delegate_tool.py
+++ b/tools/delegate_tool.py
@@ -512,9 +512,24 @@ def delegate_task(
overall_start = time.monotonic()
# Live transcripts: cache/delegation/live/<id>/task-<n>.log per task, a side channel with zero effect on message
# content or prompt caching. Best-effort: on failure live_paths is empty and delegation proceeds.
+ #
+ # The transcripts' profile home is resolved from stable parent-owned
+ # state (the parent's per-profile SessionDB path), NOT ambient
+ # get_hermes_dir(): this thread may have crossed a raw threading.Thread
+ # boundary that dropped the session's _HERMES_HOME_OVERRIDE ContextVar,
+ # 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
+
from tools.delegation_live_log import create_live_transcripts
live_deleg_id, live_writers, live_paths = create_live_transcripts(
- task_list, context, model=creds.get("model"), provider=creds.get("provider")
+ task_list, context, model=creds.get("model"), provider=creds.get("provider"),
+ home=_live_home,
)
_announce_batch(parent_agent, len(task_list), live_deleg_id)
origin = _capture_origin()
diff --git a/tools/delegation_live_log.py b/tools/delegation_live_log.py
index 0d096a15852..c1b46d437f2 100644
--- a/tools/delegation_live_log.py
+++ b/tools/delegation_live_log.py
@@ -37,10 +37,18 @@ _STREAM_BUFFER_FLUSH_CHARS = 4000
_TIME_FMT = "%Y-%m-%d %H:%M:%S"
-def live_transcript_root() -> Path:
- """Root directory for live transcripts (profile-safe, never ~/.hermes)."""
+def live_transcript_root(home: Optional[Path] = None) -> Path:
+ """Root directory for live transcripts (profile-safe, never ~/.hermes).
+
+ Pass ``home`` when the caller holds stable parent-owned profile state
+ (e.g. the parent agent's SessionDB path). Ambient ``get_hermes_home()``
+ consults a ContextVar that raw ``threading.Thread`` boundaries drop, so
+ in a multi-profile process an ambient resolve can land transcripts under
+ whatever profile the process-wide ``HERMES_HOME`` names at that moment
+ (#91996).
+ """
from hermes_constants import get_hermes_dir
- return get_hermes_dir("cache/delegation", "delegation_cache") / "live"
+ return get_hermes_dir("cache/delegation", "delegation_cache", home=home) / "live"
@contextmanager
@@ -228,35 +236,42 @@ def create_live_transcripts(
task_list: List[Dict[str, Any]], context: Optional[str] = None,
delegation_id: Optional[str] = None, model: Optional[str] = None,
provider: Optional[str] = None,
+ home: Optional[Path] = None,
) -> tuple[Optional[str], List[Optional[LiveTranscriptWriter]], List[str]]:
"""One pre-headered writer per task + a manifest.json; prunes stale dirs.
Returns ``(delegation_id, writers, paths)``; on any top-level failure
- ``(None, [None]*n, [])`` so delegation proceeds untouched."""
+ ``(None, [None]*n, [])`` so delegation proceeds untouched.
+
+ ``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).
+ """
n = len(task_list)
prune_stale_live_dirs() # 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]}"
- made = [LiveTranscriptWriter(deleg_id, i, str(t.get("goal", "")), context=t.get("context") or context)
+ root = live_transcript_root(home)
+ made = [LiveTranscriptWriter(deleg_id, i, str(t.get("goal", "")),
+ context=t.get("context") or context, root=root)
for i, t in enumerate(task_list)]
writers: List[Optional[LiveTranscriptWriter]] = [w if w.path is not None else None for w in made]
paths: List[str] = [str(w.path) for w in made if w.path is not None]
if not paths:
return None, [None] * n, []
- _write_manifest(deleg_id, task_list, paths, model=model, provider=provider)
+ _write_manifest(deleg_id, task_list, paths, model=model, provider=provider, home=home)
return deleg_id, writers, paths
return None, [None] * n, []
-def _manifest_path(delegation_id: str) -> Path:
- return live_transcript_root() / delegation_id / "manifest.json"
+def _manifest_path(delegation_id: str, home: Optional[Path] = None) -> Path:
+ return live_transcript_root(home) / delegation_id / "manifest.json"
def _write_manifest(delegation_id: str, task_list: List[Dict[str, Any]],
paths: List[str], model: Optional[str] = None,
- provider: Optional[str] = None) -> None:
with _best_effort("manifest write"):
- _dump_json(_manifest_path(delegation_id), {
+ _dump_json(_manifest_path(delegation_id, home), {
"delegation_id": delegation_id, "started": time.strftime(_TIME_FMT),
"task_count": len(task_list), "model": model, "provider": provider,
"tasks": [{
@@ -268,12 +283,13 @@ def _write_manifest(delegation_id: str, task_list: List[Dict[str, Any]],
def update_manifest_statuses(delegation_id: Optional[str],
- results: List[Dict[str, Any]]) -> None:
+ results: List[Dict[str, Any]],
+ home: Optional[Path] = None) -> None:
"""Best-effort per-task status update once the batch has aggregated."""
if not delegation_id:
return
with _best_effort("manifest update"):
- mp = _manifest_path(delegation_id)
+ mp = _manifest_path(delegation_id, home)
manifest = json.loads(mp.read_text(encoding="utf-8-sig"))
by_index = {r.get("task_index"): r for r in results if isinstance(r, dict)}
for task in manifest.get("tasks", []):