Skip to content

netresearch/matrix-skill / skills/matrix-communication

matrix-communication

Flagged

Use when communicating via Matrix chat, notifying teams, or managing E2EE. Triggers on #room:server references, Matrix URLs, and chat requests.

FileKindSize
README.mdmarkdown2.9 KB
SKILL.mdskill md6.7 KB
evals/evals.jsonconfig12.6 KB
references/agent-governance.mdmarkdown2.0 KB
references/api-reference.mdmarkdown7.3 KB
references/command-reference.mdmarkdown8.9 KB
references/e2ee-guide.mdmarkdown17.2 KB
references/hookshot-integration.mdmarkdown10.7 KB
references/messaging-guide.mdmarkdown13.8 KB
references/no-editorializing.mdmarkdown331 B
references/setup-guide.mdmarkdown11.1 KB
references/troubleshooting.mdmarkdown7.8 KB
scripts/_lib/__init__.pyscript3.6 KB
scripts/_lib/backup_mac.pyscript1.2 KB
scripts/_lib/config.pyscript4.6 KB
scripts/_lib/daemon_client.pyscript3.0 KB
scripts/_lib/deps.pyscript1.9 KB
scripts/_lib/downloads.pyscript1.1 KB
scripts/_lib/e2ee.pyscript13.2 KB
scripts/_lib/formatting.pyscript14.4 KB
scripts/_lib/http.pyscript4.8 KB
scripts/_lib/reactions.pyscript2.9 KB
scripts/_lib/roomlog.pyscript13.7 KB
scripts/_lib/rooms.pyscript15.5 KB
scripts/_lib/secret_input.pyscript2.0 KB
scripts/_lib/test_backup_mac.pyscript1.5 KB
scripts/_lib/test_config.pyscript7.1 KB
scripts/_lib/test_daemon_client.pyscript5.9 KB
scripts/_lib/test_downloads.pyscript2.3 KB
scripts/_lib/test_e2ee.pyscript14.3 KB
scripts/_lib/test_formatting.pyscript15.5 KB
scripts/_lib/test_http.pyscript4.1 KB
scripts/_lib/test_reactions.pyscript15.2 KB
scripts/_lib/test_roomlog.pyscript20.2 KB
scripts/_lib/test_rooms.pyscript13.7 KB
scripts/_lib/test_secret_input.pyscript2.2 KB
scripts/_lib/test_trust.pyscript8.3 KB
scripts/_lib/trust.pyscript5.3 KB
scripts/_lib/utils.pyscript1.7 KB
scripts/matrix-create-room.pyexecutablescript4.7 KB
scripts/matrix-doctor.pyexecutablescript22.2 KB
scripts/matrix-download-e2ee.pyexecutablescript7.7 KB
scripts/matrix-e2ee-setup.pyexecutablescript9.2 KB
scripts/matrix-e2ee-verify.pyexecutablescript29.2 KB
scripts/matrix-edit-e2ee.pyexecutablescript7.9 KB
scripts/matrix-edit.pyexecutablescript5.3 KB
scripts/matrix-fetch-keys.pyexecutablescript9.1 KB
scripts/matrix-invite.pyexecutablescript3.0 KB
scripts/matrix-key-backup.pyexecutablescript21.3 KB
scripts/matrix-power-level.pyexecutablescript7.0 KB
scripts/matrix-react.pyexecutablescript14.1 KB
scripts/matrix-read-e2ee.pyexecutablescript12.8 KB
scripts/matrix-read.pyexecutablescript4.7 KB
scripts/matrix-redact.pyexecutablescript5.0 KB
scripts/matrix-resolve.pyexecutablescript1.7 KB
scripts/matrix-rooms.pyexecutablescript3.8 KB
scripts/matrix-send-e2ee.pyexecutablescript19.4 KB
scripts/matrix-send.pyexecutablescript9.4 KB
scripts/matrix-watch.pyexecutablescript5.3 KB
scripts/matrix-watchd.pyexecutablescript23.5 KB
scripts/test_matrix_doctor.pyscript14.2 KB
scripts/test_matrix_read_e2ee.pyscript2.7 KB

scripts/_lib/test_formatting.py

View on GitHub
# SPDX-License-Identifier: MIT
# SPDX-FileCopyrightText: Netresearch DTT GmbH

