Skip to content

Fix: Compact inbound metadata - #72749

Closed
sahilsatralkar wants to merge 1 commit into
openclaw:mainfrom
sahilsatralkar:fix/issue-72704-compact-inbound-metadata
Closed

sahilsatralkar wants to merge 1 commit into
openclaw:mainfrom
sahilsatralkar:fix/issue-72704-compact-inbound-metadata

Conversation

@sahilsatralkar

Copy link
Copy Markdown
Contributor

Summary

Describe the problem and fix in 2–5 bullets:

If this PR fixes a plugin beta-release blocker, title it fix(<plugin-id>): beta blocker - <summary> and link the matching Beta blocker: <plugin-name> - <summary> issue labeled beta-blocker. Contributors cannot label PRs, so the title is the PR-side signal for maintainers and automation.

  • Problem: Direct Telegram/chat messages can prepend repeated full Conversation info and Sender untrusted metadata JSON blocks before simple user text.
  • Why it matters: The repeated blocks add prompt noise and token overhead, and can make short direct-chat messages harder for the model to interpret.
  • What changed: Added optional messages.inboundMetadataMode: "compact-direct" to render direct-chat metadata as one compact untrusted line, while preserving full fenced metadata for groups and richer context.
  • What did NOT change (scope boundary): Defaults remain unchanged; group chats, replies, forwards, locations, structured context, and history keep the existing full metadata format.

Change Type (select all)

  • Bug fix
  • Feature
  • Refactor required for the fix
  • Docs
  • Security hardening
  • Chore/infra

Scope (select all touched areas)

  • Gateway / orchestration
  • Skills / tool execution
  • Auth / tokens
  • Memory / storage
  • Integrations
  • API / contracts
  • UI / DX
  • CI/CD / infra

Linked Issue/PR

Root Cause (if applicable)

  • Root cause: Inbound prompt assembly always used the full untrusted metadata block format for direct external-channel messages.
  • Missing detection / guardrail: Existing tests covered safety and metadata presence, but not compact direct-chat prompt shape or stripping compact AI-facing metadata from user-visible history.
  • Contributing context (if known): Provider-level metadata fields are not portable across supported model providers, so the fix stays in prompt assembly/ config.

Regression Test Plan (if applicable)

For bug fixes or regressions, name the smallest reliable test coverage that should catch this. Otherwise write N/A.

  • Coverage level that should have caught this:
    • Unit test
    • Seam / integration test
    • End-to-end test
    • Existing coverage already sufficient
    • Target test or file: src/auto-reply/reply/inbound-meta.test.ts, src/auto-reply/reply/strip-inbound-meta.test.ts, src/auto-reply/reply/get-reply-run.media- only.test.ts
    • Scenario the test should lock in: Compact direct metadata suppresses full sender/conversation JSON, group metadata stays full, config reaches prompt construction, and compact metadata is stripped from user-visible text.
    • Why this is the smallest reliable guardrail: These tests cover the prompt builder, the call site, and the display/history sanitizer without requiring a live Telegram bot.
    • Existing test that already covers this (if any): Existing inbound metadata tests covered full metadata behavior and safety escaping.
    • If no new test is added, why not: N/A

User-visible / Behavior Changes

New optional config: messages.inboundMetadataMode: "compact-direct".

Default behavior remains unchanged.

Diagram (if applicable)

For UI changes or non-trivial logic flows, include a small ASCII diagram reviewers can scan quickly. Otherwise write N/A.

  Before:
  [direct chat message] -> [full conversation JSON + full sender JSON + body]

  After:
  [direct chat message + compact-direct] -> [one compact untrusted metadata line + body]
  [group/rich context] -> [existing full fenced metadata blocks]

Security Impact (required)

  • New permissions/capabilities? (No)
  • Secrets/tokens handling changed? (No)
  • New/changed network calls? (No)
  • Command/tool execution surface changed? (No)
  • Data access scope changed? (No)
  • If any Yes, explain risk + mitigation: N/A

Repro + Verification

Environment

  • OS: macOS
  • Runtime/container: Node 22 / pnpm
  • Model/provider: N/A
  • Integration/channel (if any): Telegram/direct chat prompt assembly
  • Relevant config (redacted): messages.inboundMetadataMode: "compact-direct"

Steps

  1. Configure messages.inboundMetadataMode: "compact-direct".
  2. Build inbound user context for a direct Telegram message.
  3. Compare prompt prefix against default/full mode and group-chat mode.

