Skip to content
Closed
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
113 changes: 112 additions & 1 deletion agent/trajectory.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,11 +7,116 @@

import json
import logging
import os
from datetime import datetime
from typing import Any, Dict, List
from pathlib import Path
from typing import Any, Dict, List, Optional

from hermes_constants import get_hermes_home

logger = logging.getLogger(__name__)

# Redirects already reported, keyed by (source, target). A datagen run appends
# once per turn; the destination only needs to be announced once per process.
_REDIRECT_WARNED: set[tuple[str, str]] = set()


def _find_git_root(start: Path) -> Optional[Path]:
"""Walk *start* and its parents looking for a ``.git`` entry.

Returns the directory containing ``.git``, or ``None`` if we reach the
filesystem root without finding one. Mirrors
``agent.prompt_builder._find_git_root``. ``.exists()`` (not ``.is_dir()``)
because a linked worktree and a submodule both carry ``.git`` as a *file*
holding a gitdir pointer, and a transcript is just as committable there.
"""
try:
current = start.resolve()
except OSError: # pragma: no cover - defensive: unresolvable cwd
return None
for parent in [current, *current.parents]:
if (parent / ".git").exists():
return parent
return None


def _allow_git_cwd() -> bool:
"""Read ``agent.trajectory_allow_git_cwd`` (default False).

Config is loaded lazily and read-only, per the ``moa_trace`` precedent:
this runs once per saved trajectory, not per tool iteration. Any failure
means "not allowed", which keeps the safe placement on a broken config
rather than falling back into the checkout.
"""
try:
from hermes_cli.config import load_config_readonly

agent_cfg = (load_config_readonly() or {}).get("agent") or {}
return bool(agent_cfg.get("trajectory_allow_git_cwd", False))
except Exception: # pragma: no cover - defensive
return False


def resolve_trajectory_path(filename: str) -> str:
"""Keep a relative trajectory filename out of a git work tree.

``save_trajectory`` is called from ``finalize_turn``, so its default
relative filename resolves against whatever CWD the agent was launched in
— routinely a source checkout. A full verbatim transcript (message text,
tool results, tool-call arguments) then lands next to the source as an
untracked file, one ``git add -A`` away from being published.

So when the resolved target sits inside a git work tree, place the file
under ``<HERMES_HOME>/trajectories/`` instead and say so. Nothing is
dropped or truncated — trajectories are training data and stay
full-fidelity; only the destination changes, to the same private directory
the rest of Hermes' state already uses.

Three escape hatches keep CWD placement supported:

* an **absolute** ``filename`` is honoured as-is — an explicit path is a
deliberate choice, not an ambient default;
* ``agent.trajectory_allow_git_cwd: true`` in ``config.yaml`` restores the
old behaviour globally;
* a CWD outside any git work tree (a scratch dir, ``/tmp``, a datagen box)
is untouched, which is the common datagen shape already.

Returns the path to write, as a string. On any unexpected failure the
original *filename* is returned so tracing never breaks a turn.
"""
try:
path = Path(filename)
if path.is_absolute():
return filename

target = Path(os.getcwd()) / path
git_root = _find_git_root(target.parent)
if git_root is None or _allow_git_cwd():
return filename

base = get_hermes_home() / "trajectories"
# Preserve any relative subdirectory the caller asked for so two
# callers using the same basename don't collide, but never let ".."
# walk the write back out of the trajectories dir.
relative = path if ".." not in path.parts else Path(path.name)
redirected = base / relative
redirected.parent.mkdir(parents=True, exist_ok=True)

key = (str(target), str(redirected))
if key not in _REDIRECT_WARNED:
_REDIRECT_WARNED.add(key)
logger.warning(
"Trajectory would have been written inside the git work tree at %s; "
"writing to %s instead so a full transcript is not left in your "
"checkout. Set agent.trajectory_allow_git_cwd: true in config.yaml "
"to write to the working directory anyway, or pass an absolute path.",
git_root, redirected,
)
return str(redirected)
except Exception as e: # pragma: no cover - defensive
logger.debug("Trajectory path resolution failed (%s); using %s", e, filename)
return filename


