Skip to main content

md2xarticle

Markdown in, X Article out. One command turns a Markdown file, Mermaid diagrams included, into a paste-ready article body plus polished images for the X (Twitter) Article editor.

Status: The full conversion (md2xarticle ARTICLE.md) is implemented: one run writes article.html, outline.txt, the images, and manifest.json. So are diagrams, outline, and check. This README is the v0 design for whoever builds it, human or bot.

If you are an agent

Run md2xarticle article.md -o out/ --json. Read out/manifest.json. Paste out/article.html into the X Article editor, then upload each image in manifest order at its marker.

The short bot skill (install, commands, --json and manifest.json, upload order, exit codes, privacy check) is in docs/BOT-SKILL.md.

Why

X Articles accept rich text, but only in a narrow shape: three text levels, native tables and code blocks, and images that must be uploaded in the editor because paste drops them. Long-form Markdown does not fit that shape out of the box.

Converting one real long-form article by hand showed where the time goes:

  • Deep heading levels (#### and below) had no place to go and had to be restructured by hand.
  • Mermaid diagrams came out cropped tight, off-center, and in stock Mermaid styling, at whatever size the renderer picked.
  • Text placeholders had to be swapped for images one by one.
  • Much of the work was copy, paste, and tweak inside the X rich editor.
  • The 5:2 cover image was a separate job.
  • Captions taken automatically from the nearest heading read badly.
  • The privacy check before publishing was a manual read-through.

md2xarticle's rule: if the tool can do it, the human should not have to. Whatever is left by hand (today, image uploads) is made as short and as obvious as possible.

Just works

The default:

pip install md2xarticle
md2xarticle article.md -o out/

Output:

out/
  article.html      # paste this into the X Article editor
  outline.txt       # the restructured heading outline, for a quick check
  manifest.json     # image order, file, caption, anchor text (for bots)
  images/
    01.png          # 16:9 body images, numbered in reading order
    02.png
    cover.png       # 5:2, only with --cover

Zero config is the goal. No browser, no Node, no web service, and no network at run time. The diagram font is DejaVu Sans, which ships inside the pinned mermaidx package, so images look the same on every machine. Cover titles use the same font. Every flag has a default.

Python 3.11 to 3.13. Platforms: Windows, WSL, Linux, and macOS, on Intel and ARM where the dependencies ship wheels.

WSL note: run inside WSL, output lands in the Linux filesystem. To paste from a browser on Windows, either write to the Windows side (-o /mnt/c/<folder>/out) or open the folder through \\wsl$. md2xarticle prints this hint when it detects WSL.

Acceptance tests (zero-config goal)

Input Expected behavior
Plain Markdown, # and ## only Headings map 1:1 to Heading and Subheading; no images; manifest.json has an empty image list; exit 0.
Deep headings (### to ######) Restructured per Headings; outline.txt shows the result; no heading level beyond Subheading reaches the HTML.
Tables and fenced code Stay as real <table> and <pre><code> markup, never images.
Mermaid blocks Each becomes a themed PNG centered on a 16:9 canvas, a numbered marker in the HTML, and a manifest entry.
Invalid Mermaid block That diagram fails with its line number and the exact command to retry it alone; the rest of the article still renders; exit 1.
--cover Adds images/cover.png at 5:2.
Front matter (YAML) Read for title, subtitle, and cover text; not pasted into the body.
Empty file Empty article, exit 0.
Same input twice Byte-identical HTML and manifest; PNGs identical on the same platform.

Concepts

flowchart LR
    MD[article.md] --> P[parse<br/>markdown-it-py]
    P --> S[shape for X<br/>headings, markers]
    S --> W[article.html<br/>outline.txt]
    P --> D[Mermaid blocks]
    D --> R[render<br/>mermaidx]
    R --> C[compose<br/>Pillow, 16:9 and 5:2]
    C --> I[images/NN.png]
    S --> M[manifest.json]
    I --> M

X Article constraints

These are the facts the design is built around. Anything not listed here is unknown until the Phase 0 paste test measures it.

  • Three text levels: Heading, Subheading, Body.
  • Tables and code blocks are supported natively. They must reach the editor as real markup.
  • Images cannot come through paste. They are uploaded in the editor, one at a time.
  • Cover image is 5:2.
  • Body images are 16:9 for now. Other ratios may come later.

Headings

X has two heading levels, so the tool restructures instead of renaming.

The first #, or a front matter title, is the article title. It does not appear in the body.

When the document uses a single # as that title, the body mapping is:

Markdown X Article
## Heading
### Subheading
#### and deeper Bold lead-in paragraph, or a list item when siblings form a list

Otherwise the mapping is:

Markdown X Article
# or ## Heading
### Subheading
#### and deeper Bold lead-in paragraph, or a list item when siblings form a list

The tool picks the mapping, writes it to outline.txt, and prints it, so a human or bot can check the structure before pasting. --heading-map overrides the choice.

This restructuring is implemented; md2xarticle outline ARTICLE.md prints the result.

Diagrams

Each Mermaid block is rendered to a PNG, trimmed, and placed on a fixed canvas.

  • Renderer: mermaidx by default, pinned to mermaidx==0.11.3, novasvg==0.11.5, and quickjs-ng==0.18.0.1, with Pillow==13.0.0 for composition. It runs real Mermaid inside an embedded QuickJS engine and rasterizes with novasvg, so it needs no Node and no Chrome. Known costs: about 0.5 to 2 seconds per diagram, and bundled-font metrics can differ slightly from a browser render. Fidelity notes are in Phase 0 findings.
  • Theme: the default is mono: DejaVu Sans (from mermaidx), neutral gray on white, rounded boxes, and generous spacing. The other built-ins are soft (pale teal on white), warm (amber on cream), and two matched to X's own palette: x-light (white, text #0F1419, borders #CFD9DE) and x-dark (black, text #E7E9EA, borders #2F3336). Both X themes use X blue (#1D9BF0) only as an accent, for the gitGraph main branch, tags, and the first pie slice, and draw a cover subtitle in X's secondary text gray. Every built-in starts from Mermaid's base theme with its own palette; Mermaid's own default theme is never used. Palette, corner radius, spacing, and later the font are set in a customization file. See Customization.
  • Composition: Pillow trims the render, scales it to fit with even padding, and centers it on a 16:9 canvas (default 1600x900, set by --size). The cover composer does the same at 5:2 (default 1500x600) with an optional title and subtitle above the diagram, from front matter title and subtitle (or cover_title and cover_subtitle in the customization file). Upscaling is capped at 3x the native render, so a tiny diagram is not blown up. Every image must be the exact canvas size, with content centered within 4 px (body) or 8 px (cover with a title or subtitle), and a minimum margin of 4% of each side.
  • Never cropped tight, never off-center. A check measures the margins of every output image against those tolerances.
  • Readable text. A flowchart that is limited by the canvas height is also rendered with wider label wrapping (320 px instead of Mermaid's 200 px), and whichever draws larger is kept. The cover makes this choice again against its own diagram box, below the title and subtitle. The source is never rewritten. When a diagram still has to shrink below 0.65x on a body image or the cover, so its text drops under about 10 px, the run warns and names the next step: a layout = "LR" override for a flowchart, or splitting the diagram.
  • Tall diagrams. A top-down flowchart or a sequence diagram that is taller than 16:9 and would shrink on the default canvas is also rendered compact: a flowchart with Mermaid's dagre layout at 30 px between ranks (the default ELK layout ignores rank spacing), a sequence diagram with tighter message spacing. Whichever fits 16:9 larger is kept; [style] compact_tall = false turns this off.
  • Wide flowcharts. A flowchart wider than 16:9 is limited by the canvas width, so it cannot be scaled up further without breaking the margins. It is also rendered compact (dagre, 30 px between ranks and between nodes), and the compact render is kept only when it draws at least 10% larger. The direction is never changed. [style] compact_tall = false turns this off too.
  • The diagram's own theme. A %%{init: ...}%% directive that sets theme or themeVariables keeps its colors for that diagram; the run theme's colors are not applied to it. Spacing, corner radius, and the canvas color still come from the run theme.
  • Subgraph spacing. The default ELK layout can leave a large empty band at the bottom of a subgraph that has both an outgoing edge and an incoming back edge. That band is removed after layout, keeping the flowchart padding under the last node.
  • gitGraph labels. Slanted commit labels are measured against the lanes, branch lines, branch names, tags, commits, and each other. Only the lane or commit gaps that need it are widened, so no label crosses anything. Level labels are left as Mermaid draws them.
  • Same input, same bytes. With the pinned stack, a run in a fresh process writes byte-identical PNGs on the same platform.

Image markers and the manifest

Images cannot be pasted, so the tool makes placement obvious and ordered.

  • Each diagram's spot in article.html holds a short visible marker, for example [Image 02: Request flow], on its own line. The human or bot uploads images/02.png there and deletes the marker.
  • manifest.json lists the same things in machine form:
{
  "version": 1,
  "source": "article.md",
  "cover": "images/cover.png",
  "images": [
    {
      "order": 1,
      "file": "images/01.png",
      "marker": "[Image 01: System overview]",
      "caption": "System overview",
      "anchor_text": "The pieces fit together like this:",
      "source_line": 42
    }
  ]
}

anchor_text is the paragraph just before the image, so a bot can find the spot in the editor even after the marker text is gone.

This is implemented. md2xarticle diagrams writes manifest.json next to the images. cover is null when there is no cover image. source is the article file name, not a path. The manifest lists only images that were written.

Captions

Captions come from, in order: a Mermaid title, a %% caption: comment in the block, the alt text of a following *Figure: ...* line, a following line that is italic as a whole (*...* or _..._), then the nearest heading. If none of those are present, the caption is Diagram NN, so every marker has a label. See Decided.

Privacy scan

--check-privacy (or the check command) flags, without changing anything:

  • Email addresses and phone-number shapes
  • Local paths: Windows user folders, Unix and macOS home folders, \\wsl$ shares, and Windows user folders seen from WSL under /mnt/<drive>/Users
  • Secret-shaped strings: API keys, bearer tokens, PEM blocks, credentials in URLs
  • Names from an optional local deny-list file that never leaves the machine. The path comes from --deny-list FILE or the MD2XARTICLE_PRIVACY_DENYLIST environment variable; the file is not shipped with the package.

Findings print with file and line, and never include the matched text. It is a check, not a block: exit 1 on findings, and the output files are still written. The check command writes nothing.

Architecture

The design uses abstract base classes (abc.ABC) as interfaces, with one concrete subclass per implementation. The interfaces sit where things really vary: the parser library, the diagram renderer, the image shape, the output format, and the operating system.

classDiagram
    class MarkdownParser {
        <<abstract>>
        +parse(text) Document
    }
    class MarkdownItParser
    MarkdownParser <|-- MarkdownItParser

    class DiagramRenderer {
        <<abstract>>
        +render(source, theme) RenderedImage
        +available() bool
    }
    class MermaidxRenderer
    class MmdrRenderer
    class MmdcRenderer
    DiagramRenderer <|-- MermaidxRenderer
    DiagramRenderer <|-- MmdrRenderer
    DiagramRenderer <|-- MmdcRenderer

    class ImageComposer {
        <<abstract>>
        +compose(image, size) Image
    }
    class BodyImageComposer
    class CoverComposer
    ImageComposer <|-- BodyImageComposer
    ImageComposer <|-- CoverComposer

    class ArticleWriter {
        <<abstract>>
        +write(article, out_dir) list
    }
    class XArticleHtmlWriter
    class ManifestWriter
    ArticleWriter <|-- XArticleHtmlWriter
    ArticleWriter <|-- ManifestWriter

    class Platform {
        <<abstract>>
        +font_dirs() list
        +default_output_dir() Path
        +open_result(path)
        +notes() list
    }
    class WindowsPlatform
    class PosixPlatform
    class WslPlatform
    Platform <|-- WindowsPlatform
    Platform <|-- PosixPlatform
    PosixPlatform <|-- WslPlatform

    class Pipeline {
        +run(source, out_dir) Result
    }
    Pipeline --> MarkdownParser
    Pipeline --> DiagramRenderer
    Pipeline --> ImageComposer
    Pipeline --> ArticleWriter
    Pipeline --> Platform
Interface Subclasses What varies
MarkdownParser MarkdownItParser The parsing library, so it can be swapped later.
DiagramRenderer MermaidxRenderer (default); later MmdrRenderer (Rust reimplementation), MmdcRenderer (needs Node and Chromium, opt-in only) How Mermaid becomes pixels.
ImageComposer BodyImageComposer (16:9), CoverComposer (5:2) Canvas shape, padding, and cover text.
ArticleWriter XArticleHtmlWriter, ManifestWriter Output format.
Platform WindowsPlatform, PosixPlatform, WslPlatform Font lookup, default output folder, opening the result, the WSL paste note.

Rules:

  • Pipeline depends only on the base classes. It never imports a concrete subclass.
  • A factory picks the subclasses from CLI flags and the detected platform. It is the only place that knows the concrete names.
  • No network renderer is ever the default. mermaid.ink, Kroki, and similar services are out unless a future flag opts in by name.
  • Paths use pathlib; files are read and written as UTF-8 explicitly. The OS split lives in Platform, not in every class.
  • Renderers report available(), so a missing optional backend fails with the install command, not a stack trace.

Pipeline:

flowchart TD
    A[CLI args] --> F[factory<br/>flags plus detected platform]
    F --> PL[Pipeline<br/>base classes only]
    PL --> P1[MarkdownParser.parse]
    P1 --> P2[shape for X<br/>heading map, markers, captions]
    P2 --> P3{Mermaid blocks?}
    P3 -->|yes| P4[DiagramRenderer.render<br/>per block]
    P4 --> P5[ImageComposer.compose<br/>16:9, and 5:2 cover]
    P3 -->|no| P6
    P5 --> P6[ArticleWriter.write<br/>HTML, outline, manifest]
    P6 --> P7{--check-privacy?}
    P7 -->|yes| P8[privacy scan<br/>report findings]
    P7 -->|no| P9[summary, Platform notes,<br/>exit code]
    P8 --> P9

Suggested layout:

src/md2xarticle/
  cli.py
  pipeline.py
  factory.py
  parse/        base.py  markdown_it.py
  shape/        headings.py  markers.py  captions.py
  render/       base.py  mermaidx.py
  compose/      base.py  body.py  cover.py
  write/        base.py  html.py  manifest.py
  platform/     base.py  windows.py  posix.py  wsl.py
  privacy.py
  fonts.py      finds DejaVu Sans inside mermaidx (no font files ship here)
tests/
  contracts/    one contract suite per base class
  snapshots/    synthetic .md fixtures and expected outputs

Planned commands

All four are implemented: the full conversion, diagrams, outline, and check. Defaults match the quick start.

md2xarticle ARTICLE.md [-o OUT] [options]

The full conversion: HTML, outline, images, manifest.

Flag Default Meaning
-o, --out DIR ./out (from Platform) Output folder. Created if missing.
--cover off Also build images/cover.png at 5:2. Uses front matter title and subtitle if present.
--theme NAME mono Diagram theme: mono, soft, warm, x-light, or x-dark. Overridden by --custom-path when that file sets a theme.
--custom-path FILE off One TOML customization file for this run. See Customization.
--size WxH 1600x900 Body image size. Must be 16:9 for now.
--only N[,N] all diagrams Render only these diagrams, by 1-based index. Used in the error retry hint.
--renderer NAME mermaidx Diagram renderer.
--heading-map MAP auto Override the heading restructuring.
--check-privacy off Run the privacy scan after writing.
--json off Print a machine-readable summary to stdout instead of text.
-v, --verbose off Full renderer message on a failed diagram, and a traceback on an internal error (exit 3). Without it, exit 3 is a short message and a try: line, never a traceback.
--open off Open the output folder when done.

Sample output:

md2xarticle 0.1.1  article.md -> out/

Outline (X levels)
  H   Introduction
  H   How it works
  SH    The parser
  SH    The renderer
          [bold lead-in] Theme details
  H   Results

Images
  01  images/01.png  System overview      (after "The pieces fit together like this:")
  02  images/02.png  Request flow         (after "Each request goes through three steps:")
  cover  images/cover.png  5:2

Wrote out/article.html, out/outline.txt, out/manifest.json, 3 images in 2.4s

Next: open out/article.html, copy all, paste into the X Article editor,
then upload images in order at each [Image NN] marker.

--json output:

{
  "ok": true,
  "out_dir": "out",
  "html": "out/article.html",
  "outline": "out/outline.txt",
  "manifest": "out/manifest.json",
  "images": 2,
  "cover": true,
  "failed": [],
  "warnings": [],
  "privacy_findings": [],
  "notes": []
}

images counts the body images written; cover says whether images/cover.png was written. failed lists each diagram that did not render (order, source_line, error). privacy_findings is [] when --check-privacy is off. notes holds platform hints, such as the WSL paste note.

md2xarticle diagrams ARTICLE.md [-o OUT] [--cover]

Images only: render every Mermaid block to a polished, centered 16:9 PNG, plus an optional 5:2 cover. This is the Phase 1 milestone and is useful on its own for an article whose text is already in the X editor and only needs better images. --only, --theme, --custom-path, --size, --renderer, and --check-privacy apply here too. --check-privacy scans the source article after writing; images are still written.

md2xarticle check ARTICLE.md

Privacy scan only. Prints findings with line numbers. Writes nothing. --deny-list FILE or MD2XARTICLE_PRIVACY_DENYLIST supplies the optional local deny-list. --json prints the same findings as a list. Exit 1 on findings, 0 if clean, 2 on a usage error (missing file or deny-list).

md2xarticle outline ARTICLE.md

Implemented. Prints the restructured heading outline only, so the structure can be checked before converting.

Customization

--custom-path FILE points to one TOML file with the theme, layout, cover, and sizes for that run. The usual pattern is one file per Markdown article:

md2xarticle article.md --custom-path article.toml

With no flag, the built-in defaults apply: theme mono, and Mermaid source is rendered as written.

The file may set the theme (palette, corner radius, spacing, label wrapping, gitGraph label rotation; font later), per-diagram layout overrides, cover choice and text, and image sizes. A value in the file wins over the matching flag (--theme, --size), and the run prints a warning when that happens.

The file is read with the standard library tomllib, so no extra TOML dependency is needed.

Example:

theme = "mono"
size = "1600x900"
cover_size = "1500x600"
cover = "diagram:2"
cover_subtitle = ""            # "" turns the front matter subtitle off

[style]
corner_radius = 8
spacing = 16
wrap_width = 280               # flowchart label wrapping, px (default: automatic)
rotate_commit_labels = false   # gitGraph: level commit labels (default: rotated)
compact_tall = true            # tall or wide flowcharts and tall sequences may render compact

[[diagrams]]
id = 1
layout = "LR"

Output contract

Text summary to stdout by default; --json for machines. Warnings and errors go to stderr.

Exit codes:

Code Meaning
0 Ok.
1 Findings: a diagram failed, privacy findings, or a heading needed a forced fallback. Output that could be written was written.
2 Usage error (bad flag, missing file, wrong size ratio).
3 Internal error.

Every error prints the exact next command to try. Examples:

error: diagram 03 (article.md line 88) failed to render: Parse error on line 4
try:   md2xarticle diagrams article.md --only 3 --verbose
error: renderer 'mermaidx' is not installed
try:   pip install md2xarticle
error: renderer 'mmdc' is planned and not available yet
try:   md2xarticle diagrams article.md --renderer mermaidx

Testing

  • Contract tests. One suite per base class. Every subclass runs its base class's suite, so a new renderer, composer, writer, or platform must pass the same checks before it plugs in.
  • Snapshot tests. Synthetic Markdown fixtures in, expected output out: today the diagrams --json result and manifest.json; HTML snapshots join with the HTML writer. PNGs are checked by the image checks and determinism below, not against stored reference images.
  • Image checks. Every output PNG is checked for exact canvas size, aspect ratio, and margins: content centered within 4 px (body) or 8 px (cover with a title or subtitle), with a minimum margin of 4% of each side. Never cropped tight.
  • Cross-platform. CI runs the full suite on Windows, macOS, and Ubuntu across the supported Python versions, so the image checks and determinism hold on each OS. There is no cross-OS perceptual diff against reference images yet; it is planned, not in CI.
  • Determinism. Same input twice gives byte-identical HTML and manifest. With the pinned renderer stack (mermaidx==0.11.3, novasvg==0.11.5, quickjs-ng==0.18.0.1, Pillow==13.0.0), PNG output is byte-identical across fresh processes on one platform. Byte equality across OSes is not expected.
  • No network. A conversion runs in a fresh process with a socket guard that fails the run on any connect or DNS lookup, even one the caller swallows. On Ubuntu, CI also converts inside unshare -rn (no network interfaces), after proving that connects and DNS fail there and succeed outside it.
  • Packaging. CI builds the wheel and sdist on all three OSes, checks every file against an allowlist (package code is .py, themes are .json), runs the hygiene scan over their contents, installs each into a fresh venv, and runs md2xarticle --help and a diagrams --cover conversion.
  • Spec sync. A test fails when the Python range or the pins stated here drift from pyproject.toml, or when any workflow names a Python outside that range or none covers it all. Workflows are linted with a pinned, checksummed actionlint.
  • Skip budget. The run fails when more tests skip than tests/skip_budget.py expects (0 today).

Hygiene

This is an open-source repository. Nothing personal goes in it.

  • No personal information, real names, usernames, local paths, email addresses, or secrets anywhere: code, package, tests, fixtures, docs, examples, commit messages.
  • Fixtures are synthetic. Real articles are tested locally and never committed.
  • Example paths are generic: article.md, out/, images/01.png.
  • A hygiene check (tools/hygiene.py, the one scanner) runs in CI on every PR and push, over the tree, the commit messages, and the built wheel and sdist. It scans for email shapes, home-directory paths, secret shapes, typographic marks, byte-order marks, and a deny-list kept outside the repo (MD2XARTICLE_HYGIENE_DENYLIST). Typographic marks under tests/snapshots/ are allowed, because those fixtures capture the HTML writer's typography. Its planted fixture (--selftest) and the pytest suite prove it fails visibly.
  • md2xarticle ships no font files. DejaVu Sans comes with mermaidx, under its own license. Any font bundled here later must have a license that allows redistribution, shipped beside it.

Release

Publishing is trusted publishing from GitHub Actions, with no stored PyPI token. The workflow file is .github/workflows/release.yml. workflow_dispatch from main is a dry run: it builds the package, runs the tests, twine check --strict, and a wheel smoke test, and it uploads nothing. A v* tag on main runs the same checks and publishes to PyPI through the pypi environment. A human admin approves the pypi environment when a required reviewer is set. The testpypi environment is unused. The runbook, including the one-time admin settings, is docs/RELEASE.md.

Roadmap

flowchart LR
    P0[Phase 0<br/>renderer fidelity,<br/>X paste test, theme] --> P1[Phase 1<br/>diagrams milestone<br/>16:9 and 5:2]
    P1 --> P2[Phase 2<br/>HTML, outline,<br/>manifest]
    P2 --> P3[Phase 3<br/>privacy scan, polish,<br/>PyPI release, bot skill doc]
Phase Work Done when
0. Measure Render a synthetic diagram set with mermaidx on all three OSes and note fidelity gaps. Paste test: which elements survive paste into the X editor (spacing, nested lists, links, blockquotes, inline code, tables, code blocks). Show theme samples to the owner. Renderer notes are in docs/PHASE0-FINDINGS.md. Still open: the paste-survival table (the owner runs the X paste test) and an owner pick of theme samples, which only confirms the default.
1. Diagrams md2xarticle diagrams article.md produces polished, centered 16:9 PNGs and an optional 5:2 cover. ABC skeleton, contract tests, CI matrix, and hygiene check land here. The owner drops the images into an existing X draft and approves them. CI is green on all three OSes. Every image is the exact canvas size, with content centered within 4 px (body) or 8 px (cover with a title or subtitle), and a minimum margin of 4% of each side.
2. Article HTML writer shaped by the Phase 0 paste table, heading restructuring, outline.txt, markers, captions, manifest.json, --json. A synthetic long-form fixture pastes into X with no text cleanup. The owner's manual-edit list passes as acceptance tests.
3. Release Privacy scan, error messages with next commands, README and docs, a short skill doc for bots, PyPI release from CI. pip install md2xarticle works on Windows, WSL, Linux, and macOS from a clean environment.

Phase 1 comes before the full pipeline on purpose: a real article is already drafted in the X editor and is waiting only on better images.

Project done when: a real long-form article goes from Markdown to a ready-to-publish X draft with only the image uploads done by hand.

Not in scope: posting to X, driving the X editor, or any browser automation. md2xarticle writes files; a human or a bot does the upload.

Open questions

Ask the owner. Do not guess.

  • What X paste keeps. Spacing, nested lists, links, blockquotes, inline code, tables, and code blocks are unmeasured until the Phase 0 paste test. The owner runs that test by pasting tests/snapshots/paste_test.html and tests/snapshots/paste_test.nested.html (both written from tests/snapshots/paste_test.md). The HTML writer's current markup, listed under Decided, follows public reports until then.
  • The owner's manual edits. The list of hand edits made in the X editor on the real article. Each one becomes an acceptance test.
  • Image placement. How close to one-step placement X allows. Markers plus manifest is the baseline; anything better depends on what the editor permits without browser automation.
  • --watch mode. Wanted or not.
  • Renderer fallback. If mermaidx output falls short of the theme bar, which alternate wins: mmdr (fast, not official Mermaid) or opt-in mmdc (needs Node and Chromium).
  • Cover content. What the 5:2 cover is built from: a chosen diagram, the title on a themed background, or a supplied image.

Decided:

  • --custom-path FILE. One TOML customization file per run, typically one file per article. No flag means built-in defaults (theme mono, Mermaid rendered as written). See Customization.
  • Default theme. mono (neutral gray on white), picked by the owner from the theme samples. soft, warm, x-light, and x-dark are options, and Mermaid's own default theme is not used. Further look-and-feel is customization.
  • HTML writer markup (write/html.py, one function per element; revisit after the paste test). No classes, inline styles, or scripts, and the same input gives the same bytes.
    • Headings: X Heading is <h2> and Subheading is <h3>, never <h1>, because X keeps the title in its own field. The title goes in <title> only. Heading text is plain, matching outline.txt.
    • Deep headings: a bold lead-in is <p><strong>...</strong></p> on its own line; a run of sibling list-item headings is one <ul>.
    • Paragraphs: one <p> per paragraph, with no empty paragraphs for spacing. A soft line break becomes a space and a hard break becomes <br>.
    • Inline: <strong>, <em>, <s>, <a href> (titles dropped), and <code>.
    • Lists: <ul> and <ol> (with start when it is not 1), always tight, so there is no <p> inside <li>. Nested lists are flattened by default into the top-level list, with an en dash per level and the number kept for ordered sub-items, because public reports say X drops nested items. HtmlOptions(nested_lists="nest") keeps real nesting.
    • Quotes: <blockquote> with <p> inside.
    • Code blocks: <pre><code>, with the language tag dropped because X has no highlighting.
    • Tables: <table> with <thead>/<tbody>, <th> and <td>, and alignment dropped.
    • Divider: <hr>.
    • Images: each Mermaid block becomes its marker as its own <p>, taken from the document's image reference when one exists and [Image NN] otherwise. A Markdown image becomes the text [Image: alt].
    • Raw HTML in the source is escaped and shown as text. HTML comments (<!-- ... -->) are notes for the author and are dropped, block or inline.
  • Caption source rules. Captions are taken in this order: a Mermaid title (front matter in the diagram source, a title line, or a pie title), then a %% caption: comment in the block, then the text of an immediately following *Figure: ...* line (also **Figure: ...**, _Figure: ..._, Figure: ..., and ![Figure: ...](...)), then an immediately following paragraph that is one italic run (*...* or _..._, one line; a paragraph with only some italic words, or bold, does not count), then the nearest preceding heading. If none of those are present, the caption is Diagram NN (padded like the image number) so every marker has a label. A diagram with no explicit caption still gets one.
  • Markers and manifest. Each written body image gets a marker [Image NN: caption] and a manifest.json entry with order, file, marker, caption, anchor_text, and source_line. anchor_text is the paragraph immediately before the diagram, or null when the previous block is not a paragraph. source is the article file name, not a path. cover is images/cover.png or null. Image numbers are zero-padded to at least two digits, matching images/NN.png. The manifest lists only images that were written (a failed render is omitted). diagrams writes manifest.json, and --json includes a manifest path.
  • Nested diagrams. A Mermaid fence inside a list item or blockquote is a diagram like any other and keeps its place in reading order. It takes no anchor_text and no Figure: caption from the text around it; its caption comes from its own title or %% caption:, then the nearest heading.
  • HTML comments (dogfood finding). Comments are dropped from article.html: a comment-only block, a comment next to other raw HTML, and an inline comment. Other raw HTML is still escaped and shown as text. The writer now tokenizes raw HTML (markdown-it html on) so comments can be found, but never passes HTML through. A dropped comment also no longer separates a diagram from the line after it, so a caption line below a comment still counts.
  • Italic caption line (dogfood finding). A paragraph right after a top-level diagram that is one italic run is its caption, after the Figure: forms and before the nearest heading. A Figure: line still wins; a Mermaid title and %% caption: still win over both. The italic line stays in the article body, like a Figure: line does, so the words remain under the image after the marker is deleted. Nested diagrams still take no caption from the text around them.
  • The diagram's own %%{init}%% theme (dogfood finding). Honored rather than warned about: it is cheap (the renderer's own themeVariables were overriding the directive) and "Mermaid source is rendered as written" reads that way. Only colors and the Mermaid theme name come from the directive; layout, spacing, corner radius, and the canvas color stay the run theme's, so every image keeps the same canvas.
  • Wide flowcharts (dogfood finding). Not scaled past the canvas width: the 16:9 size and the 4% minimum margin stay. Instead, a flowchart wider than 16:9 gets a compact dagre render and keeps it when it draws at least 10% larger (a sample four-stage loop chart goes from about 1.03x to 1.22x). The 10% floor keeps diagrams that gain little on the default ELK layout, so they render as before. It shares compact_tall rather than adding a new key.
  • PyPI release. Trusted publishing from .github/workflows/release.yml. workflow_dispatch from main is a dry run (build, tests, twine, wheel smoke; uploads nothing). A v* tag on main publishes to PyPI (environment pypi). A human admin approves the pypi environment when a reviewer is required. The testpypi environment is unused. See Release and docs/RELEASE.md.
  • Full conversion (md2xarticle ARTICLE.md).
    • Any first argument that is not a command name (diagrams, outline, check) or -h, --help, --version starts the full conversion, so flags may come before the file. An article named like a command is passed as ./check.
    • Pipeline.run parses once, renders and composes the images, then hands one Article (images written, cover, Markdown text, its parse, heading map) to every ArticleWriter the factory gives it: XArticleHtmlWriter, then ManifestWriter. The privacy scan runs last, only with --check-privacy.
    • article.html and outline.txt are always written in full. A diagram that failed, or that --only left out, keeps the numbered [Image NN] marker in the HTML and is not in the manifest, which lists only images written in this run.
    • Exit 1 for a failed diagram, privacy findings, or a heading fallback. A heading fallback prints a warning and try: md2xarticle ARTICLE.md --heading-map flat. A failed diagram keeps the retry line from the Output contract: md2xarticle diagrams ARTICLE.md --only N --verbose. Usage and internal errors name the full conversion in their try: line.
    • --json has the README keys plus outline, failed, and notes; see the sample under Planned commands. The text summary counts the cover in its image total and cuts a long anchor_text to 48 characters.
    • --open opens the output folder through Platform.open_result after writing.
  • Contract reports (rco). .github/workflows/rco.yml, written by rco init from repo-context-optimizer 0.1.6 (the workflow pins that version), adds one report-only rco job (Ubuntu, Python 3.12). On a pull request its job summary shows rco diff, rco affected, rco drift pins and the cross-PR notice; on a push to main it runs rco update. It is not a required check and nothing runs at pre-commit. pins/core.json (model, theme, errors, the package root) and pins/interfaces.json (the five base classes, pipeline, factory) pin the most-imported public contracts; a drift is a report, and a change made on purpose re-pins with rco pin --for FILES --format json --out pins/NAME.json. rco.toml keeps every default.

Proposed in this draft but not yet approved by the owner. Confirm or cut each one:

  • Subcommands check and outline, alongside diagrams.
  • Flags --heading-map, --only, --open, and --size.
  • Default image sizes: 1600x900 for body images and 1500x600 for the cover.
  • Exit code 1 for a failed diagram or for privacy findings.
  • Privacy deny-list: an optional local list of names for the privacy scan, kept out of the repo.

Working on this repo (for agents)

  • Open questions go to the owner before you guess. If a decision is listed above, or you find a new one, ask and wait. Record the answer in this README.
  • Prefer checks over hard gates. Report facts visibly (CI checks, findings, warnings) instead of blocking work.
  • Small, verifiable PRs. One concern per PR, each with a done-when that a test or check confirms.
  • Do not re-run flaky tests until they pass. Fix them. A flaky image diff usually means a nondeterministic renderer, font, or Pillow setting.
  • Keep the interfaces honest. A new subclass passes its base class's contract suite. Pipeline never imports a concrete class.
  • Hygiene first. Run the hygiene check before every push. Synthetic fixtures only. Once per checkout, turn on the repo hooks with git config core.hooksPath .githooks. pre-commit runs tools/hygiene.py --staged on staged blobs.
  • Contracts before code. Install the repo-context-optimizer version that .github/workflows/rco.yml pins, in a separate environment on the Python version that workflow uses (rco needs a newer Python than this package's floor). Then run rco pack --for FILES before editing those files and rco diff $(git merge-base origin/main HEAD) HEAD before pushing. Both are advisory.
  • No network at run time. If a feature needs the network, it is out of scope or opt-in by name, and the owner decides.

Prior art

Browser tools and editor extensions already convert Markdown for X Articles, and some agent skills drive the X editor through a browser. md2xarticle differs in being a local, pip-installable CLI with no browser, Node, or network, real Mermaid rendering, and a manifest so bots can finish the job.

License

MIT, under the si4ai organization. See LICENSE.

Metadata

Release files for md2xarticle 0.1.1

For a detailed explanation of source distributions (sdists) and built distributions (wheels), please see the package formats documentation.

Source distribution (sdist)

Source distribution for md2xarticle 0.1.1
File Size Uploaded Provenance Actions
md2xarticle-0.1.1.tar.gz 127.0 kB With provenance Details for md2xarticle-0.1.1.tar.gz

Built distribution (wheel)

Table of built distributions (wheels) for md2xarticle 0.1.1
File Interpreter ABI Platform Actions
md2xarticle-0.1.1-py3-none-any.whl Python 3 none any Details for md2xarticle-0.1.1-py3-none-any.whl

Total release size: 209.8 kB

Release files / md2xarticle-0.1.1.tar.gz

Download URL md2xarticle-0.1.1.tar.gz
Size 127.0 kB
Tags Source
SHA-256 checksum
How to use checksums
a09239520a0d229451bcf8d2b8b748474d36794cb5c6a28b102d8582095204cf
BLAKE2b-256 checksum
How to use checksums
ad21ef49c35c76b93ebe8d6725b3af60290ad2ddc50593424f9352567ed8751e
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Release files / md2xarticle-0.1.1-py3-none-any.whl

Download URL md2xarticle-0.1.1-py3-none-any.whl
Size 82.8 kB
Tags Python 3
SHA-256 checksum
How to use checksums
3131210edd29253c581c1c8e8f41e8b86fe4605db5a64bad8ff95e1d102c8aef
BLAKE2b-256 checksum
How to use checksums
7b6a0cbf9035690fc5271e7cb4b54b120a388ba10c2590c02c3698196c1ec8ee
Upload date
Uploaded using Trusted Publishing?
What is trusted publishing?
Yes
Uploaded via twine/7.0.0 CPython/3.13.16

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

Security for md2xarticle 0.1.1

Provenance

Provenance describes where a file came from. On PyPI, provenance is shared via attestations, which provide a verifiable record of the build or publishing details. View details, limitations and caveats.

Full provenance

Both files in this release have been uploaded with provenance metadata.

Select from 2 files

Attestation for md2xarticle-0.1.1.tar.gz

PyPI Publish Attestation

PyPI verified that this artifact, at this checksum, originated from the publisher listed below.

Signed by GitHub Actions, verified by PyPI on Nov 24, 2026.

Transparency log

A note on package security

PyPI is a repository for distributing packages, not a service for auditing them. While third-party security researchers and our staff do their best to detect and remove malicious packages, PyPI cannot guarantee the quality, security or suitability of any given package.

To learn more about protecting yourself from malicious actors, visit our package security documentation.

Release history Release notifications | RSS feed

This release

0.1.1 This release

2 release files Full provenance

Anthropic, PBC Visionary sponsor Bloomberg Visionary sponsor Hudson River Trading Visionary sponsor Meta Visionary sponsor NVIDIA Visionary sponsor Microsoft Sustainability sponsor Depot Continuous Integration AWS Cloud computing and Security Sponsor Datadog Monitoring Fastly CDN Google Download Analytics Sentry Error logging StatusPage Status page