# Mermaid Diagram Standards — Engineering Documentation

> Purpose: Ensure Mermaid diagrams inside `/docs/*` stay small, consistent, and maintainable.
> Scope: Applies to all documentation updates and code audits.
> Default: Prefer multiple small diagrams over one large one.

---

## 0) Non-negotiables

- **Diagrams must be readable in a PR diff** (even if this repo doesn’t commit). If the diagram is too large to review quickly, it must be split.
- **Never create “everything” diagrams.** Use layers and link between them via headings.
- **Do not invent components.** Only document what is evidenced by code/docs.
- **One diagram = one purpose.** If it explains two things, split it.

---

## 1) Diagram layers (choose the correct layer)

Use these layers consistently:

### L0 — Context (Audience: non-technical + new dev)
- **Question answered:** “What is this system and what external actors/systems touch it?”
- **Allowed elements:** People/roles, external systems, the platform boundary.
- **Forbidden:** internal modules, tables, classes, endpoints.
- **Target size:** 7–10 nodes.

### L1 — Containers (Audience: engineering/product)
- **Question answered:** “What are the major apps/services/datastores and how do they talk?”
- **Allowed:** apps, services, datastores, queues, third parties.
- **Forbidden:** internal classes/functions.
- **Target size:** 12–18 nodes.

### L2 — Components (Audience: dev onboarding)
- **Question answered:** “Inside *one* container, what are the major modules and responsibilities?”
- **Rule:** L2 diagrams **must not** span more than one container.
- **Target size:** 10–16 nodes.

### L3 — Flows (Audience: debugging/behaviour)
- **Question answered:** “What happens when X happens?”
- **Format:** `sequenceDiagram` preferred.
- **Rule:** one scenario only (e.g., “Place Order”, “Sync Invoice”).
- **Target size:** 8–25 messages.

---

## 2) When to split a diagram

Split if any of the following is true:

- Flowchart exceeds **18 nodes** or **22 edges**.
- Diagram requires zooming to read in a typical editor window.
- More than **2 bounded contexts** are involved.
- Lines cross heavily or there are “hairball” clusters.

**Splitting patterns (preferred):**
- Split by **layer** (L1 vs L2).
- Split by **domain** (Orders vs Pricing vs Integrations).
- Split by **scenario** (Checkout vs Reorder vs Returns).

---

## 3) Mermaid conventions

### 3.1 Orientation
- Architecture maps: `flowchart LR`
- Component maps: `flowchart TB` (only if it reads better)
- Behaviour: `sequenceDiagram`

### 3.2 Node IDs and labels
- Node IDs: `snake_case` only.
- Human labels: Title Case.

Example:
```mermaid
flowchart LR
  yii_app[Yii2 App]
  erp[(ERP Database)]
```

### 3.3 Use boundaries
Always group by boundaries using `subgraph`.

Example:
```mermaid
flowchart LR
  subgraph Platform[Platform]
    api[Public API]
    yii_app[Yii2 App]
  end

  subgraph ERP[ERP]
    erp[ERP System]
  end

  api --> yii_app --> erp
```

### 3.4 Arrow meaning
Use arrows consistently:
- `-->` synchronous call / request
- `-.->` async event / queued / best-effort signal
- `==>` critical async pipeline (rare; only if you’re consistent across docs)

If mixed semantics are used, add a tiny legend.

### 3.5 Text on edges
Edge labels should be **short** and **verb-based**:
- Good: `Place Order`, `Sync Stock`, `Fetch Pricing`
- Bad: long sentences, implementation detail, function names.

---

## 4) Styling rules (minimal, consistent)

Keep styling extremely light. Use at most these classes:
- `external` (outside parties)
- `system` (major apps/services)
- `data` (datastores)
- `queue` (queues/brokers)

Template:
```mermaid
flowchart LR
classDef external stroke-width:1.5px;
classDef system stroke-width:1.5px;
classDef data stroke-dasharray:3 3,stroke-width:1.5px;
classDef queue stroke-dasharray:6 3,stroke-width:1.5px;

  customer[Customer]:::external
  api[Public API]:::system
  db[(MySQL)]:::data
  q[[Queue]]:::queue

  customer --> api --> db
  api -.-> q
```

