Claude Skill

architect-implement

Generate a full Architecture Description (AD.md) from accepted ADRs using multi-agent DAG orchestration. Use when accepted ADRs exist and you need to produce or update unified architecture documentation.

LLM Mart · 0 points · 9 views 0 listing impressions 0 install-command copies
Virus-scanned Reviewed automatically before listing.

Full trust report

Download tikalk-adlc-team-skills-skills_architect_architect-implement-3035db2.zip · 51 KB
Part of tikalk/adlc-team-skills — 21 skills

Install

skills CLI npx skills add https://github.com/tikalk/adlc-team-skills/tree/main/skills/architect/architect-implement
Claude Code claude plugin marketplace add https://llmmart.ai/marketplace.json && claude plugin install tikalk-adlc-team-skills@llmmart
Git git clone https://github.com/tikalk/adlc-team-skills.git

The skills CLI installs just this skill, for any of its supported agents. Claude Code installs the whole tikalk/adlc-team-skills collection as a plugin from our marketplace. Git is the plain clone.

Skill manifest

architect-implement

What this skill does

Generate a full Architecture Description (AD.md) from Architecture Decision Records (ADRs) using a multi-agent DAG orchestration approach:

  1. Plan Agent: Analyze ADRs, detect sub-systems, generate a customized DAG, and get user approval.
  2. Execute Agent: Generate architecture views per sub-system following the DAG, with dependency context passing.
  3. Summarize Agent: Aggregate all views, resolve cross-subsystem conflicts, and generate a unified AD.md.

Key Insight: ADRs capture why decisions were made; the Architecture Description captures what the system looks like as a result of those decisions.

When to use

  • After /architect-specify or /architect-clarify: Generate AD from discussed and accepted ADRs.
  • After /architect-init: Document brownfield architecture.
  • ADR Updates: Regenerate AD.md after new decisions.
  • Documentation Sprint: Create comprehensive architecture docs.

When NOT to use

  • No ADRs exist: Use /architect-specify or /architect-init first.
  • Feature-level: Feature AD is generated during the feature's plan phase, not by this skill.
  • Minor updates: Use direct editing for small changes.

Process

User Input

$ARGUMENTS

You MUST consider the user input before proceeding (if not empty).

Examples of User Input:

  • "Focus on deployment and operational views - we need infrastructure docs"
  • "Generate all views with emphasis on security perspective"
  • "Update existing AD.md with new ADRs from recent decisions"
  • Empty input: Generate complete Architecture Description from all ADRs

Flags

  • --views VIEWS: Architecture views to generate

    • core (default): Context, Functional, Information, Development, Deployment (5 core views)
    • all: All 7 views including Concurrency and Operational
    • Custom: comma-separated (e.g., concurrency,operational) - always includes core views
  • --sequential (default): Execute views sequentially for maximum quality

    • Recommended: Allows checkpoint after Functional view
  • --parallel: Allow parallel execution where dependency chains permit

    • Warning: May reduce cross-view consistency - use only when time-constrained
  • --no-checkpoint: Skip Functional view checkpoint (not recommended)

    • Warning: Functional view is the "cornerstone" that shapes all others
  • --force: Bypass workflow state validation (emergency use only)

    • WARNING: Use only when you understand the risks
    • Skips clarify Phase 5.5 completion check
    • Skips pre-flight ADR status validation
    • May result in incomplete or inconsistent architecture

Important: When --views is core (default), skip Concurrency View (3.4) and Operational View (3.7) entirely. Only generate them when explicitly requested via --views all or --views concurrency,operational.

Rozanski & Woods Methodology Alignment

This command implements the Viewpoints and Perspectives framework from Software Systems Architecture (2nd Edition) by Nick Rozanski and Eoin Woods.

Core Principles

  1. Functional View is the Cornerstone

    "The Functional view is the cornerstone of most ADs... It usually drives the shape of other system structures such as the information structure, concurrency structure, deployment structure, and so on." — Rozanski & Woods

  2. Views are Interrelated, Not Independent

    "The decisions taken in one view can have a considerable impact on the others, and it is a big part of the architect's job to make sure that these implications are understood."

  3. Perspectives Apply to Views

    "You never work with perspectives in isolation but instead use them with each view to analyze and validate the qualities of your architecture."

  4. Quality Over Speed Architecture mistakes are expensive to fix. Sequential execution with checkpoints is the default to ensure quality.

Viewpoint Dependency Graph

                    ┌──────────┐
                    │ Context  │  (System boundaries)
                    └────┬─────┘
                         │
                         ▼
                 ┌───────────────┐
                 │  FUNCTIONAL   │  ★ CORNERSTONE ★
                 │  (Drives all  │  USER CHECKPOINT
                 │   other views)│  REQUIRED HERE
                 └───────┬───────┘
                         │
         ┌───────────────┼───────────────┐
         │               │               │
         ▼               ▼               ▼
   ┌───────────┐   ┌───────────┐   ┌───────────┐
   │Information│   │Concurrency│   │Development│
   │           │   │(optional) │   │           │
   └─────┬─────┘   └─────┬─────┘   └─────┬─────┘
         │               │               │
         └───────────────┼───────────────┘
                         │
                         ▼
                  ┌────────────┐
                  │ Deployment │
                  └──────┬─────┘
                         │
                         ▼
                  ┌────────────┐
                  │ Operational│  (optional)
                  └────────────┘

Dynamic Viewpoint & Perspective Selection

Viewpoints and perspectives are selected dynamically based on system characteristics:

Category Always Included Auto-Detected (Optional)
Viewpoints Context, Functional Information, Concurrency, Development, Deployment, Operational
Perspectives Security, Performance Accessibility, Availability, Evolution, Internationalization, Location, Regulation, Usability, Development Resource

Reference: https://www.viewpoints-and-perspectives.info/

Goal

Transform Architecture Decision Records (ADRs) into a comprehensive Architecture Description (AD.md) using a multi-agent DAG orchestration approach:

  1. Plan Agent: Analyze ADRs, detect sub-systems, generate customized DAG, get user approval
  2. Execute Agent: Generate views per sub-system following the DAG, with dependency context
  3. Summarize Agent: Aggregate all views, resolve conflicts, generate unified AD.md

Role & Context

You are acting as an Architecture Orchestrator managing a multi-phase documentation generation workflow. Your role involves:

  • Planning the generation DAG based on sub-system analysis
  • Executing view generation with proper dependency ordering
  • Summarizing views into a unified Architecture Description
  • Persisting state for resumability across AI agent sessions

Architecture Document Hierarchy

