Skip to content

fix(discord): keep code fences intact when rebalancing reasoning italics - #103166

Merged
steipete merged 1 commit into
openclaw:mainfrom
wuqxuan:grok/discord-italics-code-fence-rebalance
Jul 28, 2026
Merged

steipete merged 1 commit into
openclaw:mainfrom
wuqxuan:grok/discord-italics-code-fence-rebalance

Conversation

@wuqxuan

@wuqxuan wuqxuan commented Jul 9, 2026 •

Copy link
Copy Markdown
Contributor

Closes #102911

What Problem This Solves

Fixes an issue where Discord reasoning messages that wrap content in _…_ would corrupt markdown code fences and inline code when the message was split across chunks. After a chunk boundary that started with a code delimiter, the italics rebalancer could prepend _ (breaking _```python / _~~~ / _code``) or leave unmatched trailing _ on continuation chunks.

Why This Change Was Made

rebalanceReasoningItalics still closes/reopens reasoning italics so each Discord message stays independently balanced. When the next chunk starts with a code delimiter:

  1. Do not prepend _ onto the code opener.
  2. Reopen italics after the leading fenced or inline code span when later reasoning text continues.
  3. Drop a lone trailing _ on pure-code continuations.
  4. Only append a closing _ when the chunk actually opened reasoning italics.

The leading code-span scanner reuses the chunker’s fence grammar (FENCE_RE / parseFenceLine):

  • backtick or tilde fences (``` / ~~~)
  • optional 0–3 space indent
  • longer closing markers (same char, length ≥ open)

Also restores main’s strict-index guards (expectDefined, charAt) so the Discord package typecheck and knip production export scan stay green after the main refresh, and keeps chunkDiscordText unexported (tests use chunkDiscordTextWithMode).

Regression tests assert exact second-chunk output and even _ counts for backtick, tilde, indented, longer-close, inline, and pure-code cases.

User Impact

Discord reasoning/thinking replies that contain code blocks or inline code no longer break markdown fences at chunk boundaries, including tilde and indented fences, and each chunk keeps balanced reasoning italics when text continues after code.

Evidence

Focused tests (exact head 529b4bc3006)

$ node scripts/run-vitest.mjs extensions/discord/src/chunk.test.ts

 Test Files  1 passed (1)
      Tests  24 passed (24)

Production-path harness at exact head 529b4bc3006

API: chunkDiscordTextWithMode({ chunkMode: "length" }) → rebalanceReasoningItalics
Opts: { maxLines: 10, maxChars: 2000 }

Exact second chunks:

tilde+more:     "~~~python\nprint(1)\n~~~\n_more reasoning_"
indent+more:    "  ```python\nprint(1)\n  ```\n_more reasoning_"
long-close+more:"```python\nprint(1)\n````\n_more reasoning_"
backtick pure:  "```python\nprint(1)\n```"
inline+after:   "`inline_code_token`\n_10. after_"
normal continue:"_10. line\n11. line\n12. line_"