"""Tests for `_lib.formatting` markdown→HTML conversion.

The skill directory contains a hyphen (`matrix-communication`) so it is
not importable as a Python package; run the file directly or use unittest
discovery:

    python3 skills/matrix-communication/scripts/_lib/test_formatting.py
    python3 -m unittest discover \\
        -s skills/matrix-communication/scripts/_lib -p 'test_formatting.py'

Stdlib only.
"""

import os
import sys
import unittest

sys.path.insert(0, os.path.dirname(__file__))

from formatting import (
    add_bot_prefix,
    build_mentions,
    inject_pills,
    markdown_to_html,
    mention_pill,
    rich_text_fields,
    shorten_service_urls,
)


class ShortenServiceUrlsTests(unittest.TestCase):
    def test_jira_bare_url_is_shortened(self):
        out = shorten_service_urls("see https://jira.example.com/browse/PROJ-42")
        self.assertIn("[PROJ-42](https://jira.example.com/browse/PROJ-42)", out)

    def test_gitlab_bare_url_is_shortened(self):
        out = shorten_service_urls(
            "see https://gitlab.example.com/grp/proj/-/merge_requests/7"
        )
        self.assertIn(
            "[grp/proj#7](https://gitlab.example.com/grp/proj/-/merge_requests/7)",
            out,
        )

    def test_existing_gitlab_markdown_link_is_preserved(self):
        """Regression: pre-wrapped markdown links must NOT be re-wrapped.

        Before the fix this produced `[mytext]([grp/proj#7](url))` which
        confused the link parser and leaked literal `)` into the rendered
        message.
        """
        src = "[mytext](https://gitlab.example.com/grp/proj/-/merge_requests/7) — note"
        out = shorten_service_urls(src)
        self.assertEqual(out, src)

    def test_existing_jira_markdown_link_is_preserved(self):
        src = "[NRS-1](https://jira.example.com/browse/NRS-1) — note"
        out = shorten_service_urls(src)
        self.assertEqual(out, src)

    def test_existing_github_markdown_link_is_preserved(self):
        src = "[my pr](https://github.com/owner/repo/pull/9) — note"
        out = shorten_service_urls(src)
        self.assertEqual(out, src)

    def test_mixed_protected_and_bare_urls(self):
        src = (
            "see [my mr](https://gitlab.example.com/grp/proj/-/merge_requests/7) "
            "and https://gitlab.example.com/grp/proj/-/issues/12"
        )
        out = shorten_service_urls(src)
        # First link untouched
        self.assertIn(
            "[my mr](https://gitlab.example.com/grp/proj/-/merge_requests/7)", out
        )
        # Second link auto-shortened
        self.assertIn(
            "[grp/proj#12](https://gitlab.example.com/grp/proj/-/issues/12)", out
        )

    def test_forged_placeholder_does_not_raise(self):
        """A user-supplied `\\x00MDLINK<n>\\x00` sequence must not crash the
        restore step with IndexError. Unknown placeholders are left as-is."""
        # No real markdown link in the input, but a forged placeholder is.
        src = "literal placeholder \x00MDLINK99\x00 should pass through"
        out = shorten_service_urls(src)
        self.assertIn("\x00MDLINK99\x00", out)


class MarkdownToHtmlListTests(unittest.TestCase):
    def test_dash_bullets_render_as_ul(self):
        html = markdown_to_html("- one\n- two")
        self.assertIn("<ul>", html)
        self.assertIn("<li>one</li>", html)
        self.assertIn("<li>two</li>", html)

    def test_asterisk_bullets_render_as_ul(self):
        """Regression: `* ` bullets must render as a list, not as italic."""
        html = markdown_to_html("* one\n* two")
        self.assertIn("<ul>", html)
        self.assertIn("<li>one</li>", html)
        self.assertIn("<li>two</li>", html)
        self.assertNotIn("<em>", html)

    def test_plus_bullets_render_as_ul(self):
        html = markdown_to_html("+ one\n+ two")
        self.assertIn("<ul>", html)
        self.assertIn("<li>one</li>", html)
        self.assertIn("<li>two</li>", html)

    def test_asterisk_bullet_with_inline_italic(self):
        """A bullet line may still contain an italic span elsewhere."""
        html = markdown_to_html("* item *emph* tail")
        self.assertIn("<li>item <em>emph</em> tail</li>", html)

    def test_asterisk_inside_word_still_italicises(self):
        """Mid-line `*pairs*` still emit <em>."""
        html = markdown_to_html("hello *world*")
        self.assertIn("<em>world</em>", html)


