Files
archie/internal/channels/telegram/richblocks_test.go
T
sam c4ddb9acdf Feat/q9au inline review comments (#895)
* feat(workflow): post line-anchored review comments with suggested fixes

Bead archie-core-q9au (docs/prds/inline-review.md). A review's findings reached
the operator only as a flat list in the PR body, so the author had to map every
finding back to its line by hand and apply mechanical fixes by hand. Now the
line-anchored findings are also posted as inline review comments, carrying a
one-click suggestion when the reviewer could state the fix.

Domain (internal/domain/workflow):
- ReviewFinding gains Suggestion; Validate rejects one on anything but a
  confirmed finding, so the agent's record_finding call is refused with
  something it can act on. Validate splits into validateAnchor /
  validateClassification / validateDisposition, which also brings it back under
  the cyclop limit the gate enforces.
- StagePostReviewComments runs after StageOpenPR in the implement workflow. It
  posts only line-anchored findings (Line > 0); a whole-file finding has no line
  to attach to and stays in the body list, which remains the complete record.
  It is best-effort: the PR is open and the body already lists every finding, so
  a failed comment is logged, never a park -- the same reasoning as OpenPR's
  existing best-effort LinkBranch call.
- The suggestion fence is gated on Verdict == confirmed where the fence is
  written, because it is a one-click apply: a wrong suggestion breaks the code
  and the author has to notice.

Forge (internal/forge): ReviewCommentWriter + GitHub/Gitea implementations,
type-asserted like PullRequestReader so a forge that cannot is skipped rather
than faked (NoopForge is pinned as not satisfying it). GitHub loops one
CreateComment per comment and joins the failures, so one refused anchor cannot
drop the rest; Gitea carries them on a single COMMENT-state review.

Two deliberate departures from the PRD's sketch, both recorded in it:
- The interface is batch (CreateReviewComments), not one call per comment:
  Gitea's only inline shape is one submitted review, and the set then crosses
  NATS once instead of once per finding.
- The head SHA is resolved inside each forge implementation rather than by the
  caller. The stage runs in archie-agent, which holds no forge credentials and
  has no PullRequestReader; the daemon-side forgerpc handler is the only place
  that does.

Transport (internal/forgerpc): workflow.Forger gains the method, so the agent
reaches the daemon over the new create_review_comments subject; the server
type-asserts the writer and answers an incapable forge with an error the stage
logs. This is the one proxied method whose absence on an image skew does not
park a task.

The reviewer prompt and record_finding schema ask for a suggestion on a
confirmed, mechanically fixable defect only.

Regenerating the wfextract symbol table -- the documented way a new exported
workflow symbol reaches interpreted stage plugins -- also picked up symbols that
were missing from the committed table (the Status* and Source* constants,
ReviewCheck, Store, Task, and the _Store wrapper). Nil-guards were re-applied to
every wrapper afterwards, as that file's header requires.

Evidence: task check exit 0 (incl. 229 UI tests). Three mutations of the new
stage logic each fail a test that names the behaviour -- dropping the
confirmed-only gate, dropping the Line > 0 filter, and letting a posting failure
escape -- so the tests discriminate rather than passing vacuously.

* fix(build): drop the Dockerfile pin assertion

The guard fetched golangci-lint's go.mod at image build time to fail the build
when GOLANGCI_LINT_VERSION and GOFUMPT_VERSION disagreed. It only ever tripped
on self-inflicted pin drift, but it added a network fetch and a new failure
mode to the release build, which is not where that belongs.

The pins stay correct (golangci-lint 2.13.2, whose vendored gofumpt v0.11.0
equals GOFUMPT_VERSION) and the comment above them still states the invariant,
so the reasoning survives without the build-time machinery. The pin change
itself reaches the agent image through the normal release path: CI rebuilds
and pushes archie-agent on an archie/vX.Y.Z release, and a gateway-only
release deliberately does not.

* feat(workflow): add the remediate workflow for PR review remediation

Implements step 5 of docs/prds/pr-review-remediation.md: a remediate
workflow that resumes the task's existing worktree onto its PR branch
(worktree.Manager.Resume, not Prepare's refresh), runs a builder agent
against the review's actionable comments, commits and pushes to the
same branch, and replies via the forge's ReplyToReview. Task.RetryCount
doubles as the remediation round counter, capped by the repo's
max_retries; the round-cap stage parks the task and posts one comment
when it's hit.

Task gains a ReviewPayload field (JSON-encoded review unit) with full
store/proto/staterpc plumbing. workflow.Forger gains Comment and
ReplyToReview, proxied to archie-agent via a new forgerpc RPC. Resume
and its Dir lookup are added as an unexported optional Trees capability
rather than widening the exported interface, which is already at
golangci-lint's interfacebloat cap and is projected into wfextract's
Yaegi symbol table for repository-authored stage plugins.

The daemon-side reaction consumer that dispatches into this workflow
(subscribing ARCHIE_REACTIONS, grouping comments by review, enforcing
per-task serialization) is tracked separately in archie-core-8li9.4.

* feat(messaging): extract standalone messaging service binary and process composition

* feat(messaging): adapt channel frontends to consume Gateway ChatContract

* feat(messaging): remove in-process channels and Router from daemon bootstrap

Telegram, email and webhook now run only in the Messaging Service, which
reaches this process through the Gateway's ChatContract. The daemon builds
no channel and no gateway.Router, so the wiring that existed only to serve
them goes with it: setupGateways, setupEmailGateway, setupWebhookGateway,
setupTelegramGateway, buildTelegramRouter, makeTelegramReload and the
release-announcement path helper.

The seams those paths owned move to where they can still be honoured:

- Channel ValidateConfig runs in archiemessaging.compose, which now returns
  an error, so a configured-but-invalid front-end fails the service rather
  than being dropped silently.
- The inbound rate limiter moves to the Gateway process, which owns the only
  Router and therefore the only place a per-sender budget applies to every
  channel's turns.
- The daemon's gateway readiness probe becomes a ContractProbe against the
  Gateway. It cannot observe a channel lifecycle it no longer runs, and a
  channel-count probe would have reported every daemon degraded.
- telegramSetup is now chatSetup (in chat_setup.go), trimmed to the fields a
  chat turn runner actually reads.

Telegram operator features that were wired only in the daemon (/update,
release announcements, version reporting, SIGHUP reload) are not yet wired
in the Messaging Service: archie-core-8cda.6.6. Channel lifecycle reporting:
archie-core-8cda.6.8. The Gateway process builds no worktree manager, so
review_pr is unadvertised on every channel: archie-core-8cda.6.7.

* feat(messaging): re-wire the Telegram operator surface in the Messaging Service

setupTelegramGateway satisfied eight telegram.Gateway seams from the daemon's
own process. Each is resolved by where the fact it needs is owned, not by
where it used to be built; the decision table is in
docs/architecture/migration-decisions.md.

Wired here: /update (built from this service's own [chat.telegram] check and
install commands), the update-report relay (same sha256(bot_user)[:8] path the
daemon wrote, so a pending report is found rather than written afresh),
show_tool_calls, and /restart's config reload, which re-resolves the token and
allowlist from this service's own file and refuses a reload that resolves to
an empty token.

/version is sourced from the Gateway: ChatSnapshot gains a Version field
carrying the Gateway's rendered build block, read per call and bounded by the
dependency timeout. cmd/archie-messaging deliberately takes no version
ldflags, so it cannot report a partial upgrade as a matched one.

RunningVersions and ReleaseAnnouncements stay nil. Both need a component's
real running version, and the only versions this process can obtain are a
different binary's stamps -- reporting them would manufacture exactly the
false success the update check exists to catch, and the announcer without
parseable versions is a no-op that reads as configured. archie-core-8cda.6.9
carries the contract that unblocks them. Dangerous stays nil: no composition
has ever supplied a command authority.

Enrich is dropped from the update service: componentInstallTypeEnricher read
[nats], which this service must not decode, so the check command's own
reported install type stands.

* fix(workflow): guard inline review comments against head drift

Two findings from the review of q9au.

A comment's line numbers describe exactly one revision of the branch, but the
forge resolved the pull request's head at posting time -- after the review had
already read the worktree. A push in that window (a collaborator, a retry) meant
the findings were anchored to whatever now occupied those lines, mislabelling
instead of failing. The revision the review measured now travels with the
comment set: OpenPR records it from the same worktree read it already performs
(TaskContext.ReviewedHeadSHA), StagePostReviewComments threads it through
Forger to forgerpc, and the forge refuses the whole set once the head it reads
has moved off it -- which the best-effort stage logs, the PR body remaining the
record. An unmeasured revision posts unverified rather than dropping every
finding, so a worktree that cannot report one degrades instead of regressing.

Suggestion was documented single-line only, because GitHub applies a suggestion
fence up to its first line and a multi-line replacement would silently corrupt
the file. Only the verdict was validated, so a multi-line suggestion reached the
renderer and posted as that truncated fence. Validate now rejects an embedded
newline, which makes record_finding refuse it with feedback the model can act on
instead of the reviewer discovering the corruption later.

* fix(gateway): render chat reports as lines, not one run-on paragraph

/status and /tasks are line-oriented reports, but their newlines were plain
"\n" -- CommonMark's soft wrap. The Telegram rich-block renderer space-joins
soft-wrapped lines, by design: a Telegram paragraph renders an embedded
newline as nothing at all, so a space is the only separator that survives.
The reports therefore arrived as one line each: "Runtime Provider: DeepSeek
Model: deepseek/deepseek-flash", and every task's title, state and park
reason jammed together.

The renderer now implements CommonMark's hard line break (two trailing
spaces, or a trailing backslash): the line closes its own block and the next
one hugs it, so a stanza keeps its lines without the spacer paragraph that
separates unrelated blocks. Ordinary prose is untouched -- a model's wrapped
paragraph still joins with a space. The producers mark their report lines
with it.

Two report fixes alongside:

- A park reason is capped to its first line at 160 runes. It carries whatever
  the failing stage reported, which for a lint gate is the whole tool log;
  unbounded, one parked task pushed every other task out of the reply. The
  full reason is still on the task.
- /status loses its "Runtime" sub-header. A section header over two fields
  made a four-fact report read like a document.
2026-09-19 23:44:51 +10:00

464 lines
16 KiB
Go

package telegram
import (
"strings"
"testing"
"github.com/go-telegram/bot/models"
)
// blockText extracts the plain text of a single block, for assertions.
func blockText(b models.InputRichBlock) string {
switch b.Type {
case models.RichBlockTypeParagraph:
if b.InputRichBlockParagraph != nil {
return b.InputRichBlockParagraph.Text.PlainText
}
case models.RichBlockTypeSectionHeading:
if b.InputRichBlockSectionHeading != nil {
return b.InputRichBlockSectionHeading.Text.PlainText
}
case models.RichBlockTypePreformatted:
if b.InputRichBlockPreformatted != nil {
return b.InputRichBlockPreformatted.Text.PlainText
}
}
return ""
}
func TestMarkdownToBlocksHeadings(t *testing.T) {
// A spacer paragraph precedes the heading: Telegram adds no gap between
// adjacent blocks on its own, so the parser inserts one explicitly
// before every non-heading-following block. See appendBlock.
blocks := markdownToBlocks("Intro prose.\n### Danger\nMore prose.")
if len(blocks) != 4 {
t.Fatalf("blocks = %d, want 4 (%v)", len(blocks), blockTypes(blocks))
}
heading := blocks[2]
if heading.Type != models.RichBlockTypeSectionHeading {
t.Fatalf("second block type = %q, want heading", heading.Type)
}
if got := heading.InputRichBlockSectionHeading.Size; got != 3 {
t.Errorf("heading size = %d, want 3 (for ###)", got)
}
if got := blockText(heading); got != "Danger" {
t.Errorf("heading text = %q, want Danger", got)
}
}
func TestMarkdownToBlocksHeadingsMapDepthToSize(t *testing.T) {
for _, tc := range []struct {
line string
size int
}{
{"# One", 1},
{"## Two", 2},
{"### Three", 3},
{"#### Four", 4},
{"##### Five", 5},
{"###### Six", 6},
} {
blocks := markdownToBlocks(tc.line)
if len(blocks) != 1 {
t.Fatalf("%q: blocks = %d, want 1", tc.line, len(blocks))
}
if got := blocks[0].InputRichBlockSectionHeading.Size; got != tc.size {
t.Errorf("%q: size = %d, want %d", tc.line, got, tc.size)
}
}
}
func TestMarkdownToBlocksFencedCode(t *testing.T) {
// Non-heading blocks get an explicit spacer paragraph on both sides; see
// appendBlock.
in := "before\n```go\nfunc main() {}\n```\nafter"
blocks := markdownToBlocks(in)
if len(blocks) != 5 {
t.Fatalf("blocks = %d, want 5 (%v)", len(blocks), blockTypes(blocks))
}
pre := blocks[2]
if pre.Type != models.RichBlockTypePreformatted {
t.Fatalf("second block type = %q, want pre", pre.Type)
}
if got := pre.InputRichBlockPreformatted.Language; got != "go" {
t.Errorf("language = %q, want go", got)
}
if got := blockText(pre); got != "func main() {}" {
t.Errorf("code = %q, want func main() {}", got)
}
}
func TestMarkdownToBlocksBulletList(t *testing.T) {
// Non-heading blocks get an explicit spacer paragraph on both sides; see
// appendBlock.
in := "Text before\n- one\n- two\nText after"
blocks := markdownToBlocks(in)
if len(blocks) != 5 {
t.Fatalf("blocks = %d, want 5 (%v)", len(blocks), blockTypes(blocks))
}
list := blocks[2]
if list.Type != models.RichBlockTypeList {
t.Fatalf("second block type = %q, want list", list.Type)
}
items := list.InputRichBlockList.Items
if len(items) != 2 {
t.Fatalf("list items = %d, want 2", len(items))
}
if got := blockText(items[0].Blocks[0]); got != "one" {
t.Errorf("item 0 = %q, want one", got)
}
}
func TestMarkdownToBlocksBlockQuotation(t *testing.T) {
// Non-heading blocks get an explicit spacer paragraph on both sides; see
// appendBlock.
in := "prose\n> important note\nafter"
blocks := markdownToBlocks(in)
if len(blocks) != 5 {
t.Fatalf("blocks = %d, want 5 (%v)", len(blocks), blockTypes(blocks))
}
quote := blocks[2]
if quote.Type != models.RichBlockTypeBlockQuotation {
t.Fatalf("second block type = %q, want blockquote", quote.Type)
}
if got := blockText(quote.InputRichBlockBlockQuotation.Blocks[0]); got != "important note" {
t.Errorf("quote text = %q, want 'important note'", got)
}
}
func TestMarkdownToBlocksStripsInlineMarkers(t *testing.T) {
blocks := markdownToBlocks("**bold** and `code` and [a link](https://example.com)")
if len(blocks) != 1 {
t.Fatalf("blocks = %d, want 1", len(blocks))
}
got := blockText(blocks[0])
for _, marker := range []string{"**", "`", "](https://example.com)"} {
if strings.Contains(got, marker) {
t.Errorf("text %q leaked marker %q", got, marker)
}
}
if !strings.Contains(got, "a link (https://example.com)") {
t.Errorf("text = %q, want link rendered as 'label (url)'", got)
}
if !strings.Contains(got, "bold") {
t.Errorf("text = %q, lost bold content", got)
}
}
func TestMarkdownToBlocksToolBlockBecomesParagraphAndCode(t *testing.T) {
// The tool progress block composes a label line then a ```text fence.
// Non-heading blocks get an explicit spacer paragraph on both sides; see
// appendBlock.
in := "🔧 shell — done\n```text\nexit 0\n```\ndone"
blocks := markdownToBlocks(in)
if len(blocks) != 5 {
t.Fatalf("blocks = %d, want 5 (%v)", len(blocks), blockTypes(blocks))
}
if got := blockText(blocks[0]); got != "🔧 shell — done" {
t.Errorf("label block = %q", got)
}
if blocks[2].Type != models.RichBlockTypePreformatted {
t.Fatalf("third block type = %q, want pre", blocks[2].Type)
}
if got := blockText(blocks[2]); got != "exit 0" {
t.Errorf("code = %q, want exit 0", got)
}
}
func TestMarkdownToBlocksEmptyAndResets(t *testing.T) {
if blocks := markdownToBlocks(""); len(blocks) != 0 {
t.Fatalf("empty input produced %d blocks", len(blocks))
}
// Consecutive headings must not collapse into one block.
blocks := markdownToBlocks("### One\n### Two")
if len(blocks) != 2 {
t.Fatalf("two headings produced %d blocks", len(blocks))
}
}
func TestBlocksToPlainText(t *testing.T) {
blocks := markdownToBlocks("## Head\n\npara one\n- item\n```\ncode\n```")
out := strings.Join(blocksToPlainText(blocks), "\n\n")
if strings.Contains(out, "##") || strings.Contains(out, "```") {
t.Fatalf("plain text leaked markdown markers: %q", out)
}
if !strings.Contains(out, "Head") || !strings.Contains(out, "para one") ||
!strings.Contains(out, "item") || !strings.Contains(out, "code") {
t.Fatalf("plain text lost content: %q", out)
}
}
func blockTypes(blocks []models.InputRichBlock) []string {
types := make([]string, len(blocks))
for i, b := range blocks {
types[i] = string(b.Type)
}
return types
}
func TestSplitBlocksFitsInOneChunk(t *testing.T) {
blocks := markdownToBlocks("one\n\n## Two\n\n- a\n- b")
chunks := splitBlocks(blocks, 10_000)
if len(chunks) != 1 {
t.Fatalf("chunks = %d, want 1", len(chunks))
}
if len(chunks[0]) != len(blocks) {
t.Fatalf("chunk has %d blocks, want %d", len(chunks[0]), len(blocks))
}
}
func TestSplitBlocksBreaksOnlyAtBlockBoundaries(t *testing.T) {
// A large code block followed by prose must not be split mid-block.
big := strings.Repeat("x", 5000)
blocks := markdownToBlocks("```text\n" + big + "\n```\n\nafter")
chunks := splitBlocks(blocks, 1000)
if len(chunks) != 2 {
t.Fatalf("chunks = %d, want 2", len(chunks))
}
// First chunk is the preformatted block, whole.
if chunks[0][0].Type != models.RichBlockTypePreformatted {
t.Fatalf("first block type = %q, want pre", chunks[0][0].Type)
}
if got := blockText(chunks[0][0]); got != big {
t.Fatalf("code block was truncated (len %d)", len(got))
}
// Second chunk carries the trailing paragraph.
if chunks[1][0].Type != models.RichBlockTypeParagraph {
t.Fatalf("second chunk block type = %q, want paragraph", chunks[1][0].Type)
}
}
func TestSplitBlocksPreservesOrderAndContent(t *testing.T) {
blocks := markdownToBlocks("para one\n\npara two\n\npara three")
chunks := splitBlocks(blocks, 4)
var all []models.InputRichBlock
for _, chunk := range chunks {
all = append(all, chunk...)
}
if len(all) != len(blocks) {
t.Fatalf("total blocks %d, want %d", len(all), len(blocks))
}
// Spacer paragraphs (see appendBlock) are empty and intentionally
// dropped here, same as blocksToPlainText does for the real send path.
var texts []string
for _, b := range all {
if text := blockText(b); text != "" {
texts = append(texts, text)
}
}
got := strings.Join(texts, " ")
want := "para one para two para three"
if got != want {
t.Fatalf("order/content = %q, want %q", got, want)
}
}
func TestSplitBlocksEmptyAndOversizedBlock(t *testing.T) {
if chunks := splitBlocks(nil, 1000); len(chunks) != 1 || len(chunks[0]) != 0 {
t.Fatalf("empty input chunks = %v, want a single empty chunk", chunks)
}
// A single block larger than the bound is kept whole.
blocks := markdownToBlocks(strings.Repeat("z", 5000))
chunks := splitBlocks(blocks, 100)
if len(chunks) != 1 {
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)
}
}
// TestMarkdownToBlocksHardLineBreak is the regression case for a chat report
// arriving as one run-on line. /status and /tasks are line-oriented: every
// newline is a real break, not CommonMark's soft wrap. Rendered without hard
// breaks, "Runtime\nProvider: X\nModel: Y" reached Telegram as
// "Runtime Provider: X Model: Y", and a task's title, state and park reason
// were jammed into a single line each.
func TestMarkdownToBlocksHardLineBreak(t *testing.T) {
blocks := markdownToBlocks("Runtime \nProvider: DeepSeek \nModel: deepseek/flash")
var texts []string
for _, b := range blocks {
texts = append(texts, blockText(b))
}
want := []string{"Runtime", "Provider: DeepSeek", "Model: deepseek/flash"}
if len(texts) != len(want) {
t.Fatalf("blocks = %d (%v), want %d lines each as its own block", len(texts), texts, len(want))
}
for i, w := range want {
if texts[i] != w {
t.Errorf("block[%d] = %q, want %q", i, texts[i], w)
}
}
}
// TestMarkdownToBlocksHardBreakKeepsTheStanzaTight pins that hard-broken lines
// stay one visual stanza: the spacer paragraph that separates unrelated blocks
// must not be inserted between lines the producer marked as continuing.
func TestMarkdownToBlocksHardBreakKeepsTheStanzaTight(t *testing.T) {
blocks := markdownToBlocks("First line \nSecond line\n\nNew stanza")
texts := make([]string, 0, len(blocks))
for _, b := range blocks {
texts = append(texts, blockText(b))
}
want := []string{"First line", "Second line", "", "New stanza"}
if len(texts) != len(want) {
t.Fatalf("blocks = %v, want %v", texts, want)
}
for i, w := range want {
if texts[i] != w {
t.Errorf("block[%d] = %q, want %q", i, texts[i], w)
}
}
}
// TestMarkdownToBlocksSoftWrapStillJoins pins that ordinary prose is
// unaffected: a model's wrapped paragraph must not become ragged lines just
// because the reports now ask for hard breaks.
func TestMarkdownToBlocksSoftWrapStillJoins(t *testing.T) {
blocks := markdownToBlocks("A wrapped sentence\ncontinues here.")
if len(blocks) != 1 {
t.Fatalf("blocks = %d, want 1 joined paragraph", len(blocks))
}
if got := blockText(blocks[0]); got != "A wrapped sentence continues here." {
t.Errorf("paragraph = %q, want the two lines joined with a space", got)
}
}
// TestMarkdownToBlocksHardBreakDoesNotLeakPastABlankLine pins that a stanza's
// last line does not pull the next stanza up against it. The hard break
// belongs to the paragraph it closed, not to the document.
func TestMarkdownToBlocksHardBreakDoesNotLeakPastABlankLine(t *testing.T) {
blocks := markdownToBlocks("Line one \n\nLine two")
texts := make([]string, 0, len(blocks))
for _, b := range blocks {
texts = append(texts, blockText(b))
}
want := []string{"Line one", "", "Line two"}
if len(texts) != len(want) {
t.Fatalf("blocks = %v, want %v (a spacer between the two stanzas)", texts, want)
}
for i, w := range want {
if texts[i] != w {
t.Errorf("block[%d] = %q, want %q", i, texts[i], w)
}
}
}