Repository navigation
fix(openclaw): apply the shared prompt-privacy rule to automatic recall and capture #2636
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
hidb4ai
merged 2 commits into
oceanbase:master
from
Fengzdadi:fix/openclaw-prompt-privacy
Nov 17, 2026
Merged
Changes from all commits
Commits
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
140 changes: 140 additions & 0 deletions
140
integrations/openclaw/plugins/memory-powercontext/src/prompt-privacy.test.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,140 @@ | ||
| /* | ||
| * Copyright (c) 2026 OceanBase. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| import { readFileSync } from "node:fs"; | ||
| import type { OpenClawPluginApi } from "openclaw/plugin-sdk/plugin-entry"; | ||
| import { describe, expect, it } from "vitest"; | ||
| import { resolvePowerContextConfig } from "./config.js"; | ||
| import type { PowerContextClient } from "./http.js"; | ||
| import { registerPowerContextLifecycle } from "./lifecycle.js"; | ||
| import { containsSecret, scrubSecrets } from "./secrets.js"; | ||
|
|
||
| type PrivacyCase = { id: string; prompt: string; sensitive: boolean; authorization?: string }; | ||
| type Hook = (event: unknown, context: unknown) => unknown; | ||
|
|
||
| const { cases } = JSON.parse(readFileSync( | ||
| new URL("../../../../../tests/fixtures/automatic_prompt_privacy.json", import.meta.url), | ||
| "utf8", | ||
| )) as { cases: PrivacyCase[] }; | ||
|
|
||
| function expectNoSyntheticSecret(value: string): void { | ||
| expect(value).not.toContain("synthetic-value-2084"); | ||
| expect(value).not.toContain("synthetic_value_2084"); | ||
| } | ||
|
|
||
| describe("shared automatic prompt privacy policy", () => { | ||
| it.each(cases)("$id", ({ prompt, sensitive, authorization }) => { | ||
| expect(containsSecret(prompt, authorization)).toBe(sensitive); | ||
| const query = scrubSecrets(prompt, authorization); | ||
| if (sensitive) expectNoSyntheticSecret(query); | ||
| else expect(query).toBe(prompt); | ||
| }); | ||
| }); | ||
|
|
||
| const TOKEN_ENV = "POWERCONTEXT_PRIVACY_TEST_TOKEN"; | ||
| const CONTEXT = { agentId: "main", sessionId: "session-privacy", sessionKey: "agent:main:direct:user-1" }; | ||
|
|
||
| function createHarness(options: { captureMaxChars?: number } = {}) { | ||
| const config = resolvePowerContextConfig(undefined, { | ||
| endpoint: "https://powercontext.test", | ||
| tokenEnv: TOKEN_ENV, | ||
| ...options, | ||
| }); | ||
| const requests: Array<{ path: string; body: Record<string, unknown> }> = []; | ||
| const client = { | ||
| async get() { | ||
| return { memory_extraction: true }; | ||
| }, | ||
| async post(path: string, body: Record<string, unknown>) { | ||
| requests.push({ path, body }); | ||
| if (path === "/v1/scope-bindings/resolve") return { scope_id: "scp_privacy" }; | ||
| if (path === "/v1/sources/content") return { status: "accepted", position: 1 }; | ||
| return { schema: "powercontext.prepared-context.v1", status: "empty", content: null, content_bytes: 0 }; | ||
| }, | ||
| } as unknown as PowerContextClient; | ||
| const hooks = new Map<string, Hook>(); | ||
| registerPowerContextLifecycle({ | ||
| on: (name: string, handler: Hook) => hooks.set(name, handler), | ||
| logger: { warn() {}, debug() {} }, | ||
| } as unknown as OpenClawPluginApi, { | ||
| client, | ||
| getConfig: () => config, | ||
| isPrivateSession: () => true, | ||
| createClosingSignal: () => new AbortController().signal, | ||
| }); | ||
| return { | ||
| requests, | ||
| hook: (name: string) => hooks.get(name)!, | ||
| prepare: () => requests.find(({ path }) => path === "/v1/context/prepare"), | ||
| captures: () => requests.filter(({ path }) => path === "/v1/sources/content"), | ||
| }; | ||
| } | ||
|
|
||
| async function withServerToken(token: string | undefined, run: () => Promise<void>): Promise<void> { | ||
| const previous = process.env[TOKEN_ENV]; | ||
| if (token === undefined) delete process.env[TOKEN_ENV]; | ||
| else process.env[TOKEN_ENV] = token; | ||
| try { | ||
| await run(); | ||
| } finally { | ||
| if (previous === undefined) delete process.env[TOKEN_ENV]; | ||
| else process.env[TOKEN_ENV] = previous; | ||
| } | ||
| } | ||
|
|
||
| describe("automatic recall and capture", () => { | ||
| it.each(cases)("$id", async ({ prompt, sensitive, authorization }) => { | ||
| const harness = createHarness(); | ||
| const messages = [{ role: "user", content: prompt }]; | ||
| await withServerToken(authorization?.replace(/^Bearer\s+/u, ""), async () => { | ||
| await harness.hook("before_prompt_build")({ messages, prompt }, CONTEXT); | ||
| await harness.hook("agent_end")({ success: true, runId: "run-privacy", messages }, CONTEXT); | ||
| }); | ||
|
|
||
| expect(harness.prepare()).toBeDefined(); | ||
| if (sensitive) { | ||
| expect(harness.captures()).toEqual([]); | ||
| expectNoSyntheticSecret(JSON.stringify(harness.requests)); | ||
| } else { | ||
| expect(harness.prepare()!.body.query).toBe(prompt.trim()); | ||
| expect(harness.captures()).toHaveLength(1); | ||
| expect(harness.captures()[0]!.body.content).toBe(`User: ${prompt.trim()}`); | ||
| } | ||
| }); | ||
|
|
||
| it("recognizes the Server token the client sends after trimming the environment value", async () => { | ||
| const harness = createHarness(); | ||
| const messages = [{ role: "user", content: "Use synthetic-value-2084 in the request." }]; | ||
| await withServerToken(" synthetic-value-2084\n", async () => { | ||
| await harness.hook("before_prompt_build")({ messages }, CONTEXT); | ||
| await harness.hook("agent_end")({ success: true, runId: "run-token", messages }, CONTEXT); | ||
| }); | ||
|
|
||
| expect(harness.prepare()!.body.query).toBe("Use [REDACTED] in the request."); | ||
| expect(harness.captures()).toEqual([]); | ||
| }); | ||
|
|
||
| it("skips a pre-compaction capture whose credential lies beyond the capture truncation", async () => { | ||
| const harness = createHarness({ captureMaxChars: 128 }); | ||
| const messages = [{ role: "user", content: `${"context ".repeat(40)}api_key=synthetic-value-2084` }]; | ||
| await withServerToken(undefined, async () => { | ||
| await harness.hook("before_compaction")({ messages, messageCount: 1, compactingCount: 1 }, CONTEXT); | ||
| }); | ||
|
|
||
| expect(harness.captures()).toEqual([]); | ||
| expectNoSyntheticSecret(JSON.stringify(harness.requests)); | ||
| }); | ||
| }); |
36 changes: 36 additions & 0 deletions
36
integrations/openclaw/plugins/memory-powercontext/src/secrets.ts
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,36 @@ | ||
| /* | ||
| * Copyright (c) 2026 OceanBase. | ||
| * | ||
| * Licensed under the Apache License, Version 2.0 (the "License"); | ||
| * you may not use this file except in compliance with the License. | ||
| * You may obtain a copy of the License at | ||
| * | ||
| * http://www.apache.org/licenses/LICENSE-2.0 | ||
| * | ||
| * Unless required by applicable law or agreed to in writing, software | ||
| * distributed under the License is distributed on an "AS IS" BASIS, | ||
| * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. | ||
| * See the License for the specific language governing permissions and | ||
| * limitations under the License. | ||
| */ | ||
|
|
||
| const SECRET_PATTERNS = [ | ||
| /-----BEGIN [A-Z0-9 ]*PRIVATE KEY-----[\s\S]*?(?:-----END [A-Z0-9 ]*PRIVATE KEY-----|$)/giu, | ||
| // Consume complete headers before the assignment rule can consume just a scheme or first cookie. | ||
| /(?<![\w-])["']?\b(?:authorization|proxy-authorization|cookie|set-cookie)\b["']?[ \t]*[:=][ \t]*[^\r\n]*(?:\r?\n[ \t]+[^\r\n]*)*/giu, | ||
| /(?<![\w-])["']?\b(?:api[_ -]?key|access[_ -]?(?:key|token)|client[_ -]?secret|secret(?:[_ -]?key)?|private[_ -]?key|password|passwd|passphrase|token|authorization|cookie)\b["']?\s*[:=]\s*(?:"[^"\r\n]*"|'[^'\r\n]*'|`[^`\r\n]*`|[^\s,;}\]]+)/giu, | ||
| /(?<![\w-])bearer\s+[A-Za-z0-9._~+/=-]{8,}(?![\w-])/giu, | ||
| /(?<![\w-])(?:sk-[A-Za-z0-9][A-Za-z0-9_-]{7,}|github_pat_[A-Za-z0-9_]{8,}|gh[pousr]_[A-Za-z0-9_]{8,}|xox[baprs]-[A-Za-z0-9-]{8,})(?![\w-])/giu, | ||
| ] as const | ||
|
|
||
| /** Return text with recognized credential-shaped values replaced. */ | ||
| export function scrubSecrets(text: string, authorization?: string): string { | ||
| const credential = authorization?.replace(/^Bearer\s+/iu, '') | ||
| if (credential) text = text.replaceAll(credential, '[REDACTED]') | ||
| return SECRET_PATTERNS.reduce((scrubbed, pattern) => scrubbed.replace(pattern, '[REDACTED]'), text) | ||
| } | ||
|
|
||
| /** Detect secrets without rejecting ordinary words that merely contain a marker. */ | ||
| export function containsSecret(text: string, authorization?: string): boolean { | ||
| return scrubSecrets(text, authorization) !== text | ||
| } | ||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
[P2] 自动 prompt 隐私规则在 openclaw 侧是手写副本,未进入
scripts/generate_integration_lifecycle.py的生成链本文件 17-33 行的规则与
integrations/lifecycle/prompt-privacy.ts(并行 PR #2644 headb91159a4)除 2 行注释外逐字节相同;用仓库自带 fixturetests/fixtures/automatic_prompt_privacy.json实测 23 个 case 全通过(node 22.22.2 直接类型擦除执行,探针D:\test\github\review\oceanbase-powercontext-pr-2636\probes\probe_privacy.mjs)。问题不在规则本身,而在副本的登记方式。证据:
TYPESCRIPT_COPIES已包含{_OPENCLAW}/src/transport.ts,说明 openclaw 本来就参与这条生成链;TYPESCRIPT_COPIES["prompt-privacy.ts"]只列了_DSH/_OPENCODE/_PI,没有_OPENCLAW;scripts/generate_integration_lifecycle.py(同一作者的 refactor(integrations): generate the TypeScript prompt-privacy copies from one source #2644、fix(integrations): recall with the end of a long prompt in Hermes, LangChain, LangGraph, and Pydantic AI #2647 都登记了自己的副本)。影响:
make integration-lifecycle-check只校验已登记的副本,于是这条规则现在有 4 份实现、只有 3 份受校验。此后修改integrations/lifecycle/prompt-privacy.ts时,openclaw 的secrets.ts漂移不会被任何门禁发现,而docs/{en,zh}/docs/integrations/openclaw.md已改成「自动召回和捕获遵循同一策略」,两份文档会先于代码失真。建议:把本文件改名为
src/prompt-privacy.ts,在TYPESCRIPT_COPIES["prompt-privacy.ts"]追加{_OPENCLAW}/src/prompt-privacy.ts,lifecycle.ts改 import 路径。若 openclaw 因打包或加载方式必须保留独立文件名,请在生成器注释中写明这条例外,使后续改动有据可循。There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed: this rule should be a registered copy. #2644 adds the
prompt-privacy.tsentry toTYPESCRIPT_COPIESand has not merged yet, so this PR cannot register against it today. Whichever of #2636 and #2644 merges second will move this rule tosrc/prompt-privacy.ts, add{_OPENCLAW}/src/prompt-privacy.tsto that entry, and update the import inlifecycle.ts, somake integration-lifecycle-checkcovers all four copies.