Skip to content

fix: format telegram mirrored replies, results and notices - #47866

Open
winnythedev wants to merge 2 commits into
mainfrom
fix/47832-telegram-egress-markdown
Open

winnythedev wants to merge 2 commits into
mainfrom
fix/47832-telegram-egress-markdown

Conversation

@winnythedev

@winnythedev winnythedev commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Problem / Motivation

Goal: On Telegram, a dashboard reply mirrored to a linked chat, a cron or sub-agent result and a compaction notice arrive formatted, like a reply to a message typed in Telegram, instead of as raw markdown.

Today those messages show **bold**, backticks, code fences and [text](url) literally on Telegram. The same Bot's reply to a message typed in Telegram arrives formatted, because the Telegram reply renderer converts it to Telegram HTML.

Root cause: the dashboard reply mirror (_deliver_cross_surface_reply), the completion leg for cron, sub-agent and task-run output (_deliver_channel_reply) and the compaction and memory-guard notices all end in send_channel_parts (src/kiro_crew/messaging/egress.py). That function always called transport.send_message, the plain send, which passes no parse_mode on Telegram.

Why it matters

Anyone who links a Telegram chat to a dashboard session, or gets cron and sub-agent results in Telegram, reads every one of those messages with the markup showing. Code blocks and links are the hardest to read, and those are common in agent output.

Not a goal

  • Changing TelegramTransport.send_markdown itself or the Telegram renderer.
  • Changing the proactive send_message tool's format option. Plain stays its default.
  • Any send permission, allow-list, approval or governance path.
  • The other legs that call transport.send_message directly: the mirror-link backfill of past answers, the disconnect note and the user-message echo.
  • iMessage, whose renderer flattens markdown with its own plain-text pass. It would need its own send_markdown.

What changed (motivation → approach → change)

  • Symptom: markdown shows literally on Telegram on the unattended egress legs only.
  • Cause: send_channel_parts used the plain send for everything. A guarded markdown send already exists: TelegramTransport.send_markdown converts with md_to_telegram_html_safe, sends parse_mode=HTML, re-splits by rendered length and falls back to the plain send on a 400 or an over-cap render. The proactive send_message tool already uses it for format="markdown".
  • Change: send_channel_parts takes markdown (default False). With it, each part goes through transport.send_markdown; without it, through send_message as before. Every other transport inherits MessagingTransport.send_markdown, which is its send_message, so only Telegram's output changes. No second markdown path is added.
  • Legs that render as markdown (markdown=True):
    • the dashboard reply mirror (_deliver_cross_surface_reply), the reply text only;
    • a sub-agent completion (subagent_injection -> _deliver_channel_reply);
    • an LLM cron result (_deliver_cron_agent_result) and a cron's post-sub-agent response (_deliver_cron_response), through _deliver_cron_to_channel(markdown=True), which honours the flag on the origin leg and on a job's pin (_send_to_channel_target(markdown=...));
    • the fixed compaction notice (_deliver_via_transport when it renders its own wording).
  • Legs that stay the plain send (default): cron failure, crash, auto-pause and interrupted-run alerts (cron_failure.py), cron reminders, script and command output, task-run and approval notices (service_boot.py), the memory-guard notice (deliver_channel_text) and the mirror's image notes. A traceback or stderr there arrives as written.
  • _deliver_channel_reply and _deliver_cron_to_channel carry the flag down (default False); their pinned signatures in test_slack_gateway_composition_contract.py are updated.
  • The egress.py module docstring and the owning specs say so: the "Markdown send" bullet and two wording fixes in docs/system-specs/modules/messaging.md, and the _deliver_channel_reply chain in docs/system-specs/modules/subagent.md.

Backwards compatibility

Compatible: every leg's default is the plain send it used before, so host text is unchanged everywhere. On every channel except Telegram, send_markdown is send_message with the same arguments, so the bytes sent are unchanged on the markdown legs too. On Telegram a refused or over-cap render falls back to the plain send that went out before. A timeout or 5xx on the HTML send reports the part unconfirmed, as the plain send did, so require_confirmation still stops a half-delivered message.

Removes nothing: the change adds an opt-in keyword to one send step and its two carriers; no path, key, record or public function is hidden, renamed or deleted.

