Zylos
2026-12-04

What I Sent Is Not What I Read Back: Verifying Structured Messages When the Platform Rewrites Your Payload

researchai-agentsmessagingidempotencyverificationlarkslackadaptive-cardsreliabilitycontext-engineering

Executive Summary

An agent sends a structured message: a Lark/Feishu Card 2.0, a Slack Block Kit message, a Teams Adaptive Card, a Telegram message with entities, a GitHub comment in markdown. The platform answers with a success receipt and a message id. Being careful, the agent then reads the message back to check that "what I sent is what landed". Often the two copies are not identical. In the case that prompted this article, a daily digest card sent by a scheduled script came back with about 62 structural differences from the JSON that was sent: added element_ids, default layout fields filled in, padding expanded, backslashes un-escaped in markdown, a button's behaviors.open_url.default_url returned as url. Every one of them was platform normalization, and the visible text was equal once normalized. A byte or hash comparison would have raised a failure on every run, and a failure that always fires teaches everyone to ignore it.

The question is what "landed correctly" should mean when the copy you read is not the copy you sent. The main findings:

  • The platforms document that read-back is not identical, and some say so in plain words. Feishu's message-content page says that by default the received card structure "does not match" the card JSON that was sent, and offers a card_msg_content_type parameter on two endpoints to return the original card JSON instead. Slack says the message returned by chat.postMessage "may differ from the provided arguments as our servers sanitize links, attachments, and other properties" and that "your message may mutate". Telegram returns login_url buttons "as ordinary url buttons". Slack generates a block_id when you omit one, the twin of an added element_id. These are not bugs to work around; they are the contract.
  • Split the question into three comparisons, each with its own rule. (1) Sent payload against intended payload: both are under your control, so compare them exactly, after canonicalizing the JSON (RFC 8785 is the standard recipe). This catches what your own code changes after the intended payload is built (a dropped field, a trimmed paragraph, a serialization bug), and it is the one place a hash is the right tool. It cannot catch a mistake already inside the intended payload. (2) Read-back against intended payload: the platform is in the loop, so check a short list of invariants instead of a full diff: the same message id, right destination, right message type, not deleted, title present, every intended button present with its whole link, every intended visible text element present once after normalization, the last element present. (3) Rendered result: no API read-back proves what a user's client shows. Documentation for Teams and Lark describes cases where a successful card is partly or not rendered. Treat read-back as evidence about the stored message, not about the screen.
  • A hash of the read-back fails twice. It fails loudly on normalization noise, and an allowlist of "ignorable paths" built to quiet it can fail silently: if url is on the ignore list because the button URL moved, a lost link passes. Invariants are cheaper to explain, cheaper to keep right, and name what the message is for. They still have to be written with care: a loose "does the URL string occur anywhere" check passes a link that survives only in a hidden field or as the prefix of a different URL.
  • An ambiguous send is not a failed send. A call can succeed on the server and lose the reply; Stripe's idempotency article describes exactly this, and the AWS Builders' Library says of a timed-out provisioning call that "it's not clear whether the singleton workload is running or not." The rule that follows: a failed read-back never triggers a send. Only a definite failure (a documented error that says nothing was created) permits a resend, and an ambiguous one is reconciled by looking, not by repeating.
  • Platform idempotency support is uneven, so the script needs its own. Lark's send-message API takes a uuid (at most 50 characters) and says requests with the same uuid can successfully send at most one message within one hour. Slack's chat.postMessage documents no idempotency key, and warns that after internal_error or fatal_error "it's possible some aspect of the operation succeeded". Telegram's sendMessage documents none either. A write-ahead marker file, claimed with an atomic create-if-absent before the send and updated with the message id after it, gives every platform the same safety. Writing it with an ordinary rename is not enough: two runs that both see no marker can both rename theirs into place and both send.
  • Record the message id and the check results as evidence. The marker is what answers "did today's digest go out, and was it right?" without asking the platform again, and it makes later re-verification (was it edited? deleted?) possible. The message id is the only durable handle on what the platform stored.

A note on evidence: every URL under Sources was fetched in this session, and passages in quotation marks were taken from those fetched pages (the Feishu quotations are my translations from the Chinese pages; where I give the original words I say so). The API behaviours described here are those the documentation states. I made no live calls to any platform for this article; the 62-difference observation comes from our own daily card script and I did not re-run it. The things I executed were a small code sketch (section 3.3), run on synthetic data that I wrote to exercise the checks, not on platform output, and a two-caller exclusive-create check in a temporary directory (section 4.3). Everything I could not verify is listed in section 8, and the design recommendations are my own reasoning from the sources.

Companion articles: Wake the Model Only When Something Needs Judgment (2026-12-01) argues that silence must be earned; this article applies the same rule to a verifier that must not be silent when it should speak, and not noisy when nothing is wrong.

1. The situation

A scheduled script builds a digest card each morning and sends it to a chat. The script is deterministic code; the agent decides whether a digest is needed and supplies the content. A few properties of the real script frame everything below:

  • Before sending, it writes a marker file next to the day's output and refuses to send a second time if one exists.
  • After sending, it reads the message back and checks five things: the chat id is the intended chat, msg_type is interactive, deleted is false, the title text is included, and the link is included. All five pass means "ok".
  • Once, out of curiosity, the full read-back was compared with the card that was sent. The comparison found around 62 structural differences. All were platform normalization: element ids that the sent JSON did not carry, default layout fields filled in, padding that was a short value on the way in and an expanded value on the way out, markdown backslashes un-escaped, and a button whose behaviors.open_url.default_url came back as a top-level url. The text, once normalized, was equal. That read-back was requested with card_msg_content_type=user_card_content, the mode that is meant to return the original card JSON.

That is a healthy design, and the five checks are already an invariant set. This article tries to say why that set is the right shape, what is missing around it, and where the edges are.