Document Purpose Location
{REPO_ROOT}/.adlc/drafts/adr/ Architectural decisions with rationale (individual file format) Input
{REPO_ROOT}/.adlc/architect/state.json DAG execution state State
{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md Per-view outputs Reference
{REPO_ROOT}/AD.md Full Architecture Description Output
{REPO_ROOT}/.adlc/memory/constitution.md Governance principles Constraint

IMPORTANT - Path Resolution:

  • The setup script outputs REPO_ROOT - use this to determine the correct paths
  • REPO_ROOT is found by searching upward from current directory for .adlc directory
  • NEVER use relative paths like .adlc/drafts/adr.md - always use {REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md
  • The setup script reads individual ADR files from the adr/ directory
  • When running from a subdirectory (e.g., a subproject directory), .adlc may be in the parent directory

View Templates

Located in the skill's templates/ directory:

Template Purpose
templates/views/context.md Context View template
templates/views/functional.md Functional View template
templates/views/information.md Information View template
templates/views/concurrency.md Concurrency View template (optional)
templates/views/development.md Development View template
templates/views/deployment.md Deployment View template
templates/views/operational.md Operational View template (optional)
Perspective Templates (10 total)
templates/perspectives/security.md
templates/perspectives/performance.md
templates/perspectives/accessibility.md
templates/perspectives/availability.md
templates/perspectives/evolution.md
templates/perspectives/internationalization.md
templates/perspectives/location.md
templates/perspectives/regulation.md
templates/perspectives/usability.md
templates/perspectives/development-resource.md

Three-Phase DAG Workflow

┌─────────────────────────────────────────────────────────────────────────────┐
│                          PHASE 1: PLAN                                      │
│  ┌─────────────┐    ┌─────────────────┐    ┌─────────────────────────────┐ │
│  │ Load ADRs   │───▶│ Detect Sub-     │───▶│ Generate DAG per Sub-system │ │
│  │             │    │ systems         │    │ (apply customization rules) │ │
│  └─────────────┘    └─────────────────┘    └──────────────┬──────────────┘ │
│                                                           │                 │
│                                            ┌──────────────▼──────────────┐ │
│                                            │ Present Plan for Approval   │ │
│                                            │ (user confirms or modifies) │ │
│                                            └──────────────┬──────────────┘ │
│                                                           │                 │
│                                            ┌──────────────▼──────────────┐ │
│                                            │ Write state.json            │ │
│                                            └─────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                          PHASE 2: EXECUTE                                   │
│  ┌─────────────────────────────────────────────────────────────────────┐   │
│  │  For each sub-system, execute DAG in topological order:             │   │
│  │                                                                      │   │
│  │  ┌─────────┐    ┌────────────┐    ┌─────────────┐    ┌───────────┐ │   │
│  │  │ Context │───▶│ Functional │───▶│ Information │───▶│Development│ │   │
│  │  └─────────┘    └────────────┘    └─────────────┘    └───────────┘ │   │
│  │                        │                                    │       │   │
│  │                        ▼                                    ▼       │   │
│  │               ┌─────────────┐                      ┌────────────┐  │   │
│  │               │ Concurrency │                      │ Deployment │  │   │
│  │               │ (optional)  │                      └────────────┘  │   │
│  │               └─────────────┘                             │        │   │
│  │                                                           ▼        │   │
│  │                                                   ┌─────────────┐  │   │
│  │                                                   │ Operational │  │   │
│  │                                                   │ (optional)  │  │   │
│  │                                                   └─────────────┘  │   │
│  └─────────────────────────────────────────────────────────────────────┘   │
│                                                                             │
│  Each view: Read dependencies → Generate content (with perspectives inline)
│             → Update state.json with progress                               │
└─────────────────────────────────────────────────────────────────────────────┘
                                      │
                                      ▼
┌─────────────────────────────────────────────────────────────────────────────┐
│                          PHASE 3: SUMMARIZE                                 │
│  ┌──────────────────┐    ┌─────────────────────┐    ┌──────────────────┐   │
│  │ Read all view    │───▶│ Detect cross-       │───▶│ Resolve conflicts│   │
│  │ files            │    │ subsystem conflicts │    │ using ADRs       │   │
│  └──────────────────┘    └─────────────────────┘    └────────┬─────────┘   │
│                                                               │             │
│  ┌──────────────────┐                       ┌──────────────▼───────────┐ │
│  │ Move Accepted    │◀─────────────────────────│ Aggregate into            │ │
│  │ ADRs to memory   │                         │ unified AD.md (views include│ │
│  └──────────────────┘                         │ perspective sections)     │ │
│                                             └───────────────────────────────┘ │
└─────────────────────────────────────────────────────────────────────────────┘

Note: Perspectives (Security, Performance, etc.) are now applied during view generation in Phase 2, not as a separate step in Phase 3. This follows the R&W principle: "use them with each view to analyze and validate the qualities of your architecture."

Pre-Flight Validation (MANDATORY - Hard Enforcement)

CRITICAL: These validations are ENFORCED. Execution will HALT if checks fail. Use --force flag only in emergency situations with full understanding of risks.

Before starting Phase 1, you MUST validate prerequisites:

Workflow State Check (unless --force)

  1. Check clarify completion in state.json:
    • Load {REPO_ROOT}/.adlc/architect/state.json
    • Check workflow.clarify_completed field
    • If false or missing:
      ❌ WORKFLOW VALIDATION FAILED
      
      The implement command requires ADRs to be approved via /architect-clarify first.
      
      Current workflow state: clarify_completed = false
      
      Required: Run /architect-clarify and complete Phase 5.5 (ADR Approval)
      
      Options:
      1. Run /architect-clarify to approve ADRs
      2. Use --force to bypass (NOT RECOMMENDED - may cause inconsistent architecture)
      
      ⚠️  Using --force skips important validation steps and may result in:
         - Processing unapproved ADRs
         - Missing critical architectural decisions
         - Incomplete architecture documentation
      
    • HALT execution (unless --force flag provided)

ADR Status Check

  1. Check ADRs exist: Verify {REPO_ROOT}/.adlc/drafts/adr/ or {REPO_ROOT}/.adlc/memory/adr/ exists (individual file format)
  2. Check for Accepted ADRs: Count ADRs with status "Accepted"
    • If zero Accepted ADRs: STOP and output:
      ❌ Cannot proceed: No Accepted ADRs found
      
      The implement command requires ADRs with "Accepted" status.
      Current ADRs are: [list statuses found]
      
      Run /architect-clarify to review and approve ADRs first.
      
    • If ≥1 Accepted ADR: Proceed and report: "✓ Found N Accepted ADRs"

Mandatory Execution Constraints

CRITICAL -- READ THIS BEFORE PROCEEDING

The following constraints are MANDATORY. Violation of any constraint invalidates the output and requires restart.

Constraint 1: View Files MUST Be Written to Disk

You MUST write each view to disk as a separate file before proceeding to the next view. Location: {REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md

  • Do NOT hold views in memory and write only AD.md
  • Do NOT combine multiple views into a single write operation
  • Each file MUST be readable and standalone
  • Minimum content: 20 lines with proper section headers

Constraint 2: State MUST Be Updated After EACH View

You MUST update state.json immediately after EACH individual view file is written to disk and verified readable -- before starting the next view in the DAG. Do NOT batch updates per-subsystem or per-phase. Mark each view's progress as "completed" only AFTER the file exists on disk and you've verified it by reading it back.

Constraint 3: Functional View Checkpoint is MANDATORY

You MUST pause after Functional view for user checkpoint (unless --no-checkpoint). Do NOT silently continue. Present checkpoint options A/B/C/D and WAIT for response. The Functional view is the "cornerstone" -- user approval is required.

Constraint 4: Phase "completed" Requires Verification

You MUST NOT mark phase as "completed" in state.json until:

  • All view files exist on disk (verify by reading each file)
  • AD.md has been written with content aggregated from view files
  • Drafts cleanup has been performed and verified
  • The final verification table (10 checks) has been output

Constraint 5: AD.md Content MUST Come From View Files

You MUST NOT write AD.md directly from ADRs. AD.md content MUST come from reading the generated view files. The flow is strictly: ADRs → Views (files on disk) → AD.md (aggregated from views)

Constraint 6: Phase 3 MUST Read From Disk

You MUST read view files from disk in Phase 3, not from memory. Use file read operations. This ensures resumability and auditability. If a view file cannot be read, STOP and report the error.

Constraint 7: Views MUST Be in Sub-system DAG

You MUST NOT generate a view that is not listed in the sub-system's dag array in state.json. Before generating any view, check the DAG. If the view is absent, mark it as skipped in state.json and proceed. Generating views outside the DAG creates orphaned files and invalidates the architecture.

Constraint 8: AD.md MUST Be Organized by Viewpoint

You MUST organize AD.md by viewpoint (§3.1 Context, §3.2 Functional, §3.3 Information, etc.), NOT by subsystem. Each viewpoint section presents the unified system-level perspective that merges content from all subsystems. Subsystem-specific detail is accessible via "Subsystem Details" links (see Step 3.5).

WRONG (per-subsystem — this is what subsystem view files are for): ## 5. Sub-System: Auth → ### 5.1 Context → ### 5.2 Functional

RIGHT (per-viewpoint — unified across ALL subsystems): ## 3. Architectural Views → ### 3.1 Context View → ### 3.2 Functional View

Constraint 9: Diagrams MUST Use Mermaid Syntax

You MUST use Mermaid syntax for all architectural diagrams in both view files and AD.md. ASCII box-drawing art (characters like ┌, └, ├, │, ───, ═══) is NOT permitted for architecture diagrams.

Accepted Mermaid diagram types:

  • graph TB/LR — architecture, topology, flow diagrams
  • erDiagram — data models and entity relationships
  • sequenceDiagram — interaction flows
  • flowchart — process flows

Directory tree listings (code organization) may use plain text code blocks — these are not architectural diagrams.

PHASE 1: PLAN (Plan Agent)

Objective: Analyze ADRs, detect sub-systems, generate customized DAG, get user approval

Script Action: Run scripts/bash/setup-architect.sh which calls plan-dag internally

Step 1.1: Load and Analyze ADRs

  1. Read ADR Directory: Load ADRs from {REPO_ROOT}/.adlc/drafts/adr/ (and check {REPO_ROOT}/.adlc/memory/adr/ if drafts is empty)
  2. Parse ADR Index: Extract sub-systems from {REPO_ROOT}/.adlc/drafts/adr/adr.md or individual ADR files
  3. Group ADRs by Sub-system: Create mapping of sub-system → ADRs
  4. Validate ADR Status (MANDATORY):
    • Count ADRs by status: Accepted / Proposed / Discovered
    • If zero Accepted ADRs: STOP execution and output error:
      ❌ PHASE 1 BLOCKED: No Accepted ADRs
      
      Found: [N] Proposed, [M] Discovered, [0] Accepted
      
      The implement command ONLY processes "Accepted" ADRs.
      Run /architect-clarify to approve ADRs before implementation.
      
    • Report to user: "✓ Found [N] Accepted ADRs ready for implementation"

ADR Index Table Format:

| ID | Sub-System | Decision | Status | Date | Owner |
|----|------------|----------|--------|------|-------|
| ADR-001 | Core | Microservices architecture | Accepted | 2024-01-15 | @architect |
| ADR-002 | Auth | OAuth2 with PKCE | Accepted | 2024-01-16 | @security |
| ADR-003 | Data | PostgreSQL primary store | Accepted | 2024-01-17 | @data |

Step 1.2: Detect Sub-systems and Characteristics

For each sub-system, analyze ADRs to detect:

Characteristic Detection Pattern DAG Customization
Serverless Lambda, Functions, serverless Deployment view first
Event-driven Events, messaging, async, Kafka, RabbitMQ Include Concurrency view
Data-intensive Analytics, ETL, data pipeline Information view priority
API-first REST, GraphQL, OpenAPI Functional view priority
Multi-region Global, multi-region, geo Deployment + Operational

Step 1.3: Generate Customized DAG per Sub-system

Default DAG (Core Views):

Context → Functional → Information → Development → Deployment

Extended DAG (All Views):

Context → Functional → Information ──┬─→ Development → Deployment → Operational
                                     └─→ Concurrency ─────────────────┘

DAG Customization Rules:

Pattern Detected DAG Modification
Serverless Deployment before Development
Event-driven Add Concurrency after Information
Data-intensive Information has highest priority after Context
Microservices Add Concurrency, expand Functional
Monolith Simplify Functional, skip Concurrency

Step 1.4: Present Plan for User Approval

Sub-System Count Threshold Enforcement (MANDATORY): Regardless of any prior approval from /architect-specify, you MUST apply the following rules before presenting the DAG plan:

Sub-System Count Required Action
1–3 Present plan; auto-approve allowed
4–6 MUST ask user confirmation — do not proceed without explicit approval
>6 MUST suggest grouping and MUST ask confirmation

CRITICAL: Approval from /architect-specify (Phase 0) does NOT substitute for DAG execution plan approval. The user must confirm the per-sub-system DAG plan independently.

Present the execution plan to the user:

## DAG Execution Plan

**Sub-systems detected**: 3
**Total views to generate**: 15 (5 views × 3 sub-systems)

### Sub-system: Core
**ADRs**: ADR-001, ADR-005, ADR-008
**Characteristics**: Microservices, Event-driven
**DAG**: Context → Functional → Information → Concurrency → Development → Deployment

### Sub-system: Auth
**ADRs**: ADR-002, ADR-006
**Characteristics**: API-first
**DAG**: Context → Functional → Information → Development → Deployment

### Sub-system: Data
**ADRs**: ADR-003, ADR-004, ADR-007
**Characteristics**: Data-intensive
**DAG**: Context → Information → Functional → Development → Deployment

---

**Approve this plan?** [Yes/Modify/Cancel]

Step 1.5: Write state.json

After user approval, write the execution plan to {REPO_ROOT}/.adlc/architect/state.json:

{
  "version": "1.1.0",
  "created_at": "2024-01-20T10:30:00Z",
  "updated_at": "2024-01-20T10:30:00Z",
  "phase": "plan_approved",
  "views_mode": "core",
  "workflow": {
    "clarify_completed": false,
    "clarify_completed_at": null,
    "adrs_approved_count": 0,
    "implement_started": false,
    "implement_started_at": null
  },
  "subsystems": [
    {
      "id": "core",
      "name": "Core",
      "adrs": ["ADR-001", "ADR-005", "ADR-008"],
      "characteristics": ["microservices", "event-driven"],
      "dag": ["context", "functional", "information", "concurrency", "development", "deployment"],
      "progress": {
        "context": "pending",
        "functional": "pending",
        "information": "pending",
        "concurrency": "pending",
        "development": "pending",
        "deployment": "pending"
      }
    },
    {
      "id": "auth",
      "name": "Auth",
      "adrs": ["ADR-002", "ADR-006"],
      "characteristics": ["api-first"],
      "dag": ["context", "functional", "information", "development", "deployment"],
      "progress": {
        "context": "pending",
        "functional": "pending",
        "information": "pending",
        "development": "pending",
        "deployment": "pending"
      }
    }
  ],
  "perspectives": ["security", "performance"],
  "output_file": "AD.md"
}

PHASE 2: EXECUTE (Execute Agent)

Objective: Generate views per sub-system following the DAG, with dependency context passing

Script Action: The agent reads state.json and executes views in DAG order

Step 2.1: Read Execution State

  1. Load {REPO_ROOT}/.adlc/architect/state.json
  2. Identify next view(s) to generate (views with all dependencies completed)
  3. Load relevant ADRs for the current sub-system

Step 2.2: Generate Views in DAG Order

For each view in the DAG:

  1. DAG Membership Check: Confirm the view is listed in the sub-system's dag array in state.json. If absent → mark skipped, do NOT generate, continue to next view.
  2. Check Dependencies: Ensure all dependency views are completed
  3. Load Dependency Context: Read completed view files for context
  4. Load View Template: Read from templates/views/{view}.md
  5. Generate View Content: Fill template with ADR-derived content
  6. Write View File: Save to {REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md
  7. Update State: Mark view as "completed" in state.json

View Generation with Dependency Context:

## Generating: Functional View for "Core" sub-system

**Dependencies loaded**:
- Context View: {REPO_ROOT}/.adlc/architect/views/core/context.md (completed)

**ADRs for this view**: ADR-001 (Microservices), ADR-005 (API Gateway)

**Generating content...**

Step 2.3: View Templates and Placeholders

Each view template contains placeholders to be filled:

Placeholder Replacement
[SUB_SYSTEM_NAME] Sub-system name from state.json
[ADR_IDS] Comma-separated ADR IDs
[DATE] Current date (YYYY-MM-DD)
[ENTITY_N] Extracted from ADRs
[COMPONENT_N] Extracted from ADRs

Step 2.4: View Generation Details

Context View

Purpose: System scope and external interactions (blackbox view) Dependencies: None (first in DAG) Template: templates/views/context.md Key Content:

  • System scope description
  • External entities table (stakeholders + external systems only)
  • Context diagram (system as single blackbox)
  • External dependencies table
Functional View (★ CORNERSTONE - USER CHECKPOINT)

Purpose: Internal components, responsibilities, interactions Dependencies: Context View Template: templates/views/functional.md Key Content:

  • Functional elements table
  • Element interactions diagram
  • Functional boundaries

IMPORTANT: After generating the Functional view, execution pauses for user approval. This is the "cornerstone" view that shapes all subsequent views.

Rozanski & Woods: "The Functional view is the cornerstone... It usually drives the shape of other system structures."

Checkpoint Options:

  • A: Approve - Continue to remaining views
  • B: Modify - Edit functional view, then continue
  • C: Restart - Regenerate with feedback
  • D: Cancel - Stop execution

If skipping checkpoint (--no-checkpoint flag): Generate without pause but log warning.

Information View

Purpose: Data storage, management, and flow Dependencies: Context View, Functional View Template: templates/views/information.md Key Content:

  • Data entities table
  • ER diagram
  • Data flow description
Concurrency View (Optional)

Purpose: Runtime processes, threads, coordination Dependencies: Functional View, Information View Template: templates/views/concurrency.md Condition: Only if --views all or --views concurrency Key Content:

  • Process structure table
  • Sequence diagram
  • Coordination mechanisms
Development View

Purpose: Code organization, dependencies, CI/CD Dependencies: Functional View Template: templates/views/development.md Key Content:

  • Code organization structure
  • Module dependencies
  • Build & CI/CD description
Deployment View

Purpose: Physical environment, nodes, networks Dependencies: Development View Template: templates/views/deployment.md Key Content:

  • Runtime environments table
  • Network topology diagram
  • Hardware requirements
Operational View (Optional)

Purpose: Operations, support, maintenance Dependencies: Deployment View Template: templates/views/operational.md Condition: Only if --views all or --views operational Key Content:

  • Operational responsibilities
  • Monitoring & alerting
  • Disaster recovery

Step 2.5: Update Progress in state.json

WARNING: Batching state updates (e.g., updating only after all views for a sub-system are complete) violates Constraint 2. Update state.json immediately after each individual view file is written and verified.

After each view is generated:

{
  "progress": {
    "context": "completed",
    "functional": "completed",
    "information": "in_progress",
    "development": "pending",
    "deployment": "pending"
  },
  "updated_at": "2024-01-20T11:15:00Z"
}

Step 2.6: Resumability

If the agent session is interrupted:

  1. Next session loads state.json
  2. Identifies views with "pending" or "in_progress" status
  3. Continues from where it left off
  4. Skips already "completed" views

Phase 2→3 Gate: Verify View Files Exist (MANDATORY)

Before proceeding to Phase 3, you MUST verify that all expected view files exist on disk:

  1. For each subsystem in state.json, check every view with status "completed"
  2. Verify the file exists: {REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md
  3. Verify each file is readable and has minimum content (≥20 lines)
  4. Mermaid scan (Constraint 9): Scan each view file for ASCII box-drawing characters (┌, └, ├, │, ═, ───). If found in any view that should contain architectural diagrams (context, functional, information, deployment), flag as a warning and note the file for correction.

Verification Checklist (output this table):

Subsystem View File Path Exists Readable Lines Mermaid OK
✓/✗ ✓/✗ ✓/⚠

Gate Decision:

  • If ALL checks pass → Proceed to Phase 3
  • If Mermaid warnings → Log warnings but proceed (non-blocking). Output:
    ⚠️ MERMAID WARNING: ASCII box-drawing art detected in:
    - {subsystem}/{view}: Convert to Mermaid diagram syntax
    
    Proceeding to Phase 3. Fix ASCII diagrams in next iteration.
    
  • If ANY other check fails → STOP and report:
    ❌ PHASE 2→3 GATE BLOCKED
    
    Missing or invalid view files detected:
    - {subsystem}/{view}: [reason]
    
    Regenerate missing views before proceeding to Phase 3.
    

Placeholder Validation (MANDATORY)

Before finalizing any view file, you MUST validate that all placeholders are filled:

Placeholder Patterns to Check

Pattern Example Severity Action Required
[TBD] [TBD] CRITICAL Must be filled before completion
[STAKEHOLDER_*] [STAKEHOLDER_1] CRITICAL Must be replaced with actual stakeholder names
[ENTITY_*] [ENTITY_1] CRITICAL Must be replaced with actual entity names
[COMPONENT_*] [COMPONENT_1] CRITICAL Must be replaced with actual component names
[SUB_SYSTEM_NAME] [SUB_SYSTEM_NAME] CRITICAL Must be replaced with actual sub-system name
[ADR_IDS] [ADR_IDS] HIGH Must be replaced with actual ADR references
[DATE] [DATE] MEDIUM Must be replaced with actual date

Validation Process

  1. Scan each view file after generation for unfilled placeholders
  2. Count occurrences of each pattern
  3. Severity Assessment:
    • CRITICAL: Blocks completion - view cannot be marked "completed"
    • HIGH: Should be filled but non-blocking if context is clear
    • MEDIUM: Nice to have but not required

Validation Report Template

## Placeholder Validation Report

| View | Placeholder | Count | Severity | Status |
|------|-------------|-------|----------|--------|
| context | [STAKEHOLDER_1] | 3 | CRITICAL | ❌ UNFILLED |
| functional | [COMPONENT_1] | 5 | CRITICAL | ❌ UNFILLED |

### Critical Placeholders Unfilled

**❌ VALIDATION FAILED**: Cannot mark views as "completed" with unfilled critical placeholders.

**Required Actions**:
1. Review ADRs for stakeholder names → fill [STAKEHOLDER_*] placeholders
2. Review ADRs for component names → fill [COMPONENT_*] placeholders
3. Re-run view generation with complete information

Enforcement

  • Views with unfilled CRITICAL placeholders CANNOT be marked "completed" in state.json
  • Phase 2→3 gate WILL FAIL if any view has unfilled critical placeholders
  • Use --force to bypass (emergency only - document all unfilled placeholders)

PHASE 3: SUMMARIZE (Summarize Agent)

Objective: Aggregate all views, resolve conflicts, generate unified AD.md

Script Action: Run summarize action

Step 3.1: Read All View Files FROM DISK (MANDATORY)

CRITICAL: You MUST read each view file from the filesystem using actual file read operations. Do NOT use content from memory or from the ADRs directly. The view files are the SOLE source of truth.

  1. Scan Directory: List {REPO_ROOT}/.adlc/architect/views/ directory
  2. Read Each File (MANDATORY - file by file):
    • For each subsystem/view combination in state.json
    • Read the file: {REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md
    • If file cannot be read → STOP and report error:
      ❌ PHASE 3 ERROR: Cannot read view file
      File: {path}
      Error: {error details}
      
      View files must exist and be readable before AD.md generation.
      
  3. Validate Content (MANDATORY):
    • Each view file MUST contain ≥20 lines
    • Each view MUST contain proper section headers (## or ###)
    • If content validation fails → STOP and report:
      ❌ PHASE 3 ERROR: Invalid view file content
      File: {path}
      Lines: {count} (minimum 20 required)
      
      View files must have substantial content before AD.md generation.
      
  4. Organize: Group content by view type across all sub-systems

Directory Structure:

{REPO_ROOT}/.adlc/architect/views/
├── core/
│   ├── context.md
│   ├── functional.md
│   ├── information.md
│   ├── concurrency.md
│   ├── development.md
│   └── deployment.md
├── auth/
│   ├── context.md
│   ├── functional.md
│   ├── information.md
│   ├── development.md
│   └── deployment.md
└── data/
    ├── context.md
    ├── functional.md
    ├── information.md
    ├── development.md
    └── deployment.md

Step 3.2: Detect Cross-Subsystem Conflicts

Compare views across sub-systems for:

Conflict Type Detection Resolution
Naming inconsistency Same component, different names Standardize to ADR terminology
Technology mismatch Different tech for same purpose Defer to relevant ADR
Boundary overlap Components claimed by multiple sub-systems Use ADR scope definitions
Diagram inconsistency Same entity, different representations Unify styling

Step 3.3: Resolve Conflicts Using ADRs

ADRs are the Source of Truth. When conflicts are detected:

  1. Find the relevant ADR(s) that govern the conflicting area
  2. Apply the ADR decision to resolve the conflict
  3. Document the resolution in the unified view
## Conflict Resolution Log

| Conflict | ADR Reference | Resolution |
|----------|---------------|------------|
| Auth component naming | ADR-002 | Standardized to "AuthService" per ADR-002 |
| Database technology | ADR-003 | PostgreSQL confirmed as primary per ADR-003 |

Step 3.4: Aggregate into Unified AD.md

CRITICAL: Viewpoint-Organized Aggregation (Constraint 8)

The AD.md MUST follow the structure below, organized by viewpoint. Each viewpoint section merges content from ALL subsystems into a unified system-level description. Do NOT organize by subsystem -- that structure belongs in the subsystem view files, not in the aggregated AD.md.

For each viewpoint:

  1. Present a system-level summary that shows how all subsystems relate
  2. Include a unified Mermaid diagram showing cross-subsystem interactions
  3. Summarize each subsystem's role within this viewpoint
  4. Link to subsystem details (if 2+ subsystems, per Step 3.5)
Per-Viewpoint Aggregation Recipe
Viewpoint How to Aggregate
Context Single system-level blackbox diagram (Mermaid graph). Subsystems appear as internal blocks only if they have independent external interfaces. Merge and deduplicate stakeholder and external entity tables across all subsystems.
Functional Merged component inventory table across all subsystems. Single unified interaction diagram showing cross-subsystem data flows. Use Mermaid subgraph blocks per subsystem to show boundaries.
Information Consolidated ER diagram (Mermaid erDiagram) combining all subsystem entities. Unified data flow showing how data moves across subsystem boundaries (Mermaid flowchart). Deduplicate entity tables.
Concurrency Merged process structure table. Unified sequence/flow diagrams showing cross-subsystem async interactions.
Development Single code organization tree showing all subsystems as top-level directories. Merged build process and CI/CD pipeline tables. Unified technology stack mapping.
Deployment Single deployment topology diagram (Mermaid graph) showing all subsystems in their runtime environments. Merged runtime environments and hardware requirements tables.
Operational Merged operational responsibilities table. Unified monitoring, alerting, and DR strategy across all subsystems.

Structure of Unified AD.md:

# Architecture Description: [Project Name]

## 1. Document Information
[Version, date, authors, status]

## 2. Architectural Goals & Constraints
[From constitution and constraint ADRs]

## 3. Architectural Views

### 3.1 Context View
[Unified from all sub-system context views]
[Single system-level context diagram]

> **Subsystem Details**: [Core](.adlc/architect/views/core/context.md) | [Auth](.adlc/architect/views/auth/context.md) | [Data](.adlc/architect/views/data/context.md)

### 3.2 Functional View
[Merged functional elements from all sub-systems]
[Unified component diagram]

> **Subsystem Details**: [Core](.adlc/architect/views/core/functional.md) | [Auth](.adlc/architect/views/auth/functional.md) | [Data](.adlc/architect/views/data/functional.md)

### 3.3 Information View
[Consolidated data model]
[Unified ER diagram]

> **Subsystem Details**: [Core](.adlc/architect/views/core/information.md) | [Auth](.adlc/architect/views/auth/information.md) | [Data](.adlc/architect/views/data/information.md)

### 3.4 Concurrency View (if applicable)
[Merged from sub-systems with concurrency]

> **Subsystem Details**: [Core](.adlc/architect/views/core/concurrency.md) | [Auth](.adlc/architect/views/auth/concurrency.md)

### 3.5 Development View
[Unified code organization]

> **Subsystem Details**: [Core](.adlc/architect/views/core/development.md) | [Auth](.adlc/architect/views/auth/development.md) | [Data](.adlc/architect/views/data/development.md)

### 3.6 Deployment View
[Consolidated deployment topology]

> **Subsystem Details**: [Core](.adlc/architect/views/core/deployment.md) | [Auth](.adlc/architect/views/auth/deployment.md) | [Data](.adlc/architect/views/data/deployment.md)

### 3.7 Operational View (if applicable)
[Merged operational concerns]

> **Subsystem Details**: [Core](.adlc/architect/views/core/operational.md) | [Auth](.adlc/architect/views/auth/operational.md)

## 4. Architectural Perspectives

### 4.1 Security Perspective
[Apply security template across all views]

### 4.2 Performance & Scalability Perspective
[Apply performance template across all views]

## 5. Architecture Decision Records Summary
[Index linking to {REPO_ROOT}/.adlc/memory/adr/adr.md]

## 6. Tech Stack Summary
[Consolidated from all ADRs]

Step 3.5: Generate Subsystem View Links (CONDITIONAL)

Condition: Only generate links if len(state.json.subsystems) > 1

For each view section in AD.md:

  1. Collect subsystem links:

    • For each subsystem in state.json
    • Check if view exists in subsystem's dag array
    • Build link: [SubsystemName](.adlc/architect/views/{subsystem-id}/{view}.md)
  2. Format link block:

    > **Subsystem Details**: [Core](path) | [Auth](path) | [Data](path)
    
  3. Handle missing views:

    • If a subsystem doesn't have a particular view (not in dag), skip that subsystem's link
    • Example: If Auth doesn't have Concurrency view, omit from Concurrency links
  4. Single subsystem case:

    • If only 1 subsystem exists, SKIP adding links entirely
    • The unified view is identical to the subsystem view, making links redundant

Example Output (3 subsystems, all have Context view):

### 3.1 Context View
[Unified system-level context]

> **Subsystem Details**: [Core](.adlc/architect/views/core/context.md) | [Auth](.adlc/architect/views/auth/context.md) | [Data](.adlc/architect/views/data/context.md)

Example Output (2 subsystems, only Core has Concurrency):

### 3.4 Concurrency View
[Merged concurrency concerns]

> **Subsystem Details**: [Core](.adlc/architect/views/core/concurrency.md)

Step 3.6: Apply Perspectives

Load perspective templates and apply across all views:

Security Perspective (templates/perspectives/security.md)
  • Authentication & authorization approach
  • Data protection measures
  • Threat model table
Performance Perspective (templates/perspectives/performance.md)
  • Performance requirements table
  • Scalability model
  • Capacity planning

Step 3.7: ADR Lifecycle Management (MANDATORY)

After generating AD.md, perform ALL of the following steps:

Step 1: Filter Accepted ADRs

  • Identify ADRs with exact status "Accepted" only
  • MUST remain in drafts: Any ADR with status "Proposed", "Discovered", "Deprecated", or "Superseded" — these are NOT eligible for promotion
  • Verification: After filtering, count non-Accepted ADRs in the promotion set. If >0, STOP and fix before proceeding.

Step 2: Copy to Canonical Location (MANDATORY)

  • Move Accepted ADR files into {REPO_ROOT}/.adlc/memory/adr/
  • Create the file if it doesn't exist, or merge with existing content
  • VERIFY: Read the file back and confirm ADRs are present

Step 3: Clean Up Drafts (MANDATORY)

  • Move each promoted ADR file from {REPO_ROOT}/.adlc/drafts/adr/ to {REPO_ROOT}/.adlc/memory/adr/
  • If no ADRs remain in drafts → the setup script cleans up empty directories
  • VERIFY: Confirm:
    • No duplicate ADRs exist (same ID in both locations)
    • Remaining ADRs (if any) are Proposed/Discovered only
    • adr.md index regenerated for both scopes (drafts + memory)

Step 3b: Generate Memory ADR Index (MANDATORY)

After moving Accepted ADRs to .adlc/memory/adr/, generate a memory index file at {REPO_ROOT}/.adlc/memory/adr/adr.md using the generate_adr_index function from the setup script (the same function that generates the drafts index, but with scope=memory):

source "{REPO_ROOT}/.agents/skills/architect-implement/scripts/bash/setup-architect.sh"
generate_adr_index memory

This writes {REPO_ROOT}/.adlc/memory/adr/adr.md with the 7-column schema, parsing YAML frontmatter via parse_fm_field. The index format:

# Architecture Decision Records (Memory)

> Auto-generated by /architect-implement. Accepted ADRs only.
> Source: .adlc/memory/adr/ADR-*.md

## ADR Index

| ID | Sub-System | Decision | Status | Date |
|----|------------|----------|--------|------|
| ADR-301 | System | Agent-Agnostic Container Architecture | Completed | 2026-08-08 |

This index is consumed by team-boot for session-start injection and by architect-analyze for architecture review (similar to how CDR.md is used for team-level context).

Step 4: Report Lifecycle Changes (MANDATORY) Output this summary to the user:

📋 ADR Lifecycle Summary:
├── Promoted to memory: [N] Accepted ADRs
├── Remaining in drafts: [M] ADRs (Proposed/Discovered)
├── Duplicates found: [0] ✓
└── Cleanup verified: ✓

If ANY step fails: STOP and fix before marking Phase 3 complete.

Step 3.8: Generate Final Report

## Architecture Description Generated

**Output**: AD.md (project root)
**Views Mode**: [core|all|custom]
**Sub-systems Processed**: N

**Views Generated**:
| Sub-system | Views | Status |
|------------|-------|--------|
| Core | Context, Functional, Information, Concurrency, Development, Deployment | ✓ |
| Auth | Context, Functional, Information, Development, Deployment | ✓ |
| Data | Context, Functional, Information, Development, Deployment | ✓ |

**Perspectives Applied**:
- [x] Security
- [x] Performance & Scalability

**Conflicts Resolved**: M
**ADR Coverage**: X/Y ADRs incorporated

**ADR Lifecycle**:
- Promoted to canonical: N ADRs
- Remaining in drafts: M ADRs

**Recommended Next Steps**:
1. Review generated AD.md for accuracy
2. Run `/architect-analyze` for consistency validation
3. Share with stakeholders for review
4. Run `/architect-analyze` to validate the generated architecture

Final Completion Verification (MANDATORY)

Before marking state.json phase as "completed", verify ALL outputs:

Run this 10-point verification checklist:

Check Expected Verification Method Status
1. View files on disk N files (one per view per subsystem) List {REPO_ROOT}/.adlc/architect/views/ ☐
2. AD.md exists Yes, at project root Check file existence ☐
3. AD.md content size >200 lines Count lines in AD.md ☐
4. AD.md has all views N sections (## 3.x headers) Parse AD.md headers ☐
5. Memory ADRs promoted N Accepted ADRs Count files in {REPO_ROOT}/.adlc/memory/adr/ ☐
6. Drafts cleaned No duplicates Compare drafts vs memory ☐
7. state.json consistent All views "completed" Verify progress field ☐
8. Subsystem links (if applicable) Links in AD.md (if 2+ subsystems) Scan AD.md for "Subsystem Details" ☐
9. Viewpoint-organized (Constraint 8) No ## N. Sub-System: sections Scan AD.md for per-subsystem top-level headers ☐
10. Mermaid diagrams (Constraint 9) No ASCII box-drawing art Scan AD.md for ┌, └, ├, ═ characters ☐

Gate Rule:

  • If ALL checks pass (☑): Mark phase as "completed" in state.json
  • If ANY check fails (☒): Do NOT mark as completed. Fix the issue and re-verify.

Output to User:

✅ Architecture Description Generation Complete

Verification Results:
├── View files: [N] generated ✓
├── AD.md: [lines] lines, [sections] views ✓
├── Subsystem links: [N] links (if applicable) ✓
├── Viewpoint-organized: ✓
├── Mermaid diagrams: ✓
├── ADRs promoted: [N] to memory ✓
├── Drafts cleaned: [N] remaining ✓
└── State consistent: ✓

Status: READY FOR USE

State File Schema

Location: {REPO_ROOT}/.adlc/architect/state.json

{
  "version": "1.1.0",
  "created_at": "ISO8601 timestamp",
  "updated_at": "ISO8601 timestamp",
  "phase": "planning | plan_approved | executing | summarizing | completed",
  "views_mode": "core | all | custom",
  "subsystems": [
    {
      "id": "lowercase-kebab-case",
      "name": "Display Name",
      "adrs": ["ADR-001", "ADR-002"],
      "characteristics": ["microservices", "event-driven"],
      "dag": ["context", "functional", "information", "development", "deployment"],
      "progress": {
        "context": "pending | in_progress | completed | skipped",
        "functional": "pending | in_progress | completed | skipped"
      }
    }
  ],
  "perspectives": ["security", "performance"],
  "conflicts_detected": [],
  "conflicts_resolved": [],
  "output_file": "AD.md"
}

Key Rules

ADR Traceability

  • Every view section must reference source ADRs
  • No content without ADR backing
  • ADRs are source of truth for conflict resolution

State Persistence

  • Always update state.json after each operation
  • Resume gracefully from any interruption
  • Track progress at view granularity

Multi-Agent Compatibility

  • State file works with any AI agent (Claude, Copilot, Cursor, etc.)
  • No agent-specific dependencies
  • Human-readable state for debugging

Diagram Quality

  • Validate Mermaid syntax before writing
  • Consistent styling across sub-systems
  • Unified diagrams in final AD.md

Context

$ARGUMENTS

Next Steps

After implement completes, run /architect-analyze to validate consistency and quality.

Verification

  • AD.md exists at {REPO_ROOT}/AD.md with more than 200 lines and all viewpoint sections (## 3.x headers).
  • Per-subsystem view files exist at {REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md for every completed view.
  • state.json is consistent: all generated views are marked "completed" and the phase is "completed".
  • Accepted ADRs promoted: all ADRs with status "Accepted" are moved to {REPO_ROOT}/.adlc/memory/adr/; the memory index is regenerated at {REPO_ROOT}/.adlc/memory/adr/adr.md.
  • Drafts cleaned up: promoted ADR files moved from {REPO_ROOT}/.adlc/drafts/adr/ to {REPO_ROOT}/.adlc/memory/adr/; no duplicates remain; any remaining drafts are Proposed/Discovered only.
  • AD.md is viewpoint-organized: sections are grouped by viewpoint (## 3. Architectural Views → ### 3.1 Context View, etc.), not by subsystem.
  • Mermaid-only diagrams: no ASCII box-drawing characters (┌, └, ├, │, ═, ───) are used for architectural diagrams.
  • Placeholder validation passed: no critical placeholders ([TBD], [STAKEHOLDER_*], [ENTITY_*], [COMPONENT_*], [SUB_SYSTEM_NAME]) remain unfilled in view files.
  • Subsystem detail links are present in AD.md when two or more subsystems were processed.
Files (adlc-team-skills)
  • scripts
    • bash
      • ascii-generator.sh 17.8 KB
        #!/usr/bin/env bash
        # ASCII diagram generator for architecture views
        # Generates ASCII art for all 7 Rozanski & Woods architectural views
        #
        # Core Views (always generated with --views=core):
        #   - Context, Functional, Information, Development, Deployment
        #
        # Optional Views (only with --views=all or --views=concurrency,operational):
        #   - Concurrency (3.4)
        #   - Operational (3.7)
        
        # Generate Context View diagram (system boundary)
        # CRITICAL: System must be shown as a SINGLE BLACKBOX - no internal components
        # Only show: Stakeholders (human actors) + External systems (third-party, outside your control)
        # DO NOT show: Internal databases, services, caches (those go in Deployment/Functional views)
        generate_context_ascii() {
            local system_name="${1:-System}"
            
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                     Context View Diagram                     │
        │            (System shown as single blackbox)                 │
        └─────────────────────────────────────────────────────────────┘
        
                STAKEHOLDERS                           EXTERNAL SYSTEMS
                ────────────                           ────────────────
        
            ┌──────────────┐                         ┌────────────────┐
            │    Users     │                         │    Payment     │
            │  (End Users) │                         │   Provider     │
            └──────┬───────┘                         │   (External)   │
                   │                                 └───────┬────────┘
                   │ Uses                                    │
                   │                                         │ Processes
                   ▼                                         │ payments
            ┌─────────────────────────────────────────────────────────┐
            │                                                         │
            │                    ┌─────────────────┐                  │
            │                    │                 │                  │
            │                    │     SYSTEM      │◄─────────────────┘
            │                    │   (This App)    │
            │                    │                 │──────────────────┐
            │                    └─────────────────┘                  │
            │                         ▲                               │
            │                         │                               │
            └─────────────────────────│───────────────────────────────┘
                                      │ Manages                       │
            ┌──────────────┐          │                               ▼
            │    Admins    │──────────┘                    ┌────────────────┐
            │(Administrators)                              │   Identity     │
            └──────────────┘                               │   Provider     │
                                                           │   (External)   │
                                                           └────────────────┘
        
        Legend:
          ─────►  Data/control flow crossing system boundary
          [SYSTEM] = Single blackbox (internal details in Functional/Deployment views)
          (External) = Third-party services outside your control
        EOF
        }
        
        # Generate Functional View diagram (component interactions)
        generate_functional_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                   Functional View Diagram                    │
        └─────────────────────────────────────────────────────────────┘
        
                  User Request
                       │
                       ▼
            ┌──────────────────────┐
            │    API Gateway       │
            └──────────┬───────────┘
                       │
                ┏──────┴──────┓
                ▼             ▼
        ┌───────────────┐  ┌───────────────┐
        │ Authentication│  │   Business    │
        │    Service    │  │     Logic     │
        └───────┬───────┘  └───────┬───────┘
                │                  │
                └──────────┬───────┘
                           ▼
                ┌──────────────────────┐
                │   Data Access Layer  │
                └──────────┬───────────┘
                           │
                    ┏──────┴──────┓
                    ▼             ▼
            ┌─────────────┐  ┌─────────────┐
            │  Database   │  │    Cache    │
            └─────────────┘  └─────────────┘
        EOF
        }
        
        # Generate Information View diagram (data entities)
        generate_information_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                  Information View Diagram                    │
        └─────────────────────────────────────────────────────────────┘
        
        ┌──────────┐         ┌──────────┐         ┌──────────┐
        │   User   │1      n │  Order   │1      n │OrderItem │
        ├──────────┤◄────────├──────────┤◄────────├──────────┤
        │ id (PK)  │         │ id (PK)  │         │ id (PK)  │
        │ email    │         │ user_id  │         │ order_id │
        │ name     │         │ status   │         │product_id│
        │created_at│         │ total    │         │ quantity │
        └──────────┘         │created_at│         │ price    │
                             └──────────┘         └────┬─────┘
                                                       │
                                                       │n
                                                       ▼
                                                 ┌──────────┐
                                                 │ Product  │
                                                 ├──────────┤
                                                 │ id (PK)  │
                                                 │ name     │
                                                 │ price    │
                                                 │ sku      │
                                                 └──────────┘
        
        Key: PK = Primary Key, FK = Foreign Key
             1 = One, n = Many, ◄──── = Relationship
        EOF
        }
        
        # Generate Concurrency View diagram (process timeline)
        # OPTIONAL VIEW: Only generated when --views=all or --views=concurrency
        generate_concurrency_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                  Concurrency View Diagram                    │
        └─────────────────────────────────────────────────────────────┘
        
        User    WebServer   AppServer    Worker    Database
          │         │           │           │          │
          │─Request─>│           │           │          │
          │         │           │           │          │
          │         │─Process──>│           │          │
          │         │           │           │          │
          │         │           │──Query───────────────>│
          │         │           │           │          │
          │         │           │<──Results─────────────│
          │         │           │           │          │
          │         │           │─Queue Job─>│          │
          │         │           │           │          │
          │         │           │           │──Update──>│
          │         │<─Response─│           │          │
          │         │           │           │<─Done────│
          │<─Result─│           │           │          │
          │         │           │           │          │
        
        Processes run concurrently:
        - Main Request/Response Flow (vertical)
        - Background Worker Processing (parallel)
        EOF
        }
        
        # Generate Development View diagram (module dependencies)
        generate_development_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                  Development View Diagram                    │
        └─────────────────────────────────────────────────────────────┘
        
        Directory Structure:
        
        project-root/
        ├── src/
        │   ├── api/              ◄─── API Layer (Controllers)
        │   │   └── routes/           │
        │   │                          │ depends on
        │   ├── services/         ◄───┘
        │   │   └── business/      ◄─── Services Layer
        │   │                          │
        │   ├── repositories/          │ depends on
        │   │   └── data/          ◄───┘
        │   │                       ◄─── Data Access Layer
        │   ├── models/                │
        │   │   └── entities/      ◄───┘ depends on
        │   │                       ◄─── Models (Shared)
        │   └── utils/
        │       └── helpers/       ◄─── Utilities (Shared)
        │
        ├── tests/
        │   ├── unit/
        │   ├── integration/
        │   └── e2e/
        │
        └── docs/
        
        Dependency Rules:
        - API → Services → Repositories → Models
        - No circular dependencies
        - Utilities shared across layers
        EOF
        }
        
        # Generate Deployment View diagram (infrastructure)
        generate_deployment_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                  Deployment View Diagram                     │
        └─────────────────────────────────────────────────────────────┘
        
                                Internet
                                    │
                                    ▼
                           ┌────────────────┐
                           │ Load Balancer  │
                           │   (ALB/Nginx)  │
                           └────────┬───────┘
                                    │
                ┌───────────────────┼───────────────────┐
                │                   │                   │
                ▼                   ▼                   ▼
        ┌───────────────┐  ┌───────────────┐  ┌───────────────┐
        │  Web Server 1 │  │  Web Server 2 │  │  Web Server 3 │
        │   (Public)    │  │   (Public)    │  │   (Public)    │
        └───────┬───────┘  └───────┬───────┘  └───────┬───────┘
                │                   │                   │
                └───────────────────┼───────────────────┘
                                    │
                                    ▼
                           ┌────────────────┐
                           │   App Tier     │
                           │   (Private)    │
                           └────────┬───────┘
                                    │
                ┌───────────────────┼───────────────────┐
                │                   │                   │
                ▼                   ▼                   ▼
        ┌───────────────┐  ┌───────────────┐  ┌───────────────┐
        │   Database    │  │  Redis Cache  │  │    Object     │
        │   (Primary)   │  │               │  │   Storage     │
        │   (Private)   │  │   (Private)   │  │   (S3/Blob)   │
        └───────┬───────┘  └───────────────┘  └───────────────┘
                │
                ▼
        ┌───────────────┐
        │   Database    │
        │   (Replica)   │
        │   (Private)   │
        └───────────────┘
        EOF
        }
        
        # Generate Operational View diagram (operational workflow)
        # OPTIONAL VIEW: Only generated when --views=all or --views=operational
        generate_operational_ascii() {
            cat <<'EOF'
        ┌─────────────────────────────────────────────────────────────┐
        │                 Operational View Diagram                     │
        └─────────────────────────────────────────────────────────────┘
        
        Deployment Workflow:
        
            START
              │
              ▼
        ┌──────────────┐
        │  Run Tests   │──┐
        │  & Build     │  │ Fail
        └──────┬───────┘  │
               │ Pass     │
               ▼          │
        ┌──────────────┐  │
        │  Deploy to   │  │
        │   Staging    │  │
        └──────┬───────┘  │
               │          │
               ▼          │
        ┌──────────────┐  │
        │Run Staging   │──┤ Fail
        │    Tests     │  │
        └──────┬───────┘  │
               │ Pass     │
               ▼          │
        ┌──────────────┐  │
        │   Manual     │──┤ Reject
        │  Approval?   │  │
        └──────┬───────┘  │
               │ Approve  │
               ▼          │
        ┌──────────────┐  │
        │  Deploy to   │  │
        │ Production   │  │
        └──────┬───────┘  │
               │          │
               ▼          │
        ┌──────────────┐  │
        │   Monitor    │  │
        │   Health     │  │
        └──────┬───────┘  │
               │          │
           ┌───┴───┐      │
           │Healthy│      │
           ▼       ▼      │
          YES      NO     │
           │        │     │
           │   ┌────────┐│
           │   │Rollback││
           │   └────┬───┘│
           │        │    │
           ▼        ▼    ▼
          END    Alert Team
        
        Monitoring: Continuous
        Backups: Daily automated
        On-call: 24/7 rotation
        EOF
        }
        
        # Main function to generate diagram for a specific view
        # Usage: generate_ascii_diagram "context" "System Name"
        generate_ascii_diagram() {
            local view_type="$1"
            local system_name="${2:-System}"
            
            case "$view_type" in
                context)
                    generate_context_ascii "$system_name"
                    ;;
                functional)
                    generate_functional_ascii
                    ;;
                information)
                    generate_information_ascii
                    ;;
                concurrency)
                    generate_concurrency_ascii
                    ;;
                development)
                    generate_development_ascii
                    ;;
                deployment)
                    generate_deployment_ascii
                    ;;
                operational)
                    generate_operational_ascii
                    ;;
                *)
                    echo "Error: Unknown view type '$view_type'" >&2
                    return 1
                    ;;
            esac
        }
        
        # Export functions for use in other scripts
        export -f generate_context_ascii
        export -f generate_functional_ascii
        export -f generate_information_ascii
        export -f generate_concurrency_ascii
        export -f generate_development_ascii
        export -f generate_deployment_ascii
        export -f generate_operational_ascii
        export -f generate_ascii_diagram
        
      • common.sh 3.1 KB
        #!/usr/bin/env bash
        #
        # Minimal common helpers for adlc-skills architect-* skills.
        # Bundled with the skill so it works standalone, outside the Spec Kit extension system.
        
        # Locate the project root by walking up from CWD until we find .adlc or .git.
        _get_project_root() {
            local dir
            dir="$(pwd)"
            while [ "$dir" != "/" ]; do
                if [ -d "$dir/.adlc" ] || [ -d "$dir/.git" ]; then
                    echo "$dir"
                    return 0
                fi
                dir="$(dirname "$dir")"
            done
            # Fallback: current working directory.
            echo "$(pwd)"
        }
        
        # Seed bundled templates into the project's .adlc/templates/ directory.
        # Only copies files when the destination does not exist, so user customizations are preserved.
        _seed_templates() {
            local repo_root="${1:-$(_get_project_root)}"
            local script_dir
            script_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
            local src_dir="$script_dir/../../templates"
            local dest_dir="$repo_root/.adlc/templates"
        
            [ -d "$src_dir" ] || return 0
        
            mkdir -p "$dest_dir"
        
            local f basename
            for f in "$src_dir"/*; do
                [ -e "$f" ] || continue
                basename=$(basename "$f")
                if [ -d "$f" ]; then
                    if [ ! -d "$dest_dir/$basename" ]; then
                        cp -r "$f" "$dest_dir/$basename"
                    fi
                else
                    if [ ! -f "$dest_dir/$basename" ]; then
                        cp "$f" "$dest_dir/$basename"
                    fi
                fi
            done
        }
        
        # Emulates the get_feature_paths function from the Spec Kit common.sh.
        # The architect setup script evals this output to obtain REPO_ROOT.
        get_feature_paths() {
            local repo_root
            repo_root="$(_get_project_root)"
            _seed_templates "$repo_root"
            echo "REPO_ROOT=\"$repo_root\""
        }
        
        # Get architecture diagram format (mermaid or ascii).
        # Override via ARCHITECTURE_DIAGRAM_FORMAT env var; defaults to "mermaid".
        # Invalid values fall back to "mermaid".
        get_architecture_diagram_format() {
            local format="${ARCHITECTURE_DIAGRAM_FORMAT:-mermaid}"
            if [[ "$format" == "mermaid" || "$format" == "ascii" ]]; then
                echo "$format"
            else
                echo "mermaid"
            fi
        }
        
        # Validate Mermaid diagram syntax (lightweight regex validation).
        # Returns 0 if valid, 1 if invalid.
        # Args: $1 - Mermaid code string
        validate_mermaid_syntax() {
            local mermaid_code="$1"
        
            # Check if empty
            if [[ -z "$mermaid_code" ]]; then
                return 1
            fi
        
            # Check for basic Mermaid diagram types
            if ! echo "$mermaid_code" | grep -qE '^(graph|flowchart|sequenceDiagram|classDiagram|stateDiagram|erDiagram|gantt|pie|journey|gitGraph|mindmap|timeline)'; then
                return 1
            fi
        
            # Check for balanced brackets/parentheses (simplified)
            local open_brackets close_brackets open_parens close_parens
            open_brackets=$(echo "$mermaid_code" | grep -o '\[' | wc -l)
            close_brackets=$(echo "$mermaid_code" | grep -o '\]' | wc -l)
            open_parens=$(echo "$mermaid_code" | grep -o '(' | wc -l)
            close_parens=$(echo "$mermaid_code" | grep -o ')' | wc -l)
        
            if [[ $open_brackets -ne $close_brackets ]] || [[ $open_parens -ne $close_parens ]]; then
                return 1
            fi
        
            # Basic syntax passed
            return 0
        }
        
      • mermaid-generator.sh 8.9 KB
        #!/usr/bin/env bash
        # Mermaid diagram generator for architecture views
        # Generates Mermaid code for all 7 Rozanski & Woods architectural views
        #
        # Core Views (always generated with --views=core):
        #   - Context, Functional, Information, Development, Deployment
        #
        # Optional Views (only with --views=all or --views=concurrency,operational):
        #   - Concurrency (3.4)
        #   - Operational (3.7)
        
        # Generate Context View diagram (system boundary)
        # CRITICAL: System must be shown as a SINGLE BLACKBOX - no internal components
        # Only show: Stakeholders (human actors) + External systems (third-party, outside your control)
        # DO NOT show: Internal databases, services, caches (those go in Deployment/Functional views)
        generate_context_mermaid() {
            local system_name="${1:-System}"
            
            cat <<'EOF'
        graph TD
            %% Stakeholders (human actors interacting with the system)
            Users["👥 Users/Clients"]
            Admins["👤 Administrators"]
            
            %% THE SYSTEM - Single blackbox (NO internal components)
            System["🏢 System<br/>(This Application)"]
            
            %% External Systems (third-party services outside your control)
            ExtPayment["💳 Payment Provider<br/>(External)"]
            ExtAuth["🔐 Identity Provider<br/>(External)"]
            ExtAPI["🌐 Partner API<br/>(External)"]
            
            %% Stakeholder interactions
            Users -->|"Uses"| System
            Admins -->|"Manages"| System
            
            %% External system integrations
            System -->|"Processes payments"| ExtPayment
            System -->|"Authenticates via"| ExtAuth
            System -->|"Exchanges data"| ExtAPI
            
            %% Styling
            classDef systemNode fill:#f47721,stroke:#333,stroke-width:3px,color:#fff
            classDef stakeholderNode fill:#4a9eff,stroke:#333,stroke-width:1px,color:#fff
            classDef externalNode fill:#e0e0e0,stroke:#333,stroke-width:1px
            
            class System systemNode
            class Users,Admins stakeholderNode
            class ExtPayment,ExtAuth,ExtAPI externalNode
        EOF
        }
        
        # Generate Functional View diagram (component interactions)
        generate_functional_mermaid() {
            cat <<'EOF'
        graph TD
            APIGateway["API Gateway"]
            AuthService["Authentication<br/>Service"]
            BusinessLogic["Business Logic<br/>Layer"]
            DataAccess["Data Access<br/>Layer"]
            Cache["Cache Layer"]
            
            APIGateway -->|Routes| AuthService
            APIGateway -->|Routes| BusinessLogic
            AuthService -->|Validates| BusinessLogic
            BusinessLogic -->|Queries| DataAccess
            BusinessLogic -->|Caches| Cache
            DataAccess -->|Reads/Writes| Cache
            
            classDef serviceNode fill:#4a9eff,stroke:#333,stroke-width:2px,color:#fff
            classDef dataNode fill:#66c2a5,stroke:#333,stroke-width:2px,color:#fff
            
            class APIGateway,AuthService,BusinessLogic serviceNode
            class DataAccess,Cache dataNode
        EOF
        }
        
        # Generate Information View diagram (data entities and relationships)
        generate_information_mermaid() {
            cat <<'EOF'
        erDiagram
            User ||--o{ Session : has
            User ||--o{ Order : places
            Order ||--|{ OrderItem : contains
            OrderItem }o--|| Product : references
            Product ||--o{ Inventory : tracked_in
            User ||--o{ Address : has
            Order }o--|| Address : ships_to
            
            User {
                int id PK
                string email
                string name
                timestamp created_at
            }
            
            Order {
                int id PK
                int user_id FK
                string status
                decimal total
                timestamp created_at
            }
            
            Product {
                int id PK
                string name
                decimal price
                string sku
            }
        EOF
        }
        
        # Generate Concurrency View diagram (process timeline)
        # OPTIONAL VIEW: Only generated when --views=all or --views=concurrency
        generate_concurrency_mermaid() {
            cat <<'EOF'
        sequenceDiagram
            participant User
            participant WebServer
            participant AppServer
            participant Worker
            participant Database
            
            User->>WebServer: HTTP Request
            WebServer->>AppServer: Process Request
            AppServer->>Database: Query Data
            Database-->>AppServer: Return Results
            
            par Background Processing
                AppServer->>Worker: Queue Background Job
                Worker->>Database: Update Records
            end
            
            AppServer-->>WebServer: Response
            WebServer-->>User: HTTP Response
        EOF
        }
        
        # Generate Development View diagram (module dependencies)
        generate_development_mermaid() {
            cat <<'EOF'
        graph LR
            API["🔌 API Layer"]
            Services["⚙️ Services Layer"]
            Repositories["💾 Repositories"]
            Models["📦 Models"]
            Utils["🛠️ Utilities"]
            
            API -->|depends on| Services
            Services -->|depends on| Repositories
            Repositories -->|depends on| Models
            Services -->|uses| Utils
            API -->|uses| Utils
            
            classDef layerNode fill:#9b59b6,stroke:#333,stroke-width:2px,color:#fff
            classDef supportNode fill:#95a5a6,stroke:#333,stroke-width:1px,color:#fff
            
            class API,Services,Repositories layerNode
            class Models,Utils supportNode
        EOF
        }
        
        # Generate Deployment View diagram (infrastructure)
        generate_deployment_mermaid() {
            cat <<'EOF'
        graph TB
            subgraph "Production Environment"
                LB["⚖️ Load Balancer"]
                
                subgraph "Application Tier"
                    Web1["Web Server 1"]
                    Web2["Web Server 2"]
                    Web3["Web Server 3"]
                end
                
                subgraph "Data Tier"
                    DB_Primary["🗄️ Database<br/>Primary"]
                    DB_Replica["🗄️ Database<br/>Replica"]
                    Cache["💾 Redis Cache"]
                end
                
                subgraph "Storage Tier"
                    S3["☁️ Object Storage"]
                end
            end
            
            Internet["🌐 Internet"] -->|HTTPS| LB
            LB -->|Distributes| Web1
            LB -->|Distributes| Web2
            LB -->|Distributes| Web3
            
            Web1 -->|Reads/Writes| DB_Primary
            Web2 -->|Reads/Writes| DB_Primary
            Web3 -->|Reads/Writes| DB_Primary
            
            DB_Primary -->|Replicates to| DB_Replica
            
            Web1 -->|Caches| Cache
            Web2 -->|Caches| Cache
            Web3 -->|Caches| Cache
            
            Web1 -->|Stores files| S3
            Web2 -->|Stores files| S3
            Web3 -->|Stores files| S3
            
            classDef infraNode fill:#e74c3c,stroke:#333,stroke-width:2px,color:#fff
            classDef dataNode fill:#3498db,stroke:#333,stroke-width:2px,color:#fff
            
            class LB,Web1,Web2,Web3 infraNode
            class DB_Primary,DB_Replica,Cache,S3 dataNode
        EOF
        }
        
        # Generate Operational View diagram (operational workflow)
        # OPTIONAL VIEW: Only generated when --views=all or --views=operational
        generate_operational_mermaid() {
            cat <<'EOF'
        flowchart TD
            Start([🚀 Deployment Initiated])
            BuildTests{Run Tests<br/>& Build}
            BuildSuccess[✅ Build Success]
            BuildFail[❌ Build Failed]
            
            Deploy[📦 Deploy to Staging]
            StagingTests{Staging Tests<br/>Pass?}
            
            ManualApproval{Manual<br/>Approval?}
            ProdDeploy[🎯 Deploy to Production]
            
            Monitor[📊 Monitor Health]
            HealthCheck{System<br/>Healthy?}
            
            Rollback[⏪ Rollback]
            Alert[🚨 Alert Team]
            Complete([✅ Deployment Complete])
            
            Start --> BuildTests
            BuildTests -->|Pass| BuildSuccess
            BuildTests -->|Fail| BuildFail
            
            BuildSuccess --> Deploy
            BuildFail --> Alert
            
            Deploy --> StagingTests
            StagingTests -->|Pass| ManualApproval
            StagingTests -->|Fail| Alert
            
            ManualApproval -->|Approved| ProdDeploy
            ManualApproval -->|Rejected| Alert
            
            ProdDeploy --> Monitor
            Monitor --> HealthCheck
            
            HealthCheck -->|Healthy| Complete
            HealthCheck -->|Issues| Rollback
            
            Rollback --> Alert
            
            classDef successNode fill:#27ae60,stroke:#333,stroke-width:2px,color:#fff
            classDef errorNode fill:#e74c3c,stroke:#333,stroke-width:2px,color:#fff
            classDef processNode fill:#3498db,stroke:#333,stroke-width:2px,color:#fff
            
            class BuildSuccess,Complete successNode
            class BuildFail,Alert,Rollback errorNode
            class Deploy,ProdDeploy,Monitor processNode
        EOF
        }
        
        # Main function to generate diagram for a specific view
        # Usage: generate_mermaid_diagram "context" "System Name"
        generate_mermaid_diagram() {
            local view_type="$1"
            local system_name="${2:-System}"
            
            case "$view_type" in
                context)
                    generate_context_mermaid "$system_name"
                    ;;
                functional)
                    generate_functional_mermaid
                    ;;
                information)
                    generate_information_mermaid
                    ;;
                concurrency)
                    generate_concurrency_mermaid
                    ;;
                development)
                    generate_development_mermaid
                    ;;
                deployment)
                    generate_deployment_mermaid
                    ;;
                operational)
                    generate_operational_mermaid
                    ;;
                *)
                    echo "Error: Unknown view type '$view_type'" >&2
                    return 1
                    ;;
            esac
        }
        
        # Export functions for use in other scripts
        export -f generate_context_mermaid
        export -f generate_functional_mermaid
        export -f generate_information_mermaid
        export -f generate_concurrency_mermaid
        export -f generate_development_mermaid
        export -f generate_deployment_mermaid
        export -f generate_operational_mermaid
        export -f generate_mermaid_diagram
        
      • setup-architect.sh 54 KB
        #!/usr/bin/env bash
        
        set -e
        
        JSON_MODE=false
        ACTION=""
        ARGS=()
        VIEWS="core"
        ADR_HEURISTIC="surprising"
        DECOMPOSE=true
        
        # Get script directory FIRST (needed for common.sh sourcing)
        SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
        
        # Find project root by walking up from CWD
        _find_project_root() {
            local dir="$(pwd)"
            while [ "$dir" != "/" ]; do
                if [ -d "$dir/.adlc" ] || [ -d "$dir/.git" ]; then
                    echo "$dir"
                    return 0
                fi
                dir="$(dirname "$dir")"
            done
            return 1
        }
        
        PROJECT_ROOT="$(_find_project_root)" || PROJECT_ROOT="$(pwd)"
        
        # Load common functions - use absolute path from project root
        if [[ -n "$PROJECT_ROOT" && -f "$PROJECT_ROOT/.adlc/scripts/bash/common.sh" ]]; then
            source "$PROJECT_ROOT/.adlc/scripts/bash/common.sh"
        elif [[ -f "$SCRIPT_DIR/common.sh" ]]; then
            source "$SCRIPT_DIR/common.sh"
        else
            echo "Error: Could not find common.sh" >&2
            exit 1
        fi
        
        # Get all paths and variables from common functions
        eval "$(get_feature_paths)"
        
        # Parse arguments (run after common.sh to have REPO_ROOT defined)
        while [[ $# -gt 0 ]]; do
            case "$1" in
                --json)
                    JSON_MODE=true
                    shift
                    ;;
                --views)
                    shift
                    VIEWS="$1"
                    shift
                    ;;
                --views=*)
                    VIEWS="${1#*=}"
                    shift
                    ;;
                --adr-heuristic)
                    shift
                    ADR_HEURISTIC="$1"
                    shift
                    ;;
                --adr-heuristic=*)
                    ADR_HEURISTIC="${1#*=}"
                    shift
                    ;;
                --no-decompose)
                    DECOMPOSE=false
                    shift
                    ;;
                --no-decompose=*)
                    DECOMPOSE=false
                    shift
                    ;;
                init|map|update|review|specify|implement|clarify|analyze|validate|plan-dag|execute-dag|summarize)
                    ACTION="$1"
                    shift
                    ;;
                --help|-h)
                    echo "Usage: $0 [action] [context] [--json] [--views VIEWS] [--adr-heuristic HEURISTIC]"
                    echo ""
                    echo "Actions:"
                    echo "  specify    Interactive PRD exploration to create system ADRs (greenfield)"
                    echo "  clarify    Refine and resolve ambiguities in existing ADRs"
                    echo "  init       Reverse-engineer architecture from existing codebase (brownfield)"
                    echo "  implement  Generate full Architecture Description (AD.md) from ADRs"
                    echo "  analyze    Validate architecture for consistency and quality issues"
                    echo "  validate   Validate plan alignment with architecture (READ-ONLY)"
                    echo "  map        (alias for init) Reverse-engineer architecture from existing codebase"
                    echo "  update     Update architecture based on code/spec changes"
                    echo "  review     Validate architecture against constitution"
                    echo ""
                    echo "DAG Workflow Actions (used internally by implement):"
                    echo "  plan-dag   Phase 1: Generate DAG execution plan for user approval"
                    echo "  execute-dag Phase 2: Execute DAG to generate views per sub-system"
                    echo "  summarize  Phase 3: Aggregate views into unified AD.md"
                    echo ""
                    echo "Options:"
                    echo "  --json             Output results in JSON format"
                    echo "  --views VIEWS      Architecture views to generate: core (default), all, or comma-separated"
                    echo "  --adr-heuristic H  ADR generation heuristic: surprising (default), all, minimal"
                    echo "  --no-decompose     Disable automatic sub-system decomposition (default: auto-detect)"
                    echo "  --help             Show this help message"
                    echo ""
                    echo "Examples:"
                    echo "  $0 specify \"B2B SaaS for supply chain management\""
                    echo "  $0 init --views all \"Django monolith with PostgreSQL\""
                    echo "  $0 init --views concurrency,operational \"Microservices architecture\""
                    echo "  $0 clarify --adr-heuristic all \"Document all decisions\""
                    echo "  $0 implement \"Generate full AD.md from ADRs\""
                    echo ""
                    echo "Pro Tip: Add context/description after the action for better results."
                    echo "The AI will use your input to understand system scope and constraints."
                    exit 0
                    ;;
                *)
                    ARGS+=("$1")
                    shift
                    ;;
            esac
        done
        
        # Default action if not specified
        if [[ -z "$ACTION" ]]; then
            if [[ -f "$REPO_ROOT/AD.md" ]]; then
                ACTION="update"
            else
                ACTION="init"
            fi
        fi
        
        # Ensure directories exist
        mkdir -p "$REPO_ROOT/.adlc/memory"
        mkdir -p "$REPO_ROOT/.adlc/drafts"
        
        # Architecture files (ADR Lifecycle)
        AD_FILE="$REPO_ROOT/AD.md"
        TEMPLATE_FILE="$REPO_ROOT/.adlc/templates/architecture-template.md"
        AD_TEMPLATE_FILE="$REPO_ROOT/.adlc/templates/AD-template.md"
        
        # Export for use in functions
        export ARCHITECTURE_VIEWS="$VIEWS"
        export ADR_HEURISTIC="$ADR_HEURISTIC"
        export DECOMPOSE="$DECOMPOSE"
        
        # Function to detect sub-systems from codebase structure
        detect_subsystems() {
            local subsystems=""
            local count=0
            
            echo "Detecting sub-systems from codebase structure..." >&2
            
            # Check for common sub-system patterns
            
            # 1. Top-level feature directories (src/, app/, services/)
            local dirs=()
            if [[ -d "src" ]]; then
                for d in src/*/; do
                    if [[ -d "$d" ]]; then
                        local dirname
                        dirname=$(basename "$d")
                        # Skip common non-sub-system directories
                        if [[ "$dirname" != "utils" && "$dirname" != "common" && "$dirname" != "lib" && "$dirname" != "shared" && "$dirname" != "core" ]]; then
                            dirs+=("$dirname")
                        fi
                    fi
                done
            fi
            
            if [[ -d "services" ]]; then
                for d in services/*/; do
                    if [[ -d "$d" ]]; then
                        local dirname
                        dirname=$(basename "$d")
                        dirs+=("$dirname")
                    fi
                done
            fi
            
            if [[ -d "modules" ]]; then
                for d in modules/*/; do
                    if [[ -d "$d" ]]; then
                        local dirname
                        dirname=$(basename "$d")
                        dirs+=("$dirname")
                    fi
                done
            fi
            
            if [[ -d "apps" ]]; then
                for d in apps/*/; do
                    if [[ -d "$d" ]]; then
                        local dirname
                        dirname=$(basename "$d")
                        dirs+=("$dirname")
                    fi
                done
            fi
            
            # 2. Check for docker-compose services (microservices indicator)
            if [[ -f "docker-compose.yml" ]] || [[ -f "docker-compose.yaml" ]]; then
                local compose_file="docker-compose.yml"
                [[ -f "docker-compose.yaml" ]] && compose_file="docker-compose.yaml"
                
                local services=()
                while IFS= read -r line; do
                    if [[ "$line" =~ ^[[:space:]]*([a-zA-Z0-9_-]+):[[:space:]]*$ ]]; then
                        local svc="${BASH_REMATCH[1]}"
                        # Skip common non-service entries
                        if [[ "$svc" != "version" && "$svc" != "services" && "$svc" != "networks" && "$svc" != "volumes" ]]; then
                            services+=("$svc")
                        fi
                    fi
                done < "$compose_file"
                
                for svc in "${services[@]}"; do
                    local found=false
                    for d in "${dirs[@]}"; do
                        d_lower=$(printf '%s' "$d" | tr '[:upper:]' '[:lower:]')
                        svc_lower=$(printf '%s' "$svc" | tr '[:upper:]' '[:lower:]')
                        if [[ "$d_lower" == *"$svc_lower"* ]] || [[ "$svc_lower" == *"$d_lower"* ]]; then
                            found=true
                            break
                        fi
                    done
                    if [[ "$found" == "false" ]]; then
                        dirs+=("$svc")
                    fi
                done
            fi
            
            # 3. Check for Node.js workspaces (monorepo indicator)
            if [[ -f "package.json" ]]; then
                if grep -q '"workspaces"' package.json 2>/dev/null; then
                    local pkgs
                    pkgs=$(node -e "try { const p = require('./package.json'); console.log(Object.keys(p.workspaces?.packages || {}).join(' ')); } catch(e) { }" 2>/dev/null || true)
                    for pkg in $pkgs; do
                        local dirname
                        dirname=$(basename "$pkg")
                        if [[ "$dirname" != "node_modules" ]]; then
                            dirs+=("$dirname")
                        fi
                    done
                fi
            fi
            
            # 4. Check for Python namespace packages
            if [[ -f "pyproject.toml" ]]; then
                local pkg_dirs=()
                while IFS= read -r -d '' d; do
                    pkg_dirs+=("$(basename "$d")")
                done < <(find . -maxdepth 3 -name "__init__.py" -printf '%h\n' 2>/dev/null | grep -v node_modules | grep -v __pycache__ | sort -u || true)
                
                for pdir in "${pkg_dirs[@]}"; do
                    if [[ "$pdir" != "." && "$pdir" != "src" ]]; then
                        dirs+=("$pdir")
                    fi
                done
            fi
            
            # Remove duplicates and build output
            local unique_dirs=($(printf '%s\n' "${dirs[@]}" | sort -u))
            
            if [[ ${#unique_dirs[@]} -gt 0 ]]; then
                echo "Detected potential sub-systems:" >&2
                for d in "${unique_dirs[@]}"; do
                    ((count++))
                    echo "  - $d" >&2
                done
                echo "Total: $count sub-system(s)" >&2
            else
                echo "No distinct sub-systems detected from directory structure." >&2
            fi
            
            # Return as JSON if JSON mode
            if $JSON_MODE; then
                echo "["
                local first=true
                for d in "${unique_dirs[@]}"; do
                    if [[ "$first" == "true" ]]; then
                        first=false
                    else
                        echo ","
                    fi
                    echo -n "  {\"id\": \"$d\", \"name\": \"$d\", \"detection_method\": \"directory\", \"evidence\": \"directory: $d/\"}"
                done
                echo ""
                echo "]"
            fi
        }
        
        # Function to detect tech stack from codebase
        detect_tech_stack() {
            local tech_stack=""
            
            echo "Scanning codebase for technology stack..." >&2
            
            # Languages
            if [[ -f "package.json" ]]; then
                tech_stack+="**Languages**: JavaScript/TypeScript\n"
                tech_stack+="**Package Manager**: npm/yarn\n"
            fi
            
            if [[ -f "requirements.txt" ]] || [[ -f "setup.py" ]] || [[ -f "pyproject.toml" ]]; then
                tech_stack+="**Languages**: Python\n"
                if [[ -f "pyproject.toml" ]]; then
                    tech_stack+="**Package Manager**: pip/poetry/uv\n"
                fi
            fi
            
            if [[ -f "Cargo.toml" ]]; then
                tech_stack+="**Languages**: Rust\n"
                tech_stack+="**Package Manager**: Cargo\n"
            fi
            
            if [[ -f "go.mod" ]]; then
                tech_stack+="**Languages**: Go\n"
                tech_stack+="**Package Manager**: go modules\n"
            fi
            
            if [[ -f "pom.xml" ]] || [[ -f "build.gradle" ]]; then
                tech_stack+="**Languages**: Java\n"
                if [[ -f "pom.xml" ]]; then
                    tech_stack+="**Build System**: Maven\n"
                else
                    tech_stack+="**Build System**: Gradle\n"
                fi
            fi
            
            if [[ -f "*.csproj" ]] || [[ -f "*.sln" ]]; then
                tech_stack+="**Languages**: C#/.NET\n"
                tech_stack+="**Build System**: dotnet\n"
            fi
            
            # Frameworks (basic detection)
            if [[ -f "package.json" ]]; then
                if grep -q "react" package.json 2>/dev/null; then
                    tech_stack+="**Frontend Framework**: React\n"
                fi
                if grep -q "vue" package.json 2>/dev/null; then
                    tech_stack+="**Frontend Framework**: Vue\n"
                fi
                if grep -q "angular" package.json 2>/dev/null; then
                    tech_stack+="**Frontend Framework**: Angular\n"
                fi
                if grep -q "express" package.json 2>/dev/null; then
                    tech_stack+="**Backend Framework**: Express\n"
                fi
                if grep -q "fastify" package.json 2>/dev/null; then
                    tech_stack+="**Backend Framework**: Fastify\n"
                fi
            fi
            
            if [[ -f "requirements.txt" ]] || [[ -f "pyproject.toml" ]]; then
                if grep -q "django" requirements.txt 2>/dev/null || grep -q "django" pyproject.toml 2>/dev/null; then
                    tech_stack+="**Backend Framework**: Django\n"
                fi
                if grep -q "fastapi" requirements.txt 2>/dev/null || grep -q "fastapi" pyproject.toml 2>/dev/null; then
                    tech_stack+="**Backend Framework**: FastAPI\n"
                fi
                if grep -q "flask" requirements.txt 2>/dev/null || grep -q "flask" pyproject.toml 2>/dev/null; then
                    tech_stack+="**Backend Framework**: Flask\n"
                fi
            fi
            
            # Databases
            if [[ -f "docker-compose.yml" ]] || [[ -f "docker-compose.yaml" ]]; then
                if grep -q "postgres" docker-compose.* 2>/dev/null; then
                    tech_stack+="**Database**: PostgreSQL\n"
                fi
                if grep -q "mysql" docker-compose.* 2>/dev/null; then
                    tech_stack+="**Database**: MySQL\n"
                fi
                if grep -q "mongodb" docker-compose.* 2>/dev/null; then
                    tech_stack+="**Database**: MongoDB\n"
                fi
                if grep -q "redis" docker-compose.* 2>/dev/null; then
                    tech_stack+="**Cache**: Redis\n"
                fi
            fi
            
            # Infrastructure
            if [[ -f "Dockerfile" ]]; then
                tech_stack+="**Containerization**: Docker\n"
            fi
            
            local yaml_files=(*.yaml)
            if [[ -d "kubernetes" ]] || [[ -d "k8s" ]] || [[ -f "${yaml_files[0]}" ]] && grep -q "apiVersion:" *.yaml 2>/dev/null; then
                tech_stack+="**Orchestration**: Kubernetes\n"
            fi
            
            if [[ -d "terraform" ]] || [[ -f "*.tf" ]]; then
                tech_stack+="**IaC**: Terraform\n"
            fi
            
            local github_yml_files=(".github/workflows/"*.yml)
            local github_yaml_files=(".github/workflows/"*.yaml)
            if [[ -f "${github_yml_files[0]}" ]] || [[ -f "${github_yaml_files[0]}" ]]; then
                tech_stack+="**CI/CD**: GitHub Actions\n"
            fi
            
            if [[ -f ".gitlab-ci.yml" ]]; then
                tech_stack+="**CI/CD**: GitLab CI\n"
            fi
            
            if [[ -f "Jenkinsfile" ]]; then
                tech_stack+="**CI/CD**: Jenkins\n"
            fi
            
            echo -e "$tech_stack"
        }
        
        # Function to map directory structure
        map_directory_structure() {
            echo "Scanning directory structure..." >&2
            
            local structure=""
            
            # Common patterns
            if [[ -d "src" ]]; then
                structure+="**Source Code**: src/\n"
                if [[ -d "src/api" ]] || [[ -d "src/routes" ]]; then
                    structure+="  - API Layer: src/api/ or src/routes/\n"
                fi
                if [[ -d "src/services" ]]; then
                    structure+="  - Business Logic: src/services/\n"
                fi
                if [[ -d "src/models" ]]; then
                    structure+="  - Data Models: src/models/\n"
                fi
                if [[ -d "src/utils" ]]; then
                    structure+="  - Utilities: src/utils/\n"
                fi
            fi
            
            if [[ -d "tests" ]] || [[ -d "test" ]]; then
                structure+="**Tests**: tests/ or test/\n"
            fi
            
            if [[ -d "docs" ]]; then
                structure+="**Documentation**: docs/\n"
            fi
            
            if [[ -d "scripts" ]]; then
                structure+="**Scripts**: scripts/\n"
            fi
            
            if [[ -d "infra" ]] || [[ -d "infrastructure" ]]; then
                structure+="**Infrastructure**: infra/ or infrastructure/\n"
            fi
            
            echo -e "$structure"
        }
        
        # Function to extract API endpoints (basic pattern matching)
        extract_api_endpoints() {
            echo "Scanning for API endpoints..." >&2
            
            local endpoints=""
            
            # Look for common API route patterns
            if [[ -d "src" ]]; then
                # Express.js style
                endpoints+=$(grep -r "router\.\(get\|post\|put\|delete\|patch\)" src 2>/dev/null | head -10 || true)
                
                # FastAPI style
                endpoints+=$(grep -r "@app\.\(get\|post\|put\|delete\|patch\)" src 2>/dev/null | head -10 || true)
                
                # Flask style
                endpoints+=$(grep -r "@app\.route" src 2>/dev/null | head -10 || true)
            fi
            
            if [[ -n "$endpoints" ]]; then
                echo "API Endpoints detected (sample):"
                echo "$endpoints" | head -10
            fi
        }
        
        # Function to scan existing docs for deduplication
        scan_existing_docs() {
            local repo_root="${1:-$REPO_ROOT}"
            local findings=""
            
            echo "Scanning existing documentation for deduplication..." >&2
            
            # Check for existing architecture docs
            if [[ -f "$repo_root/AD.md" ]]; then
                findings+="EXISTING_AD: $repo_root/AD.md\n"
            fi
            
            if [[ -f "$repo_root/docs/architecture.md" ]]; then
                findings+="EXISTING_ARCHITECTURE: $repo_root/docs/architecture.md\n"
            fi
            
            # Scan README for tech stack
            if [[ -f "$repo_root/README.md" ]]; then
                if grep -q "Tech Stack\|Technology\|Built with" "$repo_root/README.md" 2>/dev/null; then
                    findings+="TECH_STACK_IN_README: $repo_root/README.md\n"
                fi
                if grep -q "PostgreSQL\|MySQL\|MongoDB\|Redis" "$repo_root/README.md" 2>/dev/null; then
                    findings+="DATABASE_IN_README: $repo_root/README.md\n"
                fi
                if grep -q "React\|Vue\|Angular" "$repo_root/README.md" 2>/dev/null; then
                    findings+="FRONTEND_IN_README: $repo_root/README.md\n"
                fi
            fi
            
            # Scan AGENTS.md for context
            if [[ -f "$repo_root/AGENTS.md" ]]; then
                findings+="AGENTS_CONTEXT: $repo_root/AGENTS.md\n"
            fi
            
            # Scan CONTRIBUTING.md for dev guidelines
            if [[ -f "$repo_root/CONTRIBUTING.md" ]]; then
                findings+="DEV_GUIDELINES: $repo_root/CONTRIBUTING.md\n"
            fi
            
            echo -e "$findings"
        }
        
        # Function to parse views flag
        parse_views() {
            local views_arg="$1"
            
            case "$views_arg" in
                "all"|"full")
                    echo "context functional information concurrency development deployment operational"
                    ;;
                "core"|"minimal"|"")
                    echo "context functional information development deployment"
                    ;;
                *)
                    # Parse comma-separated: "concurrency,operational"
                    local valid_views=""
                    local all_views="context functional information concurrency development deployment operational"
                    
                    IFS=',' read -ra VIEWS_ARRAY <<< "$views_arg"
                    for view in "${VIEWS_ARRAY[@]}"; do
                        view=$(echo "$view" | tr -d ' ')  # Trim whitespace
                        # Check if view is valid
                        if echo "$all_views" | grep -qw "$view"; then
                            valid_views="$valid_views $view"
                        fi
                    done
                    
                    # Always include core views
                    for view in context functional information development deployment; do
                        if ! echo "$valid_views" | grep -qw "$view"; then
                            valid_views="$valid_views $view"
                        fi
                    done
                    
                    echo "$valid_views" | sed 's/^ *//'
                    ;;
            esac
        }
        
        # ============================================================================
        # Hybrid ADR Storage Helpers (v2.2.0)
        # ============================================================================
        
        # ADRs are always stored as individual files (ADR-{NNN}.md) in a directory
        detect_adr_format() {
            echo "hybrid"
        }
        
        # Parse a YAML frontmatter field from a markdown file (MADR 3.0.0 frontmatter).
        # Usage: parse_fm_field "file" "fieldname"
        # Returns the field value with quotes, inline comments, and surrounding whitespace stripped.
        parse_fm_field() {
            local file="$1"
            local field="$2"
            awk -v fld="^[[:space:]]*$2:[[:space:]]*" '
                /^---[[:space:]]*$/ { fm++; next }
                fm == 1 && $0 ~ fld {
                    # strip the "key:" prefix
                    sub(fld, "")
                    # strip inline YAML comments
                    sub(/[[:space:]]+#.*$/, "")
                    # strip surrounding quotes
                    gsub(/^["'\'']|["'\'']$/, "")
                    # strip list brackets / leading "- "
                    gsub(/^\[|\]$/, "")
                    # trim
                    sub(/^[[:space:]]+/, ""); sub(/[[:space:]]+$/, "")
                    print
                    exit
                }
            ' "$file"
        }
        
        # Extract the MADR H1 title (first "# " line after frontmatter) from a markdown file.
        # Usage: parse_fm_title "file"
        parse_fm_title() {
            awk '/^---[[:space:]]*$/ { fm++; next } fm >= 2 && /^#[[:space:]]+/ { sub(/^#[[:space:]]+/, ""); sub(/[[:space:]]+$/, ""); print; exit }' "$1"
        }
        
        # Generate adr.md index from individual ADR files
        generate_adr_index() {
            local scope="${1:-drafts}"
            local adr_dir="$REPO_ROOT/.adlc/$scope/adr"
            local index_file="$adr_dir/adr.md"
        
            if [[ ! -d "$adr_dir" ]]; then
                return 0
            fi
        
            local index_content="# Architecture Decision Records
        
        ## ADR Index
        
        | ID | Sub-System | Decision | Status | Date | Decision Makers | File |
        |----|------------|----------|--------|------|------------------|------|
        "
        
            local quick_links=$'\n---\n\n## Quick Links\n\n'
        
            # Sort ADR files numerically
            for f in $(ls -1 "$adr_dir"/ADR-*.md 2>/dev/null | sort -t'-' -k2 -n); do
                local fname
                fname=$(basename "$f")
                local id
                id=$(echo "$fname" | sed -E 's/ADR-([0-9]+)\.md/\1/')
        
                # Extract metadata from MADR frontmatter (fallback to empty + defaults)
                local title=""
                local subsystem=""
                local status=""
                local date=""
                local decision_makers=""
        
                title=$(parse_fm_title "$f")
                status=$(parse_fm_field "$f" "status")
                date=$(parse_fm_field "$f" "date")
                decision_makers=$(parse_fm_field "$f" "decision-makers")
                subsystem=$(parse_fm_field "$f" "sub-system")
        
                # Defaults
                [[ -z "$status" ]] && status="Proposed"
                [[ -z "$date" ]] && date="YYYY-MM-DD"
                [[ -z "$decision_makers" ]] && decision_makers=""
                [[ -z "$subsystem" ]] && subsystem="System"
                [[ -z "$title" ]] && title="ADR-$id"
        
                index_content+="| ADR-$(printf "%03d" "$id") | $subsystem | $title | $status | $date | $decision_makers | [$fname]($fname) |\n"
                quick_links+="- [ADR-$(printf "%03d" "$id"): $title]($fname)\n"
            done
        
            echo -e "${index_content}\n${quick_links}" > "$index_file"
        }
        
        
        # Read a single ADR by ID
        get_adr_by_id() {
            local adr_id="$1"
            local scope="${2:-drafts}"
            local adr_dir="$REPO_ROOT/.adlc/$scope/adr"
        
            # Normalize ID
            local numeric_id
            numeric_id=$(echo "$adr_id" | sed -E 's/[^0-9]//g')
            local padded_id
            padded_id=$(printf "%03d" "$numeric_id")
        
            local hybrid_file="$adr_dir/ADR-$padded_id.md"
            if [[ -f "$hybrid_file" ]]; then
                cat "$hybrid_file"
                return 0
            fi
        
            return 1
        }
        
        # List all ADR IDs
        list_adrs() {
            local scope="${1:-drafts}"
            local adr_dir="$REPO_ROOT/.adlc/$scope/adr"
        
            if [[ -d "$adr_dir" ]]; then
                ls -1 "$adr_dir"/ADR-*.md 2>/dev/null | sed -E 's/.*ADR-([0-9]+)\.md/\1/' | sort -n
            fi
        }
        
        # Get ADR count
        get_adr_count() {
            local scope="${1:-drafts}"
            local adr_dir="$REPO_ROOT/.adlc/$scope/adr"
        
            if [[ -d "$adr_dir" ]]; then
                ls -1 "$adr_dir"/ADR-*.md 2>/dev/null | wc -l
            else
                echo "0"
            fi
        }
        
        # Write a single ADR to disk (regenerates adr.md index)
        write_adr() {
            local adr_id="$1"
            local adr_content="$2"
            local scope="${3:-drafts}"
            local adr_dir="$REPO_ROOT/.adlc/$scope/adr"
        
            mkdir -p "$adr_dir"
        
            local numeric_id
            numeric_id=$(echo "$adr_id" | sed -E 's/[^0-9]//g')
            local padded_id
            padded_id=$(printf "%03d" "$numeric_id")
        
            echo "$adr_content" > "$adr_dir/ADR-$padded_id.md"
        
            # Regenerate derived artifacts
            generate_adr_index "$scope"
        }
        
        # Move ADR from one scope to another (e.g., drafts -> memory)
        move_adr() {
            local adr_id="$1"
            local from_scope="${2:-drafts}"
            local to_scope="${3:-memory}"
        
            local from_dir="$REPO_ROOT/.adlc/$from_scope/adr"
            local to_dir="$REPO_ROOT/.adlc/$to_scope/adr"
        
            local numeric_id
            numeric_id=$(echo "$adr_id" | sed -E 's/[^0-9]//g')
            local padded_id
            padded_id=$(printf "%03d" "$numeric_id")
        
            mkdir -p "$to_dir"
        
            if [[ -f "$from_dir/ADR-$padded_id.md" ]]; then
                mv "$from_dir/ADR-$padded_id.md" "$to_dir/ADR-$padded_id.md"
            fi
        
            # Regenerate both scopes
            generate_adr_index "$from_scope"
            generate_adr_index "$to_scope"
        }
        
        # ============================================================================
        # Diagram generation
        # ============================================================================
        
        # Function to generate and insert diagrams into architecture.md
        generate_and_insert_diagrams() {
            local arch_file="$1"
            local system_name="${2:-System}"
            local views_list="${3:-$ARCHITECTURE_VIEWS}"
            
            # Parse views
            local parsed_views
            parsed_views=$(parse_views "$views_list")
            
            echo "📊 Generating architecture diagrams..." >&2
            echo "   Views: $parsed_views" >&2
            
            # Get diagram format from config
            local diagram_format
            diagram_format=$(get_architecture_diagram_format)
            
            echo "   Using diagram format: $diagram_format" >&2
            
            # Source diagram generators
            local generator_dir="$SCRIPT_DIR"
            if [[ "$diagram_format" == "mermaid" ]]; then
                source "$generator_dir/mermaid-generator.sh"
            else
                source "$generator_dir/ascii-generator.sh"
            fi
            
            # Generate each diagram and insert into template
            for view in $parsed_views; do
                echo "   Generating ${view} view diagram..." >&2
                
                local diagram_code
                if [[ "$diagram_format" == "mermaid" ]]; then
                    diagram_code=$(generate_mermaid_diagram "$view" "$system_name")
                    
                    # Validate Mermaid syntax
                    if ! validate_mermaid_syntax "$diagram_code"; then
                        echo "   ⚠️  Mermaid validation failed for ${view} view, using ASCII fallback" >&2
                        source "$generator_dir/ascii-generator.sh"
                        diagram_code=$(generate_ascii_diagram "$view" "$system_name")
                        diagram_format="ascii"
                    fi
                else
                    diagram_code=$(generate_ascii_diagram "$view" "$system_name")
                fi
                
                # Create the diagram block with appropriate markdown
                local diagram_block
                if [[ "$diagram_format" == "mermaid" ]]; then
                    diagram_block="\`\`\`mermaid
        $diagram_code
        \`\`\`"
                else
                    diagram_block="\`\`\`text
        $diagram_code
        \`\`\`"
                fi
                
                # Insert diagram into the architecture file at appropriate location
                # This is a simplified insertion - AI agent via architect.md template will do the real work
                # We're just providing the diagram generation capability here
            done
            
            echo "✅ Diagram generation complete" >&2
        }
        
        # Action: Specify (greenfield - interactive PRD exploration to create ADRs)
        action_specify() {
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_template="$REPO_ROOT/.adlc/templates/adr-template.md"
        
            echo "📐 Setting up for interactive ADR creation..." >&2
        
            # Ensure drafts directory exists
            mkdir -p "$REPO_ROOT/.adlc/drafts"
        
        
            # Show decomposition status
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "" >&2
                echo "🔄 Sub-system decomposition: ENABLED" >&2
                echo "   (AI agent will detect domains from PRD and propose sub-systems)" >&2
            else
                echo "" >&2
                echo "⚠️  Sub-system decomposition: DISABLED (--no-decompose flag)" >&2
                echo "   (AI agent will generate monolithic ADRs)" >&2
            fi
        
            # Initialize hybrid ADR directory if empty
            local adr_count
            adr_count=$(get_adr_count "drafts")
            if [[ "$adr_count" -eq 0 ]]; then
                if [[ -f "$adr_template" ]]; then
                    echo "Creating ADR template for hybrid storage..." >&2
                    # Write template as a placeholder ADR-000 that agents will replace
                    mkdir -p "$adr_dir"
                    cp "$adr_template" "$adr_dir/ADR-000.md"
                    echo "✅ Initialized hybrid ADR directory: $adr_dir" >&2
                else
                    mkdir -p "$adr_dir"
                    echo "✅ Created hybrid ADR directory: $adr_dir" >&2
                fi
            else
                echo "✅ Found $adr_count existing ADR(s)" >&2
            fi
        
            echo "" >&2
            echo "Ready for interactive PRD exploration." >&2
            echo "The AI agent will:" >&2
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "  0. (Phase 0) Detect domains in PRD and propose sub-systems" >&2
                echo "     → Ask user to confirm sub-system breakdown" >&2
            fi
            echo "  1. Analyze your PRD/requirements input" >&2
            echo "  2. Ask clarifying questions about architecture" >&2
            echo "  3. Create ADRs for each key decision" >&2
            echo "  4. Save decisions to .adlc/drafts/adr/ADR-{NNN}.md (Proposed status)" >&2
            echo "     (ADRs will be moved to memory/team after /architect-implement)" >&2
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "  5. Organize ADRs by sub-system" >&2
            fi
            echo "" >&2
            echo "After completion, run '/architect-implement' to generate full AD.md" >&2
        
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"specify\",\"adr_dir\":\"$adr_dir\",\"context\":\"${ARGS[*]}\",\"decomposition\":\"$DECOMPOSE\"}"
            fi
        }
        
        # Action: Clarify (refine existing ADRs)
        action_clarify() {
            # Auto-migrate both scopes before loading
        
        
            # Check drafts first (primary working location), fall back to memory if drafts is empty
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local fallback_adr_dir="$REPO_ROOT/.adlc/memory/adr"
            local fallback_adr_dir="$REPO_ROOT/.adlc/memory/adr"
        
            local active_dir="$adr_dir"
            local active_dir="$adr_dir"
            local active_scope="drafts"
        
            local draft_count
            draft_count=$(get_adr_count "drafts")
            local memory_count
            memory_count=$(get_adr_count "memory")
        
            if [[ "$draft_count" -eq 0 ]]; then
                if [[ "$memory_count" -gt 0 ]]; then
                    echo "ℹ️  Drafts ADR file not found, using memory ADRs" >&2
                    active_dir="$fallback_adr_dir"
                    active_dir="$fallback_adr_dir"
                    active_scope="memory"
                else
                    echo "❌ ADR directory does not exist: $adr_dir" >&2
                    echo "Run '/architect-specify' or '/architect-init' first" >&2
                    exit 1
                fi
            fi
        
            local adr_count
            adr_count=$(get_adr_count "$active_scope")
            local format
            format=$(detect_adr_format "$active_scope")
        
            echo "🔍 Loading existing ADRs for clarification..." >&2
            echo "Found $adr_count ADR(s) in $active_dir (format: $format)" >&2
        
            echo "" >&2
            echo "Ready for ADR refinement." >&2
            echo "The AI agent will:" >&2
            echo "  1. Review existing ADRs" >&2
            echo "  2. Ask targeted clarification questions" >&2
            echo "  3. Update ADRs based on your responses" >&2
            echo "  4. Regenerate adr.md index after updates" >&2
            echo "  5. Flag any inconsistencies or gaps" >&2
        
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"clarify\",\"adr_dir\":\"$adr_dir\",\"adr_count\":$adr_count,\"format\":\"$format\",\"context\":\"${ARGS[*]}\"}"
            fi
        }
        
        # Action: Implement (generate full AD.md from ADRs)
        action_implement() {
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local ad_file="$REPO_ROOT/AD.md"
            local ad_template="$REPO_ROOT/.adlc/templates/AD-template.md"
            
            # Auto-migrate before checking
        
            local adr_count
            adr_count=$(get_adr_count "drafts")
        
            if [[ "$adr_count" -eq 0 ]]; then
                echo "❌ No ADR drafts found" >&2
                echo "Run '/architect-specify' or '/architect-init' first" >&2
                exit 1
            fi
        
            echo "📐 Setting up for Architecture Description generation..." >&2
        
            # Initialize AD.md from template if it doesn't exist
            if [[ ! -f "$ad_file" ]]; then
                if [[ -f "$ad_template" ]]; then
                    echo "Creating AD.md from template..." >&2
                    cp "$ad_template" "$ad_file"
                    echo "✅ Created: $ad_file" >&2
                else
                    echo "⚠️  AD template not found: $ad_template" >&2
                    echo "The AI agent will create AD.md from scratch" >&2
                fi
            else
                echo "✅ AD.md already exists, will be updated: $ad_file" >&2
            fi
        
            echo "" >&2
            echo "Ready for Architecture Description generation." >&2
            echo "The AI agent will:" >&2
            echo "  1. Read all $adr_count ADR(s) from .adlc/drafts/adr/" >&2
            echo "  2. Generate 7 Rozanski & Woods viewpoints" >&2
            echo "  3. Apply Security and Performance perspectives" >&2
            echo "  4. Create Mermaid diagrams for each view" >&2
            echo "  5. Write complete AD.md to project root" >&2
            echo "  6. Move Accepted ADRs to canonical location (.adlc/memory/adr/)" >&2
            echo "  7. Regenerate adr.md index for both scopes" >&2
            echo "  8. Clean up drafts if all ADRs are Accepted" >&2
        
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"implement\",\"adr_dir\":\"$adr_dir\",\"ad_file\":\"$ad_file\",\"adr_count\":$adr_count,\"context\":\"${ARGS[*]}\"}"
            fi
        }
        
        # Action: Initialize (brownfield - reverse-engineer from codebase, ADRs only)
        action_init() {
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_template="$REPO_ROOT/.adlc/templates/adr-template.md"
        
            echo "🔍 Initializing brownfield architecture discovery..." >&2
        
            # Ensure drafts directory exists
            mkdir -p "$REPO_ROOT/.adlc/drafts"
        
        
            # Scan existing docs for deduplication
            local existing_docs
            existing_docs=$(scan_existing_docs "$REPO_ROOT")
            if [[ -n "$existing_docs" ]]; then
                echo "📋 Found existing documentation:" >&2
                echo "$existing_docs" | while read -r line; do
                    echo "  - $line" >&2
                done
                echo "" >&2
            fi
        
            # Detect tech stack for context
            echo "🔍 Scanning codebase..." >&2
            local tech_stack
            tech_stack=$(detect_tech_stack)
        
            local dir_structure
            dir_structure=$(map_directory_structure)
        
            # Phase 0: Sub-system detection (if decomposition enabled)
            local subsystems_json=""
            local decompose_status="disabled"
        
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "" >&2
                echo "🔄 Phase 0: Sub-System Detection" >&2
                subsystems_json=$(detect_subsystems)
                decompose_status="enabled"
        
                if [[ -n "$subsystems_json" ]] && [[ "$subsystems_json" != "[]" ]]; then
                    echo "" >&2
                    echo "📦 Sub-systems will be used to organize ADRs" >&2
                    echo "   (AI agent will confirm with user before proceeding)" >&2
                fi
            else
                echo "" >&2
                echo "⚠️  Sub-system decomposition disabled (--no-decompose flag)" >&2
            fi
        
            # Initialize hybrid ADR directory if empty
            local adr_count
            adr_count=$(get_adr_count "drafts")
            if [[ "$adr_count" -eq 0 ]]; then
                mkdir -p "$adr_dir"
                if [[ -f "$adr_template" ]]; then
                    echo "Creating ADR template for hybrid storage..." >&2
                    cp "$adr_template" "$adr_dir/ADR-000.md"
                    echo "✅ Initialized hybrid ADR directory: $adr_dir" >&2
                else
                    echo "✅ Created hybrid ADR directory: $adr_dir" >&2
                fi
            else
                echo "✅ Found $adr_count existing ADR(s)" >&2
            fi
        
            echo "" >&2
            echo "📊 Codebase Analysis Summary:" >&2
            echo "$tech_stack" >&2
            echo "" >&2
            echo "$dir_structure" >&2
        
            echo "" >&2
            echo "Ready for brownfield architecture discovery." >&2
            echo "The AI agent will:" >&2
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "  0. (Phase 0) Propose sub-systems from code structure" >&2
                echo "     → Ask user to confirm sub-system breakdown" >&2
            fi
            echo "  1. Analyze codebase structure and patterns" >&2
            echo "  2. Infer architectural decisions from code" >&2
            echo "  3. Create ADRs marked as 'Discovered (Inferred)'" >&2
            if [[ "$DECOMPOSE" == "true" ]]; then
                echo "  4. Organize ADRs by sub-system" >&2
            fi
            echo "  5. Auto-trigger /architect-clarify to validate findings" >&2
            echo "" >&2
            echo "NOTE: AD.md will NOT be created until ADRs are validated." >&2
            echo "      After clarification, run /architect-implement to generate AD.md" >&2
        
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"init\",\"adr_dir\":\"$adr_dir\",\"tech_stack\":\"$tech_stack\",\"existing_docs\":\"$existing_docs\",\"source\":\"brownfield\",\"decomposition\":\"$decompose_status\",\"subsystems\":$subsystems_json}"
            fi
        }
        
        # Action: Map (brownfield)
        action_map() {
            echo "🔍 Mapping existing codebase to architecture..." >&2
            
            # Scan existing docs
            local existing_docs
            existing_docs=$(scan_existing_docs "$REPO_ROOT")
            
            # Detect tech stack
            echo "" >&2
            echo "Tech Stack Detected:" >&2
            tech_stack=$(detect_tech_stack)
            echo "$tech_stack" >&2
            
            # Map directory structure
            echo "" >&2
            echo "Code Organization:" >&2
            dir_structure=$(map_directory_structure)
            echo "$dir_structure" >&2
            
            # Extract API endpoints
            echo "" >&2
            extract_api_endpoints >&2
            
            # Output structured data for AI agent to populate AD.md
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"map\",\"tech_stack\":\"$tech_stack\",\"directory_structure\":\"$dir_structure\",\"existing_docs\":\"$existing_docs\"}"
            else
                echo "" >&2
                echo "📋 Mapping complete. Use this information to populate AD.md:" >&2
                
                if [[ -n "$existing_docs" ]]; then
                    echo "" >&2
                    echo "Existing Documentation (reference, don't duplicate):" >&2
                    echo "$existing_docs" | while read -r line; do
                        echo "  - $line" >&2
                    done
                fi
                
                echo "" >&2
                echo "Architecture Sections:" >&2
                echo "  - Context View (3.1): Define system boundaries" >&2
                echo "  - Development View (3.5): Use directory structure above" >&2
                echo "  - Deployment View (3.6): Check docker-compose.yml, k8s configs, terraform" >&2
                echo "  - Functional View (3.2): Use API endpoints detected" >&2
                echo "  - Information View (3.3): Check database schemas, ORM models" >&2
            fi
        }
        
        # Action: Update
        action_update() {
            if [[ ! -f "$AD_FILE" ]]; then
                echo "❌ Architecture does not exist: $AD_FILE" >&2
                echo "Run '/architect-specify' or '/architect-init' first" >&2
                exit 1
            fi
            
            echo "🔄 Updating architecture based on recent changes..." >&2
            
            # Check for recent commits (basic approach)
            if command -v git &> /dev/null && [[ -d "$REPO_ROOT/.git" ]]; then
                echo "" >&2
                echo "Recent changes:" >&2
                git log --oneline --since="7 days ago" 2>/dev/null | head -10 >&2 || true
            fi
            
            # Detect changes in tech stack
            echo "" >&2
            echo "Current Tech Stack:" >&2
            detect_tech_stack >&2
            
            # Regenerate diagrams with current format and views
            generate_and_insert_diagrams "$AD_FILE" "System" "$VIEWS"
            
            echo "" >&2
            echo "✅ Update analysis complete" >&2
            echo "Review the architecture document and update affected sections:" >&2
            echo "  - New tables/models? → Update Information View" >&2
            echo "  - New services/components? → Update Functional View + Deployment View" >&2
            echo "  - New queues/async? → Update Concurrency View (if included)" >&2
            echo "  - New dependencies? → Update Development View" >&2
            echo "  - Add ADR if significant decision was made" >&2
            
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"update\",\"ad_file\":\"$AD_FILE\",\"adr_dir\":\"$adr_dir\"}"
            fi
        }
        
        # Action: Review
        action_review() {
            if [[ ! -f "$AD_FILE" ]]; then
                echo "❌ Architecture does not exist: $AD_FILE" >&2
                echo "Run '/architect-specify' or '/architect-init' first" >&2
                exit 1
            fi
            
            echo "🔍 Reviewing architecture..." >&2
            
            # Check for completeness
            local issues=()
            
            # Check for required sections
            if ! grep -q "## 1\. Introduction" "$AD_FILE"; then
                issues+=("Missing: Introduction section")
            fi
            
            if ! grep -q "## 2\. Stakeholders & Concerns" "$AD_FILE"; then
                issues+=("Missing: Stakeholders section")
            fi
            
            if ! grep -q "## 3\. Architectural Views" "$AD_FILE"; then
                issues+=("Missing: Architectural Views section")
            fi
            
            if ! grep -q "### 3.1 Context View" "$AD_FILE"; then
                issues+=("Missing: Context View")
            fi
            
            if ! grep -q "### 3.2 Functional View" "$AD_FILE"; then
                issues+=("Missing: Functional View")
            fi
            
            if ! grep -q "## 4\. Architectural Perspectives" "$AD_FILE"; then
                issues+=("Missing: Perspectives section")
            fi
            
            if ! grep -q "## 5\. Global Constraints & Principles" "$AD_FILE"; then
                issues+=("Missing: Global Constraints section")
            fi
            
            # Check for placeholder content
            if grep -q "\[SYSTEM_NAME\]" "$AD_FILE"; then
                issues+=("Placeholder: System name not filled in")
            fi
            
            if grep -q "\[STAKEHOLDER_" "$AD_FILE"; then
                issues+=("Placeholder: Stakeholders not filled in")
            fi
            
            # Report results
            if [[ ${#issues[@]} -eq 0 ]]; then
                echo "✅ Architecture review passed - no major issues found" >&2
            else
                echo "⚠️  Architecture review found issues:" >&2
                for issue in "${issues[@]}"; do
                    echo "  - $issue" >&2
                done
            fi
            
            # Check constitution alignment if it exists
            local constitution_file="$REPO_ROOT/.adlc/memory/constitution.md"
            if [[ -f "$constitution_file" ]]; then
                echo "" >&2
                echo "📜 Checking constitution alignment..." >&2
                echo "✅ Constitution file found: $constitution_file" >&2
                echo "Manually verify that architecture adheres to constitutional principles" >&2
            fi
            
            # Check for ADRs
            local adr_mem_dir="$REPO_ROOT/.adlc/memory/adr"
            if [[ -d "$adr_mem_dir" ]]; then
                echo "" >&2
                echo "📋 ADR directory found: $adr_mem_dir" >&2
                local adr_count
                adr_count=$(ls -1 "$adr_mem_dir"/ADR-*.md 2>/dev/null | wc -l)
                echo "   Found $adr_count ADR(s)" >&2
            fi
            
            if $JSON_MODE; then
                if [[ ${#issues[@]} -eq 0 ]]; then
                    echo "{\"status\":\"success\",\"action\":\"review\",\"ad_file\":\"$AD_FILE\",\"adr_dir\":\"$adr_mem_dir\",\"issues\":[]}"
                else
                    # Format issues as JSON array
                    issues_json=$(printf '%s\n' "${issues[@]}" | jq -R . | jq -s .)
                    echo "{\"status\":\"warning\",\"action\":\"review\",\"ad_file\":\"$AD_FILE\",\"adr_dir\":\"$adr_mem_dir\",\"issues\":$issues_json}"
                fi
            fi
        }
        
        # Action: Analyze (validate architecture consistency)
        action_analyze() {
            echo "🔍 Architecture Analysis Mode" >&2
            echo ""
        
            # Auto-migrate before analysis
        
        
            local ad_file="$REPO_ROOT/AD.md"
            local adr_dir="$REPO_ROOT/.adlc/memory/adr"
            local adr_dir="$REPO_ROOT/.adlc/memory/adr"
            local constitution_file="$REPO_ROOT/.adlc/memory/constitution.md"
        
            local ad_exists=false
            local adr_exists=false
            local constitution_exists=false
        
            if [[ -f "$ad_file" ]]; then
                ad_exists=true
                echo "📄 AD.md found: $ad_file" >&2
            else
                echo "⚠️  AD.md not found at $ad_file" >&2
            fi
        
            local adr_count
            adr_count=$(get_adr_count "memory")
            if [[ "$adr_count" -gt 0 ]]; then
                adr_exists=true
                echo "📋 ADR file found: $adr_dir ($adr_count ADRs)" >&2
            else
                echo "⚠️  ADR directory not found: $adr_dir" >&2
            fi
        
            if [[ -f "$constitution_file" ]]; then
                constitution_exists=true
                echo "📜 Constitution found: $constitution_file" >&2
            fi
        
            # Scan for feature-level architecture
            local feature_ads=()
            local feature_adrs=()
        
            if [[ -d "$REPO_ROOT/specs" ]]; then
                while IFS= read -r -d '' f; do
                    feature_ads+=("$f")
                done < <(find "$REPO_ROOT/specs" -name "AD.md" -print0 2>/dev/null)
        
                while IFS= read -r -d '' f; do
                    feature_adrs+=("$f")
                done < <(find "$REPO_ROOT/specs" -name "ADR-*.md" -print0 2>/dev/null)
        
                if [[ ${#feature_ads[@]} -gt 0 ]]; then
                    echo "📁 Feature ADs found: ${#feature_ads[@]}" >&2
                fi
                if [[ ${#feature_adrs[@]} -gt 0 ]]; then
                    echo "📁 Feature ADRs found: ${#feature_adrs[@]}" >&2
                fi
            fi
        
            echo "" >&2
            echo "Ready for architecture consistency analysis." >&2
            echo "The AI agent will:" >&2
            echo "  1. Load all architecture artifacts" >&2
            echo "  2. Execute detection passes A-G" >&2
            echo "  3. Assign severity levels to findings" >&2
            echo "  4. Generate structured analysis report" >&2
            echo "  5. Suggest remediation actions" >&2
        
            if $JSON_MODE; then
                local feature_ads_json="[]"
                local feature_adrs_json="[]"
        
                if [[ ${#feature_ads[@]} -gt 0 ]]; then
                    feature_ads_json=$(printf '%s\n' "${feature_ads[@]}" | jq -R . | jq -s .)
                fi
                if [[ ${#feature_adrs[@]} -gt 0 ]]; then
                    feature_adrs_json=$(printf '%s\n' "${feature_adrs[@]}" | jq -R . | jq -s .)
                fi
        
                echo "{\"status\":\"success\",\"action\":\"analyze\",\"ad_file\":\"$ad_file\",\"ad_exists\":$ad_exists,\"adr_dir\":\"$adr_dir\",\"adr_exists\":$adr_exists,\"constitution_file\":\"$constitution_file\",\"constitution_exists\":$constitution_exists,\"feature_ads\":$feature_ads_json,\"feature_adrs\":$feature_adrs_json,\"context\":\"${ARGS[*]}\"}"
            fi
        }
        
        # Action: Plan DAG (Phase 1 of implement - generate execution plan)
        action_plan_dag() {
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            local state_file="$REPO_ROOT/.adlc/architect/state.json"
            local views_dir="$REPO_ROOT/.adlc/architect/views"
        
            echo "📐 DAG Planning Phase" >&2
            echo "" >&2
        
            # Auto-migrate before planning
        
            local adr_count
            adr_count=$(get_adr_count "drafts")
        
            if [[ "$adr_count" -eq 0 ]]; then
                echo "❌ No ADR drafts found" >&2
                echo "Run '/architect-specify' or '/architect-init' first" >&2
                exit 1
            fi
        
            # Ensure directories exist
            mkdir -p "$REPO_ROOT/.adlc/architect"
            mkdir -p "$views_dir"
        
            # Extract unique sub-systems from ADR files
            local subsystems=()
            if [[ -d "$adr_dir" ]]; then
                for f in "$adr_dir"/ADR-*.md; do
                    [[ -f "$f" ]] || continue
                    local subsystem=""
                    subsystem=$(parse_fm_field "$f" "sub-system")
                    if [[ -n "$subsystem" && "$subsystem" != "Sub-System" ]]; then
                        local found=false
                        for s in "${subsystems[@]}"; do
                            if [[ "$s" == "$subsystem" ]]; then
                                found=true
                                break
                            fi
                        done
                        if [[ "$found" == "false" ]]; then
                            subsystems+=("$subsystem")
                        fi
                    fi
                done
            elif [[ -d "$adr_dir" ]]; then
                while IFS= read -r line; do
                    if [[ "$line" =~ ^\|[[:space:]]*ADR-[0-9]+[[:space:]]*\|[[:space:]]*([^|]+)[[:space:]]*\| ]]; then
                        local subsystem="${BASH_REMATCH[1]}"
                        subsystem=$(echo "$subsystem" | xargs)
                        if [[ -n "$subsystem" && "$subsystem" != "Sub-System" ]]; then
                            local found=false
                            for s in "${subsystems[@]}"; do
                                if [[ "$s" == "$subsystem" ]]; then
                                    found=true
                                    break
                                fi
                            done
                            if [[ "$found" == "false" ]]; then
                                subsystems+=("$subsystem")
                            fi
                        fi
                    fi
                done < "$adr_dir"
            fi
        
            # Default to "System" if no sub-systems found
            if [[ ${#subsystems[@]} -eq 0 ]]; then
                subsystems=("System")
            fi
        
            echo "📋 ADR directory found: $adr_dir" >&2
            echo "   Found $adr_count ADR(s)" >&2
            echo "   Sub-systems detected: ${subsystems[*]}" >&2
            echo "" >&2
            echo "Ready for DAG planning." >&2
            echo "The AI agent will:" >&2
            echo "  1. Analyze ADRs by sub-system" >&2
            echo "  2. Generate customized DAG per sub-system" >&2
            echo "  3. Present execution plan for user approval" >&2
            echo "  4. Save approved plan to state.json" >&2
        
            if $JSON_MODE; then
                # Build subsystems JSON array
                local subsystems_json="["
                local first=true
                for s in "${subsystems[@]}"; do
                    if [[ "$first" == "true" ]]; then
                        first=false
                    else
                        subsystems_json+=","
                    fi
                    subsystems_json+="{\"id\":\"$(echo "$s" | tr '[:upper:]' '[:lower:]' | tr ' ' '-')\",\"name\":\"$s\"}"
                done
                subsystems_json+="]"
        
                echo "{\"status\":\"success\",\"action\":\"plan-dag\",\"adr_dir\":\"$adr_dir\",\"state_file\":\"$state_file\",\"views_dir\":\"$views_dir\",\"adr_count\":$adr_count,\"subsystems\":$subsystems_json,\"context\":\"${ARGS[*]}\"}"
            fi
        }
        
        # Action: Execute DAG (Phase 2 of implement - generate views based on state)
        action_execute_dag() {
            local state_file="$REPO_ROOT/.adlc/architect/state.json"
            local views_dir="$REPO_ROOT/.adlc/architect/views"
            
            echo "🔧 DAG Execution Phase" >&2
            echo "" >&2
            
            # Check if state file exists
            if [[ ! -f "$state_file" ]]; then
                echo "❌ No execution plan found: $state_file" >&2
                echo "Run '/architect-implement' first to generate and approve a DAG plan" >&2
                exit 1
            fi
            
            # Ensure views directory exists
            mkdir -p "$views_dir"
            
            echo "📄 State file found: $state_file" >&2
            echo "📁 Views directory: $views_dir" >&2
            echo "" >&2
            echo "Ready for DAG execution." >&2
            echo "The AI agent will:" >&2
            echo "  1. Read execution plan from state.json" >&2
            echo "  2. Identify next view(s) to generate" >&2
            echo "  3. Generate view with dependency context" >&2
            echo "  4. Write to .adlc/architect/views/{subsystem}/{view}.md" >&2
            echo "  5. Update progress in state.json" >&2
            
            if $JSON_MODE; then
                # Output the state file content for the AI agent
                if [[ -f "$state_file" ]]; then
                    local state_content
                    state_content=$(cat "$state_file")
                    echo "{\"status\":\"success\",\"action\":\"execute-dag\",\"state_file\":\"$state_file\",\"views_dir\":\"$views_dir\",\"state\":$state_content}"
                else
                    echo "{\"status\":\"error\",\"action\":\"execute-dag\",\"error\":\"state_file_not_found\"}"
                fi
            fi
        }
        
        # Action: Summarize (Phase 3 of implement - aggregate views into AD.md)
        action_summarize() {
            local state_file="$REPO_ROOT/.adlc/architect/state.json"
            local views_dir="$REPO_ROOT/.adlc/architect/views"
            local ad_file="$REPO_ROOT/AD.md"
            local adr_dir="$REPO_ROOT/.adlc/drafts/adr"
            
            echo "📝 Summarization Phase" >&2
            echo "" >&2
            
            # Check if views directory exists and has content
            if [[ ! -d "$views_dir" ]]; then
                echo "❌ Views directory not found: $views_dir" >&2
                echo "Run '/architect-implement' to generate views first" >&2
                exit 1
            fi
            
            # Count view files
            local view_count
            view_count=$(find "$views_dir" -name "*.md" -type f 2>/dev/null | wc -l)
            
            if [[ "$view_count" -eq 0 ]]; then
                echo "❌ No view files found in $views_dir" >&2
                echo "Run '/architect-implement' to generate views first" >&2
                exit 1
            fi
            
            # List all view files
            echo "📁 Views directory: $views_dir" >&2
            echo "   Found $view_count view file(s):" >&2
            find "$views_dir" -name "*.md" -type f | while read -r f; do
                echo "   - ${f#$views_dir/}" >&2
            done
            echo "" >&2
            
            echo "Ready for summarization." >&2
            echo "The AI agent will:" >&2
            echo "  1. Read all view files from .adlc/architect/views/" >&2
            echo "  2. Detect cross-subsystem conflicts" >&2
            echo "  3. Resolve conflicts using ADRs as source of truth" >&2
            echo "  4. Aggregate into unified AD.md" >&2
            echo "  5. Apply Security and Performance perspectives" >&2
            echo "  6. Move Accepted ADRs to canonical location" >&2
            
            if $JSON_MODE; then
                # Build list of view files
                local views_json="["
                local first=true
                while IFS= read -r f; do
                    if [[ "$first" == "true" ]]; then
                        first=false
                    else
                        views_json+=","
                    fi
                    local rel_path="${f#$views_dir/}"
                    views_json+="{\"path\":\"$f\",\"relative\":\"$rel_path\"}"
                done < <(find "$views_dir" -name "*.md" -type f 2>/dev/null)
                views_json+="]"
                
                echo "{\"status\":\"success\",\"action\":\"summarize\",\"state_file\":\"$state_file\",\"views_dir\":\"$views_dir\",\"ad_file\":\"$ad_file\",\"adr_dir\":\"$adr_dir\",\"view_count\":$view_count,\"views\":$views_json}"
            fi
        }
        
        # Action: Validate (READ-ONLY architecture validation for plan alignment)
        action_validate() {
            local adr_dir="$REPO_ROOT/.adlc/memory/adr"
            local adr_dir="$REPO_ROOT/.adlc/memory/adr"
        
            echo "🔍 Architecture Validation Mode (READ-ONLY)" >&2
            echo ""
        
            # Auto-migrate before validation
        
            local adr_count
            adr_count=$(get_adr_count "memory")
        
            # Check if architecture exists
            if [[ "$adr_count" -eq 0 ]]; then
                echo "⏭️  Architecture not found: $adr_dir" >&2
                echo "     Skipping validation gracefully" >&2
                if $JSON_MODE; then
                    echo "{\"status\":\"skipped\",\"action\":\"validate\",\"reason\":\"architecture_not_found\"}"
                fi
                exit 0
            fi
        
            echo "📋 ADR directory found: $adr_dir" >&2
            echo "   Found $adr_count ADR(s)" >&2
            echo "" >&2
            echo "Ready for READ-ONLY architecture validation." >&2
            echo "The AI agent will:" >&2
            echo "  1. Load architecture from ADRs and AD.md" >&2
            echo "  2. Validate plan alignment with architecture" >&2
            echo "  3. Identify blocking/high-severity issues" >&2
            echo "  4. Report findings (READ-ONLY, no modifications)" >&2
        
            if $JSON_MODE; then
                echo "{\"status\":\"success\",\"action\":\"validate\",\"adr_dir\":\"$adr_dir\",\"adr_count\":$adr_count,\"context\":\"${ARGS[*]}\"}"
            fi
        }
        
        # Execute action
        case "$ACTION" in
            specify)
                action_specify
                ;;
            clarify)
                action_clarify
                ;;
            init|map)
                action_init
                ;;
            implement)
                action_implement
                ;;
            plan-dag)
                action_plan_dag
                ;;
            execute-dag)
                action_execute_dag
                ;;
            summarize)
                action_summarize
                ;;
            analyze)
                action_analyze
                ;;
            validate)
                action_validate
                ;;
            update)
                action_update
                ;;
            review)
                action_review
                ;;
            *)
                echo "❌ Unknown action: $ACTION" >&2
                echo "Use --help for usage information" >&2
                exit 1
                ;;
        esac
        
    • powershell
      • ASCII-Generator.ps1 17.8 KB · in bundle
      • Mermaid-Generator.ps1 8.9 KB · in bundle
      • setup-architect.ps1 49 KB · in bundle
  • SKILL.md 54.3 KB
    ---
    name: architect-implement
    description: Use when accepted ADRs exist and AD.md must be produced or updated as unified architecture documentation.
    disable-model-invocation: true
    ---
    
    # architect-implement
    
    ## What this skill does
    
    Generate a full Architecture Description (AD.md) from Architecture Decision Records (ADRs) using a **multi-agent DAG orchestration** approach:
    
    1. **Plan Agent**: Analyze ADRs, detect sub-systems, generate a customized DAG, and get user approval.
    2. **Execute Agent**: Generate architecture views per sub-system following the DAG, with dependency context passing.
    3. **Summarize Agent**: Aggregate all views, resolve cross-subsystem conflicts, and generate a unified AD.md.
    
    **Key Insight**: ADRs capture **why** decisions were made; the Architecture Description captures **what** the system looks like as a result of those decisions.
    
    ## When to use
    
    - **After `/architect-specify` or `/architect-clarify`**: Generate AD from discussed and accepted ADRs.
    - **After `/architect-init`**: Document brownfield architecture.
    - **ADR Updates**: Regenerate AD.md after new decisions.
    - **Documentation Sprint**: Create comprehensive architecture docs.
    
    ### When NOT to use
    
    - **No ADRs exist**: Use `/architect-specify` or `/architect-init` first.
    - **Feature-level**: Feature AD is generated during the feature's plan phase, not by this skill.
    - **Minor updates**: Use direct editing for small changes.
    
    ## Process
    
    ### User Input
    
    ```text
    $ARGUMENTS
    ```
    
    You **MUST** consider the user input before proceeding (if not empty).
    
    **Examples of User Input**:
    
    - `"Focus on deployment and operational views - we need infrastructure docs"`
    - `"Generate all views with emphasis on security perspective"`
    - `"Update existing AD.md with new ADRs from recent decisions"`
    - Empty input: Generate complete Architecture Description from all ADRs
    
    ### Flags
    
    - `--views VIEWS`: Architecture views to generate
      - `core` (default): Context, Functional, Information, Development, Deployment (5 core views)
      - `all`: All 7 views including Concurrency and Operational
      - Custom: comma-separated (e.g., `concurrency,operational`) - always includes core views
    
    - `--sequential` (default): Execute views sequentially for maximum quality
      - Recommended: Allows checkpoint after Functional view
    - `--parallel`: Allow parallel execution where dependency chains permit
      - Warning: May reduce cross-view consistency - use only when time-constrained
    
    - `--no-checkpoint`: Skip Functional view checkpoint (not recommended)
      - Warning: Functional view is the "cornerstone" that shapes all others
    
    - `--force`: Bypass workflow state validation (emergency use only)
      - **WARNING**: Use only when you understand the risks
      - Skips clarify Phase 5.5 completion check
      - Skips pre-flight ADR status validation
      - May result in incomplete or inconsistent architecture
    
    **Important**: When `--views` is `core` (default), **skip** Concurrency View (3.4) and Operational View (3.7) entirely. Only generate them when explicitly requested via `--views all` or `--views concurrency,operational`.
    
    ### Rozanski & Woods Methodology Alignment
    
    This command implements the **Viewpoints and Perspectives** framework from 
    *Software Systems Architecture* (2nd Edition) by Nick Rozanski and Eoin Woods.
    
    #### Core Principles
    
    1. **Functional View is the Cornerstone**
       > "The Functional view is the cornerstone of most ADs... It usually drives 
       > the shape of other system structures such as the information structure, 
       > concurrency structure, deployment structure, and so on."
       > — Rozanski & Woods
    
    2. **Views are Interrelated, Not Independent**
       > "The decisions taken in one view can have a considerable impact on the 
       > others, and it is a big part of the architect's job to make sure that 
       > these implications are understood."
    
    3. **Perspectives Apply to Views**
       > "You never work with perspectives in isolation but instead use them with 
       > each view to analyze and validate the qualities of your architecture."
    
    4. **Quality Over Speed**
       Architecture mistakes are expensive to fix. Sequential execution with 
       checkpoints is the default to ensure quality.
    
    #### Viewpoint Dependency Graph
    
    ```text
                        ┌──────────┐
                        │ Context  │  (System boundaries)
                        └────┬─────┘
                             │
                             ▼
                     ┌───────────────┐
                     │  FUNCTIONAL   │  ★ CORNERSTONE ★
                     │  (Drives all  │  USER CHECKPOINT
                     │   other views)│  REQUIRED HERE
                     └───────┬───────┘
                             │
             ┌───────────────┼───────────────┐
             │               │               │
             ▼               ▼               ▼
       ┌───────────┐   ┌───────────┐   ┌───────────┐
       │Information│   │Concurrency│   │Development│
       │           │   │(optional) │   │           │
       └─────┬─────┘   └─────┬─────┘   └─────┬─────┘
             │               │               │
             └───────────────┼───────────────┘
                             │
                             ▼
                      ┌────────────┐
                      │ Deployment │
                      └──────┬─────┘
                             │
                             ▼
                      ┌────────────┐
                      │ Operational│  (optional)
                      └────────────┘
    ```
    
    #### Dynamic Viewpoint & Perspective Selection
    
    Viewpoints and perspectives are selected dynamically based on system characteristics:
    
    | Category | Always Included | Auto-Detected (Optional) |
    |----------|-----------------|--------------------------|
    | Viewpoints | Context, Functional | Information, Concurrency, Development, Deployment, Operational |
    | Perspectives | Security, Performance | Accessibility, Availability, Evolution, Internationalization, Location, Regulation, Usability, Development Resource |
    
    **Reference**: https://www.viewpoints-and-perspectives.info/
    
    ### Goal
    
    Transform Architecture Decision Records (ADRs) into a comprehensive Architecture Description (AD.md) using a **multi-agent DAG orchestration** approach:
    
    1. **Plan Agent**: Analyze ADRs, detect sub-systems, generate customized DAG, get user approval
    2. **Execute Agent**: Generate views per sub-system following the DAG, with dependency context
    3. **Summarize Agent**: Aggregate all views, resolve conflicts, generate unified AD.md
    
    ### Role & Context
    
    You are acting as an **Architecture Orchestrator** managing a multi-phase documentation generation workflow. Your role involves:
    
    - **Planning** the generation DAG based on sub-system analysis
    - **Executing** view generation with proper dependency ordering
    - **Summarizing** views into a unified Architecture Description
    - **Persisting** state for resumability across AI agent sessions
    
    #### Architecture Document Hierarchy
    
    | Document | Purpose | Location |
    |----------|---------|----------|
    | `{REPO_ROOT}/.adlc/drafts/adr/` | Architectural decisions with rationale (individual file format) | Input |
    | `{REPO_ROOT}/.adlc/architect/state.json` | DAG execution state | State |
    | `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md` | Per-view outputs | Reference |
    | `{REPO_ROOT}/AD.md` | Full Architecture Description | Output |
    | `{REPO_ROOT}/.adlc/memory/constitution.md` | Governance principles | Constraint |
    
    **IMPORTANT - Path Resolution**:
    - The setup script outputs `REPO_ROOT` - use this to determine the correct paths
    - REPO_ROOT is found by searching upward from current directory for `.adlc` directory
    - NEVER use relative paths like `.adlc/drafts/adr.md` - always use `{REPO_ROOT}/.adlc/drafts/adr/ADR-{NNN}.md`
    - The setup script reads individual ADR files from the `adr/` directory
    - When running from a subdirectory (e.g., a subproject directory), `.adlc` may be in the parent directory
    
    #### View Templates
    
    Located in the skill's `templates/` directory:
    
    | Template | Purpose |
    |----------|---------|
    | `templates/views/context.md` | Context View template |
    | `templates/views/functional.md` | Functional View template |
    | `templates/views/information.md` | Information View template |
    | `templates/views/concurrency.md` | Concurrency View template (optional) |
    | `templates/views/development.md` | Development View template |
    | `templates/views/deployment.md` | Deployment View template |
    | `templates/views/operational.md` | Operational View template (optional) |
    
    | Perspective Templates (10 total) |
    |-----------------------------------|
    | `templates/perspectives/security.md` |
    | `templates/perspectives/performance.md` |
    | `templates/perspectives/accessibility.md` |
    | `templates/perspectives/availability.md` |
    | `templates/perspectives/evolution.md` |
    | `templates/perspectives/internationalization.md` |
    | `templates/perspectives/location.md` |
    | `templates/perspectives/regulation.md` |
    | `templates/perspectives/usability.md` |
    | `templates/perspectives/development-resource.md` |
    
    ### Three-Phase DAG Workflow
    
    ```text
    ┌─────────────────────────────────────────────────────────────────────────────┐
    │                          PHASE 1: PLAN                                      │
    │  ┌─────────────┐    ┌─────────────────┐    ┌─────────────────────────────┐ │
    │  │ Load ADRs   │───▶│ Detect Sub-     │───▶│ Generate DAG per Sub-system │ │
    │  │             │    │ systems         │    │ (apply customization rules) │ │
    │  └─────────────┘    └─────────────────┘    └──────────────┬──────────────┘ │
    │                                                           │                 │
    │                                            ┌──────────────▼──────────────┐ │
    │                                            │ Present Plan for Approval   │ │
    │                                            │ (user confirms or modifies) │ │
    │                                            └──────────────┬──────────────┘ │
    │                                                           │                 │
    │                                            ┌──────────────▼──────────────┐ │
    │                                            │ Write state.json            │ │
    │                                            └─────────────────────────────┘ │
    └─────────────────────────────────────────────────────────────────────────────┘
                                          │
                                          ▼
    ┌─────────────────────────────────────────────────────────────────────────────┐
    │                          PHASE 2: EXECUTE                                   │
    │  ┌─────────────────────────────────────────────────────────────────────┐   │
    │  │  For each sub-system, execute DAG in topological order:             │   │
    │  │                                                                      │   │
    │  │  ┌─────────┐    ┌────────────┐    ┌─────────────┐    ┌───────────┐ │   │
    │  │  │ Context │───▶│ Functional │───▶│ Information │───▶│Development│ │   │
    │  │  └─────────┘    └────────────┘    └─────────────┘    └───────────┘ │   │
    │  │                        │                                    │       │   │
    │  │                        ▼                                    ▼       │   │
    │  │               ┌─────────────┐                      ┌────────────┐  │   │
    │  │               │ Concurrency │                      │ Deployment │  │   │
    │  │               │ (optional)  │                      └────────────┘  │   │
    │  │               └─────────────┘                             │        │   │
    │  │                                                           ▼        │   │
    │  │                                                   ┌─────────────┐  │   │
    │  │                                                   │ Operational │  │   │
    │  │                                                   │ (optional)  │  │   │
    │  │                                                   └─────────────┘  │   │
    │  └─────────────────────────────────────────────────────────────────────┘   │
    │                                                                             │
    │  Each view: Read dependencies → Generate content (with perspectives inline)
    │             → Update state.json with progress                               │
    └─────────────────────────────────────────────────────────────────────────────┘
                                          │
                                          ▼
    ┌─────────────────────────────────────────────────────────────────────────────┐
    │                          PHASE 3: SUMMARIZE                                 │
    │  ┌──────────────────┐    ┌─────────────────────┐    ┌──────────────────┐   │
    │  │ Read all view    │───▶│ Detect cross-       │───▶│ Resolve conflicts│   │
    │  │ files            │    │ subsystem conflicts │    │ using ADRs       │   │
    │  └──────────────────┘    └─────────────────────┘    └────────┬─────────┘   │
    │                                                               │             │
    │  ┌──────────────────┐                       ┌──────────────▼───────────┐ │
    │  │ Move Accepted    │◀─────────────────────────│ Aggregate into            │ │
    │  │ ADRs to memory   │                         │ unified AD.md (views include│ │
    │  └──────────────────┘                         │ perspective sections)     │ │
    │                                             └───────────────────────────────┘ │
    └─────────────────────────────────────────────────────────────────────────────┘
    ```
    
    > **Note**: Perspectives (Security, Performance, etc.) are now applied **during** view generation in Phase 2, not as a separate step in Phase 3. This follows the R&W principle: "use them with each view to analyze and validate the qualities of your architecture."
    
    ### Pre-Flight Validation (MANDATORY - Hard Enforcement)
    
    > **CRITICAL**: These validations are ENFORCED. Execution will HALT if checks fail.
    > Use `--force` flag only in emergency situations with full understanding of risks.
    
    **Before starting Phase 1, you MUST validate prerequisites:**
    
    #### Workflow State Check (unless --force)
    
    1. **Check clarify completion in state.json**:
       - Load `{REPO_ROOT}/.adlc/architect/state.json`
       - Check `workflow.clarify_completed` field
       - If `false` or missing:
         ```
         ❌ WORKFLOW VALIDATION FAILED
    
         The implement command requires ADRs to be approved via /architect-clarify first.
    
         Current workflow state: clarify_completed = false
    
         Required: Run /architect-clarify and complete Phase 5.5 (ADR Approval)
    
         Options:
         1. Run /architect-clarify to approve ADRs
         2. Use --force to bypass (NOT RECOMMENDED - may cause inconsistent architecture)
    
         ⚠️  Using --force skips important validation steps and may result in:
            - Processing unapproved ADRs
            - Missing critical architectural decisions
            - Incomplete architecture documentation
         ```
       - **HALT execution** (unless `--force` flag provided)
    
    #### ADR Status Check
    
    2. **Check ADRs exist**: Verify `{REPO_ROOT}/.adlc/drafts/adr/` or `{REPO_ROOT}/.adlc/memory/adr/` exists (individual file format)
    3. **Check for Accepted ADRs**: Count ADRs with status "Accepted"
       - If **zero Accepted ADRs**: **STOP** and output:
         ```
         ❌ Cannot proceed: No Accepted ADRs found
    
         The implement command requires ADRs with "Accepted" status.
         Current ADRs are: [list statuses found]
    
         Run /architect-clarify to review and approve ADRs first.
         ```
       - If **≥1 Accepted ADR**: Proceed and report: "✓ Found N Accepted ADRs"
    
    ### Mandatory Execution Constraints
    
    > **CRITICAL -- READ THIS BEFORE PROCEEDING**
    >
    > The following constraints are MANDATORY. Violation of any constraint
    > invalidates the output and requires restart.
    >
    > #### Constraint 1: View Files MUST Be Written to Disk
    > You **MUST** write each view to disk as a separate file before proceeding
    > to the next view. Location: `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md`
    > - Do NOT hold views in memory and write only AD.md
    > - Do NOT combine multiple views into a single write operation
    > - Each file MUST be readable and standalone
    > - Minimum content: 20 lines with proper section headers
    >
    > #### Constraint 2: State MUST Be Updated After EACH View
    > You **MUST** update state.json immediately after EACH individual view
    > file is written to disk and verified readable -- before starting the
    > next view in the DAG. Do NOT batch updates per-subsystem or per-phase.
    > Mark each view's progress as "completed" only AFTER the file exists on
    > disk and you've verified it by reading it back.
    >
    > #### Constraint 3: Functional View Checkpoint is MANDATORY
    > You **MUST** pause after Functional view for user checkpoint (unless `--no-checkpoint`).
    > Do NOT silently continue. Present checkpoint options A/B/C/D and WAIT for response.
    > The Functional view is the "cornerstone" -- user approval is required.
    >
    > #### Constraint 4: Phase "completed" Requires Verification
    > You **MUST NOT** mark phase as "completed" in state.json until:
    > - All view files exist on disk (verify by reading each file)
    > - AD.md has been written with content aggregated from view files
    > - Drafts cleanup has been performed and verified
    > - The final verification table (10 checks) has been output
    >
    > #### Constraint 5: AD.md Content MUST Come From View Files
    > You **MUST NOT** write AD.md directly from ADRs. AD.md content MUST come from
    > reading the generated view files. The flow is strictly:
    > ADRs → Views (files on disk) → AD.md (aggregated from views)
    >
    > #### Constraint 6: Phase 3 MUST Read From Disk
    > You **MUST** read view files from disk in Phase 3, not from memory.
    > Use file read operations. This ensures resumability and auditability.
    > If a view file cannot be read, STOP and report the error.
    >
    > #### Constraint 7: Views MUST Be in Sub-system DAG
    > You **MUST NOT** generate a view that is not listed in the sub-system's
    > `dag` array in state.json. Before generating any view, check the DAG.
    > If the view is absent, mark it as `skipped` in state.json and proceed.
    > Generating views outside the DAG creates orphaned files and invalidates
    > the architecture.
    >
    > #### Constraint 8: AD.md MUST Be Organized by Viewpoint
    > You **MUST** organize AD.md by **viewpoint** (§3.1 Context, §3.2 Functional,
    > §3.3 Information, etc.), **NOT** by subsystem. Each viewpoint section
    > presents the **unified system-level** perspective that merges content
    > from all subsystems. Subsystem-specific detail is accessible via
    > "Subsystem Details" links (see Step 3.5).
    >
    > **WRONG** (per-subsystem — this is what subsystem view files are for):
    > `## 5. Sub-System: Auth → ### 5.1 Context → ### 5.2 Functional`
    >
    > **RIGHT** (per-viewpoint — unified across ALL subsystems):
    > `## 3. Architectural Views → ### 3.1 Context View → ### 3.2 Functional View`
    >
    > #### Constraint 9: Diagrams MUST Use Mermaid Syntax
    > You **MUST** use Mermaid syntax for all architectural diagrams in both
    > view files and AD.md. ASCII box-drawing art (characters like `┌`, `└`,
    > `├`, `│`, `───`, `═══`) is **NOT** permitted for architecture diagrams.
    >
    > Accepted Mermaid diagram types:
    > - `graph TB/LR` — architecture, topology, flow diagrams
    > - `erDiagram` — data models and entity relationships
    > - `sequenceDiagram` — interaction flows
    > - `flowchart` — process flows
    >
    > Directory tree listings (code organization) may use plain `text`
    > code blocks — these are not architectural diagrams.
    
    ### PHASE 1: PLAN (Plan Agent)
    
    **Objective**: Analyze ADRs, detect sub-systems, generate customized DAG, get user approval
    
    **Script Action**: Run `scripts/bash/setup-architect.sh` which calls `plan-dag` internally
    
    #### Step 1.1: Load and Analyze ADRs
    
    1. **Read ADR Directory**: Load ADRs from `{REPO_ROOT}/.adlc/drafts/adr/` (and check `{REPO_ROOT}/.adlc/memory/adr/` if drafts is empty)
    2. **Parse ADR Index**: Extract sub-systems from `{REPO_ROOT}/.adlc/drafts/adr/adr.md` or individual ADR files
    3. **Group ADRs by Sub-system**: Create mapping of sub-system → ADRs
    4. **Validate ADR Status** (MANDATORY):
       - Count ADRs by status: Accepted / Proposed / Discovered
       - If **zero Accepted ADRs**: **STOP execution** and output error:
         ```
         ❌ PHASE 1 BLOCKED: No Accepted ADRs
         
         Found: [N] Proposed, [M] Discovered, [0] Accepted
         
         The implement command ONLY processes "Accepted" ADRs.
         Run /architect-clarify to approve ADRs before implementation.
         ```
       - Report to user: "✓ Found [N] Accepted ADRs ready for implementation"
    
    **ADR Index Table Format**:
    
    ```markdown
    | ID | Sub-System | Decision | Status | Date | Owner |
    |----|------------|----------|--------|------|-------|
    | ADR-001 | Core | Microservices architecture | Accepted | 2024-01-15 | @architect |
    | ADR-002 | Auth | OAuth2 with PKCE | Accepted | 2024-01-16 | @security |
    | ADR-003 | Data | PostgreSQL primary store | Accepted | 2024-01-17 | @data |
    ```
    
    #### Step 1.2: Detect Sub-systems and Characteristics
    
    For each sub-system, analyze ADRs to detect:
    
    | Characteristic | Detection Pattern | DAG Customization |
    |---------------|-------------------|-------------------|
    | Serverless | Lambda, Functions, serverless | Deployment view first |
    | Event-driven | Events, messaging, async, Kafka, RabbitMQ | Include Concurrency view |
    | Data-intensive | Analytics, ETL, data pipeline | Information view priority |
    | API-first | REST, GraphQL, OpenAPI | Functional view priority |
    | Multi-region | Global, multi-region, geo | Deployment + Operational |
    
    #### Step 1.3: Generate Customized DAG per Sub-system
    
    **Default DAG (Core Views)**:
    
    ```text
    Context → Functional → Information → Development → Deployment
    ```
    
    **Extended DAG (All Views)**:
    
    ```text
    Context → Functional → Information ──┬─→ Development → Deployment → Operational
                                         └─→ Concurrency ─────────────────┘
    ```
    
    **DAG Customization Rules**:
    
    | Pattern Detected | DAG Modification |
    |-----------------|------------------|
    | Serverless | Deployment before Development |
    | Event-driven | Add Concurrency after Information |
    | Data-intensive | Information has highest priority after Context |
    | Microservices | Add Concurrency, expand Functional |
    | Monolith | Simplify Functional, skip Concurrency |
    
    #### Step 1.4: Present Plan for User Approval
    
    **Sub-System Count Threshold Enforcement** (MANDATORY):
    Regardless of any prior approval from `/architect-specify`, you **MUST**
    apply the following rules before presenting the DAG plan:
    
    | Sub-System Count | Required Action |
    |-----------------|-----------------|
    | 1–3 | Present plan; auto-approve allowed |
    | 4–6 | **MUST ask user confirmation** — do not proceed without explicit approval |
    | >6 | **MUST suggest grouping** and **MUST ask confirmation** |
    
    > **CRITICAL**: Approval from `/architect-specify` (Phase 0) does **NOT**
    > substitute for DAG execution plan approval. The user must confirm the
    > per-sub-system DAG plan independently.
    
    Present the execution plan to the user:
    
    ```markdown
    ## DAG Execution Plan
    
    **Sub-systems detected**: 3
    **Total views to generate**: 15 (5 views × 3 sub-systems)
    
    ### Sub-system: Core
    **ADRs**: ADR-001, ADR-005, ADR-008
    **Characteristics**: Microservices, Event-driven
    **DAG**: Context → Functional → Information → Concurrency → Development → Deployment
    
    ### Sub-system: Auth
    **ADRs**: ADR-002, ADR-006
    **Characteristics**: API-first
    **DAG**: Context → Functional → Information → Development → Deployment
    
    ### Sub-system: Data
    **ADRs**: ADR-003, ADR-004, ADR-007
    **Characteristics**: Data-intensive
    **DAG**: Context → Information → Functional → Development → Deployment
    
    ---
    
    **Approve this plan?** [Yes/Modify/Cancel]
    ```
    
    #### Step 1.5: Write state.json
    
    After user approval, write the execution plan to `{REPO_ROOT}/.adlc/architect/state.json`:
    
    ```json
    {
      "version": "1.1.0",
      "created_at": "2024-01-20T10:30:00Z",
      "updated_at": "2024-01-20T10:30:00Z",
      "phase": "plan_approved",
      "views_mode": "core",
      "workflow": {
        "clarify_completed": false,
        "clarify_completed_at": null,
        "adrs_approved_count": 0,
        "implement_started": false,
        "implement_started_at": null
      },
      "subsystems": [
        {
          "id": "core",
          "name": "Core",
          "adrs": ["ADR-001", "ADR-005", "ADR-008"],
          "characteristics": ["microservices", "event-driven"],
          "dag": ["context", "functional", "information", "concurrency", "development", "deployment"],
          "progress": {
            "context": "pending",
            "functional": "pending",
            "information": "pending",
            "concurrency": "pending",
            "development": "pending",
            "deployment": "pending"
          }
        },
        {
          "id": "auth",
          "name": "Auth",
          "adrs": ["ADR-002", "ADR-006"],
          "characteristics": ["api-first"],
          "dag": ["context", "functional", "information", "development", "deployment"],
          "progress": {
            "context": "pending",
            "functional": "pending",
            "information": "pending",
            "development": "pending",
            "deployment": "pending"
          }
        }
      ],
      "perspectives": ["security", "performance"],
      "output_file": "AD.md"
    }
    ```
    
    ### PHASE 2: EXECUTE (Execute Agent)
    
    **Objective**: Generate views per sub-system following the DAG, with dependency context passing
    
    **Script Action**: The agent reads `state.json` and executes views in DAG order
    
    #### Step 2.1: Read Execution State
    
    1. Load `{REPO_ROOT}/.adlc/architect/state.json`
    2. Identify next view(s) to generate (views with all dependencies completed)
    3. Load relevant ADRs for the current sub-system
    
    #### Step 2.2: Generate Views in DAG Order
    
    For each view in the DAG:
    
    0. **DAG Membership Check**: Confirm the view is listed in the sub-system's
       `dag` array in state.json. If absent → mark `skipped`, do NOT generate,
       continue to next view.
    1. **Check Dependencies**: Ensure all dependency views are completed
    2. **Load Dependency Context**: Read completed view files for context
    3. **Load View Template**: Read from `templates/views/{view}.md`
    4. **Generate View Content**: Fill template with ADR-derived content
    5. **Write View File**: Save to `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md`
    6. **Update State**: Mark view as "completed" in state.json
    
    **View Generation with Dependency Context**:
    
    ```markdown
    ## Generating: Functional View for "Core" sub-system
    
    **Dependencies loaded**:
    - Context View: {REPO_ROOT}/.adlc/architect/views/core/context.md (completed)
    
    **ADRs for this view**: ADR-001 (Microservices), ADR-005 (API Gateway)
    
    **Generating content...**
    ```
    
    #### Step 2.3: View Templates and Placeholders
    
    Each view template contains placeholders to be filled:
    
    | Placeholder | Replacement |
    |-------------|-------------|
    | `[SUB_SYSTEM_NAME]` | Sub-system name from state.json |
    | `[ADR_IDS]` | Comma-separated ADR IDs |
    | `[DATE]` | Current date (YYYY-MM-DD) |
    | `[ENTITY_N]` | Extracted from ADRs |
    | `[COMPONENT_N]` | Extracted from ADRs |
    
    #### Step 2.4: View Generation Details
    
    ##### Context View
    
    **Purpose**: System scope and external interactions (blackbox view)
    **Dependencies**: None (first in DAG)
    **Template**: `templates/views/context.md`
    **Key Content**:
    
    - System scope description
    - External entities table (stakeholders + external systems only)
    - Context diagram (system as single blackbox)
    - External dependencies table
    
    ##### Functional View (★ CORNERSTONE - USER CHECKPOINT)
    
    **Purpose**: Internal components, responsibilities, interactions
    **Dependencies**: Context View
    **Template**: `templates/views/functional.md`
    **Key Content**:
    
    - Functional elements table
    - Element interactions diagram
    - Functional boundaries
    
    > **IMPORTANT**: After generating the Functional view, execution **pauses** for user approval.
    > This is the "cornerstone" view that shapes all subsequent views.
    > 
    > **Rozanski & Woods**: "The Functional view is the cornerstone... It usually drives the shape of other system structures."
    > 
    > **Checkpoint Options**:
    > - **A**: Approve - Continue to remaining views
    > - **B**: Modify - Edit functional view, then continue
    > - **C**: Restart - Regenerate with feedback
    > - **D**: Cancel - Stop execution
    
    **If skipping checkpoint** (`--no-checkpoint` flag): Generate without pause but log warning.
    
    ##### Information View
    
    **Purpose**: Data storage, management, and flow
    **Dependencies**: Context View, Functional View
    **Template**: `templates/views/information.md`
    **Key Content**:
    
    - Data entities table
    - ER diagram
    - Data flow description
    
    ##### Concurrency View (Optional)
    
    **Purpose**: Runtime processes, threads, coordination
    **Dependencies**: Functional View, Information View
    **Template**: `templates/views/concurrency.md`
    **Condition**: Only if `--views all` or `--views concurrency`
    **Key Content**:
    
    - Process structure table
    - Sequence diagram
    - Coordination mechanisms
    
    ##### Development View
    
    **Purpose**: Code organization, dependencies, CI/CD
    **Dependencies**: Functional View
    **Template**: `templates/views/development.md`
    **Key Content**:
    
    - Code organization structure
    - Module dependencies
    - Build & CI/CD description
    
    ##### Deployment View
    
    **Purpose**: Physical environment, nodes, networks
    **Dependencies**: Development View
    **Template**: `templates/views/deployment.md`
    **Key Content**:
    
    - Runtime environments table
    - Network topology diagram
    - Hardware requirements
    
    ##### Operational View (Optional)
    
    **Purpose**: Operations, support, maintenance
    **Dependencies**: Deployment View
    **Template**: `templates/views/operational.md`
    **Condition**: Only if `--views all` or `--views operational`
    **Key Content**:
    
    - Operational responsibilities
    - Monitoring & alerting
    - Disaster recovery
    
    #### Step 2.5: Update Progress in state.json
    
    > **WARNING**: Batching state updates (e.g., updating only after all views
    > for a sub-system are complete) violates Constraint 2. Update state.json
    > immediately after each individual view file is written and verified.
    
    After each view is generated:
    
    ```json
    {
      "progress": {
        "context": "completed",
        "functional": "completed",
        "information": "in_progress",
        "development": "pending",
        "deployment": "pending"
      },
      "updated_at": "2024-01-20T11:15:00Z"
    }
    ```
    
    #### Step 2.6: Resumability
    
    If the agent session is interrupted:
    
    1. Next session loads `state.json`
    2. Identifies views with `"pending"` or `"in_progress"` status
    3. Continues from where it left off
    4. Skips already `"completed"` views
    
    #### Phase 2→3 Gate: Verify View Files Exist (MANDATORY)
    
    **Before proceeding to Phase 3, you MUST verify that all expected view files exist on disk:**
    
    1. For each subsystem in state.json, check every view with status "completed"
    2. Verify the file exists: `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md`
    3. Verify each file is readable and has minimum content (≥20 lines)
    4. **Mermaid scan (Constraint 9)**: Scan each view file for ASCII box-drawing
       characters (`┌`, `└`, `├`, `│`, `═`, `───`). If found in any view that
       should contain architectural diagrams (context, functional, information,
       deployment), flag as a warning and note the file for correction.
    
    **Verification Checklist** (output this table):
    
    | Subsystem | View | File Path | Exists | Readable | Lines | Mermaid OK |
    |-----------|------|-----------|--------|----------|-------|------------|
    | {subsystem} | {view} | {path} | ✓/✗ | ✓/✗ | {N} | ✓/⚠ |
    
    **Gate Decision:**
    - If **ALL checks pass** → Proceed to Phase 3
    - If **Mermaid warnings** → Log warnings but proceed (non-blocking). Output:
      ```
      ⚠️ MERMAID WARNING: ASCII box-drawing art detected in:
      - {subsystem}/{view}: Convert to Mermaid diagram syntax
      
      Proceeding to Phase 3. Fix ASCII diagrams in next iteration.
      ```
    - If **ANY other check fails** → STOP and report:
      ```
      ❌ PHASE 2→3 GATE BLOCKED
      
      Missing or invalid view files detected:
      - {subsystem}/{view}: [reason]
      
      Regenerate missing views before proceeding to Phase 3.
      ```
    
    ### Placeholder Validation (MANDATORY)
    
    **Before finalizing any view file, you MUST validate that all placeholders are filled:**
    
    #### Placeholder Patterns to Check
    
    | Pattern | Example | Severity | Action Required |
    |---------|---------|----------|-----------------|
    | `[TBD]` | `[TBD]` | CRITICAL | Must be filled before completion |
    | `[STAKEHOLDER_*]` | `[STAKEHOLDER_1]` | CRITICAL | Must be replaced with actual stakeholder names |
    | `[ENTITY_*]` | `[ENTITY_1]` | CRITICAL | Must be replaced with actual entity names |
    | `[COMPONENT_*]` | `[COMPONENT_1]` | CRITICAL | Must be replaced with actual component names |
    | `[SUB_SYSTEM_NAME]` | `[SUB_SYSTEM_NAME]` | CRITICAL | Must be replaced with actual sub-system name |
    | `[ADR_IDS]` | `[ADR_IDS]` | HIGH | Must be replaced with actual ADR references |
    | `[DATE]` | `[DATE]` | MEDIUM | Must be replaced with actual date |
    
    #### Validation Process
    
    1. **Scan each view file** after generation for unfilled placeholders
    2. **Count occurrences** of each pattern
    3. **Severity Assessment**:
       - **CRITICAL**: Blocks completion - view cannot be marked "completed"
       - **HIGH**: Should be filled but non-blocking if context is clear
       - **MEDIUM**: Nice to have but not required
    
    #### Validation Report Template
    
    ```markdown
    ## Placeholder Validation Report
    
    | View | Placeholder | Count | Severity | Status |
    |------|-------------|-------|----------|--------|
    | context | [STAKEHOLDER_1] | 3 | CRITICAL | ❌ UNFILLED |
    | functional | [COMPONENT_1] | 5 | CRITICAL | ❌ UNFILLED |
    
    ### Critical Placeholders Unfilled
    
    **❌ VALIDATION FAILED**: Cannot mark views as "completed" with unfilled critical placeholders.
    
    **Required Actions**:
    1. Review ADRs for stakeholder names → fill [STAKEHOLDER_*] placeholders
    2. Review ADRs for component names → fill [COMPONENT_*] placeholders
    3. Re-run view generation with complete information
    ```
    
    #### Enforcement
    
    - Views with unfilled CRITICAL placeholders **CANNOT** be marked "completed" in state.json
    - Phase 2→3 gate **WILL FAIL** if any view has unfilled critical placeholders
    - Use `--force` to bypass (emergency only - document all unfilled placeholders)
    
    ### PHASE 3: SUMMARIZE (Summarize Agent)
    
    **Objective**: Aggregate all views, resolve conflicts, generate unified AD.md
    
    **Script Action**: Run `summarize` action
    
    #### Step 3.1: Read All View Files FROM DISK (MANDATORY)
    
    > **CRITICAL**: You MUST read each view file from the filesystem using actual file read operations. 
    > Do NOT use content from memory or from the ADRs directly. The view files are the SOLE source of truth.
    
    1. **Scan Directory**: List `{REPO_ROOT}/.adlc/architect/views/` directory
    2. **Read Each File** (MANDATORY - file by file):
       - For each subsystem/view combination in state.json
       - Read the file: `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md`
       - If file cannot be read → **STOP** and report error:
         ```
         ❌ PHASE 3 ERROR: Cannot read view file
         File: {path}
         Error: {error details}
         
         View files must exist and be readable before AD.md generation.
         ```
    3. **Validate Content** (MANDATORY):
       - Each view file MUST contain ≥20 lines
       - Each view MUST contain proper section headers (## or ###)
       - If content validation fails → **STOP** and report:
         ```
         ❌ PHASE 3 ERROR: Invalid view file content
         File: {path}
         Lines: {count} (minimum 20 required)
         
         View files must have substantial content before AD.md generation.
         ```
    4. **Organize**: Group content by view type across all sub-systems
    
    **Directory Structure**:
    
    ```text
    {REPO_ROOT}/.adlc/architect/views/
    ├── core/
    │   ├── context.md
    │   ├── functional.md
    │   ├── information.md
    │   ├── concurrency.md
    │   ├── development.md
    │   └── deployment.md
    ├── auth/
    │   ├── context.md
    │   ├── functional.md
    │   ├── information.md
    │   ├── development.md
    │   └── deployment.md
    └── data/
        ├── context.md
        ├── functional.md
        ├── information.md
        ├── development.md
        └── deployment.md
    ```
    
    #### Step 3.2: Detect Cross-Subsystem Conflicts
    
    Compare views across sub-systems for:
    
    | Conflict Type | Detection | Resolution |
    |--------------|-----------|------------|
    | Naming inconsistency | Same component, different names | Standardize to ADR terminology |
    | Technology mismatch | Different tech for same purpose | Defer to relevant ADR |
    | Boundary overlap | Components claimed by multiple sub-systems | Use ADR scope definitions |
    | Diagram inconsistency | Same entity, different representations | Unify styling |
    
    #### Step 3.3: Resolve Conflicts Using ADRs
    
    **ADRs are the Source of Truth**. When conflicts are detected:
    
    1. Find the relevant ADR(s) that govern the conflicting area
    2. Apply the ADR decision to resolve the conflict
    3. Document the resolution in the unified view
    
    ```markdown
    ## Conflict Resolution Log
    
    | Conflict | ADR Reference | Resolution |
    |----------|---------------|------------|
    | Auth component naming | ADR-002 | Standardized to "AuthService" per ADR-002 |
    | Database technology | ADR-003 | PostgreSQL confirmed as primary per ADR-003 |
    ```
    
    #### Step 3.4: Aggregate into Unified AD.md
    
    > **CRITICAL: Viewpoint-Organized Aggregation (Constraint 8)**
    >
    > The AD.md MUST follow the structure below, organized by **viewpoint**.
    > Each viewpoint section merges content from ALL subsystems into a unified
    > system-level description. Do NOT organize by subsystem -- that structure
    > belongs in the subsystem view files, not in the aggregated AD.md.
    >
    > For each viewpoint:
    > 1. Present a **system-level summary** that shows how all subsystems relate
    > 2. Include a **unified Mermaid diagram** showing cross-subsystem interactions
    > 3. Summarize each subsystem's role within this viewpoint
    > 4. Link to subsystem details (if 2+ subsystems, per Step 3.5)
    
    ##### Per-Viewpoint Aggregation Recipe
    
    | Viewpoint | How to Aggregate |
    |-----------|-----------------|
    | **Context** | Single system-level blackbox diagram (Mermaid `graph`). Subsystems appear as internal blocks only if they have independent external interfaces. Merge and deduplicate stakeholder and external entity tables across all subsystems. |
    | **Functional** | Merged component inventory table across all subsystems. Single unified interaction diagram showing cross-subsystem data flows. Use Mermaid `subgraph` blocks per subsystem to show boundaries. |
    | **Information** | Consolidated ER diagram (Mermaid `erDiagram`) combining all subsystem entities. Unified data flow showing how data moves across subsystem boundaries (Mermaid `flowchart`). Deduplicate entity tables. |
    | **Concurrency** | Merged process structure table. Unified sequence/flow diagrams showing cross-subsystem async interactions. |
    | **Development** | Single code organization tree showing all subsystems as top-level directories. Merged build process and CI/CD pipeline tables. Unified technology stack mapping. |
    | **Deployment** | Single deployment topology diagram (Mermaid `graph`) showing all subsystems in their runtime environments. Merged runtime environments and hardware requirements tables. |
    | **Operational** | Merged operational responsibilities table. Unified monitoring, alerting, and DR strategy across all subsystems. |
    
    **Structure of Unified AD.md**:
    
    ```markdown
    # Architecture Description: [Project Name]
    
    ## 1. Document Information
    [Version, date, authors, status]
    
    ## 2. Architectural Goals & Constraints
    [From constitution and constraint ADRs]
    
    ## 3. Architectural Views
    
    ### 3.1 Context View
    [Unified from all sub-system context views]
    [Single system-level context diagram]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/context.md) | [Auth](.adlc/architect/views/auth/context.md) | [Data](.adlc/architect/views/data/context.md)
    
    ### 3.2 Functional View
    [Merged functional elements from all sub-systems]
    [Unified component diagram]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/functional.md) | [Auth](.adlc/architect/views/auth/functional.md) | [Data](.adlc/architect/views/data/functional.md)
    
    ### 3.3 Information View
    [Consolidated data model]
    [Unified ER diagram]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/information.md) | [Auth](.adlc/architect/views/auth/information.md) | [Data](.adlc/architect/views/data/information.md)
    
    ### 3.4 Concurrency View (if applicable)
    [Merged from sub-systems with concurrency]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/concurrency.md) | [Auth](.adlc/architect/views/auth/concurrency.md)
    
    ### 3.5 Development View
    [Unified code organization]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/development.md) | [Auth](.adlc/architect/views/auth/development.md) | [Data](.adlc/architect/views/data/development.md)
    
    ### 3.6 Deployment View
    [Consolidated deployment topology]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/deployment.md) | [Auth](.adlc/architect/views/auth/deployment.md) | [Data](.adlc/architect/views/data/deployment.md)
    
    ### 3.7 Operational View (if applicable)
    [Merged operational concerns]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/operational.md) | [Auth](.adlc/architect/views/auth/operational.md)
    
    ## 4. Architectural Perspectives
    
    ### 4.1 Security Perspective
    [Apply security template across all views]
    
    ### 4.2 Performance & Scalability Perspective
    [Apply performance template across all views]
    
    ## 5. Architecture Decision Records Summary
    [Index linking to {REPO_ROOT}/.adlc/memory/adr/adr.md]
    
    ## 6. Tech Stack Summary
    [Consolidated from all ADRs]
    ```
    
    #### Step 3.5: Generate Subsystem View Links (CONDITIONAL)
    
    **Condition**: Only generate links if `len(state.json.subsystems) > 1`
    
    For each view section in AD.md:
    
    1. **Collect subsystem links**:
       - For each subsystem in state.json
       - Check if view exists in subsystem's `dag` array
       - Build link: `[SubsystemName](.adlc/architect/views/{subsystem-id}/{view}.md)`
    
    2. **Format link block**:
       ```markdown
       > **Subsystem Details**: [Core](path) | [Auth](path) | [Data](path)
       ```
    
    3. **Handle missing views**:
       - If a subsystem doesn't have a particular view (not in `dag`), skip that subsystem's link
       - Example: If Auth doesn't have Concurrency view, omit from Concurrency links
    
    4. **Single subsystem case**:
       - If only 1 subsystem exists, **SKIP** adding links entirely
       - The unified view is identical to the subsystem view, making links redundant
    
    **Example Output** (3 subsystems, all have Context view):
    ```markdown
    ### 3.1 Context View
    [Unified system-level context]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/context.md) | [Auth](.adlc/architect/views/auth/context.md) | [Data](.adlc/architect/views/data/context.md)
    ```
    
    **Example Output** (2 subsystems, only Core has Concurrency):
    ```markdown
    ### 3.4 Concurrency View
    [Merged concurrency concerns]
    
    > **Subsystem Details**: [Core](.adlc/architect/views/core/concurrency.md)
    ```
    
    #### Step 3.6: Apply Perspectives
    
    Load perspective templates and apply across all views:
    
    ##### Security Perspective (`templates/perspectives/security.md`)
    
    - Authentication & authorization approach
    - Data protection measures
    - Threat model table
    
    ##### Performance Perspective (`templates/perspectives/performance.md`)
    
    - Performance requirements table
    - Scalability model
    - Capacity planning
    
    #### Step 3.7: ADR Lifecycle Management (MANDATORY)
    
    After generating AD.md, perform ALL of the following steps:
    
    **Step 1: Filter Accepted ADRs**
    - Identify ADRs with **exact** status "Accepted" only
    - **MUST remain in drafts**: Any ADR with status "Proposed", "Discovered",
      "Deprecated", or "Superseded" — these are NOT eligible for promotion
    - **Verification**: After filtering, count non-Accepted ADRs in the promotion
      set. If >0, STOP and fix before proceeding.
    
    **Step 2: Copy to Canonical Location (MANDATORY)**
    - Move Accepted ADR files into `{REPO_ROOT}/.adlc/memory/adr/`
    - Create the file if it doesn't exist, or merge with existing content
    - **VERIFY**: Read the file back and confirm ADRs are present
    
    **Step 3: Clean Up Drafts (MANDATORY)**
     - Move each promoted ADR file from `{REPO_ROOT}/.adlc/drafts/adr/` to `{REPO_ROOT}/.adlc/memory/adr/`
     - If no ADRs remain in drafts → the setup script cleans up empty directories
     - **VERIFY**: Confirm:
       - No duplicate ADRs exist (same ID in both locations)
       - Remaining ADRs (if any) are Proposed/Discovered only
       - `adr.md` index regenerated for both scopes (drafts + memory)
    
    **Step 3b: Generate Memory ADR Index (MANDATORY)**
    
    After moving Accepted ADRs to `.adlc/memory/adr/`, generate a memory index file at `{REPO_ROOT}/.adlc/memory/adr/adr.md` using the `generate_adr_index` function from the setup script (the same function that generates the drafts index, but with scope=memory):
    
    ```bash
    source "{REPO_ROOT}/.agents/skills/architect-implement/scripts/bash/setup-architect.sh"
    generate_adr_index memory
    ```
    
    This writes `{REPO_ROOT}/.adlc/memory/adr/adr.md` with the 7-column schema, parsing YAML frontmatter via `parse_fm_field`. The index format:
    
    ```markdown
    # Architecture Decision Records (Memory)
    
    > Auto-generated by /architect-implement. Accepted ADRs only.
    > Source: .adlc/memory/adr/ADR-*.md
    
    ## ADR Index
    
    | ID | Sub-System | Decision | Status | Date |
    |----|------------|----------|--------|------|
    | ADR-301 | System | Agent-Agnostic Container Architecture | Completed | 2026-08-08 |
    ```
    
    This index is consumed by `team-boot` for session-start injection and by `architect-analyze` for architecture review (similar to how `CDR.md` is used for team-level context).
    
    **Step 4: Report Lifecycle Changes (MANDATORY)**
    Output this summary to the user:
    ```
    📋 ADR Lifecycle Summary:
    ├── Promoted to memory: [N] Accepted ADRs
    ├── Remaining in drafts: [M] ADRs (Proposed/Discovered)
    ├── Duplicates found: [0] ✓
    └── Cleanup verified: ✓
    ```
    
    **If ANY step fails**: STOP and fix before marking Phase 3 complete.
    
    #### Step 3.8: Generate Final Report
    
    ```markdown
    ## Architecture Description Generated
    
    **Output**: AD.md (project root)
    **Views Mode**: [core|all|custom]
    **Sub-systems Processed**: N
    
    **Views Generated**:
    | Sub-system | Views | Status |
    |------------|-------|--------|
    | Core | Context, Functional, Information, Concurrency, Development, Deployment | ✓ |
    | Auth | Context, Functional, Information, Development, Deployment | ✓ |
    | Data | Context, Functional, Information, Development, Deployment | ✓ |
    
    **Perspectives Applied**:
    - [x] Security
    - [x] Performance & Scalability
    
    **Conflicts Resolved**: M
    **ADR Coverage**: X/Y ADRs incorporated
    
    **ADR Lifecycle**:
    - Promoted to canonical: N ADRs
    - Remaining in drafts: M ADRs
    
    **Recommended Next Steps**:
    1. Review generated AD.md for accuracy
    2. Run `/architect-analyze` for consistency validation
    3. Share with stakeholders for review
    4. Run `/architect-analyze` to validate the generated architecture
    ```
    
    ### Final Completion Verification (MANDATORY)
    
    **Before marking state.json phase as "completed", verify ALL outputs:**
    
    Run this 10-point verification checklist:
    
    | Check | Expected | Verification Method | Status |
    |-------|----------|---------------------|--------|
    | 1. View files on disk | N files (one per view per subsystem) | List `{REPO_ROOT}/.adlc/architect/views/` | ☐ |
    | 2. AD.md exists | Yes, at project root | Check file existence | ☐ |
    | 3. AD.md content size | >200 lines | Count lines in AD.md | ☐ |
    | 4. AD.md has all views | N sections (## 3.x headers) | Parse AD.md headers | ☐ |
    | 5. Memory ADRs promoted | N Accepted ADRs | Count files in `{REPO_ROOT}/.adlc/memory/adr/` | ☐ |
    | 6. Drafts cleaned | No duplicates | Compare drafts vs memory | ☐ |
    | 7. state.json consistent | All views "completed" | Verify progress field | ☐ |
    | 8. Subsystem links (if applicable) | Links in AD.md (if 2+ subsystems) | Scan AD.md for "Subsystem Details" | ☐ |
    | 9. Viewpoint-organized (Constraint 8) | No `## N. Sub-System:` sections | Scan AD.md for per-subsystem top-level headers | ☐ |
    | 10. Mermaid diagrams (Constraint 9) | No ASCII box-drawing art | Scan AD.md for `┌`, `└`, `├`, `═` characters | ☐ |
    
    **Gate Rule:**
    - If **ALL checks pass** (☑): Mark phase as "completed" in state.json
    - If **ANY check fails** (☒): Do NOT mark as completed. Fix the issue and re-verify.
    
    **Output to User:**
    ```
    ✅ Architecture Description Generation Complete
    
    Verification Results:
    ├── View files: [N] generated ✓
    ├── AD.md: [lines] lines, [sections] views ✓
    ├── Subsystem links: [N] links (if applicable) ✓
    ├── Viewpoint-organized: ✓
    ├── Mermaid diagrams: ✓
    ├── ADRs promoted: [N] to memory ✓
    ├── Drafts cleaned: [N] remaining ✓
    └── State consistent: ✓
    
    Status: READY FOR USE
    ```
    
    ### State File Schema
    
    **Location**: `{REPO_ROOT}/.adlc/architect/state.json`
    
    ```json
    {
      "version": "1.1.0",
      "created_at": "ISO8601 timestamp",
      "updated_at": "ISO8601 timestamp",
      "phase": "planning | plan_approved | executing | summarizing | completed",
      "views_mode": "core | all | custom",
      "subsystems": [
        {
          "id": "lowercase-kebab-case",
          "name": "Display Name",
          "adrs": ["ADR-001", "ADR-002"],
          "characteristics": ["microservices", "event-driven"],
          "dag": ["context", "functional", "information", "development", "deployment"],
          "progress": {
            "context": "pending | in_progress | completed | skipped",
            "functional": "pending | in_progress | completed | skipped"
          }
        }
      ],
      "perspectives": ["security", "performance"],
      "conflicts_detected": [],
      "conflicts_resolved": [],
      "output_file": "AD.md"
    }
    ```
    
    ### Key Rules
    
    #### ADR Traceability
    
    - **Every view section** must reference source ADRs
    - **No content** without ADR backing
    - **ADRs are source of truth** for conflict resolution
    
    #### State Persistence
    
    - **Always update** state.json after each operation
    - **Resume gracefully** from any interruption
    - **Track progress** at view granularity
    
    #### Multi-Agent Compatibility
    
    - State file works with any AI agent (Claude, Copilot, Cursor, etc.)
    - No agent-specific dependencies
    - Human-readable state for debugging
    
    #### Diagram Quality
    
    - **Validate** Mermaid syntax before writing
    - **Consistent styling** across sub-systems
    - **Unified diagrams** in final AD.md
    
    ### Context
    
    $ARGUMENTS
    
    ## Next Steps
    
    After implement completes, run `/architect-analyze` to validate consistency and quality.
    
    ## Verification
    
    - **AD.md exists** at `{REPO_ROOT}/AD.md` with more than 200 lines and all viewpoint sections (`## 3.x` headers).
    - **Per-subsystem view files** exist at `{REPO_ROOT}/.adlc/architect/views/{subsystem}/{view}.md` for every completed view.
    - **state.json is consistent**: all generated views are marked `"completed"` and the phase is `"completed"`.
    - **Accepted ADRs promoted**: all ADRs with status `"Accepted"` are moved to `{REPO_ROOT}/.adlc/memory/adr/`; the memory index is regenerated at `{REPO_ROOT}/.adlc/memory/adr/adr.md`.
    - **Drafts cleaned up**: promoted ADR files moved from `{REPO_ROOT}/.adlc/drafts/adr/` to `{REPO_ROOT}/.adlc/memory/adr/`; no duplicates remain; any remaining drafts are Proposed/Discovered only.
    - **AD.md is viewpoint-organized**: sections are grouped by viewpoint (`## 3. Architectural Views → ### 3.1 Context View`, etc.), not by subsystem.
    - **Mermaid-only diagrams**: no ASCII box-drawing characters (`┌`, `└`, `├`, `│`, `═`, `───`) are used for architectural diagrams.
    - **Placeholder validation passed**: no critical placeholders (`[TBD]`, `[STAKEHOLDER_*]`, `[ENTITY_*]`, `[COMPONENT_*]`, `[SUB_SYSTEM_NAME]`) remain unfilled in view files.
    - **Subsystem detail links** are present in AD.md when two or more subsystems were processed.

Comments (0)

Sign in to join the conversation.

No comments yet.

Reviews (0)

No reviews yet.

Related