The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
test: regression conformance suites for the 7 recurring Aug-2026 bug classes
Tekniumd15f4a782663
diff --git a/tests/agent/test_injected_param_strip_retry_registry.py b/tests/agent/test_injected_param_strip_retry_registry.pynew file mode 100644index 00000000000..cd6169a79e9--- /dev/null+++ b/tests/agent/test_injected_param_strip_retry_registry.py@@ -0,0 +1,284 @@+"""Registry walk for the injected-parameter strip-and-retry safety class.++Bug class (#90257, #89897, #91164, #89503): a parameter that Hermes (or the+provider's own gateway) injects into a request — ``prompt_cache_retention``,+reasoning translations, ``temperature``/``max_tokens``/``response_format``+adjustments — draws an HTTP 400 from the provider and the turn DIES instead+of stripping the parameter (or retrying the identical request when the field+was never ours) and completing.++Two request paths are pinned, each driving the REAL recovery code with only+the HTTP boundary faked (a client that 400s once, then succeeds):++* Classifier path (main conversation loop): ``classify_api_error`` ++ ``_SERVER_INJECTED_PARAM_SENDERS`` (fixed in PR #91643). The registry is+ walked at collection time, so adding a new injected param automatically+ extends coverage. The retry contract mirrors conversation_loop: retryable+ → resend identical request; non-retryable → abort.+* Auxiliary path: ``agent.auxiliary_client.call_llm``'s reactive strip-and-+ retry rungs for every parameter that path knows how to strip.++Guard: a 400 naming a param NOT in the registry must still fail — we never+blindly strip arbitrary params, because that would convert our own request+bug into a friendly lie (error-classifier policy, AGENTS.md).+"""++import copy+from types import SimpleNamespace+from unittest.mock import patch++import pytest++from agent.error_classifier import (+ FailoverReason,+ _SERVER_INJECTED_PARAM_SENDERS,+ classify_api_error,+)+from agent.auxiliary_client import call_llm+++class MockAPIError(Exception):+ """Simulates an OpenAI SDK APIStatusError (status_code + body)."""++ def __init__(self, message, status_code=None, body=None):+ super().__init__(message)+ self.status_code = status_code+ self.body = body or {}+++# ---------------------------------------------------------------------------+# Path 1 — classifier path (main conversation loop contract)+# ---------------------------------------------------------------------------++REGISTRY_PARAMS = sorted(_SERVER_INJECTED_PARAM_SENDERS)+++def _error_shapes(param):+ """Real provider 400 shapes naming *param* (see #90257 live capture)."""+ openai_body = {+ "error": {+ "message": f"Unsupported parameter: '{param}'",+ "type": "invalid_request_error",+ "param": param,+ "code": "unsupported_parameter",+ }+ }+ return [+ pytest.param(+ f"Error code: 400 - {openai_body!r}", openai_body,+ id=f"{param}-openai-structured",+ ),+ pytest.param(+ f"{param} is not supported on this model", {},+ id=f"{param}-message-only",+ ),+ pytest.param(+ f"Unknown parameter: {param}",+ {"detail": f"Unknown parameter: {param}"},+ id=f"{param}-terse-detail",+ ),+ ]+++def _drive_conversation_retry(transport, *, provider, model, max_attempts=3):+ """Minimal loop honoring the conversation_loop classifier contract.++ retryable → resend the identical request; non-retryable → abort the turn.+ The classifier under test is the REAL one; only the transport is fake.+ """+ for _ in range(max_attempts):+ try:+ return transport()+ except Exception as exc: # noqa: BLE001 — contract mirror+ verdict = classify_api_error(+ exc, provider=provider, model=model,+ approx_tokens=50, num_messages=3,+ )+ if not verdict.retryable:+ raise+ raise AssertionError("retries exhausted")+++class _FlakyTransport:+ """400s exactly once, then succeeds — the HTTP boundary and nothing else."""++ def __init__(self, error):+ self.error = error+ self.calls = 0++ def __call__(self):+ self.calls += 1+ if self.calls == 1:+ raise self.error+ return {"ok": True}+++class TestClassifierPathRegistryWalk:+ """Every registered injected param × every real 400 shape must retry."""++ def test_registry_is_never_empty(self):+ assert REGISTRY_PARAMS, "injected-param registry must not be empty"++ @pytest.mark.parametrize("param", REGISTRY_PARAMS)+ def test_classified_retryable_without_compression(self, param):+ """#90257/#91164: injected-param 400 → retryable server_error,+ never routed into the compression loop (request shape was fine)."""+ for msg_param in _error_shapes(param):+ message, body = msg_param.values+ err = MockAPIError(message, status_code=400, body=copy.deepcopy(body))+ verdict = classify_api_error(+ err, provider="openai-codex", model="gpt-5.6-sol",+ approx_tokens=546912, context_length=272000, num_messages=576,+ )+ assert verdict.reason == FailoverReason.server_error, message+ assert verdict.retryable is True, message+ assert verdict.should_compress is False, message++ @pytest.mark.parametrize("param", REGISTRY_PARAMS)+ def test_turn_completes_via_retry(self, param):+ """The full contract: 400 once naming the injected param, retry the+ identical request, turn completes (#89503 — the turn used to die)."""+ for msg_param in _error_shapes(param):+ message, body = msg_param.values+ transport = _FlakyTransport(+ MockAPIError(message, status_code=400, body=copy.deepcopy(body))+ )+ result = _drive_conversation_retry(+ transport, provider="openai-codex", model="gpt-5.6-sol",+ )+ assert result == {"ok": True}, message+ assert transport.calls == 2, message++ @pytest.mark.parametrize("param", REGISTRY_PARAMS)+ def test_sender_route_still_fails_fast(self, param):+ """When the current provider IS a deliberate sender of the param, the+ 400 is a real request bug — it must stay a non-retryable format_error."""+ sender = _SERVER_INJECTED_PARAM_SENDERS[param][0]+ err = MockAPIError(+ f"Unsupported parameter: '{param}'", status_code=400,+ body={"error": {"message": f"Unsupported parameter: '{param}'",+ "code": "unsupported_parameter", "param": param}},+ )+ verdict = classify_api_error(err, provider=sender, model="any-model")+ assert verdict.reason == FailoverReason.format_error+ assert verdict.retryable is False++ def test_guard_unregistered_param_still_fails(self):+ """Policy guard: a 400 naming a param NOT in the registry must abort.+ Blindly stripping arbitrary params would mask real request bugs+ (never convert our own request bug into a friendly lie)."""+ err = MockAPIError(+ "Unsupported parameter: 'frobnication_level'", status_code=400,+ body={"error": {"message": "Unsupported parameter: 'frobnication_level'",+ "code": "unsupported_parameter",+ "param": "frobnication_level"}},+ )+ verdict = classify_api_error(+ err, provider="openai-codex", model="gpt-5.6-sol",+ )+ assert verdict.reason == FailoverReason.format_error+ assert verdict.retryable is False+ transport = _FlakyTransport(err)+ with pytest.raises(MockAPIError):+ _drive_conversation_retry(+ transport, provider="openai-codex", model="gpt-5.6-sol",+ )+ assert transport.calls == 1 # aborted on first attempt, no blind retry+++# ---------------------------------------------------------------------------+# Path 2 — auxiliary call path (call_llm reactive strip-and-retry rungs)+# ---------------------------------------------------------------------------++class _FlakyClient:+ """Fake OpenAI-SDK client: chat.completions.create 400s once, then OK."""++ def __init__(self, error):+ self.base_url = "https://api.openai.com/v1"+ self.calls = []+ self._error = error+ self.chat = SimpleNamespace(+ completions=SimpleNamespace(create=self._create)+ )++ def _create(self, **kwargs):+ self.calls.append(copy.deepcopy(kwargs))+ if len(self.calls) == 1:+ raise self._error+ return {"ok": True}+++def _aux_patches(client):+ return (+ patch("agent.auxiliary_client._resolve_task_provider_model",+ return_value=("openai-codex", "gpt-5.5", None, None, None)),+ patch("agent.auxiliary_client._get_cached_client",+ return_value=(client, "gpt-5.5")),+ patch("agent.auxiliary_client._validate_llm_response",+ side_effect=lambda resp, _task, **_kw: resp),+ )+++# Every parameter the auxiliary path knows how to strip, with a real provider+# phrasing and the kwargs that inject it. If a new strip rung is added to+# call_llm, extend this walk (the guard test below keeps the boundary honest).+AUX_STRIPPABLE = [+ pytest.param(+ {"temperature": 0.3},+ "HTTP 400: Unsupported parameter: temperature",+ lambda kw: "temperature" not in kw,+ id="temperature",+ ),+ pytest.param(+ {"max_tokens": 128},+ "Error code: 400 - {'error': {'message': \"Unsupported parameter: "+ "'max_tokens' is not supported with this model.\", "+ "'code': 'unsupported_parameter', 'param': 'max_tokens'}}",+ lambda kw: "max_tokens" not in kw and "max_completion_tokens" not in kw,+ id="max_tokens",+ ),+ pytest.param(+ {"extra_body": {"response_format": {"type": "json_object"}}},+ "HTTP 400: Unsupported parameter: response_format",+ lambda kw: "response_format"+ not in (kw.get("extra_body") or {}) and "response_format" not in kw,+ id="response_format",+ ),+]+++class TestAuxiliaryPathStripRetryWalk:+ """call_llm must strip the rejected injected param and retry to success."""++ @pytest.mark.parametrize("inject_kwargs,error_msg,stripped_ok", AUX_STRIPPABLE)+ def test_strips_param_and_completes(self, inject_kwargs, error_msg, stripped_ok):+ """#89897/#90257 class: provider 400 names a param we injected — the+ aux call must retry once WITHOUT the param and return the response."""+ client = _FlakyClient(RuntimeError(error_msg))+ p1, p2, p3 = _aux_patches(client)+ with p1, p2, p3:+ result = call_llm(+ task="session_search",+ messages=[{"role": "user", "content": "hi"}],+ **inject_kwargs,+ )+ assert result == {"ok": True}+ assert len(client.calls) == 2, "expected exactly one strip-and-retry"+ assert stripped_ok(client.calls[1]), (+ f"retry still carried the rejected param: {client.calls[1].keys()}"+ )++ def test_guard_unregistered_param_still_raises(self):+ """A 400 naming a param the aux path has no strip rung for must+ surface — no blind stripping, no silent success (#91164 policy)."""+ client = _FlakyClient(+ RuntimeError("HTTP 400: Unsupported parameter: frobnication_level")+ )+ p1, p2, p3 = _aux_patches(client)+ with p1, p2, p3:+ with pytest.raises(RuntimeError, match="frobnication_level"):+ call_llm(+ task="session_search",+ messages=[{"role": "user", "content": "hi"}],+ )+ assert len(client.calls) == 1, "must not retry an unknown-param 400"diff --git a/tests/agent/test_transcript_decoration_idempotence.py b/tests/agent/test_transcript_decoration_idempotence.pynew file mode 100644index 00000000000..78f2d27d10e--- /dev/null+++ b/tests/agent/test_transcript_decoration_idempotence.py@@ -0,0 +1,200 @@+"""Idempotence law for transcript decoration passes: f(f(x)) == f(x).++Pins bug #90971 (fixed in PR #91350): ``apply_anthropic_cache_control`` was+non-idempotent on pre-decorated input — the negative-slice / tool-budget+interplay stacked a fifth ``cache_control`` marker onto messages a prior+pass had already decorated, reproducing Anthropic's ``cache_control can only+be specified up to 4 times`` HTTP 400 mid-conversation.++Behavior contracts pinned here (complementing, not duplicating,+tests/agent/test_prompt_caching.py::TestApplyIdempotency which covers exact+layout convergence and caller non-mutation):++1. IDEMPOTENCE — for every realistic transcript shape x, the serialized form+ of f(f(x)) is byte-identical to f(x).+2. BUDGET — the total decoration count after any number of passes never+ exceeds Anthropic's 4-breakpoint budget.++Shapes include the #90971 regression input (already-decorated transcripts)+plus dict-content and list-content messages, tool blocks, and mixed forms.+"""++import copy+import json++import pytest++from agent.prompt_caching import (+ _count_cache_markers,+ apply_anthropic_cache_control,+)++MARKER = {"type": "ephemeral"}+BUDGET = 4 # Anthropic's hard cap on cache_control breakpoints+++def _canon(messages):+ """Deterministic byte serialization for the byte-identity assertion."""+ return json.dumps(messages, sort_keys=True, ensure_ascii=False).encode()+++def _tool_block(i, decorated=False):+ # Two text parts: single-part [{"type","text"}] lists are canonicalized+ # to plain strings by the strip pass (by-design flattening of the shape+ # decoration itself produces), so multi-part is the realistic list form+ # that must round-trip byte-exactly.+ part = {"type": "text", "text": f"tool result {i}"}+ if decorated:+ part["cache_control"] = dict(MARKER)+ return {+ "role": "tool",+ "tool_call_id": f"call_{i}",+ "content": [{"type": "text", "text": f"tool header {i}"}, part],+ }+++def _clean_transcript():+ """system + alternating user/assistant, plain string (dict) content."""+ msgs = [{"role": "system", "content": "STATIC_PREFIX system rules and tools"}]+ for i in range(6):+ msgs.append({"role": "user", "content": f"user turn {i}"})+ msgs.append({"role": "assistant", "content": f"assistant turn {i}"})+ return msgs+++def _list_content_transcript():+ """List-content parts on user turns + tool blocks interleaved."""+ msgs = [{"role": "system", "content": "STATIC_PREFIX system rules"}]+ for i in range(4):+ msgs.append({+ "role": "user",+ "content": [+ {"type": "text", "text": f"question {i}"},+ {"type": "text", "text": "attachment context"},+ ],+ })+ msgs.append({+ "role": "assistant",+ "content": f"calling tool {i}",+ "tool_calls": [{"id": f"call_{i}", "type": "function",+ "function": {"name": "t", "arguments": "{}"}}],+ })+ msgs.append(_tool_block(i))+ msgs.append({"role": "assistant", "content": f"answer {i}"})+ return msgs+++def _predecorated_transcript():+ """The #90971 regression shape: input a PRIOR pass already decorated.++ Markers live both top-level and on content parts (both shapes the+ decorator itself produces), including on a tool block near the tail+ where the negative-slice budget math went wrong.+ """+ msgs = [{"role": "system", "content": [+ {"type": "text", "text": "STATIC_PREFIX early", "cache_control": dict(MARKER)},+ {"type": "text", "text": "late suffix", "cache_control": dict(MARKER)},+ ]}]+ for i in range(5):+ msgs.append({"role": "user", "content": f"u{i}"})+ msgs.append({"role": "assistant", "content": f"a{i}"})+ # tail: pre-decorated user (top-level marker) + decorated tool block+ msgs.append({"role": "user", "content": "recent question",+ "cache_control": dict(MARKER)})+ msgs.append({"role": "assistant", "content": "using tool",+ "tool_calls": [{"id": "call_z", "type": "function",+ "function": {"name": "t", "arguments": "{}"}}]})+ msgs.append(_tool_block(99, decorated=True))+ msgs.append({"role": "assistant", "content": "final answer"})+ return msgs+++def _mixed_partially_decorated():+ """Stale markers scattered mid-transcript (replayed history)."""+ msgs = _clean_transcript()+ msgs[3] = dict(msgs[3], cache_control=dict(MARKER))+ msgs[7] = {"role": "user", "content": [+ {"type": "text", "text": "mid turn", "cache_control": dict(MARKER)},+ ]}+ return msgs+++SHAPES = [+ pytest.param(_clean_transcript, id="clean-dict-content"),+ pytest.param(_list_content_transcript, id="list-content-with-tools"),+ pytest.param(_predecorated_transcript, id="predecorated-90971-regression"),+ pytest.param(_mixed_partially_decorated, id="mixed-stale-markers"),+]++VARIANTS = [+ pytest.param({}, id="default"),+ pytest.param({"static_system_prefix": "STATIC_PREFIX"}, id="split-system"),+ pytest.param({"native_anthropic": True}, id="native-anthropic"),+ pytest.param({"cache_ttl": "1h",+ "static_system_prefix": "STATIC_PREFIX"}, id="1h-ttl"),+]+++class TestDecorationIdempotenceLaw:+ """f(f(x)) == f(x), byte-identical, for all transcript shapes (#90971)."""++ @pytest.mark.parametrize("kwargs", VARIANTS)+ @pytest.mark.parametrize("make", SHAPES)+ def test_double_apply_is_byte_identical(self, make, kwargs):+ once = apply_anthropic_cache_control(make(), **kwargs)+ twice = apply_anthropic_cache_control(+ copy.deepcopy(once), **kwargs)+ assert _canon(twice) == _canon(once), (+ "decoration pass is not idempotent: f(f(x)) != f(x)"+ )++ @pytest.mark.parametrize("kwargs", VARIANTS)+ @pytest.mark.parametrize("make", SHAPES)+ def test_budget_never_exceeded_across_passes(self, make, kwargs):+ """No pass — first, second, or fifth — may exceed Anthropic's+ 4-breakpoint budget, even when the input was already decorated."""+ msgs = make()+ for round_no in range(1, 6):+ msgs = apply_anthropic_cache_control(msgs, **kwargs)+ count = _count_cache_markers(msgs, [])+ assert count <= BUDGET, (+ f"round {round_no}: {count} cache_control markers exceed the "+ f"{BUDGET}-breakpoint budget (the #90971 HTTP-400 class)"+ )++ @pytest.mark.parametrize("make", SHAPES)+ def test_fixed_point_reached_after_one_pass(self, make):+ """Convergence in one step: repeated application never drifts —+ rounds 1..4 all serialize identically (stronger than pairwise)."""+ forms = []+ msgs = make()+ for _ in range(4):+ msgs = apply_anthropic_cache_control(+ msgs, static_system_prefix="STATIC_PREFIX")+ forms.append(_canon(msgs))+ msgs = copy.deepcopy(json.loads(forms[-1]))+ assert len(set(forms)) == 1, "decoration drifted across rounds"++ def test_predecorated_input_does_not_inherit_extra_markers(self):+ """#90971 core symptom: pre-decorated input must not carry stale+ markers PLUS fresh ones. Every marker in the output is one the+ current pass placed — total exactly within budget, and no message+ carries more than one marker at both levels."""+ out = apply_anthropic_cache_control(+ _predecorated_transcript(), static_system_prefix="STATIC_PREFIX")+ assert _count_cache_markers(out, []) <= BUDGET+ for msg in out:+ top = 1 if "cache_control" in msg else 0+ content = msg.get("content")+ parts = (+ sum(1 for p in content+ if isinstance(p, dict) and "cache_control" in p)+ if isinstance(content, list) else 0+ )+ # A single message may legitimately hold two SYSTEM breakpoints+ # (prefix + suffix in the split-system layout); non-system+ # messages must never stack top-level + part markers.+ if msg.get("role") != "system":+ assert top + parts <= 1, (+ f"stacked markers on one message: {msg!r}"+ )diff --git a/tests/conformance/test_profile_write_tripwire.py b/tests/conformance/test_profile_write_tripwire.pynew file mode 100644index 00000000000..c9716b5f0e9--- /dev/null+++ b/tests/conformance/test_profile_write_tripwire.py@@ -0,0 +1,308 @@+"""Profile-isolation write tripwire: no cross-profile writes to the default home.++Invariant under test+--------------------+When a non-default profile is active (``HERMES_HOME`` points at+``<root>/profiles/testprof``), NO subsystem write may land anywhere under the+default profile's tree — ``<root>/state.db``, ``<root>/config.yaml``,+``<root>/memories/``, ``<root>/cron/``, or any other path directly under+``<root>`` outside the ``profiles/`` subtree.++This is a recurring bug *class*, not a single bug. Recent regressions:++* #88532 — gateway sessions physically stored in the root ``state.db`` even+ though the profile scope was active (rows carried the right profile_name,+ so the only symptom was the desktop listing them under the default bot).+* #92662 / #89190 — settings and API keys saved while a profile was active+ were written to the base profile's ``config.yaml`` / ``.env``.+* #89625 — cron listing/writing the default profile's jobs.json because the+ store paths were frozen at import time.+* #92156 — terminal env cache leaked across profiles (same import-time-+ snapshot shape of bug).++Each test here exercises a REAL persistence surface through its real code+path (no mocks of the subject) with the ``testprof`` profile active, then+walks the entire default-profile tree and fails if anything was created,+modified, or deleted there. The walk is deliberately whole-tree rather than+per-known-file so the *next* variant of this bug class (a new subsystem, a+new sidecar file) trips it too.++Reusability+-----------+``ProfileTripwire`` and the ``profile_tripwire`` fixture are module-level and+documented so future surfaces (terminal env cache, skills, plugins, logs …)+can add one small exercise function + a ``pytest.param`` to ``SURFACES``.+"""++import os+import sqlite3+from pathlib import Path++import pytest++import hermes_state+from hermes_constants import (+ reset_hermes_home_override,+ set_hermes_home_override,+)+++class ProfileTripwire:+ """Snapshot of the default profile's tree + the active testprof home.++ Construction snapshots every path under ``root`` EXCEPT the+ ``root/profiles`` subtree (that subtree is exactly where writes are+ supposed to go). ``assert_default_untouched()`` re-walks and fails on+ any created / modified / deleted entry.++ Attributes:+ root: the default profile's home (``<tmp>/hermes``).+ profile: the active profile home (``<root>/profiles/testprof``).+ """++ def __init__(self, root: Path, profile: Path):+ self.root = root+ self.profile = profile+ self._baseline = self._snapshot()++ def _snapshot(self) -> dict:+ """Map of relpath -> (kind, mtime_ns, size) for the default tree."""+ snap = {}+ profiles_subtree = self.root / "profiles"+ for dirpath, dirnames, filenames in os.walk(self.root):+ d = Path(dirpath)+ if d == self.root and "profiles" in dirnames:+ dirnames.remove("profiles") # never descend into profiles/+ for name in dirnames:+ p = d / name+ if p == profiles_subtree:+ continue+ snap[str(p.relative_to(self.root))] = ("dir", None, None)+ for name in filenames:+ p = d / name+ st = p.stat()+ snap[str(p.relative_to(self.root))] = (+ "file", st.st_mtime_ns, st.st_size,+ )+ return snap++ def assert_default_untouched(self) -> None:+ """Fail if the default profile's tree changed in any way."""+ now = self._snapshot()+ created = sorted(set(now) - set(self._baseline))+ deleted = sorted(set(self._baseline) - set(now))+ modified = sorted(+ rel for rel in set(now) & set(self._baseline)+ if now[rel] != self._baseline[rel]+ )+ problems = []+ if created:+ problems.append(f"created in default profile: {created}")+ if modified:+ problems.append(f"modified in default profile: {modified}")+ if deleted:+ problems.append(f"deleted from default profile: {deleted}")+ assert not problems, (+ "Cross-profile write leak (bug class #88532/#92662/#89190/"+ "#89625/#92156): the testprof profile was active but the default "+ f"profile tree at {self.root} changed: " + "; ".join(problems)+ )+++def profile_tripwire(tmp_path, monkeypatch):+ """Activate ``<root>/profiles/testprof`` and arm the default-tree tripwire.++ Sets up:++ 1. A temp hermes root acting as the *default* profile, seeded with the+ files a real install has (config.yaml, memories/, cron/jobs.json) so+ both "new file created" and "existing file modified" leaks are+ detectable.+ 2. ``HERMES_HOME`` (env var AND the context-local override) pointed at+ the testprof home — the exact activation shape ``--profile`` uses.+ 3. ``hermes_state.DEFAULT_DB_PATH`` restored to its import-time snapshot.+ The suite conftest deliberately re-points that constant at its own+ fake home, which trips the escape hatch in ``_default_db_path()``+ (a re-pointed constant wins over everything). Closing the hatch+ makes resolution flow through ``get_hermes_home()`` — the production+ path, and the one #88532 regressed.++ Yields a :class:`ProfileTripwire`; teardown re-asserts the invariant so+ a surface test that forgets the explicit check still trips the wire.+ """+ root = tmp_path / "hermes"+ profile = root / "profiles" / "testprof"+ profile.mkdir(parents=True)++ # Seed the default profile the way a real install looks.+ (root / "config.yaml").write_text("model:\n default: default-model\n")+ (root / "memories").mkdir()+ (root / "memories" / "MEMORY.md").write_text("default profile memory\n")+ (root / "cron").mkdir()+ (root / "cron" / "jobs.json").write_text("[]\n")+ (root / ".env").write_text("")++ monkeypatch.setenv("HERMES_HOME", str(profile))+ token = set_hermes_home_override(str(profile))++ # Close the conftest's DEFAULT_DB_PATH escape hatch (see docstring).+ monkeypatch.setattr(+ hermes_state, "DEFAULT_DB_PATH", hermes_state._IMPORT_DEFAULT_DB_PATH+ )++ tripwire = ProfileTripwire(root, profile)+ try:+ yield tripwire+ # Safety net: re-check even if the test body forgot to.+ tripwire.assert_default_untouched()+ finally:+ reset_hermes_home_override(token)+++# ---------------------------------------------------------------------------+# Surface exercisers — each drives ONE real persistence surface end to end.+# Add new surfaces here as the bug class produces new variants.+# ---------------------------------------------------------------------------++def _exercise_session_db(tripwire: ProfileTripwire) -> None:+ """SessionDB() argless construction + session + message (#88532)."""+ db = hermes_state.SessionDB()+ try:+ db.create_session("20260823_000000_tripwire", "cli")+ db.append_message("20260823_000000_tripwire", "user", "hello")+ finally:+ db.close()+ profile_state_db = tripwire.profile / "state.db"+ assert profile_state_db.exists(), (+ f"SessionDB() did not write to the active profile home "+ f"({profile_state_db} missing)"+ )+++def _exercise_config_save(tripwire: ProfileTripwire) -> None:+ """save_config()/load_config() while a profile is active (#92662, #89190)."""+ from hermes_cli.config import load_config, save_config++ cfg = load_config()+ cfg["model"] = "testprof-model" # bare-string alias form is canonical+ save_config(cfg)+ assert (tripwire.profile / "config.yaml").exists(), (+ "save_config() did not write the active profile's config.yaml"+ )+++def _exercise_memory_store(tripwire: ProfileTripwire) -> None:+ """MemoryStore.add() persistence path (same class as #92662)."""+ from tools.memory_tool import MemoryStore++ store = MemoryStore()+ store.load_from_disk()+ result = store.add("memory", "testprof remembers something")+ assert result.get("success"), f"memory add failed: {result}"+ mem_file = tripwire.profile / "memories" / "MEMORY.md"+ assert mem_file.exists(), (+ "MemoryStore did not persist to the active profile's memories/"+ )+ assert "testprof remembers something" in mem_file.read_text()+++def _exercise_cron_store(tripwire: ProfileTripwire) -> None:+ """cron save_jobs()/load_jobs() store resolution (#89625)."""+ from cron.jobs import load_jobs, save_jobs++ job = {+ "id": "tripwire-job",+ "name": "tripwire",+ "prompt": "noop",+ "schedule": {"kind": "interval", "minutes": 60, "display": "every 60m"},+ "enabled": True,+ }+ save_jobs([job])+ jobs_file = tripwire.profile / "cron" / "jobs.json"+ assert jobs_file.exists(), (+ "save_jobs() did not write the active profile's cron/jobs.json"+ )+ loaded = load_jobs()+ assert any(j.get("id") == "tripwire-job" for j in loaded), (+ "load_jobs() did not read back from the active profile's store "+ "(#89625 shape: reading the default profile's jobs instead)"+ )+ # And the default profile's jobs.json content is untouched (the tree+ # walk would also catch this; the explicit read documents the contract).+ assert (tripwire.root / "cron" / "jobs.json").read_text() == "[]\n"+++# NOTE: the terminal env cache surface (#92156) is not exercised here: the+# terminal backend cache requires spawning a real terminal session, which is+# not hermetic in this suite. Its bug shape (import-time path snapshot) is+# the same one the four surfaces above pin.++SURFACES = [+ pytest.param(_exercise_session_db, id="session_db"),+ pytest.param(_exercise_config_save, id="config_save"),+ pytest.param(_exercise_memory_store, id="memory_store"),+ pytest.param(_exercise_cron_store, id="cron_store"),+]++[email protected]("exercise", SURFACES)+def test_no_default_profile_writes(profile_tripwire, exercise):+ """Exercising a persistence surface under testprof must not touch <root>.++ Regression tripwire for the cross-profile write bug class:+ #88532 (sessions in root state.db), #92662/#89190 (settings/API keys in+ the base profile), #89625 (cron using the default profile's store),+ #92156 (terminal env cache leaking cross-profile).+ """+ exercise(profile_tripwire)+ profile_tripwire.assert_default_untouched()+++def test_session_db_file_lands_in_profile_home(profile_tripwire):+ """The state.db written by an argless SessionDB() is PHYSICALLY the+ testprof file — rows are readable from ``profiles/testprof/state.db``+ and no root ``state.db`` exists at all (#88532's exact symptom).+ """+ db = hermes_state.SessionDB()+ try:+ db.create_session("20260823_111111_tripwire", "cli")+ db.append_message("20260823_111111_tripwire", "user", "profile hello")+ finally:+ db.close()++ profile_db = profile_tripwire.profile / "state.db"+ assert profile_db.exists()+ conn = sqlite3.connect(str(profile_db))+ try:+ ids = {r[0] for r in conn.execute("SELECT id FROM sessions")}+ finally:+ conn.close()+ assert "20260823_111111_tripwire" in ids++ assert not (profile_tripwire.root / "state.db").exists(), (+ "#88532 regression: a state.db appeared in the DEFAULT profile home "+ "while testprof was active"+ )+ profile_tripwire.assert_default_untouched()+++def test_config_round_trips_through_profile_home(profile_tripwire):+ """load_config() under testprof reads testprof's config, not the root's.++ #92662/#89190 shape: the base profile's config.yaml carried the default+ model 'default-model'; a load under testprof must not see or mutate it.+ """+ from hermes_cli.config import load_config, save_config++ cfg = load_config()+ cfg["model"] = "round-trip-model" # bare-string alias form is canonical+ save_config(cfg)++ reread = load_config()+ model = reread.get("model")+ resolved = model if isinstance(model, str) else (model or {}).get("default")+ assert resolved == "round-trip-model"+ # The default profile's config still holds its own value.+ assert "default-model" in (profile_tripwire.root / "config.yaml").read_text()+ profile_tripwire.assert_default_untouched()diff --git a/tests/cron/test_cron_memory_contract.py b/tests/cron/test_cron_memory_contract.pynew file mode 100644index 00000000000..ddd2d4a5fa3--- /dev/null+++ b/tests/cron/test_cron_memory_contract.py@@ -0,0 +1,208 @@+"""Contract pin: cron <-> persistent-memory loading.++This contract FLIPPED TWICE in August 2026 and must never flip silently again:++ * #91269 reported "cron loads MEMORY.md even though skip_memory is on".+ * PR #91384 flipped cron to ``skip_memory=True`` and denylisted the+ ``memory`` toolset ("do not load MEMORY.md into scheduled jobs").+ * PR #91447 flipped it BACK: "cron jobs now load and update persistent+ memory like every other agent" — ``skip_memory=False`` at the scheduler's+ AIAgent construction site, ``memory`` removed from the cron denylist,+ and ``agent/agent_init.py`` clarified that ``skip_memory`` skips the+ *external memory provider* path (built-in MEMORY.md/USER.md store follows+ the normal ``not skip_memory or memory-toolset-requested`` rule).++CURRENT INTENDED MATRIX (as of PR #91447, pinned here):++ default cron job -> skip_memory=False; MEMORY.md/USER.md load into+ the system prompt; ``memory`` toolset follows+ normal resolution (NOT policy-denied).+ per-job enabled_toolsets -> naming ``memory`` keeps it; skip_memory stays+ False.+ config.yaml+ agent.disabled_toolsets:+ [memory] -> the ONLY off-switch: ``memory`` lands in the+ cron agent's disabled_toolsets (tool denied,+ and agent_init treats a denylisted toolset as+ not-requested). skip_memory itself is NOT a+ per-job/config toggle — the scheduler always+ passes False.++ANY future flip of this behavior MUST consciously edit this test and cite+the issue/PR that decided the flip in the module docstring above, extending+the flip history. Do not "fix" a failure here by inverting an assertion+without that citation.++Tests drive the REAL ``cron.scheduler.run_job`` path and capture the actual+kwargs the scheduler passes to AIAgent (patched at ``run_agent.AIAgent``,+matching tests/cron/test_scheduler.py's pattern).+"""++from __future__ import annotations++import contextlib+from unittest.mock import MagicMock, patch++from cron.scheduler import run_job+++def _run_job_patches(tmp_path):+ """Patch bundle so run_job runs offline; yields (fake_db, mock_agent_cls).++ Mirrors tests/cron/test_scheduler.py::_run_job_patches — every patch is+ entered via one ExitStack so none can be silently dropped.+ ``cron.scheduler._hermes_home`` is pointed at ``tmp_path`` so run_job's+ config load reads ``tmp_path/config.yaml`` (write one to exercise config+ toggles).+ """+ fake_db = MagicMock()+ fake_db.get_compression_tip.side_effect = lambda session_id: session_id+ mock_agent = MagicMock()+ mock_agent.run_conversation.return_value = {"final_response": "ok"}+ base = [+ patch("cron.scheduler._hermes_home", tmp_path),+ patch("cron.scheduler._resolve_origin", return_value=None),+ patch("hermes_cli.env_loader.load_hermes_dotenv"),+ patch("hermes_cli.env_loader.reset_secret_source_cache"),+ patch("hermes_state.SessionDB", return_value=fake_db),+ patch(+ "hermes_cli.runtime_provider.resolve_runtime_provider",+ return_value={+ "api_key": "test-key",+ "base_url": "https://example.invalid/v1",+ "provider": "openrouter",+ "api_mode": "chat_completions",+ },+ ),+ patch("run_agent.AIAgent", return_value=mock_agent),+ ]+ with contextlib.ExitStack() as stack:+ entered = [stack.enter_context(cm) for cm in base]+ yield fake_db, entered[-1]+++class TestCronMemoryContractOn:+ """Direction (a): default cron agents GET persistent memory (#91447)."""++ def test_default_cron_agent_passes_skip_memory_false(self, tmp_path):+ """The scheduler's AIAgent construction site passes skip_memory=False.++ This is the exact flag PR #91384 set to True and PR #91447 set back+ to False. skip_memory=False means the built-in MEMORY.md/USER.md+ store loads into the system prompt via agent_init's normal path.+ """+ job = {"id": "mem-contract-default", "name": "t", "prompt": "hi"}+ with _run_job_patches(tmp_path) as (_db, agent_cls):+ success, _out, _final, error = run_job(job)+ assert success is True and error is None+ kwargs = agent_cls.call_args.kwargs+ assert kwargs["skip_memory"] is False, (+ "Cron memory contract (#91447): cron agents load MEMORY.md/USER.md "+ "like any other agent. If you are flipping this on purpose, edit "+ "this module's docstring and cite the deciding issue/PR."+ )++ def test_memory_toolset_not_policy_denied_by_default(self, tmp_path):+ """PR #91447 removed 'memory' from the cron toolset denylist.++ PR #91384 had added it alongside messaging/clarify. It must not creep+ back in silently.+ """+ job = {"id": "mem-contract-denylist", "name": "t", "prompt": "hi"}+ with _run_job_patches(tmp_path) as (_db, agent_cls):+ run_job(job)+ kwargs = agent_cls.call_args.kwargs+ assert "memory" not in (kwargs["disabled_toolsets"] or []), (+ "'memory' must not be in cron's default denylist (#91447)"+ )++ def test_resolver_denylist_has_no_memory_entry(self):+ """_resolve_cron_disabled_toolsets({}) itself never emits 'memory'."""+ from cron.scheduler import _resolve_cron_disabled_toolsets++ assert "memory" not in _resolve_cron_disabled_toolsets({})+ assert "memory" not in _resolve_cron_disabled_toolsets(+ {"cron": {"allow_agent_scheduling": True}}+ )++ def test_per_job_memory_toolset_survives(self, tmp_path):+ """A per-job enabled_toolsets naming memory keeps it (no stripping).++ PR #91384 introduced _strip_cron_memory_toolset; PR #91447 deleted it.+ """+ job = {+ "id": "mem-contract-perjob",+ "name": "t",+ "prompt": "hi",+ "enabled_toolsets": ["memory", "file"],+ }+ with _run_job_patches(tmp_path) as (_db, agent_cls):+ run_job(job)+ kwargs = agent_cls.call_args.kwargs+ assert "memory" in (kwargs["enabled_toolsets"] or [])+ assert kwargs["skip_memory"] is False+++class TestCronMemoryContractOff:+ """Direction (b): the supported OFF switch stays off."""++ def test_config_disabled_toolsets_denies_memory(self, tmp_path):+ """agent.disabled_toolsets: [memory] in config.yaml denies the toolset.++ This is the intended user-level off-switch after #91447: the user+ denylist layers onto cron's base denylist (#25752), so the memory+ tool is denied AND agent_init treats a denylisted toolset as+ not-requested. A per-job enabled_toolsets cannot widen past it.+ """+ (tmp_path / "config.yaml").write_text(+ "agent:\n disabled_toolsets:\n - memory\n"+ )+ job = {+ "id": "mem-contract-off",+ "name": "t",+ "prompt": "hi",+ "enabled_toolsets": ["memory", "file"],+ }+ with _run_job_patches(tmp_path) as (_db, agent_cls):+ run_job(job)+ kwargs = agent_cls.call_args.kwargs+ assert "memory" in (kwargs["disabled_toolsets"] or []), (+ "config.yaml agent.disabled_toolsets must propagate 'memory' into "+ "the cron agent's denylist — the OFF direction of the contract"+ )++ def test_skip_memory_is_not_a_per_job_knob(self, tmp_path):+ """No per-job field flips skip_memory: the scheduler always passes False.++ Guards against a partial re-flip where some job shape quietly gets+ #91384 behavior back. A field named skip_memory on the job dict is+ ignored by the construction site.+ """+ job = {+ "id": "mem-contract-noknob",+ "name": "t",+ "prompt": "hi",+ "skip_memory": True, # not a supported job field; must be ignored+ }+ with _run_job_patches(tmp_path) as (_db, agent_cls):+ run_job(job)+ kwargs = agent_cls.call_args.kwargs+ assert kwargs["skip_memory"] is False+++class TestAgentInitOffPathStaysOff:+ """agent_init side of the OFF direction (#65429 / #91447 wording).++ skip_memory=True with 'memory' merely present-by-default but denylisted+ must NOT load the MEMORY.md store — a denylisted toolset is not a request.+ """++ def test_denylisted_memory_toolset_is_not_a_request(self):+ enabled = ["memory", "file"]+ disabled = ["memory"]+ requested = "memory" in enabled and "memory" not in disabled+ # Mirrors agent_init's _memory_toolset_requested gate exactly; the+ # deep store-construction behavior is covered by+ # tests/agent/test_skip_memory_store_65429.py.+ assert requested is Falsediff --git a/tests/hermes_cli/test_env_deprecation_truthtable.py b/tests/hermes_cli/test_env_deprecation_truthtable.pynew file mode 100644index 00000000000..f6f4eaa0507--- /dev/null+++ b/tests/hermes_cli/test_env_deprecation_truthtable.py@@ -0,0 +1,159 @@+"""Truth-table regression test for the 'Deprecated .env settings' warning.++Behavior contract (pins the fix for the TERMINAL_CWD false-positive class:+#88829, #89016, #89389, #90299 — four reports in two weeks of the startup+warning firing when TERMINAL_CWD was merely in the inherited process+environment, e.g. bridged from ``terminal.cwd`` in config.yaml or set by+session restoration / cron / the gateway):++ warn_deprecated_cwd_env_vars() emits the warning IFF the deprecated key+ (TERMINAL_CWD or MESSAGING_CWD) has a genuinely non-empty value inside+ the user's ~/.hermes/.env FILE.++ * Process environment is IRRELEVANT — runtime bridges legitimately set+ TERMINAL_CWD in os.environ (fix commit 31561e37e).+ * config.yaml ``terminal.cwd`` is IRRELEVANT — it neither triggers nor+ suppresses the warning (fix commit a93f1b2be removed suppression).+ * Commented-out or empty-valued .env entries do NOT warn.+ * There is NO quiet/non-interactive gating in the scanner itself; the+ gateway calls it before setting HERMES_QUIET (gateway/run.py), so the+ warning fires regardless of HERMES_QUIET.++Exercises the real scanner against a real temp HERMES_HOME .env file.+"""++import pytest+++REAL_PATH = "/home/user/projects/demo"++# Truth table rows:+# env_file: None = no .env file at all; str = literal .env file bytes+# proc_env: dict of process-environment vars to set (inherited, NOT .env)+# config_yaml: None = no config.yaml; str = literal config.yaml contents+# warn_keys: key names that MUST appear in the warning ((), i.e. empty,+# means the scanner must stay completely silent)+TRUTH_TABLE = [+ pytest.param(None, {}, None, (), id="all-absent-silent"),+ pytest.param(+ None, {"TERMINAL_CWD": REAL_PATH}, None, (),+ id="no-envfile-procenv-only-silent",+ ),+ pytest.param(+ "API_KEY=x\n", {"TERMINAL_CWD": "."}, None, (),+ id="procenv-dot-only-silent-88829",+ ),+ pytest.param(+ "API_KEY=x\n", {"TERMINAL_CWD": REAL_PATH}, None, (),+ id="procenv-realpath-only-silent-89016",+ ),+ pytest.param(+ "API_KEY=x\n",+ {"TERMINAL_CWD": REAL_PATH},+ f"terminal:\n cwd: {REAL_PATH}\n",+ (),+ id="config-bridged-procenv-silent-89389",+ ),+ pytest.param(+ "API_KEY=x\n", {}, f"terminal:\n cwd: {REAL_PATH}\n", (),+ id="config-only-silent-90299",+ ),+ pytest.param(+ "TERMINAL_CWD=.\n", {}, None, ("TERMINAL_CWD",),+ id="dotenv-dot-warns",+ ),+ pytest.param(+ f"TERMINAL_CWD={REAL_PATH}\n", {}, None, ("TERMINAL_CWD",),+ id="dotenv-realpath-warns",+ ),+ pytest.param(+ "TERMINAL_CWD=.\n", {}, "terminal:\n cwd: /other/path\n",+ ("TERMINAL_CWD",),+ id="dotenv-dot-warns-despite-config",+ ),+ pytest.param(+ f"TERMINAL_CWD={REAL_PATH}\n",+ {"TERMINAL_CWD": REAL_PATH},+ f"terminal:\n cwd: {REAL_PATH}\n",+ ("TERMINAL_CWD",),+ id="dotenv-warns-despite-procenv-and-config",+ ),+ pytest.param(+ "TERMINAL_CWD=\n", {"TERMINAL_CWD": REAL_PATH}, None, (),+ id="dotenv-empty-value-silent",+ ),+ pytest.param(+ "# TERMINAL_CWD=.\n", {"TERMINAL_CWD": "."}, None, (),+ id="dotenv-commented-silent",+ ),+ pytest.param(+ f"export TERMINAL_CWD={REAL_PATH}\n", {}, None, ("TERMINAL_CWD",),+ id="dotenv-export-prefix-warns",+ ),+ pytest.param(+ "TERMINAL_CWD=.\n", {"HERMES_QUIET": "1"}, None, ("TERMINAL_CWD",),+ id="quiet-mode-no-gating-dotenv-warns",+ ),+ pytest.param(+ "API_KEY=x\n",+ {"HERMES_QUIET": "1", "TERMINAL_CWD": "."},+ None,+ (),+ id="quiet-mode-procenv-only-silent",+ ),+ pytest.param(+ "MESSAGING_CWD=/msg/path\n", {}, None, ("MESSAGING_CWD",),+ id="dotenv-messaging-cwd-warns",+ ),+ pytest.param(+ "API_KEY=x\n", {"MESSAGING_CWD": "/msg/path"}, None, (),+ id="procenv-messaging-cwd-silent",+ ),+ pytest.param(+ f"MESSAGING_CWD=/msg/path\nTERMINAL_CWD={REAL_PATH}\n",+ {},+ None,+ ("MESSAGING_CWD", "TERMINAL_CWD"),+ id="dotenv-both-keys-warn",+ ),+]++[email protected]("env_file, proc_env, config_yaml, warn_keys", TRUTH_TABLE)+def test_deprecated_env_warning_truth_table(+ env_file, proc_env, config_yaml, warn_keys, monkeypatch, tmp_path, capsys+):+ """Warning fires only for genuine .env-file entries — never for+ inherited process environment or config.yaml (#88829 #89016 #89389 #90299).+ """+ hermes_home = tmp_path / ".hermes"+ hermes_home.mkdir()+ monkeypatch.setenv("HERMES_HOME", str(hermes_home))++ if env_file is not None:+ (hermes_home / ".env").write_bytes(env_file.encode("utf-8"))+ if config_yaml is not None:+ (hermes_home / "config.yaml").write_text(config_yaml, encoding="utf-8")++ # Baseline: deprecated keys absent from process env unless the row says so.+ for key in ("TERMINAL_CWD", "MESSAGING_CWD", "HERMES_QUIET"):+ monkeypatch.delenv(key, raising=False)+ for key, value in proc_env.items():+ monkeypatch.setenv(key, value)++ import hermes_cli.config as config_module++ # load_env() memoises on (path, mtime, size); invalidate so this row's+ # freshly written file is what the scanner reads.+ config_module.invalidate_env_cache()++ config_module.warn_deprecated_cwd_env_vars()++ err = capsys.readouterr().err+ if warn_keys:+ assert "Deprecated .env settings detected" in err+ for key in warn_keys:+ assert f"{key}=" in err, f"expected {key} in warning:\n{err}"+ assert "config.yaml" in err # migration hint present+ else:+ assert err == "", f"expected silence, got:\n{err}"diff --git a/tests/hermes_cli/test_update_receipt_truthfulness.py b/tests/hermes_cli/test_update_receipt_truthfulness.pynew file mode 100644index 00000000000..a8994b6d64b--- /dev/null+++ b/tests/hermes_cli/test_update_receipt_truthfulness.py@@ -0,0 +1,273 @@+"""Truthfulness invariants for the update pipeline at the RECEIPT layer.++Bug class ("update reports success while reality disagrees" — #88654,+#88848, #91378, #91439, #91962, #92780, #92902): the updater's word must be+backed by evidence. This suite pins the honesty contract of the receipt+subsystem with REAL module functions against a temp HERMES_HOME — it is not+a fleet E2E (that lives in the CI install/update harness).++Invariants pinned, and WHERE each is enforced:++1. RECEIPT ALWAYS FINALIZED — ``begin → steps → finalize`` writes a+ parseable receipt for success/failed/refused (#91283 made every+ post-begin run leave a record). A begun-but-never-finalized run+ (simulated crash) writes NOTHING to disk, so the reader the Desktop+ uses (``read_latest_receipt``, surfaced via+ ``/api/hermes/update/receipt`` — #92780) can never interpret a crash+ as success. The HTTP-layer gating of an ``outcome == "running"``+ receipt is already pinned in test_update_receipt_endpoint.py and is+ deliberately not duplicated here.++2. SUCCESS IMPLIES ACCOUNTING — #92902 made the pre-update plan the+ restart worklist. The final refuse-success decision is INLINE in+ ``_cmd_update_impl`` (update_cmd.py ~8331-8373, a 8.5k-line flow), so+ the deepest extractable real functions are pinned instead:+ ``match_runtime_outcomes`` (plan-vs-bookkeeping reconciliation) and+ ``report_unaccounted_runtimes`` (the escalation decision). The+ command's outcome selection is exactly+ ``"partial" if incomplete else "success"`` (update_cmd.py ~8360); the+ tests drive that expression with the real decision function's return+ value, so sabotaging the enforcement (making it accept a missed+ runtime) fails these tests.++3. REFUSAL IS NOT FAILURE — #91439: an exit-2 preflight refusal must+ produce a receipt distinguishable from a failed update, and the+ reader must report it as ``refused``.++Only paths/env are monkeypatched; every receipt is produced by the real+``hermes_cli.update_receipt`` / ``hermes_cli.update_inventory`` API.+"""++import json++import pytest++import hermes_cli.update_receipt as ur+from hermes_cli.update_inventory import (+ RuntimeRecord,+ UpdatePlan,+ match_runtime_outcomes,+ record_plan_in_receipt,+ report_unaccounted_runtimes,+)+++def receipt_home(tmp_path, monkeypatch):+ """Hermetic HERMES_HOME so receipts never touch the real profile."""+ home = tmp_path / ".hermes"+ home.mkdir()+ monkeypatch.setattr(+ "hermes_cli.config.get_hermes_home", lambda: home, raising=False+ )+ ur._current = None+ yield home+ ur._current = None+++def _receipt_files(home):+ directory = home / "logs" / "update_receipts"+ if not directory.is_dir():+ return []+ return sorted(directory.glob("*.json"))+++def _plan_with_runtimes(records):+ plan = UpdatePlan(install_method="git", updatable_in_place=True)+ plan.profiles = sorted({r.profile for r in records})+ plan.runtimes = list(records)+ return plan+++_THREE_RUNTIMES = [+ RuntimeRecord(kind="gateway", profile="default", pid=101,+ supervisor="manual", restart_via="manual"),+ RuntimeRecord(kind="gateway", profile="work", pid=102,+ supervisor="manual", restart_via="manual"),+ RuntimeRecord(kind="serve", profile="ops", pid=103,+ supervisor="manual", restart_via="manual"),+]+++class TestReceiptAlwaysFinalized:+ """Invariant 1 — every finalized run leaves a parseable record; a crash+ leaves NO record the reader could mistake for success (#91283, #92780)."""++ @pytest.mark.parametrize("outcome", ["success", "failed", "refused"])+ def test_finalize_writes_parseable_receipt_for_outcome(+ self, receipt_home, outcome+ ):+ ur.begin_update_receipt()+ ur.record_step("git_pull", outcome == "success", "detail")+ path = ur.finalize_update_receipt(outcome)+ assert path is not None and path.is_file()++ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] == outcome+ assert payload["finished_at"] is not None+ assert payload["steps"][0]["name"] == "git_pull"++ latest = ur.read_latest_receipt()+ assert latest is not None+ assert latest["outcome"] == outcome++ def test_nothing_on_disk_until_finalize(self, receipt_home):+ """The receipt is written atomically at finalize — a run that is+ still going (or that dies) has NO on-disk artifact to misread."""+ ur.begin_update_receipt()+ ur.record_step("pre_update_backup", True)+ assert _receipt_files(receipt_home) == []++ def test_crash_without_finalize_never_claims_success(self, receipt_home):+ """Simulated crash: begin + steps, then the process dies (fresh+ module state). The Desktop's reader (#92780 reads the receipt via+ read_latest_receipt) must see NO successful update."""+ ur.begin_update_receipt()+ ur.record_step("git_pull", True)+ ur.record_step("pip_install", True)+ # Crash: module singleton is gone, finalize never ran.+ ur._current = None++ assert _receipt_files(receipt_home) == []+ latest = ur.read_latest_receipt()+ # No receipt at all — the reader cannot report success. If this+ # ever returns a dict, it must not claim a completed success.+ assert latest is None or latest.get("outcome") != "success"++ def test_boundary_safety_net_records_crash_as_not_success(+ self, receipt_home+ ):+ """When the command boundary DOES catch the unwind (#91283), a+ non-zero exit finalizes as failed — never success."""+ ur.begin_update_receipt()+ ur.record_step("git_pull", False, "network died")+ path = ur.finalize_pending_update_receipt(1, "sys.exit(1)")+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] == "failed"+ assert ur.read_latest_receipt()["outcome"] == "failed"+++class TestSuccessImpliesAccounting:+ """Invariant 2 — #92902: the plan is the worklist. A planned runtime+ with no restart bookkeeping forbids a success outcome."""++ def _drive_decision(self, plan, **bookkeeping):+ """The real #92902 flow: reconcile, decide, finalize — mirroring+ update_cmd.py ~8331-8361 with the real decision functions."""+ outcomes = match_runtime_outcomes(plan, **bookkeeping)+ incomplete = report_unaccounted_runtimes(outcomes)+ record_plan_in_receipt(plan)+ if ur._current is not None:+ ur._current.data["runtime_outcomes"] = outcomes+ # Exact outcome-selection expression from update_cmd.py ~8360.+ path = ur.finalize_update_receipt(+ "partial" if incomplete else "success"+ )+ return outcomes, incomplete, path++ def test_n_minus_one_confirmations_refuses_success(self, receipt_home):+ """Plan of 3 runtimes, bookkeeping accounts for only 2: the verify+ layer must escalate and the receipt must NOT say success."""+ ur.begin_update_receipt()+ plan = _plan_with_runtimes(_THREE_RUNTIMES)+ outcomes, incomplete, path = self._drive_decision(+ plan,+ restarted_services=[],+ relaunched_profiles=["work"], # 102 accounted+ externally_supervised_profiles=[],+ killed_pids={101}, # 101 accounted; 103 missed+ failed_units=[],+ )+ assert incomplete is True, (+ "report_unaccounted_runtimes accepted a plan with a silently "+ "missed runtime — the #92902 invariant is broken"+ )+ missed = [o for o in outcomes if o["outcome"] == "unaccounted"]+ assert [o["pid"] for o in missed] == [103]++ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] != "success"+ assert payload["outcome"] == "partial"++ def test_full_accounting_permits_success_with_evidence(+ self, receipt_home+ ):+ """All planned runtimes accounted → success is allowed, and the+ receipt carries the plan + per-runtime outcomes as evidence."""+ ur.begin_update_receipt()+ plan = _plan_with_runtimes(_THREE_RUNTIMES)+ outcomes, incomplete, path = self._drive_decision(+ plan,+ restarted_services=[],+ relaunched_profiles=["work", "ops"],+ externally_supervised_profiles=[],+ killed_pids={101},+ failed_units=[],+ )+ assert incomplete is False+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["outcome"] == "success"+ # SUCCESS IMPLIES ACCOUNTING: the fleet/verification fields exist+ # and cover every planned runtime, none unaccounted.+ assert len(payload["plan"]["runtimes"]) == 3+ assert len(payload["runtime_outcomes"]) == 3+ assert all(+ o["outcome"] != "unaccounted" for o in payload["runtime_outcomes"]+ )++ def test_failed_unit_also_refuses_success(self, receipt_home):+ """A runtime whose restart FAILED (not merely missed) must also+ surface — outcome 'failed' in the reconciliation rows."""+ ur.begin_update_receipt()+ plan = _plan_with_runtimes(_THREE_RUNTIMES[:1])+ outcomes = match_runtime_outcomes(+ plan,+ restarted_services=[],+ relaunched_profiles=[],+ externally_supervised_profiles=[],+ killed_pids=set(),+ failed_units=["hermes-gateway.service"],+ )+ assert outcomes[0]["outcome"] == "failed"+ ur.finalize_update_receipt("partial")+++class TestRefusalIsNotFailure:+ """Invariant 3 — #91439: refusal (exit 2) and failure are distinct+ outcomes, and the reader reports which one happened."""++ def test_refusal_receipt_distinguishable_from_failure(+ self, receipt_home+ ):+ # Run 1: a real failure.+ ur.begin_update_receipt()+ ur.record_step("git_fetch", False, "remote unreachable")+ failed_path = ur.finalize_pending_update_receipt(1, "sys.exit(1)")+ failed = json.loads(failed_path.read_text(encoding="utf-8"))++ # Run 2: a preflight refusal (venv-holder / concurrent instance).+ ur.begin_update_receipt()+ ur.record_step("venv_preflight", False, "another hermes holds venv")+ refused_path = ur.finalize_pending_update_receipt(2, "sys.exit(2)")+ refused = json.loads(refused_path.read_text(encoding="utf-8"))++ assert failed["outcome"] == "failed" and failed["exit_code"] == 1+ assert refused["outcome"] == "refused" and refused["exit_code"] == 2+ assert refused["outcome"] != failed["outcome"]++ # The reader (Desktop path, #92780/#91439) reports refusal as+ # refusal — not failure, and certainly not success.+ latest = ur.read_latest_receipt()+ assert latest["outcome"] == "refused"+ assert latest["stop_reason"] == "sys.exit(2)"++ def test_refused_receipt_survives_with_its_steps(self, receipt_home):+ """#91439: the refused run's receipt keeps the evidence of WHY —+ the failing preflight step is preserved, not lost."""+ ur.begin_update_receipt()+ ur.record_step("windows_preflight", False, "hermes.exe running")+ path = ur.finalize_pending_update_receipt(2, "concurrent instance")+ payload = json.loads(path.read_text(encoding="utf-8"))+ assert payload["steps"][0]["name"] == "windows_preflight"+ assert payload["steps"][0]["ok"] is False+ assert payload["outcome"] == "refused"diff --git a/tests/hermes_state/test_state_db_maintenance_conformance.py b/tests/hermes_state/test_state_db_maintenance_conformance.pynew file mode 100644index 00000000000..787a82b545a--- /dev/null+++ b/tests/hermes_state/test_state_db_maintenance_conformance.py@@ -0,0 +1,430 @@+"""Conformance suite: state.db maintenance must be guard-aware and copy-honest.++Pins the bug CLASS behind #91839 (FTS rebuild corrupting a shared state.db),+#90806 (WAL sidecars replaced under live holders), #90613 (_safe_copy_db+copying a corrupt DB while reporting success) and #88235 (repair ran surgery+under a live writer — repair-specific guard tests already exist in+tests/test_state_db_repair_live_writer_guard.py and are NOT duplicated here).++Contract, in two sentences:++1. No maintenance entry point that does structural work on state.db may run+ unguarded against a database another live connection still holds — each+ must refuse loudly, degrade to a no-op, or coordinate safely, and the+ database must be ``PRAGMA integrity_check == ok`` afterwards.+2. Any copy/snapshot path that reports success must leave an+ integrity-clean destination; success + corrupt copy is the #90613 bug.++The REGISTRY below enumerates every known maintenance entry point. A+completeness test greps the source modules so a NEW maintenance function (or+a rename of an existing one) fails this suite loudly instead of silently+shipping without live-writer conformance coverage.++All databases are real SQLite files under tmp_path (the production-DB+isolation guard in hermes_state hard-fails on production-shaped paths — never+point these tests at a real profile). Corruption is real byte damage, not+mocks.+"""++from __future__ import annotations++import dataclasses+import re+import sqlite3+import threading+import uuid+from pathlib import Path++import pytest++import hermes_state+from hermes_state import SessionDB+from hermes_cli import backup as backup_mod+from hermes_cli.backup import (+ _create_quick_snapshot_locked,+ _safe_copy_db,+ copy_db_and_verify,+ verify_sqlite_integrity,+)++REPO_ROOT = Path(hermes_state.__file__).resolve().parent++# ---------------------------------------------------------------------------+# REGISTRY — every maintenance entry point doing structural work on state.db+# ---------------------------------------------------------------------------++[email protected](frozen=True)+class MaintenanceOp:+ """One maintenance entry point and where its live-writer safety lives."""++ module: str # import path holding the symbol+ qualname: str # symbol ("func" or "Class.method")+ kind: str # "in-place" | "copy" | "guard"+ covered_by: str # which test (here or elsewhere) pins its conformance+++REGISTRY: tuple[MaintenanceOp, ...] = (+ # In-place structural ops (part 2 here, except repair — covered elsewhere)+ MaintenanceOp("hermes_state", "SessionDB.vacuum", "in-place",+ "test_in_place_op_refuses_or_degrades_under_live_writer"),+ MaintenanceOp("hermes_state", "SessionDB.maybe_auto_prune_and_vacuum",+ "in-place",+ "test_in_place_op_refuses_or_degrades_under_live_writer"),+ MaintenanceOp("hermes_state", "SessionDB.rebuild_fts", "in-place",+ "test_in_place_op_refuses_or_degrades_under_live_writer"),+ MaintenanceOp("hermes_state", "SessionDB.optimize_fts", "in-place",+ "test_in_place_op_refuses_or_degrades_under_live_writer"),+ MaintenanceOp("hermes_state", "repair_state_db_schema", "in-place",+ "tests/test_state_db_repair_live_writer_guard.py"),+ MaintenanceOp("hermes_state", "SessionDB._try_runtime_fts_rebuild",+ "in-place", "tests/state/test_fts_runtime_rebuild.py"),+ # The guards themselves — renaming one must break this suite (#88235,+ # #90806: _foreign_state_db_holders is what stops sidecar replacement+ # under a live holder).+ MaintenanceOp("hermes_state", "_live_writer_holds_db", "guard",+ "test_registry_symbols_exist"),+ MaintenanceOp("hermes_state", "SessionDB._foreign_state_db_holders",+ "guard", "test_registry_symbols_exist"),+ MaintenanceOp("hermes_cli.backup", "verify_sqlite_integrity", "guard",+ "test_copy_honesty_page_damage"),+ # Copy/snapshot paths (part 3)+ MaintenanceOp("hermes_cli.backup", "_safe_copy_db", "copy",+ "test_copy_honesty_truncated_db"),+ MaintenanceOp("hermes_cli.backup", "copy_db_and_verify", "copy",+ "test_copy_honesty_page_damage"),+ MaintenanceOp("hermes_cli.backup", "_create_quick_snapshot_locked",+ "copy", "test_quick_snapshot_flags_corrupt_state_db"),+)++# Source files scanned for maintenance-shaped function definitions.+_SCAN_SOURCES = ("hermes_state.py", "hermes_state_search.py",+ "hermes_cli/backup.py")++# def-names matching this pattern must be in the REGISTRY or the exempt list.+_MAINT_DEF_RE = re.compile(+ r"^\s*def\s+(\w*(?:vacuum|rebuild_fts|repair_state|safe_copy|snapshot"+ r"|checkpoint|optimize_fts|copy_db)\w*)\s*\(", re.M,+)++# Reviewed and deliberately outside the registry: read-only, orchestration+# wrappers around registered ops, or non-structural helpers.+_SCAN_EXEMPT = {+ "_apply_macos_checkpoint_barrier", # per-connection pragma helper+ "_try_wal_checkpoint", # best-effort on own conn, no surgery+ "list_quick_snapshots", # read-only+ "restore_quick_snapshot", # restore target, not live state.db+ "_prune_quick_snapshots", # deletes snapshot dirs, not the DB+ "prune_quick_snapshots", # public wrapper of the above+ "_quick_snapshot_root", # path helper+ "create_quick_snapshot", # lock wrapper -> registered _locked+ "create_pre_update_snapshots_all_profiles", # loops create_quick_snapshot+ "optimize_fts_storage", # offline rebuild w/ its own tests+ "_repair_state_db_schema_locked", # inner half of registered repair+}+++def _resolve(op: MaintenanceOp):+ mod = {"hermes_state": hermes_state, "hermes_cli.backup": backup_mod}[op.module]+ obj = mod+ for part in op.qualname.split("."):+ obj = getattr(obj, part)+ return obj+++# ---------------------------------------------------------------------------+# Fixtures — real WAL-mode SessionDB in tmp dirs+# ---------------------------------------------------------------------------+++def _make_state_db(tmp_path: Path) -> Path:+ db = tmp_path / "state.db"+ handle = SessionDB(db_path=db)+ sid = handle.create_session(session_id=str(uuid.uuid4()), source="cli")+ for i in range(40):+ handle.append_message(sid, role="user",+ content=f"needle-{i} " + "payload " * 40)+ handle.close()+ return db+++def _journal_mode(db: Path) -> str:+ conn = sqlite3.connect(str(db))+ try:+ return conn.execute("PRAGMA journal_mode").fetchone()[0].lower()+ finally:+ conn.close()+++def _require_wal(db: Path) -> None:+ mode = _journal_mode(db)+ if mode != "wal":+ pytest.skip(+ f"runtime opened state.db in journal_mode={mode!r} — this "+ "interpreter's sqlite refuses WAL (known venv quirk); the "+ "live-writer contract here is only meaningful under WAL"+ )+++def _integrity_ok(db: Path) -> bool:+ conn = sqlite3.connect(str(db))+ try:+ return conn.execute("PRAGMA integrity_check").fetchone()[0] == "ok"+ finally:+ conn.close()+++class _LiveWriter:+ """A REAL second connection holding a write transaction from a thread."""++ def __init__(self, db: Path):+ self.db = db+ self.ready = threading.Event()+ self.release = threading.Event()+ self.error: Exception | None = None+ self.thread = threading.Thread(target=self._run, daemon=True)++ def _run(self) -> None:+ conn = None+ try:+ conn = sqlite3.connect(str(self.db), timeout=0.0)+ conn.execute("PRAGMA busy_timeout=0")+ conn.execute("BEGIN IMMEDIATE")+ conn.execute(+ "INSERT INTO state_meta(key, value) VALUES('lw-probe','1') "+ "ON CONFLICT(key) DO UPDATE SET value='1'"+ )+ self.ready.set()+ self.release.wait(timeout=120)+ conn.execute("ROLLBACK")+ except Exception as exc: # surfaced by __exit__+ self.error = exc+ self.ready.set()+ finally:+ if conn is not None:+ conn.close()++ def __enter__(self) -> "_LiveWriter":+ self.thread.start()+ assert self.ready.wait(timeout=30), "live writer never acquired lock"+ if self.error is not None:+ raise self.error+ return self++ def __exit__(self, *exc) -> None:+ self.release.set()+ self.thread.join(timeout=30)+++def _corrupt_page_damage(src: Path, dst: Path) -> None:+ """Real corruption: XOR 512 bytes at the page boundary holding rows."""+ data = bytearray(src.read_bytes())+ idx = data.find(b"needle-10")+ assert idx > 0, "fixture rows not found in raw db bytes"+ page_start = (idx // 4096) * 4096+ for off in range(page_start, page_start + 512):+ data[off] ^= 0xFF+ dst.write_bytes(bytes(data))+++# ---------------------------------------------------------------------------+# Part 1 — REGISTRY COMPLETENESS+# ---------------------------------------------------------------------------+++def test_registry_symbols_exist():+ """Every registered symbol must still resolve; renames break loudly.++ A silent rename would orphan the coverage below while the suite stayed+ green — the exact failure mode that let #91839/#90806 regress guarded+ paths.+ """+ for op in REGISTRY:+ obj = _resolve(op)+ assert callable(obj), f"{op.module}.{op.qualname} is not callable"+++def test_source_scan_finds_no_unregistered_maintenance_ops():+ """Grep the source modules for maintenance-shaped defs.++ Any new function whose name matches the maintenance pattern must be+ added to REGISTRY (with conformance coverage) or to _SCAN_EXEMPT (with a+ reviewed justification). Either way the addition is a conscious act.+ """+ registered = {op.qualname.split(".")[-1] for op in REGISTRY}+ found: set[str] = set()+ for rel in _SCAN_SOURCES:+ src = (REPO_ROOT / rel).read_text(encoding="utf-8", errors="replace")+ found.update(_MAINT_DEF_RE.findall(src))+ unregistered = found - registered - _SCAN_EXEMPT+ assert not unregistered, (+ "maintenance-shaped functions with no conformance coverage: "+ f"{sorted(unregistered)} — add them to REGISTRY (and write a "+ "live-writer/copy-honesty test) or to _SCAN_EXEMPT with a reason"+ )+ # And the scan itself must still see the registered names it pins,+ # otherwise the regex has rotted into vacuity.+ missing = {"vacuum", "rebuild_fts", "_safe_copy_db",+ "repair_state_db_schema"} - found+ assert not missing, f"source scan no longer sees {sorted(missing)}"+++# ---------------------------------------------------------------------------+# Part 2 — LIVE-WRITER GUARD (in-place ops)+# ---------------------------------------------------------------------------++# op name -> callable(handle) -> outcome check. Each documented outcome is+# the op's refusal/degradation contract while a second connection holds a+# write transaction. "raises" pins loud refusal; dict/int outcomes pin the+# never-raise APIs degrading without touching the index/db structure.+_IN_PLACE_CASES = {+ "SessionDB.vacuum": "raises-operational-error",+ "SessionDB.maybe_auto_prune_and_vacuum": "returns-error-dict",+ "SessionDB.rebuild_fts": "returns-zero",+ "SessionDB.optimize_fts": "returns-zero",+}++[email protected]("qualname", sorted(_IN_PLACE_CASES))+def test_in_place_op_refuses_or_degrades_under_live_writer(tmp_path, qualname):+ """#91839/#88235 class: structural work must not proceed under a holder.++ With a real second connection holding BEGIN IMMEDIATE, each in-place+ maintenance op must refuse or degrade per its documented contract, and+ the database must be integrity-clean and row-identical afterwards.+ """+ db = _make_state_db(tmp_path)+ _require_wal(db)+ handle = SessionDB(db_path=db)+ try:+ with _LiveWriter(db):+ outcome = _IN_PLACE_CASES[qualname]+ method = getattr(handle, qualname.split(".")[1])+ if outcome == "raises-operational-error":+ with pytest.raises(sqlite3.OperationalError) as exc_info:+ method()+ msg = str(exc_info.value).lower()+ assert "locked" in msg or "busy" in msg+ elif outcome == "returns-error-dict":+ result = method(retention_days=0, min_interval_hours=0)+ assert result.get("vacuumed") is False, (+ "auto-maintenance claims it vacuumed under a live writer"+ )+ assert result.get("error") or result.get("pruned") == 0+ elif outcome == "returns-zero":+ assert method() == 0, (+ f"{qualname} claims it rewrote FTS structures while a "+ "live writer held the database (#91839 class)"+ )+ finally:+ handle.close()+ assert _integrity_ok(db), f"{qualname} left state.db corrupt (#91839)"+ # Canonical rows untouched.+ conn = sqlite3.connect(str(db))+ try:+ assert conn.execute("SELECT COUNT(*) FROM messages").fetchone()[0] == 40+ finally:+ conn.close()+++def test_live_writer_probe_detects_real_holder(tmp_path):+ """The shared guard primitive must see a real holder (#88235, #90806)."""+ db = _make_state_db(tmp_path)+ _require_wal(db)+ assert hermes_state._live_writer_holds_db(db) is False+ with _LiveWriter(db):+ assert hermes_state._live_writer_holds_db(db) is True, (+ "guard failed to detect a live write transaction — every "+ "registered op relying on it is now unguarded"+ )+ assert hermes_state._live_writer_holds_db(db) is False+++# ---------------------------------------------------------------------------+# Part 3 — COPY HONESTY (#90613)+# ---------------------------------------------------------------------------+++def test_copy_honesty_page_damage(tmp_path):+ """#90613 pin: success + corrupt destination is forbidden.++ The merged fix layers verify_sqlite_integrity over the raw copier:+ ``copy_db_and_verify`` must return False AND remove the destination when+ the copy is not integrity-clean. The invariant asserted is the class:+ never (returned True and destination invalid).+ """+ good = _make_state_db(tmp_path)+ corrupt = tmp_path / "corrupt.db"+ _corrupt_page_damage(good, corrupt)+ assert not verify_sqlite_integrity(corrupt, run_pragma=True)["valid"], (+ "fixture failed to actually corrupt the database"+ )++ dst = tmp_path / "copy.db"+ ok = copy_db_and_verify(corrupt, dst)+ dst_valid = dst.exists() and verify_sqlite_integrity(+ dst, run_pragma=True)["valid"]+ assert not (ok and not dst_valid), (+ "copy_db_and_verify returned success with a corrupt destination "+ "(#90613: the exact silent-bad-backup bug)"+ )+ # Pin the merged fix's concrete behavior: refuse + clean up.+ assert ok is False+ assert not dst.exists(), "failed copy left a corrupt destination behind"+++def test_copy_honesty_truncated_db(tmp_path):+ """Truncation mid-page: even the raw copier must fail closed.++ ``_safe_copy_db`` routes through sqlite3's backup() API, which reads+ source pages — a file truncated mid-page must yield False and no+ destination, never a truthy return.+ """+ good = _make_state_db(tmp_path)+ raw = good.read_bytes()+ trunc = tmp_path / "trunc.db"+ trunc.write_bytes(raw[: len(raw) - 4096 - 100])+ assert not verify_sqlite_integrity(trunc, run_pragma=True)["valid"]++ dst = tmp_path / "copy.db"+ assert _safe_copy_db(trunc, dst) is False+ assert not dst.exists(), "_safe_copy_db left a partial destination"++ dst2 = tmp_path / "copy2.db"+ assert copy_db_and_verify(trunc, dst2) is False+ assert not dst2.exists()+++def test_quick_snapshot_flags_corrupt_state_db(tmp_path, monkeypatch):+ """The quick-snapshot path must flag — never silently absorb — a bad DB.++ A fake HERMES_HOME carries a truncated state.db plus a config.yaml. The+ snapshot must either return None or record state.db in the manifest's+ failed_dbs; a manifest listing state.db as captured is the #90613 class+ surfacing through the snapshot path.+ """+ home = tmp_path / "hermes_home"+ home.mkdir()+ (home / "config.yaml").write_text("test: true\n")+ good = _make_state_db(tmp_path)+ raw = good.read_bytes()+ (home / "state.db").write_bytes(raw[: len(raw) - 4096 - 100])++ snap_id = _create_quick_snapshot_locked(label="conformance",+ hermes_home=home)+ if snap_id is None:+ return # refused outright: honest+ snap_dir = home / "state-snapshots" / snap_id+ import json+ meta = json.loads((snap_dir / "manifest.json").read_text())+ if "state.db" in meta.get("files", {}):+ copied = snap_dir / "state.db"+ assert verify_sqlite_integrity(copied, run_pragma=True)["valid"], (+ "quick snapshot recorded a corrupt state.db as captured"+ )+ else:+ assert "state.db" in meta.get("failed_dbs", []), (+ "state.db neither captured nor flagged as failed — silent loss"+ )diff --git a/tests/tools/test_bot_mode_canonical_chat_resolution.py b/tests/tools/test_bot_mode_canonical_chat_resolution.pynew file mode 100644index 00000000000..67b4bc35b80--- /dev/null+++ b/tests/tools/test_bot_mode_canonical_chat_resolution.py@@ -0,0 +1,379 @@+"""Property-style regression suite: Bot Mode canonical-chat resolution algebra.++Bug class (10 incidents in 2 weeks): canonical "Bot Chat" resolution forking+or minting duplicates —+ #92040 newest-session preference made the pinned canonical chat unreachable+ #90705 null canonical pointer minted a duplicate empty Bot Chat per click+ #92692 fail-open minting forked fresh chats after a desktop update+ #90005 same-name group recreation reused old member sessions (PR #91082)+ #90732 infinite fork loop (set_session_title silently dropping conflicts)+ PR #92129 name-based resolution replaced session-id pins for good++Standing maintainer rule: canonical-chat identity must FAIL CLOSED — never+mint on ambiguity. Post-#92129 the contract is name-as-identity:++ One bot = ONE canonical forever-chat = (profile, session titled exactly+ "Bot Chat"). SessionDB title uniqueness (compare-and-swap in+ ``_set_session_title``, ValueError on conflict) makes that pair a registry+ of at most one row. Resolution (``session.list {title}`` and+ ``profiles.list``'s ``canonical_session``) is a PURE READ: absent registry+ → empty result / None, and creation is an explicit, separate,+ adopt-before-mint path (desktop plugin.js). No stored session-id pointer+ exists anywhere in the resolution path.++What is pinned here is the Python layer the desktop relies on. The desktop+click/create flow itself (plugin.js), and group ROOM member-session lifecycle+(#90005's original surface), live in Electron JS and are covered by+tests/canonical-chat-registry.test.mjs et al.; here we pin the DB/RPC algebra+those flows depend on, including a Python re-enactment of the #90005 and+#92692 shapes at the registry layer.+"""++from __future__ import annotations++import threading++import pytest++import tui_gateway.server as srv++CANON = "Bot Chat"+++# ---------------------------------------------------------------------------+# Fixtures (style shared with tests/tui_gateway/test_profiles_list_canonical_session.py)+# ---------------------------------------------------------------------------+++def home(tmp_path, monkeypatch):+ """Temp HERMES_HOME so the gateway resolvers read a throwaway state.db.++ ``session.list`` reaches the DB through the gateway's shared launch+ handle (``srv._get_db``), which is bound at process launch — so, like+ tests/tui_gateway/test_session_hidden_rpc.py, we point it at the temp+ DB directly. ``profiles.list`` reads each profile dir's state.db itself+ and only needs the env override.+ """+ h = tmp_path / ".hermes"+ h.mkdir(parents=True)+ monkeypatch.setenv("HERMES_HOME", str(h))++ from hermes_state import SessionDB++ handles = []++ def _shared_db():+ database = SessionDB(db_path=h / "state.db")+ handles.append(database)+ return database++ monkeypatch.setattr(srv, "_get_db", _shared_db)+ yield h+ for database in handles:+ try:+ database.close()+ except Exception:+ pass+++def _db(home):+ from hermes_state import SessionDB++ return SessionDB(db_path=home / "state.db")+++def _add_session(db, sid, *, title="", ts=1000, source="cli", hidden=False, text="hi"):+ db.create_session(sid, source)+ db.append_message(sid, "user", text, timestamp=ts)+ if title:+ with db._lock:+ db._conn.execute(+ "UPDATE sessions SET title = ?, title_source = 'user' WHERE id = ?",+ (title, sid),+ )+ if hidden:+ db.set_session_hidden(sid, True)+++def _count_sessions(home):+ import sqlite3++ conn = sqlite3.connect(home / "state.db")+ try:+ return conn.execute("SELECT COUNT(*) FROM sessions").fetchone()[0]+ finally:+ conn.close()+++def _canonical_rows(home):+ import sqlite3++ conn = sqlite3.connect(home / "state.db")+ try:+ return [+ r[0]+ for r in conn.execute(+ "SELECT id FROM sessions WHERE title = ?", (CANON,)+ ).fetchall()+ ]+ finally:+ conn.close()+++def _resolve(params=None):+ """The REAL registry resolver the desktop bot row uses: session.list {title}."""+ p = {"title": CANON, "include_hidden": True}+ p.update(params or {})+ envelope = srv._methods["session.list"](1, p)+ return envelope["result"]["sessions"]+++def _canonical_via_profiles():+ """The REAL roster resolver: profiles.list → canonical_session."""+ envelope = srv._methods["profiles.list"](1, {})+ row = next(p for p in envelope["result"]["profiles"] if p["name"] == "default")+ return row["canonical_session"]+++# ---------------------------------------------------------------------------+# State builders — every registry state named in the incident history+# ---------------------------------------------------------------------------+++def _state_empty(home):+ _db(home).close() # create the DB file with zero sessions+++def _state_one_canonical(home):+ db = _db(home)+ _add_session(db, "forever", title=CANON, ts=1000, hidden=True,+ text="forever chat content")+ db.close()+++def _state_canonical_plus_newer(home):+ """#92040 shape: newer ordinary sessions must never outrank the registry."""+ db = _db(home)+ _add_session(db, "forever", title=CANON, ts=1000, hidden=True,+ text="forever chat content")+ _add_session(db, "draft1", title="Scratch", ts=5000, text="stray draft")+ _add_session(db, "draft2", title="", ts=9000, text="newest untitled")+ db.close()+++def _state_rotated(home):+ """Identity rotated: old row renamed away, a NEW session id holds the name.++ Name-as-identity (PR #92129) means the registry follows the NAME, not any+ remembered session id — a stale pointer must never be consulted.+ """+ db = _db(home)+ _add_session(db, "old-forever", title="Bot Chat (retired)", ts=1000,+ text="old generation")+ _add_session(db, "new-forever", title=CANON, ts=2000, hidden=True,+ text="new generation")+ db.close()+++STATES = {+ "no_sessions": (_state_empty, None),+ "one_canonical": (_state_one_canonical, "forever"),+ "canonical_plus_newer": (_state_canonical_plus_newer, "forever"),+ "rotated_identity": (_state_rotated, "new-forever"),+}+++# ---------------------------------------------------------------------------+# Property 1 — IDEMPOTENCE: resolve twice, same answer, in every state+# ---------------------------------------------------------------------------++[email protected]("state", list(STATES))+def test_resolution_is_idempotent(home, state):+ """Resolving the canonical chat twice returns the identical row both times.++ #90705 / #90732: any resolver that mutates on read (minting, adopting,+ re-pinning) breaks idempotence and forks the forever-chat.+ """+ build, expected = STATES[state]+ build(home)++ first = _resolve()+ second = _resolve()++ assert first == second+ if expected is None:+ assert first == [] # fail closed: absent registry resolves to nothing+ else:+ assert [r["id"] for r in first] == [expected]++[email protected]("state", list(STATES))+def test_profiles_list_agrees_with_registry(home, state):+ """Roster preview identity == click identity (#92040, PR #92129).++ profiles.list's canonical_session and session.list's title lookup must+ name the same registry row — never the newest session.+ """+ build, expected = STATES[state]+ build(home)++ canonical = _canonical_via_profiles()+ if expected is None:+ assert canonical is None+ else:+ assert canonical["id"] == expected+ assert canonical["root_title"] == CANON+++# ---------------------------------------------------------------------------+# Property 2 — NEVER-MINT: resolution is a pure read in every state+# ---------------------------------------------------------------------------++[email protected]("state", list(STATES))+def test_resolution_never_mints(home, state):+ """Session count is unchanged by any number of resolutions (#90705, #92692).++ Fail-closed contract pinned from code (methods_session.py title-lookup+ path and methods_profiles._canonical_session_row): when NO canonical row+ exists the resolvers return []/None — they REFUSE rather than create.+ Creation is an explicit separate path (desktop adopt-before-mint), never+ a side effect of lookup.+ """+ build, _ = STATES[state]+ build(home)++ before = _count_sessions(home)+ for _ in range(3):+ _resolve()+ _canonical_via_profiles()+ assert _count_sessions(home) == before+++def test_absent_registry_resolves_empty_not_minted(home):+ """The #90705 shape exactly: null canonical → resolver must NOT mint."""+ _state_empty(home)+ assert _resolve() == []+ assert _canonical_via_profiles() is None+ assert _count_sessions(home) == 0+++# ---------------------------------------------------------------------------+# Property 3 — UNIQUENESS: at most one canonical row per profile, always+# ---------------------------------------------------------------------------+++def test_title_registry_rejects_second_canonical(home):+ """SessionDB refuses a second "Bot Chat" title (ValueError, not silence).++ #90732's fork loop started because set_session_title silently dropped+ conflicting titles; the current CAS raises, which is what lets creators+ adopt instead of minting.+ """+ db = _db(home)+ _add_session(db, "forever", title=CANON, ts=1000)+ db.create_session("pretender", "cli")+ with pytest.raises(ValueError):+ db.set_session_title("pretender", CANON)+ db.close()+ assert _canonical_rows(home) == ["forever"]+++def _adopt_or_mint(home, sid, results, idx):+ """The adopt-before-mint creation algebra plugin.js runs, re-enacted in+ Python against the real SessionDB: lookup → create+claim → on conflict+ re-lookup and ADOPT. This is the #92692 racing-resolvers shape."""+ from hermes_state import SessionDB++ db = SessionDB(db_path=home / "state.db")+ try:+ row = db.get_session_by_title(CANON)+ if row:+ results[idx] = row["id"]+ return+ db.create_session(sid, "cli")+ try:+ db.set_session_title(sid, CANON)+ results[idx] = sid+ except ValueError:+ # Lost the race: adopt the winner, never fork.+ row = db.get_session_by_title(CANON)+ results[idx] = row["id"] if row else None+ finally:+ db.close()++[email protected]("seq", [+ ["resolve", "resolve", "resolve"],+ ["create", "resolve", "create", "resolve"],+ ["resolve", "create", "resolve", "create", "resolve"],+])+def test_any_operation_sequence_leaves_at_most_one_canonical(home, seq):+ """After ANY sequence of resolve/create ops: ≤1 canonical row (#92692)."""+ _state_empty(home)+ results = {}+ for i, op in enumerate(seq):+ if op == "resolve":+ _resolve()+ else:+ _adopt_or_mint(home, f"mint-{i}", results, i)+ assert len(_canonical_rows(home)) <= 1+ creators = [v for k, v in results.items()]+ assert len(set(creators)) <= 1 # every creator converged on one identity+++def test_two_resolvers_racing_cold_profile_yield_one_canonical(home):+ """#92692: two resolvers racing on a cold profile mint at most ONE chat.++ The DB-level guarantee pinned: the title-uniqueness CAS serializes the+ claim; the loser gets ValueError and adopts. Post-state: exactly one+ canonical row, and both racers hold the SAME id.+ """+ _state_empty(home)+ results = {}+ threads = [+ threading.Thread(target=_adopt_or_mint, args=(home, f"racer-{i}", results, i))+ for i in range(2)+ ]+ for t in threads:+ t.start()+ for t in threads:+ t.join(timeout=30)++ rows = _canonical_rows(home)+ assert len(rows) == 1+ assert set(results.values()) == {rows[0]}+++# ---------------------------------------------------------------------------+# Property 4 — RECREATION: a recreated same-name identity is FRESH (#90005)+# ---------------------------------------------------------------------------+++def test_recreated_same_name_identity_gets_fresh_session(home):+ """Disband + recreate under the same name must NOT resurrect old rows.++ #90005's surface (group ROOM member sessions) lives desktop-side in+ plugin.js ($groupChats) and is not importable here; what the fix+ (PR #91082) relies on at this layer is that identity follows the CURRENT+ registry row: once the old row's title is released and a new session+ claims the name, resolution returns ONLY the new session — the retired+ row is never adopted again.+ """+ db = _db(home)+ _add_session(db, "gen1", title=CANON, ts=1000, text="first life")+ db.close()+ assert [r["id"] for r in _resolve()] == ["gen1"]++ # Disband: release the name (rename away), then recreate under same name.+ db = _db(home)+ db.set_session_title("gen1", "Bot Chat (disbanded)")+ _add_session(db, "gen2", title=CANON, ts=2000, text="second life")+ db.close()++ resolved = _resolve()+ assert [r["id"] for r in resolved] == ["gen2"]+ assert _canonical_via_profiles()["id"] == "gen2"+ assert len(_canonical_rows(home)) == 1