The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(pm): publish pin edits without reverting concurrent rows
ethernetecf5a6879eb0
diff --git a/.gitignore b/.gitignoreindex ea92770db47..b2bd61c0317 100644--- a/.gitignore+++ b/.gitignore@@ -121,6 +121,7 @@/.install_method/_pycache//bin/+/pm/.lock.json.lock/default.tar.gz/log.txt/sqlite_leak_fix.pngdiff --git a/pm/lock.py b/pm/lock.pyindex f1c47c8f257..94d532132d0 100644--- a/pm/lock.py+++ b/pm/lock.py@@ -21,7 +21,9 @@ any machine by substitution.from __future__ import annotationsimport json+import osimport re+from copy import deepcopyfrom pathlib import PathSCHEMA = 1@@ -65,12 +67,19 @@ def _write(path: Path, data: dict) -> None:from hermes_cli.runtime_state import _atomic_bytes_atomic_bytes(path, (json.dumps(data, indent=2, sort_keys=True) + "\n").encode("utf-8"))++class StaleLockRow(RuntimeError):+ """A concurrent editor changed a row that this writer plans to publish."""++class Lockfile:- """Read side of lock.json. Written only by `pm lock --bump` (cli)."""+ """Snapshot of lock.json with conflict-checked publication of changed pins."""def __init__(self, path: Path):- self.path = path- self._packages = _read(path)["packages"]+ self.path = Path(path).resolve()+ self._packages = _read(self.path)["packages"]+ self._base = deepcopy(self._packages)+ self._touched: set[str] = set()def version(self, name: str) -> str | None:return (self._packages.get(name) or {}).get("version")@@ -91,10 +100,31 @@ class Lockfile:return sorted(self._packages)def set_pin(self, name: str, version: str, artifacts: dict[str, dict]) -> None:- self._packages[name] = {"version": version, "artifacts": artifacts}+ self._packages[name] = {"version": version, "artifacts": deepcopy(artifacts)}+ self._touched.add(name)def save(self) -> None:- _write(self.path, {"schema": SCHEMA, "packages": self._packages})+ """Merge touched rows under the file's lock, or leave all rows unchanged."""+ from hermes_cli.runtime_state import _lock++ self.path.parent.mkdir(parents=True, exist_ok=True)+ fd = os.open(self.path.with_name(f".{self.path.name}.lock"), os.O_CREAT | os.O_RDWR, 0o600)+ try:+ _lock(fd, wait=True)+ current = _read(self.path, strict=True)["packages"]+ updated = dict(current)+ for name in self._touched:+ intended = self._packages[name]+ if current.get(name) != self._base.get(name) and current.get(name) != intended:+ raise StaleLockRow(f"{name} changed in {self.path}; read the lockfile again and retry")+ updated[name] = intended+ if updated != current or not self.path.exists():+ _write(self.path, {"schema": SCHEMA, "packages": updated})+ self._packages = updated+ self._base = deepcopy(updated)+ self._touched.clear()+ finally:+ os.close(fd)def termux_docker_digest() -> str:diff --git a/tests/pm/test_lockfile_publication.py b/tests/pm/test_lockfile_publication.pynew file mode 100644index 00000000000..a948e89acd8--- /dev/null+++ b/tests/pm/test_lockfile_publication.py@@ -0,0 +1,96 @@+"""Independent pin editors preserve winners and reject changed evidence."""+import json+import os+from pathlib import Path+import subprocess+import sys+import threading++import pytest++from pm.lock import Lockfile+++def test_pin_writers_merge_without_losing_other_rows(tmp_path):+ path = tmp_path / 'lock.json'+ seed = Lockfile(path)+ seed.set_pin('left', '1', {})+ seed.set_pin('right', '1', {})+ seed.save()+ code = '''+from pathlib import Path+import sys+from pm.lock import Lockfile+lock = Lockfile(Path(sys.argv[1]))+lock.set_pin(sys.argv[2], '2', {})+print('ready', flush=True)+assert sys.stdin.readline().strip() == 'save'+lock.save()+'''+ root = Path(__file__).resolve().parents[2]+ children = [subprocess.Popen([sys.executable, '-u', '-c', code, str(path), name], cwd=root,+ env=dict(os.environ), stdin=subprocess.PIPE,+ stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True)+ for name in ('left', 'right')]+ try:+ # Pipes form a barrier: both writers read their snapshot before either saves.+ for child in children:+ ready = threading.Event()+ line = []+ threading.Thread(target=lambda c=child, e=ready, out=line: (out.append(c.stdout.readline()), e.set()),+ daemon=True).start()+ assert ready.wait(10), 'writer did not reach the snapshot barrier'+ assert line == ['ready\n']+ for child in children:+ child.stdin.write('save\n')+ child.stdin.flush()+ for child in children:+ out, error = child.communicate(timeout=30)+ assert child.returncode == 0, out + error+ finally:+ for child in children:+ if child.poll() is None:+ child.kill()+ child.communicate(timeout=10)+ final = Lockfile(path)+ assert final.version('left') == final.version('right') == '2'+++def test_stale_or_invalid_evidence_never_gets_overwritten(tmp_path):+ path = tmp_path / 'lock.json'+ initial = {'schema': 1, 'packages': {'tool': {'version': '1', 'artifacts': {}},+ 'keep': {'version': '1', 'artifacts': {}}}}+ for change in ('changed', 'deleted', 'corrupt', 'removed-file'):+ path.write_text(json.dumps(initial), encoding='utf-8')+ stale = Lockfile(path)+ stale.set_pin('extra', '2', {})+ stale.set_pin('tool', '2', {})+ if change == 'corrupt':+ path.write_bytes(b'not JSON')+ elif change == 'removed-file':+ path.unlink()+ else:+ current = json.loads(path.read_text(encoding='utf-8'))+ if change == 'changed':+ current['packages']['tool']['version'] = '3'+ else:+ del current['packages']['tool']+ path.write_text(json.dumps(current), encoding='utf-8')+ before = path.read_bytes() if path.exists() else None+ with pytest.raises((RuntimeError, ValueError)):+ stale.save()+ assert (path.read_bytes() if path.exists() else None) == before+ assert not path.with_suffix('.corrupt').exists()+ path.write_text(json.dumps(initial), encoding='utf-8')+ first, retry = Lockfile(path), Lockfile(path)+ first.set_pin('tool', '2', {})+ first.save()+ before = path.read_bytes()+ os.utime(path, ns=(1234567890, 1234567890))+ modified = path.stat().st_mtime_ns+ retry.set_pin('tool', '2', {})+ retry.save()+ assert path.stat().st_mtime_ns == modified+ retry.save()+ assert path.read_bytes() == before+ assert path.stat().st_mtime_ns == modified