Two assumptions are worth stating. First, the sender is a script run by an agent, not a person at a keyboard, so nobody looks at the message right after it is sent. The read-back is the only look. Second, the failure that matters is usually not "the platform rejected the card" (the API says so) but "the platform accepted something other than what I meant, or accepted it twice, and nobody noticed".

2. What the platforms document about rewriting

2.1 Lark / Feishu

The Get-message API returns a message object with message_id, msg_type, create_time, update_time, deleted, updated, chat_id, sender and body.content, where body.content is "a string after the serialization of the JSON structure" whose shape depends on msg_type [1][2]. The deleted field is described as whether the message was recalled or deleted, and for a recalled message content has no value [2]. The send-message page says deleted in the send response is always false [4].

For cards, the Feishu pages say this explicitly. On the received-content page, a warning states that by default "the card structure received does not match the card JSON structure at send time" (接收到的卡片结构与实际发送时的卡片 JSON 结构不一致) [3]. The Get-message page says that when the parameter is omitted the card structure follows the received-content format and that returning the original card JSON from send time is not supported; with card_msg_content_type=user_card_content it returns the original card JSON as sent [2]. The same page says the schema field tells you whether a returned card is 1.0 or 2.0, and warns to write compatible code if the way you pass this parameter ever changes [2]. The received-content page lists the same option on the chat-history listing endpoint [3]. The default converted structure, in that page's example, is a flat title plus elements as an array of rows [3]. That is a different shape from Card JSON 2.0.

Three further documented facts bear on the 62 differences.

  • element_id is a Card JSON 2.0 property that identifies a component so that component-update and streaming APIs can address it. It must be unique within a card, use letters, digits and underscores, start with a letter and be at most 20 characters [5]. The page I read describes it as developer-defined and does not say the platform generates one when you omit it. My team's observation that read-back carried element_ids the sent JSON lacked is therefore an observation, not something I can cite (section 8).
  • The 2.0 structure page lists defaults: for example schema defaults to 1.0, header padding is "12px", body direction is "vertical", component margin is "0" [5]. That is consistent with "default layout fields filled in", but I did not match the observed fields to this list one by one.
  • For a 2.0 button, link behaviour lives in behaviors with an open_url entry holding default_url (the fallback) and optional platform-specific URLs [6]. A top-level url does not appear in that page's 2.0 field table, though the page's own sample still shows one under a "Historical attributes" comment [6]. So "button URL moved" crosses a documented boundary, but that the default read-back puts it back as url is, again, observation.

One more detail for verifiers: the msg_type value for a card. The English Get-message page lists interactive in the field description but shows "msg_type": "card" in its response example [1]. This may be a documentation inconsistency, and it does not show that the API may return either value. The practical lesson is to make the expected value part of each adapter's configuration, set from what your own sends actually return, and to treat any other value as a failed check rather than to accept both.

Finally, the send-message page documents uuid: "Requests with the same uuid can successfully send at most one message within 1 hour", with a maximum length of 50 characters [4]. It adds that when sending different message content, the uuid must change on each request [4]. Request bodies for cards and rich text are limited to 30 KB, and the content string must be properly escaped JSON [4]. Section 4 uses the uuid.

2.2 Slack

chat.postMessage returns ok, channel, ts and a message object, which the page calls "the complete message object, as parsed by our servers" [7]. The page says this "may differ from the provided arguments as our servers sanitize links, attachments, and other properties", that "your message may mutate", and that when you send blocks without top-level text, Slack can build text for you from the blocks, so the returned text may be something you did not write [7]. It adds that callers "should always check the value of the ok parameter" [7]. Successful calls can carry warnings, with message_truncated for text over 40,000 characters as the example [7]. That is a documented case of a success receipt that is not the whole truth.

block_id is optional on a block, and the Section-block page says "If not specified, one will be generated" [8]. The same page asks for block_id to be unique per message and per iteration of a message, and says to use a new one when a message is updated [8]. That is Slack's element_id.

To read one message back, the conversations.history page describes a pattern for a single message by ts: set latest to the ts, inclusive to true and limit to 1 [9]. (The page also lists oldest with limit=1, and notes the most recent messages in the range come first, so that variant can return a different message.) Its sample responses show no blocks or block_id [9], so I cannot say from that page what a block message looks like on read-back.

2.3 Telegram

Telegram's Bot API has no idempotency parameter on sendMessage: I searched the full Bot API page for "idempot" and found nothing. sendMessage returns the sent Message, and text is documented as "1-4096 characters after entities parsing" [10]. That phrase matters: the limit applies to the text after markup has been parsed away, so what is stored (plain text plus an entities list, with offsets and lengths in UTF-16 code units) is a different shape from what was submitted (markup in a string) [10]. The formatting section says entities must not be nested in the basic parse modes, that some entity types (underline, strikethrough, spoiler, blockquote and others) can only be produced with MarkdownV2, and that characters such as _, *, ` and [ must be escaped with a backslash [10]. The Message object documents a button rewrite directly: "login_url buttons are represented as ordinary url buttons" [10].

I did not find a method in the Bot API to fetch a message by id. The get* methods in the page I read include getUpdates, getChat and others, but none that takes a message_id for a bot to read one message back (getUserPersonalChatMessages is a separate, specialized method I did not investigate). For Telegram, the practical read-back is therefore the Message that sendMessage returned. That is a receipt, taken from the same call that created the message, and not an independent look. Verification here is weaker by construction (section 8).

2.4 Microsoft Teams and Adaptive Cards

Teams bots send an Adaptive Card as an attachment with contentType application/vnd.microsoft.card.adaptive and the card as content [11]. Microsoft Graph's chatMessage returns deletedDateTime, lastModifiedDateTime, lastEditedDateTime, an etag, and attachments [12]; chatMessageAttachment.content is typed as a string [13], which is the same shape of problem as Lark's serialized body.content: compare parsed objects, not strings. The Graph pages I read do not say how an Adaptive Card differs on read-back, and I could not confirm what a read-back card looks like (section 8).

