# architecture-drawer

Adopt this skill: https://proskills.md/skills/other/andy1314chen-architecture-drawer-plugins-architecture-drawer-skills-architecture

Page: https://proskills.md/skills/other/andy1314chen-architecture-drawer-plugins-architecture-drawer-skills-architecture
This document is the public skill bundle for that page. It contains SKILL.md and every helper file the catalog carries. No login is required.

## File: plugins/architecture-drawer/skills/architecture-drawer/SKILL.md
size: 46557
sha: 072ce52b2789e20011419f05b2b7efb54820223e
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/SKILL.md
truncated: true

````text
---
name: architecture-drawer
description: Use when asked to draw system architecture diagrams, generate technical architecture SVGs, or export architecture diagrams to editable PowerPoint presentations. Supports multi-layer diagrams with automatic layout validation and scoring (16-dimension evaluator catches collisions, overlaps, dangles, crossings, palette issues incl. colorless and gray-dominant diagrams, low-contrast labels, misaligned peers, and a Step-1 design-brief contract: the declared palette/layout/flow is asserted against the rendered SVG).
---

# SVG Architecture Drawer (Smart Version)

This Skill converts complex technical descriptions into structured SVG architecture diagrams. It integrates layout constraints, collision detection, **connection/arrow connectivity validation**, and quality evaluation, automatically identifying and guiding the correction of layout errors.
The script directory (referred to as `$SKILL` below) is this skill's own
`scripts/` folder. From a generator script that lives next to its artifacts,
resolve it relative to the script's own location (never hard-code an absolute
path, which breaks on other machines):

```python
import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
# From evals/<name>/gen.py -> ../../scripts ; adjust depth for your layout.
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
```

## Fast Path (read this first; details below are on-demand reference)

Ordinary generation follows this bounded loop. Do not read the full
specification sections before the first candidate runs — the checks below
tell you what to fix, and each section explains its own vocabulary when a
report line names it.

**Strategy — the evaluator is the oracle, not your own verification.** Do
not read `scripts/evaluator.py` to internalize every threshold, and do not
mentally verify the layout against all 16 checks before writing: that
duplicates work the evaluator does in under a second. Sketch an approximate
layout with sane coordinates, run `gen.py`, read the report lines, and fix
exactly what they name (thresholds + repairs are tabulated in
`references/checks_cheatsheet.md` — read that table instead of the
evaluator source).

**Do the arithmetic in code, not in your head.** `references/api_quickref.md`
tabulates every DSL signature + the known traps (which default draws an
arrow, text-y semantics, container `node_kind`), and the layout helpers
(`layout_grid` / `layout_row` / `layout_band` / `layout_radial`) compute
positions from the array spec — state "6 chips, 3 per row, 24px gutters",
not forty hand-derived coordinates. Start from the skeleton in
`references/gen_template.md` (constants block for bands/nodes/flow, fixed
evaluate-export tail) instead of re-deriving the boilerplate.

1. **Write the candidate** — resolve `$SKILL` (snippet above), pick ONE
   palette preset from `references/design_specs.md` (do not invent hex
   values), land the Step-1 design-brief tokens as a constants block atop
   `gen.py`, draw with `drawer.rect/circle/connect` (register `node_id`s so
   connections validate), then immediately run the script. One clear main
   flow beats a dense map; ≤12 primary nodes before the first evaluation.
2. **Evaluate** — `evaluate_svg(drawer)` prints the score; every `[FAIL]`
   line names the defect class (dangle / route-through / crossing / text
   overlap / contrast / palette). Fix exactly what the lines name; the
   Auto-Correction section maps each tag to its repair.
3. **Bounded repair** — at most **2 focused correction rounds** on the
   highest-penalty FAILs (call `auto_refine(drawer)` first: gutter and
   spacing fix themselves). If the score reaches ≥80 with no `[FAIL]`
   remaining, ship. If two rounds do not converge, stop and report the
   unresolved `[FAIL]` lines truthfully — never claim success with defects
   outstanding, and never widen the canvas or shrink text to hide them.

```dot
digraph fastpath {
    "write candidate" -> "evaluate_svg()" -> "auto_refine + fix FAILs";
    "auto_refine + fix FAILs" -> "evaluate_svg()" [label="round ≤2"];
    "auto_refine + fix FAILs" -> "ship (score≥80, 0 FAIL)" [label="clean"];
    "auto_refine + fix FAILs" -> "report unresolved FAILs truthfully"
        [label="2 rounds spent"];
}
```

## Step 0 — Intent Judgment (fidelity vs. completion)

Before writing any code, classify the requirement — the two failure modes are
mirror images: transcribing a vague spec literally produces a broken diagram,
and "improving" a precise spec produces one the user did not ask for.

**Faithful mode** — the description is clear and detailed (explicit components,
relations, flow direction, canvas): transcribe it exactly. Do **not** invent
components, layers, edges, or legend entries the user did not state, and do not
"upgrade" the palette or topology on your own taste. Adding unrequested boxes
is a defect, not a feature (画蛇添足).

**Completion mode** — the description is vague (the user may not have a fixed
picture in mind yet): infer a reasonable design, then state what you inferred.
Ambiguity signals and the corresponding conservative defaults:

| Missing in the spec | Conservative default |
|---|---|
| Relations between named components | connect adjacent tiers only, in the domain's natural flow (client → API → compute → storage) |
| Canvas / size | 1200×800 (or the diagram-type preset in `references/diagram_types.md`) |
| Diagram type | pick from `references/diagram_types.md` by content keywords |
| Layer grouping | group only when the spec's own vocabulary implies it ("… layer", "… module") |
| A composite-sounding component ("gateway", "engine") | stays ONE node — never split into sub-nodes the user did not mention |

Completion rule: an addition is legitimate only when the diagram is
structurally incoherent without it — never decorative. List every assumption
in the final reply ("assumed top-to-bottom flow; inferred gateway→auth edge")
so the user can veto. When two readings are both plausible, pick the simpler
one and note the alternative.

## Step 1 — Design Brief (开工前完整设计)

After Step 0 classifies the requirement and BEFORE writing any code, produce a
complete design proposal that combines the user's `input.md` with this skill's
design system — **state the design, then draw it**. In an interactive session
you may show the brief first and let the user veto; in headless/automation,
print it in the reply and proceed.

The brief has five mandatory sections:

1. **Canvas & layout skeleton** — canvas size, band/column/grid partition,
   margins, and the placement *strategy* as relative formulas (e.g.
   `gap = (band_w − n·card_w) / (n + 1)`, `y[i+1] = y[i] + h + GUTTER`), not
   per-element hard-coded coordinates. Name what Step 0 left open (completion
   mode) or what the spec pinned (faithful mode).
2. **Palette** — pick ONE preset scheme from `references/design_specs.md`
   (S1–S4) by information need and give the role→color mapping table: each
   business role gets a light tint fill PAIRED with its dark accent stroke;
   op cards stay white; accents ≤8; at least one chromatic accent (the ⑯
   无配色 floor). Exact hex from the spec, when given, wins over the preset.
   Color must OWN THE STRUCTURE, not decorate it: tint the band/container
   fills (band-style) or color the primary nodes (node-style) — a mostly
   gray/white skeleton with color confined to small chips FAILs the ⑯
   灰色主导 check (chromatic coverage <35% of elements AND <15% of area).
3. **Typography tiers** — 3–4 tiers with concrete values (e.g. 20 / 14 / 12 /
   10) and which text class uses each (title / section header / node label /
   note).
