Repository navigation
Conversation
🔒 Aisle Security AnalysisWe found 2 potential security issue(s) in this PR:
1. 🟠 Unsanitized memory_store tool allows persistence of envelope metadata and prompt-injection payloads in LanceDB memory
DescriptionThe
Vulnerable code: const vector = await embeddings.embed(text);
...
const entry = await db.store({
text,
vector,
importance,
category,
});RecommendationApply 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 2. 🟡 Memory capture/recall evasion via substring-based envelope sludge detection
Description
This allows a remote user to intentionally include one of the sentinel substrings (e.g.,
Because the sentinel check is implemented as Vulnerable code: for (const sentinel of INBOUND_META_SENTINELS) {
if (text.includes(sentinel)) {
return true;
}
}
...
if (looksLikeEnvelopeSludge(text)) {
return false;
}RecommendationTighten sludge detection so it only triggers on actual injected envelope blocks, not arbitrary user text. Suggested approach:
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 Last updated on: 2026-04-16T05:05:54Z |
There was a problem hiding this comment.
💡 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".
| const useLocalOnly = params.agentLocalOnly || params.agentDir !== undefined; | ||
| const store = useLocalOnly | ||
| ? loadAgentLocalAuthProfileStore(params.agentDir) | ||
| : ensureAuthProfileStore(params.agentDir); |
There was a problem hiding this comment.
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 SummaryThis PR fixes a prompt-contamination bug in Confidence Score: 5/5Safe 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 AIThis 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 |
1eaab7c to
edd13f3
Compare
There was a problem hiding this comment.
💡 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".
| 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) { |
There was a problem hiding this comment.
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 👍 / 👎.
| const untrustedIdx = cleaned.indexOf(UNTRUSTED_CONTEXT_HEADER_PREFIX); | ||
| if (untrustedIdx !== -1) { | ||
| cleaned = cleaned.slice(0, untrustedIdx); |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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".
| } | ||
|
|
||
| // Check for "Untrusted context (metadata..." header | ||
| if (text.includes(UNTRUSTED_CONTEXT_HEADER_PREFIX)) { |
There was a problem hiding this comment.
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 👍 / 👎.
|
|
||
| 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; |
There was a problem hiding this comment.
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 👍 / 👎.
There was a problem hiding this comment.
💡 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)) { |
There was a problem hiding this comment.
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 👍 / 👎.
| const ENVELOPE_JSON_LINE_RE = | ||
| /^\s*\{"(?:conversation_info|sender_name|channel_id|channel_type)"\s*:/m; |
There was a problem hiding this comment.
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 👍 / 👎.
…eplyMediaForMessage
…ReplyMediaForMessage
b31846b to
955eb20
Compare
There was a problem hiding this comment.
💡 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}`, |
There was a problem hiding this comment.
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 👍 / 👎.
| // 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)) { |
There was a problem hiding this comment.
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 👍 / 👎.
…p dead orphan transcript recovery
|
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. |
There was a problem hiding this comment.
💡 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".
| const lastAssistantTurnMs = transcriptLastCompletedAssistantTurnTimestamp(transcriptPath); | ||
| if (lastAssistantTurnMs !== null) { |
There was a problem hiding this comment.
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 👍 / 👎.
|
This has been superseded by a clean re-implementation: #73787 #67475 was closed because the head ref ( #73787 extracts exactly those 4 commits and re-applies the guards at the correct insertion points in the current upstream |
…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).
…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).
…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)
…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)
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-lancedbauto-capture was storing raw user message text fromagent_end, including OpenClaw-injected inbound scaffolding such as:Conversation info (untrusted metadata)Sender (untrusted metadata)Replied message (untrusted, for context)active-turn-recoveryboilerplate[media attached: ...]annotationsThose contaminated entries could later be recalled by
before_agent_startand 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
looksLikeEnvelopeSludge(...)to detect transport/meta contaminationsanitizeForMemoryCapture(...)to strip inbound metadata, timestamp prefixes, media annotations, and plugin scaffolding before captureshouldCapture(...)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: