Skip to content
22 changes: 18 additions & 4 deletions src/agent_env/agents/agents/claude-code/tar_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -49,8 +49,8 @@
_TAR_VERSION_TIMEOUT_S = 30
_FAILED_INCREMENTS_LOGGED = 5

# The post-tool hook, run by the agent's own Python, as a child of the CLI after every tool call, so an increment
# includes that tool's writes. It exits 0 on a capture error, so the error never reaches the model.
# The post-tool hook, run by the agent's own Python on real time, as a child of the CLI after every tool call, so an
# increment includes that tool's writes. It exits 0 on a capture error, so the error never reaches the model.
CAPTURE_SCRIPT = r'''import asyncio, fcntl, json, os, shutil, signal, subprocess, sys, time
from pathlib import Path

Expand All @@ -63,6 +63,10 @@
# tar's exit status when a file changed as it read it: the archive is still whole.
TAR_FILE_CHANGED_RC = 1
SIGTERM_EXIT_CODE = 143
# tar keeps the time it starts at as the next capture's baseline and archives only the files changed since, by their
# real mtimes, so it runs on real time. libfaketime takes the marker out of the environment of the process it's given
# to, so no child inherits it.
REAL_TIME_ENV = dict(os.environ, AGENTENV_REAL_TIME="1")


def _read_int(path):
Expand Down Expand Up @@ -221,6 +225,7 @@ def main():
["tar", "--ignore-failed-read", "--listed-incremental=" + work, "--exclude=" + changelog_dir,
"-czf", local, *members],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, pass_fds=(lock.fileno(),),
env=REAL_TIME_ENV,
)
archived = True
try:
Expand Down Expand Up @@ -261,6 +266,15 @@ def main():
sys.exit(0)
'''
_DEFAULT_CONFIG_LINE = 'CFG = "/tmp/changelog/config.json"'
# The hook decides by its own clock whether the grant it uploads with has expired, so it runs on real time, not the
# CLI's. env, started without the marker, sets it for the interpreter it execs, with or without a shell around it.
_REAL_TIME_LAUNCH = ("/usr/bin/env", "AGENTENV_REAL_TIME=1")


def _real_time_env() -> dict[str, str]:
"""This server's environment for the changelog's tar, whose start is the next capture's baseline, so on real time:
the server is, but libfaketime took the marker out of the server's environment, so what it starts isn't."""
return {**os.environ, "AGENTENV_REAL_TIME": "1"}


def gnu_tar() -> bool:
Expand Down Expand Up @@ -413,7 +427,7 @@ def __init__(
self.snar = f"{directory}/state.snar"
self.config_path = f"{directory}/config.json"
self.capture_path = f"{directory}/capture.py"
self.hook_command = f"{shlex.quote(sys.executable)} {shlex.quote(self.capture_path)}"
self.hook_command = shlex.join([*_REAL_TIME_LAUNCH, sys.executable, self.capture_path])

def capture_script(self) -> str:
"""``CAPTURE_SCRIPT`` reading this changelog's config."""
Expand Down Expand Up @@ -461,7 +475,7 @@ def _reset(self, roots: list[str], write_namespace: dict) -> None:
subprocess.run(
["tar", "--ignore-failed-read", f"--listed-incremental={self.snar}", f"--exclude={self.directory}",
"-cf", "/dev/null", *present],
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
check=False, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL, env=_real_time_env(),
)

async def apply(self, request: ObjectChangelogApplyRequest) -> ObjectChangelogApplyResponse:
Expand Down
11 changes: 9 additions & 2 deletions src/agent_env/agents/agents/opencode/a2a_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -517,7 +517,7 @@ async def _capture_changelog(self) -> None:
["tar", "--ignore-failed-read", f"--listed-incremental={pending_snar}",
*_changelog_backup_exclusions(),
f"--exclude={_CHANGELOG_DIR}", "-czf", str(archive), *roots, str(record)],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(),
)
await config["uploader"].upload(f"{sequence:06d}.tgz", archive)
pending_snar.replace(_CHANGELOG_SNAR)
Expand Down Expand Up @@ -643,10 +643,17 @@ def _baseline_changelog(roots: list[str]) -> None:
["tar", "--ignore-failed-read", f"--listed-incremental={_CHANGELOG_SNAR}",
*_changelog_backup_exclusions(),
"-cf", "/dev/null", *present],
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE,
check=True, stdout=subprocess.DEVNULL, stderr=subprocess.PIPE, env=_real_time_env(),
)


