From e427995d7028d5040ebff36e12c4785b39a8b6b8 Mon Sep 17 00:00:00 2001 From: Sam Catlow Date: Sat, 12 Sep 2026 09:44:52 +1000 Subject: [PATCH] fix(telegram): stop the relay corrupting identifiers and code Emphasis stripping ran two non-greedy regexes, `_(.+?)_` and `\*(.+?)\*`, over every paragraph, heading, list item and quote. Neither honoured CommonMark's flanking rules, so any two markers on a line paired up and both characters were deleted: "allow_concurrent": true, "max_retries": true -> "allowconcurrent": true, "maxretries": true internal/webui/config_schema_test.go -> internal/webui/configschematest.go takes no *sql.Tx and returns *Result -> takes no sql.Tx and returns Result Agent reports relayed to Telegram therefore cited files that do not exist, which reads as hallucination rather than as the transport fault it is. Replace both regexes with a scanner that pairs delimiters by CommonMark's left/right-flanking rules, including the rule that an underscore may not open or close inside a word. Single "*" additionally may not open on punctuation: CommonMark reads "*.go files in cmd/*" as emphasis, and in a relay carrying globs and pointer types that costs far more than a surviving marker. closeCode ran the same stripper over fenced code. Code is verbatim by definition, so it no longer does. Separately, markdownToBlocks knew only fenced code, not CommonMark's indented form, which models emit constantly. An indented block fell through to the paragraph case, which space-joins lines, arriving as one run-on line with its markers eaten on the way. Parse it as code, ending at the first non-indented non-blank line, and refuse to let it interrupt an open paragraph so a wrapped prose line stays prose. Paragraph continuations are now trimmed before joining, so the join is one space rather than the source indentation. Closes archie-core-8x1r, archie-core-cvu6. --- internal/channels/telegram/richblocks.go | 197 +++++++++++++++--- internal/channels/telegram/richblocks_test.go | 118 +++++++++++ 2 files changed, 291 insertions(+), 24 deletions(-) diff --git a/internal/channels/telegram/richblocks.go b/internal/channels/telegram/richblocks.go index 80115b264..c92a95c61 100644 --- a/internal/channels/telegram/richblocks.go +++ b/internal/channels/telegram/richblocks.go @@ -3,6 +3,8 @@ package telegram import ( "regexp" "strings" + "unicode" + "unicode/utf8" "github.com/go-telegram/bot/models" ) @@ -14,15 +16,14 @@ import ( // Markdown marker can survive into the rendered message. var ( - inlineLinkHTML = regexp.MustCompile(`\[([^\]]*)\]\(([^)]+)\)`) - strikeBlockMark = regexp.MustCompile(`~~(.+?)~~`) - boldBlockMark = regexp.MustCompile(`\*\*(.+?)\*\*`) - underlineBlockMark = regexp.MustCompile(`__(.+?)__`) - italicBlockMark = regexp.MustCompile(`\*(.+?)\*`) - italicBlockUndersc = regexp.MustCompile(`_(.+?)_`) - codeBlockMark = regexp.MustCompile("`([^`]*)`") + inlineLinkHTML = regexp.MustCompile(`\[([^\]]*)\]\(([^)]+)\)`) + codeBlockMark = regexp.MustCompile("`([^`]*)`") ) +// emphasisMarkers are the delimiters stripEmphasis pairs, longest first so +// "**" is consumed before the "*" pass can see it as two single markers. +var emphasisMarkers = []string{"~~", "**", "__", "*", "_"} + // richText builds a plain Text; an empty RichText.Type serializes as a JSON // string, which is exactly what a plain-text rich block wants. func richText(text string) models.RichText { @@ -107,13 +108,102 @@ func listItemText(line string) string { // text, dropping the markers so none of them can leak into the rendered block. func stripInlineMarkdown(s string) string { s = inlineLinkHTML.ReplaceAllString(s, "$1 ($2)") - s = strikeBlockMark.ReplaceAllString(s, "$1") - s = boldBlockMark.ReplaceAllString(s, "$1") - s = underlineBlockMark.ReplaceAllString(s, "$1") - s = italicBlockMark.ReplaceAllString(s, "$1") - s = italicBlockUndersc.ReplaceAllString(s, "$1") - s = codeBlockMark.ReplaceAllString(s, "$1") - return s + for _, marker := range emphasisMarkers { + s = stripEmphasis(s, marker) + } + return codeBlockMark.ReplaceAllString(s, "$1") +} + +// stripEmphasis removes paired emphasis delimiters and keeps their content. +// Pairing follows CommonMark's flanking rules, so a delimiter that cannot +// open or close is ordinary text and stays put. That is what keeps this +// project's own vocabulary intact over the wire: snake_case config keys, +// dotted paths like config_schema_test.go, and Go pointer types such as +// *sql.Tx all used to lose characters to a non-greedy `_(.+?)_` that paired +// any two markers on a line (archie-core-8x1r). +func stripEmphasis(s, marker string) string { + var b strings.Builder + for i := 0; i < len(s); { + if !strings.HasPrefix(s[i:], marker) { + b.WriteByte(s[i]) + i++ + continue + } + end := i + len(marker) + if canOpen, _ := flanking(s, i, end, marker); canOpen { + if closer := findCloser(s, end, marker); closer >= 0 { + b.WriteString(s[end:closer]) + i = closer + len(marker) + continue + } + } + b.WriteString(marker) + i = end + } + return b.String() +} + +// findCloser returns the offset of the first delimiter at or after from that +// may close emphasis, or -1 when the run is unpaired. +func findCloser(s string, from int, marker string) int { + for i := from; i+len(marker) <= len(s); i++ { + if !strings.HasPrefix(s[i:], marker) { + continue + } + if _, canClose := flanking(s, i, i+len(marker), marker); canClose { + return i + } + } + return -1 +} + +// delimiterFlanks carries CommonMark's flanking facts about one delimiter +// run: whether it is left- and/or right-flanking, and whether the characters +// either side are punctuation, which the underscore rules also need. +type delimiterFlanks struct { + left, right bool + prevPunct, nextPunct bool +} + +// flanksOf computes the flanking facts for the delimiter run s[i:j]. +func flanksOf(s string, i, j int) delimiterFlanks { + prev := ' ' + if i > 0 { + prev, _ = utf8.DecodeLastRuneInString(s[:i]) + } + next := ' ' + if j < len(s) { + next, _ = utf8.DecodeRuneInString(s[j:]) + } + prevSpace, nextSpace := unicode.IsSpace(prev), unicode.IsSpace(next) + f := delimiterFlanks{prevPunct: isPunct(prev), nextPunct: isPunct(next)} + f.left = !nextSpace && (!f.nextPunct || prevSpace || f.prevPunct) + f.right = !prevSpace && (!f.prevPunct || nextSpace || f.nextPunct) + return f +} + +// flanking reports whether the delimiter run s[i:j] may open or close +// emphasis. The rules are CommonMark's, including the one that an underscore +// may do neither inside a word. +// +// Single "*" carries one deliberate deviation: it may not open on +// punctuation. CommonMark reads "*.go files in cmd/*" as emphasis, which in a +// relay carrying shell globs and pointer types corrupts far more text than a +// stray marker would. Emphasis opening on a word still works. +func flanking(s string, i, j int, marker string) (canOpen, canClose bool) { + f := flanksOf(s, i, j) + switch marker { + case "_", "__": + return f.left && (!f.right || f.prevPunct), f.right && (!f.left || f.nextPunct) + case "*": + return f.left && !f.nextPunct, f.right + default: + return f.left, f.right + } +} + +func isPunct(r rune) bool { + return unicode.IsPunct(r) || unicode.IsSymbol(r) } // markdownToBlocks converts a Markdown document into Telegram rich-message @@ -142,6 +232,7 @@ type markdownBlockParser struct { codeLines []string codeLang string inCode bool + indented bool listItems [][]models.InputRichBlock quoteLines []string } @@ -151,12 +242,7 @@ type markdownBlockParser struct { func (p *markdownBlockParser) handleLine(line string) { trimmed := strings.TrimSpace(line) - if p.inCode { - if strings.HasPrefix(trimmed, "```") { - p.closeCode() - } else { - p.codeLines = append(p.codeLines, line) - } + if p.inCode && p.consumeCodeLine(line, trimmed) { return } @@ -176,6 +262,13 @@ func (p *markdownBlockParser) handleLine(line string) { p.flushList() } p.listItems = append(p.listItems, []models.InputRichBlock{paragraphBlock(listItemText(trimmed))}) + case p.startsIndentedCode(line): + // CommonMark's other code form. Models emit it constantly, and + // without this it fell to the paragraph case below, which + // space-joins its lines into one run-on line (archie-core-cvu6). + p.flush() + p.inCode, p.indented, p.codeLang = true, true, "" + p.codeLines = []string{stripCodeIndent(line)} case len(trimmed) > 1 && trimmed[0] == '>': p.flushParagraph() p.flushList() @@ -195,10 +288,39 @@ func (p *markdownBlockParser) handleLine(line string) { if p.paragraph.Len() > 0 { p.paragraph.WriteString(" ") } - p.paragraph.WriteString(line) + p.paragraph.WriteString(trimmed) } } +// consumeCodeLine handles one line while a code block is open, reporting +// whether that block claimed it. A fenced block ends at its closing fence; an +// indented block ends at the first non-indented, non-blank line, which is not +// a terminator and must still be parsed normally. +func (p *markdownBlockParser) consumeCodeLine(line, trimmed string) bool { + if !p.indented { + if strings.HasPrefix(trimmed, "```") { + p.closeCode() + } else { + p.codeLines = append(p.codeLines, line) + } + return true + } + if trimmed == "" || indentedCodeLine(line) { + p.codeLines = append(p.codeLines, stripCodeIndent(line)) + return true + } + p.closeCode() + return false +} + +// startsIndentedCode reports whether line opens an indented code block. It may +// not interrupt an open paragraph, list or quote, so a wrapped prose line that +// happens to be indented stays prose. +func (p *markdownBlockParser) startsIndentedCode(line string) bool { + return indentedCodeLine(line) && p.paragraph.Len() == 0 && + len(p.listItems) == 0 && len(p.quoteLines) == 0 +} + // flush closes every open construct, in the order that keeps blocks in // source order. func (p *markdownBlockParser) flush() { @@ -274,11 +396,38 @@ func (p *markdownBlockParser) flushQuote() { p.quoteLines = nil } +// closeCode emits the open code block. The text is passed through verbatim: +// code is not prose, and running the emphasis stripper over it turned +// *sql.Tx into sql.Tx and ate same-line snake_case pairs (archie-core-8x1r). func (p *markdownBlockParser) closeCode() { - if len(p.codeLines) > 0 || p.codeLang != "" { - p.appendBlock(preformattedBlock(stripInlineMarkdown(strings.Join(p.codeLines, "\n")), p.codeLang)) + lines := p.codeLines + if p.indented { + for len(lines) > 0 && strings.TrimSpace(lines[len(lines)-1]) == "" { + lines = lines[:len(lines)-1] + } } - p.codeLines, p.codeLang, p.inCode = nil, "", false + if len(lines) > 0 || p.codeLang != "" { + p.appendBlock(preformattedBlock(strings.Join(lines, "\n"), p.codeLang)) + } + p.codeLines, p.codeLang, p.inCode, p.indented = nil, "", false, false +} + +// indentedCodeLine reports whether line opens or continues an indented code +// block: four spaces or a tab, and something other than whitespace after. +func indentedCodeLine(line string) bool { + if strings.TrimSpace(line) == "" { + return false + } + return strings.HasPrefix(line, " ") || strings.HasPrefix(line, "\t") +} + +// stripCodeIndent removes the one level of indentation that marks the block, +// so the code reads at its own natural margin. +func stripCodeIndent(line string) string { + if strings.HasPrefix(line, "\t") { + return line[1:] + } + return strings.TrimPrefix(line, " ") } // blocksToPlainText flattens blocks into readable plain text for the fallback diff --git a/internal/channels/telegram/richblocks_test.go b/internal/channels/telegram/richblocks_test.go index d93650960..4023d3698 100644 --- a/internal/channels/telegram/richblocks_test.go +++ b/internal/channels/telegram/richblocks_test.go @@ -264,3 +264,121 @@ func TestSplitBlocksEmptyAndOversizedBlock(t *testing.T) { t.Fatalf("oversized single block produced %d chunks, want 1", len(chunks)) } } + +// Identifiers carrying Markdown's emphasis characters are ordinary prose in +// this project: snake_case config keys, dotted file paths and Go pointer +// types all reach Telegram inside agent reports. Emphasis stripping must +// leave them byte-for-byte intact, or the relay hands operators citations to +// files that do not exist (archie-core-8x1r). +func TestStripInlineMarkdownKeepsIdentifiers(t *testing.T) { + for _, tc := range []struct{ name, in, want string }{ + { + name: "two snake_case keys on one line", + in: `"allow_concurrent": true, "max_retries": true`, + want: `"allow_concurrent": true, "max_retries": true`, + }, + { + name: "snake_case file path", + in: "the internal/webui/config_schema_test.go file", + want: "the internal/webui/config_schema_test.go file", + }, + { + name: "two Go pointer types on one line", + in: "RecordDispatch takes no *sql.Tx and returns *Result", + want: "RecordDispatch takes no *sql.Tx and returns *Result", + }, + { + name: "leading-underscore identifiers", + in: "reply on _INBOX.foo then _INBOX.bar", + want: "reply on _INBOX.foo then _INBOX.bar", + }, + { + name: "glob patterns", + in: "glob the *.go files under cmd/*", + want: "glob the *.go files under cmd/*", + }, + } { + t.Run(tc.name, func(t *testing.T) { + if got := stripInlineMarkdown(tc.in); got != tc.want { + t.Errorf("stripInlineMarkdown(%q)\n = %q\nwant %q", tc.in, got, tc.want) + } + }) + } +} + +// The flanking rules must not cost us actual emphasis stripping: a marker +// that really does delimit emphasis still has to be reduced to plain text, +// because Telegram's renderer would otherwise show the raw marker. +func TestStripInlineMarkdownStillStripsRealEmphasis(t *testing.T) { + for _, tc := range []struct{ name, in, want string }{ + {"italic underscore", "an _emphasised_ word", "an emphasised word"}, + {"italic asterisk", "an *emphasised* word", "an emphasised word"}, + {"bold", "a **strong** word", "a strong word"}, + {"underline", "an __underlined__ word", "an underlined word"}, + {"strikethrough", "a ~~struck~~ word", "a struck word"}, + {"inline code", "call `doThing()` now", "call doThing() now"}, + {"link", "see [docs](http://x/y) here", "see docs (http://x/y) here"}, + {"bold around identifier", "the **max_retries** field", "the max_retries field"}, + {"emphasis next to punctuation", "(_emphasised_)", "(emphasised)"}, + } { + t.Run(tc.name, func(t *testing.T) { + if got := stripInlineMarkdown(tc.in); got != tc.want { + t.Errorf("stripInlineMarkdown(%q)\n = %q\nwant %q", tc.in, got, tc.want) + } + }) + } +} + +// An indented code block is CommonMark's other code form, and models emit it +// constantly. Without support it falls through to the paragraph path, which +// space-joins its lines into one run-on line (archie-core-cvu6). +func TestMarkdownToBlocksIndentedCode(t *testing.T) { + blocks := markdownToBlocks("Report:\n\n type D struct {\n Key string\n Label string\n }\n") + var pre *models.InputRichBlock + for i := range blocks { + if blocks[i].Type == models.RichBlockTypePreformatted { + pre = &blocks[i] + } + } + if pre == nil { + t.Fatalf("no preformatted block; got %v", blockTypes(blocks)) + } + want := "type D struct {\n Key string\n Label string\n}" + if got := blockText(*pre); got != want { + t.Errorf("indented code text =\n%q\nwant\n%q", got, want) + } +} + +// An indented line cannot interrupt an open paragraph: CommonMark says so, +// and treating a wrapped prose line as code would be a worse failure than +// the one being fixed. +func TestMarkdownToBlocksIndentedLineDoesNotInterruptParagraph(t *testing.T) { + blocks := markdownToBlocks("Some prose that wraps\n onto an indented line.\n") + for _, b := range blocks { + if b.Type == models.RichBlockTypePreformatted { + t.Fatalf("indented continuation became code; blocks = %v", blockTypes(blocks)) + } + } + if got := blockText(blocks[0]); got != "Some prose that wraps onto an indented line." { + t.Errorf("paragraph = %q", got) + } +} + +// Code is verbatim by definition. Running the emphasis stripper over a fenced +// block corrupted pointer types and same-line snake_case pairs alike. +func TestMarkdownToBlocksFencedCodeIsVerbatim(t *testing.T) { + body := "m := map[string]bool{\"allow_concurrent\": true, \"max_retries\": true}\nfunc f(tx *sql.Tx) *Result" + blocks := markdownToBlocks("```go\n" + body + "\n```\n") + var pre *models.InputRichBlock + for i := range blocks { + if blocks[i].Type == models.RichBlockTypePreformatted { + pre = &blocks[i] + } + } + if pre == nil { + t.Fatalf("no preformatted block; got %v", blockTypes(blocks)) + } + if got := blockText(*pre); got != body { + t.Errorf("fenced code was altered:\n got %q\nwant %q", got, body) + } +}