# RTL Diagram Generation Guidelines

## CRITICAL RULES (NEVER VIOLATE)

1. **EVERY node MUST be connected** - No orphan nodes. Every element must have at least one edge.
2. **Lines are ALWAYS orthogonal** - Use `splines=ortho` always.
3. **No wire cutting** - Use `taillabel`/`headlabel` with spaces, NEVER `xlabel` or `label`.
4. **White-box detail** - Show internal registers, logic, and operations inside modules.

---

## Agent Workflow

You are generating an RTL block diagram. Follow these steps:

### Step 1: Read the Verilog Source Files
Read all `.v` files in the source directory.

### Step 2: Parse the RTL Structure

**Identify Modules:** Look for `module <name> (...);`

**Identify Instances:** Look for `<module_type> <instance_name> (...);`

**Identify Top Module:** The module that is NEVER instantiated by others.

**Identify Clock Domains:** Look for `clk`, `wclk`, `rclk`, `*_clk` signals.

**Identify Internal Structure:** For each module, find:
- Registers (`reg`, `always @(posedge clk)`)
- Combinational logic (`assign`, `always @(*)`)
- Wire widths (`[N:0]`)

### Step 3: Design the Diagram

**Clustering Strategy:**
1. Group by clock domain (critical for CDC designs)
2. Group by functional unit (ALU, Memory, Control)
3. Group by pipeline stage (IF, ID, EX, MEM, WB for CPUs)

**White-Box Detail Level (REQUIRED):**
- Show individual registers with bit widths: `wbin [label="{ wbin | Binary[4:0] }"]`
- Show logic operations: `adder [label="{ +1 Logic | !full }"]`
- Show conversion blocks: `gray [label="{ Gray Conv | bin^(bin>>1) }"]`
- Show detect/compare logic: `detect [label="Full\\nDetect", shape=diamond]`
- Show CDC flip-flops individually: `q1 [label="{ q1 | FF1 }"]`, `q2 [label="{ q2 | FF2 }"]`

**Connection Rule (CRITICAL):**
- EVERY I/O port MUST connect to a module
- EVERY register MUST have input and output edges
- EVERY logic block MUST show data flow
- Internal wires within clusters should be connected

**What to Exclude:**
- Testbenches (`*_tb`, `tb_*`)

### Step 4: Generate DOT Code
Use the style guide below.

### Step 5: Call render_diagram
Call the `render_diagram` tool with your DOT code.

---

## DOT Style Guide (STRICT)

### Graph Attributes (MANDATORY)

```dot
digraph "Design_Name" {
    graph [
        rankdir=LR,
        splines=ortho,
        nodesep=1.0,
        ranksep=2.0,
        fontname="Arial",
        compound=true,
        overlap=false,
        sep="+25",
        bgcolor="white"
    ];
    node [fontname="Arial", shape=record, style="filled,rounded", penwidth=1.2, fontsize=10];
    edge [fontname="Arial", fontsize=9, penwidth=1.2, arrowsize=0.7, color="#424242"];

    // Title (Optional - for complex designs)
    labelloc="t";
    label=<<B><FONT POINT-SIZE="18">Design Title</FONT></B><BR/>Parameters | Description>;
}
```

### Cluster Labels (ALWAYS BOLD)

Use HTML-like labels for bold cluster titles:

```dot
subgraph cluster_name {
    label=<<B>Cluster Title</B>>;
    // ...
}
```

### Clustering Hierarchy

**Level 1 - Clock Domains (largest):**
```dot
subgraph cluster_write_domain {
    label=<<B>Write Clock Domain (wclk)</B>>;
    style="filled,rounded";
    fillcolor="#E3F2FD";
    color="#90CAF9";
    margin=25;
}

subgraph cluster_read_domain {
    label=<<B>Read Clock Domain (rclk)</B>>;
    style="filled,rounded";
    fillcolor="#FFEBEE";
    color="#EF9A9A";
    margin=25;
}
```

**Level 2 - I/O Interface (dashed border):**
```dot
subgraph cluster_write_io {
    label="Write Interface";
    style="filled,dashed";
    fillcolor="#BBDEFB";
    margin=15;
    // I/O ports here
}
```

**Level 3 - Modules:**
```dot
subgraph cluster_module_name {
    label=<<B>module_name</B>>;
    style="filled,rounded";
    fillcolor="#E1F5FE";
    margin=20;
    // Module internals here
}
```