All cases: 2 chunks; every chunk has an even _ count; no second chunk starts with _``` / _~~~ / _``.

CI surface fixes on this head

  • noUncheckedIndexedAccess: window.charAt(i), expectDefined for segment/chunk indexes (aligned with main)
  • knip production: stop exporting internal chunkDiscordText (production callers already use chunkDiscordTextWithMode)

Real behavior proof

  • Behavior addressed: Discord reasoning-italics rebalance protects code-leading openers using the full chunker fence grammar and keeps per-message _ balance.
  • Environment: local macOS, OpenClaw checkout, Node 24; production helper path chunkDiscordTextWithMode → internal length chunker → rebalanceReasoningItalics. Verification host: local macOS.
  • Exact head exercised: 529b4bc3006f4d22f4dd76589f45933ac0768d0f
  • Exact steps or command run after this patch:
    1. node --import tsx harness for tilde, indented, longer-close, pure fence, inline, and normal-text fixtures
    2. node scripts/run-vitest.mjs extensions/discord/src/chunk.test.ts (24/24)
  • Evidence after fix: exact second-chunk JSON outputs above from head 529b4bc3006; all even _ parity.
  • Control check: normal multi-chunk reasoning still reopens with leading _ on non-code continuations ("_10. line\n11. line\n12. line_").
  • Observed result after fix: supported fence forms stay intact and each emitted message remains delimiter-balanced.
  • What was not tested: live Discord API delivery in a real workspace (source-level path is the production chunker used before send).

AI disclosure

This fix was authored with AI assistance (Grok). Implementation, tests, and proof were verified against ClawSweeper review findings on #103166 (exact-head runtime proof; typecheck/knip CI on the Discord chunk surface).

@openclaw-barnacle openclaw-barnacle Bot added channel: discord Channel integration: discord size: XS labels Jul 9, 2026
@wuqxuan

wuqxuan commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. P2 Normal backlog priority with limited blast radius. labels Jul 10, 2026
@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

Codex review: needs maintainer review before merge. Reviewed July 18, 2026, 11:57 PM ET / July 19, 2026, 03:57 UTC.

Summary
The branch adjusts Discord reasoning-italic rebalancing so code-leading continuation chunks preserve fenced and inline-code delimiters while later reasoning prose remains balanced.

PR surface: Source +89, Tests +98. Total +187 across 2 files.

Reproducibility: unclear. for an independently repeated current-main live Discord run; the source-level production helper path and reported base-versus-head regression test provide a concrete, medium-confidence reproduction boundary.

Review metrics: none identified.

Root-cause cluster
Relationship: fixed_by_candidate
Canonical: #102911
Summary: This PR is the active candidate fix for the open canonical Discord code-fence rebalance regression.

Members:

Proposal only: this assessment does not dispatch repair, suppress jobs, mutate sibling items, close, or merge anything.

Merge readiness
Overall: 🐚 platinum hermit
Proof: 🦞 diamond lobster
Patch quality: 🐚 platinum hermit
Result: ready for maintainer review.

Overall follows the weaker of proof and patch quality, so missing proof can cap an otherwise strong patch.

Rank-up moves:

  • Confirm the focused Discord chunk fixtures on the final merge result because the branch is behind current main.

Risk before merge

  • [P1] This changes Discord message-boundary formatting; maintainers should verify the focused fixtures against the final merge result because the branch is reported behind current main despite being cleanly mergeable.

Maintainer options:

  1. Verify the final merge-result fixtures (recommended)
    Refresh the focused Discord chunk proof on the merge result, covering fenced, inline, and normal continuation output before landing.
  2. Accept the bounded formatting risk
    Merge with the existing exact-head harness and focused regression coverage if maintainers judge the current merge result equivalent on this isolated formatter path.

Next step before merge

  • [P2] No narrow mechanical repair remains; the next action is maintainer review of this proof-positive implementation PR and its final merge result.

Security
Cleared: The two-file Discord formatter/test change adds no dependency, workflow, permission, secret, artifact-download, or package-resolution surface.

Review details

Best possible solution:

Merge the bounded fix after a maintainer confirms the final merge result preserves the exact code-leading continuation fixtures and ordinary non-code italic continuation behavior.

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

Unclear for an independently repeated current-main live Discord run; the source-level production helper path and reported base-versus-head regression test provide a concrete, medium-confidence reproduction boundary.

Is this the best way to solve the issue?

Yes, provisionally: reusing the chunker fence grammar and inserting any italic reopen after a leading code span is narrower and more maintainable than special-casing individual delimiter forms.

AGENTS.md: found and applied where relevant.

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

Label changes

Label justifications:

  • P2: The PR repairs a user-visible Discord formatting regression with limited blast radius in a channel-local chunking path.
  • merge-risk: 🚨 message-delivery: Changing chunk-boundary delimiter handling can alter how Discord renders or segments reasoning messages even when focused tests pass.
  • rating: 🐚 platinum hermit: Overall readiness is 🐚 platinum hermit; proof is 🦞 diamond lobster and patch quality is 🐚 platinum hermit.
  • status: 👀 ready for maintainer look: ClawSweeper has no concrete contributor-facing blocker left for this PR. Sufficient (terminal): The PR provides exact-head terminal output from the production chunking helper plus focused passing regression tests; no live Discord workspace proof is needed to observe this deterministic formatter result.
  • proof: sufficient: Contributor real behavior proof is sufficient. The PR provides exact-head terminal output from the production chunking helper plus focused passing regression tests; no live Discord workspace proof is needed to observe this deterministic formatter result.
Evidence reviewed

PR surface:

Source +89, Tests +98. Total +187 across 2 files.

View PR surface stats
Area Files Added Removed Net
Source 1 143 54 +89
Tests 1 162 64 +98
Docs 0 0 0 0
Config 0 0 0 0
Generated 0 0 0 0
Other 0 0 0 0
Total 2 305 118 +187

What I checked:

  • Linked canonical bug remains open: The PR body links the open canonical report, whose described failure is the same code-fence corruption at a Discord chunk boundary; an open implementation PR should not close the issue before merge. (extensions/discord/src/chunk.ts, 529b4bc3006f)
  • Focused regression coverage: The PR supplies exact-output cases for backtick, tilde, indented, longer-close, inline-code, and pure-code continuations, plus the focused Discord chunk test result of 24 passing tests at the current head. (extensions/discord/src/chunk.test.ts, 529b4bc3006f)
  • Current review-cycle continuity: The immediately previous ClawSweeper review at the same head recorded no remaining discrete finding after the earlier fence-balance and shared-fence-grammar findings were addressed. (extensions/discord/src/chunk.ts, 529b4bc3006f)
  • Independent failing-first report: A reviewer reported the new indented-fence regression test fails on the base behavior and passes with this branch, supporting that the change targets a real boundary defect rather than only adding a redundant path. (extensions/discord/src/chunk.test.ts, 529b4bc3006f)
  • CI and security surface: Provided check data shows the repository CI gate, production types, lint, dependency guard, and CodeQL/Opengrep surfaces completed without a reported failure on this PR head. (529b4bc3006f)

Likely related people:

  • knoal: Provided an A/B regression check showing the new indented-fence case fails against the base behavior and passes with this implementation. (role: reviewer; confidence: low; files: extensions/discord/src/chunk.ts, extensions/discord/src/chunk.test.ts)
What the crustacean ranks mean
  • 🦀 challenger crab: rare, exceptional readiness with strong proof, clean implementation, and convincing validation.
  • 🦞 diamond lobster: very strong readiness with only minor maintainer review expected.
  • 🐚 platinum hermit: good normal PR, likely mergeable with ordinary maintainer review.
  • 🦐 gold shrimp: useful signal, but proof or patch confidence is still limited.
  • 🦪 silver shellfish: thin signal; proof, validation, or implementation needs work.
  • 🧂 unranked krab: not merge-ready because proof is missing/unusable or there are serious correctness or safety concerns.
  • 🌊 off-meta tidepool: rating does not apply to this item.

Shiny media proof means a screenshot, video, or linked artifact directly shows the changed behavior. Runtime, network, CSP, and security claims still need visible diagnostics.

How this review workflow works
  • ClawSweeper keeps one durable marker-backed review comment per issue or PR.
  • Re-runs edit this comment so the latest verdict, findings, and automation markers stay together instead of adding duplicate bot comments.
  • A fresh review can be triggered by eligible @clawsweeper re-review comments, exact-item GitHub events, scheduled/background review runs, or manual workflow dispatch.
  • PR/issue authors and users with repository write access can comment @clawsweeper re-review or @clawsweeper re-run on an open PR or issue to request a fresh review only.
  • Maintainers can also comment @clawsweeper review to request a fresh review only.
  • Fresh-review commands do not start repair, autofix, rebase, CI repair, or automerge.
  • Maintainer-only repair and merge flows require explicit commands such as @clawsweeper autofix, @clawsweeper automerge, @clawsweeper fix ci, or @clawsweeper address review.
  • Maintainers can comment @clawsweeper explain to ask for more context, or @clawsweeper stop to stop active automation.
Review history (6 earlier review cycles)
  • reviewed 2026-07-10T07:40:08.039Z sha dc6ca79 :: needs changes before merge. :: [P2] Balance the backtick-leading continuation chunk
  • reviewed 2026-07-10T12:18:08.887Z sha bea0744 :: needs changes before merge. :: [P2] Reuse the chunker’s full fence grammar
  • reviewed 2026-07-10T13:45:18.081Z sha 1d5120c :: needs maintainer review before merge. :: none
  • reviewed 2026-07-19T01:46:18.677Z sha 15baa02d985c84780d185c9a5a8b0c2c483118a5 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-19T02:29:04.843Z sha 15baa02d985c84780d185c9a5a8b0c2c483118a5 :: needs real behavior proof before merge. :: none
  • reviewed 2026-07-19T03:15:40.695Z sha 529b4bc3006f4d22f4dd76589f45933ac0768d0f :: needs maintainer review before merge. :: none

@wuqxuan

wuqxuan commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

Addressed ClawSweeper P2 on incomplete balancing:

  • Protect leading code delimiter (no _``` / _code)
  • Reopen reasoning italics after the fenced/inline span when text continues
  • Drop lone trailing _ on pure-code continuations
  • Close only when the chunk actually opened italics
  • Tests assert exact second-chunk output + even _ counts (20/20)