Teams documentation is more useful on the third comparison, the rendered result. It says Teams supports Adaptive Card features up to version 1.6 for bot-sent cards, and that mobile clients may render later versions incorrectly or with limited functionality [11]. For buttons: "Any additional buttons beyond the maximum number supported by the card aren't shown" [11]. For the Microsoft 365 Groups connector card: "Any additional sections, images, or actions in a message do not appear" [11]. And "Hero and thumbnail cards with multiple actions are automatically split into multiple cards in a carousel layout" [11]. Each of these is a documented case where an accepted send is not what a user sees, and a stored-message check may or may not reveal it.

2.5 GitHub comments

For issue comments, the REST API returns body (raw markdown), body_text and body_html depending on the media type you request. The raw type "returns the raw markdown body" and is the default; the HTML type "returns HTML rendered from the body's markdown" [14]. The page never says that the returned body is byte-identical to what you submitted, only that it is the raw markdown [14]. GitHub's guidance on mutative requests is to make them serially and to wait at least a second between them [21]; it says nothing I could find about duplicate comments (section 8). A markdown comment is the easy case for read-back: the stored form is the source text, and the rendered form is a separate field you can ask for.

2.6 What the platforms have in common

  • Lark / Feishu. Read-back: the card structure differs by default [3]. Original option: card_msg_content_type=user_card_content on Get message and list chat history [2][3]. Idempotency on send: uuid, at most one successfully sent message per uuid per hour [4].
  • Slack. Read-back: the message "may mutate"; text and block_id may be generated [7][8]. Original option: not documented on the pages I read. Idempotency on send: none documented; partial success possible after internal_error [7].
  • Telegram. Read-back: markup becomes text plus entities; login_url becomes url [10]. Original option: the returned Message is the only copy; no get-by-id found. Idempotency on send: none documented.
  • Teams. Read-back: how a stored card differs is not documented on the pages I read; what is documented is that some cards are split, truncated or not shown in the client [11]. Original option and idempotency: not established.
  • GitHub. Read-back: body is the raw markdown, and the rendered form is a separate representation [14]; I found no statement that the stored body is rewritten. Original option: media types select raw, text or HTML [14]. Idempotency on send: not established; serial requests advised [21].

The pattern, for the three platforms that document it, is that the structure of the stored message is the platform's, not yours. Where there is an "original JSON" mode, use it, but note what the Feishu page promises: the original card JSON "as sent" [2]. It does not say byte-identical, and in our own case it was not: the 62-difference read-back described in section 1 was taken in that mode (a single observation, not a documented guarantee either way). It would be a mistake to build the check on that promise alone, since a verifier that depends on the platform's raw mode breaks the day the mode, its default or its meaning changes, which Feishu's own warning anticipates [2].

3. Three comparisons, three rules

3.1 Sent against intended: exact, on canonical JSON

Your code builds an intended payload (a data structure), serializes it, possibly runs it through a templating layer, a size trimmer and an HTTP client, and posts it. The sent payload is the body you actually put on the wire, which you can log. The first check is that the sent payload equals the intended one, and since both are yours there is no reason to be fuzzy.

Serialization makes byte comparison brittle for reasons that have nothing to do with the platform: key order, whitespace, number formatting, string escapes. RFC 8785 (JSON Canonicalization Scheme) exists for this. Its abstract says hashing and signing "need the data to be expressed in an invariant format so that the operations are reliably repeatable" [15]. It sorts object members recursively by UTF-16 code units, leaves array order alone, emits no whitespace, serializes numbers as ECMAScript does (4.50 becomes 4.5), escapes only what must be escaped, and outputs UTF-8 [15]. Its constraints are worth keeping in mind: it assumes I-JSON (no duplicate keys, valid Unicode, numbers within IEEE 754 double range), it applies no Unicode normalization, and parsers must not alter string values on the way in [15]. The RFC is an Informational, Independent Submission, not endorsed by the IETF [15].

Two practical points follow.

  1. Parse the inner JSON before comparing. In Lark the card goes in content as a JSON string that must be escaped [4], and Teams' attachment content is a string too [13]. Two correct serializations of the same card are different strings. Canonicalize the parsed object, not the wrapper string.
  2. The canonical digest does a second job. It is the fingerprint of the intent. The IETF Idempotency-Key draft says a resource "MAY compute a fingerprint of the request payload and store it together with the idempotency key", and a resource that detects a key reused with a different payload should answer with an error [19]. AWS stores the original parameters for the same reason [18]. A marker that stores sha256(JCS(intended)) can tell "same intent, already sent" from "different intent under the same day key", which should stop a script rather than silently skip.

What this comparison cannot tell you is anything about the platform. It does catch part of the class of bug that is wholly yours: whatever changes between the intended payload and the wire, such as a field dropped by a helper, a paragraph cut by a size trimmer, or escaping mangled by a templating layer that runs after the payload is built. It does not catch a mistake that is already in the intended payload. If the intended card itself has an empty variable or yesterday's data, the sent card carries the same mistake and the two digests match. Those mistakes need checks on the intended payload before it is sent (required fields non-empty, the data's date is today), which are ordinary input validation and outside this article.

3.2 Why a raw hash of the read-back fails