**Level 4 - CDC Synchronizers:**
```dot
subgraph cluster_sync_name {
    label=<<B>sync_name</B>>;
    style="filled,rounded";
    fillcolor="#FFF3E0";
    margin=15;
}
```

### Node Shapes & Colors

| Component | Shape | Fill Color | Example |
|-----------|-------|------------|---------|
| Data I/O | `parallelogram` | `#B2DFDB` | `din [label="din[7:0]", shape=parallelogram, fillcolor="#B2DFDB"]` |
| Control I/O | `parallelogram` | `#C8E6C9` | `enable [label="enable", shape=parallelogram, fillcolor="#C8E6C9"]` |
| Clock/Reset | `parallelogram` | `#FFCCBC` | `clk [label="clk", shape=parallelogram, fillcolor="#FFCCBC"]` |
| Registers | `record` | `#FFF9C4` | `reg [label="{ name \| bits }", fillcolor="#FFF9C4"]` |
| Logic | `record` | `#E8F5E9` | `logic [label="{ Op \| desc }", fillcolor="#E8F5E9"]` |
| Comparator | `diamond` | `#FFF9C4` | `cmp [label="Detect", shape=diamond, fillcolor="#FFF9C4"]` |
| CDC FF | `record` | `#FFE0B2` | `ff [label="{ q1 \| FF1 }", fillcolor="#FFE0B2"]` |
| Memory | `record` | `#FFF9C4` | `mem [label="{ mem \| size }", fillcolor="#FFF9C4", width=2.5]` |
| Address | `parallelogram` | `#E0E0E0` | `addr [label="addr[3:0]", shape=parallelogram, fillcolor="#E0E0E0"]` |
| Flag Output | `parallelogram` | `#FFCDD2` | `flag [label="full", shape=parallelogram, fillcolor="#FFCDD2"]` |

### White-Box Node Details

Show internal structure using record labels:

```dot
// Register with bit width
wbin [label="{ wbin | Binary[4:0] }", fillcolor="#FFF9C4"];

// Logic with operation
adder [label="{ +1 Logic | !full }", fillcolor="#E8F5E9"];

// Conversion logic
gray [label="{ Gray Conv | bin^(bin>>1) }", fillcolor="#E8F5E9"];

// Memory with dimensions
mem [label="{ mem[0:15] | [7:0] x 16 }", fillcolor="#FFF9C4", width=2.5];

// Multi-line labels for complex nodes
detect [label="Full\\nDetect", shape=diamond, fillcolor="#FFF9C4"];
```

### Edge Labels (CRITICAL - Prevent Wire Cutting)

**NEVER use `xlabel`** - it causes wires to cut through labels.

**ALWAYS use `taillabel` or `headlabel` with trailing/leading spaces:**

```dot
// Label at source (trailing spaces push label away from wire)
a -> b [taillabel="signal  "];

// Label at destination (leading spaces push label away)
a -> b [headlabel="  signal"];

// With bit widths
data_reg -> mem [taillabel="wdata[7:0]  ", penwidth=2.0];
```

### Edge Types

**Data Path (thick):**
```dot
din -> reg [taillabel="data  ", penwidth=2.0];
```

**Control/Feedback (dashed, colored):**
```dot
logic -> reg [headlabel="  next", style=dashed, color="#1565C0"];
```

**CDC Crossing (green, thick, no constraint):**
```dot
wptr -> sync_ff [taillabel="wptr(Gray)  ", color="#388E3C", penwidth=2.0, constraint=false];
```

**Internal connection (default):**
```dot
a -> b;
```

### Color Palette Reference

**Domain Backgrounds:**
- Write Domain: `fillcolor="#E3F2FD"`, `color="#90CAF9"`
- Read Domain: `fillcolor="#FFEBEE"`, `color="#EF9A9A"`
- Memory: `fillcolor="#FFF8E1"`, `color="#FFE082"`

**Module Backgrounds:**
- Write-side module: `#E1F5FE`
- Read-side module: `#FCE4EC`
- CDC Sync: `#FFF3E0`

**I/O Interface (dashed):**
- Write interface: `#BBDEFB`
- Read interface: `#FFCDD2`