Expected

  • Direct chats use one compact untrusted metadata line.
  • Sender name/username JSON block is not prepended in compact direct mode.
  • Groups and rich context retain full fenced metadata blocks.
  • Compact metadata does not appear in user-visible history.

Actual

  • Matches expected after this PR.

Evidence

Attach at least one:

  • Failing test/log before + passing after
  • Trace/log snippets
  • Screenshot/recording
  • Perf numbers (if relevant)

Human Verification (required)

What you personally verified (not just CI), and how:

  • Verified scenarios:
    • pnpm check:changed
    • pnpm build
    • pnpm test src/auto-reply/reply/inbound-meta.test.ts src/auto-reply/reply/strip-inbound-meta.test.ts src/auto-reply/reply/get-reply-run.media-only.test.ts
      src/plugins/cli.test.ts src/config/schema.help.quality.test.ts
    • pnpm config:schema:check
    • pnpm config:docs:check
    • codex review --base origin/main
  • Edge cases checked: direct vs group chats, compact metadata stripping, lookalike user text preservation, default config schema generation, wiki/memory CLI
    scope review finding.
  • What you did not verify: Live Telegram bot delivery.

Review Conversations

  • I replied to or resolved every bot review conversation I addressed in this PR.
  • I left unresolved only the conversations that still need reviewer or maintainer judgment.

If a bot review conversation is addressed by this PR, resolve that conversation yourself. Do not leave bot review conversation cleanup for maintainers.

Compatibility / Migration

  • Backward compatible? (Yes)
  • Config/env changes? (Yes)
  • Migration needed? (No)
  • If yes, exact upgrade steps: Optional only. Set messages.inboundMetadataMode to "compact-direct" to enable the new direct-chat prompt format.

Risks and Mitigations

List only real risks for this PR. Add/remove entries as needed. If none, write None.

  • Risk: Compact direct metadata could leak into user-visible history.
    • Mitigation: Added sanitizer support and tests for compact metadata stripping plus lookalike user text preservation.
  • Risk: Compacting metadata could remove context needed in groups or rich-message flows.
    • Mitigation: Compact mode applies only to direct chats; groups/replies/forwards/locations/history keep full metadata.

@openclaw-barnacle openclaw-barnacle Bot added docs Improvements or additions to documentation channel: telegram Channel integration: telegram size: M labels Apr 27, 2026
@greptile-apps

greptile-apps Bot commented Apr 27, 2026 •

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR adds an optional messages.inboundMetadataMode: \"compact-direct\" config that replaces the full fenced JSON metadata blocks on direct-chat prompts with a single terse line, while keeping existing full metadata for groups, replies, forwards, locations, and history. It also folds in a small fix to auto-load the configured memory-slot plugin when the CLI primary command is wiki or memory. Defaults and all other prompt paths are unchanged.

Confidence Score: 4/5

Safe to merge; findings are P2 quality/coverage concerns with no blocking defects.

Both findings are P2: a duplicate type definition that must be kept manually in sync, and a missing test/documentation for the side-effect that extractInboundSenderLabel (and therefore senderLabel backfill in stripEnvelopeFromMessage) returns null in compact-direct mode. Core logic, safety escaping, and stripping paths look correct and are well-tested.

src/auto-reply/reply/strip-inbound-meta.ts — extractInboundSenderLabel compact-direct gap; src/auto-reply/reply/inbound-meta.ts — duplicate type definition

Comments Outside Diff (1)

  1. src/auto-reply/reply/strip-inbound-meta.ts, line 317-333 (link)

    P2 extractInboundSenderLabel returns null in compact-direct mode

    extractInboundSenderLabel only looks for Sender (untrusted metadata): and Conversation info (untrusted metadata): JSON blocks. In compact-direct mode neither block exists — only the terse single-line format is present — so this function always returns null for direct messages using that mode.

    stripEnvelopeFromMessage in gateway/chat-sanitize.ts calls extractMessageSenderLabel → extractInboundSenderLabel to backfill senderLabel on stored messages. With compact-direct enabled, senderLabel will never be populated from message content, silently dropping sender attribution from the chat history view. There is no test covering this case, so the behaviour change is unverified.

    Prompt To Fix With AI
    This is a comment left during a code review.
    Path: src/auto-reply/reply/strip-inbound-meta.ts
    Line: 317-333
    
    Comment:
    **`extractInboundSenderLabel` returns null in compact-direct mode**
    
    `extractInboundSenderLabel` only looks for `Sender (untrusted metadata):` and `Conversation info (untrusted metadata):` JSON blocks. In compact-direct mode neither block exists — only the terse single-line format is present — so this function always returns `null` for direct messages using that mode.
    
    `stripEnvelopeFromMessage` in `gateway/chat-sanitize.ts` calls `extractMessageSenderLabel` → `extractInboundSenderLabel` to backfill `senderLabel` on stored messages. With compact-direct enabled, `senderLabel` will never be populated from message content, silently dropping sender attribution from the chat history view. There is no test covering this case, so the behaviour change is unverified.
    
    How can I resolve this? If you propose a fix, please make it concise.
