Skip to content

The agent that grows with you

feat(pm): receipts as the universal machine-readable venv-op surface

ethernetbf242f3fe7d7
diff --git a/pm/cli.py b/pm/cli.py
index a5770468de7..363026978c5 100644
--- a/pm/cli.py
+++ b/pm/cli.py
@@ -521,6 +521,22 @@ def _pin_artifacts(package, decision) -> dict:
return urls_by_target
+def cmd_status(args) -> int:
+ """Print the latest pm sync receipt — the reader surface for the
+ CLI/TUI/desktop (same schema as update receipts; a failed venv
+ rebuild or a plugin bisect is as reportable as a failed update)."""
+ import json as _json
+
+ from pm import receipt
+
+ data = receipt.latest()
+ if data is None:
+ print("no pm sync receipt yet (no venv operation has run)")
+ return 0
+ print(_json.dumps(data, indent=2))
+ return 0
+
+
def cmd_bundle(args) -> int:
"""Stage a complete payload for THIS machine's target into --out:
repo snapshot + store + facts (via the normal install path, redirected)
@@ -729,6 +745,8 @@ def main(argv=None) -> int:
p.add_argument("--ref", help="git ref for the repo snapshot (default HEAD)")
p.set_defaults(func=cmd_bundle)
+ p = sub.add_parser("status", help="print the latest pm sync receipt (machine-readable)")
+ p.set_defaults(func=cmd_status)
p = sub.add_parser("update", help="resolve latest versions and re-pin the lockfile")
p.add_argument("names", nargs="*", help="packages to check/update (default: all with a latest source)")
p.add_argument("--check", action="store_true",
diff --git a/pm/packages.py b/pm/packages.py
index 2dfdd3e0514..f73c52cf5fb 100644
--- a/pm/packages.py
+++ b/pm/packages.py
@@ -433,6 +433,22 @@ class Venv(StatePackage):
decision["plugin"],
decision["reason"],
)
+ # Receipt: the machine-readable surface for this rebuild
+ # (same schema/dir as update receipts; the updater embeds
+ # these sections via pm.receipt.snapshot()).
+ try:
+ from pm import receipt
+
+ receipt.begin("sync")
+ receipt.record_feature_list(sorted(extras))
+ receipt.record_venv_rebuild(True)
+ if decisions:
+ receipt.record_bisect(decisions)
+ receipt.finalize("bisected")
+ else:
+ receipt.finalize("ok")
+ except Exception:
+ pass
return
uv_bin, env = pm_uv(venv=self.venv_dir())
diff --git a/pm/receipt.py b/pm/receipt.py
new file mode 100644
index 00000000000..302c2edc1ce
--- /dev/null
+++ b/pm/receipt.py
@@ -0,0 +1,150 @@
+"""pm sync receipts: the machine-readable surface for venv operations.
+
+Every pm venv sync — startup, plugin install, update rebuild — writes a
+receipt with the SAME schema the updater's receipts use
+(hermes_cli.update_receipt), into the same
+``<HERMES_HOME>/logs/update_receipts/`` dir with a ``kind`` field
+separating kinds. One reader (``hermes pm status``, desktop IPC) serves
+every surface: a failed venv rebuild is as reportable as a failed
+update.
+"""
+
+from __future__ import annotations
+
+import json
+import time
+from datetime import datetime, timezone
+from pathlib import Path
+from typing import Any, Optional
+
+_RECEIPT_KEEP = 20
+
+# Module current receipt — pm sync is a single-threaded CLI path.
+_current: Optional[dict[str, Any]] = None
+
+
+def _utc_now_iso() -> str:
+ return datetime.now(timezone.utc).isoformat()
+
+
+def _receipt_dir() -> Path:
+ from hermes_constants import get_hermes_home
+
+ d = get_hermes_home() / "logs" / "update_receipts"
+ d.mkdir(parents=True, exist_ok=True)
+ return d
+
+
+def begin(kind: str) -> None:
+ """Start recording a sync. ``kind``: 'sync' | 'update' (update embeds
+ the sync sections into its own receipt via `snapshot`)."""
+ global _current
+ _current = {
+ "schema": 1,
+ "kind": kind,
+ "started_at": _utc_now_iso(),
+ "steps": [],
+ "venv_rebuild": None,
+ "plugin_bisect": [],
+ "feature_list": None,
+ "platform": None,
+ "outcome": None,
+ }
+
+
+def record_step(name: str, ok: bool, detail: str = "") -> None:
+ if _current is None:
+ return
+ _current["steps"].append(
+ {"name": name, "ok": ok, "detail": detail, "at": _utc_now_iso()}
+ )
+
+
+def record_venv_rebuild(ok: bool, reason: str = "") -> None:
+ if _current is None:
+ return
+ _current["venv_rebuild"] = {"ok": ok, "reason": reason}
+
+
+def record_bisect(decisions: list[dict]) -> None:
+ if _current is None:
+ return
+ _current["plugin_bisect"] = decisions
+
+
+def record_feature_list(extras: Optional[list[str]]) -> None:
+ if _current is None:
+ return
+ _current["feature_list"] = extras
+
+
+def record_platform(platform_id: str) -> None:
+ if _current is None:
+ return
+ _current["platform"] = platform_id
+
+
+def snapshot() -> Optional[dict[str, Any]]:
+ """The in-flight receipt data — for the updater to EMBED its sync
+ sections into its own receipt (one schema, one directory)."""
+ return _current
+
+
+def finalize(outcome: str, exit_code: int = 0) -> Optional[Path]:
+ """Write the receipt (``outcome``: ok | refused | failed | bisected)
+ and rotate. Returns its path; None when nothing was begun."""
+ global _current
+ if _current is None:
+ return None
+ _current["outcome"] = outcome
+ _current["exit_code"] = exit_code
+ _current["finished_at"] = _utc_now_iso()
+ try:
+ path = _write_rotated(_current)
+ except OSError:
+ return None
+ finally:
+ _current = None
+ return path
+
+
+def latest() -> Optional[dict[str, Any]]:
+ """The newest receipt (any kind) — the reader surface for
+ ``hermes pm status`` + the desktop."""
+ try:
+ d = _receipt_dir()
+ point = d / "latest.json"
+ if point.is_file():
+ return json.loads(point.read_text(encoding="utf-8-sig"))
+ except (OSError, ValueError):
+ return None
+ return None
+
+
+def _write_rotated(data: dict[str, Any]) -> Path:
+ d = _receipt_dir()
+ stamp = time.strftime("%Y%m%dT%H%M%SZ", time.gmtime())
+ kind = data.get("kind") or "sync"
+ path = d / f"{stamp}-{kind}.json"
+ counter = 0
+ while path.exists():
+ counter += 1
+ path = d / f"{stamp}-{kind}-{counter}.json"
+ path.write_text(json.dumps(data, indent=2) + "\n", encoding="utf-8")
+ (d / "latest.json").write_text(
+ json.dumps(data, indent=2) + "\n", encoding="utf-8"
+ )
+ _rotate(d)
+ return path
+
+
+def _rotate(d: Path) -> None:
+ receipts = sorted(
+ (p for p in d.glob("*.json") if p.name != "latest.json"),
+ key=lambda p: p.name,
+ )
+ for stale in receipts[:-_RECEIPT_KEEP]:
+ try:
+ stale.unlink()
+ except OSError:
+ pass
diff --git a/tests/pm/test_receipt.py b/tests/pm/test_receipt.py
new file mode 100644
index 00000000000..d81c2ef3e48
--- /dev/null
+++ b/tests/pm/test_receipt.py
@@ -0,0 +1,72 @@
+"""pm.receipt: the universal machine-readable surface for venv ops.
+
+Every pm sync writes one; same schema/dir as update receipts; the
+updater embeds the sync sections via snapshot().
+"""
+
+from __future__ import annotations
+
+import json
+
+import pytest
+
+import pm.receipt as receipt
+
+
+def homed(tmp_path, monkeypatch):
+ """Receipt dir inside a temp hermes home."""
+ import hermes_constants
+
+ monkeypatch.setattr(hermes_constants, "get_hermes_home", lambda: tmp_path)
+ return tmp_path
+
+
+def test_begin_record_finalize_roundtrip(homed):
+ receipt.begin("sync")
+ receipt.record_step("uv-lock", True)
+ receipt.record_venv_rebuild(True)
+ receipt.record_bisect(
+ [{"plugin": "bad", "action": "disabled", "reason": "conflict"}]
+ )
+ receipt.record_feature_list(["web", "acp"])
+ path = receipt.finalize("bisected")
+ assert path is not None and path.is_file()
+
+ data = json.loads(path.read_text(encoding="utf-8"))
+ assert data["kind"] == "sync"
+ assert data["outcome"] == "bisected"
+ assert data["venv_rebuild"] == {"ok": True, "reason": ""}
+ assert data["plugin_bisect"][0]["plugin"] == "bad"
+ assert data["feature_list"] == ["web", "acp"]
+
+
+def test_latest_points_at_newest(homed):
+ receipt.begin("sync")
+ receipt.finalize("ok")
+ latest = receipt.latest()
+ assert latest is not None
+ assert latest["outcome"] == "ok"
+
+ receipt.begin("sync")
+ receipt.record_venv_rebuild(False, "uv sync exited 1")
+ receipt.finalize("failed", 1)
+ latest = receipt.latest()
+ assert latest["outcome"] == "failed"
+ assert latest["venv_rebuild"]["reason"] == "uv sync exited 1"
+
+
+def test_finalize_without_begin_is_none(homed):
+ assert receipt.finalize("ok") is None
+
+
+def test_snapshot_returns_inflight(homed):
+ receipt.begin("sync")
+ snap = receipt.snapshot()
+ assert snap is not None and snap["kind"] == "sync"
+ receipt.finalize("ok")
+ assert receipt.snapshot() is None
+
+
+def test_latest_none_when_empty(homed):
+ assert receipt.latest() is None