template:
  id: architecture-template-v3-enhanced
  name: VC-SYS Enhanced Architecture Document
  version: 3.0
  output:
    format: markdown
    filename: docs/architecture.md
    title: "{{project_name}} Architecture Document"
    
# VC-SYS Enhancement: Agent permissions and evidence requirements
permissions:
  owner: technical-architect
  editors: [integration-specialist, developer, qa]
  viewers: [scrum-master, product-owner, ux-expert]
  evidence-required: true
  anti-hallucination: enabled

workflow:
  mode: interactive
  elicitation: advanced-elicitation
  facilitation: laboratory-agent
  validation: architect-checklist
  
# VC-SYS Enhancement: Integration with specialized agents
agent-coordination:
  primary: technical-architect
  secondary: 
    - integration-specialist # For API and integration architecture
    - laboratory # For creative architectural exploration
  validation: qa
  approval: product-owner

sections:
  - id: introduction
    title: Introduction
    instruction: |
      If available, review any provided relevant documents to gather all relevant context before beginning. If at a minimum you cannot locate docs/prd.md ask the user what docs will provide the basis for the architecture.
      
      VC-SYS Enhancement: Also check for existing architecture, legacy systems, or brownfield context that may impact decisions.
    sections:
      - id: intro-content
        content: |
          This document outlines the comprehensive project architecture for {{project_name}}, including backend systems, shared services, integration patterns, and non-UI specific concerns. Its primary goal is to serve as the guiding architectural blueprint for AI-driven development, ensuring consistency, adherence to chosen patterns and technologies, and evidence-based decision making.
          
          **Relationship to Frontend Architecture:**
          If the project includes a significant user interface, a separate Frontend Architecture Document will detail the frontend-specific design and MUST be used in conjunction with this document. Core technology stack choices documented herein (see "Tech Stack") are definitive for the entire project, including any frontend components.
          
          **VC-SYS Enhancements:**
          - All architectural decisions include evidence-based rationale
          - Integration patterns consider legacy system constraints
          - Security and permission boundaries are explicitly defined
          - Performance benchmarks and scalability targets are mandatory
          
      - id: architectural-context
        title: Architectural Context Analysis
        instruction: |
          VC-SYS Enhancement: Comprehensive context analysis before architecture design:
          
          1. **Greenfield vs Brownfield Assessment:**
          - Is this a new system or enhancement to existing?
          - What legacy constraints exist?
          - What migration requirements are there?
          
          2. **Integration Landscape:**
          - What systems must this integrate with?
          - What are the integration patterns and constraints?
          - What data synchronization is required?
          
          3. **Performance Requirements:**
          - What are the latency requirements?
          - What is the expected load?
          - What are the scalability targets?
          
          4. **Security Context:**
          - What compliance requirements exist?
          - What are the data sensitivity levels?
          - What threat models apply?
        elicit: true
        evidence-required: true
        
      - id: starter-template
        title: Starter Template or Existing Project
        instruction: |
          Before proceeding further with architecture design, check if the project is based on a starter template or existing codebase:
          
          1. Review the PRD and brainstorming brief for any mentions of:
          - Starter templates (e.g., Create React App, Next.js, Vue CLI, Angular CLI, etc.)
          - Existing projects or codebases being used as a foundation
          - Boilerplate projects or scaffolding tools
          - Previous projects to be cloned or adapted
          
          2. If a starter template or existing project is mentioned:
          - Ask the user to provide access via one of these methods:
            - Link to the starter template documentation
            - Upload/attach the project files (for small projects)
            - Share a link to the project repository (GitHub, GitLab, etc.)
          - Analyze the starter/existing project to understand:
            - Pre-configured technology stack and versions
            - Project structure and organization patterns
            - Built-in scripts and tooling
            - Existing architectural patterns and conventions
            - Any limitations or constraints imposed by the starter
          - Use this analysis to inform and align your architecture decisions
          
          3. If no starter template is mentioned but this is a greenfield project:
          - Suggest appropriate starter templates based on the tech stack preferences
          - Explain the benefits (faster setup, best practices, community support)
          - Let the user decide whether to use one
          
          4. If the user confirms no starter template will be used:
          - Proceed with architecture design from scratch
          - Note that manual setup will be required for all tooling and configuration
          
          5. VC-SYS Enhancement - Legacy System Analysis:
          - If existing system, analyze current architecture
          - Document technical debt and modernization opportunities
          - Identify integration points and dependencies
          - Create migration strategy if replacement is planned
          
          Document the decision here before proceeding with the architecture design.
        elicit: true
        
      - id: changelog
        title: Change Log
        type: table
        columns: [Date, Version, Description, Author, Evidence]
        instruction: Track document versions and changes with evidence links
        
  - id: high-level-architecture
    title: High Level Architecture
    instruction: |
      This section contains multiple subsections that establish the foundation of the architecture. Present all subsections together at once.
      
      VC-SYS Enhancement: Use Technical Architect agent for deep analysis and pattern recommendations.
    elicit: true
    agent: technical-architect
    sections:
      - id: technical-summary
        title: Technical Summary
        instruction: |
          Provide a comprehensive overview (5-7 sentences) of:
          - The system's overall architecture style with justification
          - Key components and their relationships
          - Primary technology choices with evidence
          - Core architectural patterns being used
          - Performance and scalability characteristics
          - Security architecture approach
          - Reference back to the PRD goals and how this architecture supports them
        evidence-required: true
        
      - id: architectural-decision-records
        title: Architectural Decision Records (ADRs)
        instruction: |
          VC-SYS Enhancement: Document key architectural decisions with evidence
          
          For each major decision:
          - Context: What is the issue we're addressing?
          - Decision: What have we decided?
          - Alternatives: What other options were considered?
          - Consequences: What are the implications?
          - Evidence: What data supports this decision?
        type: table
        columns: [Decision, Context, Alternatives, Rationale, Evidence, Status]
        repeatable: true
        
      - id: high-level-overview
        title: High Level Overview
        instruction: |
          Based on the PRD's Technical Assumptions section, describe:
          
          1. The main architectural style (e.g., Monolith, Microservices, Serverless, Event-Driven, Hybrid)
          2. Repository structure decision from PRD (Monorepo/Polyrepo) with tooling
          3. Service architecture decision from PRD with boundaries
          4. Primary user interaction flow or data flow at a conceptual level
          5. Key architectural decisions and their rationale with evidence
          6. VC-SYS Enhancement: Integration architecture for external systems
          7. VC-SYS Enhancement: Performance architecture (caching, CDN, etc.)
          8. VC-SYS Enhancement: Security architecture layers
        evidence-required: true
        
      - id: project-diagram
        title: High Level Project Diagram
        type: mermaid
        mermaid_types: [graph, C4-context, architecture]
        instruction: |
          Create comprehensive Mermaid diagrams that visualize the architecture:
          
          1. C4 Context Diagram - System boundaries and external actors
          2. C4 Container Diagram - Major components and technologies
          3. Data Flow Diagram - How data moves through the system
          4. Integration Architecture - External system connections
          5. Security Architecture - Security boundaries and controls
          
          VC-SYS Enhancement: Include performance optimization points (caches, CDNs) and security boundaries
          
      - id: architectural-patterns
        title: Architectural and Design Patterns
        instruction: |
          List the key high-level patterns that will guide the architecture. For each pattern:
          
          1. Present 3-4 viable options if multiple exist (enhanced from BMad's 2-3)
          2. Provide your recommendation with clear rationale and evidence
          3. Include performance impact analysis
          4. Include security implications
          5. Get user confirmation before finalizing
          6. These patterns should align with the PRD's technical assumptions and project goals
          
          Common patterns to consider:
          - Architectural style patterns (Serverless, Event-Driven, Microservices, CQRS, Hexagonal, Clean Architecture)
          - Code organization patterns (Dependency Injection, Repository, Module, Factory, Domain-Driven Design)
          - Data patterns (Event Sourcing, Saga, Database per Service, CQRS, Transactional Outbox)
          - Communication patterns (REST, GraphQL, gRPC, Message Queue, Pub/Sub, WebSocket)
          - Integration patterns (API Gateway, Backend for Frontend, Anti-Corruption Layer, Strangler Fig)
          - Security patterns (Zero Trust, Defense in Depth, Policy as Code)
        template: |
          - **{{pattern_name}}:** {{pattern_description}}
            - _Rationale:_ {{rationale}}
            - _Evidence:_ {{supporting_evidence}}
            - _Performance Impact:_ {{performance_analysis}}
            - _Security Implications:_ {{security_considerations}}
            - _Trade-offs:_ {{trade_off_analysis}}
        examples:
          - "**Microservices Architecture:** Service decomposition by business capability - _Rationale:_ Enables independent scaling and deployment - _Evidence:_ Team structure aligns with service boundaries (Conway's Law) - _Performance:_ Adds network latency but enables horizontal scaling - _Security:_ Increases attack surface but enables fine-grained access control"
          
  - id: tech-stack
    title: Tech Stack
    instruction: |
      This is the DEFINITIVE technology selection section. Work with the user to make specific choices:
      
      1. Review PRD technical assumptions and any preferences from technical-preferences data file
      2. For each category, present 3-4 viable options with comprehensive pros/cons (enhanced from BMad's 2-3)
      3. Include performance benchmarks and security assessments
      4. Make a clear recommendation based on project needs with evidence
      5. Get explicit user approval for each selection
      6. Document exact versions (avoid "latest" - pin specific versions)
      7. Include upgrade strategy and EOL considerations
      8. This table is the single source of truth - all other docs must reference these choices
      
      VC-SYS Enhancements:
      - Include license compatibility check
      - Document support and community health metrics
      - Specify security update policies
      - Include performance characteristics
      
      Key decisions to finalize:
      - Starter templates (if any) with version
      - Languages and runtimes with exact versions and LTS status
      - Frameworks and libraries with security status
      - Cloud provider and key services with SLAs
      - Database and storage solutions with performance characteristics
      - Development and monitoring tools
      - Security tools and scanners
      
      Upon render of the table, ensure the user is aware of the importance of this sections choices, validate against requirements, and get explicit confirmation.
    elicit: true
    evidence-required: true
    sections:
      - id: cloud-infrastructure
        title: Cloud Infrastructure
        template: |
          - **Provider:** {{cloud_provider}}
          - **Key Services:** {{core_services_list}}
          - **Deployment Regions:** {{regions}}
          - **Availability Targets:** {{availability_sla}}
          - **Disaster Recovery:** {{dr_strategy}}
          - **Cost Optimization:** {{cost_strategy}}
          
      - id: technology-stack-table
        title: Technology Stack Table
        type: table
        columns: [Category, Technology, Version, Purpose, Rationale, License, EOL Date, Security Status]
        instruction: Populate the technology stack table with all relevant technologies including security and monitoring tools
        validation: technical-architect
        examples:
          - "| **Language** | TypeScript | 5.3.3 | Primary development language | Strong typing, excellent tooling, team expertise | MIT | 2025-03 | Active patches |"
          
  - id: data-architecture
    title: Data Architecture
    instruction: |
      VC-SYS Enhancement: Comprehensive data architecture beyond basic models
    sections:
      - id: data-models
        title: Data Models
        instruction: |
          Define the core data models/entities:
          
          1. Review PRD requirements and identify key business entities
          2. For each model, explain its purpose and relationships
          3. Include key attributes and data types
          4. Show relationships between models with cardinality
          5. Include data validation rules
          6. Document data lifecycle and retention
          7. Specify audit requirements
          8. Define data sensitivity levels
          
          Create a clear conceptual model before moving to database schema.
        elicit: true
        repeatable: true
        sections:
          - id: model
            title: "{{model_name}}"
            template: |
              **Purpose:** {{model_purpose}}
              
              **Key Attributes:**
              - {{attribute_1}}: {{type_1}} - {{description_1}} [{{validation_rule_1}}]
              - {{attribute_2}}: {{type_2}} - {{description_2}} [{{validation_rule_2}}]
              
              **Relationships:**
              - {{relationship_1}} ({{cardinality_1}})
              - {{relationship_2}} ({{cardinality_2}})
              
              **Data Governance:**
              - **Sensitivity Level:** {{sensitivity_level}}
              - **Retention Policy:** {{retention_period}}
              - **Audit Requirements:** {{audit_needs}}
              - **Encryption:** {{encryption_requirements}}
              
      - id: data-flow-architecture
        title: Data Flow Architecture
        instruction: |
          VC-SYS Enhancement: Document how data flows through the system
          
          1. Data ingestion patterns
          2. Processing pipelines
          3. Storage strategies
          4. Data synchronization
          5. Caching strategies
          6. Data archival
        type: mermaid
        mermaid_type: dataflow
        
  - id: components
    title: Components & Services
    instruction: |
      Based on the architectural patterns, tech stack, and data models from above:
      
      1. Identify major logical components/services and their responsibilities
      2. Consider the repository structure (monorepo/polyrepo) from PRD
      3. Define clear boundaries and interfaces between components
      4. Include performance SLAs for each component
      5. Define security boundaries and access controls
      6. For each component, specify:
      - Primary responsibility (single responsibility principle)
      - Key interfaces/APIs exposed with contracts
      - Dependencies on other components
      - Technology specifics based on tech stack choices
      - Performance requirements and SLAs
      - Security requirements and access controls
      - Scalability approach
      - Monitoring and alerting strategy
      
      7. Create comprehensive component diagrams
    elicit: true
    agent: integration-specialist
    sections:
      - id: component-list
        repeatable: true
        title: "{{component_name}}"
        template: |
          **Responsibility:** {{component_description}}
          
          **Key Interfaces:**
          - {{interface_1}}: {{contract_1}}
          - {{interface_2}}: {{contract_2}}
          
          **Dependencies:** {{dependencies}}
          
          **Technology Stack:** {{component_tech_details}}
          
          **Performance Requirements:**
          - **Response Time:** {{response_time_sla}}
          - **Throughput:** {{throughput_requirement}}
          - **Availability:** {{availability_target}}
          
          **Security:**
          - **Authentication:** {{auth_method}}
          - **Authorization:** {{authz_approach}}
          - **Data Protection:** {{data_protection_needs}}
          
          **Scalability:**
          - **Approach:** {{scaling_strategy}}
          - **Limits:** {{scaling_limits}}
          
          **Monitoring:**
          - **Metrics:** {{key_metrics}}
          - **Alerts:** {{alert_conditions}}
          
      - id: component-diagrams
        title: Component Diagrams
        type: mermaid
        instruction: |
          Create comprehensive Mermaid diagrams to visualize component relationships:
          - C4 Container diagram for high-level view
          - C4 Component diagram for detailed internal structure
          - Sequence diagrams for complex interactions
          - State diagrams for stateful components
          - Integration flow diagrams
          
  - id: integration-architecture
    title: Integration Architecture
    instruction: |
      VC-SYS Enhancement: Comprehensive integration design by Integration Specialist
    agent: integration-specialist
    sections:
      - id: integration-patterns
        title: Integration Patterns
        instruction: |
          Define integration approach:
          
          1. Synchronous vs asynchronous patterns
          2. API Gateway configuration
          3. Service mesh requirements
          4. Message broker selection
          5. Event streaming architecture
          6. Data synchronization patterns
          
      - id: external-apis
        title: External APIs
        condition: Project requires external API integrations
        instruction: |
          For each external service integration:
          
          1. Identify APIs needed based on PRD requirements and component design
          2. If documentation URLs are unknown, ask user for specifics
          3. Document authentication methods and security considerations
          4. List specific endpoints that will be used
          5. Note any rate limits or usage constraints
          6. Define retry and circuit breaker policies
          7. Specify monitoring and alerting for external dependencies
          8. Document fallback strategies
          
          If no external APIs are needed, state this explicitly and skip to next section.
        elicit: true
        repeatable: true
        sections:
          - id: api
            title: "{{api_name}} API"
            template: |
              - **Purpose:** {{api_purpose}}
              - **Documentation:** {{api_docs_url}}
              - **Base URL(s):** {{api_base_url}}
              - **Authentication:** {{auth_method}}
              - **Rate Limits:** {{rate_limits}}
              - **SLA:** {{api_sla}}
              
              **Key Endpoints Used:**
              - `{{method}} {{endpoint_path}}` - {{endpoint_purpose}}
                - Request: {{request_schema}}
                - Response: {{response_schema}}
                - Error Codes: {{error_codes}}
              
              **Resilience Strategy:**
              - **Retry Policy:** {{retry_config}}
              - **Circuit Breaker:** {{circuit_breaker_config}}
              - **Timeout:** {{timeout_settings}}
              - **Fallback:** {{fallback_strategy}}
              
              **Monitoring:**
              - **Success Rate Target:** {{success_rate_sla}}
              - **Latency Target:** {{latency_sla}}
              - **Alert Conditions:** {{alert_rules}}
              
              **Integration Notes:** {{integration_considerations}}
              
  - id: core-workflows
    title: Core Workflows
    type: mermaid
    mermaid_type: sequence
    instruction: |
      Illustrate key system workflows using sequence diagrams:
      
      1. Identify critical user journeys from PRD
      2. Show component interactions including external APIs
      3. Include error handling paths
      4. Document async operations
      5. Show security checkpoints
      6. Include performance optimization points (caching, etc.)
      7. Create both high-level and detailed diagrams as needed
      
      VC-SYS Enhancement: Include timing information and SLA markers
    elicit: true
    
  - id: api-specifications
    title: API Specifications
    instruction: |
      VC-SYS Enhancement: Comprehensive API design for all interfaces
    sections:
      - id: rest-api-spec
        title: REST API Specification
        condition: Project includes REST API
        type: code
        language: yaml
        instruction: |
          Create comprehensive OpenAPI 3.0 specification:
          
          1. Include all endpoints from epics/stories
          2. Define request/response schemas based on data models
          3. Document authentication requirements
          4. Include example requests/responses
          5. Add rate limiting information
          6. Document error responses
          7. Include webhook specifications if applicable
        elicit: true
        template: |
          openapi: 3.0.0
          info:
            title: {{api_title}}
            version: {{api_version}}
            description: {{api_description}}
          servers:
            - url: {{server_url}}
              description: {{server_description}}
          security:
            - {{security_scheme}}: []
          paths:
            {{api_paths}}
            
      - id: graphql-spec
        title: GraphQL Specification
        condition: Project includes GraphQL
        type: code
        language: graphql
        instruction: Create GraphQL schema if applicable
        
      - id: grpc-spec
        title: gRPC Specification
        condition: Project includes gRPC
        type: code
        language: proto
        instruction: Create Protocol Buffer definitions if applicable
        
      - id: async-api-spec
        title: AsyncAPI Specification
        condition: Project includes async messaging
        type: code
        language: yaml
        instruction: Document async message contracts
        
  - id: database-design
    title: Database Design
    instruction: |
      Transform the conceptual data models into concrete database schemas:
      
      1. Use the database type(s) selected in Tech Stack
      2. Create schema definitions using appropriate notation
      3. Include indexes, constraints, and relationships
      4. Consider performance and scalability
      5. For NoSQL, show document structures
      6. Include partitioning/sharding strategy
      7. Document backup and recovery approach
      8. Define data migration strategy
      
      Present schema in format appropriate to database type (SQL DDL, JSON schema, etc.)
    elicit: true
    sections:
      - id: database-schema
        title: Database Schema
        type: code
        language: sql
        instruction: Provide complete DDL for relational databases
        
      - id: performance-optimization
        title: Database Performance Optimization
        template: |
          - **Indexing Strategy:** {{index_approach}}
          - **Query Optimization:** {{query_patterns}}
          - **Connection Pooling:** {{pool_config}}
          - **Caching Layer:** {{cache_strategy}}
          - **Read Replicas:** {{replica_strategy}}
          - **Partitioning:** {{partition_approach}}
          
      - id: data-migration
        title: Data Migration Strategy
        condition: Existing data needs migration
        template: |
          - **Migration Approach:** {{migration_strategy}}
          - **Data Validation:** {{validation_approach}}
          - **Rollback Plan:** {{rollback_strategy}}
          - **Downtime Requirements:** {{downtime_window}}
          
  - id: source-tree
    title: Source Tree
    type: code
    language: plaintext
    instruction: |
      Create a comprehensive project folder structure that reflects:
      
      1. The chosen repository structure (monorepo/polyrepo)
      2. The service architecture (monolith/microservices/serverless)
      3. The selected tech stack and languages
      4. Component organization from above
      5. Best practices for the chosen frameworks
      6. Clear separation of concerns
      7. Test organization strategy
      8. Infrastructure as code location
      9. Documentation structure
      10. CI/CD configuration location
      
      Adapt the structure based on project needs. For monorepos, show service separation. For serverless, show function organization. Include language-specific conventions.
    elicit: true
    examples:
      - |
        project-root/
        ├── .github/                    # GitHub Actions CI/CD
        │   ├── workflows/
        │   └── CODEOWNERS
        ├── .vscode/                    # VS Code configuration
        ├── packages/                   # Monorepo packages
        │   ├── api/                    # Backend API service
        │   │   ├── src/
        │   │   │   ├── modules/        # Feature modules
        │   │   │   ├── common/         # Shared code
        │   │   │   ├── config/         # Configuration
        │   │   │   └── main.ts
        │   │   ├── tests/
        │   │   │   ├── unit/
        │   │   │   ├── integration/
        │   │   │   └── e2e/
        │   │   └── package.json
        │   ├── web/                    # Frontend application
        │   ├── shared/                 # Shared utilities/types
        │   └── infrastructure/         # IaC definitions
        │       ├── terraform/
        │       ├── kubernetes/
        │       └── docker/
        ├── docs/                       # Documentation
        │   ├── architecture/
        │   ├── api/
        │   └── guides/
        ├── scripts/                    # Build and utility scripts
        ├── .env.example               # Environment variables template
        └── package.json               # Root package.json with workspaces
        
  - id: infrastructure-deployment
    title: Infrastructure and Deployment
    instruction: |
      Define comprehensive deployment architecture and practices:
      
      1. Use IaC tool selected in Tech Stack
      2. Choose deployment strategy appropriate for the architecture
      3. Define environments and promotion flow
      4. Establish rollback procedures
      5. Consider security, monitoring, and cost optimization
      6. Include disaster recovery planning
      7. Define SLA targets
      
      Get user input on deployment preferences and CI/CD tool choices.
    elicit: true
    sections:
      - id: infrastructure-as-code
        title: Infrastructure as Code
        template: |
          - **Tool:** {{iac_tool}} {{version}}
          - **Location:** `{{iac_directory}}`
          - **Approach:** {{iac_approach}}
          - **State Management:** {{state_backend}}
          - **Secret Management:** {{secret_approach}}
          
      - id: deployment-strategy
        title: Deployment Strategy
        template: |
          - **Strategy:** {{deployment_strategy}} (Blue-Green, Canary, Rolling, etc.)
          - **CI/CD Platform:** {{cicd_platform}}
          - **Pipeline Configuration:** `{{pipeline_config_location}}`
          - **Deployment Frequency:** {{deploy_frequency}}
          - **Automated Testing Gates:** {{test_gates}}
          
      - id: environments
        title: Environments
        repeatable: true
        template: |
          - **{{env_name}}:** {{env_purpose}}
            - Infrastructure: {{env_infrastructure}}
            - Data: {{env_data_strategy}}
            - Access: {{env_access_control}}
            - Monitoring: {{env_monitoring}}
            
      - id: promotion-flow
        title: Environment Promotion Flow
        type: mermaid
        mermaid_type: gitflow
        template: "{{promotion_flow_diagram}}"
        
      - id: rollback-strategy
        title: Rollback Strategy
        template: |
          - **Primary Method:** {{rollback_method}}
          - **Trigger Conditions:** {{rollback_triggers}}
          - **Recovery Time Objective:** {{rto}}
          - **Recovery Point Objective:** {{rpo}}
          - **Testing Frequency:** {{rollback_test_schedule}}
          
      - id: disaster-recovery
        title: Disaster Recovery Plan
        template: |
          - **Backup Strategy:** {{backup_approach}}
          - **Backup Frequency:** {{backup_schedule}}
          - **Recovery Testing:** {{dr_test_schedule}}
          - **Failover Process:** {{failover_procedure}}
          - **Communication Plan:** {{incident_communication}}
          
  - id: observability-architecture
    title: Observability Architecture
    instruction: |
      VC-SYS Enhancement: Comprehensive observability strategy
    sections:
      - id: monitoring-strategy
        title: Monitoring Strategy
        template: |
          - **Metrics Platform:** {{metrics_platform}}
          - **Log Aggregation:** {{logging_platform}}
          - **Distributed Tracing:** {{tracing_platform}}
          - **APM Solution:** {{apm_tool}}
          - **Synthetic Monitoring:** {{synthetic_monitoring}}
          
      - id: alerting-strategy
        title: Alerting Strategy
        template: |
          - **Alert Manager:** {{alert_platform}}
          - **Escalation Policy:** {{escalation_rules}}
          - **On-Call Rotation:** {{oncall_approach}}
          - **SLA Monitoring:** {{sla_monitoring}}
          - **Alert Fatigue Prevention:** {{alert_reduction_strategy}}
          
  - id: error-handling-strategy
    title: Error Handling Strategy
    instruction: |
      Define comprehensive error handling approach:
      
      1. Choose appropriate patterns for the language/framework from Tech Stack
      2. Define logging standards and tools
      3. Establish error categories and handling rules
      4. Consider observability and debugging needs
      5. Ensure security (no sensitive data in logs)
      6. Include error recovery strategies
      7. Define user experience for errors
      
      This section guides both AI and human developers in consistent error handling.
    elicit: true
    sections:
      - id: general-approach
        title: General Approach
        template: |
          - **Error Model:** {{error_model}}
          - **Exception Hierarchy:** {{exception_structure}}
          - **Error Propagation:** {{propagation_rules}}
          - **Recovery Strategy:** {{recovery_approach}}
          
      - id: logging-standards
        title: Logging Standards
        template: |
          - **Library:** {{logging_library}} {{version}}
          - **Format:** {{log_format}}
          - **Levels:** {{log_levels_definition}}
          - **Structured Logging:** {{structured_log_format}}
          - **Required Context:**
            - Correlation ID: {{correlation_id_format}}
            - Service Context: {{service_context}}
            - User Context: {{user_context_rules}}
            - Performance Metrics: {{performance_context}}
          - **Sensitive Data:** {{pii_handling_rules}}
          
      - id: error-patterns
        title: Error Handling Patterns
        sections:
          - id: external-api-errors
            title: External API Errors
            template: |
              - **Retry Policy:** {{retry_strategy}}
              - **Circuit Breaker:** {{circuit_breaker_config}}
              - **Timeout Configuration:** {{timeout_settings}}
              - **Error Translation:** {{error_mapping_rules}}
              - **Fallback Strategy:** {{fallback_approach}}
              - **Dead Letter Queue:** {{dlq_strategy}}
              
          - id: business-logic-errors
            title: Business Logic Errors
            template: |
              - **Custom Exceptions:** {{business_exception_types}}
              - **User-Facing Errors:** {{user_error_format}}
              - **Error Codes:** {{error_code_system}}
              - **Validation Errors:** {{validation_error_format}}
              - **Localization:** {{error_localization}}
              
          - id: data-consistency
            title: Data Consistency
            template: |
              - **Transaction Strategy:** {{transaction_approach}}
              - **Compensation Logic:** {{compensation_patterns}}
              - **Idempotency:** {{idempotency_approach}}
              - **Eventual Consistency:** {{consistency_handling}}
              - **Conflict Resolution:** {{conflict_strategy}}
              
  - id: coding-standards
    title: Coding Standards & Guidelines
    instruction: |
      These standards are MANDATORY for AI agents and human developers. Work with user to define critical rules needed for consistent, high-quality code:
      
      1. This section directly controls AI developer behavior
      2. Focus on project-specific conventions and patterns
      3. Include performance optimization guidelines
      4. Add security coding standards
      5. Standards will be extracted to separate file for dev agent use
      
      For each standard, get explicit user confirmation it's necessary.
    elicit: true
    agent-enforcement: strict
    sections:
      - id: core-standards
        title: Core Standards
        template: |
          - **Languages & Runtimes:** {{languages_and_versions}}
          - **Style & Linting:** {{linter_config}}
          - **Code Formatting:** {{formatter_config}}
          - **Test Organization:** {{test_file_convention}}
          - **Documentation Standards:** {{doc_requirements}}
          
      - id: naming-conventions
        title: Naming Conventions
        type: table
        columns: [Element, Convention, Example, Anti-pattern]
        instruction: Include all naming conventions with examples
        
      - id: critical-rules
        title: Critical Rules
        instruction: |
          List rules that ensure quality and prevent common mistakes:
          - "Never use console.log in production code - use logger"
          - "All API responses must use ApiResponse wrapper type"
          - "Database queries must use repository pattern, never direct ORM"
          - "All async operations must have timeout configuration"
          - "Environment variables must be validated at startup"
          - "All user inputs must be validated and sanitized"
          - "Use dependency injection for testability"
        repeatable: true
        template: |
          - **{{rule_name}}:** {{rule_description}}
            - Rationale: {{why_important}}
            - Example: {{good_example}}
            - Anti-pattern: {{bad_example}}
            
      - id: performance-guidelines
        title: Performance Guidelines
        instruction: |
          VC-SYS Enhancement: Performance-focused coding standards
        template: |
          - **Query Optimization:** {{query_guidelines}}
          - **Caching Strategy:** {{caching_rules}}
          - **Async Best Practices:** {{async_patterns}}
          - **Memory Management:** {{memory_guidelines}}
          - **Connection Management:** {{connection_rules}}
          
      - id: security-guidelines
        title: Security Coding Guidelines
        instruction: |
          VC-SYS Enhancement: Security-focused coding standards
        template: |
          - **Input Validation:** {{validation_rules}}
          - **Output Encoding:** {{encoding_rules}}
          - **Authentication Checks:** {{auth_patterns}}
          - **Cryptography Usage:** {{crypto_guidelines}}
          - **Secure Defaults:** {{secure_default_rules}}
          
      - id: language-specifics
        title: Language-Specific Guidelines
        condition: Critical language-specific rules needed
        sections:
          - id: language-rules
            title: "{{language_name}} Specifics"
            repeatable: true
            template: |
              - **{{rule_topic}}:** {{rule_detail}}
                - Example: {{code_example}}
                - Rationale: {{why_needed}}
                
  - id: test-strategy
    title: Test Strategy and Standards
    instruction: |
      Work with user to define comprehensive test strategy:
      
      1. Use test frameworks from Tech Stack
      2. Decide on TDD vs test-after approach
      3. Define test organization and naming
      4. Establish coverage goals with evidence
      5. Determine integration test infrastructure
      6. Plan for test data and external dependencies
      7. Include performance and security testing
      8. Define contract testing approach
      
      Note: This detailed section is for QA agent and team reference.
    elicit: true
    agent: qa
    sections:
      - id: testing-philosophy
        title: Testing Philosophy
        template: |
          - **Approach:** {{test_approach}} (TDD, BDD, etc.)
          - **Coverage Goals:** {{coverage_targets}} (with rationale)
          - **Test Pyramid:** {{test_distribution}}
          - **Quality Gates:** {{quality_thresholds}}
          - **Test Data Strategy:** {{test_data_approach}}
          
      - id: test-types
        title: Test Types and Organization
        sections:
          - id: unit-tests
            title: Unit Tests
            template: |
              - **Framework:** {{unit_test_framework}} {{version}}
              - **File Convention:** {{unit_test_naming}}
              - **Location:** {{unit_test_location}}
              - **Mocking Library:** {{mocking_library}}
              - **Coverage Requirement:** {{unit_coverage}}
              - **Execution Time Target:** {{unit_test_speed}}
              
              **AI Agent Requirements:**
              - Generate tests for all public methods
              - Cover edge cases and error conditions
              - Follow AAA pattern (Arrange, Act, Assert)
              - Mock all external dependencies
              - Include performance assertions where relevant
              - Test security constraints
              
          - id: integration-tests
            title: Integration Tests
            template: |
              - **Scope:** {{integration_scope}}
              - **Location:** {{integration_test_location}}
              - **Execution Time Target:** {{integration_test_speed}}
              - **Test Infrastructure:**
                - **{{dependency_name}}:** {{test_approach}} ({{test_tool}})
              
              **Test Isolation Strategy:**
              - Database: {{db_isolation}}
              - External Services: {{service_isolation}}
              - Message Queues: {{queue_isolation}}
              
            examples:
              - "**Database:** In-memory H2 for unit tests, Testcontainers PostgreSQL for integration"
              - "**Message Queue:** Embedded Kafka for tests"
              - "**External APIs:** WireMock for stubbing"
              
          - id: e2e-tests
            title: End-to-End Tests
            template: |
              - **Framework:** {{e2e_framework}} {{version}}
              - **Scope:** {{e2e_scope}}
              - **Environment:** {{e2e_environment}}
              - **Test Data:** {{e2e_data_strategy}}
              - **Execution Time Target:** {{e2e_test_speed}}
              - **Parallelization:** {{parallel_strategy}}
              
          - id: performance-tests
            title: Performance Tests
            template: |
              - **Tool:** {{perf_test_tool}}
              - **Scenarios:** {{perf_test_scenarios}}
              - **Success Criteria:** {{perf_success_metrics}}
              - **Execution Schedule:** {{perf_test_schedule}}
              
          - id: security-tests
            title: Security Tests
            template: |
              - **SAST Tool:** {{sast_tool}}
              - **DAST Tool:** {{dast_tool}}
              - **Dependency Scanning:** {{dep_scan_tool}}
              - **Container Scanning:** {{container_scan}}
              - **Penetration Testing:** {{pentest_schedule}}
              
          - id: contract-tests
            title: Contract Tests
            condition: Microservices or API consumers exist
            template: |
              - **Framework:** {{contract_framework}}
              - **Approach:** {{contract_approach}}
              - **Contract Storage:** {{contract_location}}
              - **Validation:** {{contract_validation}}
              
      - id: test-data-management
        title: Test Data Management
        template: |
          - **Strategy:** {{test_data_approach}}
          - **Fixtures:** {{fixture_location}}
          - **Factories:** {{factory_pattern}}
          - **Cleanup:** {{cleanup_strategy}}
          - **PII Handling:** {{pii_test_data}}
          - **Data Generation:** {{data_generation_tools}}
          
      - id: continuous-testing
        title: Continuous Testing
        template: |
          - **CI Integration:** {{ci_test_stages}}
          - **Test Parallelization:** {{parallel_approach}}
          - **Flaky Test Management:** {{flaky_test_strategy}}
          - **Test Result Reporting:** {{test_reporting}}
          - **Failure Analysis:** {{failure_analysis_approach}}
          
  - id: security-architecture
    title: Security Architecture
    instruction: |
      Define MANDATORY security requirements for AI and human developers:
      
      1. Focus on implementation-specific rules
      2. Reference security tools from Tech Stack
      3. Define clear patterns for common scenarios
      4. Include threat modeling results
      5. These rules directly impact code generation
      6. Work with user to ensure completeness without redundancy
    elicit: true
    agent: security
    evidence-required: true
    sections:
      - id: threat-model
        title: Threat Model
        instruction: |
          VC-SYS Enhancement: Document threat analysis
        template: |
          - **Assets to Protect:** {{critical_assets}}
          - **Threat Actors:** {{threat_actors}}
          - **Attack Vectors:** {{attack_vectors}}
          - **Risk Assessment:** {{risk_matrix}}
          - **Mitigation Strategies:** {{mitigations}}
          
      - id: input-validation
        title: Input Validation
        template: |
          - **Validation Library:** {{validation_library}}
          - **Validation Location:** {{where_to_validate}}
          - **Sanitization Approach:** {{sanitization_rules}}
          - **Required Rules:**
            - All external inputs MUST be validated
            - Validation at API boundary before processing
            - Whitelist approach preferred over blacklist
            - Type validation before business logic
            - Size limits on all inputs
            - SQL injection prevention via parameterized queries
            - XSS prevention via output encoding
            
      - id: auth-authorization
        title: Authentication & Authorization
        template: |
          - **Auth Method:** {{auth_implementation}}
          - **Session Management:** {{session_approach}}
          - **MFA Support:** {{mfa_implementation}}
          - **Authorization Model:** {{authz_model}} (RBAC, ABAC, etc.)
          - **Token Management:** {{token_strategy}}
          - **Required Patterns:**
            - {{auth_pattern_1}}
            - {{auth_pattern_2}}
          - **Password Policy:** {{password_requirements}}
          
      - id: secrets-management
        title: Secrets Management
        template: |
          - **Development:** {{dev_secrets_approach}}
          - **Production:** {{prod_secrets_service}}
          - **Rotation Policy:** {{secret_rotation}}
          - **Code Requirements:**
            - NEVER hardcode secrets
            - Access via configuration service only
            - No secrets in logs or error messages
            - Secrets never in version control
            - Use least privilege principle
            
      - id: api-security
        title: API Security
        template: |
          - **Rate Limiting:** {{rate_limit_implementation}}
          - **CORS Policy:** {{cors_configuration}}
          - **Security Headers:** {{required_headers}}
          - **HTTPS Enforcement:** {{https_approach}}
          - **API Versioning:** {{version_strategy}}
          - **Request Signing:** {{request_validation}}
          
      - id: data-protection
        title: Data Protection
        template: |
          - **Encryption at Rest:** {{encryption_at_rest}}
          - **Encryption in Transit:** {{encryption_in_transit}}
          - **Key Management:** {{key_management}}
          - **PII Handling:** {{pii_rules}}
          - **Data Masking:** {{masking_approach}}
          - **Logging Restrictions:** {{what_not_to_log}}
          - **Data Residency:** {{data_location_requirements}}
          - **Right to Erasure:** {{gdpr_deletion}}
          
      - id: dependency-security
        title: Dependency Security
        template: |
          - **Scanning Tool:** {{dependency_scanner}}
          - **Update Policy:** {{update_frequency}}
          - **Approval Process:** {{new_dep_process}}
          - **License Compliance:** {{license_checking}}
          - **Supply Chain Security:** {{supply_chain_approach}}
          
      - id: compliance-requirements
        title: Compliance Requirements
        condition: Regulatory compliance needed
        template: |
          - **Standards:** {{compliance_standards}} (GDPR, HIPAA, PCI, etc.)
          - **Audit Requirements:** {{audit_needs}}
          - **Data Retention:** {{retention_policies}}
          - **Reporting:** {{compliance_reporting}}
          
  - id: performance-architecture
    title: Performance Architecture
    instruction: |
      VC-SYS Enhancement: Define performance requirements and optimization strategies
    sections:
      - id: performance-requirements
        title: Performance Requirements
        template: |
          - **Response Time Targets:**
            - P50: {{p50_target}}
            - P95: {{p95_target}}
            - P99: {{p99_target}}
          - **Throughput:** {{throughput_target}}
          - **Concurrent Users:** {{concurrent_users}}
          - **Data Volume:** {{data_volume_expectations}}
          
      - id: optimization-strategies
        title: Optimization Strategies
        template: |
          - **Caching Strategy:**
            - Client Cache: {{client_cache}}
            - CDN: {{cdn_strategy}}
            - Application Cache: {{app_cache}}
            - Database Cache: {{db_cache}}
          - **Database Optimization:** {{db_optimization}}
          - **Code Optimization:** {{code_optimization}}
          - **Asset Optimization:** {{asset_optimization}}
          - **Network Optimization:** {{network_optimization}}
          
      - id: scalability-plan
        title: Scalability Plan
        template: |
          - **Horizontal Scaling:** {{horizontal_approach}}
          - **Vertical Scaling:** {{vertical_limits}}
          - **Auto-scaling Rules:** {{autoscale_config}}
          - **Load Balancing:** {{lb_strategy}}
          - **Database Scaling:** {{db_scaling}}
          - **Cache Scaling:** {{cache_scaling}}
          
  - id: quality-assurance
    title: Quality Assurance
    instruction: |
      VC-SYS Enhancement: Comprehensive quality strategy with evidence requirements
    agent: qa
    sections:
      - id: quality-metrics
        title: Quality Metrics
        template: |
          - **Code Quality:**
            - Complexity Limits: {{complexity_limits}}
            - Duplication Threshold: {{duplication_threshold}}
            - Technical Debt Ratio: {{debt_ratio}}
          - **Test Quality:**
            - Coverage Requirements: {{coverage_requirements}}
            - Test Execution Time: {{test_time_limits}}
            - Flaky Test Tolerance: {{flaky_tolerance}}
          - **Security Quality:**
            - Vulnerability SLA: {{vuln_sla}}
            - Security Score Target: {{security_score}}
            
      - id: review-process
        title: Code Review Process
        template: |
          - **Review Requirements:** {{review_rules}}
          - **Approval Requirements:** {{approval_rules}}
          - **Automated Checks:** {{automated_checks}}
          - **Review Checklist:** {{review_checklist}}
          
  - id: checklist-results
    title: Checklist Results Report
    instruction: |
      Before running the checklist, offer to output the full architecture document. Once user confirms, execute the architect-checklist and populate results here.
      
      VC-SYS Enhancement: Include evidence for all checklist items and track compliance percentage.
    validation: architect-checklist
    evidence-required: true
    
  - id: next-steps
    title: Next Steps
    instruction: |
      After completing the architecture:
      
      1. If project has UI components:
      - Use "Frontend Architecture Mode"
      - Provide this document as input
      
      2. For all projects:
      - Review with Product Owner and get approval
      - Begin story implementation with Dev agent
      - Set up infrastructure with DevOps agent
      - Configure monitoring with SRE practices
      
      3. Include specific prompts for next agents if needed
      
      4. VC-SYS Enhancements:
      - Generate implementation tasks for Task Management System
      - Create architecture validation tests
      - Set up architecture decision record (ADR) process
      - Configure architecture fitness functions
    sections:
      - id: architect-prompt
        title: Architect Prompt
        condition: Project has UI components
        instruction: |
          Create a comprehensive prompt to hand off to Architect for Frontend Architecture creation. Include:
          - Reference to this architecture document
          - Key UI requirements from PRD
          - Any frontend-specific decisions made here
          - Performance requirements for frontend
          - Security requirements for frontend
          - Request for detailed frontend architecture
          
      - id: implementation-tasks
        title: Implementation Tasks
        instruction: |
          VC-SYS Enhancement: Generate specific tasks for development team
        template: |
          **Infrastructure Tasks:**
          - {{infra_task_1}}
          - {{infra_task_2}}
          
          **Development Tasks:**
          - {{dev_task_1}}
          - {{dev_task_2}}
          
          **Security Tasks:**
          - {{security_task_1}}
          - {{security_task_2}}
          
          **Monitoring Tasks:**
          - {{monitoring_task_1}}
          - {{monitoring_task_2}}