Prompt To Fix All With AI
This is a comment left during a code review.
Path: src/auto-reply/reply/inbound-meta.ts
Line: 15

Comment:
**Duplicate type definition**

`InboundUserContextMetadataMode` here and `InboundMetadataMode` in `src/config/types.messages.ts` are structurally identical (`"full" | "compact-direct"`). `get-reply-run.ts` reads from the config type and passes it into the function that uses the local type, so there are now two parallel definitions that must stay in sync. One of these should re-export or import from the other to ensure a single source of truth.

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

---

This is a comment left during a code review.
Path: src/auto-reply/reply/strip-inbound-meta.ts
Line: 317-333

Comment:
**`extractInboundSenderLabel` returns null in compact-direct mode**

`extractInboundSenderLabel` only looks for `Sender (untrusted metadata):` and `Conversation info (untrusted metadata):` JSON blocks. In compact-direct mode neither block exists — only the terse single-line format is present — so this function always returns `null` for direct messages using that mode.

`stripEnvelopeFromMessage` in `gateway/chat-sanitize.ts` calls `extractMessageSenderLabel` → `extractInboundSenderLabel` to backfill `senderLabel` on stored messages. With compact-direct enabled, `senderLabel` will never be populated from message content, silently dropping sender attribution from the chat history view. There is no test covering this case, so the behaviour change is unverified.

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

Reviews (1): Last reviewed commit: "fix(plugins): scope memory slot CLI load..." | Re-trigger Greptile

Comment thread src/auto-reply/reply/inbound-meta.ts Resolved
@clawsweeper

clawsweeper Bot commented Apr 30, 2026 •

Copy link
Copy Markdown
Contributor

Thanks for the context here. I swept through the related work, and this is now duplicate or superseded.

Close this PR as superseded: it usefully targets the inline inbound-metadata problem, but the same central issue now has a cleaner proof-positive and mergeable path in #90745, while this branch is conflicting, lacks after-fix real behavior proof, and adds a separate config/product surface.

Canonical path: The related issue explicitly reports Telegram inline Conversation/Sender metadata degrading model comprehension and lists both this PR and #89428 as closing references; issue comments also point to hidden runtime context as the preferred fix direction.

So I’m closing this here and keeping the remaining discussion on #90745 and #89428.

Review details

Best possible solution:

Use #90745 as the canonical landing path for keeping inbound metadata available through hidden runtime context rather than adding a parallel compact prompt-format config.

Do we have a high-confidence way to reproduce the issue?

Yes, at source level. Current main still emits full Conversation/Sender metadata blocks and re-prepends currentInboundContext into active session/model prompt strings.

Is this the best way to solve the issue?

No. The compact config is a plausible mitigation, but the hidden-runtime-context approach in #90745 is narrower because it solves the inline metadata problem without creating a parallel prompt-format configuration surface.

Security review:

Security review cleared: The diff changes TypeScript prompt formatting, config schema/help, docs, and tests; it does not add dependencies, workflows, package resolution, secrets, permissions, network calls, or execution surfaces.

AGENTS.md: found and applied where relevant.

