Skip to content

fix(memory-lancedb): reject inbound envelope metadata during capture and recall - #67475

Closed
amittell wants to merge 66 commits into
openclaw:mainfrom
amittell:upgrade-2026.4.14
Closed

amittell wants to merge 66 commits into
openclaw:mainfrom
amittell:upgrade-2026.4.14

Conversation

@amittell

Copy link
Copy Markdown
Contributor

Summary

Fix memory-lancedb prompt contamination by preventing OpenClaw transport/envelope metadata from being captured as long-term memory and later recalled into prompts.

Root cause

memory-lancedb auto-capture was storing raw user message text from agent_end, including OpenClaw-injected inbound scaffolding such as:

  • Conversation info (untrusted metadata)
  • Sender (untrusted metadata)
  • Replied message (untrusted, for context)
  • active-turn-recovery boilerplate
  • [media attached: ...] annotations

Those contaminated entries could later be recalled by before_agent_start and prepended into new prompts, which in a real traced failure poisoned a dispatched subagent run and caused it to work the wrong task.

What changed

  • add looksLikeEnvelopeSludge(...) to detect transport/meta contamination
  • add sanitizeForMemoryCapture(...) to strip inbound metadata, timestamp prefixes, media annotations, and plugin scaffolding before capture
  • reject contaminated candidates in shouldCapture(...)
  • filter contaminated recall candidates before injecting prompt context
  • add a defense-in-depth filter in formatRelevantMemoriesContext(...)

Why this is safe

This is narrowly scoped to transport/envelope contamination. Legitimate preference/fact/entity capture and recall paths still work, but memories that look like OpenClaw metadata scaffolding are now excluded.

Tests

Targeted extension-memory tests pass locally, including new regression coverage for:

  • rejecting inbound envelope sludge during capture
  • stripping contaminated content during sanitization
  • suppressing contaminated memories during recall/context formatting
  • preserving clean memories

@amittell
amittell requested a review from a team as a code owner April 16, 2026 01:57
@aisle-research-bot

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

Copy link
Copy Markdown

🔒 Aisle Security Analysis

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

# Severity Title
1 🟠 High Unsanitized memory_store tool allows persistence of envelope metadata and prompt-injection payloads in LanceDB memory
2 🟡 Medium Memory capture/recall evasion via substring-based envelope sludge detection
1. 🟠 Unsanitized memory_store tool allows persistence of envelope metadata and prompt-injection payloads in LanceDB memory
Property Value
Severity High
CWE CWE-200
Location extensions/memory-lancedb/index.ts:534-570

Description

The memory_store tool writes attacker-controlled text directly into long-term storage without applying the new envelope-metadata sanitization/filters.

  • Input: params.text comes from a tool call (LLM-controlled and potentially user-influenced).
  • Missing defenses: Unlike the auto-capture path, this tool does not call sanitizeForMemoryCapture() or shouldCapture() (which now rejects looksLikeEnvelopeSludge()), nor does it strip [media attached: ...] annotations.
  • Impact: An attacker can persist:
    • transport/envelope metadata (PII like names/channel IDs, local file paths in media annotations)
    • prompt-injection strings or tool-invocation bait
      which can later be surfaced via memory_recall tool or via auto-recall into model context (if similarity matches), enabling memory poisoning/persistent prompt injection and privacy leakage.

Vulnerable code:

const vector = await embeddings.embed(text);
...
const entry = await db.store({
  text,
  vector,
  importance,
  category,
});

Recommendation

Apply the same sanitization and capture policy used by auto-capture before embedding/storage, and reject contaminated inputs.

const sanitized = sanitizeForMemoryCapture(text);
if (!sanitized || !shouldCapture(sanitized, { maxChars: cfg.captureMaxChars })) {
  return {
    content: [{ type: "text", text: "Refusing to store unsafe/invalid memory content." }],
    details: { action: "rejected" },
  };
}

const vector = await embeddings.embed(sanitized);
...
await db.store({ text: sanitized, vector, importance, category });