class EmphasisFlankingTests(unittest.TestCase):
    """CommonMark left/right-flanking rules for `*…*`, `**…**`, `~~…~~`.

    Opening delimiter must NOT be followed by whitespace; closing delimiter
    must NOT be preceded by whitespace. Without these guards the italic
    regex used to swallow bullet `*` markers and produce broken output.
    """

    def test_italic_open_followed_by_space_does_not_match(self):
        # `*` immediately followed by space is not a valid italic opener.
        html = markdown_to_html("* one and *two*")
        self.assertNotIn("<em> one and </em>", html)
        self.assertIn("<em>two</em>", html)

    def test_italic_close_preceded_by_space_does_not_match(self):
        # `*` immediately preceded by space is not a valid italic closer.
        html = markdown_to_html("a *foo *bar")
        self.assertNotIn("<em>foo </em>", html)

    def test_bold_open_followed_by_space_does_not_match(self):
        html = markdown_to_html("** not bold ** but **bold**")
        self.assertNotIn("<strong> not bold </strong>", html)
        self.assertIn("<strong>bold</strong>", html)

    def test_strikethrough_open_followed_by_space_does_not_match(self):
        html = markdown_to_html("~~ not strike ~~ but ~~strike~~")
        self.assertNotIn("<del> not strike </del>", html)
        self.assertIn("<del>strike</del>", html)

    def test_italic_single_char(self):
        # `*x*` is a valid italic: opener followed by non-ws, closer
        # preceded by non-ws.
        html = markdown_to_html("*x*")
        self.assertIn("<em>x</em>", html)


class MarkdownToHtmlLinkTests(unittest.TestCase):
    def test_pre_wrapped_gitlab_link_renders_clean_anchor(self):
        """Regression: no stray `)` after the anchor."""
        src = "[my mr](https://gitlab.example.com/grp/proj/-/merge_requests/7)"
        html = markdown_to_html(src)
        self.assertIn(
            '<a href="https://gitlab.example.com/grp/proj/-/merge_requests/7">'
            "my mr</a>",
            html,
        )
        # Critical: no leaked closing paren after the anchor
        self.assertNotIn("</a>)", html)

    def test_pre_wrapped_jira_link_renders_clean_anchor(self):
        src = "[NRS-1](https://jira.example.com/browse/NRS-1)"
        html = markdown_to_html(src)
        self.assertIn('<a href="https://jira.example.com/browse/NRS-1">NRS-1</a>', html)
        self.assertNotIn("</a>)", html)

    def test_bullet_list_with_pre_wrapped_links(self):
        """End-to-end regression: a bullet list of pre-wrapped GitLab + Jira
        links must produce a clean `<ul><li><a>…</a></li>…</ul>` tree, with
        the pre-wrapped link text preserved (not replaced by the auto-shortener).
        """
        src = (
            "- [proj#7](https://gitlab.example.com/grp/proj/-/merge_requests/7) "
            "— note ([NRS-1](https://jira.example.com/browse/NRS-1))\n"
            "- [proj#8](https://gitlab.example.com/grp/proj/-/merge_requests/8)"
        )
        html = markdown_to_html(src)
        self.assertIn("<ul>", html)
        # Caller-provided link text preserved (would have been clobbered to
        # `grp/proj#7` by the broken auto-shortener)
        self.assertIn(
            '<a href="https://gitlab.example.com/grp/proj/-/merge_requests/7">'
            "proj#7</a>",
            html,
        )
        self.assertIn('<a href="https://jira.example.com/browse/NRS-1">NRS-1</a>', html)
        # No nested `[…](…)` artefacts (the symptom of broken re-wrapping)
        self.assertNotIn("[", html)
        self.assertNotIn("](", html)
        # Sanity: no leftover bullet asterisks (would mean inline ate the bullet)
        self.assertNotIn("<li>*", html)

    def test_parentheses_inside_the_url_stay_in_the_href(self):
        """Regression: a JQL filter ending in `currentUser()` was cut at the
        first `)`, so the href ended in `currentUser(` and a bare `)` followed
        the anchor."""
        url = (
            "https://jira.example.com/issues/?jql=status%3D%22Awaiting%20approval"
            "%22%20and%20assignee%3DcurrentUser()"
        )
        html = markdown_to_html(f"[My open approvals]({url})")
        self.assertIn(f'<a href="{url}">My open approvals</a>', html)
        self.assertNotIn("</a>)", html)

    def test_link_inside_parentheses_keeps_the_closing_paren_outside(self):
        html = markdown_to_html("note ([docs](https://example.com/a_(b)))")
        self.assertIn('(<a href="https://example.com/a_(b)">docs</a>)', html)


