# Architecture Docs

> Use this skill when creating, updating, or maintaining ARCHITECTURE.md files, when users ask about "my architecture documentation" or "architecture", when generating presentations/slides/PowerPoint from architecture documentation, when generating diagrams from architecture documentation, when validating/checking/auditing architecture (including BIAN alignment, META layers, standards compliance), or when answering questions about documented components, data structures, integrations, security, performance, deployment, technology stack, or architectural decisions

- Skill: `diegosouzapw/architecture-docs-2` (Agent Skill, multi-file: 2 files)
- Install (CLI): `npx skillmds@latest add diegosouzapw/architecture-docs-2`
- Raw SKILL.md: https://api.skillmd.com/api/skills/diegosouzapw/architecture-docs-2/raw
- Safety review: pending
- Works with: Claude Code, Claude.ai, OpenAI Codex
- Category: Security
- Author: diegosouzapw (https://skillmd.com/u/diegosouzapw)
- Updated: 2026-09-22
- Page: https://skillmd.com/skills/diegosouzapw/architecture-docs-2

---


# Architecture Documentation Skill

This skill provides comprehensive guidelines for creating and maintaining ARCHITECTURE.md files using the standardized template from ARCHITECTURE_DOCUMENTATION_GUIDE.md.

## When This Skill is Invoked

Automatically activate when:
- User asks to create architecture documentation
- User asks to update or edit ARCHITECTURE.md
- User mentions documenting system architecture
- User requests architecture review, audit, or analysis (triggers Design Drivers calculation prompt)
- User explicitly asks to "calculate design drivers" or "update design drivers"
- User asks about architecture documentation structure or best practices
- User edits Section 1 Executive Summary Key Metrics (triggers metric consistency check)
- User requests metric consistency check, verify metrics, or audit metrics
- **User asks informational questions about the documented architecture** (if ARCHITECTURE.md exists)
  - "What is our [authentication/scaling/data flow/etc.] approach?"
  - "How does [component/system/integration] work?"
  - "What technologies do we use for [purpose]?"
  - "Tell me about the architecture of [system]"
- **User asks to generate, create, or add diagrams to architecture documentation** (triggers Workflow 9)
  - "Generate my architecture diagrams"
  - "Create Mermaid diagrams from ARCHITECTURE.md"
  - "Add diagrams to my architecture"

### Query Pattern Triggers

This skill automatically activates when users ask questions about documented architecture, including:

**Reference Patterns**:
- "According to my architecture documentation..."
- "Based on the architecture..."
- "What does the architecture use/require/implement for..."
- "My architecture documentation shows/says..."
- "The architecture specifies/defines..."
- "Check/Validate/Verify the architecture [aspect]..."
- "Audit the [architecture component/pattern]..."

**Technical Query Keywords**:
- **Components**: "components", "services", "modules", "microservices", "systems"
- **Data**: "data structures", "data flow", "database", "schema", "models", "entities"
- **Integration**: "APIs", "integrations", "external systems", "endpoints", "interfaces"
- **Security**: "authentication", "authorization", "encryption", "security", "compliance"
- **Performance**: "scaling", "performance", "SLA", "capacity", "throughput", "latency"
- **Deployment**: "deployment", "cloud provider", "infrastructure", "environments", "regions"
- **Technology**: "tech stack", "languages", "frameworks", "tools", "libraries", "versions"
- **Decisions**: "why choose", "decision", "trade-offs", "alternatives", "ADR", "rationale"
- **Validation**: "check", "validate", "verify", "audit", "alignment", "BIAN", "META", "service domain", "layer", "standards", "compliance check"

**Multi-section Queries**:
- Questions requiring synthesis across multiple sections
- Cross-cutting concerns (e.g., "How does authentication work with external systems?")
- Implementation details spanning components, data, and deployment

---

## 🎯 AUTOMATIC WORKFLOW DETECTION

**IMPORTANT**: Immediately upon skill invocation, analyze the user's request to detect their intent.

### Detection Logic

Check the user's original message (before `/architecture-docs` was invoked) for these patterns:

#### Workflow 8: Presentation Generation
**Triggers:**
- Keywords: "generate", "create", "make" + "presentation", "slides", "PowerPoint", "pptx", "deck", "markdown presentation"
- Examples: "generate presentations", "create slides", "make PowerPoint", "generate presentation MD"
- Stakeholder mentions: "business presentation", "architecture slides", "compliance deck"
- Language: "presentación en español", "slides in English"

**Action when detected:**
1. Confirm: "I'll help you generate an architecture presentation Markdown file for Claude PowerPoint."
2. Jump directly to **Workflow 8, Step 1** (Stakeholder Type Selection)
3. Do NOT ask which workflow - proceed automatically

#### Workflow 9: Diagram Generation
**Triggers:**
- Keywords: "generate", "create", "add", "update", "make" + "diagram", "diagrams", "Mermaid diagram", "architecture diagram"
- Examples: "generate my architecture diagrams", "create diagrams from ARCHITECTURE.md", "add diagrams to my architecture"
- Section-specific: "generate diagrams for Section 4", "create data flow diagrams"
- Format mentions: "Mermaid diagrams", "visual diagrams", "architecture diagrams"

**Action when detected:**
1. Confirm: "I'll help you generate architecture diagrams."
2. Jump directly to **Workflow 9, Step 1** (Diagram Type Selection)
3. Do NOT ask which workflow - proceed automatically

#### Other Workflows
If the user's request matches other documented workflows (1-7, 9-10), follow their respective trigger patterns.

### If No Pattern Matches

If the user's request doesn't match any workflow triggers:
1. Acknowledge the skill invocation
2. Ask which workflow they want to use
3. Provide brief description of available workflows

---

## File Naming Convention

**IMPORTANT**: All architecture documents MUST be named **ARCHITECTURE.md**

- When creating a new architecture document, always use the filename: `ARCHITECTURE.md`
- When updating existing architecture, work with the file: `ARCHITECTURE.md`
- Do NOT use alternative names like: architecture.md, ARCH.md, system-architecture.md, etc.
- Each project/system should have ONE primary ARCHITECTURE.md file

### Location
- Place ARCHITECTURE.md in the root of the project or in a `/docs` directory
- For multi-project repositories, each project subdirectory gets its own ARCHITECTURE.md

## Working with ARCHITECTURE.md - Context Optimization

**IMPORTANT**: When working with ARCHITECTURE.md, optimize for context by loading sections incrementally, NOT the entire document at once.

### Context-Efficient Workflow

1. **Initial Assessment**
   - Read ONLY lines 1-50 of ARCHITECTURE.md to locate the **Document Index**
   - The Document Index provides exact line ranges for each section
   - Use the index to plan which sections need work
   - Identify which specific section(s) need work

2. **Section-Based Editing**
   - Use the Document Index to find exact line ranges for your target section
   - Use the Read tool with `offset` and `limit` parameters to load ONLY the relevant section
   - **Add context buffer**: Read ±10-20 lines beyond the section boundaries
   - Work on one section at a time
   - Example: Index shows Section 5 is lines 601-850, read lines 590-860 (with 10-line buffer)

3. **Incremental Updates**
   - Make edits to individual sections using the Edit tool
   - Avoid reading the full document unless absolutely necessary
   - For multi-section updates, work sequentially section by section
   - Update the Document Index line ranges if section size changes significantly

4. **Verification**
   - After edits, read ONLY the modified section to verify changes
   - Use Grep to search for specific content without loading full file
   - Update "Index Last Updated" date in the Document Index after major changes

### Using the Document Index

**Every ARCHITECTURE.md should include a Document Index** (before Section 1) with exact line ranges.

**Index Format Example:**
```markdown
## Document Index

**Quick Navigation:**
- [Section 1: Executive Summary](#1-executive-summary) → Lines 1-80
- [Section 2: System Overview](#2-system-overview) → Lines 81-150
- [Section 3: Architecture Principles](#3-architecture-principles) → Lines 151-350
- [Section 4: Architecture Layers](#4-architecture-layers) → Lines 351-600
- [Section 5: Component Details](#5-component-details) → Lines 601-850
- [Section 6: Data Flow Patterns](#6-data-flow-patterns) → Lines 851-1000
- [Section 7: Integration Points](#7-integration-points) → Lines 1001-1150
- [Section 8: Technology Stack](#8-technology-stack) → Lines 1151-1300
- [Section 9: Security Architecture](#9-security-architecture) → Lines 1301-1550
- [Section 10: Scalability & Performance](#10-scalability--performance) → Lines 1551-1750
- [Section 11: Operational Considerations](#11-operational-considerations) → Lines 1751-1950
- [Section 12: Architecture Decision Records (ADRs)](#12-architecture-decision-records-adrs) → Lines 1951-end

**Index Last Updated:** YYYY-MM-DD
```

**How to Use the Index:**

1. **Find the Index**: Read lines 1-50 to locate the Document Index
2. **Identify Target Section**: Check the index for exact line ranges
3. **Load with Context Buffer**: Read target section ± 10-20 lines for context preservation
4. **Example**:
   ```
   # To edit Section 5 (Component Details):
   # Index shows: Lines 601-850
   # Load with 10-line buffer:
   Read(file_path="ARCHITECTURE.md", offset=590, limit=270)
   # This reads lines 590-860
   ```

**Context Buffer Guidelines:**

| Edit Type | Buffer Size | Use Case |
|-----------|-------------|----------|
| **Minimal** | ±5-10 lines | Small edits (single paragraph, config value) |
| **Standard** | ±10-20 lines | Section edits (rewriting subsection, adding components) |
| **Extended** | ±20-50 lines | Cross-section edits (changes referencing adjacent sections) |

**Maintaining the Index:**

After significant edits:
1. Use `grep -n "^## [0-9]" ARCHITECTURE.md` to find actual section line numbers
2. Update the Document Index with current line ranges
3. Update "Index Last Updated" date
4. Verify index accuracy periodically (quarterly reviews)

**Note**: The Document Index is part of the ARCHITECTURE_DOCUMENTATION_GUIDE.md template and should be included in all new ARCHITECTURE.md files.

---

## Architecture Type Selection Workflow

**PURPOSE**: When creating a new ARCHITECTURE.md, prompt the user to select their architecture type. This determines the structure and content of Section 4 (Meta Architecture) and Section 5 (Component Details).

### When to Trigger

**Activate this workflow when:**
- ✅ User asks to create a NEW ARCHITECTURE.md document
- ✅ User explicitly requests to "change architecture type" or "select architecture type"
- ✅ User is updating an existing ARCHITECTURE.md and mentions changing from one architecture type to another

**Skip this workflow when:**
- ❌ Editing an existing ARCHITECTURE.md (type already selected)
- ❌ User is only updating specific sections unrelated to architecture type
- ❌ Document type is already clear from context

### Available Architecture Types

1. **Microservices Architecture (Recommended)** - Cloud-native distributed systems with independent services
2. **META Architecture** - 6-layer enterprise model (Channels → UX → Business Scenarios → Business → Domain → Core) with [BIAN V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html) alignment for Layer 5 Domain service domains
3. **3-Tier Architecture** - Classic web application pattern (Presentation → Application/Business Logic → Data)
4. **N-Layer Architecture** - Customizable patterns (DDD, Clean Architecture, Hexagonal)
5. **BIAN Architecture** - 5-layer BIAN-compliant model (Channels → BIAN Business Scenarios → BIAN Business Capabilities → BIAN Service Domains → Core Systems) with full [BIAN V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html) compliance across layers 2-4

**BIAN Standard for META**: BIAN V12.0 is the default and recommended version for META architecture. Use the [BIAN Service Landscape V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html) to identify and define service domains for Layer 5 (Domain).

### Workflow Steps

#### Step 1: Present Architecture Type Options

When creating a new ARCHITECTURE.md, present the user with architecture type selection:

```markdown
📐 **Architecture Type Selection**

Before creating your ARCHITECTURE.md, please select the architecture type that best describes your system:

**1. Microservices Architecture (Recommended)** (Cloud-Native Distributed)
   - Best for: Cloud-native systems, independently deployable services, modern applications
   - Components: API Gateway → Services → Data Stores → Event Bus
   - Complexity: High
   - Team Size: Large (10+)
   - Why Recommended: Industry standard for scalable, resilient modern applications

**2. META Architecture** (6-Layer Enterprise)
   - Best for: Large enterprise systems, financial services, complex integrations
   - Layers: Channels → UX → Business Scenarios → Integration → Domain → Core
   - Complexity: Very High
   - Team Size: Large (10+)

**3. 3-Tier Architecture** (Classic Web Application)
   - Best for: Web apps, REST APIs, standard CRUD systems
   - Tiers: Presentation → Application/Business Logic → Data
   - Complexity: Low
   - Team Size: Small-Medium (2-8)

**4. N-Layer Architecture** (Customizable Patterns)
   - Best for: DDD, Clean Architecture, Hexagonal Architecture
   - Patterns: 4-Layer DDD, 5-Layer Extended, Clean Architecture, Hexagonal
   - Complexity: Medium-High
   - Team Size: Medium (4-10)

**5. BIAN Architecture** (5-Layer BIAN-Compliant)
   - Best for: Banking systems requiring BIAN V12.0 certification, full BIAN compliance
   - Layers: Channels → BIAN Business Scenarios → BIAN Business Capabilities → BIAN Service Domains → Core Systems
   - Complexity: Very High
   - Team Size: Large (10+)
   - BIAN Compliance: Full BIAN V12.0 across layers 2-4

For detailed comparison and decision guidance, refer to: `templates/ARCHITECTURE_TYPE_SELECTOR.md`

**Which architecture type best describes your system? (1-5, or type name)**

Note: Option 1 (Microservices) is recommended for most modern cloud-native applications.
```

#### Step 2: Capture User Selection

Wait for user response (1, 2, 3, 4, or 5) or architecture type name.

**Valid inputs:**
- Numeric: `1`, `2`, `3`, `4`, `5`
- Type names: `Microservices`, `META`, `3-Tier`, `N-Layer`, `BIAN`
- Variations: `microservices`, `meta`, `three-tier`, `n-layer`, `bian`

**If user is unsure:**
- Offer to load `templates/ARCHITECTURE_TYPE_SELECTOR.md` decision guide
- Provide quick decision tree questions
- Default to **Microservices (Recommended)** for modern cloud-native systems
- Default to **META** if user has enterprise requirements and regulatory compliance needs
- Default to **3-Tier** if user wants maximum simplicity and minimal operational complexity

#### Step 3: Load Type-Specific Templates

Based on user selection, load the appropriate templates:

| Selection | Section 4 Template | Section 5 Template |
|-----------|-------------------|-------------------|
| Microservices (1) | `templates/SECTION_4_MICROSERVICES.md` | `templates/SECTION_5_MICROSERVICES.md` |
| META (2) | `templates/SECTION_4_META.md` | `templates/SECTION_5_META.md` |
| 3-Tier (3) | `templates/SECTION_4_3TIER.md` | `templates/SECTION_5_3TIER.md` |
| N-Layer (4) | `templates/SECTION_4_NLAYER_PATTERNS.md` | *(Use generic component template)* |
| BIAN (5) | `templates/SECTION_4_BIAN.md` | `templates/SECTION_5_BIAN.md` |

**Loading Process:**
1. Read the appropriate Section 4 template file
2. Read the appropriate Section 5 template file (if exists)
3. Extract template content (excluding metadata comments)
4. Prepare for insertion into ARCHITECTURE.md at correct section boundaries

#### Step 4: Add Architecture Type Metadata

When creating the ARCHITECTURE.md, add an HTML comment metadata tag at the beginning of Section 4 to track the selected architecture type:

```html
<!-- ARCHITECTURE_TYPE: META -->
```

**Valid metadata values:**
- `<!-- ARCHITECTURE_TYPE: META -->`
- `<!-- ARCHITECTURE_TYPE: 3-TIER -->`
- `<!-- ARCHITECTURE_TYPE: MICROSERVICES -->`
- `<!-- ARCHITECTURE_TYPE: N-LAYER -->`
- `<!-- ARCHITECTURE_TYPE: BIAN -->`

**Purpose:**
- Enables type detection for future edits
- Used by validation rules
- Used by Design Drivers calculation
- Used by architecture compliance skill

#### Step 5: Create ARCHITECTURE.md with Type-Specific Content

Create the complete ARCHITECTURE.md using:
- Standard sections 1-3 (same for all types)
- Type-specific Section 4 (from loaded template)
- Type-specific Section 5 (from loaded template)
- Standard sections 6-12 (same for all types)

**Include:**
- Document Index (placeholder line ranges)
- Architecture type metadata comment in Section 4
- All template content properly formatted
- Placeholder values for customization

#### Step 6: Prompt for ADR Generation (Optional)

**Trigger**: Immediately after Step 5 completes successfully (ARCHITECTURE.md created)

**Objective**: Offer to generate ADR files from Section 12 table

---

##### Step 6.0: Present ADR Generation Prompt

After ARCHITECTURE.md is successfully created, display the following prompt:

```
✅ ARCHITECTURE.md created successfully!

═══════════════════════════════════════════════════════════
📋 Architecture Decision Records (ADRs) Setup
═══════════════════════════════════════════════════════════

Section 12 of your ARCHITECTURE.md includes an ADR table with placeholder
entries. I can automatically generate these ADR files using the standard
ADR template.

Would you like me to generate the ADR files now?

Options:
1. [Yes - Generate ADRs] - Create all ADR files listed in Section 12
2. [Preview First] - Show me which ADRs will be created
3. [No Thanks] - I'll create them manually later
4. [Learn More] - Tell me about ADRs and the template

Recommended: Option 1 (Generate ADRs) - Saves time and ensures consistency
```

**Wait for user response**: `1`, `2`, `3`, `4`, or keywords like "yes", "preview", "no", "learn more"

---

##### Step 6.1: Handle User Selection

**If user selects Option 1 (Yes - Generate ADRs)**:
- Proceed to Step 6.2 (Locate Section 12)

**If user selects Option 2 (Preview First)**:
- Proceed to Step 6.2 (Locate Section 12)
- After Step 6.3 (Extract ADR List), show preview
- Re-prompt: "Proceed with generation? (yes/no)"
- If yes: Continue to Step 6.4
- If no: Skip to Step 6.8 (Complete)

**If user selects Option 3 (No Thanks)**:
- Skip to Step 6.8 (Complete with skip message)

**If user selects Option 4 (Learn More)**:
- Show ADR information:

```
Architecture Decision Records (ADRs) document important architectural choices,
providing context for future team members and explaining the "why" behind
technical decisions.

**What ADRs Document**:
- Technology selection rationale
- Architecture pattern choices
- Trade-offs and alternatives considered
- Consequences of decisions

**ADR Template Structure**:
- Context: Problem statement and requirements
- Decision: What was decided
- Rationale: Why this choice was made
- Consequences: Positive/negative outcomes
- Alternatives: Options that were considered but rejected

**Template Location**: skills/architecture-docs/adr/ADR-000-template.md
**Guide**: skills/architecture-docs/ADR_GUIDE.md

Would you like me to generate the ADR files now? (yes/no)
```

- Re-prompt with Options 1-3
- Wait for new response

---

##### Step 6.2: Locate Section 12

**Method 1: Use Document Index** (preferred)

```bash
# Read Document Index to find Section 12 line range
grep -A 20 "^## Document Index" ARCHITECTURE.md | grep "Section 12"
```

**Expected output**: `- [Section 12: Architecture Decision Records (ADRs)](#12-architecture-decision-records-adrs) → Lines 1750-1800`

**Parse line range**: Extract start line `1750` and end line `1800`

**Method 2: Fallback - Find by Header**

If Document Index method fails:

```bash
# Find Section 12 header line number
grep -n "^## 12\. Architecture Decision Records" ARCHITECTURE.md
```

**Expected output**: `1750:## 12. Architecture Decision Records (ADRs)`

**Parse line number**: Extract `1750`

**Read until**: Next section header or end of file (typically 50-100 lines)

**Error Handling**: If Section 12 not found:

```
⚠️  Section 12: Architecture Decision Records not found in ARCHITECTURE.md

This is unusual - all ARCHITECTURE.md files should include Section 12.

Would you like me to:
1. [Add Section 12] - Add the section with empty ADR table
2. [Skip ADR Generation] - Continue without generating ADRs
3. [Manual Review] - Let me check the document structure first

Recommended: Option 3 (Manual Review)
```

---

##### Step 6.3: Extract ADR List from Section 12

**Read Section 12 content**:

```bash
# Using Read tool with line range from Step 6.2
Read(file_path="ARCHITECTURE.md", offset=1750, limit=50)
```

**Parse ADR table rows**:

```bash
# Extract ADR table rows using grep
grep -E "^\| \[ADR-" ARCHITECTURE.md
```

**Expected output** (example):
```
| [ADR-001](adr/ADR-001.md) | [Title] | Accepted | YYYY-MM-DD | High/Medium/Low |
| [ADR-002](adr/ADR-002-database.md) | Database Choice | Proposed | 2024-01-20 | High |
```

**Parse each row**:

For each line matching the pattern `^\| \[ADR-`:
1. Extract ADR number: `001`, `002`, etc. (from `[ADR-001]`)
2. Extract file path from link: `adr/ADR-001.md` (from `(adr/ADR-001.md)`)
3. Extract slug (if present): `` (empty) or `database` (from `ADR-002-database.md`)
4. Extract title: Column 2 (e.g., `[Title]` or `Database Choice`)
5. Extract status: Column 3 (e.g., `Accepted`, `Proposed`)
6. Extract date: Column 4 (e.g., `YYYY-MM-DD` or `2024-01-20`)
7. Extract impact: Column 5 (e.g., `High/Medium/Low` or `High`)

**Regex Pattern** for parsing:
```regex
^\| \[ADR-(\d{3})\]\(adr\/ADR-\d{3}(-[a-z0-9-]+)?\.md\) \| (.+?) \| (.+?) \| (.+?) \| (.+?) \|
```

**Capture Groups**:
- Group 1: ADR number (e.g., `001`)
- Group 2: Optional slug (e.g., `-database` or empty)
- Group 3: Title
- Group 4: Status
- Group 5: Date
- Group 6: Impact

**Store in list**:
```python
# Example structure (pseudocode)
adrs = [
    {
        "number": "001",
        "slug": "",  # Empty means generate from title
        "title": "[Title]",
        "status": "Accepted",
        "date": "YYYY-MM-DD",
        "impact": "High/Medium/Low",
        "file_path": "adr/ADR-001.md"
    },
    {
        "number": "002",
        "slug": "database",
        "title": "Database Choice",
        "status": "Proposed",
        "date": "2024-01-20",
        "impact": "High",
        "file_path": "adr/ADR-002-database.md"
    }
]
```

**Error Handling**: If no ADRs found (empty table):

```
ℹ️  Section 12 ADR table is empty or contains only placeholder entries.

No ADRs found to generate. This is normal for newly created ARCHITECTURE.md files.

Would you like me to:
1. [Skip ADR Generation] - Continue without creating ADR files
2. [Learn About ADRs] - Understand when to create ADRs
3. [Add Sample ADR] - Create one example ADR to get started

Recommended: Option 1 (Skip) - Create ADRs as architectural decisions are made
```

**Validation**:
- Check for duplicate ADR numbers (same number appears multiple times)
- Check for malformed rows (wrong column count)

**If duplicates found**:
```
⚠️  Duplicate ADR numbers detected in Section 12 table

Duplicates found: ADR-002 (appears 2 times)

This will cause file overwrites. Please fix the table before generating ADRs.

Would you like me to:
1. [Show Duplicates] - Display the conflicting rows
2. [Auto-Renumber] - Automatically renumber ADRs sequentially
3. [Skip ADR Generation] - Fix manually and regenerate later

Recommended: Option 1 (Show Duplicates)
```

---

##### Step 6.3a: Preview ADRs (if user selected Option 2)

If user selected "Preview First" in Step 6.1:

**Display ADR list**:
```
Found {count} ADRs in Section 12 table:

1. ADR-001: [Title] (Status: Accepted, Impact: High/Medium/Low)
   → Will create: adr/ADR-001-untitled.md
   Note: Placeholder title - you can customize later

2. ADR-002: Database Choice (Status: Proposed, Impact: High)
   → Will create: adr/ADR-002-database.md

Proceed with generation? (yes/no)
```

**Wait for response**:
- If `yes` or `1`: Continue to Step 6.4
- If `no` or `2` or `skip`: Skip to Step 6.8

---

##### Step 6.4: Prepare ADR Generation

**Get ARCHITECTURE.md directory**:

```bash
# Extract directory path from ARCHITECTURE.md location
# If ARCHITECTURE.md is in current directory, use "."
# Otherwise, extract directory from file path
ARCH_DIR="."
```

**Define ADR directory path**:
```bash
ADR_DIR="${ARCH_DIR}/adr"
# Results in: "./adr" relative to ARCHITECTURE.md
```

**Create ADR directory if doesn't exist**:
```bash
mkdir -p adr
```

**Error Handling**: If directory creation fails:

```
❌ Error: Unable to create adr/ directory

Reason: [Error message from mkdir]

Possible causes:
- Insufficient file permissions
- Path does not exist
- Disk space full

Would you like me to:
1. [Retry with Different Path] - Try creating in user home directory
2. [Skip ADR Generation] - Continue without creating ADR files
3. [Manual Instructions] - Show me how to create manually

Recommended: Option 3 (Manual Instructions)
```

**Success message**:
```
Generating ADR files in ./adr/
```

---

##### Step 6.5: Load ADR Template

**Template path**: Resolve dynamically — `$PLUGIN_DIR/skills/architecture-docs/adr/ADR-000-template.md`

**Resolve plugin directory** (run once per session if not already known):
```bash
PLUGIN_DIR=$(find "$HOME" -maxdepth 10 -type d -name "solutions-architect-skills" ! -path "*/node_modules/*" 2>/dev/null | head -1)
echo "$PLUGIN_DIR"
```

**Load template** using the resolved path:
```
Read(file_path="$PLUGIN_DIR/skills/architecture-docs/adr/ADR-000-template.md")
```
(Replace `$PLUGIN_DIR` with the actual path returned by the Bash command above)

**Store template content** in memory for reuse across all ADR files

---

##### Step 6.6: Generate Each ADR File

For each ADR in the `adrs` list from Step 6.3:

**Step 6.6a: Generate File Path**

```python
# Determine slug (pseudocode)
if adr["slug"] == "":
    # Generate slug from title using Step 6.6b rules
    slug = generate_slug(adr["title"])
else:
    # Use slug from file path in table
    slug = adr["slug"]

# Construct file path
file_name = f"ADR-{adr['number']}-{slug}.md"
file_path = f"adr/{file_name}"
```

**Step 6.6b: Generate Slug from Title** (if needed)

**Slug Generation Rules**:
1. Convert title to lowercase
2. Replace spaces with hyphens
3. Remove special characters: `:?/*<>|"` (keep alphanumeric and hyphens)
4. Remove consecutive hyphens (replace `--` with `-`)
5. Trim leading/trailing hyphens
6. Limit to 50 characters
7. If title is `[Title]` or placeholder, use slug `untitled`

**Examples**:
- `Technology Stack Selection` → `technology-stack-selection`
- `REST vs. gRPC: Which API?` → `rest-vs-grpc-which-api`
- `PostgreSQL Database Choice` → `postgresql-database-choice`
- `[Title]` → `untitled`

**Step 6.6c: Check for Existing File**

```bash
# Check if file already exists
if [ -f "adr/ADR-${number}-*.md" ]; then
    # File exists - trigger conflict handling
fi
```

**If exists**:
```
⚠️  ADR file conflict detected

Existing file: adr/ADR-001-old-title.md
New file: adr/ADR-001-technology-stack.md

Would you like me to:
1. [Skip This ADR] - Don't overwrite, keep existing file
2. [Rename New ADR] - Create as ADR-{next_available} instead
3. [Overwrite] - Replace existing file (destructive)
4. [Review Existing] - Show me what's in the existing file first

Recommended: Option 4 (Review Existing)
```

**Conflict Resolution**:
- **Never auto-overwrite** existing ADRs
- Always require user confirmation
- Suggest next available ADR number if renaming

**Step 6.6d: Populate Template**

```python
# Copy template (pseudocode)
adr_content = template_content

# Replace placeholders
adr_content = adr_content.replace("ADR-XXX", f"ADR-{adr['number']}")
adr_content = adr_content.replace("[Short Decision Title]", adr["title"])

# Replace status line (keep full line format from template)
status_line_old = "**Status**: Proposed | Accepted | Deprecated | Superseded by ADR-XXX"
status_line_new = f"**Status**: {adr['status']}"
adr_content = adr_content.replace(status_line_old, status_line_new)

# Replace date
if adr["date"] == "YYYY-MM-DD" or adr["date"] == "[Date]":
    # Use current date
    current_date = datetime.now().strftime("%Y-%m-%d")
    adr_content = adr_content.replace("**Date**: YYYY-MM-DD", f"**Date**: {current_date}")
else:
    # Use date from table
    adr_content = adr_content.replace("**Date**: YYYY-MM-DD", f"**Date**: {adr['date']}")

# Replace authors (default to Architecture Team)
adr_content = adr_content.replace("**Authors**: [Author names or team name]", "**Authors**: Architecture Team")

# Replace related ADRs (empty by default)
adr_content = adr_content.replace("**Related**: [Links to related ADRs, e.g., ADR-001, ADR-005]", "**Related**: []")
```

**Special handling for placeholder titles**:
```python
# If title is placeholder, add TODO note
if adr["title"] in ["[Title]", "[title]", "Title"]:
    # Add note about placeholder
    note = "\n> **TODO**: This ADR was auto-generated with a placeholder title. Please update the title, filename, and content with your actual architectural decision.\n"
    # Insert after first header (after "# ADR-XXX: [Title]" line)
    lines = adr_content.split('\n')
    for i, line in enumerate(lines):
        if line.startswith('# ADR-'):
            lines.insert(i + 1, note)
            break
    adr_content = '\n'.join(lines)
```

**Step 6.6e: Write ADR File**

```bash
# Write the file using Write tool
Write(file_path=file_path, content=adr_content)
```

**Error Handling**: If write fails:
- Log error message
- Mark ADR as "failed" in tracking
- Continue with next ADR (don't abort entire batch)

**Step 6.6f: Report Progress**

```
✅ Created: adr/ADR-001-technology-stack.md
```

**Repeat** Steps 6.6a-6.6f for all ADRs in list

---

##### Step 6.7: Display Summary Report

After all ADRs processed:

**Count results**:
```python
total_adrs = len(adrs)
created_adrs = count(created successfully)
skipped_adrs = count(skipped due to conflicts)
failed_adrs = count(failed to write)
```

**Display summary**:
```
═══════════════════════════════════════════════════════════
✅ ADR Generation Complete
═══════════════════════════════════════════════════════════

Successfully generated {created_adrs} of {total_adrs} ADR files in ./adr/

Created ADRs:
- adr/ADR-001-technology-stack.md
- adr/ADR-002-database-choice.md
- adr/ADR-003-api-protocol.md

{If skipped_adrs > 0:}
Skipped ADRs:
- ADR-004 (file already exists: adr/ADR-004-old-title.md)

{If failed_adrs > 0:}
Failed ADRs:
- ADR-005 (write error: permission denied)

Next steps:
1. Review and customize each ADR file
2. Fill in Context, Decision, and Rationale sections
3. Update placeholder titles (marked with TODO)
4. Link related ADRs in the "Related" field
5. Update status to "Accepted" once reviewed and approved

ADR Template Guide: skills/architecture-docs/ADR_GUIDE.md
```

---

##### Step 6.8: Complete Workflow

**If user skipped ADR generation** (Option 3 in Step 6.1):

```
ℹ️  Skipped ADR generation - you can create ADR files manually later

To create ADRs manually:
1. Update Section 12 table in ARCHITECTURE.md with your ADRs
2. Copy template: cp skills/architecture-docs/adr/ADR-000-template.md adr/ADR-001-your-title.md
3. Customize the ADR content

For guidance, see: skills/architecture-docs/ADR_GUIDE.md
```

**Return to main workflow**: Architecture Type Selection Workflow completes successfully

---

**End of Step 6**

### Detecting Existing Architecture Type

When editing an existing ARCHITECTURE.md, detect the architecture type:

**Detection Method 1: Metadata Comment**
```bash
grep -n "<!-- ARCHITECTURE_TYPE:" ARCHITECTURE.md
```

If found, extract the type from the comment.

**Detection Method 2: Section 4 Header Analysis**

If no metadata comment, infer from Section 4 headers:

```bash
# Check for BIAN indicators (check FIRST - most specific)
grep -E "(Layer 2: BIAN Business Scenarios|Layer 4: BIAN Service Domains)" ARCHITECTURE.md

# Check for META indicators
grep -E "(Layer 1: Channels|Layer 5: Domain|Layer 6: Core)" ARCHITECTURE.md

# Check for 3-Tier indicators
grep -E "(Tier 1: Presentation|Tier 3: Data)" ARCHITECTURE.md

# Check for Microservices indicators
grep -E "(API Gateway|Service Mesh|Microservices Catalog)" ARCHITECTURE.md

# Check for N-Layer indicators
grep -E "(Clean Architecture|Hexagonal|Ports & Adapters)" ARCHITECTURE.md
```

**Inference Rules (in order of specificity):**
- Contains "Layer 2: BIAN Business Scenarios" OR "Layer 4: BIAN Service Domains" → **BIAN**
- Contains "Layer 1: Channels" AND "Layer 5: Domain" AND "Layer 6: Core" → **META**
- Contains "Tier 1: Presentation" OR "Tier 3: Data" → **3-Tier**
- Contains "API Gateway" AND "Service Mesh" → **Microservices**
- Contains "Clean Architecture" OR "Hexagonal" → **N-Layer**
- Cannot determine → Ask user or default to **Microservices (Recommended)**

### Changing Architecture Type (Existing Document)

If user requests to change architecture type of an existing ARCHITECTURE.md:

**Warning Steps:**
1. **Detect current type** using detection methods above
2. **Warn user** about potential data loss:
   ```
   ⚠️  **Architecture Type Change Warning**

   Current type: [DETECTED_TYPE]
   Requested type: [NEW_TYPE]

   Changing architecture type will:
   - Replace Section 4 (Meta Architecture) with new structure
   - Replace Section 5 (Component Details) with new organization
   - Require manual component remapping

   **Recommendation**: Review and backup current Sections 4 & 5 before proceeding.

   Continue with architecture type change? (yes/no)
   ```

3. **If user confirms:**
   - Load new type templates
   - Replace Section 4 content
   - Replace Section 5 content
   - Update metadata comment
   - Update Document Index
   - Report changes to user

4. **If user declines:**
   - Cancel operation
   - Suggest manual editing approach

### Type-Specific Validation

After selecting or detecting architecture type, apply type-specific validation rules:

**BIAN Architecture:**
- ✅ Must have all 5 layers (Channels, BIAN Business Scenarios, BIAN Business Capabilities, BIAN Service Domains, Core Systems)
- ✅ Layer 2 must map to BIAN Business Areas (5 areas)
- ✅ Layer 3 must map to BIAN Business Domains (30+ domains)
- ✅ Layer 4 must implement BIAN Service Domains from [BIAN V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html)
- ✅ All Layer 4 service domain names validated against official [BIAN Service Landscape V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html)
- ✅ Layer 4 components must include complete BIAN metadata (Official Name, BIAN ID, Version, Business Domain, Business Area, URL)
- ✅ Control records documented per BIAN specification for all Layer 4 service domains
- ✅ All mandatory BIAN service operations implemented (Initiate, Update, Retrieve, Control)
- ✅ Behavior qualifiers documented per BIAN spec
- ✅ Functional patterns documented per BIAN spec (Managed Object, Tracked Object, etc.)
- ✅ Full BIAN V12.0 compliance level documented
- ✅ BIAN hierarchy traceability: Service Domain → Business Domain → Business Area
- ✅ Layers documented in correct order

**META Architecture:**
- ✅ Must have all 6 layers (Channels, UX, Business Scenarios, Business, Domain, Core)
- ✅ Layer 5 must include BIAN alignment section
- ✅ Verify BIAN V12.0 is documented as the default version
- ✅ Validate BIAN service domain **names (Capabilities)** against the official [BIAN Service Landscape V12.0](https://bian.org/servicelandscape-12-0-0/views/view_51891.html)
- ✅ Ensure BIAN IDs (SD-XXX) are used for internal document tracking only
- ✅ Validate Layer 5 (Domain) components include BIAN alignment subsection with official URLs
- ✅ Layers documented in correct order

**3-Tier Architecture:**
- ✅ Must have all 3 tiers (Presentation, Application, Data)
- ✅ No direct database access from Presentation tier
- ✅ Application tier should be stateless

**Microservices Architecture:**
- ✅ Must document API Gateway and Service Mesh (or justify omission)
- ✅ Database-per-service pattern followed
- ✅ Event bus and topics documented
- ✅ Circuit breakers configured

**N-Layer Architecture:**
- ✅ Must specify which pattern (4-Layer, 5-Layer, Clean, Hexagonal)
- ✅ Dependency direction documented
- ✅ Core/domain layer is framework-free (if applicable)

**For detailed validation rules**, see: `VALIDATIONS.md` § Type-Aware Validation

### Best Practices

**DO:**
- ✅ Always prompt for architecture type when creating new ARCHITECTURE.md
- ✅ Add metadata comment to track architecture type
- ✅ Load appropriate templates based on selection
- ✅ Warn before changing architecture type of existing document
- ✅ Apply type-specific validation rules

**DON'T:**
- ❌ Assume architecture type without asking
- ❌ Mix templates from different architecture types
- ❌ Change architecture type without user confirmation
- ❌ Skip metadata comment (makes future edits harder)

### Example Workflow

**User:** "Create architecture documentation for my microservices system"

**Assistant:**
1. Detects new ARCHITECTURE.md creation
2. Presents architecture type options (1-4)
3. User selects "3" (Microservices)
4. Loads `templates/SECTION_4_MICROSERVICES.md` and `templates/SECTION_5_MICROSERVICES.md`
5. Creates ARCHITECTURE.md with:
   - Standard Sections 1-3
   - Microservices Section 4 (API Gateway, Service Mesh, Services, Event Bus)
   - Microservices Section 5 (Service catalog format)
   - Standard Sections 6-12
   - Metadata comment: `<!-- ARCHITECTURE_TYPE: MICROSERVICES -->`
6. Reports completion with architecture type confirmation

---

## Automatic Index Updates

**CRITICAL**: After ANY edit that significantly changes section line numbers (>10 lines), automatically update the Document Index.

### When to Update

**Update if:**
- ✅ Added/removed content shifting section boundaries (>10 lines)
- ✅ Modified section headers or structure
- ✅ User requests: "update the index"

**Skip if:**
- ❌ Minor edits (<10 lines)
- ❌ Only metadata changes
- ❌ Typo fixes

### Workflow Overview

**Quick Steps:**
1. **Detect**: Run `grep -n "^## [0-9]" ARCHITECTURE.md` to find section boundaries
2. **Calculate**: Parse output to determine line ranges (Section_Start to Next_Section_Start - 1)
3. **Update**: Edit Document Index (typically lines 5-21) with new ranges
4. **Timestamp**: Update "Index Last Updated" to current date
5. **Report**: Inform user which sections changed

**Example:**
```bash
# After adding content to Section 8, it grew from 906-980 to 912-996
grep -n "^## [0-9]" ARCHITECTURE.md
# Parse: Section 8 now at line 912, Section 9 at 998
# Calculate: Section 8 = 912-997, Section 9 = 998-1243
# Update index and report to user
```

### Detailed Algorithm

For complete line range calculation algorithm, step-by-step examples, verification checklist, and edge cases:
→ **METRIC_CALCULATIONS.md** § Automatic Index Updates

### Best Practices

**DO:**
- ✅ Update after significant edits
- ✅ Use grep for accuracy (don't guess)
- ✅ Update timestamp
- ✅ Report changes to user

**DON'T:**
- ❌ Update for tiny changes
- ❌ Skip timestamp update
- ❌ Change index format

---

## Metric Consistency Detection & Management

**CRITICAL**: The Executive Summary (Section 1, Key Metrics subsection around lines 31-38) contains performance metrics that serve as the **Source of Truth** for system capacity, throughput, latency, and availability targets. These metrics are often duplicated across multiple sections (especially Section 6: Data Flow, Section 7: Integration Points, and Section 10: Scalability & Performance).

**Problem**: When metrics are updated in the Executive Summary, duplicates in other sections can become stale, creating inconsistencies.

**Solution**: This skill provides automatic metric consistency detection and review-based synchronization.

### When to Trigger Metric Audit

**Automatic Trigger:**
- ✅ After editing Section 1 Executive Summary Key Metrics (typically lines 31-38)
- ✅ When user updates any metric values in the Key Metrics subsection
- ✅ After Edit tool completes on lines in Section 1 that contain metrics (TPS, latency, SLA, etc.)

**Manual Trigger:**
- User explicitly requests: "Check metric consistency", "Verify metrics", "Audit metrics", "Sync metrics"
- User updates Section 10 (Scalability & Performance) and asks to verify consistency

…(truncated)