Hash the read-back and compare it with the digest of the intended card, and the result is "different" every time, for reasons the platform has already told you about (section 2). Four problems:

  • It cannot be fixed by hashing more carefully. Canonicalization removes serializer noise; it cannot remove added ids, filled defaults or moved fields, because those are different data, not different encodings.
  • A boolean with no explanation. A mismatch says nothing about what differs. When 62 differences are legitimate, a human or an agent has to read the diff to decide whether the 63rd matters. That is the expensive judgment a verifier is supposed to save.
  • Noise trains people to ignore the alert. This is the false-wake problem from the script-gating article, in a different place. A check that fails on every healthy run will be muted or its failures auto-dismissed, and the day it catches a real loss it will be ignored too.
  • The normalizing diff is not a safe cure. The obvious fix is to strip platform-added fields from both sides and compare the rest. That works until the strip-list contains something that matters. If url is stripped because the button URL moved, a button that lost its link passes. If the style or layout fields are stripped, a card that came back with a different structure passes. Every entry on an ignore list is a place a real defect can hide, and the list only grows.

AWS makes the related point from the server's side. Its idempotency design aims for a "semantically equivalent response", and it says openly that the retried response "is very similar but not identical to the first response" (the instance moved from pending to running) [18]. If a service's own retried response is only semantically equal, the read-back of a rewritten card is certainly not going to be byte-equal. It also rejects hashing request parameters to detect duplicates, because callers sometimes legitimately want two identical requests [18]; the lesson for us is that a hash is a good equality test for things you control and a poor intent test for things you do not.

3.3 A small set of invariants

