Skip to content

fix(discord): support CJK @mention rewriting in bot-to-bot message chains - #59818

Closed
Hou-Yufan wants to merge 1 commit into
openclaw:mainfrom
Hou-Yufan:fix/discord-bot-to-bot-mention-rewrite-cjk
Closed

Hou-Yufan wants to merge 1 commit into
openclaw:mainfrom
Hou-Yufan:fix/discord-bot-to-bot-mention-rewrite-cjk

Conversation

@Hou-Yufan

Copy link
Copy Markdown

Summary

  • Problem: In multi-bot Discord setups with CJK (Chinese/Japanese/Korean) usernames, @mention rewriting fails because the mention candidate regex only matches ASCII characters [a-z0-9_.-]. When Bot A tells Bot B to mention @架构师, the text is sent as plain text instead of being converted to <@user_id>.
  • Why it matters: Without proper mention rewriting, bot-to-bot @mention chains break — the mentioned bot never receives a notification and cannot respond, breaking multi-bot collaboration workflows.
  • What changed:
    1. MENTION_CANDIDATE_PATTERN regex updated from ASCII to Unicode ([\p{L}\p{N}_.-] with /u flag)
    2. resolveDiscordDirectoryUserId now falls back across all account caches (cross-account resolution for multi-bot gateways)
    3. Reply delivery and process paths call rewriteDiscordKnownMentions on outbound text
    4. Provider startup seeds the directory cache from bot identity
    5. Preflight populates directory cache from message author + mentioned users
  • What did NOT change: No changes to core mention detection, command parsing, or message routing logic.

Change Type (select all)

  • Bug fix

Scope (select all touched areas)

  • Integrations

Linked Issue/PR

  • This PR fixes a bug or regression

Root Cause / Regression History (if applicable)

  • Root cause: The mention candidate regex was written for ASCII-only Discord usernames. CJK characters are valid Discord display names but don't match [a-z0-9_.-].
  • Missing detection / guardrail: No test with CJK usernames in the mention test suite.
  • Prior context: The regex was appropriate when Discord usernames were ASCII-only, but display names have always allowed Unicode.
  • Why this regressed now: Not a regression — this was a gap in the original implementation that becomes visible in CJK bot deployments.
  • Additionally, resolveDiscordDirectoryUserId was scoped to a single account's cache, preventing cross-account resolution needed for multi-bot gateways.

Regression Test Plan (if applicable)

  • Coverage level that should have caught this:
    • Unit test
  • Target test or file: extensions/discord/src/mentions.test.ts, extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.ts
  • Scenario the test should lock in:
    1. CJK usernames are matched by the mention candidate pattern
    2. Cross-account directory cache resolution works for multi-bot gateways
    3. Directory cache is populated from message author and mentioned users during preflight
  • Why this is the smallest reliable guardrail: Unit tests verify regex matching and cache behavior without requiring Discord API
  • Existing test that already covers this: None previously; 15 tests added in this PR

User-visible / Behavior Changes

  • Bot-to-bot @mention chains now work with CJK usernames (e.g., @架构师 is correctly rewritten to <@user_id>)
  • Directory cache resolution works across bot accounts in multi-bot gateways

Diagram (if applicable)

Before:
Bot A: "请让 @架构师 回复" -> sent as plain text "@架构师" -> 架构师 bot never notified

After:
Bot A: "请让 @架构师 回复" -> rewritten to "<@1488478869458780280>" -> 架构师 bot receives mention notification -> responds

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 (directory cache is local, in-memory, per-gateway)

Repro + Verification

Environment

  • OS: macOS
  • Runtime: Node.js 22
  • Integration/channel: Discord (6-bot multi-agent gateway with CJK bot names)

Steps

  1. Configure 2+ Discord bot accounts with CJK display names (e.g., 技术总监, 架构师)
  2. Have Bot A generate a response mentioning @架构师
  3. Observe the sent Discord message

Expected

The mention is rewritten to <@bot_user_id> and the target bot receives a mention notification.

Actual