What I checked:

  • PR diff adds compact metadata config and formatter: The diff adds InboundMetadataMode, the messages.inboundMetadataMode schema/help/docs surface, and a useCompactDirectMetadata branch that replaces direct-chat Conversation/Sender JSON blocks with one compact line. (src/auto-reply/reply/inbound-meta.ts:468, 92944b24a0f1)
  • Current main still has the reported inline metadata behavior: Current main builds Conversation info (untrusted metadata): and Sender (untrusted metadata): blocks for inbound turns, then runEmbeddedAttempt re-wraps currentInboundContext into both session and model prompt text. (src/auto-reply/reply/inbound-meta.ts:632, ec737ee74d9b)
  • This PR is not a viable landing branch now: Live PR state reports mergeable: CONFLICTING, mergeStateStatus: DIRTY, and labels include triage: needs-real-behavior-proof and status: 📣 needs proof. (92944b24a0f1)
  • Canonical replacement is proof-positive and clean: fix: carry reply metadata into runtime context #90745 is open, mergeable, clean, labeled proof: sufficient, and includes the hidden-runtime-context routing that keeps inbound/reply metadata out of prompt/session text while preserving it for the model. (1c02af7d35da)
  • Canonical issue links both fix candidates: The related issue explicitly reports Telegram inline Conversation/Sender metadata degrading model comprehension and lists both this PR and fix: keep inbound metadata in runtime context #89428 as closing references; issue comments also point to hidden runtime context as the preferred fix direction.
  • Feature history points to current inbound metadata ownership: git blame on the central inbound metadata and sanitizer functions currently points at f12ade0 after the recent broad rewrite, while git log -S shows earlier inbound metadata shaping in 31e4c21 and 53273b4. (src/auto-reply/reply/inbound-meta.ts:548, f12ade0082ad)

Likely related people:

  • zhang-guiping: Current-main blame on buildInboundUserContextPrefix, get-reply-run prompt assembly, and extractInboundSenderLabel points to the recent broad rewrite commit. (role: recent area contributor; confidence: medium; commits: f12ade0082ad; files: src/auto-reply/reply/inbound-meta.ts, src/auto-reply/reply/get-reply-run.ts, src/auto-reply/reply/strip-inbound-meta.ts)
  • steipete: History shows prior inbound metadata and sender-spoofing work that shaped the current Conversation/Sender metadata boundary. (role: feature-history owner; confidence: high; commits: 31e4c21b6776, 53273b490b3a; files: src/auto-reply/reply/inbound-meta.ts, src/auto-reply/reply/get-reply-run.ts)
  • Mars: History shows the injected inbound metadata stripping helper and tests were added in the sanitizer path this PR extends. (role: sanitizer feature contributor; confidence: medium; commits: a4e7e952e143; files: src/auto-reply/reply/strip-inbound-meta.ts)
  • vincentkoc: The current best replacement path uses hidden runtime context, and recent related reviews/history point to Vincent Koc commits in the embedded runtime-context helper family. (role: adjacent runtime-context contributor; confidence: medium; commits: aa69b12d0086; files: src/agents/embedded-agent-runner/run/runtime-context-prompt.ts, src/agents/embedded-agent-runner/run/attempt.ts)

Codex review notes: model internal, reasoning high; reviewed against ec737ee74d9b.

@sahilsatralkar
sahilsatralkar force-pushed the fix/issue-72704-compact-inbound-metadata branch from ab9faa5 to 92944b2 Compare May 15, 2026 07:58
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels May 20, 2026
@clawsweeper

clawsweeper Bot commented May 20, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper PR egg

🎁 Pass real behavior proof to wake the egg and unlock a hatchable treat.

Where did the egg go?
  • The egg game starts only after the PR passes the real-behavior proof check.
  • Before that, no creature or rarity is rolled. The treat waits for real proof.
  • This is still just collectible flavor: proof affects review readiness, not creature quality.

@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 20, 2026
@gorkem2020

gorkem2020 commented May 26, 2026 •

Copy link
Copy Markdown
Contributor

Adding wire-level evidence and a related deployment scenario in support of this PR.

Verified on OpenClaw 2026.5.7: the Sender (untrusted metadata) block continues to wrap every inbound user message from the openclaw-control-ui channel, even when that channel is the only operator-driven surface in the deployment. Captured via OpenRouter Broadcast streaming to a self-hosted Langfuse instance; representative payload visible at prompt-assembly time:

Sender (untrusted metadata):
```json
{
  "label": "openclaw-control-ui",
  "id": "openclaw-control-ui"
}
```

The wrapper has no current opt-out path for this channel in 2026.5.7, which is the gap this PR addresses for the direct-Telegram case. The same reasoning applies one-to-one to openclaw-control-ui: it is a single-operator client by construction (the operator who configured the gateway is the only sender), and the wrapper adds no defensive value for that surface.