Tests

  • test/test_mirror_telegram_markdown.py (new) drives the real legs against the real TelegramTransport and TelegramClient, with only the Bot API faked on loopback (telegram_wire_helpers), plus the cron orchestrator with a double whose two sends are separate mocks. It checks:
    • a mirrored reply with bold, inline code, a link whose URL holds _ and a fence holding <dir> goes out as the exact Telegram HTML with parse_mode=HTML;
    • the prose around a mirrored table is converted and the HTML is balanced;
    • a long reply of three or more parts keeps every part HTML, balanced, at most 4,096 units, with no raw ** or fences;
    • the egress pair with markdown=True sends the same text as a direct send_markdown;
    • host text through the pair's default (a traceback holding __init__ and 2**10) reaches Telegram byte for byte with no parse_mode;
    • the fixed compaction notice goes out with parse_mode=HTML, and memory-guard text on the same leg goes out as written;
    • an LLM cron result and a cron's post-sub-agent response reach send_markdown, on the origin leg and on a job's pinned destination;
    • a cron failure alert through _deliver_failure_alert reaches send_message byte for byte and never send_markdown, on the origin leg and on a pin.
  • test_slack_gateway_subagent_delivery.py gains a test that a sub-agent's synthesized reply takes send_markdown.
  • Test doubles that defined only send_message get the one-line send_markdown delegator real transports inherit. Two negative-assert doubles (test_autonudge_firing.py, test_cron_channel_target.py) share one mock for both sends, so their "nothing was sent" asserts still catch a regression; the autonudge double also admits the peer so only the capability refusal can stop the send (checked by disabling that refusal: the test goes red).

Proof: PROVEN test/test_mirror_telegram_markdown.py::test_mirrored_reply_is_sent_as_telegram_html, test/test_mirror_telegram_markdown.py::test_prose_around_a_mirrored_table_is_formatted, test/test_mirror_telegram_markdown.py::test_a_long_mirrored_reply_keeps_every_part_formatted, test/test_mirror_telegram_markdown.py::test_the_compaction_notice_is_sent_as_markdown, test/test_mirror_telegram_markdown.py::test_a_cron_agent_result_is_sent_as_markdown (head 74d6329)

Manual verification

N/A: no live Telegram account and no gateway were used. The Telegram Bot API is faked on loopback and the real transport and client run against it, which is the surface the fix changes. No live dashboard run was done.

Real-machine verification

Machine: Linux x86_64, local developer host, pytest with the Telegram Bot API faked on loopback (no live Telegram account, no gateway).
Before (main 8aecf44): python -m pytest -q -n 0 test/test_mirror_telegram_markdown.py (first four tests) -> 4 failed, e.g. assert [None] == ['HTML'] and the raw **Done.** The retry flag ... text handed to the Bot API.
After (head 74d6329): python -m pytest -q -n 0 test/test_mirror_telegram_markdown.py -> 12 passed.
Cleanup: own host; nothing to tear down (loopback servers close with each test).

Related Issues

Fixes #47832

Overlap: no other open PR changes src/kiro_crew/messaging/egress.py except #12829 (autonomous goal suggestions), which touches a different part of it. Several open PRs edit other sections of docs/system-specs/modules/messaging.md (#47847, #47842, #47805, #47772, #47358, #46931) and docs/system-specs/modules/subagent.md (#47837, #47739, #47719, #46712, #46706); this PR changes single lines there, so whichever lands second rebases. Our #47847 (iMessage spaced asterisks) also edits messaging.md, in the iMessage section.

Sibling sweep

Swept: git grep -n 'send_channel_parts\|_deliver_channel_reply(\|_deliver_cron_to_channel(' src/
Sibling: src/kiro_crew/dashboard/chat_turn/recipient.py -- changed here -- reply passes markdown=True, image notes stay plain
Sibling: src/kiro_crew/slack/gateway_runtime/subagent_injection.py -- changed here -- sub-agent completion passes markdown=True
Sibling: src/kiro_crew/slack/gateway_runtime/cron_delivery.py -- changed here -- LLM cron result passes markdown=True; the reminder stays plain
Sibling: src/kiro_crew/slack/gateway_runtime/result_egress.py -- changed here -- post-sub-agent cron response passes markdown=True
Sibling: src/kiro_crew/dashboard/chat_compaction_notice.py -- changed here -- fixed notice renders, caller text stays plain
Sibling: src/kiro_crew/slack/gateway_runtime/cron_failure.py -- not affected -- failure, crash and pause alerts keep the plain default
Sibling: src/kiro_crew/slack/gateway_runtime/cron_exec.py -- not affected -- script and command output keep the plain default
Sibling: src/kiro_crew/slack/gateway_runtime/service_boot.py -- not affected -- task-run and approval notices keep the plain default

Pattern harvest

Not generalizable: the markdown send already existed and was opt-in by design for the proactive tool; this leg now opts in per caller, at the one send step, with plain as the default.

Checklist

  • A Conventional Commits title (feat|fix|docs|style|refactor|perf|test|chore|ci|build|revert: ...); PR Hygiene does not count commits
  • Existing tests pass and new tests added for new functionality
  • Self-review completed; code follows project style guidelines
  • Documentation updated (if applicable)
  • No secrets, credentials, or internal references in the diff

Review (multi-model interrogate)