Before fix: plain text @架构师 sent, no notification. After fix: <@id> sent, bot notified.

Evidence

  • Failing test/log before + passing after
  • Tests: pnpm test -- extensions/discord/src/mentions.test.ts (10 tests), pnpm test -- extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.ts (5 tests), pnpm test -- extensions/discord/src/monitor/message-handler.preflight.test.ts (25 tests) — all pass.

Human Verification (required)

  • Verified scenarios: CJK mention matching, cross-account cache resolution, directory cache population from preflight, outbound mention rewriting in reply-delivery and process paths
  • Edge cases checked: Mixed CJK + ASCII usernames, discriminator tags (fix: add @lid format support and allowFrom wildcard handling #1), usernames with dots/underscores, empty directory cache
  • What you did not verify: Live Discord bot-to-bot @mention chain (verified via unit tests and gateway logs showing CJK bot names initialized)

Copilot AI review requested due to automatic review settings April 2, 2026 17:00
@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: M labels Apr 2, 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: c73fe4f513

ℹ️ 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 +119 to +124
for (const [key, subMap] of DIRECTORY_HANDLE_CACHE) {
if (key === ownKey) {
continue;
}
const found = subMap.get(handle) ?? (altHandle ? subMap.get(altHandle) : undefined);
if (found) {

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 Prevent ambiguous cross-account handle fallback

The new global fallback in resolveDiscordDirectoryUserId returns the first matching handle from any other account cache, so duplicate handles across accounts (for example two different @alice users) are resolved nondeterministically based on map insertion order. In multi-bot gateways this can rewrite a mention to the wrong Discord user ID, causing wrong-user pings or failed mentions in the current guild; the fallback should only be used when the match is unambiguous (or scoped to known bot identities).

Useful? React with 👍 / 👎.

@@ -1,7 +1,7 @@
import { resolveDiscordDirectoryUserId } from "./directory-cache.js";

const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g;
const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi;
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;

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 mention matching to true mention boundaries

Changing the prefix boundary to (^|[^\p{L}\p{N}]) makes @name inside URL paths match (for example https://x.com/@alice), so cached handles can now be rewritten inside links and other non-mention contexts. This is a behavior regression from the previous tighter boundary and can silently corrupt outbound URLs/messages when a username is present in path-like text.

Useful? React with 👍 / 👎.

@greptile-apps

greptile-apps Bot commented Apr 2, 2026

Copy link
Copy Markdown
Contributor

Greptile Summary

This PR fixes CJK @mention rewriting in Discord bot-to-bot message chains by extending the mention candidate regex to support Unicode characters, adding cross-account directory cache resolution for multi-bot gateways, seeding the cache at startup and preflight, and wiring rewriteDiscordKnownMentions into the reply-delivery and process paths.

Key changes:

  • MENTION_CANDIDATE_PATTERN updated to [\p{L}\p{N}_.-]{1,32} with /u flag — correctly matches CJK and other Unicode display names
  • resolveDiscordDirectoryUserId now falls back across all account sub-maps when the own-account lookup misses, enabling cross-bot mention resolution in the same process
  • preflightDiscordMessage passively caches the inbound message author, globalName, nick, and mentionedUsers so downstream rewriting has the data it needs without prompt-level ID injection
  • Provider startup seeds the cache with the bot's own identity using the application-ID fallback when the REST call fails
  • sendDiscordChunkWithFallback and the preview-edit path in message-handler.process.ts both apply rewriteDiscordKnownMentions on outbound text — no double-rewriting observed on the standard delivery path
  • 15 new tests covering CJK regex matching, cross-account resolution, and preflight cache population

Issues found:

  • The cross-account fallback in resolveDiscordDirectoryUserId has no guild scope. In a single-process deployment serving bots across multiple Discord servers, two guilds can have users with the same display name, and the fallback would resolve to whichever was cached first — potentially mentioning the wrong user.
  • Several rawAuthor / rawMessage / globalName accesses use unsafe type assertions against undocumented internal Carbon fields; these will silently fail if Carbon's internal structure changes.
  • The new prefix class [^\p{L}\p{N}] is broader than the previous allowlist and now permits < as a valid mention separator, which could theoretically match already-formatted <@id> tokens if a numeric handle is ever cached.

Confidence Score: 3/5

  • Safe to merge for single-guild multi-bot deployments; holds a data-isolation risk for multi-guild single-process setups that should be acknowledged before broader rollout.
  • The core CJK fix (regex + Unicode flag) is sound and well-tested. The preflight cache population and startup seeding are straightforward additions with good test coverage. The main concern is the guild-unscoped cross-account fallback: it works correctly for the stated use case (multiple cooperating bots in one server) but becomes a correctness hazard if the same process later manages bots in multiple Discord servers — a configuration that isn't explicitly guarded against. The undocumented-field type assertions add silent failure modes on future Carbon upgrades. These don't cause crashes today but represent maintainability and correctness risks that lower confidence.
  • extensions/discord/src/directory-cache.ts (cross-account fallback scope) and extensions/discord/src/monitor/message-handler.preflight.ts (undocumented Carbon field access).
Prompt To Fix All With AI
This is a comment left during a code review.
Path: extensions/discord/src/directory-cache.ts
Line: 113-127

Comment:
**Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups**

The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for *multiple distinct Discord servers*, two guilds can have different users who share the same display name (e.g. `alice`). The first one cached wins, and the sending bot ends up mentioning the wrong person.

The cache key is `accountId` (= bot token identity), not `(accountId, guildId)`. Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.

Consider scoping the directory cache key to `(accountId, guildId)` or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.

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/discord/src/monitor/message-handler.preflight.ts
Line: 292-332

Comment:
**Belt-and-suspenders fallback relies on undocumented internal fields**

Both `rawAuthor` and `rawMessage` are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:

```ts
const rawAuthor = (
  params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
  params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;
```

Because the primary path (`author.username`, `message.mentionedUsers`) already covers the Carbon-typed surface, and the `globalName` assertion on the primary author (`(author as { globalName?: string }).globalName`) also targets an untyped field, this pattern adds silent failure modes. Consider either:
- Filing an issue/PR against Carbon to expose `globalName` and `global_name` in the typed API, or
- Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.

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/discord/src/mentions.ts
Line: 4

Comment:
**Negative-class prefix `[^\p{L}\p{N}]` is broader than the previous allowlist**

Old prefix: `[\s([{"'.,;:!?]` (explicit allowlist of safe separators)
New prefix: `[^\p{L}\p{N}]` (any non-letter / non-digit — including `<`, `/`, `\`, `|`, control chars, etc.)

The practical implication: a text fragment like `<@1234567890>` (an already-formatted Discord mention) now has `<` matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as `<<@id>`. While that scenario is unlikely today (the cache only stores `username`/`globalName` strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.

Narrowing to something like `[^\p{L}\p{N}<]` or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.

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

Reviews (1): Last reviewed commit: "fix(discord): support CJK @mention rewri..." | Re-trigger Greptile

Comment on lines +113 to +127
// Fallback: check ALL account sub-maps. In a multi-bot gateway where all
// bots run in the same process, another account's preflight may have already
// cached the target handle. This cross-account fallback enables bot→bot
// @mention rewriting even when the sending bot hasn't directly processed a
// message from the target user.
const ownKey = normalizeAccountCacheKey(params.accountId);
for (const [key, subMap] of DIRECTORY_HANDLE_CACHE) {
if (key === ownKey) {
continue;
}
const found = subMap.get(handle) ?? (altHandle ? subMap.get(altHandle) : undefined);
if (found) {
return found;
}
}

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 Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups

The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for multiple distinct Discord servers, two guilds can have different users who share the same display name (e.g. alice). The first one cached wins, and the sending bot ends up mentioning the wrong person.

The cache key is accountId (= bot token identity), not (accountId, guildId). Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.

Consider scoping the directory cache key to (accountId, guildId) or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/directory-cache.ts
Line: 113-127

Comment:
**Cross-account fallback has no guild scope — can resolve wrong user in multi-guild setups**

The fallback iterates over every account sub-map in the process. This is correct when all bots share one Discord server, but in a deployment where a single process runs bots for *multiple distinct Discord servers*, two guilds can have different users who share the same display name (e.g. `alice`). The first one cached wins, and the sending bot ends up mentioning the wrong person.

The cache key is `accountId` (= bot token identity), not `(accountId, guildId)`. Because the fallback ignores account boundaries entirely, guild isolation is lost once the cross-account path fires.

Consider scoping the directory cache key to `(accountId, guildId)` or, at minimum, documenting that this system is only safe for single-guild multi-bot deployments and adding an assertion or warning when the same handle appears under two different accounts with different user IDs.

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

Comment on lines +292 to +332
// Also cache from the raw author data (snake_case fields) as a belt-and-suspenders fallback.
const rawAuthor = (
params.data as { rawAuthor?: { id?: string; username?: string; global_name?: string | null } }
).rawAuthor;
if (rawAuthor?.id && rawAuthor.username) {
rememberDiscordDirectoryUser({
accountId: params.accountId,
userId: rawAuthor.id,
handles: [rawAuthor.username, rawAuthor.global_name ?? undefined],
});
}
// Also cache any explicitly-mentioned users from the inbound message so that
// their handles are resolvable immediately, even before they speak.
for (const mentioned of message.mentionedUsers ?? []) {
const u = mentioned as { id?: string; username?: string; globalName?: string };
if (u.id && u.username) {
rememberDiscordDirectoryUser({
accountId: params.accountId,
userId: u.id,
handles: [u.username, u.globalName],
});
}
}
const rawMessage = (
params.data as {
rawMessage?: {
mentions?: Array<{ id?: string; username?: string; global_name?: string | null }>;
};
}
).rawMessage;
if (rawMessage?.mentions) {
for (const mention of rawMessage.mentions) {
if (mention.id && mention.username) {
rememberDiscordDirectoryUser({
accountId: params.accountId,
userId: mention.id,
handles: [mention.username, mention.global_name ?? undefined],
});
}
}
}

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 Belt-and-suspenders fallback relies on undocumented internal fields

Both rawAuthor and rawMessage are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:

const rawAuthor = (
  params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
  params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;

Because the primary path (author.username, message.mentionedUsers) already covers the Carbon-typed surface, and the globalName assertion on the primary author ((author as { globalName?: string }).globalName) also targets an untyped field, this pattern adds silent failure modes. Consider either:

  • Filing an issue/PR against Carbon to expose globalName and global_name in the typed API, or
  • Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/monitor/message-handler.preflight.ts
Line: 292-332

Comment:
**Belt-and-suspenders fallback relies on undocumented internal fields**

Both `rawAuthor` and `rawMessage` are accessed via unsafe type assertions against fields that aren't part of the typed Carbon API. If the internal shape of the event object changes in a future Carbon upgrade, these fallbacks will silently stop working with no type error:

```ts
const rawAuthor = (
  params.data as { rawAuthor?: { ... } }
).rawAuthor;
// ...
const rawMessage = (
  params.data as { rawMessage?: { mentions?: ... } }
).rawMessage;
```

Because the primary path (`author.username`, `message.mentionedUsers`) already covers the Carbon-typed surface, and the `globalName` assertion on the primary author (`(author as { globalName?: string }).globalName`) also targets an untyped field, this pattern adds silent failure modes. Consider either:
- Filing an issue/PR against Carbon to expose `globalName` and `global_name` in the typed API, or
- Adding a comment noting the specific Carbon version these fields were verified against, so a future bump can be audited.

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

@@ -1,7 +1,7 @@
import { resolveDiscordDirectoryUserId } from "./directory-cache.js";

const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g;
const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi;
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;

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 Negative-class prefix [^\p{L}\p{N}] is broader than the previous allowlist

Old prefix: [\s([{"'.,;:!?] (explicit allowlist of safe separators)
New prefix: [^\p{L}\p{N}] (any non-letter / non-digit — including <, /, \, |, control chars, etc.)

The practical implication: a text fragment like <@1234567890> (an already-formatted Discord mention) now has < matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as <<@id>. While that scenario is unlikely today (the cache only stores username/globalName strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.

Narrowing to something like [^\p{L}\p{N}<] or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.

Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/mentions.ts
Line: 4

Comment:
**Negative-class prefix `[^\p{L}\p{N}]` is broader than the previous allowlist**

Old prefix: `[\s([{"'.,;:!?]` (explicit allowlist of safe separators)
New prefix: `[^\p{L}\p{N}]` (any non-letter / non-digit — including `<`, `/`, `\`, `|`, control chars, etc.)

The practical implication: a text fragment like `<@1234567890>` (an already-formatted Discord mention) now has `<` matched as a valid prefix. If a numeric string matching an already-stored snowflake-as-handle ever ends up in the cache, the mention could be double-wrapped as `<<@id>`. While that scenario is unlikely today (the cache only stores `username`/`globalName` strings), widening the prefix class removes a lightweight guard that previously prevented matches in unexpected positions.

Narrowing to something like `[^\p{L}\p{N}<]` or keeping an explicit allowlist that adds CJK punctuation would preserve the intent without the added exposure.

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

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 fixes Discord outbound @mention rewriting in multi-bot gateways by expanding mention matching to Unicode (CJK) handles and improving how user handle→ID mappings are learned and resolved across bot accounts.

Changes:

  • Update mention-candidate detection to support Unicode letters/numbers and fullwidth/CJK punctuation boundaries.
  • Extend the directory cache to support cross-account handle resolution and seed/populate it from bot identity + inbound message authors/mentions.
  • Apply outbound mention rewriting in reply delivery and draft finalization paths; add unit tests for CJK and cache population behavior.

Reviewed changes

Copilot reviewed 9 out of 9 changed files in this pull request and generated 4 comments.

Show a summary per file
File Description
extensions/discord/src/mentions.ts Updates mention-candidate regex to Unicode-aware matching for CJK handles.
extensions/discord/src/directory-cache.ts Adds cross-account fallback when resolving handle→userId mappings.
extensions/discord/src/monitor/message-handler.preflight.ts Populates directory cache from inbound author + mentions during preflight.
extensions/discord/src/monitor/reply-delivery.ts Rewrites known mentions on outbound chunks prior to sending.
extensions/discord/src/monitor/message-handler.process.ts Rewrites known mentions for the “finalize via preview edit” path.
extensions/discord/src/monitor/provider.ts Seeds directory cache from the bot’s own identity at startup.
extensions/discord/src/monitor/provider.startup.ts Adds proxy-aware REST fetch wiring; bot identity fetch falls back to applicationId.
extensions/discord/src/mentions.test.ts Adds tests for CJK/fullwidth punctuation + cross-account resolution behavior.
extensions/discord/src/monitor/message-handler.preflight.directory-cache.test.ts New tests ensuring preflight seeds cache from author/mentions and enables outbound rewriting.

@@ -1,7 +1,7 @@
import { resolveDiscordDirectoryUserId } from "./directory-cache.js";

const MARKDOWN_CODE_SEGMENT_PATTERN = /```[\s\S]*?```|`[^`\n]*`/g;
const MENTION_CANDIDATE_PATTERN = /(^|[\s([{"'.,;:!?])@([a-z0-9_.-]{2,32}(?:#[0-9]{4})?)/gi;
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

The new mention-candidate regex will also match inside already-canonical Discord mentions like <@123> (prefix < satisfies [^\p{L}\p{N}]). If a cached handle is numeric (or otherwise overlaps), this can corrupt existing mentions (e.g., <@123> becoming <<@resolved>>). Consider explicitly excluding < from the allowed prefix (or add a guard in the replacer when prefix === "<") so already-formatted mentions are never rewritten.

Suggested change
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;
const MENTION_CANDIDATE_PATTERN = /(^|[^\p{L}\p{N}<])@([\p{L}\p{N}_.-]{1,32}(?:#[0-9]{4})?)/giu;

Copilot uses AI. Check for mistakes.
Comment on lines 162 to 166
if (!params.text.trim()) {
return;
}
const text = params.text;
const text = rewriteDiscordKnownMentions(params.text, { accountId: params.accountId });
const binding = params.binding;

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

rewriteDiscordKnownMentions is currently applied per already-chunked message (params.text). Because chunkDiscordTextWithMode can split long lines at arbitrary character boundaries, an @handle near a chunk boundary can be split into two chunks and will then never be rewritten. Consider rewriting the full outbound text before chunking (e.g., in deliverDiscordReply before chunkDiscordTextWithMode/resolveTextChunksWithFallback) and pass the rewritten text into the chunker, rather than rewriting each chunk here.

Copilot uses AI. Check for mistakes.
Comment on lines 273 to +305
const allowBotsSetting = params.discordConfig?.allowBots;
const allowBotsMode =
allowBotsSetting === "mentions" ? "mentions" : allowBotsSetting === true ? "all" : "off";

// Passively populate the directory cache from the message author so that
// outbound rewriteDiscordKnownMentions() can resolve @name → <@ID> for
// any user (including bots) seen in this channel — enabling bot→bot @mention
// chains without prompt-level ID injection.
if (author.id && author.username) {
rememberDiscordDirectoryUser({
accountId: params.accountId,
userId: author.id,
handles: [
author.username,
(author as { globalName?: string }).globalName,
params.data.member?.nick,
],
});
}
// Also cache from the raw author data (snake_case fields) as a belt-and-suspenders fallback.
const rawAuthor = (
params.data as { rawAuthor?: { id?: string; username?: string; global_name?: string | null } }
).rawAuthor;
if (rawAuthor?.id && rawAuthor.username) {
rememberDiscordDirectoryUser({
accountId: params.accountId,
userId: rawAuthor.id,
handles: [rawAuthor.username, rawAuthor.global_name ?? undefined],
});
}
// Also cache any explicitly-mentioned users from the inbound message so that
// their handles are resolvable immediately, even before they speak.
for (const mentioned of message.mentionedUsers ?? []) {

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

Directory-cache seeding is done before the early-return drops (own-message, guild/channel allowlist/group policy, allowBots, etc.). This means a message that is ultimately ignored/blocked can still populate the handle→ID cache, which can then affect outbound mention rewriting in allowed contexts (potentially resolving the wrong user when handles collide across guilds). Consider moving the cache population to after the message has passed the relevant allow/ignore checks, or scoping the cache entries to the validated context.

Copilot uses AI. Check for mistakes.
expect(opsRewrite).toBe("<@999888777>");
// "default" also resolves via cross-account fallback (multi-bot gateway)
const defaultRewrite = rewriteDiscordKnownMentions("@alice", { accountId: "default" });
expect(defaultRewrite).toBe("<@999888777>");
});

Copilot AI Apr 2, 2026

Copy link

Choose a reason for hiding this comment

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

Given the broader prefix match in MENTION_CANDIDATE_PATTERN, it would be good to add a regression test ensuring already-formatted mentions like <@123> are not rewritten (especially if a cached handle could be numeric or otherwise overlap). This will help catch accidental corruption of existing Discord mention markup when adjusting the regex in the future.

Suggested change
});
});
it("does not rewrite already-formatted user mentions", () => {
rememberDiscordDirectoryUser({
accountId: "default",
userId: "123456789",
handles: ["123456789"],
});
const rewritten = rewriteDiscordKnownMentions("user <@123456789> and @123456789", {
accountId: "default",
});
expect(rewritten).toBe("user <@123456789> and <@123456789>");
});

Copilot uses AI. Check for mistakes.
@Hou-Yufan
Hou-Yufan force-pushed the fix/discord-bot-to-bot-mention-rewrite-cjk branch from c73fe4f to d5b0e91 Compare April 2, 2026 17:25

@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: d5b0e9116a

ℹ️ 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 +277 to +281
// Passively populate the directory cache from the message author so that
// outbound rewriteDiscordKnownMentions() can resolve @name → <@ID> for
// any user (including bots) seen in this channel — enabling bot→bot @mention
// chains without prompt-level ID injection.
if (author.id && author.username) {

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 Defer directory cache writes until message is policy-allowed

preflightDiscordMessage stores author handles in the shared directory cache before any guild/channel allowlist decisions are applied, so even messages that are later dropped can mutate mention resolution state. Since outbound rewriting consumes this cache without channel context, traffic from blocked channels can poison @handle -> userId mappings and cause replies in allowed channels to ping the wrong user. Cache population should happen only after policy gates pass (or be scoped by guild/channel) to prevent rejected messages from affecting outbound mention rewriting.

Useful? React with 👍 / 👎.

@Hou-Yufan
Hou-Yufan force-pushed the fix/discord-bot-to-bot-mention-rewrite-cjk branch from d5b0e91 to baca86b Compare April 12, 2026 14:28

@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: baca86bed1

ℹ️ 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 +1014 to +1018
rememberDiscordDirectoryUser({
accountId: account.accountId,
userId: botUserId,
handles: [botUserName].filter(Boolean),
});

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 Seed bot cache with both username and display name

The startup cache seed only stores botUserName, which is computed as username ?? globalName; since Discord bot users always have a username, the globalName path is effectively never cached. In multi-bot setups where agents mention peers by display name (for example a CJK display name while the canonical username is ASCII), cross-account rewrite still fails on first contact because @displayName cannot resolve until that bot later appears in inbound preflight traffic. Cache both handles at startup so mention rewriting works before any inbound message from the target bot.

Useful? React with 👍 / 👎.

@Hou-Yufan
Hou-Yufan force-pushed the fix/discord-bot-to-bot-mention-rewrite-cjk branch from ea7f01e to c8db5d7 Compare April 12, 2026 14:44

@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: c8db5d714b

ℹ️ 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".

handles: [
author.username,
(author as { globalName?: string }).globalName,
params.data.member?.nick,

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 Stop caching guild nicknames in account-global handle map

Adding params.data.member?.nick to rememberDiscordDirectoryUser stores guild-scoped nicknames in an account-wide cache, while outbound rewriting (rewriteDiscordKnownMentions) resolves only by accountId and has no guild/channel context. In a multi-guild bot, two different users can share the same nickname, so the most recent inbound message overwrites the mapping and a later @nickname in another guild can be rewritten to the wrong <@userId>, causing wrong-user pings. Nicknames should be scoped by guild (or excluded from this global cache).

Useful? React with 👍 / 👎.

@clawsweeper

clawsweeper Bot commented May 1, 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 is superseded by the related Unicode Discord mention PR, which was closed after a member stated the existing ASCII mention behavior is correct. Current main and docs still steer agents toward canonical Discord mention IDs or configured mentionAliases, while this branch also adds unsafe cross-account cache resolution and lacks live Discord proof.

Canonical path: Keep the current canonical <@id> and configured mentionAliases contract; any future display-name rewrite should start as a new maintainer-approved, scoped Discord design.

So I’m closing this here because the remaining work is already tracked in the canonical issue.

Review details

Best possible solution:

Keep the current canonical <@id> and configured mentionAliases contract; any future display-name rewrite should start as a new maintainer-approved, scoped Discord design.

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

Yes for the observed behavior: current main's regex does not rewrite CJK handles. That behavior is not a confirmed bug now because current docs and the related maintainer decision keep Discord plain mention rewriting tied to canonical IDs or configured aliases.

Is this the best way to solve the issue?

No. The PR's Unicode rewrite direction is superseded by #43357, and its cache/identity changes are broader than a safe Discord mention fix.

Security review:

Security review needs attention: The diff has concrete Discord identity and mention-isolation risks, though no dependency or workflow supply-chain concern was found.

  • [medium] Account-global fallback can ping the wrong Discord user — extensions/discord/src/directory-cache.ts:123
    Cross-account fallback resolves handles from another account or guild without context, so duplicate display names can notify the wrong user.
    Confidence: 0.9
  • [medium] Rejected messages can poison handle resolution — extensions/discord/src/monitor/message-handler.preflight.ts:386
    Preflight cache writes happen before later policy drops, allowing blocked channels or senders to influence outbound mention rewriting in allowed contexts.
    Confidence: 0.87
  • [medium] Application-id fallback can weaken identity gates — extensions/discord/src/monitor/provider.startup.ts:229
    Falling back from failed fetchUser("@me") to applicationId can keep the monitor running with an unverified bot user ID, affecting self-message and mention-required gates.
    Confidence: 0.82

What I checked:

  • Current prompt contract uses canonical mentions or configured aliases: Current main tells agents to use <@USER_ID>, <#CHANNEL_ID>, and <@&ROLE_ID>, and says plain @name only pings when a configured mentionAliases entry rewrites it. (extensions/discord/src/channel.ts:310, aef93881af5f)
  • User docs describe deterministic mentionAliases: The public Discord docs document mentionAliases as the deterministic outbound mention mechanism and say unknown handles, reserved mentions, and code-span mentions are left unchanged. Public docs: docs/channels/discord.md. (docs/channels/discord.md:977, aef93881af5f)
  • Current main still uses ASCII mention candidates: The current implementation keeps the Discord outbound mention candidate regex limited to ASCII handles, matching the related maintainer decision rather than this PR's Unicode rewrite direction. (extensions/discord/src/mentions.ts:11, aef93881af5f)
  • Current main keeps cache lookup account-scoped: The resolver only reads the normalized account cache and returns undefined on a miss, so current main does not have the PR's cross-account fallback behavior. (extensions/discord/src/directory-cache.ts:95, aef93881af5f)
  • Related maintainer decision supersedes this direction: The related Unicode Discord mention PR was closed on 2026-05-17 after a member commented that Discord mentions are always ASCII and the existing regex is correct. (12d90ed76d41)
  • Live PR state is not merge-ready: GitHub reports this PR as open but conflicting, with maintainer edits allowed and no assignees or pending review requests. (c8db5d714b93)

Likely related people:

  • thewilloftheshadow: Authored the merged Discord mention-handling work that added the mention helper and directory cache, and later gave the related Unicode mention decision signal. (role: introduced behavior and recent reviewer; confidence: high; commits: d493861c1692; files: extensions/discord/src/mentions.ts, extensions/discord/src/directory-cache.ts, extensions/discord/src/send.outbound.ts)
  • steipete: Current-main blame ties the present mention helper, account-scoped resolver, and bot identity startup shape to recent Discord area work. (role: recent area contributor; confidence: medium; commits: 1c3ff34d752f, 2f43c6b334f8; files: extensions/discord/src/mentions.ts, extensions/discord/src/directory-cache.ts, extensions/discord/src/monitor/provider.startup.ts)
  • scoootscooob: Moved the Discord implementation from src/discord into extensions/discord, including the mention and directory-cache files this PR touches. (role: major refactor carrier; confidence: medium; commits: 5682ec37fada; files: extensions/discord/src/mentions.ts, extensions/discord/src/directory-cache.ts, extensions/discord/src/monitor/message-handler.preflight.ts)

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

@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 19, 2026
@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 19, 2026
@clawsweeper clawsweeper Bot added P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. labels May 19, 2026
@clawsweeper

clawsweeper Bot commented May 19, 2026

Copy link
Copy Markdown
Contributor

ClawSweeper applied the proposed close for this PR.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

channel: discord Channel integration: discord 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. merge-risk: 🚨 security-boundary 🚨 May affect sandboxing, authorization, credentials, or sensitive data. P3 Low-priority cleanup, docs, polish, ergonomics, or speculative work. 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-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.

2 participants