Additional failure mode not yet documented in the linked issues: the wrapper can become self-reinforcing through the memory plugin chain. We observed the following sequence on a pi-runtime agent using a verbose chain-of-thought model (codex/gpt-5.5 family) on the openclaw-control-ui channel:

  1. The agent repeatedly produced user-facing commentary about the "untrusted metadata" framing on every turn.
  2. The memory-lancedb-pro plugin's smart-extraction hook captured that commentary verbatim as a preferences-class memory (substance: "User is cautious about untrusted metadata injections in context").
  3. On every subsequent turn, autoRecall re-injected that captured memory into the prompt, amplifying the model's tendency to surface wrapper commentary, creating a positive feedback loop the operator has no straightforward way to break short of manually deleting the captured memory and tuning extraction aggressiveness.

This is a substrate-level cause for a plugin-layer symptom that's otherwise hard to root-cause. A compact-direct (or omit) mode for openclaw-control-ui would prevent the loop from ever seeding, in addition to the token-cost and model-comprehension benefits this PR already delivers.

Concrete ask: in addition to the direct / Telegram-DM scope already in this PR, please consider including the openclaw-control-ui channel in the same opt-in compact-direct path. The trust analysis is identical (single-operator client by construction), and the same messages.inboundMetadataMode knob could gate both with no change to the public surface or to defaults. Quieter models (e.g., MiniMax M2.7 in our setup) tolerate the verbose envelope silently; the cost falls on verbose chain-of-thought models which then surface the wrapper at the user.

Happy to provide additional Langfuse trace excerpts on request.

@openclaw-barnacle

Copy link
Copy Markdown

This pull request has been automatically marked as stale due to inactivity.
Please add updates or it will be closed.

@openclaw-barnacle openclaw-barnacle Bot added the stale Marked as stale due to inactivity label Jun 14, 2026
@clawsweeper clawsweeper Bot added P2 Normal backlog priority with limited blast radius. merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. labels Jun 14, 2026
@openclaw-barnacle openclaw-barnacle Bot removed the stale Marked as stale due to inactivity label Jun 15, 2026
@clawsweeper clawsweeper Bot added merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 15, 2026
@clawsweeper clawsweeper Bot added rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jun 17, 2026
@clawsweeper clawsweeper Bot removed the merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. label Jun 19, 2026
@clawsweeper clawsweeper Bot added the mantis: telegram-visible-proof Mantis should capture Telegram visible proof. label Jun 20, 2026
@openclaw-barnacle openclaw-barnacle Bot added the triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. label Jun 20, 2026
@clawsweeper
clawsweeper Bot temporarily deployed to qa-live-shared June 20, 2026 17:20 Inactive
@clawsweeper clawsweeper Bot added mantis: telegram-visible-proof Mantis should capture Telegram visible proof. and removed mantis: telegram-visible-proof Mantis should capture Telegram visible proof. labels Jun 21, 2026
@clawsweeper
clawsweeper Bot temporarily deployed to qa-live-shared June 21, 2026 22:44 Inactive
@clawsweeper clawsweeper Bot removed the mantis: telegram-visible-proof Mantis should capture Telegram visible proof. label Jun 23, 2026
@clawsweeper

clawsweeper Bot commented Jun 26, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

  • Action: closed this PR.
  • Close reason: duplicate or superseded.
  • Evidence: durable ClawSweeper review.
  • Coverage proof: PR B clearly carries PR A's central useful behavior through a narrower canonical implementation and is the better place to review or land the remaining metadata-preservation work; PR A's compact config/docs/sanitizer details are incidental to that superseded approach. Covering PR: fix: carry reply metadata into runtime context #90745.

@clawsweeper clawsweeper Bot closed this Jun 26, 2026

This branch was previously deployed

1 inactive deployment
qa-live-shared — 92944b24 Deployed Jun 21, 2026 by clawsweeper[bot] via Run agentic native Telegram proof #212886
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: telegram Channel integration: telegram docs Improvements or additions to documentation merge-risk: 🚨 compatibility 🚨 May break existing users, config, migrations, defaults, or upgrade paths. merge-risk: 🚨 session-state 🚨 May lose, corrupt, stale, or mis-associate session, agent, or context state. P2 Normal backlog priority with limited blast radius. rating: 🧂 unranked krab Not merge-ready due to missing proof or serious correctness/safety concerns. size: M status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. triage: needs-pr-context Candidate: external PR body lacks required problem context or evidence. triage: needs-real-behavior-proof Candidate: external PR needs after-fix proof from a real setup.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

[UX] Excessive inline JSON metadata in Telegram user messages degrades model comprehension

2 participants