def _real_time_env() -> dict[str, str]:
"""This server's environment for the changelog's tar, which keeps the time it starts at as the next capture's
baseline and archives only the files changed since, by their real mtimes, so it runs on real time: the server
does, but libfaketime took the marker out of the server's environment, so what it starts doesn't."""
return {**os.environ, "AGENTENV_REAL_TIME": "1"}


def gnu_tar() -> bool:
"""Whether this host's tar is GNU tar, which the changelog's incremental archives need."""
try:
Expand Down
58 changes: 56 additions & 2 deletions tst/unit/agents/claude_code/test_changelog.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@
import email.policy
import json
import os
import shlex
import shutil
import subprocess
import sys
Expand All @@ -22,6 +23,7 @@

from tst.unit.agents.claude_code.agent import a2a_server, claude_bridge, tar_changelog
from tst.unit.agents.claude_code.support import expiry, extension_methods, read_grant
from tst.util import recording_tar

GNU_TAR = shutil.which("tar") is not None and tar_changelog.gnu_tar()
needs_gnu_tar = pytest.mark.skipif(not GNU_TAR, reason="the changelog is a GNU incremental tar")
Expand Down Expand Up @@ -139,8 +141,8 @@ def test_the_hook_waits_long_enough_for_its_turn_and_the_script_reads_its_own_co
log, _, _, _ = _changelog(tmp_path)
assert tar_changelog.HOOK_TIMEOUT_S == 600
assert f"CFG = {json.dumps(str(tmp_path / 'changelog' / 'config.json'))}" in log.capture_script()
assert log.hook_command.endswith(f"{tmp_path / 'changelog' / 'capture.py'}")
assert log.hook_command.split()[0] == sys.executable
capture = str(tmp_path / "changelog" / "capture.py")
assert shlex.split(log.hook_command) == ["/usr/bin/env", "AGENTENV_REAL_TIME=1", sys.executable, capture]


def test_the_changelog_directory_is_one_per_port():
Expand Down Expand Up @@ -219,6 +221,58 @@ def test_enable_writes_the_script_and_config_baselines_and_installs_the_hook(tmp
assert directory.stat().st_mode & 0o777 == 0o700


def test_the_changelogs_tar_runs_on_real_time(tmp_path, staging, monkeypatch):
"""tar keeps the time it starts at as the next capture's baseline and archives only the files changed since, by
their real mtimes: on an env clock ahead of real time it left every later edit out. No process hands its children
the marker, which libfaketime takes out of the environment it's given in, so the server and the hook give tar it."""
log = recording_tar.install(tmp_path / "bin")
path = f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}"
monkeypatch.setenv("PATH", path)
monkeypatch.delenv("AGENTENV_REAL_TIME", raising=False)
root = tmp_path / "workspace"
root.mkdir()
changelog, _, _, _ = _changelog(tmp_path, roots=[str(root)])

_enable(changelog)
(root / "edited.txt").write_text("after")
result = _capture(changelog, staging.port, path=path)

assert result.returncode == 0 and "captured seq=0" in result.stderr, result.stderr
runs = recording_tar.incremental_runs(log)
assert [("-cf" in run["args"], run["real_time"]) for run in runs] == [(True, "1"), (False, "1")]


@pytest.mark.parametrize("through_shell", [True, False], ids=["shell", "no-shell"])
def test_the_hook_starts_on_real_time_with_or_without_a_shell(tmp_path, staging, monkeypatch, through_shell):
"""The hook decides by its own clock whether the grant it uploads with has expired: on an env clock past the
grant's expiry it refused every upload. A sitecustomize records the environment the hook started in, through a
shell as the CLI runs it, and without one, where a bare assignment prefix wouldn't start the hook at all."""
seen = tmp_path / "hook-started-with.json"
probe = tmp_path / "probe"
probe.mkdir()
(probe / "sitecustomize.py").write_text(
"import json, os, sys\n"
"if sys.argv[0].endswith('capture.py'):\n"
f" open({str(seen)!r}, 'w').write(json.dumps(os.environ.get('AGENTENV_REAL_TIME')))\n")
recording_tar.install(tmp_path / "bin")
monkeypatch.delenv("AGENTENV_REAL_TIME", raising=False)
root = tmp_path / "workspace"
root.mkdir()
changelog, _, _, _ = _changelog(tmp_path, roots=[str(root)])
_enable(changelog)

