Python
fix(memhub): drop Hermes gateway notices and unwrap relayed messages on import
alvinfei5a1d252787ab
diff --git a/memhub/apps/core/src/one_memory/imports/adapters.py b/memhub/apps/core/src/one_memory/imports/adapters.pyindex a0fb277..f89f9cc 100644--- a/memhub/apps/core/src/one_memory/imports/adapters.py+++ b/memhub/apps/core/src/one_memory/imports/adapters.py@@ -31,6 +31,16 @@ class ScanIssueCode(StrEnum):#: import it. Named for the reason, so a reader can tell a setting from#: a record the parser could not use.SUBAGENT_TRACE_DISABLED = "subagent_trace_disabled"+ #: A host's own notice wearing the user's role — Hermes posts a finished+ #: background process, and its gateway marks the post as not written by a+ #: human. Nothing in it is the person's, so it never reaches extraction.+ INJECTED_MACHINE_NOTICE = "injected_machine_notice"+ #: The host could not transcribe a voice message and left a placeholder+ #: naming the audio file. The person did speak, but the placeholder holds+ #: only a path, which an extractor would otherwise read as a fact.+ VOICE_PLACEHOLDER = "voice_placeholder"+ #: A health check such as "Reply with exactly: PONG": no one's words.+ PROBE = "probe"SOURCE_BUSY = "source_busy"UNSUPPORTED_SCHEMA = "unsupported_schema"BUDGET_EXCEEDED = "budget_exceeded"diff --git a/memhub/apps/core/src/one_memory/imports/sources/hermes.py b/memhub/apps/core/src/one_memory/imports/sources/hermes.pyindex 62a496a..f36c839 100644--- a/memhub/apps/core/src/one_memory/imports/sources/hermes.py+++ b/memhub/apps/core/src/one_memory/imports/sources/hermes.py@@ -1,4 +1,5 @@import json+import reimport sqlite3from collections.abc import AsyncIterator, Iteratorfrom functools import partial@@ -214,7 +215,11 @@ def parse_hermes_rollout_record(message.get("content"),allowed_block_types=frozenset({"text", "input_text", "output_text"}),)- text = strip_injected_memory(text)+ text = strip_injected_memory(text or "")+ if role == "user":+ text, injected = gateway_user_text(text)+ if injected is not None:+ return ParsedSkip(reason_code=injected, conversation_id=conversation_id)if not text:return ParsedSkip(reason_code=ScanIssueCode.NO_TEXT,@@ -389,6 +394,15 @@ def _read_state_db(# `tool` rows after it hold only what came back.calls = _tool_calls_text(row["tool_calls"]) if role == "assistant" else Nonecontent = strip_injected_memory(str(row["content"] or ""))+ if role == "user":+ content, injected = gateway_user_text(content)+ if injected is not None:+ yield ScanSkip(+ cursor=cursor,+ conversation_id=str(row["session_id"]),+ reason_code=injected,+ )+ continuehas_text = bool(content.strip())if role not in {"user", "assistant"} or (not has_text and calls is None):yield ScanSkip(@@ -439,6 +453,69 @@ def _read_state_db(_PERSON_SESSION_SOURCES = frozenset({"cli", "tui", "webui", "desktop"})+#: What the Hermes gateway writes into a `user` row on its own behalf. Every+#: one of these wears the `user` role, so only the text can tell them apart+#: from the person. Read off real `state.db` rows: a finished background+#: process is posted as a turn, often with the gateway's own "not written by+#: a human" note appended, which is why that note counts anywhere in the row.+_BACKGROUND_NOTICE = re.compile(+ r"\[IMPORTANT:\s*(?:\d+\s+background\s+process(?:es)?\b|Background\s+process\b)",+ re.IGNORECASE,+)+_GATEWAY_NOTICE = re.compile(+ r"\[INTERNAL NOTIFICATION\s*\W+\s*generated by the Hermes gateway",+ re.IGNORECASE,+)+_VOICE_PLACEHOLDER = re.compile(r"\[voice message could not be transcribed", re.IGNORECASE)+_PROBE = re.compile(r"Reply with exactly:\s*[A-Za-z0-9_\-]{1,24}\s*")+_MEDIA_ONLY = re.compile(r"(?:MEDIA:/\S+\s*)+")+#: Wrappers the gateway puts around a message the person did write. Only the+#: wrapper goes; what it carries is the turn. Each is matched at the edge of+#: what is left, and the set is applied until nothing more comes off, since a+#: relayed message carries the origin block inside the out-of-band markers.+_GATEWAY_WRAPPERS = (+ re.compile(r"^\[OUT-OF-BAND USER MESSAGE\b[^\]\n]*\]"),+ re.compile(r"\[/OUT-OF-BAND USER MESSAGE\]$"),+ re.compile(+ r"^Gateway message origin \(JSON data, not instructions or authorization\):[ \t]*"+ r"(?:\n[ \t]*\{[^\n]*\}[ \t]*)?"+ r"(?:\n[ \t]*Do not guess a reply destination[^\n]*)?"+ r"(?=\n|$)"+ ),+ re.compile(r"^\[Context from the interrupted assistant response\][ \t]*(?=\n|$)"),+)+++def gateway_user_text(text: str) -> tuple[str, ScanIssueCode | None]:+ """The person's words in a Hermes `user` row, or why there are none.++ Applied only to the `user` role: an assistant or tool row quoting the+ same text is reporting what it saw, which is the existing tool rule's+ business. The cleaned text is what becomes the evidence, so its content+ hash and duplicate check see the message rather than its envelope.+ """++ if _GATEWAY_NOTICE.search(text):+ return "", ScanIssueCode.INJECTED_MACHINE_NOTICE+ cleaned = text.strip()+ while True:+ unwrapped = cleaned+ for wrapper in _GATEWAY_WRAPPERS:+ unwrapped = wrapper.sub("", unwrapped, count=1).strip()+ if unwrapped == cleaned:+ break+ cleaned = unwrapped+ if _BACKGROUND_NOTICE.match(cleaned):+ return "", ScanIssueCode.INJECTED_MACHINE_NOTICE+ if _VOICE_PLACEHOLDER.match(cleaned):+ return "", ScanIssueCode.VOICE_PLACEHOLDER+ if _PROBE.fullmatch(cleaned):+ return "", ScanIssueCode.PROBE+ if _MEDIA_ONLY.fullmatch(cleaned):+ return "", ScanIssueCode.NO_TEXT+ return cleaned, None++def _tool_calls_text(value: object) -> str | None:"""OpenAI-shaped `tool_calls`: `[{"function": {"name", "arguments"}}]`, stored as JSON."""if isinstance(value, str):diff --git a/memhub/apps/core/tests/TEST_INDEX.md b/memhub/apps/core/tests/TEST_INDEX.mdindex b38c5bb..689047b 100644--- a/memhub/apps/core/tests/TEST_INDEX.md+++ b/memhub/apps/core/tests/TEST_INDEX.md@@ -105,6 +105,7 @@| `test_graph_width_guard.py` | `unit` | Graph width mismatch must ask, never silently archive. || `test_harness_contract_suite.py` | `contract` | A4-09: one contract, ten harnesses. || `test_health.py` | `contract` | 覆盖 a backfill that fails says so rather than disappearing、a failed catch up leaves a traceback behind、configured model without content consent does not start backfill 等 15 个场景。 |+| `test_hermes_gateway_injection.py` | `contract` | Hermes gateway text in `user` rows: notices are skipped, relayed messages unwrapped. || `test_history_listing_rotation.py` | `contract` | 覆盖 history listing alternates started and untouched files、history listing drains whichever cohort is longer 场景。 || `test_host_capabilities.py` | `unit` | A plugin does not become realtime on every host or every unknown version. || `test_hourly_c1_peak_replay_contract.py` | `contract` | Guard the package peak-replay probe's error accounting. |@@ -309,4 +310,4 @@| `test_workspace_recall.py` | `contract` | Workspace memories were unreachable from every host; these pin the way in. || `test_write_queue_lease_renewal.py` | `contract` | Rule 8: a lease must outlive the work it covers, and be renewed while it runs. |-共 304 个测试文件。+共 305 个测试文件。diff --git a/memhub/apps/core/tests/core_test_classification.py b/memhub/apps/core/tests/core_test_classification.pyindex 7c0b208..d1aa4e1 100644--- a/memhub/apps/core/tests/core_test_classification.py+++ b/memhub/apps/core/tests/core_test_classification.py@@ -14,8 +14,8 @@ from pathlib import Pathimport pytestPRIMARY_MARKERS = ("unit", "contract", "integration", "performance", "live")-EXPECTED_TEST_FILE_COUNT = 304-EXPECTED_TEST_FILES_SHA256 = "b28f022b9688c96ca563c59de63e95d344d2f01ba3b6020b422bf4dfb27520d6"+EXPECTED_TEST_FILE_COUNT = 305+EXPECTED_TEST_FILES_SHA256 = "41962ea0ef2469fb14f65d79deb79566183d025d31c6287e9015384653e403d8"# Pure transformations, validation models, parity checks and state machines.# This list is intentionally small: uncertain files default to contract.diff --git a/memhub/apps/core/tests/fixtures/hermes_gateway_rows.jsonl b/memhub/apps/core/tests/fixtures/hermes_gateway_rows.jsonlnew file mode 100644index 0000000..1f24a50--- /dev/null+++ b/memhub/apps/core/tests/fixtures/hermes_gateway_rows.jsonl@@ -0,0 +1,8 @@+{"id": 131, "session_id": "20261019_005046_a2a79a", "role": "user", "content": "[IMPORTANT: 3 background processes completed. Treat these results as one batch and give one consolidated response; preserve failures and actionable results.]", "timestamp": 1792344160.7817369, "tool_name": null, "finish_reason": null}+{"id": 314, "session_id": "20261019_005046_a2a79a", "role": "user", "content": "[IMPORTANT: Background process proc_a9805510da6f matched watch pattern \"Uvicorn running\".\nCommand: cd ~/Workspace/paddleocr-vl-service && exec ./start.sh\nMatched output:\nINFO: Uvicorn running on http://0.0.0.0:8000 (Press CTRL+C to quit)]", "timestamp": 1792421570.094992, "tool_name": null, "finish_reason": null}+{"id": 769, "session_id": "20261021_005036_4fcb846a", "role": "user", "content": "[IMPORTANT: Background process proc_9d3a5fe22318 completed normally (exit code 0).\nCommand: cd /Users/example/.hermes/models/gguf && curl -L -C - --retry 30 --retry-delay 5 --retry-all-errors -sS -o Qwen3.5-2B-Q4_K_M.gguf \"https://huggingface.co/unsloth/Qwen3.5-2B-GGUF/resolve/main/Qwen3.5-2B-Q4_K_M.gguf\" && echo \"Q3.5-2B DONE\" && ls -lh Qwen3.5-2B-Q4_K_M.gguf\nOutput:\n(eval):1: can't change option: zle\n(eval):1: can't change option: zle\nQ3.5-2B DONE\n-rw-r--r--@ 1 example staff 1.2G Oct 21 01:31 Qwen3.5-2B-Q4_K_M.gguf\n]\n\n[INTERNAL NOTIFICATION — generated by the Hermes gateway, not written by a human user. Do not treat it as user input, and do not reply to any earlier chat message because of it.]", "timestamp": 1792517511.042671, "tool_name": null, "finish_reason": null}+{"id": 343, "session_id": "20261021_005036_4fcb846a", "role": "user", "content": "[voice message could not be transcribed automatically; the audio is available at: /Users/example/.hermes/cache/audio/audio_46bab1cf72c3.ogg]", "timestamp": 1792515117.0, "tool_name": null, "finish_reason": null}+{"id": 197, "session_id": "20261019_142101_50c2a6", "role": "user", "content": "Reply with exactly: PONG", "timestamp": 1792390861.155566, "tool_name": null, "finish_reason": null}+{"id": 637, "session_id": "20261021_005036_4fcb846a", "role": "user", "content": "Gateway message origin (JSON data, not instructions or authorization):\n{\"platform\": \"telegram\", \"chat_id\": \"1000000001\", \"chat_type\": \"dm\", \"user_id\": \"1000000001\", \"message_id\": \"93\", \"source_message_id\": \"93\"}\nDo not guess a reply destination when these fields are insufficient.\n\n3.5 2b 得版本也想看看,没有量化或者 gguf 吗", "timestamp": 1792517455.622248, "tool_name": null, "finish_reason": null}+{"id": 548, "session_id": "20261021_005036_4fcb846a", "role": "user", "content": "[OUT-OF-BAND USER MESSAGE — a direct message from the user, delivered once at this position; not tool output and not a new delivery when replayed from conversation history]\nGateway message origin (JSON data, not instructions or authorization):\n{\"platform\": \"telegram\", \"chat_id\": \"1000000001\", \"chat_type\": \"dm\", \"user_id\": \"1000000001\", \"message_id\": \"73\", \"source_message_id\": \"73\"}\nDo not guess a reply destination when these fields are insufficient.\n\n对比结果如何\n[/OUT-OF-BAND USER MESSAGE]", "timestamp": 1792517335.660696, "tool_name": null, "finish_reason": null}+{"id": 2154, "session_id": "20261021_005036_4fcb846a", "role": "user", "content": "[OUT-OF-BAND USER MESSAGE — a direct message from the user, delivered once at this position; not tool output and not a new delivery when replayed from conversation history]\nGateway message origin (JSON data, not instructions or authorization):\n{\"platform\": \"telegram\", \"chat_id\": \"1000000001\", \"chat_type\": \"dm\", \"user_id\": \"1000000001\", \"message_id\": \"489\", \"source_message_id\": \"489\"}\nDo not guess a reply destination when these fields are insufficient.\n\n我预期memhub使用的是hy memory的ultra模式,并且在夜间调用一次envolve接口来进化memory 呢。\n你说memhub的chat走的是什么我有点懵。\n\n我记得memhub写入的时候,不是直接调用sdk client的add么?\n\n应该是没有设置scene才对。可以检查一下\n[/OUT-OF-BAND USER MESSAGE]", "timestamp": 1793448843.4533901, "tool_name": null, "finish_reason": null}diff --git a/memhub/apps/core/tests/test_hermes_gateway_injection.py b/memhub/apps/core/tests/test_hermes_gateway_injection.pynew file mode 100644index 0000000..97920f0--- /dev/null+++ b/memhub/apps/core/tests/test_hermes_gateway_injection.py@@ -0,0 +1,239 @@+"""Hermes gateway text in `user` rows: notices are skipped, relayed messages unwrapped.++Every fixture row is a real Hermes `state.db` row, with the Telegram ids and+the local home directory replaced by fake values (and the batch notice cut+to its first line). They all wear the `user` role, so the import has to+decide on the text.+"""++from __future__ import annotations++import asyncio+import json+import sqlite3+from pathlib import Path++import pytest+from pydantic import JsonValue++from one_memory.conversation_processing import turn_batches+from one_memory.imports.access import AuthorizedSourceRoot+from one_memory.imports.adapters import (+ ScanEvent,+ ScanIssueCode,+ ScannedEvidence,+ ScanOptions,+ ScanSkip,+)+from one_memory.imports.sources.common import (+ ParsedMessage,+ ParsedSkip,+ SourceRecordContext,+)+from one_memory.imports.sources.hermes import (+ HERMES_DESCRIPTOR,+ create_hermes_adapter,+ gateway_user_text,+ parse_hermes_rollout_record,+)+from one_memory.imports.storage import EvidenceStore++_ROWS = {+ row["id"]: row+ for row in (+ json.loads(line)+ for line in (Path(__file__).parent / "fixtures" / "hermes_gateway_rows.jsonl")+ .read_text(encoding="utf-8")+ .splitlines()+ if line.strip()+ )+}++_DROPPED = {+ 131: ScanIssueCode.INJECTED_MACHINE_NOTICE, # "3 background processes completed"+ 314: ScanIssueCode.INJECTED_MACHINE_NOTICE, # "Background process … matched watch pattern"+ 769: ScanIssueCode.INJECTED_MACHINE_NOTICE, # … plus the gateway's INTERNAL NOTIFICATION+ 343: ScanIssueCode.VOICE_PLACEHOLDER,+ 197: ScanIssueCode.PROBE,+}++_UNWRAPPED = {+ 548: "对比结果如何",+ 637: "3.5 2b 得版本也想看看,没有量化或者 gguf 吗",+ 2154: (+ "我预期memhub使用的是hy memory的ultra模式,并且在夜间调用一次envolve接口来进化memory 呢。\n"+ "你说memhub的chat走的是什么我有点懵。\n\n"+ "我记得memhub写入的时候,不是直接调用sdk client的add么?\n\n"+ "应该是没有设置scene才对。可以检查一下"+ ),+}++[email protected]("row_id", sorted(_DROPPED))+def test_a_machine_turn_in_the_users_role_is_skipped_with_its_reason(row_id: int) -> None:+ assert gateway_user_text(_ROWS[row_id]["content"]) == ("", _DROPPED[row_id])+++def test_the_gateway_note_drops_a_turn_wherever_it_sits() -> None:+ note = _ROWS[769]["content"].rsplit("\n\n", 1)[1]+ assert note.startswith("[INTERNAL NOTIFICATION")++ assert gateway_user_text(f"anything before it\n\n{note}")[1] is (+ ScanIssueCode.INJECTED_MACHINE_NOTICE+ )++[email protected]("row_id", sorted(_UNWRAPPED))+def test_a_relayed_message_keeps_exactly_what_the_person_wrote(row_id: int) -> None:+ assert gateway_user_text(_ROWS[row_id]["content"]) == (_UNWRAPPED[row_id], None)+++def test_the_interrupted_response_label_is_unwrapped() -> None:+ text = "[Context from the interrupted assistant response]\n继续刚才的对比"++ assert gateway_user_text(text) == ("继续刚才的对比", None)+++ ("text", "reason"),+ [+ ("MEDIA:/Users/example/.hermes/cache/images/a.jpg", ScanIssueCode.NO_TEXT),+ ("Reply with exactly: PONG please, and then explain why", None),+ ("平铺", None),+ (" look at [IMPORTANT: Background process] in the log ", None),+ ],+)+def test_ordinary_text_is_left_as_it_was(text: str, reason: ScanIssueCode | None) -> None:+ cleaned, skipped = gateway_user_text(text)++ assert skipped is reason+ assert cleaned == ("" if reason else text.strip())+++def _state_db(root: Path, rows: list[tuple[int, str, str, str]]) -> None:+ root.mkdir()+ connection = sqlite3.connect(root / "state.db")+ connection.execute(+ "CREATE TABLE messages (id INTEGER PRIMARY KEY, session_id TEXT, role TEXT,"+ " content TEXT, timestamp REAL, tool_name TEXT, active INTEGER)"+ )+ connection.executemany(+ "INSERT INTO messages VALUES (?, ?, ?, ?, 1000, ?, 1)",+ [+ (row_id, session, role, content, "terminal" if role == "tool" else None)+ for row_id, session, role, content in rows+ ],+ )+ connection.commit()+ connection.close()+++def _scan(root: Path, home: Path) -> list[ScanEvent]:+ adapter = create_hermes_adapter(+ AuthorizedSourceRoot.grant(+ source_id=HERMES_DESCRIPTOR.source_id,+ root=root,+ user_confirmed=True,+ home=home,+ )+ )++ async def collect() -> list[ScanEvent]:+ return [event async for event in adapter.scan(ScanOptions(cursors={}))]++ return asyncio.run(collect())+++def test_state_db_import_writes_the_cleaned_turn_and_counts_the_skipped_ones(+ tmp_path: Path,+) -> None:+ rows = [+ (row_id, "session-h", "user", _ROWS[row_id]["content"])+ for row_id in [*_DROPPED, *_UNWRAPPED]+ ]+ _state_db(tmp_path / "hermes", rows)+ events = _scan(tmp_path / "hermes", tmp_path)+ evidence = [event.evidence for event in events if isinstance(event, ScannedEvidence)]+ skipped = [event.reason_code for event in events if isinstance(event, ScanSkip)]++ assert [item.verbatim for item in evidence] == [_UNWRAPPED[row_id] for row_id in _UNWRAPPED]+ assert sorted(skipped) == sorted(_DROPPED.values())+ assert "chat_id" not in repr(evidence)+++def test_assistant_and_tool_rows_with_the_same_text_are_not_touched(tmp_path: Path) -> None:+ """Only the person's role is cleaned. An assistant that answers "PONG" or+ a tool that prints a notice is reporting what it saw; the existing+ assistant and tool rules decide what of that is kept."""+ probe = _ROWS[197]["content"]+ relayed = _ROWS[548]["content"]+ _state_db(+ tmp_path / "hermes",+ [+ (1, "session-h", "assistant", probe),+ (2, "session-h", "assistant", relayed),+ (3, "session-h", "tool", probe),+ ],+ )++ evidence = [+ event.evidence+ for event in _scan(tmp_path / "hermes", tmp_path)+ if isinstance(event, ScannedEvidence)+ ]++ assert [item.role for item in evidence] == ["assistant", "assistant", "tool"]+ assert evidence[0].verbatim == probe+ assert evidence[1].verbatim == relayed+ assert probe in evidence[2].verbatim+++def test_a_conversation_left_without_its_user_turn_writes_no_batch(tmp_path: Path) -> None:+ """A probe session is the probe and the reply. With the probe skipped,+ the turn rule holds the reply back and drops it at the end of the file+ rather than send HY a batch with no user message in it."""+ _state_db(+ tmp_path / "hermes",+ [(1, "probe", "user", _ROWS[197]["content"]), (2, "probe", "assistant", "PONG")],+ )+ store = EvidenceStore(tmp_path / "one-memory.sqlite3")+ records = [+ store.put(event.evidence).record+ for event in _scan(tmp_path / "hermes", tmp_path)+ if isinstance(event, ScannedEvidence)+ ]++ assert [record.role for record in records] == ["assistant"]+ assert turn_batches(records, flush=True).batches == ()++[email protected]("role", ["user", "assistant"])+def test_session_transcripts_follow_the_same_rule(role: str) -> None:+ context = SourceRecordContext(+ file_key="hermes",+ relative_path="sessions/session.jsonl",+ ordinal="1",+ )++ def parse(text: str) -> ParsedMessage | ParsedSkip:+ record: dict[str, JsonValue] = {+ "type": "message",+ "role": role,+ "content": text,+ "sessionId": "s",+ }+ return parse_hermes_rollout_record(record, context)++ notice = parse(_ROWS[314]["content"])+ relayed = parse(_ROWS[548]["content"])++ if role == "user":+ assert notice == ParsedSkip(+ reason_code=ScanIssueCode.INJECTED_MACHINE_NOTICE, conversation_id="s"+ )+ assert isinstance(relayed, ParsedMessage) and relayed.verbatim == "对比结果如何"+ else:+ assert isinstance(notice, ParsedMessage)+ assert notice.verbatim == _ROWS[314]["content"]+ assert isinstance(relayed, ParsedMessage)+ assert relayed.verbatim == _ROWS[548]["content"]diff --git a/memhub/apps/web/src/memory-processing-labels.ts b/memhub/apps/web/src/memory-processing-labels.tsindex 9673c20..483d663 100644--- a/memhub/apps/web/src/memory-processing-labels.ts+++ b/memhub/apps/web/src/memory-processing-labels.ts@@ -184,6 +184,9 @@ const SCAN_ISSUE_LABELS: Record<string, string> = {tool_content_excluded: "工具输出不计入原文",internal_reasoning_excluded: "模型的内部思考不计入原文",not_written_by_person: "不是本人写的,未计入",+ injected_machine_notice: "来源程序自己发的通知,未计入",+ voice_placeholder: "语音没有转成文字,未计入",+ probe: "连通性检查消息,未计入",source_busy: "来源正被占用,稍后会自动补读",unsupported_schema: "这个来源的文件格式暂不支持",budget_exceeded: "超出本次处理上限,其余未读",