Repository navigation
Conversation
🔒 Aisle Security AnalysisWe found 1 potential security issue(s) in this PR:
1. 🟡 Envelope metadata may bypass sludge detection due to line-start anchoring without leading-whitespace handling
Description
However, the canonical stripping logic in Impact when the metadata header is indented (e.g.
Vulnerable code (line-anchored match without optional leading whitespace): if (new RegExp(`^${escapedSentinel}`, "m").test(text)) {
return true;
}and const trailerRe = new RegExp(`^${escapedSentinel}`, "m");RecommendationAccept leading whitespace before sentinels, to match the canonical stripping behavior ( Update the sentinel regexes to allow optional indentation: // looksLikeEnvelopeSludge
if (new RegExp(`^\\s*${escapedSentinel}\\s*$`, "m").test(text)) {
return true;
}
// sanitizeForMemoryCapture: when locating/truncating a sentinel in plaintext
const trailerRe = new RegExp(`^\\s*${escapedSentinel}`, "m");
...
cleaned = cleaned.replace(new RegExp(`^\\s*${escapedSentinel}.*$`, "gm"), "");Also consider anchoring const blockRe = new RegExp(
`^\\s*${escapedSentinel}\\s*\\n\\s*\`\`\`json\\s*\\n[\\s\\S]*?\\n\\s*\`\`\`\\s*\\n?`,
"gm",
);Add tests for indented sentinel variants (e.g. Analyzed PR: #73787 at commit Last updated on: 2026-04-29T01:06:36Z |
Greptile SummaryThis PR adds envelope-sludge filtering to the
Confidence Score: 4/5Safe to merge; all findings are P2 quality-of-life issues, not regressions or data-loss bugs on the happy path. The PR significantly improves the status quo — previously ALL contaminated messages were stored raw. The three P2 issues (incomplete body stripping for non-JSON sentinels, unconditional whitespace collapsing, unanchored sentinel checks) are edge-case limitations rather than regressions. No P0/P1 issues were identified. extensions/memory-lancedb/index.ts — specifically the sanitizeForMemoryCapture sentinel-body stripping and escapeMemoryForPrompt whitespace handling. Prompt To Fix All With AIThis is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 578-591
Comment:
**Non-JSON sentinel bodies are not stripped — only the header line is removed**
For sentinels followed by plain text rather than a ` ```json ` code fence (most notably `"Chat history since last reply (untrusted, for context):"` and `"Thread starter (untrusted, for context):"`), `blockRe` will not match and only the sentinel header line is removed. The entire body of the history block remains in `cleaned`. If that body contains a `MEMORY_TRIGGERS` word (e.g., `"Bot: I always recommend TypeScript"` inside the quoted history), `shouldCapture` will fire on what looks like clean text and the chat-history snippet — which may be an AI response, not the current user's direct statement — gets vectorized and stored as a long-term memory.
Consider truncating at the sentinel line, similar to how the `Untrusted context` trailer is handled:
```ts
const bodyRe = new RegExp(
`^${escapedSentinel}.*?(?=\\n\\n|$)`,
"gms",
);
cleaned = cleaned.replace(bodyRe, "");
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 475-483
Comment:
**Whitespace collapsing in `escapeMemoryForPrompt` is now unconditional**
The new `.replace(/\s{2,}/g, " ").trim()` step runs on every memory, not just those that contained a `[media attached]` annotation. Any memory whose text had intentional multi-space formatting — tabular data, indented code references, etc. — will be silently reformatted when presented to the model. The stored text is unaffected, but the presentation may differ from what was captured.
If the collapse is only needed to clean up the double-space left after removing an annotation, consider scoping it:
```ts
export function escapeMemoryForPrompt(text: string): string {
const hadMedia = MEDIA_ATTACHED_PATTERN_TEST.test(text);
const stripped = text.replace(MEDIA_ATTACHED_PATTERN, "");
const normalized = hadMedia
? stripped.replace(/\s{2,}/g, " ").trim()
: stripped.trim();
return normalized.replace(/[&<>"']/g, (char) => PROMPT_ESCAPE_MAP[char] ?? char);
}
```
How can I resolve this? If you propose a fix, please make it concise.
---
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 519-529
Comment:
**`INBOUND_META_SENTINELS` membership test is not line-anchored**
The `Untrusted context (metadata…)` check uses `/^Untrusted context \(metadata/m` to avoid false-positives when the phrase appears mid-sentence. The six sentinels in `INBOUND_META_SENTINELS` use `text.includes()`, which has no such anchor. A user message such as `"I saw 'Sender (untrusted metadata):' in the API docs"` will be silently rejected from memory capture even though it contains no actual envelope data. Given how specific these phrases are the practical risk is low, but it is an inconsistency worth documenting or addressing with a `/^<sentinel>/m` anchored test for at least the more likely candidates.
How can I resolve this? If you propose a fix, please make it concise.Reviews (1): Last reviewed commit: "fix(memory-lancedb): reject envelope met..." | Re-trigger Greptile |
|
Addressed all three P2 review comments in f662cbbafa. Comment 1 (PRRT_kwDOQb6kR85-QK80) — non-JSON sentinel bodies not stripped
Comment 2 (PRRT_kwDOQb6kR85-QK-K) — whitespace collapse unconditional in The Comment 3 (PRRT_kwDOQb6kR85-QK_d) —
84 tests pass ( |
|
Thanks for the context here. I swept through the related work, and this is now duplicate or superseded. The PR is useful and in the right owner boundary, but it is not merge-ready because the new bracket-envelope detector misses documented timestamp-free envelope modes, so supported setups can still persist channel/sender metadata in long-term memory. Canonical path: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. So I’m closing this here because the remaining work is already tracked in the canonical issue. Review detailsBest possible solution: Close this stale PR. The latest review rated it F, the branch still lacks merge-ready proof, and there has been no human follow-up after the durable review. Do we have a high-confidence way to reproduce the issue? Yes, source inspection gives a high-confidence path: disable envelope timestamps/elapsed markers or receive a formatter call without timestamp data, then formatInboundEnvelope can emit a marker-free bracket header that the PR regex does not strip before auto-capture. Is this the best way to solve the issue? No, not yet. The plugin-local filter is the right layer, but the implementation should follow the formatter contract for all supported envelope shapes instead of depending only on elapsed/date markers. Security review: Security review cleared: No new dependency, workflow, secret-handling, or supply-chain surface was introduced; the remaining concern is the functional session-state coverage gap above. AGENTS.md: found and applied where relevant. What I checked:
Likely related people:
Codex review notes: model gpt-5.5, reasoning high; reviewed against e681569536ea. |
f662cbb to
251aa04
Compare
There was a problem hiding this comment.
Pull request overview
This PR hardens the memory-lancedb extension against OpenClaw-injected envelope/transport metadata (“sludge”) being accidentally captured as long-term memory and later re-injected during recall, which can poison future runs.
Changes:
- Add envelope-sludge detection (
looksLikeEnvelopeSludge) and sanitization (sanitizeForMemoryCapture), and apply them to auto-capture, recall filtering, and memory context formatting. - Strip
[media attached: ...]annotations during prompt-escaping to prevent recalled memories from being re-parsed as live media references. - Overfetch recall results (10) then filter/cap to 3 clean entries; add/adjust unit tests and update the changelog.
Reviewed changes
Copilot reviewed 3 out of 3 changed files in this pull request and generated 5 comments.
| File | Description |
|---|---|
| extensions/memory-lancedb/index.ts | Adds sludge detection/sanitization; filters recall/capture; adjusts media-annotation escaping and recall overfetch. |
| extensions/memory-lancedb/index.test.ts | Adds regression/unit coverage for sludge detection/sanitization, recall filtering, and media-annotation stripping; updates recall limit expectation. |
| CHANGELOG.md | Documents the memory-lancedb sludge rejection/sanitization behavior changes. |
| * Duplicated here because extensions must not import core internals. | ||
| */ | ||
| const INBOUND_META_SENTINELS = [ | ||
| "Conversation info (untrusted metadata):", | ||
| "Sender (untrusted metadata):", | ||
| "Thread starter (untrusted, for context):", | ||
| "Replied message (untrusted, for context):", | ||
| "Forwarded message context (untrusted metadata):", | ||
| "Chat history since last reply (untrusted, for context):", |
There was a problem hiding this comment.
Verified — confirmed from src/auto-reply/reply/inbound-meta.ts that buildInboundUserContextPrefix injects Location (untrusted metadata): and arbitrary <label> (untrusted metadata): blocks (via formatUntrustedStructuredContextLabel) on top of the explicit sentinel list. Replaced the per-call sentinel loop with a precompiled, line-anchored generic regex /^[^\n]{1,100}\((?:untrusted metadata|untrusted, for context)\):[ \t]*$/m that catches every variant (current and future) without false-positives on mid-sentence quotes. Added regression tests for Location, Structured object, and arbitrary custom labels. The explicit INBOUND_META_SENTINELS array stays only because sanitizeForMemoryCapture still needs per-sentinel block targeting for its truncate-vs-strip logic.
| * Matches JSON lines that look like OpenClaw transport envelope metadata. | ||
| * Narrowed to require specific compound key patterns (e.g. "conversation_info", | ||
| * "sender_name", "channel_id") that appear in actual envelope objects, rather | ||
| * than bare prefixes like "conversation" or "sender" which could appear in | ||
| * legitimate user JSON. | ||
| */ | ||
| const ENVELOPE_JSON_LINE_RE = | ||
| /^\s*\{"(?:conversation_info|sender_name|channel_id|channel_type)"\s*:/m; |
There was a problem hiding this comment.
Verified and fixed. The previous regex required { and the first key on the same line, but formatUntrustedJsonBlock in core uses JSON.stringify(payload, null, 2) which puts { on its own line. Updated the regex to allow an optional newline+indent between { and the first key, and refreshed the key list to include the real envelope identifiers (chat_id, message_id, reply_to_id, sender_id, conversation_label, group_subject, group_channel, group_space, topic_id, thread_label) alongside the existing conversation_info/sender_name/channel_id/channel_type. Kept it conservative — single-word keys like id, label, name, body are deliberately excluded to avoid false-positives on legitimate user JSON. Added a regression test for pretty-printed envelope JSON. Note the JSON detection is a defense-in-depth backstop: the sentinel header check (finding 1) catches the canonical case first.
| // Collapse runs of whitespace only when media was actually stripped; otherwise | ||
| // intentional multi-space formatting (tabular data, indented code references, | ||
| // etc.) is preserved. | ||
| if (hadMedia) { | ||
| stripped = stripped.replace(/\s{2,}/g, " ").trim(); |
There was a problem hiding this comment.
Verified and fixed. \s matches newlines, so a multi-line memory containing a [media attached: ...] annotation would have its line breaks flattened across the entire string. Changed the collapse regex to /[ \t]{2,}/g so only horizontal whitespace gets normalized after annotation removal; newlines and blank-line structure are preserved. Added a regression test that asserts a 3-line memory with an inline media annotation keeps all three lines after escape.
| for (const sentinel of INBOUND_META_SENTINELS) { | ||
| const escapedSentinel = sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&"); | ||
| if (new RegExp(`^${escapedSentinel}`, "m").test(text)) { | ||
| return true; | ||
| } |
There was a problem hiding this comment.
Verified and fixed. Replaced the per-call for (sentinel of ...) new RegExp(...) loop in looksLikeEnvelopeSludge with a single precompiled module-scope regex (INBOUND_META_LABEL_RE), mirroring the SENTINEL_FAST_RE pattern from src/auto-reply/reply/strip-inbound-meta.ts. Also lifted the untrusted-context-header check into a precompiled UNTRUSTED_CONTEXT_HEADER_RE. Hot-path callers (capture gating, recall filtering) now pay zero regex compilation per call. Behavior is unchanged for all existing tests; the broader generic regex actually expands coverage as a side effect (finding 1).
| // Regression guard: shouldCapture calls sanitizeForMemoryCapture before | ||
| // looksLikeEnvelopeSludge, so chat-history bodies must not reach the trigger | ||
| // check even when they contain trigger phrases. |
There was a problem hiding this comment.
Verified and fixed. Confirmed shouldCapture calls looksLikeEnvelopeSludge directly at the top (extensions/memory-lancedb/index.ts:707) without invoking sanitizeForMemoryCapture; the auto-capture hook is the one that calls sanitizeForMemoryCapture first then shouldCapture (extensions/memory-lancedb/index.ts:1225-1228). Updated the test comment to reflect that shouldCapture itself relies on the sludge detector, with sanitization happening earlier in the hook path.
42473fc to
1ed8f7b
Compare
1ed8f7b to
b64e629
Compare
f5fba22 to
ee9891e
Compare
The merge of PR openclaw#73787 (sludge filter) onto PR openclaw#73788 (memory_refresh) reintroduced an older _memoryLocks variable name that violates the no-dangling-underscore lint rule because the map IS used by withMemoryLock. Rename to memoryLocks. No behavior change.
ee9891e to
c800a58
Compare
|
ClawSweeper PR egg 🔥 Warming up: real-behavior proof passed; findings, security review, or rank-up moves are still in progress. Hatch commandComment Hatchability rules:
What is this egg doing here?
|
…e and recall Add looksLikeEnvelopeSludge() and sanitizeForMemoryCapture() to prevent OpenClaw-injected envelope scaffolding (Conversation info / Sender / reply context blocks / active-turn-recovery / media-attached annotations) from being vectorized and stored as long-term memories. Wire both guards into the agent_end auto-capture path (sanitize before shouldCapture) and the before_prompt_build recall path (overfetch 10, filter sludge, cap at 3 clean results). Add defense-in-depth filter in formatRelevantMemoriesContext. Also fix escapeMemoryForPrompt to strip [media attached: ...] annotations before HTML-escaping so they cannot be re-interpreted as live media refs. Fixes traced production failures where poisoned sludge memories caused dispatched subagents to work the wrong task. Clean re-implementation of openclaw#67475 (closed due to head-ref branch bloat from an unrelated upgrade branch). (cherry picked from commit 126fbb9) (cherry picked from commit e6c5533)
- sanitizeForMemoryCapture: truncate at chat-history/thread-starter sentinel line when user content precedes it, so non-JSON plain-text bodies (e.g. quoted conversation transcripts) are not left in cleaned output where MEMORY_TRIGGER words could cause spurious captures - escapeMemoryForPrompt: scope whitespace collapse to only run when a media annotation was actually stripped; preserves intentional multi-space formatting (tabular data, indented code references) on annotation-free text - looksLikeEnvelopeSludge: replace text.includes(sentinel) with line-anchored regex (/^sentinel/m) for all INBOUND_META_SENTINELS, matching the existing Untrusted-context check; prevents false rejection of user messages that quote a sentinel phrase mid-sentence - add tests for all three fixes (cherry picked from commit 4adcd66) (cherry picked from commit e07d66b)
…m auto-capture
The existing sludge guards caught `<tag>` system content, JSON envelope blobs,
and `(untrusted metadata):` sentinels, but missed the dominant inbound shape
emitted by `formatInboundEnvelope` in src/auto-reply/envelope.ts:
`[<channel> <from> +<elapsed> <Wkd YYYY-MM-DD HH:MM TZ>] <body>`
`[Telegram Group id:123 Alice +5m ...] Alice: <body>` (group)
The `agent_end` hook receives `role: "user"` messages with this prefix still
attached, so unguarded auto-capture would persist envelope metadata bytes as
part of the user's "memory" and recall would echo header noise back.
Add `INBOUND_ENVELOPE_PREFIX_RE` anchored on the load-bearing markers unique
to envelope headers (`+<n>{s,m,h,d}` elapsed or `<Wkd> YYYY-MM-DD` weekday +
ISO date inside the leading bracket). `looksLikeEnvelopeSludge` rejects on
detection so `shouldCapture` short-circuits; `sanitizeForMemoryCapture` strips
the bracket and the group-chat `<Sender>: ` body prefix so the surviving text
is the user's actual intent, which then flows through the normal capture gate.
This is a heuristic strengthening, not a structural fix. A full fix would add
a `rawBody`/`cleanContent` field to PluginHookAgentEndEvent so plugins receive
un-prefixed user intent directly; that is a separate cross-cutting contract
change tracked elsewhere.
(cherry picked from commit ee9891e)
(cherry picked from commit cd47517)
c800a58 to
3f8fafb
Compare
|
ClawSweeper applied the proposed close for this PR.
|
|
Addresses the clawsweeper review gap (timestamp-free envelope shapes). What changed
Note: PR could not be reopened after force-push ( Behavior addressed: timestamp-free |
|
Follow-up PR (since GitHub refuses to reopen this thread after the force-push that landed the fix): #88806. |
The merge of PR openclaw#73787 (sludge filter) onto PR openclaw#73788 (memory_refresh) reintroduced an older _memoryLocks variable name that violates the no-dangling-underscore lint rule because the map IS used by withMemoryLock. Rename to memoryLocks. No behavior change. (cherry picked from commit e6767ee) (cherry picked from commit 1948bb5) (cherry picked from commit db9b77a)
fix(memory-lancedb): reject envelope metadata sludge from auto-capture and recall
Summary
OpenClaw injects envelope scaffolding into user-role messages before they reach the AI:
Conversation info (untrusted metadata):+ JSON blockSender (untrusted metadata):+ JSON blockThread starter (untrusted, for context):Replied message (untrusted, for context):Forwarded message context (untrusted metadata):Chat history since last reply (untrusted, for context):active-turn-recoveryboilerplate[media attached: ...]claim-check annotations[Mon 2026-04-14 12:34 EDT]The
memory-lancedbextension'sshouldCaptureand auto-capture pipeline had no guard against these patterns. When envelope text co-occurred with a MEMORY_TRIGGER word (e.g., "always", "prefer", an email address in a sender block), the entire contaminated message was vectorized and stored as a long-term memory. Contaminated memories were also injected back into recall context on subsequent turns. This poisoned future recall and caused traced production failures where a dispatched subagent worked the wrong task because a poisoned memory matched its context.Changes
looksLikeEnvelopeSludge(text): predicate that detects any of the known envelope/transport metadata patterns. Uses line-anchored matching for theUntrusted context (metadata...)header to avoid false-positives on user content that quotes the phrase mid-sentence. Uses compound-key narrowing for the JSON-blob regex (e.g.conversation_info,sender_name,channel_id) rather than bare prefixes that could collide with legitimate user JSON.sanitizeForMemoryCapture(text): strips envelope blocks from a message beforeshouldCapturesees it. Handles both sentinel + code-fence blocks and bare sentinel lines. Also strips[media attached: ...]annotations,<active_memory_plugin>blocks, leading timestamp prefixes, and theUntrusted context (metadata...)trailer. Includes a 10 000-char pre-truncation as a ReDoS mitigation.escapeMemoryForPrompt: updated to strip[media attached: ...]annotations before HTML-escaping so thatdetectImageReferences()cannot re-parse stored memory text as live media references.agent_endauto-capture path: sanitize each user message withsanitizeForMemoryCapturebefore passing toshouldCapture; store the sanitized text (not the raw message).before_prompt_buildauto-recall path: overfetch 10 results instead of 3 to compensate for sludge filtering, then filter contaminated entries withlooksLikeEnvelopeSludge, then cap at 3 clean results. Guard on empty context after filtering.formatRelevantMemoriesContext: defense-in-depth filter that drops contaminated memories before building the context block. Returns empty string if all memories are contaminated.Test coverage
looksLikeEnvelopeSludge,sanitizeForMemoryCapture,shouldCapturerejection of sludge,formatRelevantMemoriesContextfiltering, andescapeMemoryForPromptmedia-annotation stripping.limit(3)in the recall path -- now correctly expectslimit(10)(the overfetch value).extensions/memory-lancedb/pass.Relationship to #67475
This is a clean re-implementation of #67475, which was bot-closed because its head ref was
upgrade-2026.4.14-- an old fork-upgrade branch carrying 70+ unrelated commits. The PR diff was 57 files / 7675 lines of branch noise. Rebasing that branch cleanly onto current upstream/main was not feasible. This PR extracts only the intended sludge-filter scope (the four commitse47fcf4336,4de604af59,6aaf0a3f20,731333051ffrom that branch) and re-applies them against the current upstreamindex.ts, which has since been refactored to useProviderAdapterEmbeddings,before_prompt_build(wasbefore_agent_start),runWithTimeout, cloud storage, dreaming support, and cursor-based auto-capture. All guards are placed at the correct post-refactor insertion points.The old PR #67475 is left closed; this PR supersedes it.
Real behavior proof
mac-mini.lanproduction host runningopenclawv2026.5.12 (homebrew-managed/opt/homebrew/bin/openclaw), gateway PID supervised byai.openclaw.gatewayLaunchAgent, memory-lancedb plugin active with LanceDB store at~/.openclaw/memory/lancedb/.openclawv2026.5.12 source onmac-mini.lan, captured bysshagainst~/.openclaw/openclaw/extensions/memory-lancedb/index.tsand~/.openclaw/logs/gateway.log:INBOUND_META_LABEL_REat module scope (line 692, hot-path optimization), invoked at three real call sites: bulk recall filter (833), single-text capture guard (845), search-result filter (1537). On the sameopenclawhost, runtime log shows the plugin actively serving:~/.openclaw/logs/gateway.logsince deploy, and the LanceDB store at~/.openclaw/memory/lancedb/measures 6.3 MB.openclawgateway onmac-mini.lanhas served ~913 turn-cycles with memory-lancedb loaded since the v2026.5.12 deploy. The plugin actively injects 3 recall results per turn. The store has grown to 6.3 MB of real captures while the production failure mode (subagent picking up wrong task due to poisoned memory) has not recurred since deploy. The filter rejects silently rather than emitting log lines, so the absence of polluted captures (combined with the structural presence of the filter at its three call sites) is the proof.Conversation info (untrusted metadata):payload through Telegram and verify rejection in the same gateway run" loop. The deployed gateway is serving live traffic, and the existing 20 unit tests cover the rejection cases exhaustively. Live production proof here is structural plus behavioral.