command = ["/bin/sh", "-c", changelog.hook_command] if through_shell else shlex.split(changelog.hook_command)
result = subprocess.run(
command, input=json.dumps({"tool_name": "Bash", "session_id": "s"}),
capture_output=True, text=True, timeout=120,
env={**os.environ, "A2A_PORT": str(staging.port), "PYTHONPATH": str(probe),
"PATH": f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}"},
)

assert result.returncode == 0 and "captured seq=0" in result.stderr, result.stderr
assert json.loads(seen.read_text()) == "1"


def test_enable_refuses_an_empty_root_list(tmp_path):
log, installed, _, _ = _changelog(tmp_path)

Expand Down
29 changes: 29 additions & 0 deletions tst/unit/agents/opencode/test_object_transfer.py
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@

from tst.unit.agents.opencode.agent import a2a_server as server
from tst.unit.agents.opencode.agent import opencode_kit
from tst.util import recording_tar


def _grant(kind):
Expand Down Expand Up @@ -512,6 +513,34 @@ async def upload(self, _path, _source):
assert config["sequence"] == 1


@pytest.mark.asyncio
async def test_the_changelogs_tar_runs_on_real_time(monkeypatch, tmp_path, oc, folders):
"""tar keeps the time it starts at as the next capture's baseline and archives only the files changed since, by
their real mtimes: on an env clock ahead of real time it left every later edit out. The server runs on real time,
but libfaketime takes the marker out of its environment, so tar is given it again."""
log = recording_tar.install(tmp_path / "bin")
monkeypatch.setenv("PATH", f"{tmp_path / 'bin'}{os.pathsep}{os.environ['PATH']}")
monkeypatch.delenv("AGENTENV_REAL_TIME", raising=False)
uploads = _KeptUploads()
monkeypatch.setattr(server, "NamespaceUploader", lambda _grant: uploads)
namespace = {
"root_path": "captures", "expires_at": _grant("http-put")["expires_at"],
"max_objects": 10, "max_object_bytes": 1 << 20, "max_total_bytes": 1 << 22,
"write": {"kind": "http-post-policy", "url": "https://objects.example.test/upload",
"fields": {"key": "captures/"}, "path_field": "key", "file_field": "file"},
}
async with oc.client() as client:
enabled = await client.post("/ext/snapshot/changelog", json={"write_namespace": namespace,
"roots": [str(folders)]})
(folders / "edited.txt").write_text("after")
await oc.agent._capture_changelog()

assert enabled.status_code == 200, enabled.text
assert list(uploads.objects) == ["000000.tgz"]
runs = recording_tar.incremental_runs(log)
assert [("-cf" in run["args"], run["real_time"]) for run in runs] == [(True, "1"), (False, "1")]


@pytest.mark.asyncio
async def test_snapshot_waits_for_active_workspace_turn(monkeypatch, oc):
started = asyncio.Event()
Expand Down
35 changes: 35 additions & 0 deletions tst/util/recording_tar.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
"""A stand-in for ``tar`` that records each run's arguments and whether it was started on real time (agent-env's
libfaketime marker in its environment), and writes the archive and snapshot files it's named, empty."""

from __future__ import annotations

import json
import sys
from pathlib import Path

_SCRIPT = """#!{python}
import json, os, sys
args = sys.argv[1:]
with open({log!r}, "a") as log:
log.write(json.dumps({{"real_time": os.environ.get("AGENTENV_REAL_TIME"), "args": args}}) + "\\n")
for arg, value in zip(args, args[1:] + [None]):
named = arg.partition("=")[2] if arg.startswith("--listed-incremental=") else value if arg in ("-cf", "-czf") else None
if named and named not in ("-", "/dev/null"):
open(named, "a").close()
"""


def install(directory: Path) -> Path:
"""A ``tar`` in ``directory``, to put first on PATH; returns the log it adds a line to per run."""
directory.mkdir(parents=True, exist_ok=True)
log = directory / "tar-runs.jsonl"
tar = directory / "tar"
tar.write_text(_SCRIPT.format(python=sys.executable, log=str(log)))
tar.chmod(0o755)
return log


def incremental_runs(log: Path) -> list[dict]:
"""The recorded runs that read or wrote an incremental snapshot."""
runs = [json.loads(line) for line in log.read_text().splitlines()] if log.exists() else []
return [run for run in runs if any(arg.startswith("--listed-incremental=") for arg in run["args"])]
Loading