Head: 01059b586

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

@wuqxuan

wuqxuan commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

Re-review request (current head)

Head: bea0744d8 (balance fix at 01059b586 + empty CI retrigger).

Previous ClawSweeper P2 is addressed:

  1. Protect code opener — no _``` / _code prepend
  2. Reopen after leading fenced/inline span when reasoning text continues
  3. Drop lone trailing _ on pure-code continuations
  4. Close only if the chunk actually opened reasoning italics
  5. Tests — exact second-chunk output + even _ counts (20/20)

Local gates: focused vitest PASS, check:changed PASS, test:changed PASS. OpenGrep CI pass after retrigger.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. merge-risk: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. and removed rating: 🦪 silver shellfish Thin PR readiness signal; proof, validation, or implementation needs work. labels Jul 10, 2026
@wuqxuan

wuqxuan commented Jul 10, 2026

Copy link
Copy Markdown
Contributor Author

Re-review: full fence grammar alignment

Head: 1d5120c8d

Addressed ClawSweeper P2 (Reuse the chunker’s full fence grammar):

  • leadingCodeSpanEnd now uses parseFenceLine / FENCE_RE (same as the chunker)
  • Supports tilde fences, 0–3 space indent, longer closers (len ≥ open)
  • Reopen still happens after the code span; pure-code drops lone trailing _
  • Exact-output tests added for tilde, indented, and longer-close (+ prior backtick/inline)

Local: 24/24 vitest, check:changed PASS, test:changed PASS.

@clawsweeper re-review

@clawsweeper

clawsweeper Bot commented Jul 10, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: ⏳ waiting on author ClawSweeper has contributor-facing work open and is waiting for author action. labels Jul 10, 2026
@wuqxuan
wuqxuan force-pushed the grok/discord-italics-code-fence-rebalance branch from 1d5120c to 15baa02 Compare July 19, 2026 01:42
@wuqxuan

wuqxuan commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Refreshed this branch onto current main via merge (non-force push) after all conflicts were resolved.

  • Previous head: 1d5120c8db80
  • New head: 15baa02d985c

@clawsweeper

clawsweeper Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. and removed proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. labels Jul 19, 2026
@wuqxuan

wuqxuan commented Jul 19, 2026

Copy link
Copy Markdown
Contributor Author

@clawsweeper re-review

Refreshed exact-head proof for chunkDiscordTextWithMode code-leading continuation chunks (tilde, indented fence, longer close, pure fence, inline, normal text) at 529b4bc3006, with 24/24 focused tests green.

Also fixed Discord package typecheck / knip CI on this surface: restored expectDefined / charAt strict-index guards and kept chunkDiscordText unexported so production uses only chunkDiscordTextWithMode.

@clawsweeper

clawsweeper Bot commented Jul 19, 2026 •

Copy link
Copy Markdown
Contributor

🦞🧹
ClawSweeper re-review requested.

I asked ClawSweeper to review this item again.
Action: item re-review queued (workflow sweep.yml, event repository_dispatch).
Result: the existing ClawSweeper review comment will be edited in place when the review finishes.

Re-review progress:

@clawsweeper clawsweeper Bot added proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR. and removed rating: 🦐 gold shrimp Decent PR readiness signal, but merge confidence is limited. status: 📣 needs proof The PR needs real behavior proof before ClawSweeper can clear the contributor ask. labels Jul 19, 2026
@steipete steipete self-assigned this Jul 28, 2026
@steipete
steipete force-pushed the grok/discord-italics-code-fence-rebalance branch from 529b4bc to 5b0cfcb Compare July 28, 2026 19:16
@steipete
steipete merged commit 5838f31 into openclaw:main Jul 28, 2026
177 of 181 checks passed
@steipete

Copy link
Copy Markdown
Contributor

Merged via squash.

vincentkoc added a commit that referenced this pull request Jul 28, 2026
…etwork-none

* origin/main: (74 commits)
  fix(ui): make Control UI ownership and permissions reliable (#115364)
  feat(system-agent): host memory import in Ask OpenClaw (#115376)
  fix(chat): preserve literal Markdown image examples (#113904)
  refactor(chat): keep web and terminal sessions synchronized (#115377)
  fix(ui): order model picker by provider strength (#115380)
  feat(ui): make Memory settings a destination page with live overview and dreams (#115383)
  docs(security): fix warning line wrap (#115388)
  fix(memory-core): avoid cubic MMR similarity rescans (#113359)
  fix(discord): preserve code-leading reasoning chunks (#103166)
  fix(slack): protect outbound hooks from previews
  fix(ui): keep explicit navigation ahead of chat canonicalization (#115366)
  fix(exec): safely cancel pending node approvals (#115373)
  fix: make Code Mode reliable across gateway and provider lifecycles (#115379)
  perf(ui): debounce event-driven session list refreshes and right-size child paging (#115374)
  feat(talk): support GPT-Live realtime voice over ChatGPT OAuth (#115226)
  feat(system-agent): guide gateway configuration in Ask OpenClaw (#115363)
  fix(agents): make overflow recovery append-only via branch-and-reappend (#115271) (#115310)
  fix(macos): bound websocket ping so a dropped pong cannot orphan its continuation (#115362)
  fix(codex): isolate native hook relay startup (#115078)
  fix(ci): stop reviving superseded pull request workflows (#115378)
  ...

# Conflicts:
#	CHANGELOG.md
github-actions Bot pushed a commit to Desicool/openclaw that referenced this pull request Jul 29, 2026
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: 🚨 message-delivery 🚨 May drop, duplicate, misroute, suppress, or wrongly target messages. P2 Normal backlog priority with limited blast radius. proof: sufficient ClawSweeper judged the real behavior proof convincing. rating: 🐚 platinum hermit Good normal PR readiness with ordinary maintainer review expected. size: S status: 👀 ready for maintainer look ClawSweeper has no concrete contributor-facing blocker left for this PR.

Projects

None yet

Development

Successfully merging this pull request may close these issues.

markdown code blocks broken by italics rebalancing in chunkDiscordText

2 participants