def convert_scratchpad_to_think(content: str) -> str:
"""Convert <REASONING_SCRATCHPAD> tags to <think> tags."""
Expand All @@ -37,10 +142,16 @@ def save_trajectory(trajectory: List[Dict[str, Any]], model: str,
completed: Whether the conversation completed successfully.
filename: Override output filename. Defaults to trajectory_samples.jsonl
or failed_trajectories.jsonl based on ``completed``.

A *relative* filename that would land inside a git work tree is redirected
under ``<HERMES_HOME>/trajectories/`` — see :func:`resolve_trajectory_path`.
Absolute paths are always honoured as given.
"""
if filename is None:
filename = "trajectory_samples.jsonl" if completed else "failed_trajectories.jsonl"

filename = resolve_trajectory_path(filename)

entry = {
"conversations": trajectory,
"timestamp": datetime.now().isoformat(),
Expand Down
15 changes: 15 additions & 0 deletions cli-config.yaml.example
Original file line number Diff line number Diff line change
Expand Up @@ -821,6 +821,21 @@ agent:
# Recommended: 20-30 for focused tasks, 50-100 for open exploration
max_turns: 500

# Allow trajectory JSONL to be written into a git work tree (default: false).
#
# Trajectory saving (AIAgent(save_trajectories=True) /
# `run_agent.py --save_trajectories`) appends a full verbatim transcript —
# message text, tool results and tool-call arguments — to a CWD-relative
# file. Launched from a source checkout, that leaves an untracked
# trajectory_samples.jsonl next to your code, one `git add -A` away from
# being committed. By default such a write is redirected under
# <HERMES_HOME>/trajectories/ (nothing is dropped, only relocated) and a
# warning names the destination.
#
# Set true to restore writing to the working directory. Passing an absolute
# filename to save_trajectory() also bypasses the redirect.
# trajectory_allow_git_cwd: false

# Inactivity timeout for gateway agent runs (seconds, 0 = unlimited).
# The agent can run indefinitely when actively calling tools or receiving
# API responses. Only fires after the agent has been idle for this duration.
Expand Down
12 changes: 12 additions & 0 deletions hermes_cli/config_defaults.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,18 @@
"max_live_sessions": 16,
"agent": {
"max_turns": 500,
# Allow trajectory JSONL to be written into a git work tree.
# save_trajectory() (AIAgent(save_trajectories=True) /
# `run_agent.py --save_trajectories`) appends a full verbatim
# transcript — message text, tool results, tool-call arguments — under
# a CWD-relative filename, so an agent run launched from a source
# checkout dropped one next to the user's code, one `git add -A` from
# being published (#77472). Default False redirects such a write under
# ``<HERMES_HOME>/trajectories/`` and warns with the destination;
# nothing is dropped or truncated, only relocated. Set True to restore
# writing to the working directory (passing an absolute filename also
# bypasses the redirect).
"trajectory_allow_git_cwd": False,
# Inactivity timeout for gateway agent execution (seconds).
# The agent can run indefinitely as long as it's actively calling
# tools or receiving API responses. Only fires when the agent has
Expand Down
8 changes: 7 additions & 1 deletion run_agent.py
Original file line number Diff line number Diff line change
Expand Up @@ -205,6 +205,7 @@ def _session_source_for_agent(platform: Optional[str]) -> str:
)
from agent.trajectory import (
convert_scratchpad_to_think,
resolve_trajectory_path,
save_trajectory as _save_trajectory_to_file,
)
from agent.tool_dispatch_helpers import (
Expand Down Expand Up @@ -7900,6 +7901,8 @@ def main(
print("💾 Trajectory saving: ENABLED")
print(" - Successful conversations → trajectory_samples.jsonl")
print(" - Failed conversations → failed_trajectories.jsonl")
print(" - Inside a git work tree these are written under "
"<HERMES_HOME>/trajectories/ instead (agent.trajectory_allow_git_cwd: true to override)")

# Initialize agent with provided parameters
try:
Expand Down Expand Up @@ -7948,7 +7951,10 @@ def main(
# Save sample trajectory to UUID-named file if requested
if save_sample:
sample_id = str(uuid.uuid4())[:8]
sample_filename = f"sample_{sample_id}.json"
# Same class of write as save_trajectory: a full verbatim trajectory
# under a relative name, so it lands in the CWD — a source checkout as
# often as not. Route it through the same guard.
sample_filename = resolve_trajectory_path(f"sample_{sample_id}.json")

# Convert messages to trajectory format (same as batch_runner)
trajectory = agent._convert_to_trajectory_format(
Expand Down
Loading