4. **Edge routing** — flow directions, solid vs dashed semantics, spine/bus
   corridors routed OUTSIDE content areas (kiss container edges, never slice
   filled rects — the semantic-QA 箭头线盖在组件上 check), junction/merge
   points, and edge-label placement rules (off the line, perpen
````

## File: plugins/architecture-drawer/skills/architecture-drawer/scripts/design_brief.py
size: 7328
sha: eaa86c514f32ad4d2f7e4612d03bf30cbbfc8fa6
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/design_brief.py

```text
"""Design Brief contract — the declared design intent of a diagram (Step 1).

A DesignBrief is the machine-readable form of the Step-1 design brief: what
palette / layout / flow the author *declared* before drawing.  The contract
checker (semantic_qa.check_design_brief) then asserts the RENDERED SVG against
this declaration.

Capability boundary (deliberate): this layer verifies
**rendering <-> self-declared contract** consistency.  It does NOT verify
"contract <-> user's true intent" — the brief and the gen.py are usually
written by the same agent in the same round, so a coherently-wrong brief
passes.  Spec-entity coverage (check_text_semantics) and human review of the
brief remain the guards for intent.

Schema rules (inconsistent states are unconstructible):
  - ``palette_role`` is the SINGLE source of declared identity: its keys are
    the data-node-id values the checker looks for in the SVG.  Key semantics
    are bound to ``layout``: band -> layer-container ids, node -> primary
    node ids.  There is no separate container list to drift out of sync.
  - ``flow_chain`` is the ordered pipeline chain (a SUBSET of palette keys —
    validated at construction).  Side bands (memory/cache columns) and
    text-only bands are palette members but not chain stages; membership is
    not derivable from paint, so it is declared explicitly.
  - tint/plain membership is DERIVED from ``ColorSpec.fill`` (white == plain).
  - All colors are canonicalized through ``svg_utils.normalize_color`` to
    lowercase #rrggbb ("white" -> "#ffffff", named colors like "gray" ->
    "#808080") — the same normalizer the checker applies to rendered SVG
    fills, so hex case/alias/named tokens never produce noise failures.
"""
import json
from dataclasses import dataclass, field
from typing import Mapping, Tuple

try:
    from svg_utils import normalize_color
except ImportError:  # standalone use without the skill on sys.path
    def normalize_color(value):  # type: ignore[misc]
        return None

_WHITE = {"white", "#fff", "#ffffff"}
_LAYOUTS = ("band", "node")
_FLOWS = ("top-down", "left-right", "none")

def norm_hex(color: str) -> str:
    """Normalize a color token to lowercase #rrggbb (3-digit expanded,
    'white' family collapsed to #ffffff). Unknown tokens pass through
    lowercased so mismatches still compare deterministically."""
    c = (color or "").strip().lower()
    if c in _WHITE:
        return "#ffffff"
    if c.startswith("#") and len(c) == 4:
        return "#" + "".join(ch * 2 for ch in c[1:])
    return c

def canon_hex(color: str) -> str:
    """Canonical #rrggbb via svg_utils.normalize_color — the SAME
    normalization the checker applies to rendered fills, so a brief and the
    SVG compare on identical tokens (named colors like 'gray' resolve to hex
    on both sides). Tokens normalize_color cannot parse ('none', '',
    unknown) keep norm_hex's lowercase passthrough so is_plain still
    recognizes them."""
    c = norm_hex(color)
    return normalize_color(c) or c

def is_plain(fill: str) -> bool:
    """A plain fill reads as white/neutral canvas (not a tinted structure)."""
    return norm_hex(fill) in _WHITE or norm_hex(fill) in ("none", "")

@dataclass(frozen=True)
class ColorSpec:
    """A declared (fill, stroke) pair — the tint+accent pairing that the
    contrast check (WCAG) relies on; declaring one hex is not enough."""
    fill: str
    stroke: str

    def __post_init__(self):
        object.__setattr__(self, "fill", canon_hex(self.fill))
        object.__setattr__(self, "stroke", canon_hex(self.stroke))

    def as_pair(self) -> Tuple[str, str]:
        return (self.fill, self.stroke)

    @classmethod
    def from_json(cls, d) -> "ColorSpec":
        return cls(d["fill"], d["stroke"])

@dataclass(frozen=True)
class DesignBrief:
    scheme: str = "S1"            # preset id from references/design_specs.md
    layout: str = "band"          # band | node  (key semantics, see module doc)
    flow: str = "top-down"        # top-down | left-right | none (no dominant axis)
    # key = data-node-id (band: layer container; node: primary node)
    palette_role: Mapping[str, ColorSpec] = field(default_factory=dict)
    # ordered pipeline chain (first -> last along the flow axis): a SUBSET of
    # palette keys; side bands / text-only bands stay out of the chain.
    flow_chain: Tuple[str, ...] = ()

    def __post_init__(self):
        if self.layout not in _LAYOUTS:
            raise ValueError(
                f"layout must be one of {_LAYOUTS}, got {self.layout!r}")
        if self.flow not in _FLOWS:
            raise ValueError(
                f"flow must be one of {_FLOWS}, got {self.flow!r}")
        object.__setattr__(self, "palette_role", dict(self.palette_role))
        unknown = [k for k in self.flow_chain if k not in self.palette_role]
        if unknown:
            raise ValueError(
                f"flow_chain keys not declared in palette_role: {unknown}")

    # -- derived views (single source of truth: palette_role) ---------------
    @property
    def tint_keys(self) -> Tuple[str, ...]:
        """Declared keys whose fill carries structure color (tinted)."""
        return tuple(k for k, s in self.palette_role.items()
                     if not is_plain(s.fill))

    @property
    def plain_keys(self) -> Tuple[str, ...]:
        """Declared keys that stay white-bottomed (op cards)."""
        return tuple(k for k, s in self.palette_role.items()
                     if is_plain(s.fill))

    @property
    def layers(self) -> Tuple[str, ...]:
        """Ordered chain stages (first -> last along the flow axis): the
        declared flow_chain. Empty for node-style briefs / no chain."""
        return tuple(self.flow_chain)

    # -- serialization (brief.json next to the artifact triplet) -----------
    def to_dict(self) -> dict:
        return {
            "scheme": self.scheme,
            "layout": self.layout,
            "flow": self.flow,
            "flow_chain": list(self.flow_chain),
            "palette_role": {k: {"fill": s.fill, "stroke": s.stroke}
                             for k, s in self.palette_role.items()},
        }

    def to_json(self) -> str:
        return json.dumps(self.to_dict(), indent=2, ensure_ascii=False)

    @classmethod
    def from_dict(cls, d) -> "DesignBrief":
        return cls(
            scheme=d.get("scheme", "S1"),
            layout=d.get("layout", "band"),
            flow=d.get("flow", "top-down"),
            flow_chain=tuple(d.get("flow_chain", ())),
            palette_role={k: ColorSpec.from_json(v)
                          for k, v in d.get("palette_role", {}).items()},
        )

    @classmethod
    def from_json(cls, text: str) -> "DesignBrief":
        return cls.from_dict(json.loads(text))

    @classmethod
    def load(cls, path) -> "DesignBrief":
        with open(path, "r", encoding="utf-8") as fh:
            return cls.from_json(fh.read())

    def write(self, path) -> None:
        with open(path, "w", encoding="utf-8") as fh:
            fh.write(self.to_json())

def load_brief_file(path) -> "DesignBrief":
    """Convenience loader used by gen.py / tests; returns None when absent."""
    try:
        return DesignBrief.load(path)
    except FileNotFoundError:
        return None
```

## File: plugins/architecture-drawer/skills/architecture-drawer/scripts/evaluator.py
size: 73745
sha: b9cae7ae8bf6cb204b85a72031441af255add997
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/evaluator.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/evaluator.py

## File: plugins/architecture-drawer/skills/architecture-drawer/scripts/semantic_qa.py
size: 56615
sha: 0abb6d0af3bb4145e8dfb773e7ed8c9f56ba9841
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/semantic_qa.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/semantic_qa.py

## File: plugins/architecture-drawer/skills/architecture-drawer/scripts/svg2pptx.py
size: 44882
sha: 25d8eade0beaa9c4004ffe69f0d7a75e85068f67
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/svg2pptx.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/svg2pptx.py

## File: plugins/architecture-drawer/skills/architecture-drawer/scripts/svg_utils.py
size: 57512
sha: 99bb2dbf68ddd843ba1a3a20710ded5f3e42de15
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/svg_utils.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/scripts/svg_utils.py

## File: plugins/architecture-drawer/skills/architecture-drawer/references/api_quickref.md
size: 2679
sha: 189998698af67535f9c1fcf857ac1212a9a7c6dc
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/references/api_quickref.md

````text
# API Quickref — SVGDrawer & layout helpers

One-page signatures + the known traps. Read this instead of grepping
`scripts/svg_utils.py` for signatures (each source grep costs a model turn;
this page answers the same questions without one).

## Layout helpers (pure geometry — they compute, you draw)

```python
from svg_utils import layout_grid, layout_row, layout_band, layout_radial

layout_grid(n, x0, y0, cols, w, h, gx, gy) -> [(x, y), ...]
    # n cells, cols per row, left-to-right then down; (w+gx)/(h+gy) pitch.
    # The card-array primitive: chips in a band, station rows, pipeline stages.

layout_row(items, x0, y0, gx) -> [(x, y0, w), ...]
    # items = list of widths. Variable-width flow: source -> queue -> engine.

layout_band(title, x, y, w, h, pad=24, title_h=28) -> (bx, by, bw, bh)
    # Drawable interior of a titled container — contents placed inside
    # never collide with the title strip or band edges.

    # ZERO crossings by construction. positions: {id: (x,y,w,h)};
    # sides: {nid: (neighbor_side, hub_side)} ready for connect().
```

State the array, not the coordinates: `for (x, y) in layout_grid(6, bx, by, 3, 120, 40, 30, 24)` replaces
six hand-computed positions and the gutter/slope arithmetic that places them.

## Drawing (register node_id so connections validate)

```python
d.rect(x, y, w, h, rx=5, fill=, stroke=, node_id=, node_kind="op", role=, bbox=)
d.circle(cx, cy, r, fill=, node_id=, node_kind="junction")
d.text(x, y, s, font_size=, anchor="middle", fill=, weight=)   # y is the CENTER line
d.line(x1, y1, x2, y2, stroke=, marker_end=, role="decoration")
d.connect(from_id, from_side, to_id, to_side, stroke=, dashed=, marker_end="arrowhead")
```

## Traps (each has cost a replay session a repair round)

- **`connect()` draws `marker_end="arrowhead"` by default** — pass `marker_end=None` explicitly for a plain
  connector. (`d.line` defaults to no arrow; ask only if you want one.)
- **Container cards**: give them `node_kind="layer"` (or `role="layer"`) when they are pure containers; use
  `node_kind="op"` only when something must `connect()` to them. Contained chips are exempt from the
  spacing check; equal-pitch arrays are protected from `auto_refine`.
- **`d.text` y is the CENTER line** (`dominant-baseline`), not the top — `y = box_y + h/2` for in-box labels.
- **Deep literals (>3 nesting) belong in named constants** — inline nested tuples/tuples-in-lists cause
  bracket-mismatch edits (observed: 3 wasted edit rounds counting parens).
- **`auto_refine(drawer)`** fixes gutter + spacing; it refuses containment pairs and grid arrays on
  purpose. Route/dangle/crossing fixes are always manual.
````

## File: plugins/architecture-drawer/skills/architecture-drawer/references/checks_cheatsheet.md
size: 7259
sha: 11e8a5411bd0fb9e01daed8f05fc70563e49b7e0
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/references/checks_cheatsheet.md

````text
# Evaluator Cheatsheet — 16 checks × threshold × trigger

Single-page reference for the quality gate in `scripts/evaluator.py`
(`evaluate_svg`). **Read this instead of the evaluator source code**: every
number below is the exact default the shipped evaluator enforces, and the
repair column is what the `[FAIL]`/`[WARN]` report line expects you to do.
All checks are **render-then-parse** — they re-read the actual SVG markup, so
`add_element`/`bbox=False` content is measured too.

**Do not pre-verify these by hand.** `evaluate_svg` runs in under a second on
a finished `gen.py`; it is the cheap oracle. Sketch an approximate layout,
run the script, read the report lines, and fix exactly what they name. The
table exists so a report line can be mapped to a threshold and a repair
without reading the check's implementation.

## Score model

Start at 100. Each failing check subtracts its penalty (see table; multiple
issues in one check multiply per-issue cost up to that check's cap). Score
floors at 0. `[FAIL]` vs `[WARN]`: both cost points; `[FAIL]` classes are
defects that must be fixed (ship gate: no `[FAIL]`), `[WARN]` classes are
quality polish — fix when cheap, never suppress.

## The 16 checks

| 1 | Collisions | Any two registered bboxes overlap | 10/issue | Move one node clear of the other; never layer business shapes |
| 2 | Canvas boundary | Any bbox outside `0,0–W,H` | 15/issue | Pull coordinates inside; enlarge canvas only via the brief |
| 3 | Text overflow (canvas) | `<text>` bbox outside canvas (pad 2) | 6/issue, cap 24 | Shorten the label or move the text inside |
| 4 | Text overflow (container) | `<text>` bbox outside its nearest containing rect (pad 6) | 3/issue, cap 18 | Widen the node/container or shorten the label |
| 5 | Text overlaps | `<text>` bbox hits a visible shape or another `<text>` (+pad 1) | 4/issue, cap 24 | Nudge the label or the shape; never stack labels |
| 6 | Coverage | Union of bboxes <5% or >60% of canvas | −20 / −10 | Repack to fill the canvas better (denser or sparser) |
| 7 | Dangling / degenerate edges | Edge endpoint >12px from any node border, or length <4px | 8/issue, cap 40 | Re-anchor with `connect(a, side, b, side)` — auto-snap |
| 8 | Duplicate edges | Same endpoint pair within 6px | 8/issue (with #7, cap 40) | Delete the duplicate; or offset via port spread (automatic when ≥2 edges share a side) |
| 9 | Phantom anchors | Invisible node (no fill/stroke/size) used as edge endpoint | 15/issue, cap 45 | Give the anchor a visible shape, or connect to a real node |
| 10 | Route-through | Edge polyline passes through an unrelated node interior (+3px margin) | 10/issue, cap 40 | Reroute: connect side-to-side so the segment misses nodes |
| 11 | Edge crossings | Two edge polylines cross in their interiors | 8/pair, cap 40 | Reroute one edge; a hub junction node often kills crossings |
| 12 | Composition budget | >2 bends, >1.35× route stretch, gutter <20px, segment <16px | 2/issue (WARN), cap 12 | Straighten the route; widen the container gutter |
| 12b | Edge-through-text | Edge segment passes through a `<text>` bbox | 8/issue, cap 24 | Reroute the edge around the label |
| 13 | Same-kind spacing | Two `op`/`junction` nodes <14px apart (Euclidean gap); a chip fully inside its card is exempt (gutter rule owns it) | 4/issue, cap 20 | Spread nodes; `auto_refine` fixes this automatically |
| 14 | Peer alignment | Same-sized same-kind peers in a row/column sharing no edge/center line (5px / 15%) | 3/issue, cap 15 | Snap the row/column to shared edges |
| 15 | Type scale | >4 distinct font sizes, or adjacent tiers <1.15× apart | 4/issue, cap 8 | Use 3–4 tiers (e.g. 20/14/12/10); merge near-duplicate sizes |
| 16 | Palette | >8 accents (hard 12); zero chromatic accents; gray-dominance (<35% business elements chromatic AND <15% painted area) | 4/issue; FAIL beyond hard cap / colorless / gray-dominant | Use a preset from `design_specs.md`; color must own bands or nodes, not just chips |
| 17 | Contrast | `<text>` on an accent fill <3:1 FAIL (<4.5:1 WARN; large text ≥24px or bold ≥18.5px → 3:1) | 6/issue, cap 18; WARN 3/issue cap 12 | Darken text on light tints / lighten on dark fills (preset tiers are pre-verified) |

> Rows 15–17 involve the semantic layer (palette / type scale / contrast are
> asserted in the brief contract too): a preset from `design_specs.md` plus
> brief palette_role keys keeps all three green without measurement.

## Report line → repair mapping (quick decode)

```
"[FAIL] N element collisions"                       → check 1: separate the shapes
"[FAIL] N elements exceed canvas boundaries"        → check 2: pull inside / resize canvas
"[FAIL] N text element(s) overflow the canvas"      → check 3: shorten/move text
"[FAIL] N edge(s) route through unrelated node"     → check 10: reroute
"[FAIL] N text overlap(s) with shapes/other text"   → check 5: nudge labels
"[WARN] Canvas coverage very low/high"              → check 6: repack density
"[FAIL] Connection check … dangling … duplicate"    → check 7/8: re-anchor / dedupe
"[FAIL] N phantom anchor(s)"                        → check 9: visible anchor
"[FAIL] N edge pair(s) cross"                       → check 11: reroute / hub
"[FAIL] N edge(s) pass through text"                → check 12b: route around text
"[WARN] composition budget violation(s)"            → check 12: straighten/gutter
"[WARN] N same-kind node pair(s) too close"         → check 13: spread / auto_refine
"[WARN] N misaligned same-kind peer pair(s)"        → check 14: snap to shared edge
"[WARN/FAIL] Typography …"                          → check 15: 3–4 tiers, ≥1.15×
"[WARN/FAIL] Palette …"                             → check 16: preset + brief keys
"[FAIL] N text element(s) below 3:1 contrast"       → check 17: contrast-safe text
```

## Anti-simulation guidance

The two most expensive mistakes an agent makes with this skill (measured:
~84% of wall-clock on a clean run): reading the evaluator source to
understand every threshold, then mentally verifying the layout against all
16 checks before writing anything. Both are wasted effort:

- The evaluator **is** the oracle and runs in <1s. Write an approximate
  layout, run, read report lines, fix what they name. Two bounded rounds
  converge on every shipped eval.
- This cheatsheet replaces source-reading for check semantics. If a report
  line's vocabulary is unclear, read this table's row, not the check's
  implementation.

## Notes on auto-fix vs manual

`auto_refine(drawer)` (in `evaluator.py`) handles checks 12 (gutter part),
13, and the spacing part of the budget automatically — call it before any
manual repair. It deliberately refuses two cases: containment pairs (a chip
inside its card is the gutter rule's business) and equal-pitch grid arrays
(>=3 aligned nodes — move the whole array instead; centering one member
breaks the alignment). Checks 7/10/11/12b (dangles, route-through, crossings,
edge-through-text) need manual rerouting: `connect()` side-to-side snapping
plus junction nodes for fan-outs. Differently-sized peers are exempt from
check 14; legend/background shapes and intentional in-box labels are exempt
from check 5.
````

## File: plugins/architecture-drawer/skills/architecture-drawer/references/design_specs.md
size: 6792
sha: 3ae9d9cc728a334452147803f59ca6efdfabf081
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/references/design_specs.md

````text
# SVG Architecture Design Specifications

## Color Palette Library

Color encodes **information**, not decoration. This skill ships multiple preset palettes — **pick by diagram type** (see the decision guide), not by aesthetic preference. Each scheme is pre-verified against the evaluator (accent count ≤ 12, no luminance clash) and tuned for a specific visual task. Categorical palettes (Okabe-Ito etc.) are optimized for class separation in scatter/line charts and look chaotic as large fills — don't use them where a monochrome or semantic scheme fits.

### How to choose

Pick by **information need** first — color must earn its place by encoding a class, a type, or a focus. Reach for S1 only when none of those apply, not as a reflex. For a per-diagram-type shortcut, see `references/diagram_types.md`.

| Information need | Scheme | Rationale |
| :--- | :--- | :--- |
| Distinguish 2–4 classes / branches / roles / lanes | **S2 Categorical** | Colorblind-safe hue separation — use whenever the eye must group by category |
| Component **type** has a fixed meaning (cloud / network device) | **S3 Semantic** | One color per type, consistent across every diagram |
| One focal element (innovation / core / hero module) | **S4 Duotone** | Cool body + single warm accent that pops |
| Pure layering / pipeline, **no** class or type distinction (or ≥4 same-tier modules) | S1 Monochrome Blue | Single-hue luminance tiers — uniform, grayscale-safe |
| Grayscale print / technical report | S1 | Pure luminance ramp is inherently gray-safe |

**S1 is the fallback, not the default.** Match an information need above first; only fall back to S1 when the diagram is genuinely just layered flow with no categorical / semantic / focal role for color. Defaulting everything to blue wastes the palette and makes every diagram look the same.

### Scheme 1: Monochrome Blue (fallback)

Single hue (Nature Blue), four luminance tiers, **unified dark stroke**. Layers are distinguished by fill lightness (ΔE 8–12, spread 3.6 — uniform), not by hue. Op cards stay white so they don't inflate the accent budget. The most克制/uniform scheme; ideal when modules ≥ 4.

| Tier | Fill | Stroke (unified) | Suggested use |
| :--- | :--- | :--- | :--- |
| L1 (lightest) | `#D5E1EB` | `#1B3A5C` | Input / frontend |
| L2 | `#BBCEDF` | `#1B3A5C` | Processing |
| L3 | `#9BB9D1` | `#1B3A5C` | I/O / transport |
| L4 (darkest) | `#769EBF` | `#1B3A5C` | Output / storage |

*Evaluator: 5 accents, no clash. ΔE(adj fill) = 8.3 / 9.7 / 11.9.*

### Scheme 2: Categorical (colorblind-safe)

Okabe-Ito (Nature Methods 2011, Bang Wong), the de-facto standard for accessible categorical figures. Use **only when distinct classes need hue separation** (2–4 groups); do not use for ≥5 side-by-side layers (switch to S1). Two fill modes: colored tint (richer, 8 accents) or white (most克制, 4 accents — color lives in the border only).

| Class | Fill (tint) | Fill (white mode) | Stroke |
| :--- | :--- | :--- | :--- |
| Orange | `#FAEED1` | `#FFFFFF` | `#E69F00` |
| Sky Blue | `#E1F2FB` | `#FFFFFF` | `#56B4E9` |
| Bluish-Green | `#D1EEE6` | `#FFFFFF` | `#009E73` |
| Deep Blue | `#D1E6F1` | `#FFFFFF` | `#0072B2` |

*Evaluator: 8 accents (tint) / 4 accents (white), no clash.*

### Scheme 3: Semantic (cloud / system architecture)

Component **type** → fixed color, consistent across every diagram (ArchiMate / AWS-diagrams convention). Op cards are white-filled; the color lives entirely in the stroke + a small type label. This keeps the accent count low even with many components.

| Component type | Stroke | Fill |
| :--- | :--- | :--- |
| Network (LB, gateway) | `#3498DB` | `#FFFFFF` |
| Compute (app, instance) | `#E67E22` | `#FFFFFF` |
| Storage | `#27AE60` | `#FFFFFF` |
| Security | `#E74C3C` | `#FFFFFF` |
| Database | `#9B59B6` | `#FFFFFF` |

*Evaluator: 5 accents, no clash. To group components into a cluster, wrap them in a near-white container (`#F7F7F7`) with a `#CCCCCC` border — neutrals, not counted.*

### Scheme 4: Duotone (focal highlight)

A tight cool family (3 hues) for the body, plus **one warm focal accent** for the single most important element. The warm color pops against the cool background without redesigning the palette. Use when the diagram has a clear "hero" (innovation point, loss module, key output).

| Role | Fill | Stroke |
| :--- | :--- | :--- |
| Cool 1 (Indigo) | `#CDD2F6` | `#5B6EE1` |
| Cool 2 (Cyan) | `#BFDFED` | `#3D9FC7` |
| Cool 3 (Teal) | `#B0DDD9` | `#2EA69A` |
| **Focal (Amber)** | `#F6D0B4` | `#E8833A` |

*Evaluator: 8 accents, no clash. Reserve the amber for exactly one element; using it on multiple nodes defeats the focal intent.*

### Structural neutrals (all schemes, not counted as accents)

| Element | Hex | Usage |
| :--- | :--- | :--- |
| Background | `#FFFFFF` | Canvas (white is the default) |
| Container / Divider | `#D5D5D5` or `#CCCCCC` | Layer frames, cluster wrappers |
| Cluster fill | `#F7F7F7` | Near-white grouping background |
| Text (Primary) | `#000000` | Main labels and headers |
| Text (Secondary) | `#333333` | Sub-labels and formulas |
| Connectors | `#4D4D4D` or `#666666` | Arrows / lines (gray, not colored) |

### Design principles (apply to all schemes)

1. **White-dominant** — ≥70% of the canvas should be white/near-white. Color is a border/label language, not a fill-everything language.
2. **Op cards stay white** — only layer/cluster containers take colored fills; individual operation cards are `fill="white"` so they don't bloat the accent count.
3. **≤3 chromatic families visible at once** (S1 has 1, S3 has up to 5 but only as strokes). If a diagram needs more, it's too complex — split it.
4. **Connectors are gray** (`#4D4D4D`), never colored. Color on a line implies data-flow semantics that belong to the node, not the edge.
5. **One focal accent max** — if highlighting, pick exactly one element (S4 amber, or a saturated stroke swap in S1). Multiple "highlights" = no highlight.

## Layout Principles

1.  **Grid-Based**: Use a 1200x800 base canvas.
2.  **Layering**: Use vertical sections (Layers) and horizontal stages (Stages).
3.  **Spacing**:
    *   Margin: 20px
    *   Section Padding: 10px
    *   Component Gap: 15px
4.  **Typography**:
    *   Main Header: 18px, Bold
    *   Sub-header: 14px, Bold
    *   Body Text: 12px, Regular
    *   Math/Formula: 13px, Monospace/Italic

## Reusable Components

### 1. Rounded Container
```svg
<rect x="x" y="y" width="w" height="h" rx="10" ry="10" fill="#HEX" stroke="#333" stroke-width="1" />
```

### 2. Arrow Marker
```svg
<defs>
  <marker id="arrowhead" markerWidth="10" markerHeight="7" refX="9" refY="3.5" orient="auto">
    <polygon points="0 0, 10 3.5, 0 7" fill="#333" />
  </marker>
</defs>
```
````

## File: plugins/architecture-drawer/skills/architecture-drawer/references/diagram_types.md
size: 13168
sha: 15cdfdbbdeb7f94d58bd3341bb08e1216bfa4d40
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/references/diagram_types.md

```text
# Diagram Type Presets — Shapes & Layout

Companion to `design_specs.md`. That file owns **color** (S1–S4 palettes) and global layout rules; this file owns **shape vocabulary and per-type layout conventions** — i.e. *what shape each element becomes* and *how the type is conventionally arranged*. Read both when the user names a diagram type.

Each preset maps a semantic role to one of the drawer's primitives (`rect` / `circle` / `database` / `decision` / `hexagon` / `component` / `cloud` / `line` / `connect` / `text` / `multiline_text` / `formula`) plus a palette tier. Coordinates are still hand-placed (this skill has no Graphviz); the layout rows below give the spacing/direction defaults that consistently pass the evaluator.

## How to choose

| Diagram type | Typical prompt keywords | Palette | Direction |
| :--- | :--- | :--- | :--- |
| Architecture (system / cloud / service) | 架构 / architecture / 微服务 / topology | S1 (≥4 same-tier modules) or S3 (component-type semantics) | TB; **≥4 tiers → TB**, else LR |
| Flowchart (process / decision logic) | 流程 / flow / pipeline / 审批 | **Role palette** (process/decision/IO hues below) — S1 only if purely linear | TB |
| ML / DL model | 模型 / network / Transformer / CNN / encoder-decoder | **Role palette** by layer type (below), or S4 for one focal layer | TB |
| ER (database schema) | ER / 表结构 / schema / 数据库设计 | S1 (or S2 if multiple entity domains) | TB |
| Sequence (interaction / 时序) | 时序 / sequence / 交互 / 协议流 | S1 (or S2 to color by actor) | LR (lifelines) × TB (time) |
| Swimlane (cross-functional / 跨职能) | 泳道 / 谁做什么 / 跨部门 | **S2** (one hue per lane) | LR inside lanes |
| Network topology | 网络 / topology / LAN / 部署拓扑 | **S3** (device-type semantics) | TB by tier |

Palette is picked by **information need**, not habit — see `design_specs.md`. When the request is genuinely ambiguous about type, fall back to Architecture + S1.

## Universal shape vocabulary (role → primitive)

Use this as the canonical mapping. A node drawn with `node_id=` is connectable; `role="layer"|"background"` marks a container that the evaluator **excludes from spacing/collision checks**. Palette checks are role-agnostic — they ignore only *neutral* fills/strokes (near-white / gray), so keep container fills near-white (`#F7F7F7`) if you don't want them counted toward the accent budget.

| Role | Primitive | Notes |
| :--- | :--- | :--- |
| Layer / tier / container / cluster | `rect(role="layer", fill=near-white, stroke=neutral)` | Dashed border for logical grouping; solid for physical |
| Service / process / module / op | `rect(node_id=…, fill=S-tier)` | The default connectable box |
| Database / persistent store | `database(node_id=…, fill=S-tier)` | Cylinder |
| Decision / branch | `decision(node_id=…, fill=S-tier)` | Diamond |
| Gateway / broker / bus (hub) | `hexagon(node_id=…, fill=S-tier)` | 6-sided; place centrally |
| External system / 3rd-party | `component(node_id=…, fill=S-tier, extra='stroke-dasharray="6,3"')` | Tabbed box; dashed border = outside boundary |
| Internet / WAN / cloud service | `cloud(node_id=…, fill=S-tier)` | Multi-lobe cloud |
| Start / End terminator | `circle(node_id=…, r=…)` or `rect(rx=h/2)` (stadium) | Small circle for start/end; stadium for labels |
| Junction / merge point | `circle(node_id=…, node_kind="junction", r=4–6)` | Tiny; auto-snaps edges |
| I/O (input/output data) | `hexagon(...)` *(no native parallelogram)* | Hexagon is the closest semantic match |
| Connector | `connect(from, side, to, side, …)` or `line(…, register_edge=True)` | Gray stroke, never colored |
| Label only (no node) | `text(...)` / `multiline_text(...)` | `role="label"` |

> **Gaps vs. draw.io**: there is no native parallelogram, ellipse, ER `table` container, or UML lifeline shape. Approximate per the notes above (I/O → hexagon; terminator → circle/stadium; ER table → `rect` container with child `rect` rows; lifeline → `rect` header + dashed `line`). Keep approximations consistent *within* a diagram.

---

## Architecture (system / cloud / service)

The default type and the one this skill is tuned for (see `evals/`).

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Tier / layer (Client / API / Service / Data) | `rect(role="layer", fill="#F7F7F7", stroke="#CCCCCC")` | Full-width band; gutter ≥20px inside |
| Service / module | `rect(node_id=…, fill=S-tier, stroke=unified)` | Op cards stay white in S1 |
| Database | `database(node_id=…, fill=S-tier)` | Green tier in S3 |
| Queue / bus / message broker (hub) | `hexagon(node_id=…, fill="#FFF2CC", stroke="#D6B656")` | **Place at the geometric center** of its clients |
| Gateway / load balancer | `hexagon(node_id=…, fill=S-tier)` | Orange tier in S3 |
| External system / 3rd-party API | `component(node_id=…, extra='stroke-dasharray="6,3"', fill="#F5F5F5", stroke="#666666")` | Dashed border = outside your boundary |
| Sync call | `connect(a, side, b, side, marker_end="arrowhead")` | Solid |
| Async / event | `connect(…, dashed=True)` | Dashed |

**Layout**: TB by default; switch to LR only when there are ≤3 tiers and the flow reads left→right. Hub nodes (queue/gateway) sit on the center column; clients radiate symmetrically so edges enter from different sides (zero crossings). Tier gap ≥40px; same-tier node gap ≥30px. Wrap each tier in a layer rect.

## Flowchart

> **Role palette**: the fills below are a self-contained, evaluator-verified
> palette where **color = flowchart role** (green = start/end, blue = process,
> yellow = decision, orange = I/O, purple = subprocess). It is an alternative
> to S1–S4, NOT a tier of them — pick it *or* an S-scheme and stay in one.

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Start / End | `circle(node_id=…, r=20, fill="#D5E8D4", stroke="#82B366")` | Green terminator |
| Process / step | `rect(node_id=…, fill="#DAE8FC", stroke="#6C8EBF")` | Blue rectangle |
| Decision | `decision(node_id=…, fill="#FFF2CC", stroke="#D6B656")` | Yellow diamond |
| I/O (data in/out) | `hexagon(node_id=…, fill="#FFE6CC", stroke="#D79B00")` | Orange (parallelogram substitute) |
| Subprocess | `rect(node_id=…, fill="#E1D5E7", stroke="#9673A6")` + double border (draw a 2nd inset rect) | Purple |
| Yes / No branch labels | `text(...)` on the decision edges | Always label both branches |

**Layout**: TB; ~200px vertical gap between steps. Decision branches go LR, then merge back to the center column. Keep the main spine on a single x; branches are short detours, not parallel columns.

## ML / Deep Learning model

Ideal for paper figures (NeurIPS/ICML style). Leverages `formula()` for tensor shapes.

> **Role palette**: the fills below are a self-contained, evaluator-verified
> palette where **color = layer type** (green = I/O, blue = conv/pool, purple =
> attention, yellow = recurrent, orange = linear, red = loss/activation). It
> is an alternative to S1–S4, NOT a tier of them — pick it *or* an S-scheme
> (e.g. S4 when one layer is the focal "hero") and stay in one.

| Element | Primitive | Fill (by layer type) |
| :--- | :--- | :--- |
| Layer block | `rect(node_id=…)` | Input/Output → `#D5E8D4`/`#82B366`; Conv/Pool → `#DAE8FC`/`#6C8EBF`; Attention/Transformer → `#E1D5E7`/`#9673A6`; RNN/LSTM/GRU → `#FFF2CC`/`#D6B656`; FC/Linear → `#FFE6CC`/`#D79B00`; Loss/Activation → `#F8CECC`/`#B85450` |
| Tensor shape annotation | `multiline_text(...)` 2nd line, or `formula(...)` | `(B, C, H, W)` or `(B, T, D)` as the label's 2nd line |
| Skip / residual connection | `connect(…, as_curve=True, dashed=True)` | Curved dashed arrow bypassing layers |
| Encoder / Decoder group | `rect(role="layer", …)` | Swimlane-style container around each stack |

**Layout**: TB (data flows top→bottom); ~150px between layers. Stack layers on the center x; skip connections curve out to the side and back. Group encoder/decoder in layer rects. Annotate every layer with its tensor shape — this is the whole point of an ML diagram.

## ER (Entity-Relationship)

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Table (entity) | `rect(role="layer", node_id=…, fill="#D5E1EB", stroke="#1B3A5C")` | Container (S1 L1 blue); header row is the table name |
| Column row | `rect(...)` child inside the table | One per column; PK row in `weight="bold"` |
| PK marker | `text("PK", weight="bold")` prefix or `text("🔑")` | Prefix the column label |
| FK relationship | `connect(…, dashed=True)` | Dashed; label with the FK column |

**Layout**: TB; ~300px between tables. Vertically stack related tables (parent above children) so FK edges read top→bottom and don't cross. No native crow's-foot — use a plain dashed arrow with the FK column as the label.

## Sequence (interaction)

The hardest to hand-place; prefer this only when the interaction *order* is the message.

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Actor / participant (lifeline header) | `rect(node_id=…, fill=S-tier)` at top | Box at the top of each column |
| Lifeline (dashed vertical) | `line(…, dashed=True, role="decoration")` | From header straight down |
| Activation bar | `rect(fill=S-tier, role="decoration")` | Narrow rect overlaid on the lifeline |
| Sync message | `connect(a, "bottom"/side, b, …, marker_end="arrowhead")` | Solid arrow between lifelines |
| Async message | `connect(…, dashed=True)` | Dashed |
| Return message | `connect(…, dashed=True, stroke="#999999")` | Grey dashed |

**Layout**: participants on a horizontal row, ~200px apart (LR). Time flows top→bottom; each message sits on its own y row, ~50px apart. Activation bars span the rows where that participant is "active". Messages are short horizontal segments between adjacent lifelines — avoid long diagonals.

## Swimlane (cross-functional)

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Pool (whole process) | `rect(role="layer", fill="#F7F7F7", stroke="#CCCCCC")` | Outer container |
| Lane (one role / team) | `rect(role="layer", fill=lane-tint, dashed=False)` | Child of pool; one per actor |
| Steps | Flowchart primitives (Start/Process/Decision/IO) | Each step's center sits inside its lane |
| Handoff (cross-lane edge) | `connect(…)` | Edges crossing a lane boundary *are* the handoffs — the diagram's point |

**Layout**: LR flow inside horizontal lanes; ≥160px horizontal step gap. Each lane is a full-height vertical slice of the pool; keep every step inside its actor's lane. Time flows left→right.

## Network topology

| Element | Primitive | Notes |
| :--- | :--- | :--- |
| Router / Switch / Firewall / LB | `component(node_id=…, fill=S3-tier)` | Tabbed box; type in the label |
| Server / compute | `rect(node_id=…, fill=S3-compute)` | |
| Storage / NAS | `database(node_id=…, fill=S3-storage)` | |
| Internet / WAN | `cloud(node_id=…, fill="#FFFFFF", stroke="#6881B3")` | |
| Zone (subnet / VLAN / DMZ) | `rect(role="layer", dashed=True, fill="#F5F5F5", stroke="#666666")` | Container; label = CIDR / zone name |
| Physical link | `connect(…, stroke_width=2)` | Plain; label = interface / VLAN |
| Logical / VPN link | `connect(…, dashed=True)` | Dashed |

**Layout**: TB by tier — Internet → edge (router/firewall) → distribution (switch/LB) → access (servers/clients). Wrap each subnet in a dashed zone container labelled with its CIDR. Label links with port/VLAN so the topology is self-documenting.

---

## Layout value cheatsheet (all types, evaluator-tuned)

These are the per-type spacing defaults. They all satisfy the evaluator floors (container gutter ≥20px, same-kind node spacing ≥14px); use them unless the diagram is crowded, then spread further.

| Type | Direction | Node gap (same row) | Tier/step gap (between rows) | Hub placement |
| :--- | :--- | :--- | :--- | :--- |
| Architecture | TB (≥4 tiers) / LR | 30px | 40px | center column, clients symmetric |
| Flowchart | TB | 40px | 200px | — |
| ML / DL | TB | 30px | 150px | — |
| ER | TB | — | 300px (table→table) | — |
| Sequence | LR × TB(time) | 200px (lifeline→lifeline) | 50px (msg→msg) | — |
| Swimlane | LR | 160px (step→step) | lane height | — |
| Network | TB | 30px | 40px | Internet at top center |

## Evaluator constraints to keep in mind

- **Font tiers**: 3–4 per diagram, adjacent tiers ≥1.15× apart (e.g. 20 / 14 / 12 / 10). Header / node-label / annotation / tensor-shape is a natural 4-tier split.
- **Palette**: ≤8 accents. Pick one palette — an S1–S4 scheme OR a type's self-contained role palette (see Flowchart / ML above) — and stay in it; don't mix colors from different palettes.
- **Containers**: nodes fully inside a layer rect need ≥20px gutter on every side.
- **Edges**: gray (`#4D4D4D`), never colored; arrowheads via `marker_end="arrowhead"`.
- **Hubs** (queue/gateway/broker): if multiple clients connect to one, fan them around it so edges enter from different sides — a single-side fan stack triggers the evaluator's bend/stretch warnings.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/references/gen_template.md
size: 3137
sha: 82b2eccf17457120d26a069932d580d0329e11d8
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/references/gen_template.md

````text
# gen.py Skeleton — copy this shape, fill in your architecture

The fixed parts (path resolution, brief, evaluation, export) never change;
only the constants block and the drawing section are yours. Following this
shape avoids re-deriving the boilerplate and the known first-run failures
(missing brief, wrong save order, deep-literal bracket slips).

```python
#!/usr/bin/env python3
"""<Arch name> — <one-line summary of the design>."""
import os, sys

_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, ".pi/skills/architecture-drawer/scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)

from svg_utils import SVGDrawer, save_svg, rasterize_svg, layout_grid, layout_row, layout_band
from design_brief import DesignBrief
from evaluator import evaluate_svg, auto_refine
from semantic_qa import run_semantic_qa
from svg2pptx import svg_to_pptx

# ---- Step 1: design brief tokens (named constants, never deep literals) ----
W, H = 1280, 860
TITLE = "<Arch name>"
NODE_IDS = ["src", "queue", "engine", "sink"]      # primary nodes
BANDS = [("layer_a", "Layer A", 120), ("layer_b", "Layer B", 300)]  # (id, label, y)
FLOW = ("src", "queue", "engine", "sink")           # flow_chain stages
PALETTE_ROLE = {                                    # data-node-id -> (fill, stroke)
    "layer_a": ("#D5E1EB", "#1B3A5C"),
}
BRIEF = DesignBrief(scheme="S1 monochrome", layout="band", flow="left-right",
                    palette_role=PALETTE_ROLE, flow_chain=FLOW)

d = SVGDrawer(width=W, height=H)
# title
d.text(W / 2, 36, TITLE, font_size=20, weight="bold")

# ---- Step 2: draw (state the array; helpers do the arithmetic) ----
for bid, label, by in BANDS:
    d.rect(60, by, W - 120, 160, fill="#F5F7FA", stroke="#1B3A5C",
           node_id=bid, node_kind="layer", role="layer")
    d.text(76, by + 24, label, font_size=14, weight="bold")
    bx, byy, bw, bh = layout_band(label, 60, by, W - 120, 160)
    for (x, y), nid in zip(layout_grid(4, bx, byy, 4, 120, 40, 24, 0), NODE_IDS):
        d.rect(x, y, 120, 40, fill="white", stroke="#1B3A5C", node_id=nid)

for a, b in zip(FLOW, FLOW[1:]):
    d.connect(a, "right", b, "left", stroke="#1B3A5C", marker_end="arrowhead")

# ---- Step 3: evaluate -> bounded repair -> export (fixed shape) ----
score, report = evaluate_svg(d)
print(f"Score: {score}")
if score < 100:
    score2, report2, fixes = auto_refine(d)
    print(f"After auto_refine: {score2}  (fixes: {fixes})")

qa = run_semantic_qa(d, expected_size=(W, H), brief=BRIEF)
save_svg(d.render(), "diagram.svg")
rasterize_svg("diagram.svg", "diagram.png", W)
svg_to_pptx("diagram.svg", "diagram.pptx")
BRIEF.write("brief.json")
```

Notes:
- The `BANDS` / `NODE_IDS` / `FLOW` constants pattern replaces inline nested
  literals — bracket mismatches in 5-deep tuples cost real repair rounds.
- Run `python3 gen.py` after every drawing change; read the report lines and
  fix exactly what they name (see `checks_cheatsheet.md`).
- Canvas/positions are approximate at first write — the evaluator is the
  oracle; do not hand-verify all 16 checks before the first run.
````

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/brief.json
size: 705
sha: 3c1cbcd25c665fe5272bc940b6120f11b66a8b88
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/brief.json

```text
{
  "scheme": "S2",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [],
  "palette_role": {
    "graph_opt": {
      "fill": "#fcfcfc",
      "stroke": "#9673a6"
    },
    "runtime_sched": {
      "fill": "#fcfcfc",
      "stroke": "#2e5aac"
    },
    "hw_concurrency": {
      "fill": "#fcfcfc",
      "stroke": "#b45f06"
    },
    "mem_pool": {
      "fill": "#fcfcfc",
      "stroke": "#d6b656"
    },
    "sched": {
      "fill": "#dae8fc",
      "stroke": "#2e5aac"
    },
    "s0": {
      "fill": "#dae8fc",
      "stroke": "#2e5aac"
    },
    "s1": {
      "fill": "#ffcc99",
      "stroke": "#b45f06"
    },
    "s2": {
      "fill": "#d5e8d4",
      "stroke": "#82b366"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/gen.py
size: 16757
sha: 3b72e85ed32c8206af37c147303f4ee00b68cfd7
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/gen.py

```text
# -*- coding: utf-8 -*-
"""MLIR AI Compiler · Multi-Stream Execution Pipeline (4-layer matrix diagram)."""
import sys, math, html
from pathlib import Path

import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
from svg_utils import SVGDrawer, save_svg, rasterize_svg, BBox
from evaluator import evaluate_svg
from design_brief import DesignBrief, ColorSpec
from semantic_qa import run_semantic_qa

# Script co-located with its SVG/PNG/PPTX in this dir (output/<ts>_<name>/).
NAME = "mlir_pipeline"
OUT = Path(__file__).resolve().parent

W, H = 1440, 1200
d = SVGDrawer(W, H, bg="#F7F7F7")
esc = html.escape

# ---- palette: exactly 8 accents (5 dark strokes + 3 light fills) ----
PURPLE = "#9673A6"; BLUE = "#2E5AAC"; ORANGE = "#B45F06"
GREEN = "#82B366"; YELLOW = "#D6B656"
ORANGE_F = "#FFCC99"; GREEN_F = "#D5E8D4"; BLUE_F = "#DAE8FC"
GRAY_S = "#888888"; GRAY_D = "#555555"; GRAY_L = "#BBBBBB"

def txt(x, y, s, sz=12, fill="#222222", anchor="middle", weight="normal"):
    d.add_element(
        f'<text x="{x}" y="{y}" font-family="Arial, sans-serif" font-size="{sz}" '
        f'fill="{fill}" text-anchor="{anchor}" font-weight="{weight}">{esc(s)}</text>')

def rrect(x, y, w, h, fill, stroke, sw=1.5, rx=8, ry=8, extra="", role=None, bbox=False):
    ra = f' data-graph-role="{role}"' if role else ""
    d.add_element(
        f'<rect x="{x}" y="{y}" width="{w}" height="{h}" rx="{rx}" ry="{ry}" '
        f'fill="{fill}" stroke="{stroke}" stroke-width="{sw}"{ra} {extra}/>',
        BBox(x, y, w, h) if bbox else None)

def _tw(s, fs, bold=False):
    # text width estimate, matching evaluator's metric (0.55 regular / 0.62 bold, CJK x1)
    coef = 0.62 if bold else 0.55
    return sum(fs * (1.0 if ord(c) > 0x2E80 else coef) for c in s)

def card(x, y, w, title, body, stroke, h=None, pad=12, body_fs=10, title_fs=12):
    """White legend card; body auto-wraps to fit width, height auto-grows."""
    inner = w - 2 * pad
    words = body.split(' ')
    lines, cur = [], ''
    for wd in words:
        trial = wd if not cur else cur + ' ' + wd
        if _tw(trial, body_fs) <= inner or not cur:
            cur = trial
        else:
            lines.append(cur); cur = wd
    if cur:
        lines.append(cur)
    title_h = title_fs + 8
    line_h = body_fs * 1.35
    total = pad + title_h + len(lines) * line_h + pad
    if h:
        total = max(total, h)
    rrect(x, y, w, total, "#FFFFFF", stroke, 1.4, 8, role="legend")
    txt(x + pad, y + pad + title_fs - 1, title, title_fs, stroke, "start", "bold")
    for i, ln in enumerate(lines):
        txt(x + pad, y + pad + title_h + i * line_h + body_fs - 1, ln, body_fs, GRAY_D, "start")
    return total

# ---- arrow markers (colors reused from the 8-accent set + neutral) ----
d.arrow_head("ah", GRAY_S, 10, 7, 9, 3.5)
d.arrow_head("ap", PURPLE)
d.arrow_head("ab", BLUE)
d.arrow_head("ao", ORANGE)
d.arrow_head("ag", GREEN)

# =================== TITLE ===================
txt(W / 2, 34, "MLIR AI Compiler · Multi-Stream Execution Pipeline", 20, "#1a1a1a", "middle", "bold")
txt(W / 2, 54, "Static Graph Optimization → Runtime Scheduling → Hardware Concurrency → Memory Reuse",
    12, GRAY_D, "middle")

# =================== BAND 1 : GRAPH OPTIMIZATION ===================
rrect(50, 64, 1340, 266, "#FCFCFC", PURPLE, 2, 12,
      extra='data-node-id="graph_opt"', role="layer")
txt(72, 92, "Graph Optimization — Compile-time · Static DAG & Fusion", 14, PURPLE, "start", "bold")
txt(72, 110, "Operator fusion · algebraic reordering · parallel-branch detection", 12, GRAY_D, "start")

# fusion dashed box
rrect(76, 140, 482, 110, "none", PURPLE, 1.5, 8, extra='stroke-dasharray="7,4" ', role="decoration")
txt(86, 158, "Vertical Fusion · 3 Kernels → 1", 12, PURPLE, "start", "bold")

# DAG op nodes (white fill, colored stroke)
def opnode(nid, x, y, w, h, top, sub, stroke):
    d.rect(x, y, w, h, rx=6, ry=6, fill="#FFFFFF", stroke=stroke, stroke_width=1.6,
           node_id=nid, node_kind="op", bbox=True)
    txt(x + w / 2, y + 20, top, 12, "#222222", "middle", "bold")
    txt(x + w / 2, y + 36, sub, 10, GRAY_D, "middle")

opnode("opA", 96, 178, 100, 52, "A · Conv", "Conv2D", PURPLE)
opnode("opB", 246, 178, 100, 52, "B · BN", "BatchNorm", PURPLE)
opnode("opC", 396, 178, 100, 52, "C · ReLU", "ReLU", PURPLE)
opnode("opD", 612, 178, 100, 52, "D · Add", "elementwise", BLUE)
opnode("opPar", 558, 268, 130, 40, "Parallel Branch", "no data dep", BLUE)

# chain edges
d.connect("opA", "right", "opB", "left", stroke=PURPLE, stroke_width=1.6, marker_end="ap")
d.connect("opB", "right", "opC", "left", stroke=PURPLE, stroke_width=1.6, marker_end="ap")
d.connect("opC", "right", "opD", "left", stroke=GRAY_S, stroke_width=1.6, marker_end="ah")
# parallel branch feeds D's second input (dashed)
d.connect("opPar", "top", "opD", "bottom", stroke=BLUE, stroke_width=1.5, marker_end="ab",
          dashed=True)
txt(690, 262, "③ Stream Concurrency", 10, BLUE, "start", "bold")

# reorder swap indicator (decorative curved double-arrow above C-D)
d.add_element(
    f'<path d="M446,168 C500,140 612,140 662,168" fill="none" stroke="{PURPLE}" '
    f'stroke-width="1.4" stroke-dasharray="5,3" marker-end="url(#ap)" '
    f'data-graph-role="decoration"/>')
txt(530, 132, "② Reorder D↔C (commutativity)", 10, PURPLE, "middle", "bold")

# right annotation cards (legend)
h1 = card(870, 140, 250, "① Vertical Fusion",
     "Conv+BN+ReLU → 1 fused kernel; ↓ global mem R/W (cf. FlashAttention, Fused GEMV)", PURPLE)
h2 = card(1140, 140, 240, "② Reordering",
     "Algebraic simplification / commutativity → eliminate intermediate buffer storage", BLUE)
card(870, 140 + max(h1, h2) + 14, 510, "③ Parallel Branch Detection",
     "Data-independent branches tagged as stream-concurrency candidates → overlapped at runtime", GREEN)

# fused-kernel output badge (under the fusion box, away from the opPar→opD edge)
rrect(200, 258, 160, 42, ORANGE_F, ORANGE, 1.4, 6, role="legend")
txt(280, 277, "Fused Kernel K1", 12, ORANGE, "middle", "bold")
txt(280, 292, "Conv + BN + ReLU", 10, GRAY_D, "middle")
d.add_element(
    f'<line x1="290" y1="250" x2="290" y2="257" stroke="{ORANGE}" stroke-width="1.4" '
    f'marker-end="url(#ao)" data-graph-role="decoration"/>')
txt(298, 248, "fuses", 10, ORANGE, "start")

# =================== BAND 2 : RUNTIME SCHEDULING ===================
rrect(50, 340, 1340, 235, "#FCFCFC", BLUE, 2, 12,
      extra='data-node-id="runtime_sched"', role="layer")
txt(72, 368, "Runtime Scheduling — Async Launch · Priority · Load Balance", 14, BLUE, "start", "bold")
txt(72, 386, "Host launch / device-exec split · work stealing for dynamic shapes", 12, GRAY_D, "start")

# scheduler
d.rect(82, 408, 196, 116, rx=10, ry=10, fill=BLUE_F, stroke=BLUE, stroke_width=1.6,
       node_id="sched", node_kind="layer", bbox=True)
txt(180, 436, "Task Scheduler", 14, BLUE, "middle", "bold")
txt(180, 456, "Host (CPU)", 12, "#333333", "middle")
txt(180, 474, "Async Launch", 10, GRAY_D, "middle")
txt(180, 490, "dependency resolve", 10, GRAY_D, "middle")
txt(180, 506, "graph capture", 10, GRAY_D, "middle")

# streams
streams = [("s0", 420, "Stream 0 · Comm", "high priority", BLUE),
           ("s1", 478, "Stream 1 · Compute", "kernel queue", ORANGE),
           ("s2", 536, "Stream 2 · D2D Copy", "low priority", GREEN)]
for nid, y, lbl, sub, st in streams:
    fl = {BLUE: BLUE_F, ORANGE: ORANGE_F, GREEN: GREEN_F}[st]
    d.rect(360, y, 214, 42, rx=6, ry=6, fill=fl, stroke=st, stroke_width=1.5,
           node_id=nid, node_kind="op", bbox=True)
    txt(467, y + 18, lbl, 12, "#222222", "middle", "bold")
    txt(467, y + 33, sub, 10, GRAY_D, "middle")
    d.connect("sched", "right", nid, "left", stroke=BLUE, stroke_width=1.4, marker_end="ab")

# queued task chips (decorative)
chip_sets = [(420, ["T", "T", "T"], BLUE),
             (478, ["K1", "K2", "K3"], ORANGE),
             (536, ["cp", "cp", "cp"], GREEN)]
for y, labs, st in chip_sets:
    for i, lb in enumerate(labs):
        cx = 600 + i * 42
        rrect(cx, y + 9, 36, 24, "#FFFFFF", st, 1.1, 4, role="legend")
        txt(cx + 18, y + 25, lb, 10, st, "middle", "bold")

txt(745, 470, "device-side queues", 10, GRAY_D, "start")
d.add_element(
    f'<path d="M738,446 C770,446 770,500 738,500" fill="none" stroke="{GRAY_S}" '
    f'stroke-width="1.2" stroke-dasharray="4,3" data-graph-role="decoration"/>')

h1 = card(870, 398, 510, "Async Launch · Priority Preemption · Work Stealing",
     "Host enqueues kernels non-blocking; high-prio comm stream preempts; idle SMs steal tasks under dynamic shapes",
     BLUE)
card(870, 398 + h1 + 12, 510, "Back-pressure & Amortization",
     "Device queues throttle host when saturated; CUDA-graph capture amortizes per-kernel launch overhead", GRAY_S)

# =================== BAND 3 : HARDWARE CONCURRENCY ===================
rrect(50, 585, 1340, 340, "#FCFCFC", ORANGE, 2, 12,
      extra='data-node-id="hw_concurrency"', role="layer")
txt(72, 613, "Hardware Concurrency — Multi-Stream Overlap · SM Partition", 14, ORANGE, "start", "bold")
txt(72, 631, "GPU SM array · timeline swimlanes · MPS / MIG spatial multiplexing", 12, GRAY_D, "start")

# GPU chip
rrect(70, 658, 214, 244, "#F2F2F2", GRAY_S, 1.4, 10, role="decoration", bbox=True)
txt(177, 681, "GPU · SM Array", 12, "#333333", "middle", "bold")
sm_x0, sm_y0, cell, sm = 88, 696, 42, 36
for r in range(4):
    for c in range(4):
        x, y = sm_x0 + c * cell, sm_y0 + r * cell
        if c < 2:
            fl, st = ORANGE_F, ORANGE
        elif c == 2:
            fl, st = GREEN_F, GREEN
        else:
            fl, st = BLUE_F, BLUE
        rrect(x, y, sm, sm, fl, st, 1, 2, role="decoration")
# MPS partition dividers (span the grid height)
for xx in [sm_x0 + 2 * cell - 4, sm_x0 + 3 * cell - 4]:
    d.add_element(
        f'<line x1="{xx}" y1="{sm_y0 - 4}" x2="{xx}" y2="{sm_y0 + 4 * cell - 4}" '
        f'stroke="{GRAY_D}" stroke-width="1" stroke-dasharray="3,2" data-graph-role="decoration"/>')
txt(128, 882, "compute", 10, ORANGE, "middle", "bold")
txt(191, 882, "copy", 10, GREEN, "middle", "bold")
txt(233, 882, "comm", 10, BLUE, "middle", "bold")
txt(177, 898, "MPS / MIG partition", 10, GRAY_D, "middle")

# time axis
AX0, AX1, AY = 320, 1370, 712
d.add_element(f'<line x1="{AX0}" y1="{AY}" x2="{AX1}" y2="{AY}" stroke="{GRAY_S}" stroke-width="1.4"/>')
for xx, lab in [(380, "T0"), (680, "T1"), (980, "T2"), (1280, "T3")]:
    d.add_element(f'<line x1="{xx}" y1="{AY-5}" x2="{xx}" y2="{AY+5}" stroke="{GRAY_S}" stroke-width="1.4"/>')
    txt(xx, AY + 19, lab, 10, GRAY_D, "middle")
txt(1342, AY - 6, "time →", 10, GRAY_S, "start")

# swimlanes
def lane_label(y, lbl, sub, st):
    txt(348, y + 16, lbl, 10, st, "end", "bold")
    txt(348, y + 30, sub, 10, GRAY_D, "end")

def bar(x, y, w, lbl, fl, st, big=False):
    rrect(x, y, w, 40, fl, st, 1.5, 5, role="decoration", bbox=True)
    txt(x + w / 2, y + 17, lbl, 12 if big else 10, "#222222", "middle", "bold")
    txt(x + w / 2, y + 31, "active" if big else "", 10, GRAY_D, "middle")

lane_label(732, "Compute", "(Tensor Core)", ORANGE)
bar(380, 736, 360, "Kernel A · MatMul", ORANGE_F, ORANGE, big=True)
bar(780, 736, 320, "Kernel B", ORANGE_F, ORANGE)
lane_label(786, "Copy D2D", "(layout xform)", GREEN)
bar(430, 790, 250, "NHWC→NCHW", GREEN_F, GREEN)
bar(820, 790, 230, "D2D copy", GREEN_F, GREEN)
lane_label(840, "Comm H2D", "(next batch)", BLUE)
bar(380, 844, 180, "H2D preload", BLUE_F, BLUE)
bar(720, 844, 220, "H2D preload", BLUE_F, BLUE)
bar(1080, 844, 220, "H2D preload", BLUE_F, BLUE)

# overlap region guides
for xx in [430, 680]:
    d.add_element(
        f'<line x1="{xx}" y1="730" x2="{xx}" y2="886" stroke="{ORANGE}" '
        f'stroke-width="1" stroke-dasharray="3,3" data-graph-role="decoration"/>')
txt(555, 902, "↕ fully concurrent · Multi-Stream Overlap", 10, ORANGE, "middle", "bold")

# =================== BAND 4 : MEMORY POOL ===================
rrect(50, 935, 1340, 235, "#FCFCFC", YELLOW, 2, 12,
      extra='data-node-id="mem_pool"', role="layer")
txt(72, 963, "Memory Pool — Lifetime · In-place · Workspace Reuse", 14, YELLOW, "start", "bold")
txt(72, 981, "Ring buffer · producer→consumer L2 locality", 12, GRAY_D, "start")

# ring buffer
cx, cy, R = 188, 1062, 56
segs = [(0, 90, YELLOW), (90, 180, ORANGE), (180, 270, GREEN), (270, 360, BLUE)]
for a0, a1, st in segs:
    x1 = cx + R * math.cos(math.radians(a0)); y1 = cy + R * math.sin(math.radians(a0))
    x2 = cx + R * math.cos(math.radians(a1)); y2 = cy + R * math.sin(math.radians(a1))
    d.add_element(
        f'<path d="M{x1:.1f},{y1:.1f} A{R},{R} 0 0 1 {x2:.1f},{y2:.1f}" fill="none" '
        f'stroke="{st}" stroke-width="15" data-graph-role="decoration"/>')
txt(cx, cy - 2, "Memory Pool", 12, "#333333", "middle", "bold")
txt(cx, cy + 15, "Ring Buffer", 10, GRAY_D, "middle")
# rotation arrow
d.add_element(
    f'<path d="M{cx + R + 4},{cy - 14} A{R + 14},{R + 14} 0 0 1 {cx + R + 4},{cy + 14}" '
    f'fill="none" stroke="{GRAY_S}" stroke-width="1.4" marker-end="url(#ah)" '
    f'data-graph-role="decoration"/>')

h_i = card(330, 988, 330, "In-place Update",
     "Add / ReLU overwrite the input buffer → zero extra allocation", YELLOW)
h_w = card(690, 988, 330, "Workspace Reuse",
     "Operators share one scratch buffer → ↓ allocation overhead", ORANGE)
h_p = card(1050, 988, 330, "Producer→Consumer Locality",
     "Next kernel consumes output while still warm in L2 cache", GREEN)
ht = max(h_i, h_w, h_p)
# arrows ring -> cards (decorative)
for ex in [330, 690, 1050]:
    d.add_element(
        f'<line x1="{cx + R}" y1="{cy}" x2="{ex}" y2="1018" stroke="{GRAY_L}" '
        f'stroke-width="1" stroke-dasharray="3,3" data-graph-role="decoration"/>')
card(330, 988 + ht + 12, 1050, "Buffer Lifetime Timeline",
     "t0 alloc K1 → t1 in-place ReLU → t2 workspace reused by K2 → t3 free   (ring arcs = ownership)", GRAY_S)

# =================== LEFT PIPELINE SPINE (drawn LAST → sits above bands, never occluded) ===================
SPX = 26
d.add_element(
    f'<line x1="{SPX}" y1="80" x2="{SPX}" y2="1156" stroke="{GRAY_L}" stroke-width="2" '
    f'stroke-dasharray="4,4" data-graph-role="decoration"/>')
for num, yy in [("1", 165), ("2", 457), ("3", 755), ("4", 1052)]:
    d.add_element(
        f'<circle cx="{SPX}" cy="{yy}" r="13" fill="#FFFFFF" stroke="{GRAY_S}" '
        f'stroke-width="1.5" data-graph-role="decoration"/>')
    txt(SPX, yy + 4, num, 12, GRAY_D, "middle", "bold")
# verbs sit inside the band gutters (330-340 / 575-585 / 925-935) so they clear every band
for yy, vb in [(330, "lowers"), (575, "dispatches"), (925, "reclaims")]:
    d.add_element(
        f'<polygon points="{SPX-5},{yy} {SPX+5},{yy} {SPX},{yy+9}" fill="{GRAY_S}" '
        f'data-graph-role="decoration"/>')
    txt(SPX + 16, yy + 7, vb, 10, GRAY_S, "start")

# =================== DESIGN BRIEF (Step 1) ===================
# Declared from input.md's matrix intent: 4 horizontal layer bands (the
# matrix rows) stacking top -> bottom, one hue per concern (graph ops /
# scheduling / hardware / memory) — S2 categorical semantics. The bands are
# palette members; the intra-band tinted containers (task scheduler + the
# three device streams) are members too. flow_chain stays empty: the numbered
# spine and gutter verbs linking the bands are decorative annotations, and no
# business edge crosses a band boundary, so no chain is assertable.
BRIEF = DesignBrief(
    scheme="S2",
    layout="band",
    flow="top-down",
    palette_role={
        "graph_opt":       ColorSpec("#FCFCFC", PURPLE),
        "runtime_sched":   ColorSpec("#FCFCFC", BLUE),
        "hw_concurrency":  ColorSpec("#FCFCFC", ORANGE),
        "mem_pool":        ColorSpec("#FCFCFC", YELLOW),
        "sched":           ColorSpec(BLUE_F, BLUE),
        "s0":              ColorSpec(BLUE_F, BLUE),
        "s1":              ColorSpec(ORANGE_F, ORANGE),
        "s2":              ColorSpec(GREEN_F, GREEN),
    },
    flow_chain=(),
)

# =================== EVALUATE & SAVE ===================
score, report = evaluate_svg(d, conn_tolerance=12.0)
print(f"Score: {score}")
for line in report:
    print(line)
qa = run_semantic_qa(d, expected_size=(W, H), brief=BRIEF)
print("Semantic QA:")
for line in qa.report():
    print(line)
svg_path = OUT / f"{NAME}.svg"
png_path = OUT / f"{NAME}.png"
pptx_path = OUT / f"{NAME}.pptx"
save_svg(d.render(), str(svg_path))
rasterize_svg(svg_path, png_path, W)
from svg2pptx import svg_to_pptx
svg_to_pptx(str(svg_path), str(pptx_path))
BRIEF.write(str(OUT / "brief.json"))
print(f"Saved triplet -> {OUT}")
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/input.md
size: 2543
sha: e8eea82a63c984f249dff3203d2e464951253403
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_120000_mlir_pipeline/input.md

```text
# MLIR AI Compiler — Multi-Stream Execution Pipeline

Draw a 4-layer MATRIX diagram of an AI-compiler runtime pipeline. Four
horizontal layer bands stack top → bottom (the matrix rows); within each band
stages and streams read left → right (the matrix columns). A vertical numbered
spine on the far left links the four bands into one downward flow.

## Structure

A matrix grid: 4 horizontal layers (top → bottom) × multiple stage columns
(left → right). Data and execution flow left → right inside every band.

### Layer 1 — Graph Optimization (compile-time · static DAG & fusion)
- Operator fusion, algebraic reordering, parallel-branch detection.
- A 3-node DAG (**Conv** → **BatchNorm** → **ReLU**) feeding an **Add** node; a
  parallel branch (no data dependency) feeds Add's second input.
- Vertical-fusion group drawn as a dashed box around Conv+BN+ReLU → fused into
  one kernel **K1**. A curved reorder-swap arc marks a commutative D↔C swap.

### Layer 2 — Runtime Scheduling (async launch · priority · load balance)
- A host-side **Task Scheduler** (CPU) fans out to three device streams:
  **Stream 0** · Comm (high priority), **Stream 1** · Compute (kernel queue),
  **Stream 2** · D2D Copy (low priority).
- Each stream owns a device-side queue of small task chips (T / K / cp).

### Layer 3 — Hardware Concurrency (multi-stream overlap · SM partition)
- A GPU **SM array** (4×4 grid) partitioned into MPS/MIG zones: compute, copy,
  comm.
- A horizontal time axis (T0→T3) with three swimlanes — Compute (Tensor Core),
  Copy D2D (layout xform), Comm H2D (next batch) — whose bars overlap in time.

### Layer 4 — Memory Pool (lifetime · in-place · workspace reuse)
- A 4-quadrant ring buffer (**Memory Pool**) whose colored arcs encode
  ownership.
- Three reuse-strategy cards: **In-place Update**, **Workspace Reuse**,
  **Producer→Consumer (L2) Locality**; a full-width **Buffer Lifetime
  Timeline** below.

### Cross-cutting
- Far-left dashed vertical spine with numbered circles 1–4 marking the bands;
  downward-triangle verbs in the band gutters: "lowers", "dispatches",
  "reclaims".
- Right-edge annotation cards in every band explain each stage's technique.

Colors distinguish the pipeline's concerns (graph ops, scheduling, hardware,
memory); keep the accent count within the skill's design-system budget. Layout,
palette, typography, and all geometry are yours to design — follow the
architecture-drawer skill's design system and let the evaluator guide
iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/brief.json
size: 887
sha: 111c8e7c50d4f87291fd4dffb769b92df97812cf
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/brief.json

```text
{
  "scheme": "S2",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [
    "L1",
    "L2",
    "L3",
    "L4",
    "L5"
  ],
  "palette_role": {
    "L1": {
      "fill": "#f2f2f2",
      "stroke": "#b0b0b0"
    },
    "L2": {
      "fill": "#f2f2f2",
      "stroke": "#b0b0b0"
    },
    "L3": {
      "fill": "#f2f2f2",
      "stroke": "#b0b0b0"
    },
    "L4": {
      "fill": "#f2f2f2",
      "stroke": "#b0b0b0"
    },
    "L5": {
      "fill": "#f2f2f2",
      "stroke": "#b0b0b0"
    },
    "memory_ctx": {
      "fill": "#b2e2e2",
      "stroke": "#333333"
    },
    "tools_gw": {
      "fill": "#ffe0b2",
      "stroke": "#333333"
    },
    "exec_engine": {
      "fill": "#c5e1a5",
      "stroke": "#333333"
    },
    "sandbox": {
      "fill": "#fff59d",
      "stroke": "#333333"
    },
    "SEC": {
      "fill": "#ef9a9a",
      "stroke": "#333333"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/gen.py
size: 12093
sha: 255a39d6f9828b91d8b1c7e469ca112f9d6c4a6b
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/gen.py

```text
"""Agent Infra layered architecture diagram generator.

Layout: 5 horizontal layers (Application -> Orchestration -> Core Capabilities ->
Execution & Environment -> Infrastructure) with the 5 core modules colored, and a
"Security & Observability" band spanning all layers on the right (cross-cutting).

Output: agent_infra_architecture.svg
"""
from pathlib import Path
import sys

import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
from svg_utils import SVGDrawer, save_svg, rasterize_svg
from evaluator import evaluate_svg
from design_brief import DesignBrief, ColorSpec
from semantic_qa import run_semantic_qa

# Script co-located with its SVG/PNG/PPTX in this dir (output/<ts>_<name>/).
# Re-run refreshes the triplet in place.
NAME = "agent_infra_architecture"
OUT = Path(__file__).resolve().parent

# ---------------------------------------------------------------------------
# Design tokens
# ---------------------------------------------------------------------------
W, H = 1280, 900

# Stack (left) + cross-cutting band (right)
SX0, SW = 30, 860          # stack x-range 30..890
SX1 = SX0 + SW             # 890
BX0, BW = 910, 330         # band x-range 910..1240

# Structural colors are PURE grays (R==G==B) so the validator treats them as
# neutral and does NOT count them as accents -> palette stays at the 5 module fills.
INK = "#333333"            # primary text / module borders
SUB = "#666666"            # secondary text
NEU_FILL = "#F2F2F2"       # neutral layer fill
NEU_STROKE = "#B0B0B0"     # neutral layer border
CARD_FILL = "#FFFFFF"
CARD_STROKE = "#BEBEBE"
EDGE = "#555555"           # connectors (pure gray)

# 5 core-module accent FILLS only (borders stay neutral gray -> 5 accents total)
C_MEM = "#B2E2E2"     # Memory & Context  (teal)
C_TOOL = "#FFE0B2"    # Tools & Gateway   (orange)
C_EXEC = "#C5E1A5"    # Execution Engine  (green)
C_SAND = "#FFF59D"    # Environment/Sandbox(yellow)
C_SEC = "#EF9A9A"     # Security band     (coral)

# Font tiers (<=4 distinct, adjacent ratio >=1.15): 22 / 14 / 11 / 9
F_TITLE, F_HEAD, F_LABEL, F_NOTE = 22, 14, 11, 9

drawer = SVGDrawer(W, H, bg="#FFFFFF")
drawer.arrow_head("arrow", EDGE, marker_width=10, marker_height=8, ref_x=9, ref_y=4)

def head_two(x, y_cn, y_en, cn, en, fill=INK, weight="bold", anchor="middle"):
    drawer.text(x, y_cn, cn, F_HEAD, fill=fill, anchor=anchor, weight=weight)
    if en:
        drawer.text(x, y_en, en, F_NOTE, fill=SUB, anchor=anchor)

def card(x, y, w, h, cn, en, fs_cn=F_LABEL, fs_en=F_NOTE):
    drawer.rect(x, y, w, h, rx=6, ry=6, fill=CARD_FILL, stroke=CARD_STROKE,
                stroke_width=1, bbox=True)
    if en:
        drawer.text(x + w / 2, y + h / 2 - fs_cn * 0.55, cn, fs_cn, fill=INK, anchor="middle")
        drawer.text(x + w / 2, y + h / 2 + fs_en * 0.75, en, fs_en, fill=SUB, anchor="middle")
    else:
        drawer.text(x + w / 2, y + h / 2, cn, fs_cn, fill=INK, anchor="middle")

def card_row(items, y, h, inner_x, inner_w, cn_fs=F_LABEL):
    n = len(items)
    gap = 14
    cw = (inner_w - gap * (n - 1)) / n
    for i, (cn, en) in enumerate(items):
        x = inner_x + i * (cw + gap)
        card(x, y, cw, h, cn, en, fs_cn=cn_fs)

def module(x, y, w, h, fill, cn, en, sub_items, nid=None):
    drawer.rect(x, y, w, h, rx=8, ry=8, fill=fill, stroke=INK, stroke_width=1.2, bbox=True,
                node_id=nid)
    head_two(x + w / 2, y + 22, y + 37, cn, en)
    pad = 12
    sub_y = y + 50
    sub_h = h - 50 - pad
    card_row(sub_items, sub_y, sub_h, x + pad, w - 2 * pad)

# ---------------------------------------------------------------------------
# Title
# ---------------------------------------------------------------------------
drawer.text(W / 2, 34, "Agent Infra 架构图", F_TITLE, fill=INK, anchor="middle", weight="bold")
drawer.text(W / 2, 58, "Agent Infrastructure  ·  分层架构 Layered Architecture",
            F_LABEL, fill=SUB, anchor="middle")

# ---------------------------------------------------------------------------
# Layer containers (neutral) + their nodes for inter-layer arrows.
# Each layer: header band (cn y+18 / en y+32), content starts at y+44.
# Inter-layer gaps = 20px so arrow segments stay >=16px after marker retraction.
# ---------------------------------------------------------------------------
inner_x, inner_w = SX0 + 18, SW - 36   # 48 .. 872  (width 824)
layers = [
    (90, 90, "应用层", "Application Layer", "L1"),
    (200, 92, "编排与治理层", "Orchestration & Governance", "L2"),
    (312, 188, "核心能力层", "Core Capabilities", "L3"),
    (520, 176, "执行与环境层", "Execution & Environment", "L4"),
    (716, 90, "基础设施层", "Infrastructure", "L5"),
]
for y, h, hcn, hen, nid in layers:
    drawer.rect(SX0, y, SW, h, rx=8, ry=8, fill=NEU_FILL, stroke=NEU_STROKE,
                stroke_width=1, node_id=nid, node_kind="layer", bbox=True)
    head_two(inner_x + 4, y + 18, y + 32, hcn, hen, anchor="start")

# L1 - Application (3 cards)
card_row([("Web 应用", "Web App"), ("REST / API", "Gateway"), ("CLI 工具", "CLI")],
         134, 46, inner_x, inner_w)
# L2 - Orchestration (4 cards)
card_row([("生命周期管理", "Lifecycle"), ("任务调度", "Scheduling"),
          ("多智能体协作", "Multi-Agent"), ("策略控制", "Policy")],
         244, 46, inner_x, inner_w)

# L3 - Core Capabilities: Memory & Context (teal) | Tools & Gateway (orange)
mW = 410
module(SX0 + 18, 356, mW, 132, C_MEM, "记忆与上下文", "Memory & Context",
       [("向量数据库", "Vector DB"), ("知识图谱", "Knowledge Graph"), ("RAG 检索", "Retrieval")],
       nid="memory_ctx")
module(SX0 + 18 + mW + 20, 356, mW, 132, C_TOOL, "工具与网关", "Tools & Gateway",
       [("MCP 协议", "MCP"), ("API 集成", "API Integration"), ("函数调用", "Function Call")],
       nid="tools_gw")

# L4 - Execution & Environment: Execution Engine (green) | Sandbox (yellow)
module(SX0 + 18, 564, mW, 120, C_EXEC, "执行引擎", "Execution Engine",
       [("高并发", "Concurrency"), ("秒级扩容", "Autoscale"), ("快速启动", "Fast Start")],
       nid="exec_engine")
module(SX0 + 18 + mW + 20, 564, mW, 120, C_SAND, "环境与沙箱", "Environment & Sandbox",
       [("代码执行", "Code Exec"), ("Serverless", "Elastic"), ("安全隔离", "Isolation")],
       nid="sandbox")

# L5 - Infrastructure (4 cards)
card_row([("计算", "Compute · GPU/CPU"), ("存储", "Storage"), ("网络", "Network"), ("K8s 编排", "Kubernetes")],
         760, 42, inner_x, inner_w)

# ---------------------------------------------------------------------------
# Security & Observability - cross-cutting band (spans full stack height)
# ---------------------------------------------------------------------------
BY0, BH = 90, 716     # 90..806, matches the layer stack
drawer.rect(BX0, BY0, BW, BH, rx=10, ry=10, fill=C_SEC, stroke=INK,
            stroke_width=1.2, node_id="SEC", node_kind="region", bbox=True)
drawer.text(BX0 + BW / 2, BY0 + 26, "安全与可观测", F_HEAD, fill=INK, anchor="middle", weight="bold")
drawer.text(BX0 + BW / 2, BY0 + 44, "Security & Observability", F_NOTE, fill=SUB, anchor="middle")
drawer.text(BX0 + BW / 2, BY0 + 60, "横向贯穿所有层 · Cross-cutting", F_NOTE, fill=SUB,
            anchor="middle", style="italic")

sec_items = [("身份认证", "Authentication"), ("数据加密", "Encryption"),
             ("行为审计", "Behavior Audit"), ("日志", "Logging"),
             ("监控", "Metrics"), ("链路追踪", "Tracing")]
s_y0, s_h, s_gap = 180, 92, 12
for i, (cn, en) in enumerate(sec_items):
    yy = s_y0 + i * (s_h + s_gap)
    card(BX0 + 14, yy, BW - 28, s_h, cn, en)

# ---------------------------------------------------------------------------
# Connectors
# ---------------------------------------------------------------------------
# 1) Vertical dependency flow between adjacent layers (stack centerline, x=460)
for a, b in [("L1", "L2"), ("L2", "L3"), ("L3", "L4"), ("L4", "L5")]:
    drawer.connect(a, "bottom", b, "top", stroke=EDGE, stroke_width=1.8, marker_end="arrow")

# 2) Cross-cutting dashed links: each layer's right edge -> band left edge
for y, h, _hcn, _hen, _nid in layers:
    cy = y + h / 2
    drawer.line(SX1, cy, BX0, cy, stroke=CARD_STROKE, stroke_width=1.2,
                register_edge=True, dashed="4,3")

# ---------------------------------------------------------------------------
# Legend
# ---------------------------------------------------------------------------
LY0 = 822
drawer.rect(SX0, LY0, SW, 60, rx=8, ry=8, fill=NEU_FILL, stroke=NEU_STROKE,
            stroke_width=1, bbox=True)
drawer.text(SX0 + 14, LY0 + 19, "图例 Legend", F_HEAD, fill=INK, anchor="start", weight="bold")

# item 1: core-module swatches
drawer.text(SX0 + 14, LY0 + 42, "核心模块 Core Modules", F_LABEL, fill=INK, anchor="start")
lx = SX0 + 14 + 158
for c in (C_MEM, C_TOOL, C_EXEC, C_SAND, C_SEC):
    drawer.rect(lx, LY0 + 35, 16, 14, rx=2, ry=2, fill=c, stroke=INK, stroke_width=0.8, bbox=False)
    lx += 22

# item 2: dependency arrow
i2 = SX0 + 470
drawer.line(i2, LY0 + 42, i2 + 34, LY0 + 42, stroke=EDGE, stroke_width=1.8, marker_end="arrow")
drawer.text(i2 + 44, LY0 + 42, "依赖 / 控制流", F_LABEL, fill=INK, anchor="start")

# item 3: dashed cross-cut
i3 = SX0 + 680
drawer.line(i3, LY0 + 42, i3 + 34, LY0 + 42, stroke=CARD_STROKE, stroke_width=1.2,
            dashed="4,3")
drawer.text(i3 + 44, LY0 + 42, "安全可观测横跨各层", F_LABEL, fill=INK, anchor="start")

# ---------------------------------------------------------------------------
# Design Brief (Step 1) — declared from input.md's intent: a 5-layer neutral
# stack (L1 应用层 -> L5 基础设施层) read top-down, the cross-cutting 安全与可观测
# band on the right, and the four core modules carrying distinct accent hues
# (S2 categorical; input.md delegates exact colors to the design system, which
# kept the stack itself neutral gray — declared here with its actual hex).
# The dependency spine links band BORDERS across the 20px gutters, and the
# marker-tip retraction pulls every line endpoint into the gutter, so no
# inter-layer edge attributes to the next band: an assertable chain would
# false-FAIL (same gutter-spine situation as the pi_agent / mlir evals).
# ---------------------------------------------------------------------------
BRIEF = DesignBrief(
    scheme="S2",
    layout="band",
    flow="top-down",
    palette_role={
        "L1":          ColorSpec(NEU_FILL, NEU_STROKE),
        "L2":          ColorSpec(NEU_FILL, NEU_STROKE),
        "L3":          ColorSpec(NEU_FILL, NEU_STROKE),
        "L4":          ColorSpec(NEU_FILL, NEU_STROKE),
        "L5":          ColorSpec(NEU_FILL, NEU_STROKE),
        "memory_ctx":  ColorSpec(C_MEM, INK),
        "tools_gw":    ColorSpec(C_TOOL, INK),
        "exec_engine": ColorSpec(C_EXEC, INK),
        "sandbox":     ColorSpec(C_SAND, INK),
        "SEC":         ColorSpec(C_SEC, INK),
    },
    flow_chain=("L1", "L2", "L3", "L4", "L5"),
)

# ---------------------------------------------------------------------------
# Evaluate + save
# ---------------------------------------------------------------------------
score, report = evaluate_svg(drawer)
print(f"Quality Score: {score}")
for line in report:
    print(line)

qa = run_semantic_qa(drawer, expected_size=(W, H), brief=BRIEF)
print("Semantic QA:")
for line in qa.report():
    print(line)

svg_path = str(OUT / f"{NAME}.svg")
png_path = str(OUT / f"{NAME}.png")
pptx_path = str(OUT / f"{NAME}.pptx")
save_svg(drawer.render(), svg_path)
# Rasterize SVG -> PNG (enforces output/<task>/ convention)
rasterize_svg(svg_path, png_path, W)
# Export to PPTX (native editable shapes)
from svg2pptx import svg_to_pptx
svg_to_pptx(drawer.render(), pptx_path)
print(f"Saved {svg_path}")
print(f"Saved {png_path}")
print(f"Saved {pptx_path} (editable shapes)")

BRIEF.write(str(OUT / "brief.json"))
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/input.md
size: 2855
sha: f1d22b6de866415b44abf39018bbf7cae303d67f
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_153000_agent_infra_architecture/input.md

```text
# Agent Infrastructure — Layered Architecture

Draw a **5-layer horizontal stack** (top → bottom) representing an AI agent
infrastructure platform, plus a **cross-cutting Security & Observability band**
on the RIGHT that spans the full height of the stack.

Title: **Agent Infra 架构图** / "Agent Infrastructure · 分层架构 Layered Architecture".

## Layers (top → bottom)

Each layer is a neutral container with a bilingual CN header + EN subtitle,
and holds component cards (or accent modules) inside.

1. **应用层 / Application Layer** — end-user interfaces (3 cards):
   Web 应用 · Web App | REST / API · Gateway | CLI 工具 · CLI.
2. **编排与治理层 / Orchestration & Governance** — agent coordination & control (4 cards):
   生命周期管理 · Lifecycle | 任务调度 · Scheduling | 多智能体协作 · Multi-Agent | 策略控制 · Policy.
3. **核心能力层 / Core Capabilities** — two accent modules side by side:
   - **记忆与上下文 / Memory & Context**: 向量数据库·Vector DB | 知识图谱·Knowledge Graph | RAG 检索·Retrieval.
   - **工具与网关 / Tools & Gateway**: MCP 协议·MCP | API 集成·API Integration | 函数调用·Function Call.
4. **执行与环境层 / Execution & Environment** — two accent modules side by side:
   - **执行引擎 / Execution Engine**: 高并发·Concurrency | 秒级扩容·Autoscale | 快速启动·Fast Start.
   - **环境与沙箱 / Environment & Sandbox**: 代码执行·Code Exec | Serverless·Elastic | 安全隔离·Isolation.
5. **基础设施层 / Infrastructure** — foundation (4 cards):
   计算·Compute GPU/CPU | 存储·Storage | 网络·Network | K8s 编排·Kubernetes.

## Cross-cutting band (right side, full height)

**安全与可观测 / Security & Observability** — a single tall band on the right
spanning ALL five layers, visually distinct from the neutral stack. Contains
6 cards: 身份认证·Authentication | 数据加密·Encryption | 行为审计·Behavior Audit |
日志·Logging | 监控·Metrics | 链路追踪·Tracing.

## Flow & connections

- **Dependency / control flow** — solid vertical arrows down the stack
  centerline linking each adjacent layer (L1→L2→L3→L4→L5).
- **Cross-cutting span** — a dashed horizontal line from each layer's right
  edge to the band's left edge, showing security & observability cut across
  every layer.
- A **legend** strip sits below the stack: core-module color swatches, the
  solid dependency arrow, and the dashed cross-cut line.

All labels are bilingual (CN + EN). The four accent modules plus the security
band use five distinct accent colors; everything else stays neutral. Layout,
exact palette, typography, and all geometry are yours to design — follow the
architecture-drawer skill's design system and let the evaluator guide
iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/brief.json
size: 1025
sha: f21ba80ea6877e5ddf196a40dae376a5135e62d5
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/brief.json

```text
{
  "scheme": "S2",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [
    "band1",
    "band2",
    "band3",
    "band4",
    "band5",
    "band6",
    "band7"
  ],
  "palette_role": {
    "band1": {
      "fill": "#dae8fc",
      "stroke": "#2e5aac"
    },
    "band2": {
      "fill": "#dae8fc",
      "stroke": "#2e5aac"
    },
    "band3": {
      "fill": "#b2e2e2",
      "stroke": "#2e8b8b"
    },
    "band4": {
      "fill": "#b2e2e2",
      "stroke": "#2e8b8b"
    },
    "band5": {
      "fill": "#ffe6cc",
      "stroke": "#d79b00"
    },
    "band6": {
      "fill": "#e1d5e7",
      "stroke": "#9673a6"
    },
    "band7": {
      "fill": "#e1d5e7",
      "stroke": "#9673a6"
    },
    "prefill_box": {
      "fill": "#ffffff",
      "stroke": "#2e8b8b"
    },
    "decode_box": {
      "fill": "#ffffff",
      "stroke": "#2e8b8b"
    },
    "storage_box": {
      "fill": "#ffe6cc",
      "stroke": "#d79b00"
    },
    "gpu_cluster": {
      "fill": "#ffe6cc",
      "stroke": "#d79b00"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/gen.py
size: 15898
sha: dfdd5877c5682cf740a88be44f89adaa30670bf5
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/gen.py

```text
"""LLM Distributed Inference Serving — 7-layer architecture diagram.

Layout: vertical layered stack. A neutral downward "spine" connects the client
(top) through seven architecture bands to the streaming output (bottom).
Internal edges show intra-layer flows (scheduler<->KV index, prefill->decode,
prefill cluster<->RDMA<->decode cluster).

Palette is held to exactly 8 accent colors (4 light fills + 4 dark strokes),
grouped by architectural function:
  blue   = control plane  (L1 Gateway, L2 Scheduler)
  teal   = compute        (L3 Inference Engine, L4 Parallelism)
  amber  = infra          (L5 Storage & Interconnect)
  purple = optimization   (L6 Hidden Optimizers, L7 Disaggregated)
Op cards are neutral white + gray stroke so they never inflate the palette.
Type scale is fixed at 4 tiers: 20 / 14 / 12 / 10.
"""

import sys
from pathlib import Path

import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
from svg_utils import SVGDrawer, save_svg, rasterize_svg
from svg2pptx import svg_to_pptx
from evaluator import evaluate_svg, auto_refine
from design_brief import DesignBrief, ColorSpec
from semantic_qa import run_semantic_qa

OUT = Path(__file__).resolve().parent
NAME = "llm_inference_arch"

# ---- palette --------------------------------------------------------------
BLUE_F, BLUE_S = "#DAE8FC", "#2E5AAC"
TEAL_F, TEAL_S = "#B2E2E2", "#2E8B8B"
AMBER_F, AMBER_S = "#FFE6CC", "#D79B00"
PURP_F, PURP_S = "#E1D5E7", "#9673A6"
CARD_F, CARD_S = "#FFFFFF", "#5A5A5A"   # neutral — not counted as accents
INK, SUB = "#222222", "#444444"          # neutral text
EDGE = "#6B6B6B"                          # neutral edges/arrows

W, H = 1400, 1400
CX = W // 2
BAND_X, BAND_W = 40, 1320

drawer = SVGDrawer(W, H, bg="#FFFFFF")
drawer.arrow_head("ah", EDGE, marker_width=10, marker_height=7, ref_x=9, ref_y=3.5)

# ---- band metadata: (num, name, fill, stroke, y, h) ----------------------
BANDS = [
    (1, "① 接入与网关层  Gateway Governance",            BLUE_F, BLUE_S, 138, 96),
    (2, "② 全局调度与路由  Scheduler & Routing",     BLUE_F, BLUE_S, 256, 120),
    (3, "③ 分布式推理引擎  Inference Engine",         TEAL_F, TEAL_S, 400, 210),
    (4, "④ 模型并行与加速  Model Parallelism",        TEAL_F, TEAL_S, 634, 150),
    (5, "⑤ 异构存储与通信  Storage & Interconnect",   AMBER_F, AMBER_S, 808, 160),
    (6, "⑥ 隐性优化组件  Hidden Optimizers",             PURP_F, PURP_S, 992, 130),
    (7, "⑦ 分离式部署  Disaggregated Serving",               PURP_F, PURP_S, 1146, 150),
]

def band_rect(n, fill, stroke, y, h):
    """Draw + register a layer band as a connectable layer node."""
    drawer.rect(BAND_X, y, BAND_W, h, rx=8, ry=8, fill=fill, stroke=stroke,
                stroke_width=1.5, node_id=f"band{n}", node_kind="layer",
                role="layer", bbox=False)

def badge(n, stroke, y):
    """Light layer-number badge (decoration, not a node)."""
    drawer.rect(55, y + 13, 42, 26, rx=5, ry=5, fill="#FFFFFF", stroke=stroke,
                stroke_width=1.5, role="decoration", bbox=False)
    drawer.text(76, y + 26, f"L{n}", 12, fill=INK, weight="bold", bbox=False)

def band_name(name, y):
    drawer.text(108, y + 27, name, 14, fill=INK, weight="bold",
                anchor="start", bbox=False)

def card(x, y, w, h, nid, title, desc, title_size=12, desc_size=10):
    """Neutral op card: rect node + two text lines (title / desc)."""
    drawer.rect(x, y, w, h, rx=6, ry=6, fill=CARD_F, stroke=CARD_S,
                stroke_width=1.2, node_id=nid, node_kind="op", role="node",
                bbox=True)
    cx = x + w / 2
    cy = y + h / 2
    drawer.text(cx, cy - 8, title, title_size, fill=INK, weight="bold", bbox=False)
    drawer.text(cx, cy + 9, desc, desc_size, fill=SUB, bbox=False)

# ---- title ----------------------------------------------------------------
drawer.text(CX, 32, "大模型分布式推理服务架构  LLM Distributed Inference Serving",
            20, fill=INK, weight="bold", bbox=False)

# ---- client ---------------------------------------------------------------
drawer.rect(560, 70, 280, 46, rx=8, ry=8, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.4, node_id="client", node_kind="op", role="node",
            bbox=True)
drawer.text(CX, 84, "客户端 Client", 12, fill=INK, weight="bold", bbox=False)
drawer.text(CX, 100, "HTTP / gRPC · Prompt + 采样参数", 10, fill=SUB, bbox=False)

# ---- bands (containers + headers) ----------------------------------------
for n, name, fill, stroke, y, h in BANDS:
    band_rect(n, fill, stroke, y, h)
    badge(n, stroke, y)
    band_name(name, y)

# ===== L1 Gateway: 4 cards ================================================
l1y = 164
for i, (nid, t, d) in enumerate([
    ("gw1", "负载均衡", "Load Balancer"),
    ("gw2", "认证鉴权", "AuthN & AuthZ"),
    ("gw3", "流量控制", "Rate Limit"),
    ("gw4", "Prompt 过滤", "Prompt Filter"),
]):
    card(415 + i * 215, l1y, 180, 44, nid, t, d)

# ===== L2 Scheduler: resource view | scheduler | KV index =================
drawer.rect(80, 294, 260, 58, rx=6, ry=6, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.2, node_id="resv", node_kind="op", role="node", bbox=True)
drawer.text(210, 314, "集群资源视图", 12, fill=INK, weight="bold", bbox=False)
drawer.text(210, 332, "GPU 显存 / 利用率 / 健康", 10, fill=SUB, bbox=False)

drawer.rect(420, 294, 340, 58, rx=6, ry=6, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.4, node_id="sched", node_kind="op", role="node", bbox=True)
drawer.text(590, 314, "全局调度器 Scheduler", 12, fill=INK, weight="bold", bbox=False)
drawer.text(590, 332, "Prefix Cache 查找 · 负载均衡", 10, fill=SUB, bbox=False)

drawer.database(840, 294, 260, 58, fill=BLUE_F, stroke=BLUE_S, stroke_width=1.4,
                node_id="kvid", node_kind="op", role="node", bbox=True)
drawer.text(970, 314, "KV 缓存索引", 12, fill=INK, weight="bold", bbox=False)
drawer.text(970, 332, "KV Cache Index", 10, fill=SUB, bbox=False)

drawer.connect("resv", "right", "sched", "left", stroke=EDGE, stroke_width=1.5, marker_end="ah")
drawer.connect("sched", "right", "kvid", "left", stroke=EDGE, stroke_width=1.5,
               marker_end="ah", dashed=True)
drawer.text(800, 310, "Prefix 命中", 10, fill=SUB, bbox=False)

# ===== L3 Inference Engine: prefill box -> decode box =====================
drawer.rect(70, 444, 590, 140, rx=8, ry=8, fill="#FFFFFF", stroke=TEAL_S,
            stroke_width=1.6, node_id="prefill_box", node_kind="layer",
            role="layer", bbox=True)
drawer.text(365, 466, "Prefill Worker（计算密集）", 12, fill=INK, weight="bold", bbox=False)
for i, (nid, t) in enumerate([
    ("pf1", "Sequence 切分"),
    ("pf2", "Attention 并行"),
    ("pf3", "KV 压缩写入"),
]):
    x = 96 + i * 176
    drawer.rect(x, 498, 156, 34, rx=5, ry=5, fill=TEAL_F, stroke=TEAL_S,
                stroke_width=1.1, node_id=nid, node_kind="op", role="node", bbox=True)
    drawer.text(x + 78, 515, t, 12, fill=INK, bbox=False)

drawer.rect(720, 444, 590, 140, rx=8, ry=8, fill="#FFFFFF", stroke=TEAL_S,
            stroke_width=1.6, node_id="decode_box", node_kind="layer",
            role="layer", bbox=True)
drawer.text(1015, 466, "Decode Worker（访存密集）", 12, fill=INK, weight="bold", bbox=False)
for i, (nid, t) in enumerate([
    ("dc1", "Continuous Batch"),
    ("dc2", "动态插入/踢出"),
    ("dc3", "逐 Token 生成"),
]):
    x = 746 + i * 176
    drawer.rect(x, 498, 156, 34, rx=5, ry=5, fill=TEAL_F, stroke=TEAL_S,
                stroke_width=1.1, node_id=nid, node_kind="op", role="node", bbox=True)
    drawer.text(x + 78, 515, t, 12, fill=INK, bbox=False)

drawer.connect("prefill_box", "right", "decode_box", "left", stroke=EDGE,
               stroke_width=1.6, marker_end="ah")
drawer.text(690, 500, "KV Cache 转移", 10, fill=SUB, bbox=False)
drawer.text(690, 528, "Continuous Batching", 10, fill=SUB, bbox=False)

# ===== L4 Parallelism: TP | PP | SP =======================================
for i, (nid, t, d) in enumerate([
    ("tp", "张量并行 TP", "QKV 矩阵列切分 · All-Reduce"),
    ("pp", "流水线并行 PP", "按层切分 · Send / Recv"),
    ("sp", "序列并行 SP", "长序列切分 · 合并"),
]):
    card(90 + i * 420, 680, 380, 80, nid, t, d)

# ===== L5 Storage & Interconnect ==========================================
drawer.rect(70, 858, 360, 98, rx=8, ry=8, fill=AMBER_F, stroke=AMBER_S,
            stroke_width=1.4, node_id="storage_box", role="layer", bbox=False)
drawer.text(250, 876, "存储层级 Storage", 12, fill=INK, weight="bold", bbox=False)
for i, line in enumerate([
    "HBM 显存：权重 + 活跃 KV Cache",
    "CPU DRAM：分片暂存 / KV 换出",
    "分布式存储：模型检查点",
]):
    drawer.text(250, 898 + i * 18, line, 10, fill=SUB, bbox=False)

drawer.rect(500, 860, 300, 34, rx=5, ry=5, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.2, node_id="nvlink", node_kind="op", role="node", bbox=True)
drawer.text(650, 877, "NVLink 节点内（TP All-Reduce）", 10, fill=INK, bbox=False)
drawer.rect(500, 912, 300, 34, rx=5, ry=5, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.2, node_id="ib", node_kind="op", role="node", bbox=True)
drawer.text(650, 929, "InfiniBand/RoCE 跨节点（PP/RDMA）", 10, fill=INK, bbox=False)

drawer.rect(880, 858, 400, 98, rx=8, ry=8, fill=AMBER_F, stroke=AMBER_S,
            stroke_width=1.4, node_id="gpu_cluster", role="layer", bbox=False)
drawer.text(1080, 876, "GPU 节点集群（8×A100/H100）", 12, fill=INK, weight="bold", bbox=False)
for i in range(4):
    gx = 910 + i * 90
    drawer.rect(gx, 898, 70, 30, rx=4, ry=4, fill="#FFFFFF", stroke="#999999",
                stroke_width=1.0, role="decoration", bbox=False)
    drawer.text(gx + 35, 913, f"GPU{i}", 10, fill=SUB, bbox=False)

# ===== L6 Hidden Optimizers ===============================================
card(90, 1044, 580, 56, "opt1",
     "通信延迟隐藏 Compute-Comm Overlap",
     "计算/通信异步重叠，掩盖跨卡同步延迟")
card(710, 1044, 580, 56, "opt2",
     "动态显存分配 KV Cache Swap",
     "显存紧张时换出冷 KV 至 CPU，按需换回")

# ===== L7 Disaggregated Serving ===========================================
drawer.rect(90, 1200, 360, 68, rx=6, ry=6, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.2, node_id="pre_cluster", node_kind="op", role="node", bbox=True)
drawer.text(270, 1222, "Prefill 集群", 12, fill=INK, weight="bold", bbox=False)
drawer.text(270, 1240, "长上下文 · 计算饱和", 10, fill=SUB, bbox=False)

drawer.hexagon(560, 1218, 240, 34, fill=PURP_F, stroke=PURP_S, stroke_width=1.3,
               node_id="rdma", node_kind="op", role="node", bbox=True)
drawer.text(680, 1235, "RDMA 高速网络", 10, fill=INK, bbox=False)

drawer.rect(910, 1200, 360, 68, rx=6, ry=6, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.2, node_id="dec_cluster", node_kind="op", role="node", bbox=True)
drawer.text(1090, 1222, "Decode 集群", 12, fill=INK, weight="bold", bbox=False)
drawer.text(1090, 1240, "快速生成 · 带宽饱和", 10, fill=SUB, bbox=False)

drawer.connect("pre_cluster", "right", "rdma", "left", stroke=EDGE,
               stroke_width=1.5, marker_end="ah")
drawer.connect("rdma", "right", "dec_cluster", "left", stroke=EDGE,
               stroke_width=1.5, marker_end="ah", dashed=True)
drawer.text(855, 1222, "任务队列 / 中间态", 10, fill=SUB, bbox=False)

# ===== streaming output ===================================================
drawer.rect(560, 1320, 280, 46, rx=8, ry=8, fill=CARD_F, stroke=CARD_S,
            stroke_width=1.4, node_id="output", node_kind="op", role="node", bbox=True)
drawer.text(CX, 1334, "采样 Sampling（Top-P / Top-K）", 12, fill=INK, weight="bold", bbox=False)
drawer.text(CX, 1350, "流式返回 Stream Output（SSE / WebSocket）", 10, fill=SUB, bbox=False)

# ===== downward spine: client -> bands -> output ==========================
spine = [("client", "band1")] + [(f"band{i}", f"band{i+1}") for i in range(1, 7)] + [("band7", "output")]
for a, b in spine:
    drawer.connect(a, "bottom", b, "top", stroke=EDGE, stroke_width=2, marker_end="ah")
drawer.text(712, 128, "请求 Request", 10, fill=SUB, anchor="start", bbox=False)

# ---- evaluate, auto-refine, emit triplet ---------------------------------
score, report = evaluate_svg(drawer)
print(f"Initial score: {score}")
for line in report:
    print(line)

if score < 100:
    score, report, fixes = auto_refine(drawer, target_score=100, max_iter=3)
    print(f"\nAfter auto_refine: {score}  (fixes: {len(fixes)})")
    for f in fixes:
        print("  -", f)
    for line in report:
        print(line)

# ---- design brief (Step 1) --------------------------------------------------
# Declared from input.md's intent: seven numbered bands ①–⑦ stacked top-down
# (gateway -> scheduler -> engine -> parallelism -> storage -> optimizers ->
# disaggregated) on a downward request spine; palette grouped by concern
# (blue/teal/amber/purple = S2 categorical, per the design-system budget
# input.md delegates to). The nested ③ worker containers draw white with the
# teal STROKE carrying the color; ⑤ repeats the amber pair on its storage /
# GPU-cluster containers. The spine arrows link band borders across the
# gutters and the marker-tip retraction lands every endpoint between bands,
# so no inter-layer edge attributes to the next band — a declared chain would
# false-FAIL (same gutter-spine situation as the pi_agent / mlir evals).
BRIEF = DesignBrief(
    scheme="S2",
    layout="band",
    flow="top-down",
    palette_role={
        "band1":       ColorSpec(BLUE_F, BLUE_S),
        "band2":       ColorSpec(BLUE_F, BLUE_S),
        "band3":       ColorSpec(TEAL_F, TEAL_S),
        "band4":       ColorSpec(TEAL_F, TEAL_S),
        "band5":       ColorSpec(AMBER_F, AMBER_S),
        "band6":       ColorSpec(PURP_F, PURP_S),
        "band7":       ColorSpec(PURP_F, PURP_S),
        "prefill_box": ColorSpec("#FFFFFF", TEAL_S),
        "decode_box":  ColorSpec("#FFFFFF", TEAL_S),
        "storage_box": ColorSpec(AMBER_F, AMBER_S),
        "gpu_cluster": ColorSpec(AMBER_F, AMBER_S),
    },
    flow_chain=("band1", "band2", "band3", "band4", "band5", "band6", "band7"),
)

print("Quality Score: %d" % score)
qa = run_semantic_qa(drawer, expected_size=(W, H), brief=BRIEF)
print("Semantic QA:")
for line in qa.report():
    print(line)

svg = drawer.render()
save_svg(svg, str(OUT / f"{NAME}.svg"))
rasterize_svg(str(OUT / f"{NAME}.svg"), str(OUT / f"{NAME}.png"), width=W)
svg_to_pptx(svg, str(OUT / f"{NAME}.pptx"))
print(f"\nFinal score: {score}")
print(f"Wrote triplet to {OUT}")
BRIEF.write(str(OUT / "brief.json"))
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/input.md
size: 3099
sha: 9467543dece513dc1f45ec1d5974d0e33e079def
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_203836_llm_inference_arch/input.md

```text
# LLM Distributed Inference Serving — 7-Layer Architecture

Draw a vertical layered stack showing a distributed LLM inference serving
system. A neutral downward "spine" connects the client (top) through seven
architecture bands to the streaming output (bottom).

## Layers (top → bottom)

Each band is one layer, named bilingually (circled number ①–⑦ + CN + EN).
Components inside each band are neutral op cards.

1. **① 接入与网关层  Gateway Governance** — 4 op cards side-by-side:
   负载均衡 Load Balancer, 认证鉴权 AuthN & AuthZ, 流量控制 Rate Limit,
   Prompt 过滤 Prompt Filter.
2. **② 全局调度与路由  Scheduler & Routing** — three nodes in a row:
   集群资源视图 (GPU 显存/利用率/健康) → 全局调度器 Scheduler (Prefix Cache
   查找 · 负载均衡) ⇢ KV 缓存索引 KV Cache Index (drawn as a database
   cylinder). The sched→kvid edge is dashed (cache-hit lookup).
3. **③ 分布式推理引擎  Inference Engine** — two nested worker containers
   side-by-side: Prefill Worker（计算密集）containing Sequence 切分 /
   Attention 并行 / KV 压缩写入 chips; Decode Worker（访存密集）
   containing Continuous Batch / 动态插入踢出 / 逐 Token 生成 chips. Connected
   by a "KV Cache 转移 · Continuous Batching" arrow.
4. **④ 模型并行与加速  Model Parallelism** — 3 wide cards:
   张量并行 TP (QKV 矩阵列分割 · All-Reduce), 流水线并行 PP (按层分割 ·
   Send/Recv), 序列并行 SP (长序列分割 · 合并).
5. **⑤ 异构存储与通信  Storage & Interconnect** — Storage container
   (HBM 显存 / CPU DRAM / 分布式存储) + NVLink 节点内 and InfiniBand/RoCE
   跨节点 interconnect cards + GPU 节点集群 (8×A100/H100) with 4 GPU chips.
6. **⑥ 隐性优化组件  Hidden Optimizers** — 2 wide cards:
   通信延迟隐藏 Compute-Comm Overlap (计算/通信异步重叠), 动态显存分配 KV
   Cache Swap (换出冷 KV 至 CPU).
7. **⑦ 分离式部署  Disaggregated Serving** — Prefill 集群 (长上下文 ·
   计算饱和) → RDMA 高速网络 (drawn as a hexagon) ⇢ Decode 集群 (快速生成 ·
   带宽饱和). The rdma→dec_cluster edge is dashed (任务队列/中间态).

Top anchor: 客户端 Client (HTTP / gRPC · Prompt + 采样参数). Bottom anchor:
采样 Sampling (Top-P/Top-K) / 流式返回 Stream Output (SSE / WebSocket).

## Flow

A central vertical spine (neutral gray) carries the request downward through
all seven band nodes (client → band1 → … → band7 → output). Internal
horizontal edges show intra-layer flows (L2 resource→scheduler→KV, L3
prefill→decode, L7 prefill→RDMA→decode).

Layer bands may share a color family per concern (gateway/scheduling blue,
engine/parallelism teal, storage amber, optimizers/disaggregation purple) —
keep the total accent count within the skill's design-system budget. Layout,
exact palette, typography, and all geometry are yours to design — follow the
architecture-drawer skill's design system and let the evaluator guide
iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/brief.json
size: 541
sha: 9b1ebb13e89cf6c826f16f6bc42e6fee31639a6e
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/brief.json

```text
{
  "scheme": "S2",
  "layout": "node",
  "flow": "none",
  "flow_chain": [],
  "palette_role": {
    "comm1": {
      "fill": "#dbeafe",
      "stroke": "#2563eb"
    },
    "geo_relay": {
      "fill": "#dbeafe",
      "stroke": "#2563eb"
    },
    "meo1": {
      "fill": "#dcfce7",
      "stroke": "#16a34a"
    },
    "src": {
      "fill": "#ffedd5",
      "stroke": "#ea580c"
    },
    "station": {
      "fill": "#e2e8f0",
      "stroke": "#475569"
    },
    "gs3": {
      "fill": "#ffffff",
      "stroke": "#475569"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/gen.py
size: 12282
sha: 9b148e09f1a36aaa7e2614f72c39a85918324d70
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/gen.py

```text
# -*- coding: utf-8 -*-
"""天地一体化卫星系统架构分层图 (Integrated Space-Ground Satellite Architecture).

Bottom = ground, top = deep space. Five vertical layers + a horizontal
functional color code (blue=comm, green=nav, orange=sensing/research,
slate=manned/station). Concrete validated edges: LEO constellation mesh and
the LEO->GEO-relay->ground data chain. Broadcast/conceptual flows (MEO
coverage beams, ground uplink/downlink) are drawn as decoration.

Palette idiom: pastel fill + same-family dark stroke per hue; all text and
arrowheads neutral black so no dark/light clash appears in either channel.
"""
import sys
from pathlib import Path

import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
from svg_utils import SVGDrawer, save_svg, rasterize_svg
from evaluator import evaluate_svg
from svg2pptx import svg_to_pptx, PptxConfig
from design_brief import DesignBrief, ColorSpec
from semantic_qa import run_semantic_qa

OUT = Path(__file__).resolve().parent
NAME = "satellite_arch"

# ---- Palette: 4 hue families (light fill + dark stroke) + neutrals -----------
BLUE, BLUE_F = "#2563EB", "#DBEAFE"       # communication / data links
GREEN, GREEN_F = "#16A34A", "#DCFCE7"     # navigation
ORANGE, ORANGE_F = "#EA580C", "#FFEDD5"   # sensing / research
SLATE, SLATE_F = "#475569", "#E2E8F0"     # manned / structural
BLACK = "#000000"                         # all text + arrowheads (neutral)
LINE = "#A8A8A8"                          # neutral scale / divider lines
BAND_A, BAND_B = "#F6F6F6", "#EFEFEF"     # neutral layer bands
EARTH_F, EARTH_S = "#E4E4E4", "#9A9A9A"   # neutral earth

F_TITLE, F_HEAD, F_BODY = 22, 15, 12

W, Hh = 1400, 1180
d = SVGDrawer(W, Hh, bg="#FFFFFF")
d.arrow_head("ah", BLACK)   # single neutral arrowhead

def band(x, y, w, h, fill):
    d.rect(x, y, w, h, rx=10, ry=10, fill=fill, stroke="none", opacity=0.9,
           role="background")

def layer_header(x, y, text):
    d.text(x, y, text, F_HEAD, fill=BLACK, anchor="start", weight="bold", bbox=False)

def sat_circle(cx, cy, r, fill, stroke, nid, sw=1.6):
    d.circle(cx, cy, r, fill=fill, stroke=stroke, stroke_width=sw,
             node_id=nid, node_kind="op")

def sat_square(cx, cy, s, fill, stroke, nid, sw=1.6):
    d.rect(cx - s / 2, cy - s / 2, s, s, rx=2, ry=2, fill=fill, stroke=stroke,
           stroke_width=sw, node_id=nid, node_kind="op")

def sat_triangle(cx, cy, r, fill, stroke, nid, sw=1.6):
    pts = f'{cx},{cy - r} {cx - r},{cy + r * 0.8} {cx + r},{cy + r * 0.8}'
    d.add_element(
        f'<polygon points="{pts}" fill="{fill}" stroke="{stroke}" '
        f'stroke-width="{sw}" stroke-linejoin="round" />', None)
    d.register_node(nid, cx - r, cy - r, 2 * r, 2 * r, kind="op", visible=True)
    d._record_color(fill, stroke)

def lbl(cx, cy, text, anchor="middle", weight="normal"):
    d.text(cx, cy, text, F_BODY, fill=BLACK, anchor=anchor, weight=weight, bbox=False)

# ---------------- Title + subtitle ----------------
d.text(W / 2, 34, "天地一体化卫星系统架构分层图", F_TITLE, fill=BLACK, weight="bold")
d.text(W / 2, 62, "涵盖轨道高度 · 卫星分类 · 数据流向", F_BODY, fill=BLACK)

# ---------------- Legend (centered row below subtitle) ----------------
LY = 88
legend = [(BLUE, BLUE_F, "通信类（含中继）"), (GREEN, GREEN_F, "导航类"),
          (ORANGE, ORANGE_F, "遥感 / 科研类"), (SLATE, SLATE_F, "载人 / 空间站")]
item_w = 168
lx0 = (W - item_w * len(legend)) / 2
for i, (dark, light, t) in enumerate(legend):
    x = lx0 + i * item_w
    d.circle(x, LY, 7, fill=light, stroke=dark, stroke_width=1.4, role="legend")
    d.text(x + 14, LY, t, F_BODY, fill=BLACK, anchor="start", bbox=False)

# ---------------- Layer bands (gapped, tracked) ----------------
CX0, CX1 = 150, 1350
BW = CX1 - CX0
bands = [
    (125, 115, "⑤ 深空探测 / 拉格朗日点层", BAND_B),
    (268, 120, "④ 地球静止轨道 GEO / 倾斜同步 IGSO", BAND_A),
    (420, 125, "③ 中地球轨道 MEO · 导航定位层", BAND_B),
    (580, 210, "② 低地球轨道 LEO · 近地密集层（200–2,000 km）", BAND_A),
    (865, 80, "① 地面支撑层", BAND_B),
]
for y, h, name, fill in bands:
    band(CX0, y, BW, h, fill)
    layer_header(CX0 + 14, y + 20, name)

# ---------------- Left altitude scale ----------------
SX = 108
d.line(SX, 120, SX, 960, stroke=LINE, stroke_width=1.5, role="decoration")
alt = [(180, ["L1 / L2 点", "百万公里级"]),
       (320, ["≈35,786 km", "GEO 同步高度"]),
       (480, ["≈20,200 km", "MEO 导航"]),
       (590, ["2,000 km"]),
       (780, ["200 km"]),
       (905, ["0 km 地面"])]
for ty, lines in alt:
    d.line(SX - 5, ty, SX + 5, ty, stroke=LINE, stroke_width=1.5, role="decoration")
    for j, ln in enumerate(lines):
        d.text(SX - 10, ty - (len(lines) - 1) * 7 + j * 14, ln,
               F_BODY, fill=BLACK, anchor="end", bbox=False)
d.text(SX, 105, "轨道高度", F_BODY, fill=BLACK, weight="bold", bbox=False)

# ---------------- Layer 5 — Deep space ----------------
Y5 = 185
for cx, t, nid in [(300, "韦伯望远镜", "ds1"), (470, "爱因斯坦探针", "ds2"),
                   (640, "太阳观测卫星", "ds3")]:
    sat_triangle(cx, Y5, 14, ORANGE_F, ORANGE, nid)
    lbl(cx, Y5 - 26, t)
for cx, t in [(860, "L1"), (980, "L2")]:
    d.add_element(
        f'<polygon points="{cx},{Y5-9} {cx+9},{Y5} {cx},{Y5+9} {cx-9},{Y5}" '
        f'fill="{SLATE_F}" stroke="{SLATE}" stroke-width="1.4"/>', None)
    lbl(cx, Y5 - 26, t)
lbl(1340, Y5 - 6, "大椭圆 / 闪电轨道", anchor="end")
lbl(1340, Y5 + 14, "地日 · 地月 L1 / L2 拉格朗日点", anchor="end")

# ---------------- Layer 4 — GEO / IGSO ----------------
Y4 = 345
d.add_element(
    f'<path d="M 175,{Y4+18} Q {(175+1145)/2},{Y4-30} 1145,{Y4+18}" '
    f'fill="none" stroke="{LINE}" stroke-width="1.6" stroke-dasharray="5,4"/>', None)
geo = [("geo_comm1", 360, Y4 + 4, BLUE_F, BLUE, "通信广播 · 亚太"),
       ("geo_met", 540, Y4 - 6, ORANGE_F, ORANGE, "气象预警 · 风云"),
       ("geo_warn", 720, Y4 - 10, ORANGE_F, ORANGE, "战略预警 · 红外"),
       ("geo_comm2", 900, Y4 - 6, BLUE_F, BLUE, "通信广播 · 广电"),
       ("geo_relay", 1230, Y4 + 4, BLUE_F, BLUE, "数据中继 · 天链")]
for nid, cx, cy, f, s, _ in geo:
    sat_square(cx, cy, 30, f, s, nid)
for nid, cx, cy, f, s, t in geo:
    lbl(cx, cy - 24, t)

# ---------------- Layer 3 — MEO navigation ----------------
meo = [("meo1", 300, 490, "北斗"), ("meo2", 460, 508, "GPS"),
       ("meo3", 620, 490, "Galileo"), ("meo4", 780, 508, "北斗"),
       ("meo5", 940, 490, "GPS"), ("meo6", 1100, 508, "Galileo")]
for nid, cx, cy, name in meo:
    sat_circle(cx, cy, 15, GREEN_F, GREEN, nid)
    lbl(cx, cy - 28, name)
lbl(700, 435, "导航定位星座（3–6 轨道面均匀分布）")
for nid, cx, cy, name in meo[::2]:  # top row only: coverage beams stay in band
    d.add_element(
        f'<polygon points="{cx-18},{cy+15} {cx+18},{cy+15} {cx},{cy+54}" '
        f'fill="{GREEN_F}" fill-opacity="0.55" stroke="{GREEN}" stroke-width="0.8" '
        f'stroke-dasharray="3,3"/>', None)
lbl(300, 558, "导航覆盖波束", anchor="start")

# ---------------- Layer 2 — LEO ----------------
comm_x = [220, 350, 480, 610, 740, 870, 1000, 1130]
Ycomm = 635
for i, cx in enumerate(comm_x):
    sat_circle(cx, Ycomm, 12, BLUE_F, BLUE, f"comm{i+1}")
for i in range(len(comm_x) - 1):
    d.connect(f"comm{i+1}", "right", f"comm{i+2}", "left",
              stroke=BLUE, stroke_width=1.4, marker_end=None)
lbl(675, Ycomm + 34, "低轨通信星座（星链 / 千帆）· 星间链路网状互联")

sense = [("sense1", 300, 695, "光学遥感"), ("sense2", 540, 695, "雷达遥感"),
         ("sense3", 790, 695, "资源勘探"), ("src", 1230, 695, None)]
for nid, cx, cy, t in sense:
    sat_square(cx, cy, 22, ORANGE_F, ORANGE, nid)
    if t:
        lbl(cx, cy + 24, t)
lbl(1230, 695 + 24, "遥感数据源")

sci = [("sci1", 430, 752, "实践 · 科学试验"), ("sci2", 670, 752, "空间环境探测")]
for nid, cx, cy, t in sci:
    sat_triangle(cx, cy, 13, ORANGE_F, ORANGE, nid)
    lbl(cx, cy + 26, t)

sat_square(980, 740, 54, SLATE_F, SLATE, "station", sw=2.0)
lbl(980, 740, "天宫", weight="bold")
lbl(980, 740 + 38, "空间站（载人航天）")

# ---------------- Layer 1 — Ground ----------------
ground = [("gs1", 360, 905, "地面测控站"), ("gs2", 740, 905, "数据接收天线"),
          ("gs3", 1130, 905, "卫星控制中心")]
for nid, cx, cy, t in ground:
    sat_square(cx, cy, 34, "#FFFFFF", SLATE, nid, sw=1.8)
    lbl(cx, cy + 30, t, weight="bold")
    # symbolic uplink / downlink (decorative)
    d.line(cx - 16, cy - 17, cx - 16, cy - 52, stroke=BLUE, stroke_width=1.6,
           marker_end="ah", role="decoration")
    d.line(cx + 16, cy - 52, cx + 16, cy - 17, stroke=BLUE, stroke_width=1.6,
           marker_end="ah", dashed="5,3", role="decoration")
lbl(360, 905 - 62, "指令↑  数据↓")

# ---------------- Relay chain (concrete validated edges) ----------------
d.connect("src", "top", "geo_relay", "bottom",
          stroke=BLUE, stroke_width=1.8, marker_end="ah")
d.connect("geo_relay", "bottom", "gs3", "top",
          stroke=BLUE, stroke_width=1.8, marker_end="ah")

# LEO<->MEO inter-satellite dashed link
d.connect("comm4", "top", "meo3", "bottom",
          stroke=BLUE, stroke_width=1.3, marker_end=None, dashed=True)
lbl(640, 552, "星间链路", anchor="start")

# ---------------- Earth horizon ----------------
d.add_element(
    f'<path d="M 0,{Hh} Q {W/2},{1005} {W},{Hh} Z" '
    f'fill="{EARTH_F}" stroke="{EARTH_S}" stroke-width="1.6"/>', None)
lbl(W / 2, 1050, "地面段 · 测控 / 数收 / 控制中心")

# ---------------- Footer ----------------
d.text(CX0 + 4, 965,
       "色系：  蓝=信息传输（通信/中继）   绿=导航感知   橙=探测与科研   深灰=载人/平台",
       F_BODY, fill=BLACK, anchor="start", bbox=False)
d.text(CX0 + 4, 987,
       "数据通路：  遥感星 → 高轨中继（天链） → 地面站；星座内部及层间由星间链路互联。",
       F_BODY, fill=BLACK, anchor="start", bbox=False)

# ---------------- Design Brief (Step 1) ----------------
# Declared from input.md's intent. The orbit-altitude bands are neutral
# background zones (gray fills, role="background"): the diagram's structural
# color is the horizontal FUNCTIONAL code carried by the satellites
# themselves (blue=comm/relay, green=nav, orange=sensing/research,
# slate=manned/platform) -> node-style brief whose palette keys are primary
# nodes: the validated relay chain 遥感数据源→GEO中继(天链)→地面控制中心
# plus one representative of each remaining hue family (LEO comm mesh,
# MEO navigation, 天宫 station). Flow: input.md's connectors are a link-style
# mesh ("a mesh, not a flow") and an up-then-down relay path that is monotonic
# on neither axis -- no dominant flow direction -> flow="none", empty chain.
BRIEF = DesignBrief(
    scheme="S2",
    layout="node",
    flow="none",
    palette_role={
        "comm1":     ColorSpec(BLUE_F, BLUE),     # LEO comm constellation
        "geo_relay": ColorSpec(BLUE_F, BLUE),     # GEO data relay (天链)
        "meo1":      ColorSpec(GREEN_F, GREEN),   # MEO navigation
        "src":       ColorSpec(ORANGE_F, ORANGE),  # remote-sensing source
        "station":   ColorSpec(SLATE_F, SLATE),   # 天宫 manned station
        "gs3":       ColorSpec("#FFFFFF", SLATE),  # ground control center
    },
    flow_chain=(),
)

# ---------------- Evaluate + render ----------------
score, report = evaluate_svg(d)
print(f"Quality Score: {score}")
for line in report:
    print(line)

qa = run_semantic_qa(d, expected_size=(W, Hh), brief=BRIEF)
print("Semantic QA:")
for line in qa.report():
    print(line)

save_svg(d.render(), str(OUT / f"{NAME}.svg"))
rasterize_svg(str(OUT / f"{NAME}.svg"), str(OUT / f"{NAME}.png"), width=1400)
svg_to_pptx(str(OUT / f"{NAME}.svg"), str(OUT / f"{NAME}.pptx"),
            config=PptxConfig(slide_w=13.333, slide_h=11.25, scale=1.0))
BRIEF.write(str(OUT / "brief.json"))
print("Done.")
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/input.md
size: 2779
sha: 9d18a9443f618778692e234ca1c54a014be571dc
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260728_2157_satellite_arch/input.md

```text
# Integrated Space-Ground Satellite System Architecture

天地一体化卫星系统架构分层图 (Integrated Space-Ground Satellite Architecture) — a layered
diagram mapping satellite subsystems across orbital-altitude bands (bottom = ground,
top = deep space), with a horizontal functional color code distinguishing what each
satellite does (comm / nav / sensing / manned).

## Layers (bottom → top)

1. **Ground Segment (地面支撑层)** — ground stations, TT&C, mission control,
   data receiving antennas, satellite control center. White-filled nodes.
2. **LEO Constellation (低地球轨道, the densest layer)** — three sub-rows:
   a mesh of low-orbit comm satellites (starlink/千帆 style) with
   inter-satellite links; a row of sensing satellites
   (optical/radar/resource) and a remote-sensing data source; a small
   science-probe sub-row; plus the manned 天宫 space station.
3. **MEO Navigation (中地球轨道)** — navigation constellation (北斗/GPS/Galileo)
   arranged as a staggered two-row ring with downward coverage beams.
4. **GEO / IGSO (地球静止轨道)** — geostationary relay, broadcast, weather,
   and strategic-warning satellites riding a single dashed orbital arc.
5. **Deep Space (深空探测 / 拉格朗日点)** — space telescopes and probes near
   the L1/L2 Lagrange points, plus a note on highly-elliptical (闪电) orbits.

The ground segment closes the diagram at the bottom with an earth-horizon
curve and a ground-segment caption beneath it.

## Functional color code (horizontal)

- **Blue** = communication payloads and data-relay links (incl. 天链 relay)
- **Green** = navigation / positioning (北斗, GPS, Galileo)
- **Orange** = sensing / earth observation / research probes
- **Slate** = manned platforms / stations / structural (天宫, ground stations)

Each layer contains nodes colored by their function.

## Flow & edges

- **LEO comm mesh**: link-style connectors between consecutive comm
  satellites (a mesh, not a flow — no arrowheads).
- **Validated relay chain (the concrete data path, draw these as real
  edges):** remote-sensing source → GEO relay → ground control (sensing data
  flowing up, then down).
- **LEO↔MEO inter-satellite link:** a dashed cross-layer constellation link,
  no arrowhead.
- Decorative uplink/downlink arrow pairs (solid up, dashed down) may sit
  beside ground stations — mark them decorative, not real edges.

Node shapes distinguish subsystem kinds (circles for satellites, squares for
ground/station nodes, apex-up triangles for probes/telescopes, diamonds for
Lagrange markers). Layout, exact palette, typography, and all geometry are
yours to design — follow the architecture-drawer skill's design system and
let the evaluator guide iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/brief.json
size: 470
sha: 743f4d5e34b39b991d38c0400d1ca8baca1735b7
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/brief.json

```text
{
  "scheme": "S2",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [
    "L_model",
    "L_exec",
    "L_graph",
    "L_backend"
  ],
  "palette_role": {
    "L_model": {
      "fill": "#faeed1",
      "stroke": "#e69f00"
    },
    "L_exec": {
      "fill": "#e1f2fb",
      "stroke": "#56b4e9"
    },
    "L_graph": {
      "fill": "#d1eee6",
      "stroke": "#009e73"
    },
    "L_backend": {
      "fill": "#d1e6f1",
      "stroke": "#0072b2"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/gen.py
size: 9505
sha: c1aacadda8ff181008739f3da796e1ef2c3eaa8a
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/gen.py

```text
"""llama.cpp architecture diagram generator.

Three-section top-to-bottom layout:
  1. Core Library  — 4 stacked layer bands (Model / Execution / Graph / Backend)
  2. Inference Execution Flow — horizontal 6-stage pipeline
  3. Server Architecture (llama-server) — routes -> queue -> context(slots) -> response

Palette: S2 Categorical (Okabe-Ito, colorblind-safe). Each library layer gets a
distinct HUE so layer boundaries read at a glance — not a single-hue ramp whose
tiers blur together. Cards inherit their parent layer's stroke (visual grouping,
no extra accents). Text is neutral; connectors gray. The inference/server sections
are a different structural concern (runtime flow, not static architecture) so they
stay neutral-gray. 8 accents total (4 tints + 4 matching strokes), within budget.
4 font tiers (20 / 14 / 12 / 10).
"""
import sys
from pathlib import Path

import os, sys
_HERE = os.path.dirname(os.path.abspath(__file__))
_SKILL = os.path.normpath(os.path.join(_HERE, "..", "..", "scripts"))
if _SKILL not in sys.path:
    sys.path.insert(0, _SKILL)
from svg_utils import SVGDrawer, save_svg, rasterize_svg
from evaluator import evaluate_svg
from svg2pptx import svg_to_pptx
from design_brief import DesignBrief, ColorSpec
from semantic_qa import run_semantic_qa

OUT = Path(__file__).resolve().parent
NAME = "llama_cpp_arch"

W, H = 1400, 1060

# ---- palette: S2 Categorical (Okabe-Ito) ---------------------------------
# Each layer = (fill tint, matching stroke). Distinct hues → layer identity is
# visible. All fills are light pastels (L>0.8); all strokes medium (0.2<L<0.8),
# so no within-channel luminance clash. 8 accents total.
LAYERS = [
    ("Model Layer",               "#FAEED1", "#E69F00"),  # Orange
    ("Execution Layer",           "#E1F2FB", "#56B4E9"),  # Sky Blue
    ("Computation Graph Layer",   "#D1EEE6", "#009E73"),  # Bluish-Green
    ("Backend Abstraction Layer", "#D1E6F1", "#0072B2"),  # Deep Blue
]
TXT   = "#222222"   # primary text  (neutral -> not counted as accent)
SUB   = "#555555"   # subtitle text (neutral)
GRAY  = "#4D4D4D"   # connectors + arrowheads (neutral)
NSTK  = "#555555"   # neutral stroke for process-section cards (neutral)
CARD  = "#FFFFFF"
PANEL = "#F7F7F7"   # near-white section panel (neutral)
DIV   = "#CCCCCC"   # panel border (neutral)

drawer = SVGDrawer(W, H, bg="#FFFFFF")
drawer.arrow_head("arrow", GRAY)

def card(x, y, w, h, nid, title, sub=None, stroke="#555555", sw=1.5):
    """White op card with optional subtitle. Registered as a node when nid given."""
    drawer.rect(x, y, w, h, rx=6, ry=6, fill=CARD, stroke=stroke, stroke_width=sw,
                node_id=nid, node_kind="op", bbox=False)
    if sub:
        drawer.text(x + w / 2, y + h * 0.36, title, 12, fill=TXT, weight="bold", bbox=False)
        drawer.text(x + w / 2, y + h * 0.70, sub, 10, fill=SUB, bbox=False)
    else:
        drawer.text(x + w / 2, y + h / 2, title, 12, fill=TXT, weight="bold", bbox=False)

def flow(a, b):
    drawer.connect(a, "right", b, "left", stroke=GRAY, stroke_width=1.5, marker_end="arrow")

CLX, CLW = 40, 1320
LH, LGAP = 120, 20
NODE_IDS = ["L_model", "L_exec", "L_graph", "L_backend"]

def layer_y(i):
    return 88 + i * (LH + LGAP)

# ---- title ---------------------------------------------------------------
drawer.text(W / 2, 36, "llama.cpp — Architecture", 20, fill=TXT, weight="bold", bbox=False)

# ============================================================ Core Library
drawer.text(CLX, 70, "Core Library", 14, fill=TXT, weight="bold", anchor="start", bbox=False)

# Per-layer card contents: (x, y_off, w, h, nid, title, subtitle)
LAYER_CARDS = [
    [  # Model Layer
        (240, 350, 66, "m_model", "llama_model", "weights & hyperparams (GGUF)"),
        (610, 350, 66, "m_vocab", "llama_vocab", "tokenizer: BPE · SPM · WPM"),
        (980, 360, 66, "m_map", "Model Arch Mapping", "llama_model_mapping() → impl"),
    ],
    [  # Execution Layer
        (240, 350, 66, "e_ctx", "llama_context", "execution state · memory"),
        (610, 350, 66, "e_batch", "llama_batch / ubatch", "token input structures"),
        (980, 360, 66, "e_kv", "llama_kv_cache", "K/V vectors · avoid recompute"),
    ],
    [  # Computation Graph Layer
        (240, 500, 66, "g_cgraph", "ggml_cgraph", "DAG of ggml_tensor ops"),
        (760, 580, 66, "g_build", "Graph Building", "build_graph(): pooling + sampling"),
    ],
    [  # Backend Abstraction Layer
        (240, 300, 66, "b_backend", "ggml-backend", "SIMD + GPU offload"),
    ],
]
BACKEND_DEV = ["CPU", "CUDA", "Metal", "Vulkan", "SYCL"]

for li, (label, lfill, lstroke) in enumerate(LAYERS):
    y = layer_y(li)
    drawer.rect(CLX, y, CLW, LH, rx=8, ry=8, fill=lfill, stroke=lstroke, stroke_width=1.5,
                node_id=NODE_IDS[li], node_kind="layer", bbox=True)
    drawer.text(CLX + 18, y + 22, label, 14, fill=TXT, weight="bold", anchor="start", bbox=False)
    cy = y + 42
    for cx, cw, ch, nid, title, sub in LAYER_CARDS[li]:
        card(cx, cy, cw, ch, nid, title, sub, stroke=lstroke)
    if li == 3:  # backend devices
        for i, name in enumerate(BACKEND_DEV):
            card(562 + i * 156, cy, 140, 66, None, name, stroke=lstroke)

# layer dependency spine (top -> bottom)
drawer.connect(NODE_IDS[0], "bottom", NODE_IDS[1], "top", stroke=GRAY, stroke_width=1.5, marker_end="arrow")
drawer.connect(NODE_IDS[1], "bottom", NODE_IDS[2], "top", stroke=GRAY, stroke_width=1.5, marker_end="arrow")
drawer.connect(NODE_IDS[2], "bottom", NODE_IDS[3], "top", stroke=GRAY, stroke_width=1.5, marker_end="arrow")

# ============================================== Inference Execution Flow
iy = 648
drawer.rect(CLX, iy, CLW, 124, rx=8, ry=8, fill=PANEL, stroke=DIV, stroke_width=1,
            bbox=True, role="background")
drawer.text(CLX + 18, iy + 24, "Inference Execution Flow", 14, fill=TXT, weight="bold",
            anchor="start", bbox=False)
stages = [
    ("s1", "Token IDs", "input"),
    ("s2", "llama_batch", "batch API"),
    ("s3", "llama_ubatch", "internal rep"),
    ("s4", "build_graph", "construct DAG"),
    ("s5", "graph_compute", "backend exec"),
    ("s6", "logits / embeds", "output"),
]
sx0, sw, sgap = 60, 188, 30
for i, (nid, t, sub) in enumerate(stages):
    card(sx0 + i * (sw + sgap), iy + 46, sw, 56, nid, t, sub, stroke=NSTK)
for i in range(len(stages) - 1):
    flow(stages[i][0], stages[i + 1][0])

# ============================================== Server Architecture
sy_c = 786
drawer.rect(CLX, sy_c, CLW, 250, rx=8, ry=8, fill=PANEL, stroke=DIV, stroke_width=1,
            bbox=True, role="background")
drawer.text(CLX + 18, sy_c + 24, "Server Architecture — llama-server", 14, fill=TXT,
            weight="bold", anchor="start", bbox=False)

# server_context container (holds llama_context + active slots); center y = 912
drawer.rect(510, 822, 520, 180, rx=8, ry=8, fill=CARD, stroke=NSTK, stroke_width=1.5,
            node_id="sv_ctx", node_kind="block", bbox=True)
drawer.text(770, 845, "server_context", 12, fill=TXT, weight="bold", bbox=False)
drawer.text(770, 863, "holds llama_context + active slots", 10, fill=SUB, bbox=False)
drawer.text(770, 885, "server_slot — parallel sequences", 10, fill=SUB, bbox=False)
for i, x in enumerate((530, 695, 860)):
    card(x, 900, 150, 72, f"slot{i + 1}", f"slot {i + 1}", f"seq #{i + 1}", stroke=NSTK)

# I/O components (centered on y=912 to align with sv_ctx)
card(70, 867, 200, 90, "sv_routes", "server_routes", "HTTP interface · middleware", stroke=NSTK)
card(300, 867, 180, 90, "sv_queue", "server_queue", "task submission", stroke=NSTK)
card(1060, 867, 270, 90, "sv_resp", "server_response", "thread-safe results", stroke=NSTK)
flow("sv_routes", "sv_queue")
flow("sv_queue", "sv_ctx")
flow("sv_ctx", "sv_resp")

# ============================================================ Design Brief
# Declared from input.md's intent: Section 1 defines the four stacked Core
# Library layer bands (Model / Execution / Graph / Backend) as a top-down
# dependency/abstraction stack ("top depends on those below", arrows linking
# each band to the one beneath) -> band layout, vertical flow axis, palette
# from the S2 Okabe-Ito layer tints. The chain stays EMPTY: the dependency
# spine snaps band-border to band-border, and the arrowhead retraction leaves
# the path end in the 20px gutter (outside the target band box), so the
# contract checker cannot attribute those edges as inter-layer stages -- an
# unverifiable chain is not declared. The Inference Flow and Server sections
# are runtime-process panels (neutral gray, background role), not tinted
# library bands, so they stay outside the band contract.
BRIEF = DesignBrief(
    scheme="S2",
    layout="band",
    flow="top-down",
    palette_role={nid: ColorSpec(fill, stroke)
                  for nid, (_label, fill, stroke) in zip(NODE_IDS, LAYERS)},
    flow_chain=("L_model", "L_exec", "L_graph", "L_backend"),
)

# ============================================================ evaluate + save
score, report = evaluate_svg(drawer)
print(f"Quality Score: {score}")
for line in report:
    print(line)

qa = run_semantic_qa(drawer, expected_size=(W, H), brief=BRIEF)
print("Semantic QA:")
for line in qa.report():
    print(line)

save_svg(drawer.render(), str(OUT / f"{NAME}.svg"))
rasterize_svg(str(OUT / f"{NAME}.svg"), str(OUT / f"{NAME}.png"), width=W)
svg_to_pptx(drawer.render(), OUT / f"{NAME}.pptx")
BRIEF.write(str(OUT / "brief.json"))
print("Saved triplet to", OUT)
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/input.md
size: 1388
sha: 7618db4725f2d9581b66bd32c2216bc10db19133
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_llama_cpp_arch/input.md

```text
# llama.cpp Architecture

Draw a three-section top-to-bottom layout for the llama.cpp project.

## Section 1: Core Library

Four stacked layer bands (each a container with components):
- **Model Layer** — GGUF format, tokenizer, weight loading, quantization formats.
- **Execution Layer** — compute graph, tensor operations, memory management.
- **Graph Layer** — operator definitions, kernel dispatch, shape inference.
- **Backend Layer** — CPU (BLAS), CUDA, Metal, Vulkan backends.

The four layers form a dependency/abstraction stack (top depends on those
below), conveyed by arrows linking each band to the one beneath it.

## Section 2: Inference Execution Flow

A horizontal 6-stage pipeline showing the inference path:
prompt → tokenize → embed → forward pass → sample → detokenize → output.
Connect with solid arrows left → right.

## Section 3: Server Architecture (llama-server)

Routes → request queue → context (slots) → model eval → response.
Show how concurrent slots share the model context: a central
`server_context` block holds the active slots, with I/O components
(routes / queue on one side, model eval / response on the other) flanking it
on a single horizontal flow line.

Layout, palette, typography, and all geometry are yours to design — follow
the architecture-drawer skill's design system and let the evaluator guide
iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/brief.json
size: 575
sha: 8590b6b25a49d4d1b37518be7f686583cd96ec6b
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/brief.json

```text
{
  "scheme": "S1",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [],
  "palette_role": {
    "interface": {
      "fill": "#d5e1eb",
      "stroke": "#1b3a5c"
    },
    "coding_agent": {
      "fill": "#bbcedf",
      "stroke": "#1b3a5c"
    },
    "agent_core": {
      "fill": "#9bb9d1",
      "stroke": "#1b3a5c"
    },
    "ai_abstraction": {
      "fill": "#769ebf",
      "stroke": "#1b3a5c"
    },
    "llm_api": {
      "fill": "#aac8de",
      "stroke": "#1b3a5c"
    },
    "event_seq": {
      "fill": "#eeeeee",
      "stroke": "#b0b0b0"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/gen.py
size: 8221
sha: 24404d138413caec6bdc1d7174d5e66cf1fafa53
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/gen.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/gen.py

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/input.md
size: 2300
sha: 240cc721e28c18a86fe926d500674094351deff7
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260729_pi_agent_architecture/input.md

```text
# π Agent — Architecture Diagram

Draw an AI agent runtime architecture with labels INSIDE component rectangles
(no text overflow). Bilingual labels (English title + Chinese subtitle).

## Layout

Left column: 4 horizontal layer bands stacked top→bottom, each a container
holding 3–4 component cards. Below the bands sit two full-width boxes (LLM API,
then an event-sequence info box).

1. **① 交互界面层 · Interface** (no package) — TUI (交互式终端), RPC (JSONL 协议),
   Print (打印 / JSON), SDK (createAgentSession()).
2. **② 编码智能体层 · pi-coding-agent** (`@earendil-works/pi-coding-agent`) —
   AgentSession (智能体协调器), SessionManager (持久化 · 压缩),
   ExtensionRunner (扩展 · 自定义工具), ResourceLoader (技能 · 模板 · 主题).
3. **③ 智能体核心层 · pi-agent-core** (`@earendil-works/pi-agent-core`) —
   Agent / agentLoop (回合生命周期管理), AgentContext (systemPrompt · messages · tools),
   AgentEvent (事件序列 · 工具执行).
4. **④ AI 抽象层 · pi-ai** (`@earendil-works/pi-ai`) — OpenAI (GPT-4o · o3),
   Anthropic (Claude 3.5/4), Google (Gemini).

Below the layers:
- **LLM API box** — dashed border, "LLM API · OpenAI / Anthropic / Google 统一流式调用".
- **Event sequence example** — a monospace info box showing one `prompt()` call's
  event lifecycle (agent_start → turn_start → message_start … → tool_execution … →
  agent_end) with Chinese explanations per line.

## Flow

- **Left spine (down)** — 请求下行 ↓: request travels top → bottom through all
  4 layers and into the LLM API box.
- **Right spine (up)** — ↑ AgentEvent 事件流: event stream bubbles bottom → top
  back up from the LLM API box through every layer. Use a visually distinct
  color for it (e.g. an event/attention accent vs the request's primary dark).
- **Tool execution arrow** (dashed, far right of the Agent Core band) — points
  outward to "Bash · 文件操作".

Flow spines must route OUTSIDE the card area — never slice through a band's
filled rectangle or the LLM box interior. Layout, exact palette, typography,
and all geometry are yours to design — follow the architecture-drawer skill's
design system and let the evaluator guide iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/brief.json
size: 553
sha: 4f4361f9d9c819352e61e5a3d68e8f1acdcebfd8
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/brief.json

```text
{
  "scheme": "S1",
  "layout": "band",
  "flow": "top-down",
  "flow_chain": [
    "api_server",
    "llm_engine",
    "exec_layer"
  ],
  "palette_role": {
    "api_server": {
      "fill": "#e8eef3",
      "stroke": "#1b3a5c"
    },
    "llm_engine": {
      "fill": "#d5e1eb",
      "stroke": "#1b3a5c"
    },
    "kv_cache": {
      "fill": "#e8eef3",
      "stroke": "#1b3a5c"
    },
    "exec_layer": {
      "fill": "#b8cde0",
      "stroke": "#1b3a5c"
    },
    "optimizations": {
      "fill": "#e8eef3",
      "stroke": "#1b3a5c"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/gen.py
size: 10474
sha: 95d1abf76845d8573071c5b85adf5b3fc59b339b
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/gen.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/gen.py

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/input.md
size: 2223
sha: 43870d14ca45fb6d0657b41d6d7c764e06741cd8
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260730_vllm_arch/input.md

```text
# vLLM — High-Throughput LLM Serving with PagedAttention

Draw a layered top-to-bottom pipeline (request → response) for the vLLM
inference serving stack, with the PagedAttention / paged KV-cache abstraction
on the right.

## Layers (top → bottom)

1. **Title bar** — "vLLM — High-Throughput LLM Serving with PagedAttention",
   subtitle "PagedAttention · Continuous Batching · High Throughput".
2. **Client** — single node: "Client / Application" (OpenAI API · HTTP / SDK).
3. **API Server** — container with two nodes: "FastAPI / ASGI Server" (request
   routing · streaming) and "OpenAI-compatible API"
   (/v1/completions · /v1/chat/completions).
4. **LLM Engine (Core)** — left container with three nodes:
   - AsyncLLMEngine (top center)
   - Scheduler (left, bullets: FCFS + priority scheduling · continuous batching ·
     preemption on KV-cache OOM · decode-step orchestration)
   - BlockManager (right, bullets: logical ↔ physical blocks · block tables
     (paging) · copy-on-write fork · reference counting)
5. **Paged KV Cache (GPU Memory)** — right container: logical blocks row,
   block table mapping (L0→P3 etc.), and a physical KV cache blocks grid
   showing allocated vs free blocks (allocated need not be contiguous → low
   fragmentation).
6. **Execution Layer (GPU workers)** — bottom container: Worker → ModelRunner →
   PagedAttention Kernel, plus an Optimizations & CUDA Kernels band
   (continuous batching · prefix caching · chunked prefill · speculative
   decoding; quantization AWQ/GPTQ/FP8 · tensor/pipeline parallelism · LoRA
   multi-adapter · prefix-aware scheduling).

A small legend at the bottom distinguishes the two edge kinds.

## Edges

- **Solid** (data / request flow): client → openai_api; fastapi → openai_api;
  openai_api → async_engine → scheduler → worker → modelrunner → pagedattn →
  phys_blocks.
- **Dashed** (cache / block management): scheduler ↔ blockmanager (alloc /
  free); blockmanager ↔ phys_blocks (manage physical).

English only. Layout, palette, typography, and all geometry are yours to
design — follow the architecture-drawer skill's design system and let the
evaluator guide iteration.
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/brief.json
size: 1373
sha: 39d140106a50287dcfaf1c320102930301ea2642
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/brief.json

```text
{
  "scheme": "flowchart-roles",
  "layout": "node",
  "flow": "top-down",
  "flow_chain": [],
  "palette_role": {
    "start": {
      "fill": "#d5e8d4",
      "stroke": "#82b366"
    },
    "hook": {
      "fill": "#ffe6cc",
      "stroke": "#d79b00"
    },
    "checkout": {
      "fill": "#e1d5e7",
      "stroke": "#9673a6"
    },
    "build_ok": {
      "fill": "#fff2cc",
      "stroke": "#d6b656"
    },
    "lint": {
      "fill": "#e1d5e7",
      "stroke": "#9673a6"
    },
    "lint_ok": {
      "fill": "#fff2cc",
      "stroke": "#d6b656"
    },
    "tests": {
      "fill": "#e1d5e7",
      "stroke": "#9673a6"
    },
    "test_ok": {
      "fill": "#fff2cc",
      "stroke": "#d6b656"
    },
    "staging": {
      "fill": "#dae8fc",
      "stroke": "#6c8ebf"
    },
    "smoke": {
      "fill": "#dae8fc",
      "stroke": "#6c8ebf"
    },
    "smoke_ok": {
      "fill": "#fff2cc",
      "stroke": "#d6b656"
    },
    "deploy": {
      "fill": "#dae8fc",
      "stroke": "#6c8ebf"
    },
    "released": {
      "fill": "#d5e8d4",
      "stroke": "#82b366"
    },
    "notify": {
      "fill": "#dae8fc",
      "stroke": "#6c8ebf"
    },
    "m1": {
      "fill": "#b0b0b0",
      "stroke": "#666666"
    },
    "m2": {
      "fill": "#b0b0b0",
      "stroke": "#666666"
    },
    "failed": {
      "fill": "#d5e8d4",
      "stroke": "#82b366"
    }
  }
}
```

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/gen.py
size: 12521
sha: 185808cd55695555962ab157415e75fa23e006e3
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/gen.py

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/gen.py

## File: plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/input.md
size: 2610
sha: 0cee353dd10396597e01516fdc6aeef9249d9730
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/input.md

Content is not inlined in the catalog. Read the upstream file: https://github.com/andy1314chen/architecture-drawer/blob/main/plugins/architecture-drawer/skills/architecture-drawer/evals/20260802_100000_cicd_pipeline_flow/input.md

## File: README.md
upstream: https://github.com/andy1314chen/architecture-drawer/blob/main/README.md

````text
# architecture-drawer

English · [简体中文](README.zh_CN.md)

A skill for [Claude Code](https://code.claude.com), Codex, Open Code, Pi Agent, and other AI coding agents: turn a text description of your system architecture into an **editable PowerPoint architecture diagram**.

![License](https://img.shields.io/badge/license-MIT-blue)

---

## What it is

Turn **text descriptions** of an architecture into **editable PPT diagrams**: the agent generates an SVG from your description, auto-validates the layout, then exports to native PowerPoint shapes.

### vs. direct image generation

| | This project | Nano Banana / GPT-Image etc. |
|---|---|---|
| Output | **Editable PPT** (every shape draggable, recolorable, retextable) | Flattened image |
| Control | High (code-generated, precisely adjustable) | Low (prompt-driven, hard to reproduce) |
| Iteration | Fine-tune directly in PPT | Regenerate from scratch |
| Cost | Low | High (per-image billing) |

## Showcase

All diagrams below were generated entirely from text descriptions by the skill, then scored by the 13-dimension evaluator (each scored ≥76/100). They double as the regression suite under `evals/` — including the first non-architecture case (a process flowchart).

### vLLM — High-Throughput LLM Inference Serving (PagedAttention)

![](docs/showcase/vllm_arch.png)

Six-layer request pipeline (client → API server → engine → paged KV cache → execution → optimizations). Solid edges = data flow; dashed = cache/block management. *Scheme S1 Monochrome Blue.*

### MLIR AI Compiler — Multi-Stream Execution Pipeline

![](docs/showcase/mlir_pipeline.png)

A 4-layer × multi-column matrix (graph optimization → transformation → lowering → codegen) with vertical-fusion grouping and a concurrent multi-stream overlap timeline. *8-accent categorical palette.*

### Agent Infrastructure — Layered Architecture

![](docs/showcase/agent_infra_architecture.png)

Five horizontal layers (application → orchestration → core capabilities → execution → infrastructure) with a cross-cutting security/observability band. Bilingual CN/EN labels. *Neutral grays + 5 colored core modules.*

### CI/CD Deployment Pipeline — Process Flowchart

![](docs/showcase/cicd_pipeline_flow.png)

The first non-architecture case: a top-to-bottom **process flowchart** with four quality-gate decisions (Build → Lint/SAST → Tests → Smoke) whose "No" branches converge via gray junction merge points onto a single Failed terminator. Green terminators · yellow decision diamonds · orange I/O hexagon · purple double-border subprocesses. *Flowchart role palette (color = role).*

## Best Practices

1. **Start with a clear text description.** Before coding, describe the architecture in prose—how many layers, what components each layer has, how they connect, and any special annotations. A crisp text spec (like the specs in `evals/*/input.md`) is the single biggest predictor of a quality diagram. For open-source projects, you can use the system architecture description from [DeepWiki](https://deepwiki.com).
2. **Let the skill generate.** Submit the text description to the skill and let it generate the initial `gen.py` and SVG. The evaluator automatically catches overlaps, dangles, and crossings.
3. **The skill auto-reviews the score.** If the score is ≥80, the diagram is structurally sound. If <80, the agent can automatically fix layout issues via `auto_refine` or by iterating on the evaluator report.
4. **Export to PPTX for final polish.** Run `svg_to_pptx()` to get an editable PowerPoint file. Tweak colors, fonts, arrows, and layout there to match your brand or publication style—these belong in the presentation layer, not the generator code.

Suggested workflow: first discuss with DeepWiki or your agent to produce a clear text description of the system architecture, then use this skill to quickly generate a PPTX diagram, and finally fine-tune colors, labels, and other details directly in PPT.

## Install (Claude Code)

This repo is a [plugin marketplace](https://code.claude.com/docs/en/plugin-marketplaces). Add it and install the plugin:

```
/plugin marketplace add Andy1314Chen/architecture-drawer
/plugin install architecture-drawer@architecture-drawer
```

Or from the CLI:

```bash
claude plugin marketplace add Andy1314Chen/architecture-drawer
claude plugin install architecture-drawer@architecture-drawer
```

Scope with `--scope project` (shared via version control) or `--scope local` (gitignored). Default is `user`.

### Codex CLI

> Codex CLI fully supports the [Agent Skills](https://agentskills.io) directory structure.

Copy the skill directory into Codex's skills folder (usually `~/.codex/skills/`):

```bash
cp -r plugins/architecture-drawer/skills/architecture-drawer ~/.codex/skills/architecture-drawer
```

Or install project-scoped (recommended):

```bash
mkdir -p .codex/skills
cp -r plugins/architecture-drawer/skills/architecture-drawer .codex/skills/
```

Once installed, ask Codex naturally — the workflow in `SKILL.md` is consumed automatically:

```
> Draw the architecture of vLLM and export to PPTX
```

### Other agent platforms (Gemini CLI, Cursor, Copilot)

Each skill is a standalone [Agent Skills spec](https://agentskills.io) directory. Copy it into your platform's skills location (typically `.agents/skills/`):

| Platform | Default skills path |
|---|---|
| Gemini CLI | `~/.gemini/skills/` |
| Cursor (@rules) | `.cursorrules` or `cursor/skills/` |
| Copilot CLI | Per-platform instructions |

```bash
cp -r plugins/architecture-drawer/skills/architecture-drawer .agents/skills/architecture-drawer
```

## Dependencies

The agent generates a `gen.py` that imports four pure-Python modules (`svg_utils.py`, `evaluator.py`, `semantic_qa.py`, `svg2pptx.py`) co-located in the skill. You don't write this code — the agent does. Install these once so generated diagrams can render and export:

| Dependency | Required by | Install |
|---|---|---|
| `python-pptx >= 1.0` | PPTX export (`svg2pptx.py`) | `pip install python-pptx` |
| `rsvg-convert` | PNG rasterization (`rasterize_svg`) | `apt install librsvg2-bin` / `brew install librsvg` |
| `pytest >= 8` | Running the test suite | `pip install pytest` |

## Testing

The suite is layered so each layer is cheap, deterministic, and covers a distinct failure mode:

| Layer | Command | What it gates | Runs in CI |
|-------|---------|---------------|-----------|
| **Deterministic regression** | `pytest` | each `evals/<name>/gen.py` scores ≥ its threshold and matches its golden SVG | ✅ always |
| **Spec compliance** | `pytest` | `SKILL.md` frontmatter, name↔directory, relative refs, core scripts present | ✅ always |
| **Doc ↔ API drift guard** | `pytest` | every `drawer.<m>(` documented in `SKILL.md`/`references/*.md` exists on `SVGDrawer`; curated public API importable | ✅ always |
| **Agent replay** | `pytest --agent-replay` | install the skill into a leak-free sandbox, let the **Pi coding agent** author `gen.py`, assert score ≥80 + full SVG/PPTX/PNG/brief.json artifact quartet, SVG passing semantic QA against its `brief.json` contract | nightly / local |

The agent-replay layer is the closest to real usage: the skill is *installed* (never inlined), a real agent discovers it via its native skill mechanism, and the harness — not the agent — re-runs the produced `gen.py` deterministically. It needs the [`pi`](https://pi.dev) CLI and a provider key; backend wiring lives in `tests/agent_backends.py`. Pin **both** the provider and the model (`--agent-provider zai --agent-model glm-5.3`, or `PI_AGENT_PROVIDER`/`PI_AGENT_MODEL`) — the headless run otherwise inherits pi's interactive default provider, which may lack credentials and fail with an opaque upstream 403; a bare `--model` id can also be ambiguous across providers. Other options: `--agent-iter N` caps the stateless refine rounds (default 3), `--agent-eval <name>` restricts the run to one frozen eval, and `--agent-case <dir>` replays an **ad-hoc case outside the frozen se
````