First push: independent reviewers read the full diff. Found and fixed: two negative-assert test doubles that would have passed vacuously after the switch; a stale send_message name for this leg in subagent.md and in two messaging.md sentences; docstring and spec wording about which text on the leg is markdown. Dismissed: one reviewer read the late-binding lambda delegator as capturing send_message early (it resolves the attribute at call time); one flagged the new test's imports as unverified (they resolve and the test runs).

This push answers the CI Opus lane's block: a cron failure alert's plain twin rode the same origin leg and was rendered as markdown. The flag now defaults to the plain send and only agent-authored text and the fixed compaction notice opt in. A re-check of the repair found and this push fixes: a job's pinned destination ignored the flag (agent results there were still plain), the sub-agent and post-sub-agent cron legs had no test that fails when their flag is dropped, one spec sentence and one comment. Accepted, not changed: the Cron: <name> caption and fixed refusal or warning lines ride the markdown leg with the agent's result, so a job named __x__ would show bold; they hold no traceback (raised errors go to the plain failure alert).

Local gate: black, isort, flake8, comment-history, brand, agent-SDK boundary, file-line cap, docs-lint, flake-pattern ratchet, wait-discipline ratchet (with the new test) and semgrep 1.78.0 pass; the 97 related test files pass (2,109 and 1,772 passed, 1 skipped). scripts/local-gate.py --tree-scans ran its related set to green on the first commit (20,273 passed, 27 skipped); its whole-tree guard pass was still running on a shared host and is left to CI. On the repair: the 97 related files passed before its last fix (2,160 and 1,772 passed, 1 skipped); on this head the six files that fix touches or exercises (494 passed), test/test_facade_mirror_guards.py, the wait and flake ratchets, semgrep and docs-lint pass. mypy reports six errors in files this PR does not touch (missing third-party stubs, an aiohttp generic), from the local venv's site packages.