class MentionTests(unittest.TestCase):
    """Regression for #90: a plain @name notifies nobody.

    Only m.mentions fires a notification on a modern client. The legacy push
    rule matched the exact localpart and nothing else, so "@bjoern" never
    reached "bjoern.marten" - which is how the case in the issue went unnoticed.
    """

    USER = "@bjoern.marten:example.org"

    def test_pill_links_to_matrix_to(self):
        pill = mention_pill(self.USER)
        self.assertEqual(
            pill, "[bjoern.marten](https://matrix.to/#/@bjoern.marten:example.org)"
        )

    def test_pill_takes_a_label(self):
        self.assertIn("[Björn]", mention_pill(self.USER, "Björn"))

    def test_mentions_block_carries_the_user_ids(self):
        self.assertEqual(build_mentions([self.USER]), {"user_ids": [self.USER]})

    def test_duplicate_mentions_are_collapsed(self):
        self.assertEqual(
            build_mentions([self.USER, self.USER])["user_ids"], [self.USER]
        )

    def test_room_mention_is_its_own_flag(self):
        self.assertEqual(build_mentions([], room=True), {"room": True})

    def test_empty_mentions_produce_an_empty_block(self):
        self.assertEqual(build_mentions([]), {})

    def test_a_bare_localpart_becomes_a_pill(self):
        out = inject_pills("bjoern.marten schau mal", [self.USER])
        self.assertIn("(https://matrix.to/#/@bjoern.marten:example.org)", out)

    def test_an_at_prefixed_name_becomes_a_pill(self):
        out = inject_pills("@bjoern.marten schau mal", [self.USER])
        self.assertIn("[bjoern.marten](https://matrix.to/#/", out)

    def test_a_name_that_is_not_in_the_text_is_not_inserted(self):
        """m.mentions already notifies. Rewriting someone's message to add a
        name they did not type is worse than a missing pill."""
        out = inject_pills("nichts von belang", [self.USER])
        self.assertEqual(out, "nichts von belang")

    def test_an_existing_link_is_not_wrapped_again(self):
        text = "[bjoern.marten](https://matrix.to/#/@bjoern.marten:example.org)"
        self.assertEqual(inject_pills(text, [self.USER]), text)

    def test_only_the_first_occurrence_is_pilled(self):
        """One pill per mention reads as an address; four read as a stutter."""
        out = inject_pills("bjoern.marten und nochmal bjoern.marten", [self.USER])
        self.assertEqual(out.count("https://matrix.to/#/"), 1)


class MarkdownToHtmlEscapingTests(unittest.TestCase):
    """Message text is escaped; only the markdown the converter knows becomes markup."""

    def test_html_in_the_message_is_shown_as_text(self):
        html = markdown_to_html('<a href="https://example.org">bank</a> and <b>x</b>')
        self.assertNotIn("<a href", html)
        self.assertNotIn("<b>", html)
        self.assertIn(
            "&lt;a href=&quot;https://example.org&quot;&gt;bank&lt;/a&gt;", html
        )

    def test_quote_in_a_link_url_stays_inside_the_attribute(self):
        html = markdown_to_html('[docs](https://example.org/a"onmouseover="x)')
        self.assertIn('href="https://example.org/a&quot;onmouseover=&quot;x"', html)

    def test_link_with_a_non_web_scheme_keeps_only_its_text(self):
        html = markdown_to_html("[click](javascript:alert(1))")
        self.assertNotIn("<a", html)
        self.assertIn("click", html)

    def test_ampersand_in_url_is_escaped_in_href(self):
        html = markdown_to_html("[q](https://example.org/?a=1&b=2)")
        self.assertIn('href="https://example.org/?a=1&amp;b=2"', html)

    def test_blockquote_and_code_block_still_render(self):
        html = markdown_to_html("> quoted <b>\n\n```\nif a < b:\n```")
        self.assertIn("<blockquote>quoted &lt;b&gt;</blockquote>", html)
        self.assertIn("<pre><code>if a &lt; b:\n</code></pre>", html)