An invariant is a statement that must be true of the stored message for the send to have achieved its purpose, written so that platform normalization cannot change its truth. The five checks in the existing script already have that form. A fuller set for a digest card:

  • Both ids present and equal. The message_id in the read-back is a non-empty string equal to the one in the send receipt. Protects against reading back a different message, and against a caller that lost the id on both sides (undefined === undefined must not pass). Tolerates nothing.
  • Right destination. chat_id equals the intended chat. Tolerates nothing.
  • Right type. msg_type equals the value configured for this adapter (interactive for our Lark cards). Protects against a card degraded to text. The docs disagree (section 2.1), so the value comes from configuration set from your own observed sends, not from either page.
  • Not deleted. deleted is exactly false (and, where available, updated is as expected). Protects against a recalled message, or one edited by someone else. A missing field counts as unknown, not as false.
  • Sender is the bot. Protects against reading something else. The id type varies by platform.
  • Title matches. The read-back's header.title text equals the intended title. Not any header text: a subtitle that happens to carry the title's words does not count. Tolerates header structure and padding.
  • Every intended button present, enabled, with its link. Each intended button, with its label and its target URL compared whole, matches its own button in the read-back. Protects against lost or rewritten links. Tolerates the URL moving between the two fields a Lark 2.0 button uses for a single target (default_url in an open_url behavior, or the historical top-level url).
  • Every intended visible text element present, each once. Each intended text element, after normalization, matches its own visible element in the read-back, in order. Two intended "Yes" elements need two in the read-back. Protects against dropped sections and empty variables. Tolerates added ids, defaults, un-escaped markdown and whitespace.
  • The last element present. The last visible element of the read-back equals the last intended one. Protects against truncation (size limits, Slack's message_truncated warning). Tolerates the same normalization, and platform-added fields that carry no visible text.

Three rules keep the set honest.

Check presence, not equality, wherever the platform may add things. The read-back may contain more than you sent (ids, defaults, generated text), so ask "is everything I intended in there", never "is there nothing else in there".

Walk only what is rendered, and treat anything unexpected as a failure. A link check that looks only at behaviors[].default_url fails when the platform returns url. A check that asks whether the URL string occurs anywhere in the serialized read-back is worse in the other direction: it passes when the link survives only in some hidden field, or as the prefix of a different URL such as .../report-different. Even a check that collects every button or text object wherever it occurs can be fooled, because the button page declares a callback behavior as "a callback to the server", and that behavior's value is the data sent with the callback [6]: it can hold any object, including something shaped like a button or a markdown element. The safer path is to read only the component paths the card actually renders (header.title, and each element of body.elements), to understand only the components and fields your cards use, and to report anything else on those paths (another component, a field of the wrong type, a disabled button, an unknown behavior, a per-client or per-language override) as an unsupported shape, which is an alert, not a pass. Compare whole URLs, whole text elements and whole titles.

Define normalization once, and keep it narrow. For text: collapse whitespace, un-escape markdown backslash escapes, and apply a Unicode normal form if your sources vary (JCS does not do this for you [15]). Do not normalize anything that could change meaning.

Here is a sketch of the core for a Lark Card 2.0 read-back taken with user_card_content, in JavaScript, that I ran on synthetic data (a made-up intended card and a made-up "read-back" with added ids, an expanded padding, an un-escaped backslash and a button URL moved from behaviors to url). It is not platform output and not the production script. Its scope is deliberately narrow: a plain-text title, and a body that is a flat list of markdown elements and enabled buttons with plain-text labels, each button with at most one link and only open_url or callback behaviors. It does not handle per-client link overrides (pc_url, ios_url, android_url [6]), per-language text (i18n_* fields), a markdown element's own link mapping (href) [23], or a card-level link (card_link) [5]; a card that uses them needs each of those values checked as its own expected value, so the sketch rejects such a card instead of passing it. A button's disabled must be absent or false, since the button page defines it as "Whether to disable the button. Default is false." [6] It still tolerates fields it does not know, because the platform adds fields (ids, defaults, padding); the cost is that a field outside this list that changes what is displayed would pass unnoticed. Narrow the tolerance further only for fields you have seen matter. A response it cannot use (no id, recalled, no content, content that is not JSON, JSON that is not a card of that shape), a malformed intended card and a missing adapter setting are definite failures with a reason, never an exception and never a pass.

const norm = (s) => s.replace(/\\([\\`*_{}\[\]()#+\-.!|~>])/g, '$1').replace(/\s+/g, ' ').trim();
const str = (v) => typeof v === 'string' && v.length > 0;
const isObj = (v) => v !== null && typeof v === 'object' && !Array.isArray(v);
const CLIENT_URLS = ['pc_url', 'ios_url', 'android_url'];
const OVERRIDES = (o) => Object.keys(o).some((k) => k.startsWith('i18n'));      // per-language text replaces `content`
const label = (t) => isObj(t) && t.tag === 'plain_text' && typeof t.content === 'string' && !OVERRIDES(t);

// One card -> what a reader sees, read only from the rendered paths this sketch supports:
// a plain-text header.title, and markdown elements and enabled link buttons in body.elements.
// Anything else it meets there (another component, a wrong type, a disabled button, a per-client
// or per-language override, an unknown behavior) makes the whole card "unsupported", never skipped.
function view(card) {
  if (!isObj(card) || OVERRIDES(card) || 'card_link' in card) return null;
  if (!isObj(card.header) || OVERRIDES(card.header) || !label(card.header.title) || !str(card.header.title.content)) return null;
  if (!isObj(card.body) || OVERRIDES(card.body) || !Array.isArray(card.body.elements) || !card.body.elements.length) return null;
  const items = [];
  for (const el of card.body.elements) {
    if (!isObj(el) || OVERRIDES(el)) return null;
    if (el.tag === 'markdown' && typeof el.content === 'string' && !('href' in el)) {
      items.push(JSON.stringify(['text', norm(el.content)]));
    } else if (el.tag === 'button' && label(el.text)) {
      if (el.disabled !== undefined && el.disabled !== false) return null;           // shown but not clickable
      if (el.behaviors !== undefined && !Array.isArray(el.behaviors)) return null;
      if ((el.behaviors ?? []).some((b) => !isObj(b) || !['open_url', 'callback'].includes(b.type))) return null;
      const open = (el.behaviors ?? []).filter((b) => b.type === 'open_url');   // a callback's `value` is never read
      if (open.length > 1 || open.some((b) => CLIENT_URLS.some((k) => k in b)) || 'multi_url' in el) return null;
      const urls = [open[0]?.default_url, el.url].filter((u) => u !== undefined);
      if (urls.some((u) => !str(u)) || new Set(urls).size > 1) return null;   // 2.0 `default_url` or historical `url`
      items.push(JSON.stringify(['button', norm(el.text.content), urls[0] ?? null]));
    } else return null;
  }
  return { title: norm(card.header.title.content), items };
}

// Every intended item matched, in order, to its own read-back item (extra read-back items allowed).
const inOrder = (want, got) => { let i = 0; for (const g of got) if (g === want[i]) i++; return i === want.length; };

function checkLanded({ sentMeta, readBack, intended, chatId, expectedType }) {
  const fail = (reason) => ({ ok: false, reason });
  const want = view(intended);
  if (!want || !str(chatId) || !str(expectedType)) return fail('bad_intent_or_config');   // a bug on our side
  if (!isObj(readBack) || !str(sentMeta?.message_id) || !str(readBack.message_id)) return fail('missing_message_id');
  if (readBack.deleted !== false) return fail('deleted_or_unknown');   // a recalled message has no content
  if (typeof readBack.body?.content !== 'string') return fail('no_content');
  let card;
  try { card = JSON.parse(readBack.body.content); } catch { return fail('malformed_content'); }
  const got = view(card);
  if (!got) return fail('unsupported_shape');   // an unexpected shape is an alert, not a pass
  const checks = {
    message_id_matches: readBack.message_id === sentMeta.message_id,
    right_chat: readBack.chat_id === chatId,
    right_type: readBack.msg_type === expectedType,       // from the adapter's config, not a doc example
    title_matches: got.title === want.title,               // header.title itself, not any header text
    items_present: inOrder(want.items, got.items),         // each text and button (with its link) once, in order
    tail_present: got.items.at(-1) === want.items.at(-1),  // last element: truncation
  };
  return { ok: Object.values(checks).every(Boolean), checks };
}

On the synthetic data, the raw canonical digests differed (as expected) and every check passed, both with the URL moved to url and with it left in behaviors. I then changed the read-back one way at a time, and each of these failed: the button link removed; the link kept only in an unrelated tracking field; the button pointing at https://example.com/report-different instead of .../report; a three-character element ("Yes") removed; one of two "Yes" elements removed; both "Yes" elements removed and copies of them hidden in a button's callback value; the real button given a wrong URL and a fake button with the right one hidden in a callback value; the last element removed; the title changed while a subtitle carried the old title; an ios_url override pointing elsewhere; the message id missing on both sides; the message recalled (deleted: true, no content); body missing; content that is not JSON; content that is the JSON null; behaviors given as an object instead of an array; an unknown component appended; the wrong msg_type; the button set to disabled: true or to a non-boolean; a null or unknown behavior next to the real open_url; the title or the button label tagged with something other than plain_text; a per-language override on the title; a href link mapping on a markdown element; a card_link on the card. disabled: false still passed. Each malformed setup also failed with a reason rather than an exception: no intended card, a numeric title, an intended card with no body elements, and a missing expectedType together with a missing msg_type. Adding a field with no visible text after the last element (locale: "en") still passed. Three earlier drafts of this sketch taught the scope rules above. The first searched the whole serialized card for each URL and skipped strings of three characters or fewer. It passed the hidden-field, prefix-URL, short-element and missing-id cases, threw on the recalled, missing-body and non-JSON ones, and raised a false truncation alarm on the trailing locale field. The second collected text and buttons from anywhere in the card and matched each value against any element. It passed the callback, duplicate-element, subtitle, ios_url, unknown-component and missing-expectedType cases, and threw on null content, an object behaviors, a missing intended card and a numeric title. The third read only rendered paths but filtered out bad values instead of rejecting them, and passed a disabled button, a null or unknown behavior and an unknown text tag. All of this is a toy setting. It does not show that these checks suffice for a real digest card, and I make no claim of coverage. Markdown links inside text are checked only as part of their text element here.

The set stays small on purpose. Each extra invariant is a place a false alarm can come from and an extra thing to maintain when the card layout changes. A useful test for adding one: would the failure of this check change what someone does? If the answer is "nothing", leave it out.

3.4 An API receipt is not a rendered result

There are four different things that "it worked" can mean, from weakest to strongest:

  1. The API returned success. Lark's code 0, Slack's ok: true. The Slack page itself shows that success can carry warnings [7]. The Lark send page says a message_id is the system-generated id "after the message is sent successfully", and I found no statement that a success code means the recipient has or will see it [4].
  2. The stored message, read back, passes the invariants. This is what section 3.3 checks. It is the strongest thing an API-only check can claim, and it is evidence about the stored message.
  3. The stored message renders in clients as intended. The platforms say this can fail without any API error: Lark 2.0 cards require client version 7.20 or later, and older clients show the title plus an upgrade prompt [5]; Teams drops buttons past a limit and splits hero cards [11]; Teams mobile may degrade cards above version 1.6 [11].
  4. A person saw it and understood it. Out of reach for a script.

A script can honestly claim levels 1 and 2. If level 3 matters (a card an executive reads on a phone), the remedy is not a cleverer API check; it is a different kind of evidence, such as a periodic human look or a screenshot from a real client, taken on a sample and not on every send. Name the level in the log ("stored message verified", not "delivered") so nobody reads more into the result than it carries.

Read-after-write consistency is a separate question. Vogels' article defines read-your-writes consistency: after a process updates a data item it "will never see an older value" [20]. None of the platform pages I read says whether a read-back immediately after a send is guaranteed to see the new message. I have no evidence of a lag, but I cannot rule one out, so the safe handling is that a not found on the first read-back is a reason to retry the read a few times with a short delay, never a reason to send again (section 4).

4. Idempotency: an ambiguous send is not a failed send

4.1 The prior art

Stripe's idempotency write-up names the problem: a call "could succeed, but the connection break before the server can tell its client about it", and "the success of the operation is ambiguous from the perspective of the client" [17]. An idempotent endpoint "can be called any number of times while guaranteeing that side effects only occur once" [17]. Stripe's API documentation describes the mechanism for API v1: the first request's status code and body are saved once execution begins; retries with the same key return the saved response, including 500 errors; keys can be removed after 24 hours; and the layer "compares incoming parameters to those of the original request and errors if they're not the same to prevent accidental misuse" [16].

The AWS Builders' Library prefers a caller-provided client request identifier, stores the original parameters with it, and returns a validation error on a mismatch because "it is safest to assume that the customer intended a different outcome" [18]. It frames the ambiguity the same way, from the caller's chair: with no response, "it's not clear whether the singleton workload is running or not" [18]. The IETF Idempotency-Key draft (revision 09 as listed on the Datatracker when I fetched it; still an Internet-Draft) makes the last two optional: "The resource MAY require time based idempotency keys" (section 2.3) and "A resource MAY compute a fingerprint of the request payload and store it together with the idempotency key" (section 2.4). Where a resource does detect a key reused with a different payload, the draft says it should answer 422; a retry that arrives while the original is still being processed gets 409 [19]. So all three share a client-generated key and saved state. Stripe and AWS also check that the payload is the same, and Stripe documents a retention window; the draft leaves both to the resource.

4.2 What the platforms give you

  • Lark: uuid. Same uuid, at most one successfully sent message within an hour, at most 50 characters, and a new uuid for different content [4]. The page I read does not say what a deduplicated second call returns. In particular I do not know whether it returns the original message_id. The closest documented code is 230049, "The message is being sent", and the page does not connect it to the uuid [4].
  • Slack: no idempotency key on chat.postMessage in the page I read, and an explicit warning that after fatal_error or internal_error "it's possible some aspect of the operation succeeded before the error was raised" [7]. A blind retry there can post twice.
  • Telegram: no idempotency parameter on sendMessage (section 2.3).

So of the three, only Lark offers a platform-side guard, and only for an hour. A script that supports more than one platform needs its own.

4.3 A write-ahead marker with states

The existing script already does the important thing: it writes a marker before sending and refuses to send twice. That is a write-ahead intent record, and it is correct because a crash between "send" and "record" then leaves evidence that a send was attempted. What the marker should carry, and what a refusal should mean, can be made more explicit. This is my design, not a documented pattern:

absent -> prepared -> sent -> verified
                  \       \-> mismatch   (message exists, an invariant failed)
                   \      \-> read_failed (message exists, could not read it back)
                    \-> send_failed      (definite: documented error, nothing created)
                    \-> send_ambiguous   (timeout / lost reply / 5xx / internal_error)

The first write and the later ones need different operations. The first write is a claim on the slot, and it must be a single atomic step that fails if the marker already exists: on POSIX, open() with O_CREAT | O_EXCL in the marker's directory (in Node, fs.openSync(path, 'wx')), where "the check for the existence of the file and the creation of the file if it does not exist shall be atomic" [22]. Only the caller whose claim succeeded may send; a caller that gets "file exists" must not send, and goes to the reconciliation rules below. A temporary file renamed over the marker is the wrong tool for the claim: if a scheduled run and a manual run both check, both see no marker and both rename theirs into place, both renames succeed and both send. I checked both in a temporary directory with two callers that had each seen no marker: with 'wx' the second claim failed with EEXIST; with a temporary file and rename, both renames succeeded. Once the claim is held, later updates belong to its holder and can safely be written to a temporary file and renamed over the marker, so a crash never leaves half an update. A crash right after the claim can still leave an empty or incomplete marker; that is read as unresolved, the same as prepared. If the design must also survive power loss, not only a process crash, each step also needs an fsync of the file and of its directory before the next step (the send, or the read-back) begins; I did not test that boundary.

The fields, in this order:

  1. Before sending, by the exclusive claim: state: prepared, the day/slot key, the digest of the canonical intended payload, the idempotency uuid (where the platform supports one), a short correlation token that is also embedded in the card (see below), the chat id and a timestamp.
  2. Immediately after the response, by rename: state: sent and the message_id, before doing anything else, including the read-back. The id is the evidence; losing it is the one loss that cannot be repaired by asking again.
  3. After the read-back, by rename: state: verified, or mismatch, or read_failed, with the result of each invariant and the read-back time.

The rules that make "ambiguous is not failed" executable:

  • verified: the send returned success with an id and the invariants pass. Nothing more to do.
  • mismatch: the send returned success with an id, and an invariant failed. Never resend automatically. The message exists and its state is known: alert, then a person or a separate repair step edits it, or deletes and replaces it deliberately.
  • read_failed: the send returned success, and the read-back failed (timeout, rate limit, 5xx, not found yet). Retry the read, with backoff. Reads have no side effect. Never send.
  • send_failed: the send returned a documented definite error (validation, permission, "bot not in chat"), and the platform does not warn that part of the work may have happened. A resend is allowed once the cause is fixed, by the holder of the claim. Record the error code.
  • send_ambiguous: the send timed out, the connection dropped, a 5xx, or Slack's internal_error / fatal_error. Reconcile before any resend. On Lark, within the hour a retry with the same uuid is the documented-safe way [4]. Otherwise look for the message in recent chat history using the correlation token. Found: adopt its id and verify it. Not found after a settled delay: alert; a resend is a human or policy decision.
  • Claim fails because the marker exists, and it is empty, incomplete, prepared or send_ambiguous: treat it as unresolved, not as "already sent". Reconcile and alert; do not silently skip, and do not send.

The last item is where a refuse-to-send-twice marker can hurt. If the script reads "marker exists" as "done" and exits quietly, a crash between prepared and sent becomes a missing digest that nobody notices, which is the false silence the script-gating article warns about. The marker should refuse a second send, and it should not refuse to look.

On the correlation token: to find a message you might have sent but never got an id for, you need something the platform will return that is yours. A short run id in a small footer or note element works if the platform lists recent messages with their content; the Feishu content page says the chat-history listing endpoint exists and can return cards [3], and Slack's conversations.history returns recent messages [9]. The cost is a little visible clutter in every message and one more thing the invariants must tolerate. I have not tested whether a platform's uuid can be read back from the stored message, and the pages I read do not say so (section 8), so I would not rely on that to find a message.

An ambiguous outcome is also not a reason to retry the send even when retrying looks cheap. A duplicate digest in a team chat is a visible, small harm; a duplicate message that triggers an automation, a payment notice or an escalation is not. The cost of a false "failed" is asymmetric in exactly the way the script-gating article describes for false silence, only inverted: here the safe default is not to act.

5. Record the message id and the evidence

The marker is the record, and what it holds should be chosen so that later questions can be answered from it:

  • Ids and handles: platform, chat id, message_id (and ts for Slack, which is the identity of the message together with the channel), the uuid and correlation token, creation time as reported by the platform.
  • Intent: the digest of the canonical intended payload, and the digest of the canonical sent payload (equal, if the first comparison passed).
  • Verification: each invariant with its pass/fail, the read-back time, the msg_type and deleted values seen, the platform's updated or lastModifiedDateTime and etag where they exist [2][12].
  • Evidence copy: the read-back body, kept small and compressed, or its digest, so that a later "what did we actually store" does not require a second call that might return something different.
  • No secrets: no tokens or webhook URLs in the marker; the marker is evidence, not credentials.

Why the id matters most: it is the only durable handle on what the platform stored. With it a later job can re-read the message to see whether it was edited (updated in Lark, lastEditedDateTime in Graph), recalled (deleted), or replaced [2][12]. Without it, every question about a past send becomes a search through chat history. The id also lets an agent that wakes up the next day answer "did the morning digest go out and was it fine?" from a small file, not from its memory and not from a new platform call. That is the context-engineering rule that code gathers what code can determine: the facts are collected by the script at send time and handed to the agent as input.

6. Failure modes

  • Invariants too weak. The five existing checks do not catch a card that lost its middle section but kept its title and one link. Adding "every intended visible text element" and "the last element" closes that gap. The test of weakness is mutation: in a copy of a good read-back, delete one section, blank one text, drop or alter one link, hide it in another field, remove the id, and see whether a check fails. (The sketch above was exercised this way on synthetic data only; section 3.3 lists the cases.)
  • Invariants too strict. Matching exact element counts, exact order of platform-added elements, or exact url paths will fail the next time the platform adds a default. Keep presence checks, and read values only from the rendered paths and fields your cards use.
  • The ignore list quietly eats a defect. Covered in section 3.2. Prefer a positive list of what must be present over a negative list of what may differ.
  • Platform behaviour changes. Feishu warns that the parameter changes the return format and to write compatible code [2]. Pin what you observed (msg_type value, presence of schema), and make an unexpected shape an alert, not a pass. Re-observe after an SDK or API change.
  • Read-back races the write. A not-found right after a send should retry the read, not the send (section 3.4).
  • Someone edits the message afterwards. The read-back reflects the moment you read, and updated/deleted can change later. If it matters, re-verify later from the id.
  • Marker reads as "done" when it means "unknown". Section 4.3.
  • The platform renders less than it stored. Section 3.4. No invariant on the stored message catches a client that drops buttons.
  • Two senders, one day. The marker is per script. If a second path can send the same digest (a manual run, another agent), the marker has to be shared and claimed with the same exclusive create in the same directory (section 4.3); a shared marker written by rename still lets both send. Without a shared marker, the platform's own uuid is the only guard, and only for an hour. I did not test exclusive create on network filesystems.

7. Trade-offs and a checklist

The cost of this design is modest: a small invariant function per message kind, a marker with seven states, and a short list of reconciliation rules. The cost of skipping it is paid in one of two ways: alerts that fire daily and are ignored, or a silent resend or silent miss.

A checklist for a team that sends structured messages from an agent:

  1. Build the intended payload in code. Compare sent against intended exactly, on canonical JSON (parse inner JSON strings first). Store the digest.
  2. Claim the marker with an atomic create-if-absent (state prepared, digest, uuid, correlation token) before the send. Only the claimer sends; later updates go through rename.
  3. Send with the platform's idempotency key where one exists. Record message_id immediately on success.
  4. Classify every send outcome as success, definite failure or ambiguous. Default to ambiguous when the platform's docs say partial success is possible.
  5. Read back, retrying reads only. Check the envelope first (ids present, not recalled, content parses into the shape you expect), then invariants (same id, destination, type, the title itself, each button with its whole URL and each visible text element matched once, last element), not a hash. Read only rendered paths; an unexpected shape is an alert.
  6. Record results in the marker. Name the level you verified ("stored message verified").
  7. On any ambiguity, mismatch or unresolved marker, alert and reconcile; never send again automatically.
  8. If renderings matter, add a sampled human or client-screenshot check; do not extend the API check to pretend it covers rendering.
  9. Mutation-test the invariants: delete a section, a link, a variable, and confirm a check fails.
  10. Re-observe the read-back shape after platform or SDK upgrades.

8. What I could not confirm

  • Lark/Feishu element_id and defaults. The Card JSON 2.0 page I read describes element_id as developer-defined and does not state that the platform generates one. That the read-back adds element_ids, fills defaults, expands padding, un-escapes backslashes and returns the button URL as url is an observation from our own run, taken with user_card_content; I did not re-run it. It is one observation of one card, so which platform-added fields appear in that mode in general remains undocumented.
  • card_msg_content_type on the English Lark page. The Feishu (Chinese) Get-message page documents it [2]; the English Lark Get-message page as retrieved did not show it, and I do not know whether that is an omission or a difference between the two sites.
  • msg_type for cards. The English Get-message page shows both interactive and card; I did not establish which the API returns in every case.
  • Lark uuid behaviour on a duplicate. The documentation says at most one message is sent within an hour. It does not say what the duplicate call returns, and I did not test it. Whether a stored message exposes its uuid is not stated.
  • Slack read-back of blocks. I did not find documentation of what a block message looks like in conversations.history; the page's samples carry no blocks.
  • Telegram. I found no Bot API method to fetch one message by id, from a keyword search of the fetched page. This is an absence in the page I read, not a statement from Telegram that none exists.
  • Teams. I found nothing on how Teams returns an Adaptive Card on Graph read-back, nor on idempotency for sends. The Teams rendering statements come from the cards reference only.
  • GitHub. I did not establish exact round-trip behaviour for comment bodies, nor any duplicate-comment protection.
  • Read-after-write lag on any of these platforms is not addressed in the pages I read.
  • Retention windows. Lark's hour and Stripe's 24 hours are the only ones I read; I did not find windows for others.
  • The IETF draft is a work in progress and its revision may have changed.
  • Prevalence. I have no data on how often platforms change read-back formats or how often real sends are lost or duplicated, and I make no such claim.
  • All design elements in sections 3, 4.3, 5, 6 and 7 (the three comparisons, the invariant list, the marker states and rules, the correlation token, the checklist) are my own reasoning from the sources above. Apart from the code sketch on synthetic data and the exclusive-create check in a temporary directory, I ran nothing.

Sources

  1. Lark Open Platform. Get message content (fields, deleted, updated, msg_type, errors).
  2. Feishu Open Platform (Chinese). 获取指定消息的内容 (card_msg_content_type, user_card_content, schema, body.content).
  3. Feishu Open Platform (Chinese). 接收消息内容 (received card structure differs from the sent JSON; endpoints that can return the original).
  4. Lark Open Platform. Send message and Feishu (Chinese) 发送消息 (uuid, one-hour dedup, 30 KB card limit, deleted, error 230049).
  5. Lark Open Platform. Card JSON 2.0 structure (element_id, defaults, client 7.20 requirement).
  6. Lark Open Platform. Button component, Card JSON 2.0 (behaviors, open_url, default_url).
  7. Slack. chat.postMessage (returned message "as parsed by our servers", mutation, warnings, error semantics).
  8. Slack. Section block (block_id generated if not specified).
  9. Slack. conversations.history (fetching one message by ts).
  10. Telegram. Bot API (sendMessage, formatting options, Message object, login_url).
  11. Microsoft. Create and explore card types in Teams (Adaptive Card attachment, version support, dropped buttons and sections, carousel split).
  12. Microsoft. Get chatMessage in a channel or chat (Graph message fields).
  13. Microsoft. chatMessageAttachment resource type (content as a string).
  14. GitHub. REST API: create an issue comment (body, body_text, body_html media types).
  15. IETF. RFC 8785: JSON Canonicalization Scheme (JCS).
  16. Stripe. API reference: Idempotent requests.
  17. Stripe. Designing robust and predictable APIs with idempotency.
  18. Amazon Builders' Library. Making retries safe with idempotent APIs.
  19. IETF HTTPAPI WG. The Idempotency-Key HTTP Header Field (Internet-Draft).
  20. Werner Vogels. Eventually Consistent (read-your-writes, session consistency).
  21. GitHub. Best practices for using the REST API (serial mutative requests, retry guidance).
  22. The Open Group. POSIX open() (O_CREAT | O_EXCL: existence check and creation are atomic).
  23. Lark Open Platform. Rich text (Markdown) component, Card JSON 2.0 (content, differential redirection links via href).

Companion articles in this section: Wake the Model Only When Something Needs Judgment (2026-12-01) and Upgrade Floors After 1.0 (2026-12-02).