Base reds: main is red since 695f379 (#47829, the settings registry's guidable flag): Build Wheel, Build Desktop, E2E shards, Frontend Tests (settingsRegistry.test.ts), Backend Tests (3.12, 3) and Coverage Gate are expected red on this merge ref and are not caused by this diff.

Contribution License Agreement

Contributions are accepted under the project's Apache-2.0 license.

The dashboard reply mirror, the cron and sub-agent completion leg and
the compaction notice share messaging.egress, whose send step called
the plain transport.send_message. Their text is the agent's own
markdown, so on Telegram bold, inline code, fences and links arrived
literally, while a reply to a message typed in Telegram arrives
formatted.

send_channel_parts now calls transport.send_markdown. Telegram's
override renders to Telegram HTML, re-splits by rendered length and
falls back to the plain send on a refusal or an over-cap render; every
other transport inherits the base send_markdown, which is its
send_message, so their bytes are unchanged. The test doubles that
define only send_message get the same delegator real transports
inherit, and the messaging spec says which legs call send_markdown.

Fixes #47832
@winnythedev
winnythedev requested review from a team and KiroCrewCaptain as code owners December 5, 2026 17:44
@github-actions github-actions Bot added the readiness: checking Automated validation is still running label Dec 5, 2026
@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

UX Review (Opus 5.5) — ⏭️ skipped

Revision 74d6329d4a6699b2e8ab53cdbda8c462d547d727 touches no user-facing surface (no changes under website/ or committed screenshots), so the UX review was skipped. Does not block merge.

@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Design Review (Opus 5.5) — ✅ PASS

Design-level review of 74d6329d4a6699b2e8ab53cdbda8c462d547d727 — updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

Design-Verdict: PASS

Nothing blocks. The change adds one opt-in flag to the existing egress step and reuses the guarded send_markdown, so every other channel and every host-text leg sends exactly what it sent before.

[DESIGN-REVIEWED] 74d6329

Description read

[DESCRIPTION-READ] a3739956a32debed53b0cca457ca7319e85a4d75f022ea5231ed0c6d726e0778

That sha256 names everything this verdict read: the PR description, plus the 1 evidence file(s) the workflow collected from it and handed this review. It covers that evidence because the media strip replaces every attachment URL with the same placeholder, so an edit swapping one attachment for another would leave the description's captured text identical while what this review judged changed. Recompute it with .github/scripts/pr-description-capture.sh over the same inputs; if it differs, the description or that evidence changed after this verdict was formed and any finding drawn from either is unproven.

@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

First Principles Review (Opus 5.5) — ✅ PASS

Premise-level review of 74d6329d4a6699b2e8ab53cdbda8c462d547d727 — why this exists and whether the shipped surface is the smallest honest version. Updated in place on each push. A BLOCK verdict blocks PR readiness; PASS does not.

First-Principles-Verdict: PASS

Nothing blocks. The fix routes agent markdown through the existing send_markdown and adds no second render path. The backfill of past answers is the one sibling left on the plain send, and the description declares it out of scope.

Notes

  • Item 1 — symptom-level: the same cause is left in one counted sibling. I grepped \.send_message\( under dashboard/ and got 8 hits; one of them, chat_mirror.py:815, sends past agent answers through live_transport.send_message(conversation_id, unit, …). On Telegram those still show raw markup. The description declares this leg out of scope ("the mirror-link backfill of past answers"), so it is a deferred finding, not a demand.

What this change ships

Inventory (6 items) — 6 justified

Intent: Telegram users get agent replies, results and notices that arrive with no renderer formatted, not as raw markdown. This is a FIX (#47832, with tests that fail on base).

  1. A dashboard reply mirrored to a linked Telegram chat arrives formatted — justified
  2. A sub-agent completion in a Telegram chat arrives formatted — justified
  3. An agent's cron result arrives formatted, on the origin leg and on a pinned destination — justified
  4. The fixed compaction notice arrives formatted on Telegram — justified
  5. Host text (failure alerts, tracebacks, memory-guard and image notes) still arrives as written — justified
  6. An opt-in markdown keyword on send_channel_parts and its carriers, with three or more markdown=True callers — justified

[FIRST-PRINCIPLES-REVIEWED] 74d6329

Description read

[DESCRIPTION-READ] 024008241a56c6f24505c8548cdd1790a74ed98c1e006dd38fbe58276316268d

That sha256 names the PR description this verdict read. Recompute it with .github/scripts/pr-description-capture.sh; if it differs, the description changed after this verdict was formed and any finding drawn from the description is unproven.

@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

GPT 6.1 Review — ✅ no blocking findings

GPT 6.1 completed its review of 74d6329d4a6699b2e8ab53cdbda8c462d547d727 and found no blocking issues.

This comment is updated in place on each push.

Review details

No findings.
[GPT-REVIEWED] 74d6329

False positive or not applicable? A repository writer can comment:
/ai-review override gpt 74d6329d4a6699b2e8ab53cdbda8c462d547d727 false-positive: <reason, 20 to 500 characters>

@github-actions

github-actions Bot commented Dec 5, 2026 •

Copy link
Copy Markdown
Contributor

Opus 5.5 Review — ✅ no blocking findings

Reviewed 74d6329d4a6699b2e8ab53cdbda8c462d547d727 — this comment is updated in place on each push.

Review details

No findings.

Notes:

  • On Telegram the default cron caption Cron: {job.name} now goes through the markdown render. A job name holding a __x__ or **x** pair shows up bold on Telegram, while the Slack leg leaves the caption unconverted.

[OPUS-REVIEWED] 74d6329

Verdict parsed from the review's SHA-scoped output markers for commit 74d6329d4a6699b2e8ab53cdbda8c462d547d727.

False positive or not applicable? A repository writer can comment:
/ai-review override fable 74d6329d4a6699b2e8ab53cdbda8c462d547d727 false-positive: <reason, 20 to 500 characters>

A cron failure alert's plain twin reaches send_channel_parts through
the same origin leg as an agent's result, so rendering every part as
markdown rewrote a traceback on Telegram: __init__ turned bold and
2**10 lost its stars.

send_channel_parts now takes markdown (default False). The reply
mirror, an agent's cron result, a sub-agent completion and the fixed
compaction notice pass True; failure, crash and pause alerts, task-run
and approval notices, the memory-guard notice and the mirror's image
notes keep send_message and arrive as written. A cron's pinned
destination honours the same flag.

Refs #47832
@github-actions github-actions Bot added readiness: action required A blocking check or review needs attention readiness: checking Automated validation is still running and removed readiness: checking Automated validation is still running readiness: action required A blocking check or review needs attention labels Dec 5, 2026
@winnythedev

Copy link
Copy Markdown
Contributor Author
  • plain-text cron failure alerts go through the markdown renderer span=c6b0f4f2d343

fixed in 74d6329: send_channel_parts takes markdown (default False, the plain send).
Only agent-authored text opts in: the reply mirror, sub-agent completions, LLM cron results and post-sub-agent responses (origin leg and pin), and the fixed compaction notice.
Failure, crash, pause and interrupted alerts, reminders, script output, task-run and approval notices, the memory-guard notice and image notes keep send_message.
Pinned by test_a_cron_failure_alert_keeps_the_plain_send_byte_for_byte, test_a_pinned_cron_failure_alert_keeps_the_plain_send and test_host_text_on_the_pair_arrives_as_written (a traceback with __init__ and 2**10 arrives byte for byte, no parse_mode).

This branch has not been deployed

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

Labels

readiness: checking Automated validation is still running

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Telegram: mirrored dashboard replies, cron and sub-agent results and compaction notices arrive as raw markdown (**, backticks, [text](url))

1 participant