class AddBotPrefixTests(unittest.TestCase):
    PREFIX = "🤖"

    def test_plain_message_gets_the_prefix(self):
        self.assertEqual(add_bot_prefix("hello", self.PREFIX), "🤖 hello")

    def test_message_already_opening_with_the_prefix_keeps_one(self):
        # matrix-announcement recommends 🤖 as the leading glyph; with
        # bot_prefix set as well, that read "🤖 🤖 🛡 …" in a room.
        message = "🤖 🛡 **Plugin 0.1.3 installed**"
        self.assertEqual(add_bot_prefix(message, self.PREFIX), message)

    def test_edit_of_a_prefixed_message_keeps_one(self):
        self.assertEqual(add_bot_prefix("  🤖 text", self.PREFIX), "  🤖 text")

    def test_heading_with_prefix_below_keeps_one(self):
        message = "## Release\n🤖 body"
        self.assertEqual(add_bot_prefix(message, self.PREFIX), message)

    def test_heading_message_prefixed_by_this_function_keeps_one(self):
        once = add_bot_prefix("## Release\nbody", self.PREFIX)
        self.assertEqual(add_bot_prefix(once, self.PREFIX), once)

    def test_prefix_with_surrounding_whitespace_is_applied_once(self):
        for message in ("hello", "## Release\nbody"):
            once = add_bot_prefix(message, " 🤖 ")
            self.assertEqual(add_bot_prefix(once, " 🤖 "), once, message)

    def test_heading_without_prefix_gets_it_below(self):
        out = add_bot_prefix("## Release\nbody", self.PREFIX)
        self.assertEqual(out.count(self.PREFIX), 1)
        self.assertTrue(out.startswith("## Release"))


class RichTextFieldsTests(unittest.TestCase):
    def test_hookshot_message_without_text_key(self):
        # Shape of a hookshot webhook message whose payload had no `text` key
        # (PBS digest into #system-monitoring, 2026-11-16): `body` is the raw
        # payload dump, `formatted_body` is what Element renders.
        content = {
            "msgtype": "m.notice",
            "body": 'Received webhook data:\n\n```json\n\n{\n  "version": "v2",\n'
            '  "html": "<details><summary>PBS backup digest</summary>ok</details>"\n}\n\n```',
            "format": "org.matrix.custom.html",
            "formatted_body": "<details><summary>PBS backup digest</summary>ok</details>",
        }
        self.assertEqual(
            rich_text_fields(content),
            {
                "format": "org.matrix.custom.html",
                "formatted_body": "<details><summary>PBS backup digest</summary>ok</details>",
            },
        )

    def test_plain_message_has_none(self):
        self.assertEqual(rich_text_fields({"msgtype": "m.text", "body": "hi"}), {})

    def test_non_string_and_empty_values_are_dropped(self):
        self.assertEqual(
            rich_text_fields({"format": 1, "formatted_body": ""}),
            {},
        )

    def test_non_dict_content(self):
        self.assertEqual(rich_text_fields(None), {})
        self.assertEqual(rich_text_fields("body"), {})


if __name__ == "__main__":
    unittest.main()
slack-gif-creatoranthropics/skillsKnowledge and utilities for creating animated GIFs optimized for Slack. Provides constraints, validation tools, and animation concepts. Use when users request animated GIFs for Slack like "make me a GIF of X doing Y for Slack."Stars: 197kUpdated Claude CodeCodexVerifiedInstall
ponytailDietrichGebert/ponytailLazy senior dev mode for any coding task: the smallest change that fully solves it, and a reply a busy human understands in one read.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailHarvest every shortcut: comment into one debt ledger, so deferrals get tracked instead of forgotten. One-shot report.Stars: 194kUpdated Claude CodeCodexVerifiedInstall
ponytail-debtDietrichGebert/ponytailList every `shortcut:` comment (and older `ponytail:` ones) as a debt ledger. One-shot report, changes nothing. Use for "ponytail debt", "what did ponytail defer", "list the shortcuts", /ponytail-debt.Stars: 194kUpdated Claude CodeCodexVerifiedInstall