Skip to content

fix(memory-lancedb): reject envelope metadata sludge from auto-capture and recall - #73787

Closed
amittell wants to merge 4 commits into
openclaw:mainfrom
amittell:fix/memory-lancedb-envelope-sludge
Closed

amittell wants to merge 4 commits into
openclaw:mainfrom
amittell:fix/memory-lancedb-envelope-sludge

Conversation

@amittell

@amittell amittell commented Apr 28, 2026 •

Copy link
Copy Markdown
Contributor

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 block
  • Sender (untrusted metadata): + JSON block
  • Thread starter (untrusted, for context):
  • Replied message (untrusted, for context):
  • Forwarded message context (untrusted metadata):
  • Chat history since last reply (untrusted, for context):
  • active-turn-recovery boilerplate
  • [media attached: ...] claim-check annotations
  • Leading timestamp prefixes like [Mon 2026-04-14 12:34 EDT]

The memory-lancedb extension's shouldCapture and 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 the Untrusted 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 before shouldCapture sees it. Handles both sentinel + code-fence blocks and bare sentinel lines. Also strips [media attached: ...] annotations, <active_memory_plugin> blocks, leading timestamp prefixes, and the Untrusted 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 that detectImageReferences() cannot re-parse stored memory text as live media references.

  • agent_end auto-capture path: sanitize each user message with sanitizeForMemoryCapture before passing to shouldCapture; store the sanitized text (not the raw message).

  • before_prompt_build auto-recall path: overfetch 10 results instead of 3 to compensate for sludge filtering, then filter contaminated entries with looksLikeEnvelopeSludge, 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

  • 20 new unit tests covering looksLikeEnvelopeSludge, sanitizeForMemoryCapture, shouldCapture rejection of sludge, formatRelevantMemoriesContext filtering, and escapeMemoryForPrompt media-annotation stripping.
  • Updated one existing test that asserted limit(3) in the recall path -- now correctly expects limit(10) (the overfetch value).
  • All 78 tests in 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 commits e47fcf4336, 4de604af59, 6aaf0a3f20, 731333051f from that branch) and re-applies them against the current upstream index.ts, which has since been refactored to use ProviderAdapterEmbeddings, before_prompt_build (was before_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

  • Behavior or issue addressed: With the patch deployed, the memory-lancedb auto-capture and recall paths reject envelope-metadata sludge so contaminated user messages are never persisted as long-term memories or re-injected into recall context. Pre-fix, traced production failures where a dispatched subagent worked the wrong task because a poisoned memory matched its context.
  • Real environment tested: mac-mini.lan production host running openclaw v2026.5.12 (homebrew-managed /opt/homebrew/bin/openclaw), gateway PID supervised by ai.openclaw.gateway LaunchAgent, memory-lancedb plugin active with LanceDB store at ~/.openclaw/memory/lancedb/.
  • Exact steps or command run after this patch:
    ssh [email protected] 'grep -nE "looksLikeEnvelopeSludge|INBOUND_META_LABEL_RE" /Users/alexm/.openclaw/openclaw/extensions/memory-lancedb/index.ts'
    ssh [email protected] 'grep -c "memory-lancedb: injecting" ~/.openclaw/logs/gateway.log'
    ssh [email protected] 'du -sh ~/.openclaw/memory/lancedb/'
  • Evidence after fix: Deployed openclaw v2026.5.12 source on mac-mini.lan, captured by ssh against ~/.openclaw/openclaw/extensions/memory-lancedb/index.ts and ~/.openclaw/logs/gateway.log:
    692:const INBOUND_META_LABEL_RE =
    712:export function looksLikeEnvelopeSludge(text: string): boolean {
    720:  if (INBOUND_META_LABEL_RE.test(text)) {
    833:  const clean = memories.filter((m) => !looksLikeEnvelopeSludge(m.text));
    845:  if (looksLikeEnvelopeSludge(text)) {
    1537:          .filter((r) => !looksLikeEnvelopeSludge(r.entry.text))
    
    Filter loaded at line 712 with precompiled INBOUND_META_LABEL_RE at 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 same openclaw host, runtime log shows the plugin actively serving:
    [plugins] memory-lancedb: injecting 3 memories into context
    
    with 913 such injection events in ~/.openclaw/logs/gateway.log since deploy, and the LanceDB store at ~/.openclaw/memory/lancedb/ measures 6.3 MB.
  • Observed result after fix: The openclaw gateway on mac-mini.lan has 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.
  • What was not tested: A synthetic "inject sentinel 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.

@aisle-research-bot

aisle-research-bot Bot commented Apr 28, 2026 •

Copy link
Copy Markdown

🔒 Aisle Security Analysis

We found 1 potential security issue(s) in this PR:

# Severity Title
1 🟡 Medium Envelope metadata may bypass sludge detection due to line-start anchoring without leading-whitespace handling
1. 🟡 Envelope metadata may bypass sludge detection due to line-start anchoring without leading-whitespace handling
Property Value
Severity Medium
CWE CWE-200
Location extensions/memory-lancedb/index.ts:523-616

Description

looksLikeEnvelopeSludge() and parts of sanitizeForMemoryCapture() only recognize inbound-metadata sentinel headers when they appear exactly at the start of a line (e.g. ^Sender (untrusted metadata):).

However, the canonical stripping logic in src/auto-reply/reply/strip-inbound-meta.ts treats sentinel lines as line.trim() === sentinel, meaning the real injected format tolerates leading indentation/whitespace.

Impact when the metadata header is indented (e.g. " Sender (untrusted metadata):"):

  • looksLikeEnvelopeSludge() will return false, so shouldCapture() may allow capture.
  • In sanitizeForMemoryCapture(), the code-fenced JSON block removal can still match, but plain-text sentinel headers/bodies (no ```json fence) rely on ^${sentinel} and will not be truncated/removed when indented.
  • Result: transport/envelope metadata (conversation identifiers, sender labels, channel IDs, etc.) can be persisted into long-term memory and later surfaced during recall.

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");

Recommendation

Accept leading whitespace before sentinels, to match the canonical stripping behavior (line.trim()).

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 blockRe to line start with optional whitespace for clarity/safety:

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. ' Sender (untrusted metadata):').


Analyzed PR: #73787 at commit f662cbb

Last updated on: 2026-04-29T01:06:36Z

@greptile-apps

greptile-apps Bot commented Apr 28, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds envelope-sludge filtering to the memory-lancedb extension: a detection predicate (looksLikeEnvelopeSludge), a sanitizer (sanitizeForMemoryCapture), defense-in-depth guards in shouldCapture and formatRelevantMemoriesContext, overfetch-then-filter in the recall path, and sanitization before storage in the capture path. The approach is well-structured and the 20 new tests cover the main cases.

  • Non-JSON sentinel bodies (e.g., raw chat history following "Chat history since last reply (untrusted, for context):") are not stripped by sanitizeForMemoryCapture — only the sentinel header line is removed. Content from previous turns that triggers a MEMORY_TRIGGERS word can still be vectorized and stored.
  • escapeMemoryForPrompt now unconditionally collapses multi-space runs, which may silently reformat memories with intentional whitespace even when no media annotation was present.
  • INBOUND_META_SENTINELS membership is tested with text.includes() (not line-anchored), unlike the Untrusted context check, creating a minor false-positive risk for user messages that quote a sentinel phrase inline.

Confidence Score: 4/5

Safe 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 AI
This 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

Comment thread extensions/memory-lancedb/index.ts Resolved
Comment thread extensions/memory-lancedb/index.ts Resolved
Comment thread extensions/memory-lancedb/index.ts Resolved
@amittell

Copy link
Copy Markdown
Contributor Author

Addressed all three P2 review comments in f662cbbafa.

Comment 1 (PRRT_kwDOQb6kR85-QK80) — non-JSON sentinel bodies not stripped

sanitizeForMemoryCapture now truncates at the sentinel line whenever meaningful user content precedes it, instead of just removing the header line. For "Chat history since last reply" and "Thread starter" blocks (which carry plain-text transcripts rather than JSON fences), any content after the sentinel is now dropped entirely. Sentinels that appear at the very beginning still strip just the header line so user text following them is preserved. Added tests covering chat-history and thread-starter sludge containing MEMORY_TRIGGER words.

Comment 2 (PRRT_kwDOQb6kR85-QK-K) — whitespace collapse unconditional in escapeMemoryForPrompt

The .replace(/\s{2,}/g, " ").trim() step is now guarded by MEDIA_ATTACHED_PATTERN_TEST.test(text) and only runs when a media annotation was actually present and stripped. Text without annotations (tabular data, indented code references, etc.) reaches the model with its original whitespace intact. Added a test asserting multi-space formatting is preserved on annotation-free input.

Comment 3 (PRRT_kwDOQb6kR85-QK_d) — INBOUND_META_SENTINELS membership not line-anchored

text.includes(sentinel) replaced with /^<escaped-sentinel>/m for every sentinel in INBOUND_META_SENTINELS, consistent with the existing /^Untrusted context \(metadata/m check. A user message like "I saw 'Sender (untrusted metadata):' in the API docs" is now correctly passed through rather than silently dropped. Added tests for both looksLikeEnvelopeSludge (returns false) and shouldCapture (returns true when a MEMORY_TRIGGER is present).

84 tests pass (pnpm test extensions/memory-lancedb). pnpm tsgo and pnpm build clean.

@clawsweeper

clawsweeper Bot commented Apr 29, 2026 •

Copy link
Copy Markdown
Contributor

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 details

Best 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:

  • stale F-rated PR: PR was opened 2026-04-28T20:15:43Z, is older than 30 days, and the latest review rated it F.
  • proof blocker: real behavior proof is insufficient and proof tier is D, so this branch is not merge-ready without contributor follow-up.
  • no human follow-up: live comments and timeline hydrated by apply contain no non-automation activity after the ClawSweeper review.

Likely related people:

  • Mert Başar: Current-main blame in this shallow checkout attributes the central memory-lancedb capture/recall helpers and envelope formatter to the grafted main commit authored by this person. (role: recent area contributor; confidence: low; commits: 0ff5fe3a80ce; files: extensions/memory-lancedb/index.ts, src/auto-reply/envelope.ts)

Codex review notes: model gpt-5.5, reasoning high; reviewed against e681569536ea.

@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from f662cbb to 251aa04 Compare May 2, 2026 18:21
Copilot AI review requested due to automatic review settings May 2, 2026 18:21

Copilot AI left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +544 to +552
* 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):",

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +558 to +565
* 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;

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +528 to +532
// 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();

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +579 to +583
for (const sentinel of INBOUND_META_SENTINELS) {
const escapedSentinel = sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
if (new RegExp(`^${escapedSentinel}`, "m").test(text)) {
return true;
}

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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).

Comment thread extensions/memory-lancedb/index.test.ts Outdated
Comment on lines +2417 to +2419
// Regression guard: shouldCapture calls sanitizeForMemoryCapture before
// looksLikeEnvelopeSludge, so chat-history bodies must not reach the trigger
// check even when they contain trigger phrases.

Copy link
Copy Markdown
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

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.

@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from 42473fc to 1ed8f7b Compare May 3, 2026 04:00
@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from 1ed8f7b to b64e629 Compare May 17, 2026 00:39
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. label May 17, 2026
@clawsweeper clawsweeper Bot added P1 High-priority user-facing bug, regression, or broken workflow. impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. labels May 17, 2026
@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from f5fba22 to ee9891e Compare May 18, 2026 02:04
@clawsweeper clawsweeper Bot added the rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. label May 18, 2026
@openclaw-barnacle openclaw-barnacle Bot added proof: supplied External PR includes structured after-fix real behavior proof. and removed triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup. labels May 18, 2026
@clawsweeper clawsweeper Bot added rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. labels May 18, 2026
amittell added a commit to amittell/openclaw that referenced this pull request May 20, 2026
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.
@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from ee9891e to c800a58 Compare May 23, 2026 22:33
@clawsweeper clawsweeper Bot added the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 23, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. and removed rating: 🌊 off-meta tidepool PR readiness rating does not apply to this item. impact:session-state Session, memory, transcript, context, or agent state can drift or corrupt. impact:security Security boundary, credential, authz, sandbox, or sensitive-data risk. labels May 23, 2026
@clawsweeper

clawsweeper Bot commented May 23, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🔥 Warming up: real-behavior proof passed; findings, security review, or rank-up moves are still in progress.

Hatch command

Comment @clawsweeper hatch when this PR is hatchable.

Hatchability rules:

  • Merged PRs are hatchable.
  • Open PRs are hatchable when they are status: 👀 ready for maintainer look, status: 🚀 automerge armed, or labeled clawsweeper:automerge.
  • Closed unmerged PRs are hatchable only when one of those hatchable labels is still present in the durable record.
What is this egg doing here?
  • Eggs appear after the PR passes real-behavior proof. It is here for vibes, not verdicts: it does not change labels, ratings, merge decisions, or automation.
  • The shell reacts to review momentum: open follow-up work warms it up, re-review makes it wobble, and a clean final review lets it hatch.
  • Hatchability usually comes from sufficient real-behavior proof, no blocking P0/P1/P2 findings, no security attention needed, and clean correctness. A merged PR is already final, so merge makes the egg hatchable independently.
  • The hatch is seeded from this repository and PR number, so the same PR keeps the same creature; the reviewed head SHA can only change safe visual details.
  • Rarity is just collectible sparkle: 🥚 common, 🌱 uncommon, 💎 rare, ✨ glimmer, and 🌈 legendary.

amittell added 4 commits May 31, 2026 16:23
…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)
…ulti-line memory formatting

(cherry picked from commit 1b504e2)
(cherry picked from commit 6526ef9)
…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)
@amittell
amittell force-pushed the fix/memory-lancedb-envelope-sludge branch from c800a58 to 3f8fafb Compare May 31, 2026 20:27
@openclaw-barnacle openclaw-barnacle Bot removed the proof: sufficient ClawSweeper judged the real behavior proof convincing. label May 31, 2026
@clawsweeper clawsweeper Bot added status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels May 31, 2026
@clawsweeper

clawsweeper Bot commented May 31, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

@clawsweeper clawsweeper Bot closed this May 31, 2026
@amittell

Copy link
Copy Markdown
Contributor Author

Addresses the clawsweeper review gap (timestamp-free envelope shapes).

What changed

  • looksLikeEnvelopeSludge now matches the marker-free [<channel-id> <from-label>] body shape using the canonical bundled channel-id registry, not just elapsed/date markers.
  • Channel-id list is read from src/plugin-sdk/chat-channel-ids.ts, which re-exports CHAT_CHANNEL_ORDER from src/channels/ids.ts (the same constant the formatter's bundled channel metadata is derived from), so the detector and formatter cannot drift.
  • sanitizeForMemoryCapture also strips the marker-free prefix in the same pass so the auto-capture flow surfaces a clean body.
  • New tests cover: marker-free envelope ([telegram alice] hello world), marker-present envelope (unchanged), user [note] ... prose, markdown links [text](url), multi-line envelope-prefixed messages, case-insensitive channel match, and bare [channel] with no from label.

Note: PR could not be reopened after force-push (mutation reopenPullRequest -> UNPROCESSABLE from GitHub once the head ref is rewritten). A follow-up PR will be opened against the same branch with the rebased SHA; this thread is preserved for the clawsweeper history.

Behavior addressed: timestamp-free formatInboundEnvelope outputs were not being stripped before auto-capture
Real environment tested: vitest against extensions/memory-lancedb/index.test.ts
Exact steps or command run after this patch: node scripts/run-vitest.mjs run extensions/memory-lancedb
Evidence after fix: Test Files 2 passed (2) / Tests 108 passed (108) (was 101 before the new cases)
Observed result after fix: filtered envelopes match the formatter contract for all supported envelope shapes, including marker-free [<channel-id> <from>] body
What was not tested: live Telegram capture round-trip

@amittell

Copy link
Copy Markdown
Contributor Author

Follow-up PR (since GitHub refuses to reopen this thread after the force-push that landed the fix): #88806.

amittell added a commit to amittell/openclaw that referenced this pull request Aug 10, 2026
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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

extensions: memory-lancedb Extension: memory-lancedb merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P1 High-priority user-facing bug, regression, or broken workflow. proof: supplied External PR includes structured after-fix real behavior proof. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: L status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants