Skip to content

The agent that grows with you

Merge remote-tracking branch 'origin/main' into ethie/pm-clean

etherneta49d196b5cfc
diff --cc hermes_cli/config.py
index a8c996898b4,a007ad63ee9..01f4c77b4bb
--- a/hermes_cli/config.py
+++ b/hermes_cli/config.py
@@@ -1987,12 -1995,12 +2011,12 @@@ def _read_raw_config_impl(*, want_deepc
return {}
path_key = str(config_path)
- cached = _RAW_CONFIG_CACHE.get(path_key)
- if cached is not None and cached[:len(cache_key)] == cache_key:
- return copy.deepcopy(cached[len(cache_key)]) if want_deepcopy else cached[len(cache_key)]
+ hit = _raw_config_cache_hit(path_key, cache_key)
+ if hit is not None:
+ return copy.deepcopy(hit) if want_deepcopy else hit
try:
- with open(config_path, encoding="utf-8") as f:
+ with open(config_path, encoding="utf-8-sig") as f:
data = fast_safe_load(f) or {}
except Exception as e:
_warn_config_parse_failure(config_path, e)
diff --cc hermes_cli/env_loader.py
index 07bc792d0b5,0026f148193..c3626606f25
--- a/hermes_cli/env_loader.py
+++ b/hermes_cli/env_loader.py
@@@ -15,7 -15,7 +15,7 @@@ from pathlib import Pat
# wiped (#57828) so early recovery provably runs before third-party imports (test_early_recovery).
# The parser internals are imported lazily below because gateway tests stub ``sys.modules["dotenv"]``.
import dotenv # noqa: F401
- from utils import atomic_replace, fast_safe_load
-from utils import atomic_replace, fast_safe_load, load_yaml_file_readonly
++from utils import atomic_replace, load_yaml_file_readonly
logger = logging.getLogger(__name__)
@@@ -529,7 -529,7 +529,7 @@@ def _apply_external_secret_sources(home
# Neither early return marks the home applied: a malformed config.yaml would otherwise permanently
# disable secret loading for this process, and an unmarked home picks up a config change on the next
-- # load (the re-parse is a cheap fast_safe_load).
++ # load (the signature-cached read is cheap).
try:
cfg = _load_secrets_config(home_path)
except Exception: # noqa: BLE001 — config errors must not block startup
diff --cc tests/tools/test_skill_ledger.py
index fb1be810945,21aea4b8dbd..4ff89310ac9
--- a/tests/tools/test_skill_ledger.py
+++ b/tests/tools/test_skill_ledger.py
@@@ -600,3 -603,183 +603,180 @@@ def test_backup_fill_ignores_tar_path_t
)
# Malicious members are not.
assert not any(p.endswith("evil.md") or p.endswith("outside.md") for p in paths)
+
-
-from pathlib import Path
-
+ import pytest
+
+
+ def _append_padded(skill_ledger, action: str, pad: str, n: int = 1) -> None:
+ """Append *n* entries padded with evidence text so the ledger file grows fast."""
+ for _ in range(n):
+ skill_ledger.append_entry(action, "my-skill", before=[], after=[], evidence={"pad": pad})
+
+
+ def test_auto_compact_triggers_at_threshold(ledger_env, monkeypatch):
+ """Crossing skills.ledger_max_bytes rewrites the ledger through the delta
+ dedup: legacy rows that still carry identical before/after manifests (written
+ before append-time ``_delta`` existed) shrink to nothing while ids and entry
+ order survive, and nothing is trimmed when dedup alone reaches the cap."""
+ import json
+
+ from tools import skill_ledger
+
+ import hermes_cli.config as _cfg
+
+ cap = {"skills": {"ledger_max_bytes": 8192}}
+ monkeypatch.setattr(_cfg, "load_config", lambda *a, **k: cap)
+ monkeypatch.setattr(_cfg, "load_config_readonly", lambda *a, **k: cap)
+
+ first_id = skill_ledger.append_entry("patch", "my-skill", before=[], after=[])
+ template = json.loads(skill_ledger.ledger_path().read_text().splitlines()[0])
+ with skill_ledger.ledger_path().open("a", encoding="utf-8") as fh:
+ for i in range(3): # legacy pre-delta rows: identical fat manifests on both sides
+ fat = [{"path": f"my-skill/f{i}j{j}.md", "sha256": "a" * 64} for j in range(40)]
+ row = dict(template, id=f"legacy{i}", before=fat, after=list(fat))
+ fh.write(json.dumps(row) + "\n")
+ assert skill_ledger.ledger_path().stat().st_size > 8192
+
+ last_id = skill_ledger.append_entry("patch", "my-skill", before=[], after=[])
+
+ # the maintenance sweep fired on that append: the file is back under the cap
+ assert skill_ledger.ledger_path().stat().st_size <= 8192
+ rows = skill_ledger.list_entries()
+ assert {r["id"] for r in rows} == {first_id, last_id, "legacy0", "legacy1", "legacy2"}, (
+ "dedup alone must reach the cap — nothing trimmed, ids survive"
+ )
+ assert all(r["before"] == [] and r["after"] == [] for r in rows), (
+ "identical manifests must be dropped by compaction"
+ )
+
+
+ def test_trim_oldest_when_still_over_cap(ledger_env, monkeypatch):
+ """When compaction alone cannot reach the cap (every entry genuinely
+ differs), the oldest lines are dropped — whatever their shape — until the
+ file fits under the LOW-WATER mark (80% of the cap, so the next append does
+ not immediately re-trigger the sweep). The newest entry survives, and lines
+ in the retained tail are never parsed or rewritten: a malformed last line
+ survives verbatim."""
+ from tools import skill_ledger
+
+ import hermes_cli.config as _cfg
+
+ cap = {"skills": {"ledger_max_bytes": 0}} # no sweeps while seeding
+ monkeypatch.setattr(_cfg, "load_config", lambda *a, **k: cap)
+ monkeypatch.setattr(_cfg, "load_config_readonly", lambda *a, **k: cap)
+
+ newest_id = None
+ for i in range(5):
+ before = [{"path": f"my-skill/old{i}.md", "sha256": f"{i}" * 64}]
+ after = [{"path": f"my-skill/new{i}.md", "sha256": f"{i + 1}" * 64}]
+ newest_id = skill_ledger.append_entry(
+ "edit", "my-skill", before=before, after=after,
+ evidence={"pad": "y" * 2048})
+ with open(skill_ledger.ledger_path(), "a", encoding="utf-8") as fh:
+ fh.write("{not json at all\n")
+ assert skill_ledger.ledger_path().stat().st_size > 8192
+
+ cap["skills"]["ledger_max_bytes"] = 8192
+ skill_ledger._maintain_size()
+
+ rows = skill_ledger.list_entries()
+ assert len(rows) < 5, "oldest entries must be trimmed when compaction is not enough"
+ assert rows[0]["id"] == newest_id, "the newest entry always survives"
+ # malformed lines are never parsed away — they stay in the file verbatim
+ raw = skill_ledger.ledger_path().read_text(encoding="utf-8")
+ assert "{not json at all" in raw
+ # A sweep that fires does not stop at the cap but at the low-water mark ...
+ assert skill_ledger.ledger_path().stat().st_size <= int(8192 * 0.8)
+ # ... so the next append rides under the cap without paying compact+trim+gc again.
+ compactions = []
+ monkeypatch.setattr(skill_ledger, "compact_ledger",
+ lambda *a, **k: compactions.append(1) or (0, 0, 0))
+ skill_ledger.append_entry(
+ "edit", "my-skill", before=[{"path": "my-skill/z.md", "sha256": "a" * 64}],
+ after=[{"path": "my-skill/z2.md", "sha256": "b" * 64}], evidence={"pad": "z" * 1000})
+ assert compactions == [], "an append under the cap must not re-run the sweep"
+ assert skill_ledger.ledger_path().stat().st_size <= 8192
+ assert "{not json at all" in skill_ledger.ledger_path().read_text(encoding="utf-8")
+ # U+2028 inside a row (ensure_ascii=False leaves it unescaped) is not a row boundary for the
+ # trim: a cap that fits only the newest row keeps that row byte-for-byte, not its second half.
+ u_row = (json.dumps({"id": "u2028", "skill": "my-skill", "action": "edit",
+ "evidence": {"note": "line one\u2028line two"}}, ensure_ascii=False) + "\n").encode("utf-8")
+ with open(skill_ledger.ledger_path(), "ab") as fh:
+ fh.write(u_row)
+ assert skill_ledger._trim_oldest(len(u_row) + 8) >= 1
+ assert skill_ledger.ledger_path().read_bytes() == u_row, "a retained row containing U+2028 survives intact"
+
+
+ def test_concurrent_appends_never_lose_a_middle_row(ledger_env, monkeypatch):
+ """Two writers appending while the maintenance sweep fires on (almost) every append:
+ every row each writer appended is either still in the ledger or was trimmed
+ oldest-first — never silently lost from the middle of a writer's sequence. The sweep's
+ read → ``os.replace`` must run under the same ``.locks/ledger.lock`` as the O_APPEND
+ write, or an append landing on the replaced inode vanishes (and ``gc_blobs`` would then
+ delete its blobs). The race is forced, not hoped for: writer A's first sweep pauses
+ between reading the ledger and replacing it until writer B has appended (or, when the
+ lock correctly blocks B, until a generous bound expires — green never depends on timing)."""
+ import threading
+
+ from tools import skill_ledger
+
+ import hermes_cli.config as _cfg
+
+ cap = {"skills": {"ledger_max_bytes": 4096}} # padded rows ~600 B: a trim on nearly every append
+ monkeypatch.setattr(_cfg, "load_config", lambda *a, **k: cap)
+ monkeypatch.setattr(_cfg, "load_config_readonly", lambda *a, **k: cap)
+
+ n, ids = 40, {"A": [], "B": []}
+ b_go, b_done = threading.Event(), threading.Event()
+ real_rewrite = skill_ledger._rewrite_ledger
+
+ def paused_rewrite(path, lines, op):
+ if threading.current_thread().name == "A" and not b_go.is_set():
+ b_go.set() # A has read the ledger; let B append now ...
+ b_done.wait(1.0) # ... and give it every chance to land before the replace
+ return real_rewrite(path, lines, op)
+
+ monkeypatch.setattr(skill_ledger, "_rewrite_ledger", paused_rewrite)
+ dropped, real_trim = [], skill_ledger._trim_oldest
+ monkeypatch.setattr(skill_ledger, "_trim_oldest",
+ lambda max_bytes: dropped.append(real_trim(max_bytes)) or dropped[-1])
+
+ def writer(k: str) -> None:
+ if k == "B":
+ b_go.wait(10.0)
+ for i in range(n):
+ before = [{"path": f"my-skill/{k}-{i}.md", "sha256": "a" * 64}]
+ after = [{"path": f"my-skill/{k}-{i}.md", "sha256": f"{i % 10}" * 64}]
+ ids[k].append(skill_ledger.append_entry(
+ "edit", "my-skill", before=before, after=after, evidence={"pad": "x" * 500}))
+ if k == "B":
+ b_done.set()
+
+ seeds = 8 # seed over the cap so A's very first append sweeps
+ for _ in range(seeds):
+ skill_ledger.append_entry("edit", "my-skill", before=[{"path": "s", "sha256": "0" * 64}],
+ after=[{"path": "s", "sha256": "1" * 64}], evidence={"pad": "x" * 500})
+ # Unreferenced blobs: a fresh one is another process's in-flight capture (row not appended yet)
+ # and must survive every sweep's blob GC; one older than the grace window is garbage and goes.
+ fresh, aged = skill_ledger._store_blob(b"in-flight"), skill_ledger._store_blob(b"stale orphan")
+ os.utime(skill_ledger.blobs_dir() / aged, (time.time() - 7200, time.time() - 7200))
+ threads = [threading.Thread(target=writer, args=(k,), name=k) for k in ids]
+ for t in threads:
+ t.start()
+ for t in threads:
+ t.join()
+
+ assert b_go.is_set(), "writer A's first append must have swept (test precondition)"
+ assert all(ids["A"]) and all(ids["B"]) and len(ids["A"]) == len(ids["B"]) == n, "every append reported success"
+ present = [json.loads(line)["id"] for line in
+ skill_ledger.ledger_path().read_text(encoding="utf-8").splitlines() if line.strip()]
+ assert present, "the newest row always survives a trim"
+ assert (skill_ledger.blobs_dir() / fresh).exists() and not (skill_ledger.blobs_dir() / aged).exists()
+ assert len(present) == seeds + 2 * n - sum(dropped), (
+ "every row is either in the ledger or was counted as trimmed — none silently lost"
+ )
+ for k, seq in ids.items():
+ survivors = [i for i in seq if i in set(present)]
+ assert survivors == seq[len(seq) - len(survivors):], (
+ f"writer {k}: rows missing from the middle — a concurrent sweep dropped an append"
+ )
diff --cc tools/skills_hub.py
index ff3a7c9f251,2b5c66f0921..14573088e6c
--- a/tools/skills_hub.py
+++ b/tools/skills_hub.py
@@@ -76,6 -78,6 +78,17 @@@ def __getattr__(name: str)
raise AttributeError(f"module {__name__!r} has no attribute {name!r}")
++def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
++ target = _PLUGIN_COMPAT_LAZY.get(name)
++ if target is None:
++ return _plugin_compat_prev_getattr(name)
++ import importlib
++ from hermes_cli.plugin_compat import warn_once
++ warn_once(__name__, name, *target)
++ return getattr(importlib.import_module(target[0]), target[1])
++# ---- END PLUGIN-COMPAT ----
++
++
# ---------------------------------------------------------------------------
# Install-path safety + guarded HTTP
# ---------------------------------------------------------------------------
@@@ -445,14 -476,14 +487,3 @@@ _PLUGIN_COMPAT_LAZY =
}
_plugin_compat_prev_getattr = __getattr__
--
--
--def __getattr__(name): # PEP 562 — chained onto the module's own __getattr__
-- target = _PLUGIN_COMPAT_LAZY.get(name)
-- if target is None:
-- return _plugin_compat_prev_getattr(name)
-- import importlib
-- from hermes_cli.plugin_compat import warn_once
-- warn_once(__name__, name, *target)
-- return getattr(importlib.import_module(target[0]), target[1])
--# ---- END PLUGIN-COMPAT ----
diff --cc utils.py
index 4d9a1c47b38,cb4db2f4add..beeb8668200
--- a/utils.py
+++ b/utils.py
@@@ -568,11 -595,40 +569,34 @@@ def safe_json_loads(text: str, default
return default
-# libyaml's CSafeLoader is ~8x faster than the pure-Python SafeLoader and a true drop-in for
-# ``safe_load`` (same restricted tag set); startup parses config.yaml and every plugin manifest,
-# so the slow path cost ~0.9 s of cold start.
-_fast_yaml_loader = getattr(yaml, "CSafeLoader", None) or yaml.SafeLoader
-
-
def fast_safe_load(stream: Any) -> Any:
- """``yaml.safe_load`` (same inputs, same result) using the libyaml C loader when available."""
- return yaml.load(stream, Loader=_fast_yaml_loader)
+ """Use the shared safe reader (which selects ruamel's C parser when available)."""
+ return yaml.safe_load(stream)
+ _YAML_FILE_CACHE: dict = {}
+ _YAML_FILE_CACHE_LOCK = threading.Lock()
+
+
+ def load_yaml_file_readonly(path: Union[str, Path]) -> Any:
+ """``fast_safe_load`` of a file, re-parsed only when its :func:`file_signature` changes.
+
+ Returns the cached object itself — callers must never mutate it. Parse errors propagate and
+ are not cached; a missing file raises ``FileNotFoundError`` like ``open`` does."""
+ path = Path(path)
+ sig = file_signature(path.stat())
+ key = str(path)
+ with _YAML_FILE_CACHE_LOCK:
+ cached = _YAML_FILE_CACHE.get(key)
+ if cached is not None and cached[0] == sig:
+ return cached[1]
+ with open(path, encoding="utf-8") as f:
+ data = fast_safe_load(f)
+ with _YAML_FILE_CACHE_LOCK:
+ _YAML_FILE_CACHE[key] = (sig, data)
+ return data
+
+
def _env_number(key: str, default, cast):
raw = os.getenv(key, "").strip()
try: