Repository navigation
fix: preserve markdown formatting across Discord chunk boundaries - #63460
jakepresent wants to merge 57 commits into
Conversation
Greptile SummaryThis PR adds blockquote prefix re-application, table header repetition, and inline marker balancing across chunk boundaries for Discord message delivery. It also fixes the The overall approach is well-structured — new span parsers are clean and the fence-parallel pattern is extended consistently. The implementation is generally solid but a handful of edge cases flagged during review remain unresolved. Confidence Score: 4/5Functionally sound for the common cases, but a few edge-case correctness issues flagged in review remain open before this should land. The core chunker integration is clean, the blockquotes/table-spans/inline-formatting modules are well-structured, and the convertMarkdownTables blockquote-stripping fix is correct. However, review threads identified concrete P1 issues that have not been addressed in the current diff: the blockquote span parser stores the last prefix depth rather than the initial one (corrupting re-prefixing when depth changes mid-block), and the Discord chunker loses the table header when a flush fires between the header candidate line and the separator line. These are real rendering bugs for inputs that trigger the edge cases, which keeps the score at 4 rather than 5. src/markdown/blockquotes.ts (prefix depth mutation) and extensions/discord/src/chunk.ts (flush between header and separator).
|
| if (current) { | ||
| spans.push({ | ||
| start: current.start, | ||
| end: offset > 0 ? offset - 1 : offset, |
There was a problem hiding this comment.
Varying blockquote depth corrupts reapplied prefix
current.prefix is updated to the last seen depth in a block, so a block that goes > line1 then >> line2 stores prefix = ">> ". If the split happens after line2 and the continuation opens with a > line3 (back to single depth), reapplyBlockquotePrefix checks line3.startsWith(">") against ">>".trimEnd() → ">>" — that fails, so >> is prepended, producing >> > line3 instead of > line3.
Consider capturing the initial prefix (first line of the block) rather than mutating it on every line, or tracking a set of active depths and applying only the matching one per line.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/markdown/blockquotes.ts
Line: 37-40
Comment:
**Varying blockquote depth corrupts reapplied prefix**
`current.prefix` is updated to the *last* seen depth in a block, so a block that goes `> line1` then `>> line2` stores `prefix = ">> "`. If the split happens after `line2` and the continuation opens with a `> line3` (back to single depth), `reapplyBlockquotePrefix` checks `line3.startsWith(">")` against `">>"`.trimEnd() → `">>"` — that fails, so `>> ` is prepended, producing `>> > line3` instead of `> line3`.
Consider capturing the *initial* prefix (first line of the block) rather than mutating it on every line, or tracking a set of active depths and applying only the matching one per line.
How can I resolve this? If you propose a fix, please make it concise.| if (!wasInsideFence) { | ||
| if (pendingTableHeader && TABLE_SEPARATOR_RE.test(originalLine.trim())) { | ||
| // Confirmed: previous line was header, this line is separator | ||
| openTable = { headerLine: lastLineWasTableCandidate, separatorLine: originalLine }; | ||
| pendingTableHeader = false; | ||
| lastLineWasTableCandidate = ""; | ||
| } else if (openTable && originalLine.includes("|")) { | ||
| // Still inside a table (data row) | ||
| } else if (originalLine.includes("|") && !openTable) { | ||
| // Potential table header - stash it and check next line | ||
| pendingTableHeader = true; | ||
| lastLineWasTableCandidate = originalLine; | ||
| } else { | ||
| // Not a table line - clear table state | ||
| openTable = null; | ||
| pendingTableHeader = false; | ||
| lastLineWasTableCandidate = ""; |
There was a problem hiding this comment.
Table-row detection is more permissive than
parseTableSpans.isTableRow
parseTableSpans.isTableRow (used by the core chunker) requires | at both ends of a trimmed line, which avoids false positives. Discord's local heuristic uses originalLine.includes("|"), so any line containing a | — e.g. a sentence like "Option A | Option B described here" — can be mistaken for a table header candidate. If the next line happens to match TABLE_SEPARATOR_RE (e.g. a list item | --- |), openTable is set for a non-table block.
Adopting the same both-ends check used in table-spans.ts would make detection consistent:
| if (!wasInsideFence) { | |
| if (pendingTableHeader && TABLE_SEPARATOR_RE.test(originalLine.trim())) { | |
| // Confirmed: previous line was header, this line is separator | |
| openTable = { headerLine: lastLineWasTableCandidate, separatorLine: originalLine }; | |
| pendingTableHeader = false; | |
| lastLineWasTableCandidate = ""; | |
| } else if (openTable && originalLine.includes("|")) { | |
| // Still inside a table (data row) | |
| } else if (originalLine.includes("|") && !openTable) { | |
| // Potential table header - stash it and check next line | |
| pendingTableHeader = true; | |
| lastLineWasTableCandidate = originalLine; | |
| } else { | |
| // Not a table line - clear table state | |
| openTable = null; | |
| pendingTableHeader = false; | |
| lastLineWasTableCandidate = ""; | |
| } else if (originalLine.includes("|") && !openTable) { | |
| // Potential table header - require | at both ends (mirrors parseTableSpans.isTableRow) | |
| const trimmed = originalLine.trim(); | |
| if (trimmed.startsWith("|") && trimmed.endsWith("|")) { | |
| pendingTableHeader = true; | |
| lastLineWasTableCandidate = originalLine; | |
| } | |
| } else { |
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/chunk.ts
Line: 213-229
Comment:
**Table-row detection is more permissive than `parseTableSpans.isTableRow`**
`parseTableSpans.isTableRow` (used by the core chunker) requires `|` at *both* ends of a trimmed line, which avoids false positives. Discord's local heuristic uses `originalLine.includes("|")`, so any line containing a `|` — e.g. a sentence like "Option A | Option B described here" — can be mistaken for a table header candidate. If the *next* line happens to match `TABLE_SEPARATOR_RE` (e.g. a list item `| --- |`), `openTable` is set for a non-table block.
Adopting the same both-ends check used in `table-spans.ts` would make detection consistent:
```suggestion
} else if (originalLine.includes("|") && !openTable) {
// Potential table header - require | at both ends (mirrors parseTableSpans.isTableRow)
const trimmed = originalLine.trim();
if (trimmed.startsWith("|") && trimmed.endsWith("|")) {
pendingTableHeader = true;
lastLineWasTableCandidate = originalLine;
}
} else {
```
How can I resolve this? If you propose a fix, please make it concise.| * Only includes parent levels (not the current item, which will be in the text). | ||
| */ | ||
| export function buildListContextPrefix(context: ListContext): string { | ||
| if (context.levels.length <= 1) { | ||
| return ""; | ||
| } | ||
| // Include all parent levels except the last (which is the current item's level) | ||
| return ( | ||
| context.levels | ||
| .slice(0, -1) | ||
| .map((level) => `${level}...`) | ||
| .join("\n") + "\n" |
There was a problem hiding this comment.
buildListContextPrefix emits literal ... into the message
The PR notes that detectListContext is "scaffolded for future integration," so this function is not yet wired up. When it is, the ... appended to each parent level (${level}...) will appear verbatim in the Discord message — e.g. - .... That is not valid Markdown and will confuse readers. If the intent is a visual ellipsis placeholder for omitted content, it should be removed or replaced before this is integrated, or the comment should make the placeholder nature explicit so it is not shipped as-is.
Prompt To Fix With AI
This is a comment left during a code review.
Path: src/markdown/lists.ts
Line: 56-67
Comment:
**`buildListContextPrefix` emits literal `...` into the message**
The PR notes that `detectListContext` is "scaffolded for future integration," so this function is not yet wired up. When it is, the `...` appended to each parent level (`${level}...`) will appear verbatim in the Discord message — e.g. `- ...`. That is not valid Markdown and will confuse readers. If the intent is a visual ellipsis placeholder for omitted content, it should be removed or replaced before this is integrated, or the comment should make the placeholder nature explicit so it is not shipped as-is.
How can I resolve this? If you propose a fix, please make it concise.|
@greptile review |
|
Tip: Greploop — Automatically fix all review issues by running Use the Greptile plugin for Claude Code to query reviews, search comments, and manage custom context directly from your terminal. |
| if (pendingTableHeader && TABLE_SEPARATOR_RE.test(originalLine.trim())) { | ||
| // Confirmed: previous line was header, this line is separator | ||
| openTable = { headerLine: lastLineWasTableCandidate, separatorLine: originalLine }; | ||
| pendingTableHeader = false; | ||
| lastLineWasTableCandidate = ""; | ||
| } else if (openTable && originalLine.trim().startsWith("|") && originalLine.trim().endsWith("|")) { | ||
| // Still inside a table (data row) | ||
| } else if (originalLine.trim().startsWith("|") && originalLine.trim().endsWith("|") && !openTable) { | ||
| // Potential table header - stash it and check next line | ||
| pendingTableHeader = true; | ||
| lastLineWasTableCandidate = originalLine; | ||
| } else { | ||
| // Not a table line - clear table state | ||
| openTable = null; | ||
| pendingTableHeader = false; | ||
| lastLineWasTableCandidate = ""; | ||
| } | ||
| } |
There was a problem hiding this comment.
Table header lost when flush occurs between header and separator
When flush() fires after the potential table header line (but before the separator is processed), openTable is still null at flush time, so flush() cannot repeat the header. The separator line then becomes the first line of the new chunk, producing a headerless table.
Concretely: if the chunk boundary lands right after | Col A | Col B |, the next chunk begins with | --- | --- | followed by data rows — the header row never appears in the continuation chunk.
A minimal fix is to treat a confirmed pendingTableHeader the same as an already-confirmed openTable inside flush():
// Inside flush(), after the openTable reopen block:
if (pendingTableHeader && lastLineWasTableCandidate && !openFence) {
// We have a candidate header but haven't seen the separator yet.
// Repeat the candidate so the separator that follows lands in context.
current = lastLineWasTableCandidate;
currentLines = 1;
}Alternatively, eagerly emit the header-only placeholder and let the separator / data rows follow it naturally into the new chunk.
Prompt To Fix With AI
This is a comment left during a code review.
Path: extensions/discord/src/chunk.ts
Line: 214-231
Comment:
**Table header lost when flush occurs between header and separator**
When `flush()` fires after the potential table header line (but before the separator is processed), `openTable` is still `null` at flush time, so `flush()` cannot repeat the header. The separator line then becomes the first line of the new chunk, producing a headerless table.
Concretely: if the chunk boundary lands right after `| Col A | Col B |`, the next chunk begins with `| --- | --- |` followed by data rows — the header row never appears in the continuation chunk.
A minimal fix is to treat a confirmed `pendingTableHeader` the same as an already-confirmed `openTable` inside `flush()`:
```typescript
// Inside flush(), after the openTable reopen block:
if (pendingTableHeader && lastLineWasTableCandidate && !openFence) {
// We have a candidate header but haven't seen the separator yet.
// Repeat the candidate so the separator that follows lands in context.
current = lastLineWasTableCandidate;
currentLines = 1;
}
```
Alternatively, eagerly emit the header-only placeholder and let the separator / data rows follow it naturally into the new chunk.
How can I resolve this? If you propose a fix, please make it concise.|
@greptile review |
1f1da21 to
068049b
Compare
|
@greptile review |
87d062d to
6612ef2
Compare
…ugin root When a packaged bundled plugin's `pluginRoot` is used directly as the npm execution cwd, `npm install <specs>` resolves the plugin's own `package.json` as the project manifest and fails with `EUNSUPPORTEDPROTOCOL: Unsupported URL Type "workspace:": workspace:*` whenever that manifest declares a `workspace:` runtime dep (e.g. `"@openclaw/plugin-sdk": "workspace:*"`). This takes out every plugin with any runtime deps at gateway startup. `ensureBundledPluginRuntimeDeps` already filters `workspace:` specs from the CLI arguments, but npm's own resolver reads the cwd manifest regardless, so the filter alone is not enough. The existing isolated execution-root + `replaceNodeModulesDir` machinery handles this exact problem for source-checkout + cache-hit installs. This change activates the same staging path for the packaged case: when `installRoot === pluginRoot` and we are not in the source-checkout cache path, stage the install inside `<pluginRoot>/.openclaw-install-stage` (which has a minimal generated `package.json`) and move the produced `node_modules/` back to the plugin root as before. - Add regression test `stages plugin-root install when the plugin's own package.json declares workspace:* deps` covering the Docker scenario (mixed `workspace:*` + concrete runtime dep, e.g. anthropic-style `@openclaw/plugin-sdk` + `@anthropic-ai/sdk`). - Update existing plugin-root-install expectations (`installs plugin-local runtime deps when one is missing`, `skips workspace-only runtime deps before npm install`, `installs deps that are only present in the package root`, `does not trust runtime deps that only resolve from the package root`, `does not treat sibling extension runtime deps as satisfying a plugin`) to assert the new `installExecutionRoot`. Reported in openclaw#70844; same root cause as openclaw#70701, openclaw#70756, openclaw#70773, openclaw#70818, openclaw#70839 which see the downstream "Cannot find package 'openclaw' from plugin-runtime-deps" symptom because their `resolveBundledRuntimeDependencyInstallRoot` resolves to an external stage dir (clean manifest) so the install succeeds but the resulting node_modules tree cannot satisfy the filtered-out workspace packages at ESM import time. ## AI assistance This PR was AI-assisted with Claude Code. Testing degree: fully tested for the touched `bundled-runtime-deps` install staging surface. - `pnpm exec vitest run --config test/vitest/vitest.plugins.config.ts src/plugins/bundled-runtime-deps.test.ts` (31/31) - `pnpm exec vitest run --config test/vitest/vitest.plugins.config.ts src/plugins/` (43/43 across 8 files) - `pnpm exec tsgo --noEmit -p tsconfig.core.json`, `pnpm exec tsgo --noEmit -p tsconfig.core.test.json` (clean) - `pnpm exec oxlint src/plugins/bundled-runtime-deps.ts src/plugins/bundled-runtime-deps.test.ts` (0 warnings, 0 errors) - `node scripts/check-src-extension-import-boundary.mjs --json` and `node scripts/check-sdk-package-extension-import-boundary.mjs --json` (both `[]`) I understand the code path changed here: packaged bundled plugins now stage their runtime-dep install one directory below `pluginRoot` so npm never reads the plugin's `workspace:*`-containing manifest during install; after install completes, the produced `node_modules/` is moved back to `pluginRoot` via the existing `replaceNodeModulesDir` helper. Signed-off-by: Simone Macario <[email protected]>
Fixes openclaw#63409. Related: openclaw#31679 openclaw#24363 openclaw#32743 openclaw#30962 When OpenClaw delivers long messages to Discord, the chunking pipeline splits text at 2000-character boundaries. Each chunk renders independently, so formatting that spans a chunk boundary breaks: tables get split mid-row, blockquotes lose their > prefix in continuation chunks, and inline formatting (bold, code) can get orphaned across splits. Extends the existing fence-aware chunking pattern to handle additional markdown structures in both the core chunker (chunkMarkdownText) and the Discord-specific chunker (chunkDiscordText). - parseTableSpans() detects table blocks (header + separator + data rows) - Tables are treated as atomic spans; the chunker avoids splitting inside them - If a table exceeds the limit, the header + separator are repeated in the continuation chunk via reopenTableHeader - isTableRow requires | at both start and end of trimmed line to avoid false positives from prose lines containing pipe characters - parseTableSpans accepts fenceSpans to skip table-like content in code fences - parseBlockquoteSpans() detects > -prefixed regions and tracks prefix depth - When splitting inside a blockquote, reapplyBlockquotePrefix() adds > to every line in the continuation chunk, bounded to the span end - convertMarkdownTables in tables.ts now accepts a blockquotePrefix parameter so blockquotes survive the IR re-render when messages contain both a table and a blockquote (all three Discord call sites pass "> ") - scanUnmatchedInlineMarkers() finds unmatched **, *, backtick at chunk ends - Closes unmatched markers before the split and reopens them after - _ markers skip word-boundary positions (before and after) to avoid mangling snake_case identifiers - detectListContext() scaffolded for future integration - Added blockquote prefix tracking and reapplication after flush() - Added table header repetition after flush() - Blockquote prefix is only applied when current chunk is empty (after flush), not on every intra-line segment continuation - 12 new tests in chunk.test.ts - Verified live on Discord with messages forcing splits across tables, blockquotes, and inline spans
…hunker The blockquote prefix was applied to segment after addition was computed, so current += addition used the stale un-prefixed value when current was non-empty (e.g. after fence/table reopen). Recompute addition after mutating segment so the prefixed value is always used. Also tighten Discord chunker table-row detection to match parseTableSpans: require | at both start and end of trimmed line to avoid false positives.
…between header and separator
… fences Discord renders blockquote bars only for each physical line, so long > paragraphs lose the bar after the first visual wrap. Pre-split long blockquote lines at word boundaries (~80 chars) so every physical line gets its own > prefix. When a code-fenced table splits across chunks, repeat the table header and separator rows in the continuation chunk so the data rows have column context. This handles the common case where convertMarkdownTables wraps tables in code fences before the chunker sees them.
…oundaries When bold, italic, or code markers span chunk boundaries, close them at the end of the current chunk and reopen at the start of the next so Discord renders each chunk with correct formatting. Implemented as a post-processing pass (rebalanceInlineFormatting) that scans each chunk for unmatched markers and appends close/reopen tokens. The marker scanner is inlined since the plugin SDK doesn't export the core inline-formatting utilities.
e617c61 to
69b11c9
Compare
|
Codex review: found issues before merge. What this changes: The PR adds shared and Discord-specific Markdown chunking support for blockquotes, tables, and inline formatting, threads blockquote-aware table conversion through Discord delivery, and carries additional release, CI, provider, plugin-runtime, docs, and test-harness changes. Maintainer follow-up before merge: Maintainer review is needed to request a narrow rebase/replacement or coordinate with overlapping PRs; the remaining blocker is not just a mechanical patch because the branch is broad, stale, and security-sensitive. Security review: Security review needs attention: The Markdown fix itself is text formatting work, but the PR context includes unrelated CI, provider trust, and runtime dependency execution changes that need separate review or a narrow rebase. Review findings:
Review detailsBest possible solution: Land a narrow, rebased fix focused on Discord/shared Markdown chunking and table conversion: preserve blockquote context with depth-correct handling, avoid splitting or decontextualizing tables, balance inline formatting without corrupting identifiers/code, and add focused regression tests. Split release, CI, provider trust, runtime-dependency, generated-baseline, gateway, and E2E harness changes into separate owner-reviewed PRs. Do we have a high-confidence way to reproduce the issue? Yes. Current-main code inspection gives a high-confidence reproduction path: force Discord/shared chunk splits inside a blockquote, table, or inline span; the current chunkers only reopen fenced code context, and table conversion still uses an empty blockquote prefix. Is this the best way to solve the issue? No. The proposed direction is useful, but this PR is not the best way to solve it because it mixes the Markdown fix with unrelated sensitive changes and still mishandles mixed-depth blockquotes; a focused rebase or replacement is safer. Full review comments:
Overall correctness: patch is incorrect Security concerns:
Acceptance criteria:
What I checked:
Likely related people:
Remaining risk / open question:
Codex review notes: model gpt-5.5, reasoning high; reviewed against 4babd925c40d. |
|
Thanks for the PR. This branch appears to include unrelated release/workflow churn around a Discord formatting change, so it is not reviewable as a focused Telegram change. Please reopen as a narrow PR with only the intended fix. |
Fixes #63409. Related: #31679 #24363 #32743 #30962
Problem
When OpenClaw delivers long messages to Discord, the chunking pipeline splits text at 2000-character boundaries. Each chunk renders independently, so formatting that spans a chunk boundary breaks: tables get split mid-row, blockquotes lose their > prefix in continuation chunks, and inline formatting can get orphaned across splits.
Additionally, convertMarkdownTables re-renders the entire message through the IR pipeline when a table is present, and was hardcoding blockquotePrefix: "" - stripping all blockquote markers even in single-chunk messages containing both a table and a blockquote.
Solution
Core chunker (src/auto-reply/chunk.ts)
Integrates table span parsing, blockquote span tracking, and inline marker balancing into chunkMarkdownText, following the existing fence-span pattern.
New span parsers
Discord-specific chunker (extensions/discord/src/chunk.ts)
The Discord extension has its own line-by-line chunker that bypasses the core chunker. This adds blockquote prefix reapplication and table header repetition directly to chunkDiscordText. Blockquote prefix is only applied after flush(), not on intra-line segment continuations.
Blockquote + table coexistence (src/markdown/tables.ts)
convertMarkdownTables now accepts an optional blockquotePrefix parameter (default "" for backward compat). All three Discord call sites pass "> " so blockquotes survive the IR re-render.
Testing