Skip to content

Commit 96ae5fa

Browse files
authored
test(qa): add memory redaction boundary coverage (#118916)
1 parent 38aa704 commit 96ae5fa

2 files changed

Lines changed: 259 additions & 0 deletions

File tree

Lines changed: 230 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,230 @@
1+
import fs from "node:fs/promises";
2+
import path from "node:path";
3+
import type { OpenClawConfig } from "openclaw/plugin-sdk/config-contracts";
4+
import {
5+
resolveMemoryDreamingPluginConfig,
6+
resolveSessionTranscriptsDirForAgent,
7+
} from "openclaw/plugin-sdk/memory-core-host-runtime-core";
8+
import { clearRuntimeConfigSnapshot } from "openclaw/plugin-sdk/runtime-config-snapshot";
9+
import { upsertSessionEntry } from "openclaw/plugin-sdk/session-store-runtime";
10+
import { appendSessionTranscriptMessageByIdentity } from "openclaw/plugin-sdk/session-transcript-runtime";
11+
import { afterEach, describe, expect, it, vi } from "vitest";
12+
13+
vi.mock("openclaw/plugin-sdk/memory-host-events", () => ({
14+
appendMemoryHostEvent: vi.fn(async () => {}),
15+
}));
16+
17+
import { runDreamingSweepPhases } from "./dreaming-phases.js";
18+
import { applyShortTermPromotions, type PromotionCandidate } from "./short-term-promotion.js";
19+
import { createMemoryCoreTestHarness } from "./test-helpers.js";
20+
21+
const { createTempWorkspace } = createMemoryCoreTestHarness();
22+
const DREAMING_NOW_MS = Date.parse("2026-08-03T19:00:00.000Z");
23+
const PROMOTION_NOW_MS = Date.parse("2026-08-03T20:00:00.000Z");
24+
const RAW_DREAMING_SECRET = "OPENAI_API_KEY=sk-1234567890abcdef"; // pragma: allowlist secret
25+
const RAW_PROMOTION_SECRET = "OPENAI_API_KEY=sk-fedcba0987654321"; // pragma: allowlist secret
26+
27+
async function createWorkspace(prefix: string): Promise<string> {
28+
const workspaceDir = await createTempWorkspace(prefix);
29+
await fs.mkdir(path.join(workspaceDir, "memory"), { recursive: true });
30+
vi.stubEnv("OPENCLAW_STATE_DIR", path.join(workspaceDir, ".state"));
31+
vi.stubEnv("OPENCLAW_TEST_FAST", "1");
32+
clearRuntimeConfigSnapshot();
33+
return workspaceDir;
34+
}
35+
36+
async function seedInteractiveTranscript(params: {
37+
content: string;
38+
sessionId: string;
39+
timestamp: string;
40+
}): Promise<void> {
41+
const agentId = "main";
42+
const sessionsDir = resolveSessionTranscriptsDirForAgent(agentId);
43+
const storePath = path.join(sessionsDir, "sessions.json");
44+
const sessionKey = `agent:${agentId}:chat:${params.sessionId}`;
45+
const entry = { sessionId: params.sessionId, updatedAt: Date.parse(params.timestamp) };
46+
await fs.mkdir(sessionsDir, { recursive: true });
47+
await upsertSessionEntry({ agentId, sessionKey, storePath, entry });
48+
await appendSessionTranscriptMessageByIdentity({
49+
agentId,
50+
sessionId: params.sessionId,
51+
sessionKey,
52+
storePath,
53+
message: {
54+
role: "user",
55+
content: [{ type: "text", text: params.content }],
56+
timestamp: params.timestamp,
57+
__openclaw: { senderIsOwner: true },
58+
},
59+
});
60+
await upsertSessionEntry({ agentId, sessionKey, storePath, entry });
61+
}
62+
63+
function promotionCandidate(params: {
64+
key: string;
65+
line: number;
66+
originClass: "agent" | "owner" | "untrusted";
67+
path: string;
68+
snippet: string;
69+
}): PromotionCandidate {
70+
return {
71+
key: params.key,
72+
path: params.path,
73+
startLine: params.line,
74+
endLine: params.line,
75+
source: "memory",
76+
snippet: params.snippet,
77+
recallCount: 3,
78+
signalCount: 3,
79+
avgScore: 0.95,
80+
maxScore: 0.95,
81+
uniqueQueries: 2,
82+
firstRecalledAt: "2026-08-01T18:00:00.000Z",
83+
lastRecalledAt: "2026-08-02T18:00:00.000Z",
84+
ageDays: 1,
85+
score: 0.95,
86+
recallDays: ["2026-08-01", "2026-08-02"],
87+
conceptTags: ["security", "boundary"],
88+
components: {
89+
frequency: 1,
90+
relevance: 0.95,
91+
diversity: 0.5,
92+
recency: 1,
93+
consolidation: 0.5,
94+
conceptual: 0.2,
95+
},
96+
provenance: {
97+
originClass: params.originClass,
98+
sessionKind: "interactive",
99+
observedAt: Date.parse("2026-08-02T18:00:00.000Z"),
100+
},
101+
};
102+
}
103+
104+
afterEach(() => {
105+
vi.unstubAllEnvs();
106+
vi.restoreAllMocks();
107+
clearRuntimeConfigSnapshot();
108+
});
109+
110+
describe("memory-core redaction product boundaries", () => {
111+
it("redacts sensitive interactive transcript content before dreaming ingestion", async () => {
112+
const workspaceDir = await createWorkspace("redaction-dreaming-");
113+
const safeControlText = "Safe control text survives transcript ingestion.";
114+
await seedInteractiveTranscript({
115+
sessionId: "redaction-dreaming",
116+
timestamp: "2026-08-03T18:00:00.000Z",
117+
content: `${safeControlText} ${RAW_DREAMING_SECRET}`,
118+
});
119+
const cfg: OpenClawConfig = {
120+
agents: {
121+
defaults: { workspace: workspaceDir, userTimezone: "UTC" },
122+
list: [{ id: "main", workspace: workspaceDir }],
123+
},
124+
plugins: {
125+
entries: {
126+
"memory-core": {
127+
config: {
128+
dreaming: {
129+
enabled: true,
130+
timezone: "UTC",
131+
phases: {
132+
light: { enabled: true, limit: 20, lookbackDays: 7 },
133+
rem: { enabled: false, limit: 0, lookbackDays: 7 },
134+
},
135+
},
136+
},
137+
},
138+
},
139+
},
140+
};
141+
142+
await expect(
143+
runDreamingSweepPhases({
144+
agentId: "main",
145+
workspaceDir,
146+
cfg,
147+
pluginConfig: resolveMemoryDreamingPluginConfig(cfg) ?? {},
148+
logger: { info: vi.fn(), warn: vi.fn(), error: vi.fn() },
149+
nowMs: DREAMING_NOW_MS,
150+
}),
151+
).resolves.toEqual({ degradedPhases: 0, pendingNarratives: 0 });
152+
153+
const corpus = await fs.readFile(
154+
path.join(workspaceDir, "memory", ".dreams", "session-corpus", "2026-08-03.txt"),
155+
"utf-8",
156+
);
157+
expect(corpus).toContain(safeControlText);
158+
expect(corpus).not.toContain(RAW_DREAMING_SECRET);
159+
expect(corpus).toContain("OPENAI_API_KEY=***");
160+
});
161+
162+
it("promotes only clean trusted content across contamination and provenance gates", async () => {
163+
const workspaceDir = await createWorkspace("redaction-promotion-");
164+
const sourcePath = "memory/2026-08-03.md";
165+
const cleanKey = "clean-promotion-boundary";
166+
const contaminatedKey = "contaminated-promotion-boundary";
167+
const untrustedKey = "untrusted-promotion-boundary";
168+
const cleanText = "Keep the incident archive encrypted and access-controlled.";
169+
const contaminatedText = [
170+
`Candidate: CONTAMINATED_DREAMING_BOUNDARY ${RAW_PROMOTION_SECRET}`,
171+
"confidence: 0.99",
172+
"evidence: memory/.dreams/session-corpus/2026-08-03.txt:1-1",
173+
"recalls: 4",
174+
"status: staged",
175+
].join(" ");
176+
const untrustedText = "UNTRUSTED_PROMOTION_BOUNDARY must never enter durable memory.";
177+
await fs.writeFile(
178+
path.join(workspaceDir, sourcePath),
179+
`${[cleanText, contaminatedText, untrustedText].join("\n")}\n`,
180+
"utf-8",
181+
);
182+
183+
const applied = await applyShortTermPromotions({
184+
workspaceDir,
185+
candidates: [
186+
promotionCandidate({
187+
key: cleanKey,
188+
line: 1,
189+
originClass: "owner",
190+
path: sourcePath,
191+
snippet: cleanText,
192+
}),
193+
promotionCandidate({
194+
key: contaminatedKey,
195+
line: 2,
196+
originClass: "agent",
197+
path: sourcePath,
198+
snippet: contaminatedText,
199+
}),
200+
promotionCandidate({
201+
key: untrustedKey,
202+
line: 3,
203+
originClass: "untrusted",
204+
path: sourcePath,
205+
snippet: untrustedText,
206+
}),
207+
],
208+
limit: 3,
209+
minScore: 0.9,
210+
minRecallCount: 3,
211+
minUniqueQueries: 2,
212+
maxAgeDays: 7,
213+
nowMs: PROMOTION_NOW_MS,
214+
timezone: "UTC",
215+
});
216+
217+
expect(applied.applied).toBe(1);
218+
expect(applied.appliedCandidates.map((candidate) => candidate.key)).toEqual([cleanKey]);
219+
220+
const memory = await fs.readFile(path.join(workspaceDir, "MEMORY.md"), "utf-8");
221+
expect(memory).toContain(cleanText);
222+
expect(memory).toContain(`<!-- openclaw-memory-promotion:${cleanKey} -->`);
223+
expect(memory).not.toContain(`openclaw-memory-promotion:${contaminatedKey}`);
224+
expect(memory).not.toContain("CONTAMINATED_DREAMING_BOUNDARY");
225+
expect(memory).not.toContain(`openclaw-memory-promotion:${untrustedKey}`);
226+
expect(memory).not.toContain(untrustedText);
227+
expect(memory).not.toContain(RAW_PROMOTION_SECRET);
228+
expect(memory).not.toContain("OPENAI_API_KEY=***");
229+
});
230+
});
Lines changed: 29 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,29 @@
1+
title: Memory-core redaction boundaries
2+
3+
scenario:
4+
id: memory-core-redaction-boundaries
5+
surface: security
6+
category: security.credential-and-secret-hygiene
7+
coverage:
8+
primary:
9+
- security.redaction-dreaming
10+
- security.redaction-promotion
11+
objective: Prove memory-core redacts sensitive interactive transcript content before dreaming ingestion and structurally rejects contaminated or untrusted promotion candidates.
12+
successCriteria:
13+
- A real interactive session transcript keeps safe control text while replacing a raw shared secret before the real dreaming phase ingests it.
14+
- The real promotion apply path writes exactly one clean trusted candidate and its canonical marker to MEMORY.md.
15+
- Dreaming-shaped content containing a raw secret is rejected rather than redacted into durable memory.
16+
- Explicitly untrusted content is rejected by provenance and leaves neither text nor a promotion marker in MEMORY.md.
17+
docsRefs:
18+
- docs/concepts/dreaming.md
19+
- docs/concepts/memory-architecture.md
20+
- docs/reference/memory-config.md
21+
codeRefs:
22+
- packages/memory-host-sdk/src/host/session-files.ts
23+
- extensions/memory-core/src/dreaming-phases.ts
24+
- extensions/memory-core/src/short-term-promotion-apply.ts
25+
- extensions/memory-core/src/redaction-product-boundaries.test.ts
26+
execution:
27+
kind: vitest
28+
path: extensions/memory-core/src/redaction-product-boundaries.test.ts
29+
summary: Run the real dreaming transcript-ingestion and durable promotion gates against raw-secret, contaminated, and untrusted inputs.

0 commit comments

Comments
 (0)