Also consider escaping/stripping [media attached: ...] and envelope sentinels on recall tool output (or filtering results with looksLikeEnvelopeSludge) to avoid reintroducing contaminated content to the model.

2. 🟡 Memory capture/recall evasion via substring-based envelope sludge detection
Property Value
Severity Medium
CWE CWE-840
Location extensions/memory-lancedb/index.ts:287-397

Description

looksLikeEnvelopeSludge() treats the presence of certain sentinel phrases as contamination anywhere in the text, and shouldCapture() rejects any text that matches this heuristic.

This allows a remote user to intentionally include one of the sentinel substrings (e.g., "Conversation info (untrusted metadata):", "Sender (untrusted metadata):") inside an otherwise normal message to:

  • prevent that message from being auto-captured into long-term memory (shouldCapture() returns false), and
  • cause any stored memory containing the substring to be filtered out during recall (formatRelevantMemoriesContext() drops it).

Because the sentinel check is implemented as text.includes(sentinel) (not anchored to line start / block structure), even quoting the phrase mid-sentence will trigger the rejection. This is a feature-level denial of service / evasion vector against memory retention and safety/audit memory recall.

Vulnerable code:

for (const sentinel of INBOUND_META_SENTINELS) {
  if (text.includes(sentinel)) {
    return true;
  }
}
...
if (looksLikeEnvelopeSludge(text)) {
  return false;
}

Recommendation

Tighten sludge detection so it only triggers on actual injected envelope blocks, not arbitrary user text.

Suggested approach:

  • Treat sentinels as sludge only when they appear at the start of a line (and ideally followed by a JSON fence/block), e.g. (^|\n)Sender \(untrusted metadata\):.
  • Alternatively, prefer sanitizing by stripping known metadata blocks (as sanitizeForMemoryCapture already does for start-of-line cases) and then base capture/reject decisions on the sanitized output, rather than rejecting if any sentinel substring remains.

Example tightening:

const SENTINEL_LINE_RE = new RegExp(
  `^(?:${INBOUND_META_SENTINELS.map(s => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")).join("|")})\\s*$`,
  "m",
);

export function looksLikeEnvelopeSludge(text: string): boolean {
  if (!text) return false;
  if (SENTINEL_LINE_RE.test(text)) return true;
  ​// keep other structured checks (anchored header, specific JSON line keys, etc.)
  ...
}

This preserves the protection against injected transport metadata while preventing user-controlled substring insertion from disabling memory capture/recall.


Analyzed PR: #67475 at commit 7c21e44

Last updated on: 2026-04-16T05:05:54Z

@openclaw-barnacle openclaw-barnacle Bot added channel: telegram Channel integration: telegram extensions: memory-lancedb Extension: memory-lancedb cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL labels Apr 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 1eaab7c169

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread src/agents/auth-profiles/store.ts Outdated
Comment on lines +144 to +147
const useLocalOnly = params.agentLocalOnly || params.agentDir !== undefined;
const store = useLocalOnly
? loadAgentLocalAuthProfileStore(params.agentDir)
: ensureAuthProfileStore(params.agentDir);

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.

P1 Badge Reload locked auth updates from disk, not runtime snapshots

updateAuthProfileStoreWithLock now falls back to ensureAuthProfileStore(...) when agentDir is omitted, which can return runtime snapshots instead of the current on-disk file. In a live gateway, lock-protected writers that call this without agentDir (for example usage/cooldown and profile-state updates) can overwrite newer credentials written by CLI or another process with stale in-memory data, because the updater no longer guarantees a fresh disk reload before saving.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Apr 16, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes a prompt-contamination bug in memory-lancedb where OpenClaw transport/envelope metadata (sender info, conversation headers, media annotations, active-turn-recovery boilerplate) was being captured as long-term memory and later recalled into new agent prompts. It adds looksLikeEnvelopeSludge, sanitizeForMemoryCapture, and defense-in-depth filtering at the capture, recall, and context-formatting layers. Separately, it adds <function> tag handling to stripToolCallXmlTags for Gemma-style tool calls and introduces subagent resume routing logic.