**Nodes:**
- Registers: `#FFF9C4` (yellow)
- Logic: `#E8F5E9` (green)
- CDC FFs: `#FFE0B2` (orange)
- Data I/O: `#B2DFDB` (teal)
- Control I/O: `#C8E6C9` (light green)
- Clock/Reset: `#FFCCBC` (peach)
- Address: `#E0E0E0` (gray)
- Flag outputs: `#FFCDD2` (pink)

**Edges:**
- Default: `#424242`
- Write feedback: `#1565C0` (blue)
- Read feedback: `#C62828` (red)
- CDC: `#388E3C` (green)

---

## Complete Template

```dot
digraph "Design_Name" {
    graph [rankdir=LR, splines=ortho, nodesep=1.0, ranksep=2.0,
           fontname="Arial", compound=true, overlap=false, sep="+25", bgcolor="white"];
    node [fontname="Arial", shape=record, style="filled,rounded", penwidth=1.2, fontsize=10];
    edge [fontname="Arial", fontsize=9, penwidth=1.2, arrowsize=0.7, color="#424242"];

    labelloc="t";
    label=<<B><FONT POINT-SIZE="18">Design Title</FONT></B><BR/>Parameters>;

    // ========== CLOCK DOMAIN 1 ==========
    subgraph cluster_domain1 {
        label=<<B>Clock Domain 1 (clk1)</B>>;
        style="filled,rounded";
        fillcolor="#E3F2FD";
        color="#90CAF9";
        margin=25;

        // I/O Interface
        subgraph cluster_io1 {
            label="Interface 1";
            style="filled,dashed";
            fillcolor="#BBDEFB";
            margin=15;
            // I/O ports
        }

        // Module
        subgraph cluster_module1 {
            label=<<B>module_name</B>>;
            style="filled,rounded";
            fillcolor="#E1F5FE";
            margin=20;
            // Registers, logic, etc.
        }

        // CDC Sync
        subgraph cluster_sync {
            label=<<B>sync_name</B>>;
            style="filled,rounded";
            fillcolor="#FFF3E0";
            margin=15;
            // Sync FFs
        }
    }

    // ========== SHARED RESOURCES ==========
    subgraph cluster_shared {
        label=<<B>Shared Resource</B><BR/>(Description)>;
        style="filled,rounded";
        fillcolor="#FFF8E1";
        color="#FFE082";
        margin=20;
        // Memory, etc.
    }

    // ========== CONNECTIONS ==========
    // Data paths (thick)
    // Control paths (dashed)
    // CDC paths (green, constraint=false)
}
```

---

## Checklist Before Rendering (MANDATORY)

### Connection Verification (CRITICAL)
- [ ] **EVERY I/O parallelogram has at least one edge** (no floating inputs)
- [ ] **EVERY register node has input AND output edges**
- [ ] **EVERY logic block connects to registers or I/O**
- [ ] **CDC FFs form a chain** (q1 -> q2)
- [ ] **Clock/reset ports connect to their target modules**

### Layout Rules
- [ ] Graph has `nodesep=1.0`, `ranksep=2.0`, `sep="+25"`
- [ ] `splines=ortho` is set (NEVER remove)
- [ ] All cluster labels use `<<B>Title</B>>` for bold
- [ ] Clock domains have `margin=25`
- [ ] Modules have `margin=20`

### Edge Labeling (Prevents Wire Cutting)
- [ ] All edge labels use `taillabel="signal  "` (trailing spaces) or `headlabel="  signal"` (leading spaces)
- [ ] **NO `xlabel` used anywhere** (causes wire to cut through label)
- [ ] **NO `label` on edges** (use taillabel/headlabel instead)

### White-Box Detail
- [ ] Registers show bit widths: `{ name | [N:0] }`
- [ ] Logic shows operation: `{ +1 | condition }`
- [ ] CDC sync shows individual FFs: `{ q1 | FF1 }`, `{ q2 | FF2 }`
- [ ] Comparators use diamond shape

### CDC Paths
- [ ] CDC edges have `color="#388E3C"` (green)
- [ ] CDC edges have `penwidth=2.0`
- [ ] CDC edges have `constraint=false`

### Style
- [ ] Colors follow the palette consistently
- [ ] No testbench modules included
- [ ] Data paths use `penwidth=2.0`
- [ ] Control/feedback paths use `style=dashed`
