The agent that grows with you
Python aiai-agentai-agentsanthropicchatgptclaudeclaude-codecodexhermeshermes-agentllmnous-researchopenai
fix(gateway): preserve Unicode delivery and persisted records
ethernet61dc26cd7d98
diff --git a/gateway/config_loader.py b/gateway/config_loader.pyindex 93a6053f01a..a5d08d7c16f 100644--- a/gateway/config_loader.py+++ b/gateway/config_loader.py@@ -25,7 +25,7 @@ def load_legacy_gateway_json(home: Path) -> Any:if not path.exists():return {}try:- with open(path, "r", encoding="utf-8") as f:+ with open(path, "r", encoding="utf-8-sig") as f:data = json.load(f) or {}logger.info("Loaded legacy %s — consider moving settings to config.yaml", path)return data@@ -348,7 +348,7 @@ def read_yaml_layers(home: Path) -> dict:config_yaml_path = home / "config.yaml"yaml_cfg: dict = {}if config_yaml_path.exists():- with open(config_yaml_path, encoding="utf-8") as f:+ with open(config_yaml_path, encoding="utf-8-sig") as f:yaml_cfg = yaml.safe_load(f) or {}# Managed scope: overlay administrator-pinned values (this loader bypassesdiff --git a/tests/gateway/test_config.py b/tests/gateway/test_config.pyindex 620c5d84426..8287d3fb742 100644--- a/tests/gateway/test_config.py+++ b/tests/gateway/test_config.py@@ -26,6 +26,32 @@ from gateway.config import ()[email protected]("encoding", ["utf-8", "utf-8-sig"])+def test_gateway_file_layers_preserve_unicode_and_fallback(tmp_path, monkeypatch, encoding):+ import json++ monkeypatch.setenv("HERMES_HOME", str(tmp_path))+ monkeypatch.setattr(Path, "home", lambda: tmp_path)+ legacy = tmp_path / "gateway.json"+ yaml_path = tmp_path / "config.yaml"+ legacy.write_bytes(json.dumps({"reset_triggers": ["/départ"], "quick_commands": {+ "salut": {"type": "prompt", "prompt": "héritage 世界"},+ }}, ensure_ascii=False).encode(encoding))+ config = load_gateway_config()+ assert config.reset_triggers == ["/départ"]+ assert config.quick_commands["salut"]["prompt"] == "héritage 世界"++ yaml_path.write_bytes("quick_commands:\n salut:\n type: prompt\n prompt: bonjour 世界\n".encode(encoding))+ config = load_gateway_config()+ assert config.reset_triggers == ["/départ"]+ assert config.quick_commands["salut"]["prompt"] == "bonjour 世界"++ yaml_path.write_bytes("quick_commands: [".encode(encoding))+ assert load_gateway_config().quick_commands["salut"]["prompt"] == "héritage 世界"+ legacy.write_bytes("{broken".encode(encoding))+ assert load_gateway_config().quick_commands == {}++class TestHomeChannelRoundtrip:def test_to_dict_from_dict(self):hc = HomeChannel(diff --git a/tests/tools/test_bot_live_owner_delivery.py b/tests/tools/test_bot_live_owner_delivery.pyindex c35d5d8fd29..8ea2cdf836e 100644--- a/tests/tools/test_bot_live_owner_delivery.py+++ b/tests/tools/test_bot_live_owner_delivery.py@@ -14,9 +14,13 @@ def test_delivery_is_idempotent_fenced_and_permanent(tmp_path, terminal_status):owner = dict(profile_home=str(tmp_path.resolve()), session_id="chat",lease_id="lease", live_session_id="live")delivery_id = "a" * 32- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id=delivery_id)+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id)assert queued["status"] == "queued"- assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id=delivery_id) == queued+ path = tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME / f"{delivery_id}.json"+ raw = path.read_bytes()+ assert not raw.startswith(b"\xef\xbb\xbf")+ path.write_bytes(b"\xef\xbb\xbf" + raw)+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id) == queuedwith pytest.raises(ValueError):mailbox.deliver_to_live_owner(tmp_path, owner, "different", delivery_id=delivery_id)assert mailbox.claim_pending_delivery(tmp_path, dict(owner, lease_id="other")) is None@@ -34,21 +38,79 @@ def test_delivery_is_idempotent_fenced_and_permanent(tmp_path, terminal_status):assert child.returncode == 0, errresults.append(json.loads(out))claims = [r for r in results if r is not None]- assert len(claims) == 1 and claims[0]["message"] == "hello"+ assert len(claims) == 1 and claims[0]["message"] == "héllo 世界"assert mailbox.read_delivery_result(tmp_path, delivery_id)["status"] == "claimed"assert mailbox.claim_pending_delivery(tmp_path, owner) is None- receipt = mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="answer")+ path.write_bytes(b"\xef\xbb\xbf" + path.read_bytes())+ receipt = mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="réponse 世界")+ assert not path.read_bytes().startswith(b"\xef\xbb\xbf")+ path.write_bytes(b"\xef\xbb\xbf" + path.read_bytes())assert mailbox.read_delivery_result(tmp_path, delivery_id) == receipt- assert mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="answer") == receipt+ assert mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="réponse 世界") == receiptwith pytest.raises(ValueError):mailbox.complete_delivery(tmp_path, delivery_id, status=terminal_status, reply="rewrite")- assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id=delivery_id) == receipt+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id=delivery_id) == receiptassert mailbox.claim_pending_delivery(tmp_path, owner) is Noneif os.name != "nt":for path in (tmp_path / "runtime" / mailbox.DELIVERY_DIR_NAME).iterdir():assert path.stat().st_mode & 0o077 == 0[email protected]("intent_state", ["new", "existing", "raced"])+def test_live_dm_bom_readers_preserve_pinned_intent(tmp_path, monkeypatch, intent_state):+ from pathlib import Path++ from hermes_cli.active_sessions import try_acquire_active_session+ from hermes_state import SessionDB+ from tools import bot_live_delivery as mailbox, bot_mode_dm++ db = SessionDB(db_path=tmp_path / "state.db")+ db.create_session(session_id="chat", source="cli")+ db.set_session_title("chat", "Bot Chat")+ lease, refusal = try_acquire_active_session(+ session_id="chat", surface="desktop", config={}, registry_home=tmp_path,+ metadata=dict(live_session_id="live", bot_live_delivery_consumer=True))+ assert refusal is None and lease is not None+ try:+ owner = mailbox.find_canonical_live_owner(tmp_path)+ assert owner is not None+ payload = tmp_path / "message.txt"+ payload.write_bytes("héllo 世界".encode("utf-8-sig"))+ intent_path = Path(str(payload) + ".live.json")+ author = {"id": "bot:coder", "name": "Renée", "is_bot": True}+ intent = dict(owner=owner, message="pinned 世界", delivery_id="d" * 32, author=author)+ encoded = json.dumps(intent, ensure_ascii=False).encode("utf-8-sig")+ if intent_state == "existing":+ intent_path.write_bytes(encoded)+ elif intent_state == "raced":+ real_open = os.open++ def competing_intent(path, flags, *args, **kwargs):+ if Path(path) == intent_path:+ intent_path.write_bytes(encoded)+ return real_open(path, flags, *args, **kwargs)++ monkeypatch.setattr(os, "open", competing_intent)+ record = bot_mode_dm._admit_live_dm(tmp_path, str(payload), author)+ assert record is not None+ assert record["message"] == ("héllo 世界" if intent_state == "new" else "pinned 世界")+ assert record["owner"] == owner and record["author"] == author+ if intent_state == "new":+ assert not intent_path.read_bytes().startswith(b"\xef\xbb\xbf")+ intent_path.write_bytes(b"\xef\xbb\xbf" + intent_path.read_bytes())+ payload.write_text("must not replace pinned payload", encoding="utf-8")+ assert bot_mode_dm._admit_live_dm(None, str(payload)) == record+ claim = mailbox.claim_pending_delivery(tmp_path, owner)+ assert claim is not None and claim["delivery_id"] == record["delivery_id"]+ assert mailbox.claim_pending_delivery(tmp_path, owner) is None+ intent_path.write_bytes(b"\xef\xbb\xbf{broken")+ assert bot_mode_dm._run_delivery([], str(payload), stdin_file=False, profile_home=tmp_path) == 1+ assert payload.exists() # Ambiguous admission must retain its evidence, not retry a transport.+ finally:+ lease.release()+ db.close()++def test_fifo_survives_clock_rollback(tmp_path, monkeypatch):from tools import bot_live_delivery as mailbox@@ -100,9 +162,9 @@ def test_delivery_keeps_the_sender_and_refuses_a_different_one_under_the_same_idowner = dict(profile_home=str(tmp_path.resolve()), session_id="chat", lease_id="lease", live_session_id="live")author = {"id": "bot:coder", "name": "coder", "is_bot": True}- queued = mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author)+ queued = mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author)assert queued["author"] == author- assert mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author=author) == queued+ assert mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author=author) == queuedwith pytest.raises(ValueError):- mailbox.deliver_to_live_owner(tmp_path, owner, "hello", delivery_id="b" * 32, author={**author, "id": "bot:other"})+ mailbox.deliver_to_live_owner(tmp_path, owner, "héllo 世界", delivery_id="b" * 32, author={**author, "id": "bot:other"})assert "author" not in mailbox.deliver_to_live_owner(tmp_path, owner, "no sender", delivery_id="c" * 32)diff --git a/tests/tools/test_bot_mode_dm.py b/tests/tools/test_bot_mode_dm.pyindex ac6b61e93a4..bfa03962329 100644--- a/tests/tools/test_bot_mode_dm.py+++ b/tests/tools/test_bot_mode_dm.py@@ -468,9 +468,10 @@ def test_live_dm_runner_retry_never_reexecutes_failed_claim(tmp_path, monkeypatc@pytest.mark.parametrize("stdin_file", [False, True])-def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file):[email protected]("encoding", ["utf-8", "utf-8-sig"])+def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file, encoding):dm_file = tmp_path / "message with spaces.txt"- dm_file.write_text("secret $(not shell)", encoding="utf-8")+ dm_file.write_bytes("secret λ $(not shell)".encode(encoding))observed = tmp_path / "observed.txt"child = tmp_path / "child.py"child.write_text(@@ -479,7 +480,7 @@ def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file)import pathlibimport sys- source = sys.stdin if sys.argv[1] == "-" else open(sys.argv[1], encoding="utf-8")+ source = sys.stdin if sys.argv[1] == "-" else open(sys.argv[1], encoding="utf-8-sig")with source:pathlib.Path(sys.argv[2]).write_text(source.read(), encoding="utf-8")"""@@ -495,7 +496,7 @@ def test_delivery_runner_keeps_file_for_child_then_unlinks(tmp_path, stdin_file))assert returncode == 0- assert observed.read_text(encoding="utf-8") == "secret $(not shell)"+ assert observed.read_text(encoding="utf-8") == "secret λ $(not shell)"assert not dm_file.exists()@@ -690,6 +691,21 @@ def test_delivery_main_maps_launch_exception_to_one_and_unlinks(tmp_path, monkeyassert not dm_file.exists()+def test_local_turn_decodes_utf8_reply_without_locale_default(tmp_path, monkeypatch, capsys):+ child = tmp_path / "reply.py"+ child.write_text(+ "import sys\n"+ "sys.stdout.buffer.write('réponse 世界'.encode('utf-8'))\n"+ "sys.stderr.buffer.write('diagnostic café'.encode('utf-8'))\n",+ encoding="utf-8",+ )+ monkeypatch.setattr(subprocess, "_text_encoding", lambda: "ascii")+ assert bot_mode_dm._run_local_turn([sys.executable, str(child)], str(tmp_path / "unused")) == 0+ captured = capsys.readouterr()+ assert captured.out == "réponse 世界"+ assert captured.err == "diagnostic café"++@pytest.mark.parametrize("stdin_file", [False, True])def test_real_delivery_command_round_trip(tmp_path, stdin_file):dm_file = tmp_path / "message with spaces.txt"diff --git a/tests/tools/test_completed_process_results.py b/tests/tools/test_completed_process_results.pyindex 820eeb5086f..6e5ffa782c3 100644--- a/tests/tools/test_completed_process_results.py+++ b/tests/tools/test_completed_process_results.py@@ -167,7 +167,7 @@ def test_receipts_are_bounded_redacted_and_session_scoped(tmp_path, monkeypatch)owner_task_id=f"owner-{index}", session_key=f"chat-{index}",parent_session_id="owner-session",started_at=time.time() - receipts.RESULT_RETENTION_SECONDS * 2,- output_buffer="x" * MAX_OUTPUT_CHARS + "\n" + secret,+ output_buffer="x" * MAX_OUTPUT_CHARS + "\nréponse 世界\n" + secret,exited=True, exit_code=index,)registry._running[session.id] = session@@ -177,9 +177,16 @@ def test_receipts_are_bounded_redacted_and_session_scoped(tmp_path, monkeypatch)paths = list((get_hermes_home() / "logs" / "process-results").glob("*.json"))assert len(paths) == 2assert all(secret not in path.read_text(encoding="utf-8") for path in paths)+ for path in paths:+ raw = path.read_bytes()+ assert not raw.startswith(b"\xef\xbb\xbf")+ path.write_bytes(b"\xef\xbb\xbf" + raw)fresh = ProcessRegistry()assert fresh.get(sessions[0].id) is Nonerecovered = fresh.get(sessions[-1].id)+ assert recovered is not None+ assert "réponse 世界" in recovered.output_buffer+ assert recovered.exited and recovered._completion_event.is_set()assert recovered.owner_task_id == sessions[-1].owner_task_idassert len(recovered.output_buffer) <= MAX_OUTPUT_CHARSassert fresh.list_sessions() == [] # Status/liveness scans stay in memory.diff --git a/tools/bot_live_delivery.py b/tools/bot_live_delivery.pyindex 981346c779e..1294acb0f62 100644--- a/tools/bot_live_delivery.py+++ b/tools/bot_live_delivery.py@@ -101,7 +101,7 @@ def _locked(home: Path | str):def _read(path: Path) -> dict[str, Any] | None:try:- return json.loads(path.read_text(encoding="utf-8"))+ return json.loads(path.read_text(encoding="utf-8-sig"))except FileNotFoundError:return Nonediff --git a/tools/bot_mode_dm.py b/tools/bot_mode_dm.pyindex b27715005ae..21325adc741 100644--- a/tools/bot_mode_dm.py+++ b/tools/bot_mode_dm.py@@ -369,7 +369,7 @@ def _run_local_turn(argv: list[str], dm_file: str, *, env: Optional[dict[str, stdef _turn():return subprocess.run([*argv, "--query-file", dm_file], check=False, stdin=subprocess.DEVNULL,- capture_output=True, text=True, env=env)+ capture_output=True, text=True, encoding="utf-8", env=env)proc = _turn()if proc.returncode != 0:@@ -414,19 +414,19 @@ def _admit_live_dm(profile_home: Path | None, dm_file: str, author: Optional[dicintent: dict[str, Any]intent_path = Path(dm_file + ".live.json")if intent_path.exists():- intent = json.loads(intent_path.read_text(encoding="utf-8"))+ intent = json.loads(intent_path.read_text(encoding="utf-8-sig"))else:assert profile_home is not Noneowner = find_canonical_live_owner(profile_home)if owner is None:return None- intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8"),+ intent = dict(owner=owner, message=Path(dm_file).read_text(encoding="utf-8-sig"),delivery_id=hashlib.sha256(str(Path(dm_file).resolve()).encode()).hexdigest(),**({"author": author} if author else {}))try:fd = os.open(intent_path, os.O_CREAT | os.O_EXCL | os.O_WRONLY, 0o600)except FileExistsError:- intent = json.loads(intent_path.read_text(encoding="utf-8"))+ intent = json.loads(intent_path.read_text(encoding="utf-8-sig"))else:with os.fdopen(fd, "w", encoding="utf-8") as stream:json.dump(intent, stream)@@ -506,7 +506,8 @@ def _run_delivery(argv: list[str], dm_file: str, *, stdin_file: bool,# Keep the file open until the transport exits; cleanup occurs# after subprocess.run returns, not merely after stdin reaches EOF.with open(dm_file, "r", encoding="utf-8-sig") as stream:- return subprocess.run(argv, stdin=stream, check=False, env=env).returncode+ # Passing the file descriptor as stdin bypasses the BOM-aware decoder.+ return subprocess.run(argv, input=stream.read().encode("utf-8"), check=False, env=env).returncodefinally:_unlink_dm_file(dm_file)diff --git a/tools/process_registry_results.py b/tools/process_registry_results.pyindex 0c5724eda11..62435edd28a 100644--- a/tools/process_registry_results.py+++ b/tools/process_registry_results.py@@ -98,7 +98,7 @@ def load_completed_results(prefix: str = "") -> dict:if not path.stem.startswith(prefix):continuetry:- record = json.loads(path.read_text(encoding="utf-8"))+ record = json.loads(path.read_text(encoding="utf-8-sig"))if record["id"] != path.stem or not re.fullmatch(r"proc_[\w]+", record["id"]):continueif not _owns_result(owner, record.get("parent_session_id")):