Confidence Score: 5/5

Safe to merge; all remaining findings are P2 style/performance suggestions that do not affect correctness.

The core contamination fix is correct and thoroughly tested with layered defense (shouldCapture, recall filter, formatRelevantMemoriesContext). Regex safety (separate test/replace MEDIA_ATTACHED_PATTERN variants), sentinel stripping ordering, and the dangling-function recovery path in assistant-visible-text.ts all check out. The one open concern (per-call RegExp construction) is a pure performance nit with no correctness impact.

No files require special attention.

Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/memory-lancedb/index.ts
Line: 354-365

Comment:
**Per-call RegExp construction in `sanitizeForMemoryCapture`**

12 `new RegExp(...)` objects are compiled on every call (2 per sentinel × 6 sentinels). Since `.replace()` with a global regex resets `lastIndex` to 0 when it finishes, these can be pre-compiled once at module level without any shared-state risk.

```ts
// After INBOUND_META_SENTINELS declaration:
const SENTINEL_REGEXES = INBOUND_META_SENTINELS.map((sentinel) => {
  const esc = sentinel.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
  return {
    blockRe: new RegExp(
      `${esc}\\s*\\n\\s*\`\`\`json\\s*\\n[\\s\\S]*?\\n\\s*\`\`\`\\s*\\n?`,
      "g",
    ),
    bareRe: new RegExp(`^${esc}.*$`, "gm"),
  };
});
```

Then in `sanitizeForMemoryCapture` replace the inner loop body with `cleaned = cleaned.replace(entry.blockRe, "").replace(entry.bareRe, "")` using the pre-compiled pairs. This avoids recompilation on every capture event.

How can I resolve this? If you propose a fix, please make it concise.

Reviews (2): Last reviewed commit: "telegram: add missing isSelfAuthoredTele..." | 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
amittell force-pushed the upgrade-2026.4.14 branch from 1eaab7c to edd13f3 Compare April 16, 2026 03:14
@openclaw-barnacle openclaw-barnacle Bot added size: M and removed channel: telegram Channel integration: telegram cli CLI command changes commands Command implementations agents Agent runtime and tooling size: XL labels Apr 16, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: edd13f33a3

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +695 to +699
const results = await db.search(vector, 3, 0.3);

if (results.length === 0) {
// Filter out contaminated memories before injection
const cleanResults = results.filter((r) => !looksLikeEnvelopeSludge(r.entry.text));
if (cleanResults.length === 0) {

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.

P1 Badge Overfetch recall candidates before sludge filtering

The auto-recall hook now requests only 3 nearest vectors and then removes contaminated entries, so if legacy sludge rows occupy those top 3 slots the plugin returns no memories even when clean matches exist just below them. This creates a recall regression for existing databases after this fix: before_agent_start can silently stop injecting relevant memories until users manually clean old rows. Fetch more than 3 results (or filter at query/storage level) and then take the first 3 clean entries.

Useful? React with 👍 / 👎.

Comment thread extensions/memory-lancedb/index.ts Outdated
Comment on lines +341 to +343
const untrustedIdx = cleaned.indexOf(UNTRUSTED_CONTEXT_HEADER_PREFIX);
if (untrustedIdx !== -1) {
cleaned = cleaned.slice(0, untrustedIdx);

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.

P2 Badge Restrict untrusted-context stripping to real header lines

sanitizeForMemoryCapture truncates at the first occurrence of the prefix "Untrusted context (metadata" anywhere in the text, not just at an injected metadata header boundary. If a user message legitimately quotes that phrase (for example while discussing OpenClaw prompt formatting), everything after it is discarded before capture, which can corrupt or drop valid memories. The strip condition should require an actual header line/signature rather than a substring match.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 6402c6b6cb

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment thread extensions/memory-lancedb/index.ts Outdated
}

// Check for "Untrusted context (metadata..." header
if (text.includes(UNTRUSTED_CONTEXT_HEADER_PREFIX)) {

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.

P2 Badge Match untrusted-context marker only as metadata header

The looksLikeEnvelopeSludge check now uses text.includes("Untrusted context (metadata"), which flags any mention of that phrase anywhere in user text. Because both shouldCapture(...) and recall filtering call this helper, a normal message like Remember that "Untrusted context (metadata)" appears in the docs will be dropped from capture (or removed during recall) even though it is not envelope metadata. This makes the mid-line false positive still present in the main capture/recall path.

Useful? React with 👍 / 👎.

Comment thread extensions/memory-lancedb/index.ts Outdated

const UNTRUSTED_CONTEXT_HEADER_PREFIX = "Untrusted context (metadata";
const ACTIVE_TURN_RECOVERY_RE = /active-turn-recovery/i;
const ENVELOPE_JSON_LINE_RE = /^\s*\{"(?:conversation|sender|channel)/m;

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.

P2 Badge Narrow envelope JSON detection to metadata-specific payloads

The new ENVELOPE_JSON_LINE_RE treats any line beginning with {"conversation..., {"sender..., or {"channel... as contamination, which is broader than injected transport metadata. In practice, user messages that paste JSON configs (for example, snippets containing a top-level channel key) are now rejected by shouldCapture, and previously stored memories with that shape are filtered from recall. This introduces false negatives for legitimate technical content.

Useful? React with 👍 / 👎.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 7c21e44e93

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".


// Check for any inbound metadata sentinel
for (const sentinel of INBOUND_META_SENTINELS) {
if (text.includes(sentinel)) {

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.

P2 Badge Anchor sentinel matching to metadata header lines

looksLikeEnvelopeSludge currently treats any occurrence of sentinel text as contamination via text.includes(...), so legitimate user content that quotes headers like "Sender (untrusted metadata):" is dropped from both capture (shouldCapture) and recall/context formatting. This is a behavioral regression introduced by the new sludge filter path; matching should be limited to actual header lines (for example, line-start/line-end patterns) so quoted documentation or debugging text can still be remembered.

Useful? React with 👍 / 👎.

Comment on lines +275 to +276
const ENVELOPE_JSON_LINE_RE =
/^\s*\{"(?:conversation_info|sender_name|channel_id|channel_type)"\s*:/m;

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.

P2 Badge Tighten envelope JSON filtering to avoid payload false positives

Even after narrowing from bare keys, ENVELOPE_JSON_LINE_RE still classifies any line beginning with {"channel_id":...} or {"channel_type":...} as envelope sludge, which will reject valid technical memories (for example, Slack/Discord webhook JSON snippets) during capture and suppress them during recall. The filter should require a stronger envelope signature than a single top-level key to avoid discarding legitimate JSON content.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added channel: bluebubbles Channel integration: bluebubbles channel: msteams Channel integration: msteams channel: telegram Channel integration: telegram channel: whatsapp-web Channel integration: whatsapp-web app: web-ui App: web-ui gateway Gateway runtime cli CLI command changes commands Command implementations agents Agent runtime and tooling labels Apr 16, 2026
@amittell
amittell force-pushed the upgrade-2026.4.14 branch from b31846b to 955eb20 Compare April 17, 2026 15:09
@openclaw-barnacle openclaw-barnacle Bot removed channel: bluebubbles Channel integration: bluebubbles channel: msteams Channel integration: msteams channel: whatsapp-web Channel integration: whatsapp-web app: web-ui App: web-ui labels Apr 17, 2026

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 955eb20944

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

entry.spawnMode === "session"
? "[Subagent Context] This subagent session is persistent and remains available for thread follow-up messages."
: undefined,
`[Subagent Task]: ${entry.task}`,

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.

P1 Badge Preserve steered task text for restart redispatch

This redispatch path reconstructs the child run prompt from entry.task, but steer-restart flows dispatch a new message while the run record can still carry the previous task text, so a gateway restart can re-run the wrong instruction when the run is classified as resumable-fresh. In practice this means a user-issued steer update can be lost and replaced by the old task after restart recovery; store/replay the actual dispatched message (or update the registry task on steer replacement) before building childTaskMessage.

Useful? React with 👍 / 👎.

Comment thread src/agents/subagent-registry-helpers.ts Outdated
// Before marking as errored, check whether the transcript shows the run already
// completed successfully. This recovers runs that finished before a gateway restart
// but whose completion wasn't flushed to the run registry.
if (typeof params.entry.endedAt !== "number" && hasCompletedTranscript(params.entry, params.storeCache)) {

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.

P2 Badge Make orphan transcript recovery reachable

The new completion-recovery branch is effectively unreachable in orphan reconciliation: this function is invoked only after a run is already classified as missing-session-entry or missing-session-id, but hasCompletedTranscript(...) bails out when sessionEntry.sessionId is absent, so the recovery path never fires for the cases it is intended to rescue. As a result, completed runs in these orphan states are still pruned as errors instead of being recovered from transcript tail data.

Useful? React with 👍 / 👎.

@openclaw-barnacle openclaw-barnacle Bot added the r: too-many-prs Auto-close: author has more than twenty active PRs. label Apr 21, 2026
@openclaw-barnacle

Copy link
Copy Markdown

Closing this PR because the author has more than 10 active PRs in this repo. Please reduce the active PR queue and reopen or resubmit once it is back under the limit. You can close your own PRs to get back under the limit.

@chatgpt-codex-connector chatgpt-codex-connector Bot 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.

💡 Codex Review

Here are some automated review suggestions for this pull request.

Reviewed commit: 3173886188

ℹ️ About Codex in GitHub

Codex has been enabled to automatically review pull requests in this repo. Reviews are triggered when you

  • Open a pull request for review
  • Mark a draft as ready
  • Comment "@codex review".

If Codex has suggestions, it will comment; otherwise it will react with 👍.

When you sign up for Codex through ChatGPT, Codex can also answer questions or update the PR, like "@codex address that feedback".

Comment on lines +616 to +617
const lastAssistantTurnMs = transcriptLastCompletedAssistantTurnTimestamp(transcriptPath);
if (lastAssistantTurnMs !== null) {

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.

P2 Badge Fall back when completed transcript lines lack timestamps

Resumability now hinges on transcriptLastCompletedAssistantTurnTimestamp(...) returning a timestamp; when the final assistant turn is complete but has no parseable timestamp, this path falls through to resumable-fresh and re-dispatches work that already finished before restart. A timestamp-less completed turn should still be treated as replayable (or at least not blindly redispatched), otherwise restart recovery can duplicate side effects for historical/heterogeneous transcript formats.

Useful? React with 👍 / 👎.

@amittell

Copy link
Copy Markdown
Contributor Author

This has been superseded by a clean re-implementation: #73787

#67475 was closed because the head ref (upgrade-2026.4.14) was an old fork-upgrade branch carrying 70+ unrelated commits, making the diff 57 files / 7675 lines of branch noise. The intended scope — the sludge filter for memory-lancedb — was only 4 commits on that branch.

#73787 extracts exactly those 4 commits and re-applies the guards at the correct insertion points in the current upstream index.ts, which has been refactored significantly (ProviderAdapterEmbeddings, before_prompt_build, runWithTimeout, cloud storage, dreaming, cursor-based auto-capture). All 78 tests pass on the new branch. Please review #73787 instead.

amittell added a commit to amittell/openclaw that referenced this pull request May 4, 2026
…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).
amittell added a commit to amittell/openclaw that referenced this pull request May 18, 2026
…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).
amittell added a commit to amittell/openclaw that referenced this pull request May 31, 2026
…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)
steipete pushed a commit to amittell/openclaw that referenced this pull request Jun 1, 2026
…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)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

agents Agent runtime and tooling channel: telegram Channel integration: telegram cli CLI command changes commands Command implementations extensions: memory-lancedb Extension: memory-lancedb gateway Gateway runtime r: too-many-prs Auto-close: author has more than twenty active PRs. size: XL

Projects

None yet

Development

Successfully merging this pull request may close these issues.

1 participant