From 90668d51713f05d487bda1b460c3d7dc2baa421b Mon Sep 17 00:00:00 2001 From: Fengzdadi <453788063@qq.com> Date: Mon, 23 Nov 2026 16:35:19 -0500 Subject: [PATCH] fix(hermes): keep recognized credentials out of the pre-compression checkpoint Pre-compression capture redacted each message only with the plugin's own rule, so an Authorization Bearer value or a prefixed key name such as DB_PASSWORD= reached the Server. Each message is now redacted with the shared prompt-privacy rule and then the plugin's rule, the same order the evaluation trace uses. The message stays in the window, so a credential never fails a required checkpoint, and fingerprints, Source IDs and coverage are unchanged. --- docs/en/docs/integrations/hermes.md | 9 +-- docs/en/docs/integrations/index.md | 5 +- docs/zh/docs/integrations/hermes.md | 7 +- docs/zh/docs/integrations/index.md | 3 +- .../hermes/plugins/powercontext/helpers.py | 8 ++- .../hermes/plugins/powercontext/provider.py | 21 +++--- tests/integrations/test_hermes_provider.py | 67 +++++++++++++++++++ 7 files changed, 98 insertions(+), 22 deletions(-) diff --git a/docs/en/docs/integrations/hermes.md b/docs/en/docs/integrations/hermes.md index 8b6f558c92..7ea57f4504 100644 --- a/docs/en/docs/integrations/hermes.md +++ b/docs/en/docs/integrations/hermes.md @@ -102,15 +102,16 @@ Turning off turn capture does not turn off recall, pre-compression capture, or e | Recall / prefetch | Query (trimmed; when longer than 8192 characters or 8192 UTF-8 bytes, cut to its most recent text within both bounds; recognized credentials replaced with `[REDACTED]`), Scope and preparation options; prepared context returns to Hermes | PowerContext Server | Active provider, nonempty query and resolved Scope; each turn prepares its own prompt, and the post-turn background prefetch sends nothing | Select a different memory provider to stop this provider's automatic recall; there is no separate recall switch here | PowerContext automatic recall stops; capture switches alone leave recall available | | Completed turn | Bounded user/assistant text pair, plus session metadata; not the complete tool transcript. A turn whose user or assistant text contains a recognized credential is skipped as a whole | PowerContext Server, as a Source | `capture_turns=true`; automatic writes are suppressed outside the primary agent context | Set `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` before entering sensitive text | Stops this Source capture; recall, pre-compression capture and explicit writes remain independent | | Session end | Flush request for already accepted inputs, not another upload of the session transcript | PowerContext Server | `flush_on_session_end=true`; waits for background writes and checks extraction capability | `POWERCONTEXT_HERMES_FLUSH_ON_SESSION_END=false` | Stops this flush trigger; accepted Sources remain and other processing triggers are unaffected | -| Before compression | New user/assistant evidence window, excluding system/tool messages and redacting detected secrets | PowerContext Server, as a Source | `capture_pre_compress=false`; opt in with `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | Stops this capture and its subsequent extraction attempt; a required checkpoint fails rather than reporting success | +| Before compression | New user/assistant evidence window, excluding system/tool messages; recognized credentials in each message are replaced with `[REDACTED]`, and the message stays in the window | PowerContext Server, as a Source | `capture_pre_compress=false`; opt in with `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | Stops this capture and its subsequent extraction attempt; a required checkpoint fails rather than reporting success | | Explicit remember / built-in memory mirror | Requested Memory content or change, with exact references for updates | PowerContext Server | Explicit operation, or primary-context `on_memory_write` for add/replace/remove | Do not invoke the write or mirror-producing built-in operation; no dedicated mirror switch | Turning off turn capture does not disable these writes | | Evaluation trace | Prompt/query, recalled context and correlation metadata; detected secrets are redacted | Local JSONL files, by default under `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`; opt in with `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | Stops new trace records without disabling recall or capture; existing files remain sensitive | Recall queries and completed-turn capture follow the [automatic prompt privacy](index.md#automatic-prompt-privacy) policy: recognized credentials are replaced in the query, and a turn whose user or assistant text contains one is not captured. -Pre-compression capture redacts detected secrets with its own rules, which are separate from that policy and -recognize fewer credential formats. A turn that completed-turn capture skips can still reach the Server, redacted by -those rules, in a pre-compression window. +Pre-compression capture replaces the same recognized credentials in each message, then applies the plugin's own +redaction, and keeps the message in the window, so a credential in the transcript does not make a required checkpoint +fail. A turn that completed-turn capture skips can therefore still reach the Server in a pre-compression window, with +its recognized credentials replaced. Pre-compression capture prefers the host-normalized `evidence_messages` when supplied, so earlier compression summaries are not reintroduced as fresh evidence. The provider declares checkpoint API v2 and raises on an diff --git a/docs/en/docs/integrations/index.md b/docs/en/docs/integrations/index.md index 32c6364107..64b3216abf 100644 --- a/docs/en/docs/integrations/index.md +++ b/docs/en/docs/integrations/index.md @@ -80,8 +80,9 @@ their capture defaults: A recognized credential in the user text or the assistant reply skips the whole completed turn (Hermes, LangChain), because the turn Source stores both; a recognized credential in the user prompt skips the `user_prompt` event -(Pydantic AI). Pydantic AI model-response and tool events keep their key-based and known-credential redaction, and -Hermes pre-compression capture keeps its own redaction. The configured Server credential is the adapter's token, or +(Pydantic AI). Pydantic AI model-response and tool events keep their key-based and known-credential redaction. +Hermes pre-compression capture replaces recognized credentials in each message and keeps the message, so a credential +does not make a required checkpoint fail. The configured Server credential is the adapter's token, or Hermes's Authorization value. A skip is logged at debug level with the reason `sensitive_content` and without the rejected text; a completed-turn skip also names the side, user or assistant, that contained the credential. diff --git a/docs/zh/docs/integrations/hermes.md b/docs/zh/docs/integrations/hermes.md index 0f12fee2d3..07ecedfcb1 100644 --- a/docs/zh/docs/integrations/hermes.md +++ b/docs/zh/docs/integrations/hermes.md @@ -98,13 +98,14 @@ Evaluation trace 包含 prompt 和召回上下文,应保留在本机并按敏 | 召回 / prefetch | query(去掉首尾空白;超过 8192 个字符或 8192 个 UTF-8 字节时保留同时满足两项上限的最近文本;识别到的凭据替换为 `[REDACTED]`)、Scope 和准备选项;Prepared Context 返回 Hermes | PowerContext Server | provider 已激活、query 非空且 Scope 已解析;每轮按当前 prompt 准备,turn 结束后的后台预取不发请求 | 切换 memory provider 可停止该 provider 的自动召回;此处没有独立召回开关 | PowerContext 自动召回停止;仅关闭捕获不影响召回 | | 完成 turn | 有长度上限的 user/assistant 文本对,以及 session 元数据;不是完整工具 transcript。用户或助手文本含可识别凭据的 turn 整条跳过 | PowerContext Server,保存为 Source | `capture_turns=true`;非主 Agent 上下文抑制自动写入 | 输入敏感文本前设置 `POWERCONTEXT_HERMES_CAPTURE_TURNS=false` | 停止该 Source 捕获;召回、压缩前捕获和显式写入仍独立工作 | | 会话结束 | 针对已接受输入的 flush 请求,不会重新上传会话 transcript | PowerContext Server | `flush_on_session_end=true`;等待后台写入并检查提取能力 | `POWERCONTEXT_HERMES_FLUSH_ON_SESSION_END=false` | 停止此 flush 触发;已接受的 Source 保留,其他处理触发不受影响 | -| 压缩前 | 新 user/assistant 证据窗口,排除 system/tool 消息并脱敏检测到的 secret | PowerContext Server,保存为 Source | `capture_pre_compress=false`;用 `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` 显式开启 | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | 停止此捕获及其后续提取尝试;必需 checkpoint 会失败而非报告成功 | +| 压缩前 | 新 user/assistant 证据窗口,排除 system/tool 消息;每条消息中识别到的凭据替换为 `[REDACTED]`,消息仍保留在窗口中 | PowerContext Server,保存为 Source | `capture_pre_compress=false`;用 `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=true` 显式开启 | `POWERCONTEXT_HERMES_CAPTURE_PRE_COMPRESS=false` | 停止此捕获及其后续提取尝试;必需 checkpoint 会失败而非报告成功 | | 显式 remember / 内置 Memory mirror | 请求的 Memory 内容或变更,更新携带精确引用 | PowerContext Server | 显式操作,或主上下文中 add/replace/remove 的 `on_memory_write` | 不调用该写入或产生 mirror 的内置操作;没有专用 mirror 开关 | 关闭 turn 捕获不会禁用这些写入 | | Evaluation trace | prompt/query、召回上下文及关联元数据;检测到的 secret 会脱敏 | 本地 JSONL 文件,默认位于 `$HERMES_HOME/powercontext/evaluation-trace/` | `evaluation_trace=false`;用 `POWERCONTEXT_HERMES_EVALUATION_TRACE=true` 显式开启 | `POWERCONTEXT_HERMES_EVALUATION_TRACE=false` | 停止新增 trace,不禁用召回或捕获;已有文件仍是敏感数据 | 召回 query 与完成 turn 捕获遵循[自动 prompt 隐私策略](index.md#自动-prompt-隐私策略):query 中识别到的凭据会被替换, -用户或助手文本含凭据的 turn 不会被捕获。压缩前捕获使用自身规则脱敏检测到的 secret,与该策略相互独立, -能识别的凭据格式也更少。完成 turn 捕获跳过的 turn 仍可能出现在压缩前窗口中,按这些规则脱敏后发送到 Server。 +用户或助手文本含凭据的 turn 不会被捕获。压缩前捕获替换每条消息中同样识别到的凭据,再应用插件自身的脱敏规则, +并把消息保留在窗口中,所以 transcript 中的凭据不会导致必需 checkpoint 失败。 +因此,完成 turn 捕获跳过的 turn 仍可能出现在压缩前窗口中,识别到的凭据替换后发送到 Server。 压缩前捕获优先使用宿主提供的规范化 `evidence_messages`,避免把先前压缩摘要再次作为新证据。 provider 声明 checkpoint API v2,必需 checkpoint 未提交时会抛出异常。这描述的是 provider 契约:仓库的 diff --git a/docs/zh/docs/integrations/index.md b/docs/zh/docs/integrations/index.md index 1a21b3f21d..b112c22b61 100644 --- a/docs/zh/docs/integrations/index.md +++ b/docs/zh/docs/integrations/index.md @@ -74,7 +74,8 @@ powercontext setup 用户文本或助手回复中识别到凭据时,整轮跳过完成轮次捕获(Hermes、LangChain),因为轮次 Source 同时保存两者; User Prompt 中识别到凭据时跳过 `user_prompt` 事件(Pydantic AI)。Pydantic AI 的模型响应和工具事件继续按键名和 -已知凭据值脱敏,Hermes 的压缩前捕获继续使用自身的脱敏规则。当前 Server 凭据指适配器配置的 token,或 Hermes 的 +已知凭据值脱敏。Hermes 的压缩前捕获替换每条消息中识别到的凭据并保留该消息, +所以凭据不会导致必需 checkpoint 失败。当前 Server 凭据指适配器配置的 token,或 Hermes 的 Authorization 值。跳过时在 debug 日志中记录原因 `sensitive_content`,不包含被拒绝的文本;完成轮次的跳过还注明 凭据所在的一侧(用户或助手)。 diff --git a/integrations/hermes/plugins/powercontext/helpers.py b/integrations/hermes/plugins/powercontext/helpers.py index d929cc1e0d..60b5ce5b7e 100644 --- a/integrations/hermes/plugins/powercontext/helpers.py +++ b/integrations/hermes/plugins/powercontext/helpers.py @@ -21,7 +21,7 @@ import logging import os import re -from collections.abc import Iterable +from collections.abc import Callable, Iterable from pathlib import Path from typing import Any @@ -162,7 +162,9 @@ def redact_secrets(text: str) -> str: return text -def precompress_entries(messages: list[dict[str, Any]]) -> list[tuple[str, dict[str, Any]]]: +def precompress_entries( + messages: list[dict[str, Any]], *, redact: Callable[[str], str] = redact_secrets +) -> list[tuple[str, dict[str, Any]]]: entries: list[tuple[str, dict[str, Any]]] = [] for message in messages: role = str(message.get("role", "")).strip().lower() @@ -177,7 +179,7 @@ def precompress_entries(messages: list[dict[str, Any]]) -> list[tuple[str, dict[ fingerprint = hashlib.sha256( json.dumps(fingerprint_payload, ensure_ascii=False, sort_keys=True, default=str).encode("utf-8") ).hexdigest() - entries.append((fingerprint, {"role": role, "content": redact_secrets(text)})) + entries.append((fingerprint, {"role": role, "content": redact(text)})) return entries diff --git a/integrations/hermes/plugins/powercontext/provider.py b/integrations/hermes/plugins/powercontext/provider.py index f8d892f226..6e258d0825 100644 --- a/integrations/hermes/plugins/powercontext/provider.py +++ b/integrations/hermes/plugins/powercontext/provider.py @@ -151,13 +151,13 @@ def _recall_query_tail(text: str) -> str: return "" -def _trace_redaction(text: str, authorization: str | None) -> str: - """Redact evaluation-trace text with the shared rule and then the plugin's own rule. +def _redact_credentials(text: str, authorization: str | None) -> str: + """Redact text with the shared rule and then the plugin's own rule. - The trace redacts everything the recall query redacts, and the plugin's rule then redacts what it still recognizes. - The shared rule must run first: the plugin's assignment pattern consumes a scheme word or the start of a - private-key block (``Authorization: Bearer X`` becomes ``[REDACTED] X``), and the shared rule no longer recognizes - what is left. + The evaluation trace and the pre-compression checkpoint redact everything the recall query redacts, and the + plugin's rule then redacts what it still recognizes. The shared rule must run first: the plugin's assignment + pattern consumes a scheme word or the start of a private-key block (``Authorization: Bearer X`` becomes + ``[REDACTED] X``), and the shared rule no longer recognizes what is left. """ return _redact_secrets(_scrub_secrets(text, authorization)) @@ -889,8 +889,8 @@ def prefetch(self, query: str, *, session_id: str = "") -> str: self._record_trace_event( "powercontext_injection", session_id=session_key, - query=_recall_query_tail(_trace_redaction(query, authorization)), - injected_text=_trace_redaction(content.strip(), authorization), + query=_recall_query_tail(_redact_credentials(query, authorization)), + injected_text=_redact_credentials(content.strip(), authorization), status=trace_status, content_bytes=len(content.encode("utf-8")), ) @@ -1087,7 +1087,10 @@ def on_pre_compress( return "" evidence = evidence_messages if evidence_messages is not None else messages - entries = _precompress_entries(evidence) + authorization = getattr(client, "authorization", None) + # A message is redacted in place rather than left out, so a credential in the transcript never makes a required + # checkpoint fail, and fingerprints still hash the original messages. + entries = _precompress_entries(evidence, redact=lambda text: _redact_credentials(text, authorization)) new_entries = _new_precompress_entries(self._precompress_snapshot, entries) if not new_entries: self._precompress_snapshot = [fingerprint for fingerprint, _message in entries] diff --git a/tests/integrations/test_hermes_provider.py b/tests/integrations/test_hermes_provider.py index 9832d21267..af1e0870d4 100644 --- a/tests/integrations/test_hermes_provider.py +++ b/tests/integrations/test_hermes_provider.py @@ -59,6 +59,9 @@ def hermes_modules(monkeypatch): class FakeClient: + # A subclass or a test sets the configured Authorization value; the provider reads it like the real client's. + authorization: str | None = None + def __init__(self) -> None: self.calls: list[tuple[str, tuple[Any, ...], dict[str, Any]]] = [] self.base_url = "http://powercontext.test:8000" @@ -915,6 +918,70 @@ def test_pre_compress_filters_roles_and_redacts_secrets(provider_and_client): assert "deployment" in content +@pytest.mark.parametrize("role", ["user", "assistant"]) +@pytest.mark.parametrize("case", PROMPT_PRIVACY_CASES, ids=[case["id"] for case in PROMPT_PRIVACY_CASES]) +def test_pre_compress_keeps_recognized_credentials_out_of_the_checkpoint(tmp_path, hermes_modules, caplog, case, role): + provider_module, _cli_module = hermes_modules + helpers = importlib.import_module("plugins.powercontext.helpers") + client = FakeClient() + client.authorization = case.get("authorization") + provider = provider_module.PowerContextMemoryProvider( + {"capture_pre_compress": True}, client_factory=lambda _config: client + ) + provider.initialize("session-1", hermes_home=str(tmp_path), agent_identity="coder", user_id="user-7") + window = [ + {"role": "user", "content": "Keep the public API stable."}, + {"role": role, "content": case["prompt"]}, + ] + + with caplog.at_level(logging.DEBUG): + try: + provider.on_pre_compress(window, require_checkpoint=True) + finally: + provider.shutdown() + + captures = [call for call in client.calls if call[0] == "capture_content"] + assert len(captures) == 1 + content = captures[0][1][2] + metadata = captures[0][2]["metadata"] + assert metadata["message_count"] == 2 + assert metadata["powercontext_capture_coverage"]["status"] == "complete" + if case["sensitive"]: + # The message stays in the window with its credential replaced, so the checkpoint still commits. + assert content.startswith("[user] Keep the public API stable.\n") + assert "[REDACTED]" in content + for marker in ("synthetic-value-2084", "synthetic_value_2084", "SyntheticValue2084"): + assert marker not in json.dumps({"content": content, "metadata": metadata}) + assert marker not in caplog.text + else: + assert ( + content == f"[user] Keep the public API stable.\n[{role}] {helpers.redact_secrets(case['prompt'].strip())}" + ) + + +def test_required_checkpoint_commits_a_window_with_a_recognized_credential_once(provider_and_client): + provider, client = provider_and_client + provider._config["capture_pre_compress"] = True + window = [ + {"role": "user", "content": "Which header does the deploy job send?"}, + # The plugin's own rule consumes the scheme word and leaves this value; the shared rule replaces it. + {"role": "assistant", "content": "It sends Authorization: Bearer synthetic-value-2084 to the registry."}, + ] + + provider.on_pre_compress(window, require_checkpoint=True) + provider.on_pre_compress(window, require_checkpoint=True) + provider.on_pre_compress( + [*window, {"role": "user", "content": "Rotate it after the release."}], require_checkpoint=True + ) + + captures = [call for call in client.calls if call[0] == "capture_content"] + assert [capture[1][2] for capture in captures] == [ + "[user] Which header does the deploy job send?\n[assistant] It sends [REDACTED]", + "[user] Rotate it after the release.", + ] + assert all(capture[2]["metadata"]["powercontext_capture_coverage"]["status"] == "complete" for capture in captures) + + @pytest.mark.parametrize( "entry,fail_flush", [