**Rule:** Do not introduce colours/themes per repo. Keep it uniform.

---

## 5) Diagram headers (metadata block)

Every diagram must include a metadata comment block directly above it:

```mermaid
%% Title: Orders — Web to ERP (L3)
%% Layer: L3
%% Owner: Engineering
%% Last verified: YYYY-MM-DD HH:MM (Europe/London)
%% Scope: Place an order from web checkout through ERP creation
%% Excludes: Payment capture, fulfilment, returns
```

If you update a diagram, update **Last verified**.

---

## 6) Where diagrams live in `/docs`

- Diagrams are embedded in the relevant markdown file (e.g., `/docs/ARCHITECTURE.md`, `/docs/SECURITY.md`).
- If a diagram is reused in multiple docs, place it in:
  - `/docs/diagrams/<layer>/<name>.mmd`
  - and embed via copy/paste (Mermaid include mechanisms vary per tooling; avoid assumptions).

**Rule:** Don’t create new doc locations outside `/docs`.

---

## 7) Rules for code-audit generated `ARCHITECTURE.md` updates

When an AI agent generates or updates `ARCHITECTURE.md` during an audit:

1. Add/maintain a short **System Map** section.
2. Prefer this structure:
   - **L0 Context** (one small diagram)
   - **L1 Containers** (one medium diagram)
   - **L2 Components** (one per major container)
   - **L3 Key Flows** (multiple small sequences)
3. If an existing diagram is “too big”, replace it with:
   - one higher-level diagram, plus
   - 2–5 smaller diagrams beneath it.

---

## 8) Sequence diagram rules (L3)

- Use `autonumber`.
- Participants are nouns, not classes.
- Avoid internal method names.

Template:
```mermaid
sequenceDiagram
  %% Title: Checkout — Place Order (L3)
  %% Layer: L3
  %% Owner: Engineering
  %% Last verified: YYYY-MM-DD HH:MM (Europe/London)
  %% Scope: From checkout submit to ERP order creation
  %% Excludes: Payment capture

  autonumber
  actor Customer
  participant Store as Magento
  participant API as Public API
  participant App as Yii2 App
  participant ERP as ERP

  Customer->>Store: Submit Checkout
  Store->>API: Create Order
  API->>App: Validate + Price
  App->>ERP: Post Sales Order
  ERP-->>App: Order Number
  App-->>API: Success
  API-->>Store: Confirmation
```

If a sequence exceeds ~25 messages, split by sub-scenario:
- “Validate basket”
- “Price resolution”
- “ERP post + response handling”

---

## 9) Updating diagrams when code changes

If any change affects:
- business logic
- API contracts
- integrations
- authentication
- data handling
- background jobs

…then you must:
1. Identify **which layer(s)** change.
2. Update only the impacted diagrams.
3. Update the **Last verified** timestamp.
4. Add a short note under the diagram:
   - “Change note: <1–2 lines>”

---

## 10) Anti-patterns (do not do these)

- ❌ One diagram showing every module, table, queue, and endpoint.
- ❌ Diagrams that rely on colours to convey meaning.
- ❌ Edge labels like full sentences.
- ❌ Using Mermaid to document exact DB schemas (use tables/docs instead).
- ❌ Mixing L1 + L2 detail in one diagram.

---

## 11) AI Operating Instruction (copy/paste prompt)

When performing documentation audits or updates, include this instruction:

> Follow `/docs/MERMAID_DIAGRAM_STANDARDS.md`.  
> Keep diagrams within node/edge limits.  
> Use the L0–L3 layers.  
> Split large diagrams into smaller ones.  
> Update metadata headers and the “Last verified” timestamp.

---

## 12) Quick checklist

- [ ] Correct layer (L0/L1/L2/L3)
- [ ] Under size limits
- [ ] Uses `subgraph` boundaries
- [ ] Short, consistent edge labels
- [ ] Minimal styling (only approved classes)
- [ ] Metadata header present
- [ ] “Last verified” updated

