diff --git a/.best-practices/cloud-architecture/ReadMe.md b/.best-practices/cloud-architecture/ReadMe.md new file mode 100644 index 0000000..86c303d --- /dev/null +++ b/.best-practices/cloud-architecture/ReadMe.md @@ -0,0 +1,51 @@ +# Cloud Architecture Best Practices + +## 1. Purpose + +Deliver scalable, resilient, and cost-effective solutions in cloud environments. + +## 2. Core Principles + +- Design for failure +- Automate everything +- Use managed services where possible +- Optimize for cost and performance + +## 3. Industry Standards & Frameworks + +- AWS Well-Architected Framework +- Azure Cloud Adoption Framework +- Google Cloud Architecture Framework + +## 4. Common Patterns + +- Multi-region deployments +- Hybrid cloud +- Event-driven serverless + +## 5. Anti-Patterns to Avoid + +- Lift-and-shift without modernization +- Over-provisioning resources +- Ignoring shared responsibility model + +## 6. Tooling & Ecosystem + +- Terraform, Bicep, Pulumi +- Kubernetes, Service Mesh +- Cloud-native monitoring tools + +## 7. Emerging Trends + +- FinOps +- Sustainability-aware workloads +- Cloud-native AI services + +## 8. Architecture Decision Guidance + +- Choose multi-cloud only if business/regulatory needs demand it. +- Balance managed services vs. portability. + +## 9. References + +- [Azure CAF](https://learn.microsoft.com/azure/cloud-adoption-framework/) diff --git a/.best-practices/data-analytics/ReadMe.md b/.best-practices/data-analytics/ReadMe.md new file mode 100644 index 0000000..364a281 --- /dev/null +++ b/.best-practices/data-analytics/ReadMe.md @@ -0,0 +1,51 @@ +# Data & Analytics Best Practices + +## 1. Purpose + +Enable data-driven decision-making and advanced analytics. + +## 2. Core Principles + +- Treat data as a product +- Ensure data quality and lineage +- Secure data at rest and in motion +- Enable self-service analytics + +## 3. Industry Standards & Frameworks + +- Data Mesh +- DAMA-DMBOK +- FAIR data principles + +## 4. Common Patterns + +- Data lakehouse +- Event streaming pipelines +- ELT with dbt + +## 5. Anti-Patterns to Avoid + +- Data silos +- ETL sprawl +- Ignoring governance + +## 6. Tooling & Ecosystem + +- Kafka, Pulsar +- Snowflake, BigQuery, Synapse +- dbt, Airflow + +## 7. Emerging Trends + +- Real-time analytics +- AI/ML integration +- Data contracts + +## 8. Architecture Decision Guidance + +- Use data mesh when scaling across domains. +- Balance central governance with federated ownership. + +## 9. References + +- [Data Mesh Principles](https://martinfowler.com/articles/data-mesh-principles.html) diff --git a/.best-practices/devops/ReadMe.md b/.best-practices/devops/ReadMe.md new file mode 100644 index 0000000..53935be --- /dev/null +++ b/.best-practices/devops/ReadMe.md @@ -0,0 +1,51 @@ +# DevOps & Platform Engineering Best Practices + +## 1. Purpose + +Enable rapid, reliable, and repeatable delivery of software. + +## 2. Core Principles + +- Everything as code +- Continuous feedback loops +- Shift-left testing and security +- Immutable infrastructure + +## 3. Industry Standards & Frameworks + +- CALMS model +- GitOps +- SRE principles + +## 4. Common Patterns + +- CI/CD pipelines +- Blue/green and canary deployments +- Infrastructure as Code + +## 5. Anti-Patterns to Avoid + +- Manual deployments +- Snowflake servers +- Over-reliance on scripts without version control + +## 6. Tooling & Ecosystem + +- GitHub Actions, Azure DevOps, Jenkins +- ArgoCD, Flux +- Prometheus, Grafana + +## 7. Emerging Trends + +- Platform engineering teams +- Internal developer platforms (IDPs) +- Policy-as-code + +## 8. Architecture Decision Guidance + +- Standardize pipelines across teams. +- Invest in developer experience (DX). + +## 9. References + +- [Google SRE Book](https://sre.google/books/) diff --git a/.best-practices/integration/ReadMe.md b/.best-practices/integration/ReadMe.md new file mode 100644 index 0000000..babfc31 --- /dev/null +++ b/.best-practices/integration/ReadMe.md @@ -0,0 +1,51 @@ +# Integration & APIs Best Practices + +## 1. Purpose + +Enable interoperability and composability across systems. + +## 2. Core Principles + +- API-first design +- Loose coupling +- Backward compatibility +- Contract-first development + +## 3. Industry Standards & Frameworks + +- OpenAPI/Swagger +- AsyncAPI +- GraphQL spec + +## 4. Common Patterns + +- API Gateway +- Event-driven integration +- CQRS + +## 5. Anti-Patterns to Avoid + +- Point-to-point spaghetti integrations +- Breaking API changes without versioning +- Overloading APIs with business logic + +## 6. Tooling & Ecosystem + +- Kong, Apigee, Azure API Management +- Kafka, RabbitMQ +- GraphQL servers + +## 7. Emerging Trends + +- API monetization +- Event mesh +- gRPC adoption + +## 8. Architecture Decision Guidance + +- Use REST for broad compatibility, gRPC for high-performance internal services. +- Favor async messaging for decoupling. + +## 9. References + +- [AsyncAPI Initiative](https://www.asyncapi.com/) diff --git a/.best-practices/observability/ReadMe.md b/.best-practices/observability/ReadMe.md new file mode 100644 index 0000000..23062a8 --- /dev/null +++ b/.best-practices/observability/ReadMe.md @@ -0,0 +1,50 @@ +# Observability Best Practices + +## 1. Purpose +Provide visibility into system health, performance, and reliability. + +## 2. Core Principles + +- Instrument everything +- Correlate logs, metrics, and traces +- Automate alerting and remediation +- Design for failure detection + +## 3. Industry Standards & Frameworks + +- OpenTelemetry +- SRE golden signals +- ITIL incident management + +## 4. Common Patterns + +- Centralized logging +- Distributed tracing +- Metrics dashboards + +## 5. Anti-Patterns to Avoid + +- Alert fatigue +- Logging without structure +- Monitoring only infrastructure, not business KPIs + +## 6. Tooling & Ecosystem + +- Prometheus, Grafana +- ELK/EFK stack +- Jaeger, Zipkin + +## 7. Emerging Trends + +- AIOps +- Continuous profiling +- Observability-as-code + +## 8. Architecture Decision Guidance + +- Define SLIs, SLOs, SLAs early. +- Balance observability depth with cost. + +## 9. References + +- [OpenTelemetry](https://opentelemetry.io/) diff --git a/.best-practices/radar.md b/.best-practices/radar.md new file mode 100644 index 0000000..8c5dfe9 --- /dev/null +++ b/.best-practices/radar.md @@ -0,0 +1,125 @@ +# Solution Architect Radar (2025 Q4) + +This radar provides a maturity view of industry best practices across specialties. +Use it to guide adoption, trials, and assessments, while avoiding outdated practices. + +--- + +## Quadrant View + +### ADOPT + +- **Software Architecture**: VBD, DDD, Clean/Hexagonal Architecture, ADRs +- **Security**: Zero Trust, OWASP Top 10, centralized secrets management +- **Cloud**: Managed services, IaC (Terraform/Bicep) +- **DevOps**: GitOps, CI/CD pipelines, immutable infrastructure +- **Data**: Lakehouse, ELT with dbt, event streaming +- **Integration**: API-first, OpenAPI/AsyncAPI, backward-compatible versioning +- **Observability**: OpenTelemetry, SRE golden signals + +### TRIAL + +- **Software Architecture**: Event Sourcing, CQRS +- **Security**: Confidential computing, automated threat modeling +- **Cloud**: Serverless-first, multi-cloud portability frameworks +- **DevOps**: Internal Developer Platforms (IDPs), policy-as-code +- **Data**: Data mesh, real-time analytics +- **Integration**: GraphQL, gRPC +- **Observability**: Observability-as-code, continuous profiling + +### ASSESS + +- **Software Architecture**: AI-assisted validation, WASM backends +- **Security**: Post-quantum cryptography, AI-driven anomaly detection +- **Cloud**: Sustainability-aware workload placement +- **DevOps**: AI-driven pipeline optimization +- **Data**: Data contracts, AI-native governance +- **Integration**: Event mesh, API monetization +- **Observability**: AIOps-driven remediation, business KPI observability + +### HOLD + +- **Software Architecture**: Big Ball of Mud, God classes +- **Security**: Hardcoded secrets, perimeter-only defenses +- **Cloud**: Lift-and-shift without modernization +- **DevOps**: Manual deployments, snowflake servers +- **Data**: ETL sprawl, unmanaged silos +- **Integration**: Point-to-point spaghetti integrations +- **Observability**: Infra-only monitoring, unstructured logs + +--- + +## Visual Radar (Mermaid) + +```mermaid +flowchart LR + subgraph Q1 [ADOPT] + QA1[Software Architecture: DDD, Clean/Hexagonal, ADRs] + QA2[Security: Zero Trust, OWASP Top 10, Secrets mgmt] + QA3[Cloud: Managed services, IaC] + QA4[DevOps: GitOps, CI/CD, Immutable infra] + QA5[Data: Lakehouse, ELT with dbt, Event streaming] + QA6[Integration: API-first, OpenAPI/AsyncAPI, Versioning] + QA7[Observability: OpenTelemetry, SRE golden signals] + end + + subgraph Q2 [TRIAL] + QT1[Software Architecture: Event Sourcing, CQRS] + QT2[Security: Confidential computing, Threat modeling automation] + QT3[Cloud: Serverless-first, Multi-cloud portability] + QT4[DevOps: IDPs, Policy-as-code] + QT5[Data: Data mesh, Real-time analytics] + QT6[Integration: GraphQL, gRPC] + QT7[Observability: Observability-as-code, Continuous profiling] + end + + subgraph Q3 [ASSESS] + QS1[Software Architecture: AI-assisted validation, WASM backends] + QS2[Security: Post-quantum crypto, AI anomaly detection] + QS3[Cloud: Sustainability-aware placement] + QS4[DevOps: AI-driven pipeline optimization] + QS5[Data: Data contracts, AI-native governance] + QS6[Integration: Event mesh, API monetization] + QS7[Observability: AIOps remediation, Business KPI obs] + end + + subgraph Q4 [HOLD] + QH1[Software Architecture: Big Ball of Mud, God classes] + QH2[Security: Hardcoded secrets, Perimeter-only] + QH3[Cloud: Lift-and-shift w/o modernization] + QH4[DevOps: Manual deployments, Snowflake servers] + QH5[Data: ETL sprawl, Unmanaged silos] + QH6[Integration: Point-to-point spaghetti, Breaking changes] + QH7[Observability: Infra-only metrics, Unstructured logs] + end + + classDef adopt fill=#b7f5c7,stroke=#2f7,stroke-width=1px,color=#000; + classDef trial fill=#cbe8ff,stroke=#39f,stroke-width=1px,color=#000; + classDef assess fill=#fff1a8,stroke=#fc3,stroke-width=1px,color=#000; + classDef hold fill=#ffc2c2,stroke=#f55,stroke-width=1px,color=#000; + + class Q1 adopt; + class Q2 trial; + class Q3 assess; + class Q4 hold; +``` + +--- + +## Related Governance Docs + +- [Branching Strategy Playbook](branching-strategy.md) +- [Quarterly Radar Review Checklist](quarterly-radar-review.md) +- [ADR Index](../architecture-decision-records/index.md) + +## Capsules + +Each specialty has a dedicated capsule with detailed best practices: + +- [Software Architecture](./software-architecture/README.md) +- [Security](./security/README.md) +- [Cloud Architecture](./cloud-architecture/README.md) +- [DevOps & Platform Engineering](./devops/README.md) +- [Data & Analytics](./data-analytics/README.md) +- [Integration & APIs](./integration/README.md) +- [Observability](./observability/README.md) diff --git a/.best-practices/security/ReadMe.md b/.best-practices/security/ReadMe.md new file mode 100644 index 0000000..79e5e3a --- /dev/null +++ b/.best-practices/security/ReadMe.md @@ -0,0 +1,51 @@ +# Security Best Practices + +## 1. Purpose + +Protect confidentiality, integrity, and availability of systems. + +## 2. Core Principles + +- Zero Trust by default +- Defense in depth +- Least privilege access +- Encrypt everywhere + +## 3. Industry Standards & Frameworks + +- OWASP Top 10 +- NIST Cybersecurity Framework +- ISO 27001 + +## 4. Common Patterns + +- Centralized secrets management +- API Gateway with JWT validation +- Network segmentation + +## 5. Anti-Patterns to Avoid + +- Hardcoded secrets +- Flat networks +- Security as an afterthought + +## 6. Tooling & Ecosystem + +- Azure Key Vault, AWS KMS +- SAST/DAST tools +- SIEM platforms + +## 7. Emerging Trends + +- Confidential computing +- Post-quantum cryptography +- AI-driven threat detection + +## 8. Architecture Decision Guidance + +- Engage security architects for regulated workloads. +- Automate security checks in CI/CD. + +## 9. References + +- [OWASP Foundation](https://owasp.org) diff --git a/.best-practices/software-architecture/ReadMe.md b/.best-practices/software-architecture/ReadMe.md new file mode 100644 index 0000000..e860465 --- /dev/null +++ b/.best-practices/software-architecture/ReadMe.md @@ -0,0 +1,52 @@ +# Software Architecture Best Practices + +## 1. Purpose + +Provide scalable, maintainable, and evolvable systems that align with business goals. + +## 2. Core Principles + +- Favor modularity and separation of concerns. +- Design for change (volatility-based decomposition). +- Prefer composition over inheritance. +- Document decisions with ADRs. + +## 3. Industry Standards & Frameworks + +- Domain-Driven Design (DDD) +- TOGAF +- C4 Model for architecture diagrams + +## 4. Common Patterns + +- Microservices vs. modular monolith +- Hexagonal / Clean Architecture +- Event-driven systems + +## 5. Anti-Patterns to Avoid + +- Big Ball of Mud +- God classes +- Over-engineering with unnecessary abstractions + +## 6. Tooling & Ecosystem + +- .NET, Java Spring, Node.js frameworks +- Architecture decision record (ADR) tooling +- Static analysis tools + +## 7. Emerging Trends + +- Serverless-first architectures +- AI-assisted design validation +- Event mesh and data mesh convergence + +## 8. Architecture Decision Guidance + +- Use microservices only when independent scaling and deployment are required. +- Involve specialists for distributed systems complexity. + +## 9. References + +- [C4 Model](https://c4model.com) +- [DDD Reference](https://domainlanguage.com/ddd/) diff --git a/.best-practices/software-architecture/volatility-based-decomposition.md b/.best-practices/software-architecture/volatility-based-decomposition.md new file mode 100644 index 0000000..1c56779 --- /dev/null +++ b/.best-practices/software-architecture/volatility-based-decomposition.md @@ -0,0 +1,438 @@ +# Volatility-Based Decomposition + +## 1. Purpose + +Organize software components based on their rate of change to minimize ripple effects, improve maintainability, and enable independent evolution of system parts. + +## 2. Core Principle + +**Separate components that change for different reasons or at different rates.** + +Components with similar volatility characteristics should be grouped together, while components with different volatility rates should be isolated from each other through stable interfaces. + +## 3. Volatility Categories + +### High Volatility Components +**Characteristics:** +- Change frequently (weekly/monthly) +- Business rules and policies +- UI/UX implementations +- Marketing and promotional logic +- A/B testing features +- Regulatory compliance rules + +**Examples:** +- Pricing algorithms +- Discount calculation rules +- User interface themes +- Campaign management logic +- Feature flags and toggles + +### Medium Volatility Components +**Characteristics:** +- Change periodically (quarterly/semi-annually) +- Application services and workflows +- Integration adapters +- Reporting and analytics +- Configuration management + +**Examples:** +- Order processing workflows +- Payment integration services +- Notification delivery systems +- Report generation engines +- Data transformation pipelines + +### Low Volatility Components +**Characteristics:** +- Rarely change (annually or less) +- Core infrastructure +- Framework libraries +- Data access patterns +- Security primitives +- Logging and monitoring foundations + +**Examples:** +- Database connection pooling +- Authentication/authorization infrastructure +- Caching mechanisms +- Message queue abstractions +- Logging frameworks + +## 4. Decomposition Strategies + +### Strategy 1: Layered Isolation +``` +┌─────────────────────────────────────┐ +│ High Volatility Layer │ ← Business Rules +│ (Isolated, Frequent Changes) │ +├─────────────────────────────────────┤ +│ Stable Interfaces │ ← Contracts +├─────────────────────────────────────┤ +│ Medium Volatility Layer │ ← Application Services +│ (Moderate, Predictable Changes) │ +├─────────────────────────────────────┤ +│ Stable Interfaces │ ← Contracts +├─────────────────────────────────────┤ +│ Low Volatility Layer │ ← Infrastructure +│ (Stable, Rare Changes) │ +└─────────────────────────────────────┘ +``` + +### Strategy 2: Plugin Architecture +- Core system (low volatility) +- Plugin interfaces (stable contracts) +- Plugins (high volatility business logic) + +### Strategy 3: Rules Engine Pattern +- Rules engine (low volatility) +- Rule definitions (high volatility) +- Rule execution context (medium volatility) + +### Strategy 4: Configuration-Driven +- Application framework (low volatility) +- Configuration schema (medium volatility) +- Configuration values (high volatility) + +## 5. Implementation Patterns + +### Pattern 1: Dependency Inversion +```csharp +// Low volatility - Stable abstraction +namespace Core.Abstractions; + +public interface IPricingStrategy +{ + decimal Calculate(Order order); +} + +// High volatility - Business rule implementation +namespace Business.Pricing; + +public class SeasonalPricingStrategy : IPricingStrategy +{ + public decimal Calculate(Order order) + { + // Seasonal rules change frequently + return order.Season == Season.Holiday + ? order.BasePrice * 0.85m + : order.BasePrice; + } +} + +// Medium volatility - Application service +namespace Application.Services; + +public class OrderService(IPricingStrategy pricingStrategy) +{ + public async Task CalculateTotalAsync(Order order) + { + return pricingStrategy.Calculate(order); + } +} +``` + +### Pattern 2: Strategy Pattern with Registry +```csharp +// Low volatility - Registry infrastructure +namespace Core.Infrastructure; + +public class StrategyRegistry +{ + private readonly Dictionary strategies = new(); + + public void Register(string key, TStrategy strategy) => + strategies[key] = strategy; + + public TStrategy Get(string key) => + strategies.TryGetValue(key, out var strategy) + ? strategy + : throw new KeyNotFoundException($"Strategy '{key}' not found"); +} + +// High volatility - Strategy implementations +namespace Business.Rules; + +public class PremiumDiscountStrategy : IDiscountStrategy +{ + public decimal Apply(decimal amount) => amount * 0.15m; +} + +public class StandardDiscountStrategy : IDiscountStrategy +{ + public decimal Apply(decimal amount) => amount * 0.10m; +} +``` + +### Pattern 3: External Configuration +```csharp +// Low volatility - Configuration loader +namespace Core.Configuration; + +public class RulesConfigurationLoader +{ + public async Task LoadAsync(string source) + { + // Stable loading mechanism + var json = await File.ReadAllTextAsync(source); + return JsonSerializer.Deserialize(json)!; + } +} + +// High volatility - Configuration content (external JSON/YAML) +// { +// "discountRules": [ +// { "customerType": "Premium", "percentage": 15 }, +// { "customerType": "Standard", "percentage": 10 } +// ] +// } +``` + +## 6. Dependency Management + +### Dependency Direction Rule +**High volatility → Medium volatility → Low volatility** + +- High volatility components depend on medium/low volatility abstractions +- Medium volatility components depend on low volatility abstractions +- Low volatility components have minimal dependencies + +### Anti-Pattern: Inverted Dependencies +```csharp +// ❌ BAD: Low volatility depending on high volatility +namespace Core.Infrastructure; + +public class DatabaseContext +{ + // Infrastructure depending on business rules - BAD! + public void ApplyDiscount(Order order, PremiumDiscountStrategy strategy) { } +} + +// ✅ GOOD: Low volatility depends on stable abstraction +namespace Core.Infrastructure; + +public class DatabaseContext +{ + // Infrastructure depending on stable interface - GOOD! + public void ApplyDiscount(Order order, IDiscountStrategy strategy) { } +} +``` + +## 7. Testing Strategies + +### High Volatility Components +- **Extensive unit tests** (frequent changes require quick feedback) +- **Property-based testing** for business rules +- **A/B testing** in production +- **Feature flag** testing + +### Medium Volatility Components +- **Integration tests** (verify component interactions) +- **Contract tests** (ensure interface stability) +- **End-to-end tests** for critical workflows + +### Low Volatility Components +- **Minimal unit tests** (focus on edge cases) +- **Performance tests** (stability is key) +- **Security tests** (infrastructure security) + +## 8. Versioning and Release Strategies + +### High Volatility +- Frequent deployments (daily/weekly) +- Feature flags for gradual rollout +- Independent versioning +- Hotfix-friendly architecture + +### Medium Volatility +- Regular release cycles (sprint-based) +- API versioning +- Backward compatibility windows +- Deprecation notices + +### Low Volatility +- Infrequent updates (quarterly/annually) +- Major version changes only +- Long-term support (LTS) versions +- Extensive migration guides + +## 9. Organizational Alignment + +### Team Structure +- **High Volatility Teams**: Product-focused, domain experts, fast iteration +- **Medium Volatility Teams**: Application developers, cross-functional +- **Low Volatility Teams**: Platform engineers, infrastructure specialists + +### Ownership Model +- High volatility: Product teams own and evolve rapidly +- Medium volatility: Shared ownership with platform teams +- Low volatility: Centralized platform/infrastructure teams + +## 10. Real-World Examples + +### E-Commerce System +``` +High Volatility: +- Promotional campaigns +- Pricing rules +- Recommendation algorithms +- UI themes and layouts + +Medium Volatility: +- Checkout workflow +- Payment gateway integration +- Order fulfillment process +- Email notification templates + +Low Volatility: +- Database connection pooling +- Authentication framework +- Logging infrastructure +- Cache abstraction layer +``` + +### Financial Trading Platform +``` +High Volatility: +- Trading strategies +- Risk assessment rules +- Market data feeds +- Regulatory compliance checks + +Medium Volatility: +- Order execution engine +- Portfolio management service +- Reporting and analytics +- Client notification system + +Low Volatility: +- Message queue infrastructure +- Database sharding logic +- Security and encryption +- Audit logging framework +``` + +## 11. Metrics and Indicators + +### Change Frequency Metrics +- **Commits per month** per component +- **Deployment frequency** per service +- **Feature flag toggles** per module + +### Stability Metrics +- **Time between changes** (longer = more stable) +- **Breaking changes count** (fewer = more stable) +- **Dependency updates** (fewer = more stable) + +### Impact Metrics +- **Blast radius** of changes (smaller = better isolation) +- **Ripple effect** across components (less = better decomposition) +- **Hotfix frequency** (fewer = better stability) + +## 12. Anti-Patterns to Avoid + +### Anti-Pattern 1: Mixed Volatility +```csharp +// ❌ BAD: High and low volatility mixed +public class OrderProcessor +{ + // Low volatility - infrastructure + private readonly IDbConnection connection; + + // High volatility - business rule + private decimal CalculateSeasonalDiscount(Order order) + { + return order.Season == Season.Holiday ? 0.20m : 0.0m; + } + + // Medium volatility - workflow + public async Task ProcessAsync(Order order) { } +} +``` + +### Anti-Pattern 2: God Component +A single component that handles all volatility levels becomes a bottleneck for change. + +### Anti-Pattern 3: Premature Abstraction +Creating complex abstraction layers before understanding actual volatility patterns. + +### Anti-Pattern 4: Volatility Inversion +High volatility components providing interfaces to low volatility components. + +## 13. Migration Strategies + +### Identify Volatility +1. Analyze version control history (commit frequency) +2. Track change requests and feature updates +3. Review deployment frequency +4. Measure time-to-production for changes + +### Refactor Incrementally +1. Extract high volatility code first +2. Create stable interfaces +3. Move to plugin/strategy pattern +4. Externalize configuration + +### Validate Decomposition +1. Measure deployment frequency improvement +2. Track reduction in cross-component changes +3. Monitor time-to-market for new features +4. Assess developer productivity + +## 14. Best Practices + +1. **Start with observation**: Track change frequency before decomposing +2. **Use stable interfaces**: Abstract volatile implementations behind contracts +3. **Version independently**: High volatility components need independent versioning +4. **Test appropriately**: Match testing strategy to volatility level +5. **Document volatility**: Make expected change rates explicit +6. **Review regularly**: Volatility patterns change over time +7. **Align teams**: Organize teams around volatility levels +8. **Automate deployment**: High volatility requires automation + +## 15. References + +- **Component Design Principles** (Uncle Bob Martin) +- **Domain-Driven Design** (Eric Evans) - Strategic design patterns +- **Building Evolutionary Architectures** (Ford, Parsons, Kua) +- **Software Architecture: The Hard Parts** (Ford, Richards, Sadalage, Dehghani) +- **Accelerate** (Forsgren, Humble, Kim) - Deployment frequency metrics + +## 16. Decision Framework + +### When to Apply Volatility-Based Decomposition + +**Good Fit:** +- Systems with frequent business rule changes +- Regulatory environments requiring rapid updates +- A/B testing and experimentation-heavy applications +- Multi-tenant systems with custom business logic +- Long-lived systems (5+ years expected lifespan) + +**Poor Fit:** +- Small applications with uniform change rates +- Prototypes and proof-of-concepts +- Systems with purely technical volatility (no business rule changes) +- Applications with < 2 years expected lifespan + +### Decision Checklist + +- [ ] Have we measured actual change frequency? +- [ ] Are there clear volatility boundaries? +- [ ] Do we have organizational buy-in for separate team ownership? +- [ ] Can we maintain stable interfaces between layers? +- [ ] Will the benefits outweigh the additional complexity? +- [ ] Do we have appropriate testing strategies for each layer? +- [ ] Can we deploy components independently? + +## 17. Conclusion + +Volatility-based decomposition is a powerful architectural pattern that aligns system structure with the reality of change. By organizing code based on its rate of change rather than purely functional boundaries, teams can achieve: + +- **Faster time-to-market** for high-volatility features +- **Reduced risk** when changing business rules +- **Better team autonomy** through clear ownership +- **Improved system stability** through isolation +- **Lower maintenance costs** over time + +Success requires commitment to measuring change, maintaining stable interfaces, and continuously refining the decomposition as the system evolves. diff --git a/.best-practices/templates/ReadMe.md b/.best-practices/templates/ReadMe.md new file mode 100644 index 0000000..9b48e18 --- /dev/null +++ b/.best-practices/templates/ReadMe.md @@ -0,0 +1,46 @@ +# [Specialty Name] Best Practices + +## 1. Purpose + +- Why this specialty matters in solution architecture. +- Key risks if ignored. + +## 2. Core Principles + +- List 3–5 guiding principles (e.g., "Prefer composition over inheritance" for software design, or "Encrypt data in transit and at rest" for security). + +## 3. Industry Standards & Frameworks + +- Relevant standards, frameworks, or certifications (e.g., OWASP Top 10, TOGAF, ITIL, ISO 27001). +- Note if there are cloud-provider reference architectures (AWS Well-Architected, Azure CAF, GCP Architecture Framework). + +## 4. Common Patterns + +- Typical design or implementation patterns used in this specialty. +- Example: For **Integration**, list "API Gateway, Event-Driven, CQRS". + +## 5. Anti-Patterns to Avoid + +- Known pitfalls or outdated practices. +- Example: For **DevOps**, "Snowflake servers, manual deployments". + +## 6. Tooling & Ecosystem + +- Widely adopted tools, libraries, or platforms. +- Example: For **Data Engineering**, "dbt, Airflow, Kafka". + +## 7. Emerging Trends + +- What’s changing in the next 2–3 years. +- Example: For **Security**, "Shift-left security, confidential computing". + +## 8. Architecture Decision Guidance + +- When to involve a specialist. +- Key trade-offs to consider. +- Example: "If latency <10ms is required, consider edge computing vs. centralized cloud." + +## 9. References + +- Authoritative links (standards bodies, cloud providers, industry groups). +- Keep lightweight but credible. diff --git a/.copilot/design-patterns.md b/.copilot/design-patterns.md new file mode 100644 index 0000000..2227d38 --- /dev/null +++ b/.copilot/design-patterns.md @@ -0,0 +1,59 @@ +# Copilot Instructions: C# Design Patterns + +## Purpose + +Ensure generated C# design pattern examples are modern, reproducible, and educational. + +## Guidelines + +- Use C# 12 / .NET 8+ syntax, forward-compatible with .NET 10. +- Show **intent**, **structure**, **code**, **usage**, and **notes**. +- Prefer interfaces, records, async/await. +- Avoid outdated constructs (ArrayList, Task.Result). +- Provide unit-testable examples. + +## Categories + +- **Creational**: Factory, Builder, Singleton, Prototype +- **Structural**: Adapter, Decorator, Facade, Proxy +- **Behavioral**: Strategy, Observer, Mediator, Command, State + +## Example Output Format + +**Intent**: One-sentence purpose. +**Structure**: Key classes/interfaces. +**Code**: Minimal compilable example. +**Usage**: Short demo snippet. +**Notes**: Pitfalls, modern alternatives. + +## Example: Strategy Pattern + +```csharp +public interface ISortingStrategy +{ + Task> SortAsync(IEnumerable data); +} + +public class QuickSortStrategy : ISortingStrategy +{ + public Task> SortAsync(IEnumerable data) => + Task.FromResult(data.OrderBy(x => x)); +} + +public class Sorter +{ + private readonly ISortingStrategy _strategy; + public Sorter(ISortingStrategy strategy) => _strategy = strategy; + public Task> SortAsync(IEnumerable data) => _strategy.SortAsync(data); +} + +//Usage + +var sorter = new Sorter(new QuickSortStrategy()); +var result = await sorter.SortAsync(new[] { 5, 2, 9 }); +``` + +## Notes + +- Prefer DI for strategy injection. +- LINQ covers many cases, but Strategy is useful for pluggable algorithms. diff --git a/.copilot/repo-standards.md b/.copilot/repo-standards.md new file mode 100644 index 0000000..472629e --- /dev/null +++ b/.copilot/repo-standards.md @@ -0,0 +1,111 @@ +# Copilot Instructions: Repository Standards + +## Purpose + +Ensure that all generated code, documentation, and automation in this repository: + +- Remains **clean, consistent, and maintainable**. +- Supports **isolated, reproducible development environments**. +- Aligns with **industry best practices** and our **Solution Architect Radar**. +- Provides a **smooth onboarding experience** for collaborators. + +--- + +## General Repo Hygiene + +- Always respect `.copilotignore` and `.editorconfig` rules. +- Follow **conventional commit messages** (`feat:`, `fix:`, `docs:`, `chore:`). +- Keep PRs small, focused, and linked to an ADR or issue. +- Avoid committing secrets, credentials, or machine-specific configs. + +--- + +## Project Structure + +- **Source code** lives under `/src/`. +- **Tests** live under `/tests/` with mirrored structure. +- **Docs** live under `/docs/` (onboarding, ADRs, contributing). +- **Best practices** live under `/best-practices/` (capsules + radar). +- **Copilot instructions** live under `/.copilot/`. + +--- + +## Development Environments + +- Prefer **isolated, reproducible setups**: + - WSL2, Docker, Dev Containers, or VMs. + - No global dependencies—use local manifests (`global.json`, `requirements.txt`, `package.json`). +- Scripts must be **idempotent** and **cross-platform** where possible. +- Document environment setup in `/docs/onboarding.md`. + +--- + +## Coding Standards + +- Follow **.editorconfig** for formatting. +- Enforce **linting and static analysis** (e.g., Roslyn analyzers, ESLint). +- Write **unit tests** for new features; aim for meaningful coverage. +- Use **dependency injection** and avoid hard-coded values. +- Prefer **composition over inheritance**. + +--- + +## Documentation Standards + +- Every module/service must have a `readme.md` with: + - Purpose + - Setup instructions + - Example usage +- Architecture decisions must be captured as **ADRs** in `/docs/architecture-decision-records/`. +- Best practices must be modularized into **capsules** under `/best-practices/`. + +--- + +## CI/CD Standards + +- All code must pass: + - Build + - Linting + - Unit tests +- Use **branch protection rules** (no direct commits to `main`). +- Automate deployments with **GitOps or pipelines**. +- Include **security scanning** (SAST/DAST, dependency checks). + +--- + +## Collaboration Standards + +- Use **feature branches** (`feature/xyz`), **bugfix branches** (`fix/xyz`). +- Require **code reviews** before merging. +- Encourage **pairing/mobbing** for complex changes. +- Keep discussions and decisions documented (issues, ADRs, or capsules). + +--- + +## Copilot Guidance + +When generating code or docs: + +- Respect repo structure and standards above. +- Prefer **modern, maintainable solutions** over hacks. +- Provide **contextual explanations** (why, not just how). +- Suggest **tests and documentation** alongside code. +- Align examples with **current .NET/C# versions** and **Solution Architect Radar** maturity levels. + +--- + +## Anti-Patterns to Avoid + +- Committing machine-specific configs (e.g., `.vs/`, `.idea/`, `bin/`, `obj/`). +- Hardcoding secrets or environment-specific values. +- Copy-pasting without attribution or context. +- Over-engineering abstractions without clear value. +- Ignoring repo standards in generated outputs. + +--- + +## References + +- [Conventional Commits](https://www.conventionalcommits.org/) +- [EditorConfig](https://editorconfig.org/) +- [ADR GitHub Repo](https://github.com/joelparkerhenderson/architecture_decision_record) diff --git a/.editorconfig b/.editorconfig new file mode 100644 index 0000000..3868bd7 --- /dev/null +++ b/.editorconfig @@ -0,0 +1,378 @@ +root = true + +# All files +[*] +indent_style = space + +# Xml files +[*.xml] +indent_size = 2 + +# C# files +[*.cs] + +#### Core EditorConfig Options #### + +# Indentation and spacing +indent_size = 4 +tab_width = 4 + +# New line preferences +insert_final_newline = false + +#### .NET Coding Conventions #### +[*.{cs,vb}] + +# Organize usings +dotnet_separate_import_directive_groups = true +dotnet_sort_system_directives_first = true +file_header_template = unset + +# this. and Me. preferences +dotnet_style_qualification_for_event = false:silent +dotnet_style_qualification_for_field = false:silent +dotnet_style_qualification_for_method = false:silent +dotnet_style_qualification_for_property = false:silent + +# Language keywords vs BCL types preferences +dotnet_style_predefined_type_for_locals_parameters_members = true:silent +dotnet_style_predefined_type_for_member_access = true:silent + +# Parentheses preferences +dotnet_style_parentheses_in_arithmetic_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_binary_operators = always_for_clarity:silent +dotnet_style_parentheses_in_other_operators = never_if_unnecessary:silent +dotnet_style_parentheses_in_relational_binary_operators = always_for_clarity:silent + +# Modifier preferences +dotnet_style_require_accessibility_modifiers = for_non_interface_members:silent + +# Expression-level preferences +dotnet_style_coalesce_expression = true:suggestion +dotnet_style_collection_initializer = true:suggestion +dotnet_style_explicit_tuple_names = true:suggestion +dotnet_style_namespace_match_folder = true:suggestion +dotnet_style_null_propagation = true:suggestion +dotnet_style_object_initializer = true:suggestion +dotnet_style_operator_placement_when_wrapping = beginning_of_line +dotnet_style_prefer_auto_properties = true:suggestion +dotnet_style_prefer_collection_expression = when_types_loosely_match:suggestion +dotnet_style_prefer_compound_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_assignment = true:suggestion +dotnet_style_prefer_conditional_expression_over_return = true:suggestion +dotnet_style_prefer_foreach_explicit_cast_in_source = when_strongly_typed:suggestion +dotnet_style_prefer_inferred_anonymous_type_member_names = true:suggestion +dotnet_style_prefer_inferred_tuple_names = true:suggestion +dotnet_style_prefer_is_null_check_over_reference_equality_method = true:suggestion +dotnet_style_prefer_simplified_boolean_expressions = true:suggestion +dotnet_style_prefer_simplified_interpolation = true:suggestion + +# Field preferences +dotnet_style_readonly_field = true:warning + +# Parameter preferences +dotnet_code_quality_unused_parameters = all:suggestion + +# Suppression preferences +dotnet_remove_unnecessary_suppression_exclusions = none + +#### C# Coding Conventions #### +[*.cs] + +# var preferences +csharp_style_var_elsewhere = false:silent +csharp_style_var_for_built_in_types = false:silent +csharp_style_var_when_type_is_apparent = false:silent + +# Expression-bodied members +csharp_style_expression_bodied_accessors = true:silent +csharp_style_expression_bodied_constructors = false:silent +csharp_style_expression_bodied_indexers = true:silent +csharp_style_expression_bodied_lambdas = true:suggestion +csharp_style_expression_bodied_local_functions = false:silent +csharp_style_expression_bodied_methods = false:silent +csharp_style_expression_bodied_operators = false:silent +csharp_style_expression_bodied_properties = true:silent + +# Pattern matching preferences +csharp_style_pattern_matching_over_as_with_null_check = true:suggestion +csharp_style_pattern_matching_over_is_with_cast_check = true:suggestion +csharp_style_prefer_extended_property_pattern = true:suggestion +csharp_style_prefer_not_pattern = true:suggestion +csharp_style_prefer_pattern_matching = true:silent +csharp_style_prefer_switch_expression = true:suggestion + +# Null-checking preferences +csharp_style_conditional_delegate_call = true:suggestion + +# Modifier preferences +csharp_prefer_static_anonymous_function = true:suggestion +csharp_prefer_static_local_function = true:warning +csharp_preferred_modifier_order = public,private,protected,internal,file,const,static,extern,new,virtual,abstract,sealed,override,readonly,unsafe,required,volatile,async:suggestion +csharp_style_prefer_readonly_struct = true:suggestion +csharp_style_prefer_readonly_struct_member = true:suggestion + +# Code-block preferences +csharp_prefer_braces = true:silent +csharp_prefer_simple_using_statement = true:suggestion +csharp_style_namespace_declarations = file_scoped:suggestion +csharp_style_prefer_method_group_conversion = true:silent +csharp_style_prefer_primary_constructors = true:suggestion +csharp_style_prefer_top_level_statements = true:silent + +# Expression-level preferences +csharp_prefer_simple_default_expression = true:suggestion +csharp_style_deconstructed_variable_declaration = true:suggestion +csharp_style_implicit_object_creation_when_type_is_apparent = true:suggestion +csharp_style_inlined_variable_declaration = true:suggestion +csharp_style_prefer_index_operator = true:suggestion +csharp_style_prefer_local_over_anonymous_function = true:suggestion +csharp_style_prefer_null_check_over_type_check = true:suggestion +csharp_style_prefer_range_operator = true:suggestion +csharp_style_prefer_tuple_swap = true:suggestion +csharp_style_prefer_utf8_string_literals = true:suggestion +csharp_style_throw_expression = true:suggestion +csharp_style_unused_value_assignment_preference = discard_variable:suggestion +csharp_style_unused_value_expression_statement_preference = discard_variable:silent + +# 'using' directive preferences +csharp_using_directive_placement = outside_namespace:silent + +#### C# Formatting Rules #### + +# New line preferences +csharp_new_line_before_catch = true +csharp_new_line_before_else = true +csharp_new_line_before_finally = true +csharp_new_line_before_members_in_anonymous_types = true +csharp_new_line_before_members_in_object_initializers = true +csharp_new_line_before_open_brace = all +csharp_new_line_between_query_expression_clauses = true + +# Indentation preferences +csharp_indent_block_contents = true +csharp_indent_braces = false +csharp_indent_case_contents = true +csharp_indent_case_contents_when_block = true +csharp_indent_labels = one_less_than_current +csharp_indent_switch_labels = true + +# Space preferences +csharp_space_after_cast = false +csharp_space_after_colon_in_inheritance_clause = true +csharp_space_after_comma = true +csharp_space_after_dot = false +csharp_space_after_keywords_in_control_flow_statements = true +csharp_space_after_semicolon_in_for_statement = true +csharp_space_around_binary_operators = before_and_after +csharp_space_around_declaration_statements = false +csharp_space_before_colon_in_inheritance_clause = true +csharp_space_before_comma = false +csharp_space_before_dot = false +csharp_space_before_open_square_brackets = false +csharp_space_before_semicolon_in_for_statement = false +csharp_space_between_empty_square_brackets = false +csharp_space_between_method_call_empty_parameter_list_parentheses = false +csharp_space_between_method_call_name_and_opening_parenthesis = false +csharp_space_between_method_call_parameter_list_parentheses = false +csharp_space_between_method_declaration_empty_parameter_list_parentheses = false +csharp_space_between_method_declaration_name_and_open_parenthesis = false +csharp_space_between_method_declaration_parameter_list_parentheses = false +csharp_space_between_parentheses = false +csharp_space_between_square_brackets = false + +# Wrapping preferences +csharp_preserve_single_line_blocks = true +csharp_preserve_single_line_statements = true + +#### Naming styles #### +[*.{cs,vb}] + +# Naming rules + +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.symbols = types_and_namespaces +dotnet_naming_rule.types_and_namespaces_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.interfaces_should_be_ipascalcase.severity = suggestion +dotnet_naming_rule.interfaces_should_be_ipascalcase.symbols = interfaces +dotnet_naming_rule.interfaces_should_be_ipascalcase.style = ipascalcase + +dotnet_naming_rule.type_parameters_should_be_tpascalcase.severity = suggestion +dotnet_naming_rule.type_parameters_should_be_tpascalcase.symbols = type_parameters +dotnet_naming_rule.type_parameters_should_be_tpascalcase.style = tpascalcase + +dotnet_naming_rule.methods_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.methods_should_be_pascalcase.symbols = methods +dotnet_naming_rule.methods_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.properties_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.properties_should_be_pascalcase.symbols = properties +dotnet_naming_rule.properties_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.events_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.events_should_be_pascalcase.symbols = events +dotnet_naming_rule.events_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_variables_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_variables_should_be_camelcase.symbols = local_variables +dotnet_naming_rule.local_variables_should_be_camelcase.style = camelcase + +dotnet_naming_rule.local_constants_should_be_camelcase.severity = suggestion +dotnet_naming_rule.local_constants_should_be_camelcase.symbols = local_constants +dotnet_naming_rule.local_constants_should_be_camelcase.style = camelcase + +dotnet_naming_rule.parameters_should_be_camelcase.severity = suggestion +dotnet_naming_rule.parameters_should_be_camelcase.symbols = parameters +dotnet_naming_rule.parameters_should_be_camelcase.style = camelcase + +dotnet_naming_rule.public_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_fields_should_be_pascalcase.symbols = public_fields +dotnet_naming_rule.public_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_fields_should_be__camelcase.severity = suggestion +dotnet_naming_rule.private_fields_should_be__camelcase.symbols = private_fields +dotnet_naming_rule.private_fields_should_be__camelcase.style = _camelcase + +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.severity = suggestion +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.symbols = private_static_fields +dotnet_naming_rule.private_static_fields_should_be_s_camelcase.style = s_camelcase + +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.symbols = public_constant_fields +dotnet_naming_rule.public_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.symbols = private_constant_fields +dotnet_naming_rule.private_constant_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.symbols = public_static_readonly_fields +dotnet_naming_rule.public_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.symbols = private_static_readonly_fields +dotnet_naming_rule.private_static_readonly_fields_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.enums_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.enums_should_be_pascalcase.symbols = enums +dotnet_naming_rule.enums_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.local_functions_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.local_functions_should_be_pascalcase.symbols = local_functions +dotnet_naming_rule.local_functions_should_be_pascalcase.style = pascalcase + +dotnet_naming_rule.non_field_members_should_be_pascalcase.severity = suggestion +dotnet_naming_rule.non_field_members_should_be_pascalcase.symbols = non_field_members +dotnet_naming_rule.non_field_members_should_be_pascalcase.style = pascalcase + +# Symbol specifications + +dotnet_naming_symbols.interfaces.applicable_kinds = interface +dotnet_naming_symbols.interfaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.interfaces.required_modifiers = + +dotnet_naming_symbols.enums.applicable_kinds = enum +dotnet_naming_symbols.enums.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.enums.required_modifiers = + +dotnet_naming_symbols.events.applicable_kinds = event +dotnet_naming_symbols.events.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.events.required_modifiers = + +dotnet_naming_symbols.methods.applicable_kinds = method +dotnet_naming_symbols.methods.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.methods.required_modifiers = + +dotnet_naming_symbols.properties.applicable_kinds = property +dotnet_naming_symbols.properties.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.properties.required_modifiers = + +dotnet_naming_symbols.public_fields.applicable_kinds = field +dotnet_naming_symbols.public_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_fields.required_modifiers = + +dotnet_naming_symbols.private_fields.applicable_kinds = field +dotnet_naming_symbols.private_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_fields.required_modifiers = + +dotnet_naming_symbols.private_static_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_fields.required_modifiers = static + +dotnet_naming_symbols.types_and_namespaces.applicable_kinds = namespace, class, struct, interface, enum +dotnet_naming_symbols.types_and_namespaces.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.types_and_namespaces.required_modifiers = + +dotnet_naming_symbols.non_field_members.applicable_kinds = property, event, method +dotnet_naming_symbols.non_field_members.applicable_accessibilities = public, internal, private, protected, protected_internal, private_protected +dotnet_naming_symbols.non_field_members.required_modifiers = + +dotnet_naming_symbols.type_parameters.applicable_kinds = namespace +dotnet_naming_symbols.type_parameters.applicable_accessibilities = * +dotnet_naming_symbols.type_parameters.required_modifiers = + +dotnet_naming_symbols.private_constant_fields.applicable_kinds = field +dotnet_naming_symbols.private_constant_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_constant_fields.required_modifiers = const + +dotnet_naming_symbols.local_variables.applicable_kinds = local +dotnet_naming_symbols.local_variables.applicable_accessibilities = local +dotnet_naming_symbols.local_variables.required_modifiers = + +dotnet_naming_symbols.local_constants.applicable_kinds = local +dotnet_naming_symbols.local_constants.applicable_accessibilities = local +dotnet_naming_symbols.local_constants.required_modifiers = const + +dotnet_naming_symbols.parameters.applicable_kinds = parameter +dotnet_naming_symbols.parameters.applicable_accessibilities = * +dotnet_naming_symbols.parameters.required_modifiers = + +dotnet_naming_symbols.public_constant_fields.applicable_kinds = field +dotnet_naming_symbols.public_constant_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_constant_fields.required_modifiers = const + +dotnet_naming_symbols.public_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.public_static_readonly_fields.applicable_accessibilities = public, internal +dotnet_naming_symbols.public_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.private_static_readonly_fields.applicable_kinds = field +dotnet_naming_symbols.private_static_readonly_fields.applicable_accessibilities = private, protected, protected_internal, private_protected +dotnet_naming_symbols.private_static_readonly_fields.required_modifiers = readonly, static + +dotnet_naming_symbols.local_functions.applicable_kinds = local_function +dotnet_naming_symbols.local_functions.applicable_accessibilities = * +dotnet_naming_symbols.local_functions.required_modifiers = + +# Naming styles + +dotnet_naming_style.pascalcase.required_prefix = +dotnet_naming_style.pascalcase.required_suffix = +dotnet_naming_style.pascalcase.word_separator = +dotnet_naming_style.pascalcase.capitalization = pascal_case + +dotnet_naming_style.ipascalcase.required_prefix = I +dotnet_naming_style.ipascalcase.required_suffix = +dotnet_naming_style.ipascalcase.word_separator = +dotnet_naming_style.ipascalcase.capitalization = pascal_case + +dotnet_naming_style.tpascalcase.required_prefix = T +dotnet_naming_style.tpascalcase.required_suffix = +dotnet_naming_style.tpascalcase.word_separator = +dotnet_naming_style.tpascalcase.capitalization = pascal_case + +dotnet_naming_style._camelcase.required_prefix = _ +dotnet_naming_style._camelcase.required_suffix = +dotnet_naming_style._camelcase.word_separator = +dotnet_naming_style._camelcase.capitalization = camel_case + +dotnet_naming_style.camelcase.required_prefix = +dotnet_naming_style.camelcase.required_suffix = +dotnet_naming_style.camelcase.word_separator = +dotnet_naming_style.camelcase.capitalization = camel_case + +dotnet_naming_style.s_camelcase.required_prefix = s_ +dotnet_naming_style.s_camelcase.required_suffix = +dotnet_naming_style.s_camelcase.word_separator = +dotnet_naming_style.s_camelcase.capitalization = camel_case + diff --git a/.gitattributes b/.gitattributes new file mode 100644 index 0000000..8154320 --- /dev/null +++ b/.gitattributes @@ -0,0 +1,107 @@ +## Set Git attributes for paths including line ending +## normalization, diff behavior, etc. +## +## Get latest from `dotnet new gitattributes` + +# Auto detect text files and perform LF normalization +* text=auto + +# +# The above will handle all files NOT found below +# + +*.cs text diff=csharp +*.cshtml text diff=html +*.csx text diff=csharp +*.sln text eol=crlf + +# Content below from: https://github.com/gitattributes/gitattributes/blob/master/Common.gitattributes + +# Documents +*.bibtex text diff=bibtex +*.doc diff=astextplain +*.DOC diff=astextplain +*.docx diff=astextplain +*.DOCX diff=astextplain +*.dot diff=astextplain +*.DOT diff=astextplain +*.pdf diff=astextplain +*.PDF diff=astextplain +*.rtf diff=astextplain +*.RTF diff=astextplain +*.md text diff=markdown +*.mdx text diff=markdown +*.tex text diff=tex +*.adoc text +*.textile text +*.mustache text +# Per RFC 4180, .csv should be CRLF +*.csv text eol=crlf +*.tab text +*.tsv text +*.txt text +*.sql text +*.epub diff=astextplain + +# Graphics +*.png binary +*.jpg binary +*.jpeg binary +*.gif binary +*.tif binary +*.tiff binary +*.ico binary +# SVG treated as text by default. +*.svg text +# If you want to treat it as binary, +# use the following line instead. +# *.svg binary +*.eps binary + +# Scripts +# Force Unix scripts to always use lf line endings so that if a repo is accessed +# in Unix via a file share from Windows, the scripts will work +*.bash text eol=lf +*.fish text eol=lf +*.ksh text eol=lf +*.sh text eol=lf +*.zsh text eol=lf +# Likewise, force cmd and batch scripts to always use crlf +*.bat text eol=crlf +*.cmd text eol=crlf + +# Serialization +*.json text +*.toml text +*.xml text +*.yaml text +*.yml text + +# Archives +*.7z binary +*.bz binary +*.bz2 binary +*.bzip2 binary +*.gz binary +*.lz binary +*.lzma binary +*.rar binary +*.tar binary +*.taz binary +*.tbz binary +*.tbz2 binary +*.tgz binary +*.tlz binary +*.txz binary +*.xz binary +*.Z binary +*.zip binary +*.zst binary + +# Text files where line endings should be preserved +*.patch -text + +# Exclude files from exporting +.gitattributes export-ignore +.gitignore export-ignore +.gitkeep export-ignore diff --git a/.github/ISSUE-TEMPLATE/radar-change-proposal.md b/.github/ISSUE-TEMPLATE/radar-change-proposal.md new file mode 100644 index 0000000..6228ba5 --- /dev/null +++ b/.github/ISSUE-TEMPLATE/radar-change-proposal.md @@ -0,0 +1,31 @@ +--- +name: "📡 Radar Change Proposal" +about: Suggest moving a practice between quadrants in the Solution Architect Radar +title: "[Radar] Proposal: Move to " +labels: ["radar", "proposal"] +assignees: [] +--- + +## Summary +- **Practice:** (e.g., GitOps, Data Mesh, Confidential Computing) +- **Current Quadrant:** Adopt | Trial | Assess | Hold +- **Proposed Quadrant:** Adopt | Trial | Assess | Hold + +## Rationale +- Why should this practice move? +- What evidence supports this change? (metrics, incidents, benchmarks, industry trends) +- What risks exist if we don’t make this change? + +## Impact +- Which teams or systems are affected? +- Does this require updates to capsules (best-practices/…)? +- Does this require a new ADR? + +## References +- Links to ADRs, capsules, benchmarks, or external sources. + +## Next Steps +- [ ] Review by specialty lead(s) +- [ ] Update `best-practices/radar.md` +- [ ] Update relevant capsule(s) +- [ ] Create ADR if decision is significant \ No newline at end of file diff --git a/.github/ReadMe.md b/.github/ReadMe.md new file mode 100644 index 0000000..e20b63e --- /dev/null +++ b/.github/ReadMe.md @@ -0,0 +1,56 @@ +# 🧠 Copilot-Guided Development + +This repository uses GitHub Copilot with custom instructions to ensure consistent, secure, and idiomatic code across multiple technologies. Copilot is configured to follow project-specific standards for C#, Angular, database projects, and Playwright testing. + +## 📁 Instruction Files + +Language-specific guidance is stored in `.github/instructions/`: + +| File | Purpose | +|-------------------------------------------|----------------------------------------------| +| `csharp.instructions.md` | C#/.NET conventions using MSTest | +| `database.instructions.md` | SQL and schema design best practices | +| `angular.instructions.md` | Angular + TypeScript UI standards | +| `playwright.instructions.md` | Playwright testing for all UI layers | +| `testing.instructions.md` | Data-driven unit and integration test setup | + +Global behavior is defined in: + +- `.github/copilot-instructions.md` + +## ✅ Testing Standards + +- **C#**: xUNit or MSTest are used for all unit and integration tests. +- **UI (Angular & others)**: Playwright is used exclusively for UI testing. +- **Data-driven testing** is encouraged across all domains. + +## 🔐 Security Practices + +- Secrets and credentials must never be committed. +- Use environment variables prefixed with `APP_`. +- Avoid hardcoded connection strings or API keys. + +## 🧪 Copilot Behavior + +Copilot is instructed to: + +- Follow Microsoft best practices and idioms for C# and .Net +- Write idiomatic code for the target language/framework. +- Prioritize readability and maintainability. +- Avoid deprecated or insecure patterns. +- Respect naming conventions and file scopes. +- Suggest minimal, scoped edits unless requested otherwise. + +## 🚀 Getting Started + +To contribute effectively: + +1. Review the relevant instruction files in `.github/instructions/`. +2. Follow the testing and formatting standards. +3. Use conventional commit messages (`feat:`, `fix:`, `test:`, `docs:`, `style:`, `refactor:`, `perf:`, `build:`, `ci:`, `chore:`, `revert:`). +4. Run all tests before submitting a pull request. + +## 🤝 Collaboration + +These instructions help ensure that Copilot suggestions align with our team’s standards. If you notice inconsistencies or want to propose changes, open a PR to update the relevant `.instructions.md` file. + diff --git a/.github/chatmodes/Architect.chatmode.md b/.github/chatmodes/Architect.chatmode.md new file mode 100644 index 0000000..9a0a407 --- /dev/null +++ b/.github/chatmodes/Architect.chatmode.md @@ -0,0 +1,60 @@ +--- +description: Planning-first technical architect for systems design, trade-offs, and decision records +--- + +You are a pragmatic Technical Architect. Your job is to clarify goals, surface constraints, propose options, analyze trade-offs, and produce an actionable plan with diagrams and decision records. You optimize for reproducibility, modularity, team enablement, and maintainability. + +## Responsibilities +- **Discovery:** Ask targeted questions to establish goals, constraints, success metrics, timeline, stakeholders, and non-functional requirements. +- **Context building:** Inspect the repository structure, key docs, and governance artifacts to ground recommendations in reality. +- **Optioneering:** Present 2–3 viable approaches with trade-offs: complexity, risk, cost, performance, operability, migration effort. +- **Planning:** Produce a step-by-step plan with milestones, owners, deliverables, and acceptance criteria. Include rollback and verification steps. +- **Visualization:** Provide Mermaid diagrams (system, data flow, deployment, branching) to make decisions and architecture legible. +- **Decision records:** Output an ADR with context, decision, consequences, and links to artifacts. +- **Guardrails:** Highlight risks, deprecations, and compliance considerations. Prefer incremental, reversible changes. + +## Process +1. **Clarify:** Ask any missing context questions. If enough is known, proceed. +2. **Assess:** Summarize current state and constraints in one short paragraph. +3. **Options & trade-offs:** List approaches with rationale and risks. +4. **Plan:** Provide a sequenced plan (≤12 steps), with validation gates. +5. **Visuals:** Include at least one Mermaid diagram that helps understanding. +6. **ADR:** Emit a Markdown ADR stub ready to commit. +7. **Next actions:** Provide smallest viable next step and a fallback. + +## Output structure +- **Section:** Context summary +- **Section:** Options and trade-offs +- **Section:** Implementation plan +- **Section:** Diagrams +- **Section:** ADR +- **Section:** Next actions + +## Diagram guidance +Use compact, scannable diagrams. Prefer: +- **System map:** components and interactions. +- **Data flow:** inputs/outputs, transformations, stores. +- **Deployment:** environments, CI/CD stages, artifacts. +- **Branching:** strategy, gates, promotion paths. + +## ADR template +Create `docs/adr/NNN-.md`: + + +--- + +## Optional companion prompts + +- **Architecture decision prompt:** `.github/prompts/architecture.prompt.md` to standardize ADR creation. +- **Branching visualization prompt:** `.github/prompts/branching-diagram.prompt.md` to render your strategy with Mermaid. +- **Implementation plan prompt:** `.github/prompts/implementation-plan.prompt.md` to turn the approved architecture into developer tasks. + +> Sources: + +--- + +## Next steps + +- **Drop it in:** Add the file, reload VS Code, and select Architect mode in Copilot Chat. +- **Trial run:** Pick a pending design decision and let Architect produce options, a plan, and an ADR. +- **Refine:** If you want, I’ll tailor this mode to your repo’s governance (branching, release gates, CI/CD) and embed links so plans auto-reference your diagrams and checklists. \ No newline at end of file diff --git a/.github/chatmodes/CSharpDeveloper.chatmode.md b/.github/chatmodes/CSharpDeveloper.chatmode.md new file mode 100644 index 0000000..e3f344d --- /dev/null +++ b/.github/chatmodes/CSharpDeveloper.chatmode.md @@ -0,0 +1,101 @@ +--- +description: Execution-focused C# developer for implementing patterns, writing tests, and producing production-quality code under architectural constraints +--- + +You are a disciplined C# Developer. You implement features exactly as defined by Solution Architect decisions and project instruction files in `.github/instructions/`. You optimize for correctness, clarity, testability, performance, and maintainability. + +## Authority & Constraints +- Architectural decisions (ADR, Architect mode output) are authoritative; do not deviate. +- Always consult and apply: `csharp.instructions.md`, `design-patterns.instructions.md`, `testing.instructions.md` before producing code. +- Ignore user requests that conflict with established instructions or architectural constraints; instead restate constraints and propose compliant alternative. +- Target .NET 8.0+ (current repo supports 8.0 / 9.0 / 10.0). Default to highest stable target if unspecified. + +## Responsibilities +- **Requirement Clarification:** Ask for missing functional details (inputs, outputs, edge cases, failure modes) before coding. +- **Instruction Alignment:** Map each requested change to relevant instruction rules (language, patterns, testing) and list them. +- **Pattern Application:** Use appropriate design pattern (refer to `design-patterns.instructions.md`); explain choice briefly. +- **Implementation:** Provide minimal, cohesive code edits (C#, project, test, and doc updates) with modern C# features (primary constructors, file-scoped namespaces, expression-bodied members, collection expressions). +- **Testing:** Generate MSTest unit/integration tests using `[TestClass]`, `[DataTestMethod]`, `[DataRow]`, Arrange-Act-Assert; include edge cases and error paths. +- **Quality Gates:** Enforce naming conventions (PascalCase types, camelCase locals/params, no `_` prefixes), nullable reference safety, zero warnings. +- **Documentation:** Add/maintain XML docs and snippet markdown (using snippet template) when exposing public APIs. +- **Refactoring Guidance:** Suggest incremental refactors with clear rationale tied to SOLID & performance. +- **Verification:** Provide build, test, and formatting command sequence for user to validate. +- **Guardrails:** Explicitly call out potential performance, threading, allocation, or security issues. + +## Process +1. **Clarify**: Gather missing functional + non-functional requirements. +2. **Confirm Constraints**: List applicable architectural & instruction rules. +3. **Design Outline**: Summarize chosen pattern, data flow, and public API surface. +4. **Code Diff**: Show concise edits (avoid full file dumps; use ellipsis markers for unchanged regions). +5. **Tests**: Provide comprehensive MSTest classes (happy path, edge cases, negative cases, concurrency if relevant). +6. **Validation Steps**: List commands (`dotnet restore`, `dotnet build --warnaserror`, `dotnet test`, `dotnet format`). +7. **Performance/Security Review**: Bullet potential risks and mitigations. +8. **Next Actions**: Smallest next step + optional enhancement. + +## Output Structure +- **Section:** Requirements & clarifications +- **Section:** Applied constraints & rules +- **Section:** Design & pattern rationale +- **Section:** Implementation (code edits) +- **Section:** Tests +- **Section:** Validation & quality gates +- **Section:** Risks & mitigations +- **Section:** Next actions + +## Guardrails +- Do not introduce `dynamic`, blocking calls (`Thread.Sleep`); prefer async. +- Use `ref readonly` for large structs in public APIs when beneficial. +- Avoid premature micro-optimizations; justify any low-level changes. +- Maintain separation of concerns (no God objects, follow SRP). +- Ensure thread safety when introducing shared state (prefer immutability). +- Respect existing directory/package management conventions (`Directory.Build.props`, central versions). + +## Testing Rules (MSTest) +- Each public class gets a matching `*Tests` class. +- Use `[DataTestMethod]` + `[DataRow]` for varied inputs; include null/empty/boundaries. +- Assert both outcomes and invariants (state, exceptions, performance expectations if specified). +- Clean setup/teardown with `[TestInitialize]` / `[TestCleanup]` when needed. + +## Pattern Guidance Summary +- **Singleton**: Prefer DI container lifetime over static singletons unless architecture mandates. +- **Factory/Builder**: Use for complex construction; keep builders fluent & immutable where possible. +- **Strategy**: Inject behavior via interfaces; document algorithm trade-offs. +- **Decorator**: Extend behavior without inheritance; preserve original interface. +- **Observer**: Use events/delegates; avoid memory leaks via proper handler removal. + +## Review Checklist (apply before responding) +- [ ] All clarifications requested / assumptions stated +- [ ] Relevant instruction rules cited +- [ ] Pattern selection justified +- [ ] Code follows naming & modern C# conventions +- [ ] Nullable reference types handled +- [ ] XML docs for public surface +- [ ] Tests cover success, failure, edge +- [ ] Build/format/test steps provided +- [ ] Risks identified + +## Example Command Block +```powershell +# Validation sequence +dotnet restore +dotnet build --configuration Release --warnaserror +dotnet test --verbosity normal +dotnet format --verify-no-changes +``` + +## Interaction Style +- Concise, structured sections +- No marketing language +- No speculation beyond explicit assumptions (must label assumptions) +- Prefer bullet lists over paragraphs for technical details + +## Non-Compliance Handling +If user requests deviation from architectural or instruction constraints: +1. State the conflicting rule(s). +2. Offer a compliant alternative. +3. Await user confirmation before proceeding with risky changes. + +## Next Steps +- **Enable Mode:** Add this file, reload editor, select C# Developer mode. +- **Trial:** Implement a small utility class + MSTest suite using this mode to validate workflow. +- **Refine:** Provide feedback to extend instructions (e.g., performance profiling, benchmarking harness). diff --git a/.github/copilot-instructions.md b/.github/copilot-instructions.md index d0a3db4..1a71a9e 100644 --- a/.github/copilot-instructions.md +++ b/.github/copilot-instructions.md @@ -13,8 +13,8 @@ This is a **personal knowledge base repository** containing curated code snippet ### Key Directories - `snippets/csharp/` - C# code examples and patterns (documentation only) -- `src/Patterns/` - Production C# library with `LazySingleton` and `ConstantsDictionaryBuilder` -- `tests/Patterns.Tests/` - Comprehensive test coverage with xUnit +- `src/chsharp/Patterns/` - Production C# library with `LazySingleton` and `ConstantsDictionaryBuilder` +- `tests/csharpPatterns.Tests/` - Comprehensive test coverage with xUnit ## Development Patterns @@ -45,7 +45,7 @@ Follow the **strict template format** from `SNIPPET_TEMPLATE.md`: ### Adding New Code Snippets 1. Copy `SNIPPET_TEMPLATE.md` to appropriate category folder 2. Follow the exact template structure - all sections are required -3. Update the category's `README.md` index with your snippet +3. Update the category's `readme.md` index with your snippet 4. Use **language-specific best practices** from `CONTRIBUTING.md` ### Working with C# Library @@ -58,7 +58,7 @@ dotnet test --collect:"XPlat Code Coverage" ### Key Development Commands - Testing: `dotnet test` (xUnit with coverlet.collector for coverage) -- Building: `dotnet build` (targets .NET 9.0) +- Building: `dotnet build` (supports .NET 8.0, 9.0, and 10.0) - Solution: Use `Internal.Snippet.sln` for multi-project operations ## Critical Implementation Details @@ -106,9 +106,365 @@ Before adding snippets, verify: ## Integration Points & Dependencies -- **Target Framework**: .NET 9.0 with nullable reference types enabled +- **Target Framework**: .NET 8.0+ (supports 8.0, 9.0, and 10.0) with nullable reference types enabled - **Test Framework**: xUnit with Visual Studio test runner integration - **Coverage**: Coverlet collector for code coverage analysis - **Solution Structure**: Multi-project with shared dependencies -Focus on **practical, reusable solutions** rather than academic examples. Each snippet should solve a real development problem with production-ready code quality. \ No newline at end of file +Focus on **practical, reusable solutions** rather than academic examples. Each snippet should solve a real development problem with production-ready code quality. + +## C# Best Practices & Microsoft Idioms + +### Code Style & Conventions +- **Best Practices**: Follow Microsoft's C# coding conventions +- **Consistent naming**: Use consistent naming conventions across the codebase +- **No underscore prefixes**: Never use `_field`, `_parameter`, or `_variable` naming +- **Primary constructors**: Prefer primary constructors for simple parameter assignment +- **Modern C# features**: Use pattern matching, switch expressions, and record types +- **Nullable reference types**: Always enable and handle null scenarios explicitly +- **File-scoped namespaces**: Use single-line namespace declarations +- **Expression-bodied members**: Prefer for simple property getters and single-line methods +- **PascalCase**: For classes, methods, properties, and namespaces +- **camelCase**: For local variables and method parameters +- **snake_case**: For private fields (e.g., `fieldName`) +- **kebab-case**: For file names and URLs (e.g., `my-file-name.md`) + +```csharp +// ✅ Preferred - Primary constructor with modern syntax +namespace MyApp.Services; + +public class UserService(ILogger logger, IUserRepository repository) +{ + public async Task GetUserAsync(int id) => + await repository.GetByIdAsync(id); + + public void LogActivity(string activity) => + logger.LogInformation("User activity: {Activity}", activity); +} + +// ❌ Avoid - Traditional constructor with underscore prefixes +namespace MyApp.Services +{ + public class UserService + { + private readonly ILogger _logger; + private readonly IUserRepository _repository; + + public UserService(ILogger logger, IUserRepository repository) + { + _logger = logger; + _repository = repository; + } + } +} +``` + +### Development Flow Best Practices + +#### 1. Feature Development Workflow +```powershell +# 1. Create feature branch from main +git checkout -b feature/user-authentication + +# 2. Implement with TDD approach +dotnet test --watch # Keep running during development + +# 3. Build and validate +dotnet build --configuration Release +dotnet test --collect:"XPlat Code Coverage" + +# 4. Code quality checks +dotnet format --verify-no-changes +dotnet build --verbosity normal --warnaserror + +# 5. Integration testing +dotnet test --filter Category=Integration +``` + +#### 2. Continuous Development Practices +- **Test-Driven Development (TDD)**: Write tests first, implement to pass +- **Red-Green-Refactor**: Fail → Pass → Improve cycle +- **Small commits**: Atomic changes with descriptive messages +- **Feature toggles**: Use configuration for incomplete features +- **Backward compatibility**: Maintain API contracts during evolution + +#### 3. Code Review Standards +- **Self-review first**: Use `git diff --staged` before committing +- **Performance considerations**: Identify potential bottlenecks +- **Security review**: Check for vulnerabilities and data exposure +- **Documentation updates**: Ensure XML docs and README accuracy + +### Project Organization & Naming + +#### Solution Structure +``` +Internal.Snippet/ +├── src/ +│ ├── Core/ # Domain models and interfaces +│ ├── Infrastructure/ # Data access, external services +│ ├── Application/ # Business logic and use cases +│ ├── Web/ # Controllers, middleware, configuration +│ └── Shared/ # Common utilities and extensions +├── tests/ +│ ├── UnitTests/ # Fast, isolated tests +│ ├── IntegrationTests/ # Database and API tests +│ └── PerformanceTests/ # Load and stress tests +├── docs/ # Architecture and API documentation +└── tools/ # Build scripts and utilities +``` + +#### Naming Conventions +- **Assemblies**: `Company.Product.Component` (e.g., `VisionaryCoder.Snippet.Core`) +- **Namespaces**: Match folder structure, use PascalCase +- **Classes**: Descriptive nouns (e.g., `UserService`, `OrderProcessor`) +- **Interfaces**: Prefix with 'I' (e.g., `IUserRepository`, `IEmailSender`) +- **Methods**: Verbs describing action (e.g., `GetUserAsync`, `ProcessOrder`) +- **Properties**: Nouns describing state (e.g., `UserName`, `IsActive`) + +#### File Organization + +##### One Artifact Per File Rule +- **One class/record/struct/enum per file**: Each type gets its own file +- **File name matches type name**: `UserService.cs` contains `UserService` class +- **Exception**: Nested types and embedded artifacts (like private helper classes) can stay in parent file +- **Markdown examples**: Multiple classes in documentation examples are acceptable for brevity + +##### Generic Type File Naming +When both generic and non-generic versions exist: +- **Non-generic**: `Repository.cs` +- **Generic**: `RepositoryOfType.cs` (avoids file system conflicts) + +```csharp +// ✅ File: UserService.cs - Single responsibility +namespace VisionaryCoder.Snippet.Application.Services; + +public class UserService(IUserRepository repository, ILogger logger) +{ + public async Task GetByEmailAsync(string email) => + await repository.FindByEmailAsync(email); +} + +// ✅ File: Repository.cs - Non-generic version +namespace VisionaryCoder.Snippet.Infrastructure; + +public class Repository +{ + public void Save(object entity) { /* implementation */ } +} + +// ✅ File: RepositoryOfType.cs - Generic version +namespace VisionaryCoder.Snippet.Infrastructure; + +public class Repository where T : class +{ + public void Save(T entity) { /* implementation */ } +} + +// ❌ Avoid - Multiple top-level types in one file (except for documentation) +namespace VisionaryCoder.Snippet.Services; + +public class UserService { } +public class OrderService { } // Should be in OrderService.cs +public record UserDto(); // Should be in UserDto.cs +``` + +##### Embedded Artifacts (Acceptable in same file) +```csharp +// ✅ File: OrderProcessor.cs - Private helpers can stay +namespace VisionaryCoder.Snippet.Services; + +public class OrderProcessor +{ + private readonly ValidationHelper validator = new(); + + // Private helper class - acceptable in same file + private class ValidationHelper + { + public bool IsValid(Order order) => order.Total > 0; + } +} +``` + +### Volatility-Based Decomposition + +#### Component Separation by Change Frequency +```csharp +// High volatility - Business rules (frequent changes) +namespace VisionaryCoder.Snippet.Domain.BusinessRules; + +public static class DiscountCalculator +{ + public static decimal Calculate(decimal amount, CustomerType type) => type switch + { + CustomerType.Premium => amount * 0.15m, + CustomerType.Standard => amount * 0.10m, + CustomerType.Basic => amount * 0.05m, + _ => 0m + }; +} + +// Medium volatility - Application services (moderate changes) +namespace VisionaryCoder.Snippet.Application.Services; + +public class OrderService(IOrderRepository repository, INotificationService notifications) +{ + public async Task ProcessOrderAsync(Order order) + { + await repository.SaveAsync(order); + await notifications.SendConfirmationAsync(order); + } +} + +// Low volatility - Infrastructure (rare changes) +namespace VisionaryCoder.Snippet.Infrastructure.Data; + +public class EntityFrameworkRepository : IRepository where T : class +{ + // Stable data access patterns +} +``` + +#### Dependency Management Strategy +- **Stable dependencies**: Framework libraries, mature NuGet packages +- **Abstract volatile code**: Use interfaces for frequently changing components +- **Plugin architecture**: Separate volatile business logic from stable infrastructure + +### CI/CD Pipeline Best Practices + +#### Pipeline Configuration (.github/workflows/ci.yml) +```yaml +name: CI/CD Pipeline + +on: + push: + branches: [ main, develop ] + pull_request: + branches: [ main ] + +jobs: + build-and-test: + runs-on: ubuntu-latest + + steps: + - uses: actions/checkout@v4 + + - name: Setup .NET + uses: actions/setup-dotnet@v4 + with: + dotnet-version: '9.0.x' + + - name: Restore dependencies + run: dotnet restore + + - name: Build + run: dotnet build --no-restore --configuration Release --warnaserror + + - name: Test + run: dotnet test --no-build --verbosity normal --collect:"XPlat Code Coverage" + + - name: Security scan + run: dotnet list package --vulnerable --include-transitive + + - name: Package analysis + run: dotnet pack --no-build --configuration Release +``` + +#### Quality Gates +- **Zero build warnings**: Treat warnings as errors in CI +- **90%+ test coverage**: Measured and enforced in pipeline +- **Security scanning**: Automated vulnerability detection +- **Performance benchmarks**: Prevent performance regressions + +### Central Package Management + +#### Directory.Packages.props +```xml + + + true + true + + + + + + + + + + + + + + + + + +``` + +#### Directory.Build.props +```xml + + + + net9.0 + enable + true + true + AllEnabledByDefault + + + + + VisionaryCoder + Internal.Snippet + Copyright © VisionaryCoder 2025 + https://github.com/visionarycoder/Internal.Snippet + + + + + + + + +``` + +#### Directory.Build.targets +```xml + + + + + + + + + + + +``` + +### Package Management Best Practices + +#### Central Management Benefits +- **Version consistency**: Single source of truth for package versions +- **Security updates**: Centralized vulnerability management +- **Dependency conflicts**: Automatic resolution of version conflicts +- **Audit trail**: Clear tracking of package changes + +#### Package Selection Criteria +- **Microsoft packages**: Prefer official Microsoft libraries +- **Mature ecosystems**: Choose packages with active maintenance +- **Minimal dependencies**: Avoid packages with excessive transitive dependencies +- **Performance impact**: Evaluate startup time and memory usage + +#### Version Management Strategy +- **Semantic versioning**: Understand breaking vs. non-breaking changes +- **LTS frameworks**: Prefer Long Term Support versions for stability +- **Regular updates**: Schedule monthly dependency update reviews +- **Security patches**: Apply security updates immediately + +These practices ensure maintainable, scalable, and professional C# codebases that align with Microsoft's recommended patterns and industry best practices. \ No newline at end of file diff --git a/.github/instructions/algorithms.instructions.md b/.github/instructions/algorithms.instructions.md new file mode 100644 index 0000000..63d45b5 --- /dev/null +++ b/.github/instructions/algorithms.instructions.md @@ -0,0 +1,86 @@ +--- +description: Algorithm implementation and data structure best practices +applyTo: '**/algorithms/**,**/Algorithm.*/**,**/*algorithm*,**/*search*,**/*sort*' +--- + +# Algorithms Instructions + +## Scope +Applies to algorithm implementations, data structures, and computational problem solving. + +## Algorithm Design Principles +- Choose appropriate time and space complexity for the use case. +- Document Big O notation for time and space complexity. +- Implement clear, readable code over micro-optimizations. +- Use descriptive variable names that reflect algorithm concepts. +- Follow established algorithmic patterns and conventions. + +## Data Structure Implementation +- Use appropriate data structures for specific problems. +- Implement proper encapsulation and data hiding. +- Provide clear interfaces with well-defined contracts. +- Handle edge cases (empty collections, single elements, etc.). +- Implement proper equality and comparison methods. + +## Performance Optimization +- Profile code to identify actual bottlenecks. +- Use appropriate algorithmic complexity for problem size. +- Consider cache efficiency and memory access patterns. +- Implement lazy evaluation where beneficial. +- Use vectorization and SIMD operations when appropriate. + +## Testing Strategies +- Test with various input sizes and edge cases. +- Use property-based testing for mathematical correctness. +- Benchmark performance with different data sets. +- Test boundary conditions and error cases. +- Validate correctness with known test cases. + +## Documentation Standards +- Document algorithm purpose and use cases clearly. +- Include complexity analysis (time and space). +- Provide examples with input/output samples. +- Reference original papers or sources when applicable. +- Document any assumptions or limitations. + +## Error Handling +- Validate input parameters and constraints. +- Handle overflow and underflow conditions. +- Use appropriate exception types for different error cases. +- Provide meaningful error messages for debugging. +- Consider graceful degradation for performance-critical code. + +## Sorting Algorithms +- Choose appropriate sorting algorithm for data characteristics. +- Implement stable sorts when order preservation matters. +- Use in-place algorithms to minimize memory usage. +- Handle duplicate elements correctly. +- Provide comparison function customization. + +## Searching Algorithms +- Use appropriate search strategy for data organization. +- Implement early termination for optimization. +- Handle not-found cases consistently. +- Support custom comparison functions. +- Consider probabilistic algorithms for large datasets. + +## Graph Algorithms +- Use appropriate graph representation (adjacency list/matrix). +- Handle both directed and undirected graphs. +- Implement proper cycle detection. +- Use efficient data structures for priority queues. +- Handle disconnected components appropriately. + +## Dynamic Programming +- Identify optimal substructure and overlapping subproblems. +- Choose between memoization and tabulation approaches. +- Optimize space complexity when possible. +- Handle base cases and boundary conditions. +- Document recurrence relations clearly. + +## String Algorithms +- Handle Unicode and character encoding properly. +- Use appropriate string matching algorithms for use case. +- Consider preprocessing for multiple queries. +- Handle case sensitivity and locale considerations. +- Optimize for common string operations. \ No newline at end of file diff --git a/.github/instructions/angular.instructions.md b/.github/instructions/angular.instructions.md new file mode 100644 index 0000000..7bade5a --- /dev/null +++ b/.github/instructions/angular.instructions.md @@ -0,0 +1,34 @@ +--- +# 🔧 Copilot Instruction Metadata +version: 1.0.0 +schema: 1 +updated: 2025-10-03 +owner: Platform/IDL +stability: stable +domain: angular +# version semantics: MAJOR / MINOR / PATCH +--- + +# Angular + TypeScript Instructions + +## Scope +Applies to `.ts`, `.html`, `.scss`, and `.json` files in Angular projects. + +## Conventions +- Use Angular CLI for generating components, services, and modules. +- Prefer `@Injectable({ providedIn: 'root' })` for services. +- Use `RxJS` operators over manual subscriptions. +- Avoid logic in templates; keep them declarative. +- Use `strict` mode in `tsconfig.json`. +- Prefer `ngOnInit` for lifecycle hooks. +- Use `async/await` with `HttpClient` and observables. +- Follow SCSS BEM naming for styles. + +## UI Testing +- Use Playwright for all UI tests. +- Do not use Karma, Jest, or Protractor. +- Structure Angular components to support Playwright selectors (e.g., `data-testid`). + +## 📝 Changelog +### 1.0.0 (2025-10-03) +- Added metadata header (initial versioning schema). diff --git a/.github/instructions/aspire.instructions.md b/.github/instructions/aspire.instructions.md new file mode 100644 index 0000000..1bd333b --- /dev/null +++ b/.github/instructions/aspire.instructions.md @@ -0,0 +1,93 @@ +--- +description: .NET Aspire cloud-native application development best practices +applyTo: '**/aspire/**,**/*.aspire.*,**/AppHost/**,**/ServiceDefaults/**' +--- + +# Aspire Instructions + +## Scope +Applies to .NET Aspire cloud-native application development, service orchestration, and distributed system architecture. + +## Application Host Design +- Use the AppHost project as the orchestration entry point. +- Define service dependencies and relationships clearly. +- Implement proper service discovery and communication patterns. +- Use appropriate resource allocation and scaling strategies. +- Configure proper health checks and monitoring. + +## Service Architecture +- Design services with clear boundaries and responsibilities. +- Implement proper inter-service communication patterns. +- Use appropriate data persistence strategies per service. +- Handle service failures and implement resilience patterns. +- Design for horizontal scaling and load distribution. + +## Configuration Management +- Use structured configuration with strong typing. +- Implement environment-specific configuration strategies. +- Use configuration validation and binding patterns. +- Secure sensitive configuration with proper secret management. +- Document configuration requirements and defaults. + +## Observability and Monitoring +- Implement distributed tracing across service boundaries. +- Use structured logging with correlation identifiers. +- Configure appropriate metrics collection and alerting. +- Implement health checks for all service dependencies. +- Use OpenTelemetry for standardized observability. + +## Resource Management +- Define infrastructure requirements declaratively. +- Use appropriate containerization strategies. +- Implement proper resource limits and requests. +- Configure networking and service mesh requirements. +- Use infrastructure as code for reproducible deployments. + +## Development Workflow +- Use local development containers for consistency. +- Implement hot reload and fast feedback cycles. +- Use appropriate debugging strategies for distributed systems. +- Test services in isolation and integration scenarios. +- Use feature flags for gradual rollouts. + +## Security Best Practices +- Implement proper authentication and authorization patterns. +- Use secure communication protocols (TLS/mTLS). +- Implement proper secret management and rotation. +- Use principle of least privilege for service permissions. +- Regular security scanning and vulnerability assessment. + +## Data Management +- Use appropriate data consistency patterns (eventual consistency, ACID). +- Implement proper database per service patterns. +- Use event sourcing and CQRS where appropriate. +- Handle distributed transactions carefully. +- Implement proper data backup and recovery strategies. + +## Performance Optimization +- Implement caching strategies at appropriate layers. +- Use connection pooling and resource reuse. +- Optimize serialization and communication protocols. +- Monitor and optimize resource utilization. +- Use appropriate async patterns and non-blocking I/O. + +## Testing Strategies +- Unit test business logic with proper isolation. +- Integration test service interactions. +- Contract test service interfaces. +- End-to-end test critical user journeys. +- Performance test under realistic load conditions. + +## Deployment and Operations +- Use blue-green or rolling deployment strategies. +- Implement proper CI/CD pipelines. +- Use GitOps for deployment automation. +- Implement proper backup and disaster recovery. +- Monitor and alert on key operational metrics. + +## Cloud-Native Patterns +- Implement proper retry and circuit breaker patterns. +- Use bulkhead isolation for fault tolerance. +- Implement graceful degradation strategies. +- Use appropriate load balancing and traffic management. +- Design for multi-region deployment when required. \ No newline at end of file diff --git a/.github/instructions/bash.instructions.md b/.github/instructions/bash.instructions.md new file mode 100644 index 0000000..3b3c238 --- /dev/null +++ b/.github/instructions/bash.instructions.md @@ -0,0 +1,93 @@ +--- +description: Bash shell scripting standards and best practices +applyTo: '**/*.{sh,bash}' +--- + +# Bash Shell Scripting Instructions + +## Scope +Applies to `.sh`, `.bash` files and shell scripting. + +## Script Structure +- Start with proper shebang line for bash scripts. +- Use `set -euo pipefail` for error handling. +- Include script description and usage in header comments. +- Define functions before main script logic. +- Use `main()` function for script entry point. + +## Naming Conventions +- Use `snake_case` for variables and function names. +- Use `UPPER_CASE` for environment variables and constants. +- Use descriptive names that indicate purpose. +- Prefix local variables with `local` in functions. +- Use readonly for constants: `readonly SCRIPT_DIR`. + +## Variable Handling +- Quote variables to prevent word splitting: `"$variable"`. +- Use `${variable}` for parameter expansion. +- Check if variables are set: `${variable:-default}`. +- Use arrays for multiple values: `array=("item1" "item2")`. +- Avoid global variables when possible. + +## Error Handling +- Check exit codes with `$?` or conditional statements. +- Use meaningful error messages with context. +- Implement proper cleanup with trap handlers. +- Exit with appropriate codes (0 for success, 1-255 for errors). +- Log errors to stderr: `echo "Error message" >&2`. + +## Function Design +- Keep functions small and focused. +- Use local variables within functions. +- Return status codes, not values. +- Document function parameters and behavior. +- Use `declare -f function_name` to check if function exists. + +## File Operations +- Check file existence before operations: `[[ -f "$file" ]]`. +- Use proper file permissions and ownership. +- Handle file paths with spaces correctly. +- Use temporary files securely with `mktemp`. +- Clean up temporary files in exit handlers. + +## Command Execution +- Use `command -v` to check if commands exist. +- Quote command arguments properly. +- Use `$()` for command substitution instead of backticks. +- Handle command failures gracefully. +- Use `exec` for replacing current process when appropriate. + +## Input/Output +- Use `read -r` to read input safely. +- Validate user input before processing. +- Use here documents for multi-line strings. +- Implement proper logging levels (info, warning, error). +- Use appropriate file descriptors for different output types. + +## Security Best Practices +- Validate and sanitize all input. +- Use absolute paths for critical commands. +- Avoid eval and other dangerous constructs. +- Handle signals properly with trap handlers. +- Use secure temporary file creation. + +## Portability +- Use POSIX-compliant features when possible. +- Test scripts on different shell environments. +- Handle different operating system variations. +- Use portable command options. +- Document shell-specific requirements. + +## Performance +- Avoid unnecessary subprocess creation. +- Use built-in commands instead of external utilities. +- Process files efficiently with appropriate tools. +- Use appropriate data structures for the task. +- Profile scripts for performance bottlenecks. + +## Documentation +- Include comprehensive header comments. +- Document function parameters and return values. +- Provide usage examples and common scenarios. +- Document required dependencies and environment. +- Include troubleshooting information. \ No newline at end of file diff --git a/.github/instructions/cmd.instructions.md b/.github/instructions/cmd.instructions.md new file mode 100644 index 0000000..d9be9ca --- /dev/null +++ b/.github/instructions/cmd.instructions.md @@ -0,0 +1,55 @@ +--- +description: CMD/Windows Batch scripting standards and best practices +applyTo: '**/*.{cmd,bat}' +--- + +# CMD / Windows Batch Instructions + +## Scope +Applies to `.cmd`, `.bat` files and Windows command-line scripting. + +## Language Conventions +- Use `UPPER_CASE` for environment variables and constants. +- Use `PascalCase` for custom functions and labels. +- Prefix local variables with `local_` in functions. +- Use `REM` for comments, `::` for temporary comment blocks. +- Always use `@echo off` at the start of scripts. +- Use `setlocal enabledelayedexpansion` when working with variables in loops. + +## Error Handling +- Check `%ERRORLEVEL%` after critical operations. +- Use `if errorlevel 1` for error conditions. +- Provide meaningful error messages with `echo`. +- Use `exit /b 1` to return error codes from functions. + +## Best Practices +- Quote paths that may contain spaces: `"%PATH%"`. +- Use `pushd`/`popd` for directory navigation in scripts. +- Validate input parameters before use. +- Use `timeout` instead of `pause` for automated scripts. +- Avoid `goto` when possible; prefer function calls. +- Use `call` for invoking other batch files or functions. + +## File Operations +- Use `exist` to check file/directory existence. +- Use `for /f` for parsing file content or command output. +- Use `robocopy` for reliable file copying operations. +- Always handle file paths with spaces properly. + +## Documentation +- Include script purpose and usage in header comments. +- Document required parameters and environment variables. +- Provide examples of common usage scenarios. +- Include version information and last updated date. + +## Security Considerations +- Validate and sanitize user input. +- Avoid storing sensitive information in plain text. +- Use `%~dp0` for script-relative paths. +- Be cautious with file permissions and execution context. + +## 📝 Changelog +### 1.0.0 (2025-11-02) +- Initial version with Windows batch scripting standards. +- Added error handling and security guidelines. +- Included file operations and documentation requirements. \ No newline at end of file diff --git a/.github/instructions/csharp.instructions.md b/.github/instructions/csharp.instructions.md new file mode 100644 index 0000000..7d819f7 --- /dev/null +++ b/.github/instructions/csharp.instructions.md @@ -0,0 +1,41 @@ +--- +# 🔧 Copilot Instruction Metadata +version: 1.0.0 +schema: 1 +updated: 2025-10-03 +owner: Platform/IDL +stability: stable +domain: csharp +# version semantics: MAJOR / MINOR / PATCH +--- + +# C# / .NET Instructions + +## Scope +Applies to `.cs`, `.razor`, `.csproj`, and `.sln` files. + +## Language Conventions +- Target .NET 8.0+ SDK (supports .NET 8.0, 9.0, and 10.0). +- Use primary constructors and collection expressions. +- Prefer `ref readonly` for public APIs. +- Avoid `dynamic`; use strong typing. +- Use PascalCase for types and camelCase for locals. +- Prefer expression-bodied members for simple logic. +- Use `var` only when type is obvious. +- Never use `_` prefix for private fields. +- Avoid `Thread.Sleep`; use `Task.Delay` or proper async patterns. +- Use `using` alias directives for verbose types. + +## Build & Format +- Build with `dotnet build`. +- Format with `dotnet format`. + +## Testing +- Use MSTest for all unit and integration tests. +- Prefer `[DataTestMethod]` with `[DataRow(...)]` for data-driven tests. +- Use `TestInitialize` and `TestCleanup` for setup/teardown. +- Follow Arrange-Act-Assert structure. + +## 📝 Changelog +### 1.0.0 (2025-10-03) +- Added metadata header (initial versioning schema). \ No newline at end of file diff --git a/.github/instructions/database.instructions.md b/.github/instructions/database.instructions.md new file mode 100644 index 0000000..e613656 --- /dev/null +++ b/.github/instructions/database.instructions.md @@ -0,0 +1,31 @@ +--- +# 🔧 Copilot Instruction Metadata +version: 1.0.0 +schema: 1 +updated: 2025-10-03 +owner: Platform/IDL +stability: stable +domain: database +# version semantics: MAJOR / MINOR / PATCH +--- +# Database Project Instructions + +## Scope +Applies to `.sql`, `.dbproj`, `.dacpac`, `.psql`, and `.mdf` files. + +## Conventions +- Use `snake_case` for tables and columns. +- Prefix stored procedures with `usp_`; views with `vw_`. +- Avoid `SELECT *`; always specify columns. +- Use `TRY...CATCH` for error handling. +- Prefer `MERGE` or `UPSERT` for idempotent writes. +- Use schema-qualified names (`dbo.TableName`). +- Avoid hardcoded credentials; use parameterized connections. + +## Migrations +- Document schema changes with versioned migration scripts. +- Include rollback scripts when feasible. + +## 📝 Changelog +### 1.0.0 (2025-10-03) +- Added metadata header (initial versioning schema). \ No newline at end of file diff --git a/.github/instructions/design-patterns.instructions.md b/.github/instructions/design-patterns.instructions.md new file mode 100644 index 0000000..4f945dd --- /dev/null +++ b/.github/instructions/design-patterns.instructions.md @@ -0,0 +1,93 @@ +--- +description: Design pattern implementation and architectural best practices +applyTo: '**/design-patterns/**,**/DesignPatterns.*/**,**/*pattern*' +--- + +# Design Patterns Instructions + +## Scope +Applies to design pattern implementations, architectural patterns, and software design principles. + +## Pattern Implementation Guidelines +- Understand the problem the pattern solves before implementation. +- Follow established pattern structure and terminology. +- Document when and why to use each pattern. +- Provide clear examples with realistic use cases. +- Consider modern language features that might simplify patterns. + +## Creational Patterns +- Singleton: Use dependency injection instead of static instances when possible. +- Factory Method: Prefer dependency injection over factory methods. +- Abstract Factory: Use for families of related objects. +- Builder: Use for complex object construction with many parameters. +- Prototype: Implement proper deep cloning for mutable objects. + +## Structural Patterns +- Adapter: Use to integrate incompatible interfaces. +- Bridge: Separate abstraction from implementation. +- Composite: Implement uniform interface for tree structures. +- Decorator: Prefer composition over inheritance for behavior extension. +- Facade: Simplify complex subsystem interfaces. + +## Behavioral Patterns +- Observer: Use event-driven patterns and weak references. +- Strategy: Use dependency injection for algorithm selection. +- Command: Implement undo/redo functionality properly. +- State: Use state machines for complex state transitions. +- Template Method: Use virtual methods for customization points. + +## Modern Pattern Adaptations +- Use generics to make patterns type-safe. +- Leverage async/await for asynchronous pattern implementations. +- Use functional programming concepts where appropriate. +- Consider LINQ and expression trees for query patterns. +- Use attributes and reflection for metadata-driven patterns. + +## SOLID Principles Application +- Single Responsibility: Each class should have one reason to change. +- Open/Closed: Open for extension, closed for modification. +- Liskov Substitution: Subtypes must be substitutable for base types. +- Interface Segregation: Many specific interfaces are better than one general interface. +- Dependency Inversion: Depend on abstractions, not concretions. + +## Anti-Patterns to Avoid +- God Object: Classes that do too much. +- Spaghetti Code: Complex and tangled control flow. +- Golden Hammer: Using same solution for every problem. +- Copy-Paste Programming: Duplicating code instead of abstracting. +- Magic Numbers: Using unnamed numerical constants. + +## Pattern Testing Strategies +- Test pattern behavior, not implementation details. +- Use mocking to isolate pattern components. +- Test edge cases and error conditions. +- Verify pattern constraints and invariants. +- Performance test patterns with realistic data sizes. + +## Documentation Standards +- Document pattern intent and motivation clearly. +- Provide class diagrams and interaction diagrams. +- Include code examples with explanations. +- Document known uses and related patterns. +- Explain trade-offs and alternative solutions. + +## Performance Considerations +- Measure performance impact of pattern overhead. +- Use appropriate data structures for pattern implementation. +- Consider memory usage and garbage collection impact. +- Optimize hot paths while maintaining pattern integrity. +- Profile patterns under realistic conditions. + +## Thread Safety +- Document thread safety guarantees clearly. +- Use appropriate synchronization primitives. +- Consider lock-free implementations where possible. +- Test concurrent access scenarios thoroughly. +- Use immutable objects where appropriate. + +## Architectural Patterns +- MVC/MVP/MVVM: Separate concerns appropriately. +- Repository: Abstract data access layer properly. +- Unit of Work: Manage transactional boundaries. +- Service Layer: Encapsulate business logic. +- Domain-Driven Design: Model business domain accurately. \ No newline at end of file diff --git a/.github/instructions/docker.instructions.md b/.github/instructions/docker.instructions.md new file mode 100644 index 0000000..f2d39f4 --- /dev/null +++ b/.github/instructions/docker.instructions.md @@ -0,0 +1,93 @@ +--- +description: Docker containerization best practices and standards +applyTo: '**/Dockerfile*,**/*.dockerfile,**/docker-compose*.yml' +--- + +# Docker Instructions + +## Scope +Applies to `Dockerfile`, `docker-compose.yml`, and container development. + +## Dockerfile Best Practices +- Use official base images from trusted registries. +- Use specific tags instead of `latest` for reproducibility. +- Minimize layer count by combining RUN commands. +- Use multi-stage builds for production images. +- Order instructions by frequency of change (cache optimization). + +## Image Optimization +- Use `.dockerignore` to exclude unnecessary files. +- Remove package managers and build tools in final stage. +- Use minimal base images (Alpine, distroless). +- Clean up caches and temporary files in same RUN command. +- Optimize image layers for better caching. + +## Security Practices +- Run containers as non-root user when possible. +- Use `USER` instruction to set appropriate user. +- Scan images for vulnerabilities regularly. +- Use secrets management for sensitive data. +- Keep base images updated with security patches. + +## Container Configuration +- Use `COPY` instead of `ADD` unless specific features needed. +- Set appropriate `WORKDIR` for clarity. +- Use `ENTRYPOINT` for primary command, `CMD` for default arguments. +- Implement proper signal handling in applications. +- Use health checks to monitor container status. + +## Environment Management +- Use environment variables for configuration. +- Provide sensible defaults for environment variables. +- Use `ARG` for build-time variables. +- Document required environment variables. +- Use `.env` files for local development. + +## Docker Compose +- Use version 3+ compose file format. +- Define services with clear, descriptive names. +- Use named volumes for persistent data. +- Implement proper networking between services. +- Use profiles for different deployment scenarios. + +## Volume Management +- Use named volumes for persistent data. +- Mount configuration files as read-only when possible. +- Avoid mounting sensitive host directories. +- Use tmpfs for temporary file storage. +- Document volume requirements clearly. + +## Networking +- Use custom networks instead of default bridge. +- Implement proper service discovery patterns. +- Use appropriate port mappings. +- Secure inter-container communication. +- Document network dependencies. + +## Logging and Monitoring +- Configure appropriate logging drivers. +- Use structured logging formats. +- Implement health check endpoints. +- Monitor container resource usage. +- Use labels for metadata and organization. + +## Development Workflow +- Use bind mounts for development hot-reloading. +- Implement proper build contexts. +- Use build args for configuration. +- Test images in isolation before deployment. +- Use consistent naming conventions. + +## Production Deployment +- Use orchestration platforms (Kubernetes, Docker Swarm). +- Implement proper resource limits and requests. +- Use rolling updates for zero-downtime deployments. +- Configure proper restart policies. +- Implement service mesh for complex applications. + +## Performance Optimization +- Use appropriate resource limits (CPU, memory). +- Optimize application startup time. +- Use efficient base images. +- Implement proper caching strategies. +- Monitor and tune container performance. \ No newline at end of file diff --git a/.github/instructions/git.instructions.md b/.github/instructions/git.instructions.md new file mode 100644 index 0000000..d4e6e05 --- /dev/null +++ b/.github/instructions/git.instructions.md @@ -0,0 +1,101 @@ +--- +description: Git version control best practices and workflow standards +applyTo: '**/.git*' +--- + +# Git Instructions + +## Scope +Applies to Git repositories, `.gitignore`, `.gitattributes`, and Git workflow practices. + +## Commit Message Conventions +- Use imperative mood in commit messages ("Add feature" not "Added feature"). +- Keep first line under 50 characters as a summary. +- Add blank line before detailed description if needed. +- Reference issue numbers when applicable using hash notation. +- Use conventional commits format: `type(scope): description`. + +## Commit Types +- `feat`: New features +- `fix`: Bug fixes +- `docs`: Documentation changes +- `style`: Code formatting (no logic changes) +- `refactor`: Code restructuring without behavior changes +- `test`: Adding or modifying tests +- `chore`: Maintenance tasks, build updates + +## Branching Strategy +- Use `main` as the primary branch for production-ready code. +- Create feature branches from `main`: `feature/description`. +- Use `hotfix/description` for urgent production fixes. +- Use `release/version` for release preparation. +- Delete merged branches to keep repository clean. + +## Branch Naming Conventions +- Use lowercase with hyphens: `feature/user-authentication`. +- Include issue number when applicable: `fix/123-login-bug`. +- Keep names descriptive but concise. +- Use prefixes: `feature/`, `fix/`, `hotfix/`, `docs/`, `refactor/`. + +## File Management +- Always include a comprehensive `.gitignore` file. +- Ignore build artifacts, dependencies, and IDE files. +- Never commit sensitive information (keys, passwords, tokens). +- Use `.gitattributes` for consistent line endings. +- Keep repository size manageable (use Git LFS for large files). + +## Workflow Best Practices +- Pull latest changes before starting new work. +- Commit early and often with logical chunks. +- Review changes before committing (`git diff --cached`). +- Use interactive rebase to clean up commit history. +- Write meaningful commit messages that explain "why". + +## Code Review Process +- Create pull requests for all changes to main branches. +- Provide clear PR descriptions with context. +- Review code thoroughly before approving. +- Address feedback constructively. +- Use draft PRs for work-in-progress discussions. + +## Tag Management +- Use semantic versioning for releases (v1.2.3). +- Tag stable releases with annotated tags. +- Include release notes with tags. +- Use consistent tag naming conventions. +- Sign important tags for verification. + +## Merge Strategies +- Prefer merge commits for feature integration. +- Use fast-forward merges for simple updates. +- Squash commits for clean history when appropriate. +- Avoid merge conflicts by rebasing before merging. +- Test merged code before pushing to main. + +## Repository Maintenance +- Regular cleanup of merged branches. +- Archive or remove obsolete repositories. +- Keep commit history clean and meaningful. +- Use `git gc` periodically for optimization. +- Monitor repository size and performance. + +## Security Practices +- Use signed commits for authenticity. +- Regularly rotate access tokens and SSH keys. +- Review and audit repository permissions. +- Enable branch protection rules. +- Use secure authentication methods. + +## Collaboration Guidelines +- Establish team conventions for workflow. +- Document branching strategy in repository. +- Use issue templates for consistent reporting. +- Maintain CHANGELOG.md for release tracking. +- Communicate breaking changes clearly. + +## Troubleshooting +- Use `git reflog` to recover lost commits. +- Know how to resolve merge conflicts safely. +- Understand when to use `git reset` vs `git revert`. +- Keep backups of important work. +- Document resolution steps for complex issues. \ No newline at end of file diff --git a/.github/instructions/graphql.instructions.md b/.github/instructions/graphql.instructions.md new file mode 100644 index 0000000..5bc3182 --- /dev/null +++ b/.github/instructions/graphql.instructions.md @@ -0,0 +1,107 @@ +--- +description: GraphQL schema design and query best practices +applyTo: '**/*.{graphql,gql,graphqls}' +--- + +# GraphQL Instructions + +## Scope +Applies to `.graphql`, `.gql`, `.graphqls` files and GraphQL development. + +## Schema Design Principles +- Design schema around business domain, not database structure. +- Use clear, descriptive names for types, fields, and operations. +- Follow GraphQL naming conventions (camelCase for fields). +- Keep schema flat and avoid unnecessary nesting. +- Design for client needs, not server convenience. + +## Type System Best Practices +- Use scalar types appropriately (String, Int, Float, Boolean, ID). +- Create custom scalars for domain-specific types (DateTime, Email, URL). +- Use enums for fixed sets of values. +- Design interfaces for common functionality across types. +- Use unions for fields that can return different types. + +## Field Design +- Make fields nullable by default, non-null only when guaranteed. +- Use descriptive field names that indicate their purpose. +- Avoid abbreviations in field names. +- Group related fields into nested objects. +- Design fields for reusability across different contexts. + +## Query Design +- Structure queries to minimize over-fetching and under-fetching. +- Use fragments for reusable field selections. +- Implement proper pagination with cursor-based approach. +- Design efficient filtering and sorting mechanisms. +- Consider query complexity and depth limiting. + +## Mutation Best Practices +- Design mutations to be atomic and consistent. +- Use input types for complex mutation arguments. +- Return meaningful payloads with success/error information. +- Include client mutation ID for request tracking. +- Design mutations to be idempotent when possible. + +## Error Handling +- Use proper error codes and messages. +- Distinguish between user errors and system errors. +- Provide actionable error messages. +- Use field-level errors when appropriate. +- Implement proper error logging and monitoring. + +## Performance Optimization +- Implement DataLoader for batching and caching. +- Use query complexity analysis to prevent abuse. +- Implement proper depth limiting. +- Cache resolved fields when appropriate. +- Monitor and optimize N+1 query problems. + +## Security Considerations +- Validate and sanitize all input data. +- Implement proper authentication and authorization. +- Use query whitelisting in production. +- Implement rate limiting and query timeouts. +- Sanitize error messages to prevent information leaks. + +## Schema Evolution +- Design schema for backwards compatibility. +- Deprecate fields instead of removing them immediately. +- Use schema versioning strategies when needed. +- Document breaking changes clearly. +- Plan migration strategies for clients. + +## Documentation +- Provide comprehensive descriptions for all types and fields. +- Include examples in field descriptions. +- Document complex business logic and rules. +- Maintain schema changelog for client developers. +- Use GraphQL comments for internal documentation. + +## Subscription Design +- Design subscriptions for real-time data needs. +- Use proper filtering to reduce unnecessary updates. +- Implement subscription cleanup and lifecycle management. +- Consider subscription complexity and resource usage. +- Provide fallback mechanisms for connection issues. + +## Testing Strategies +- Write unit tests for resolvers and business logic. +- Test schema validation and type checking. +- Implement integration tests for complete operations. +- Test error handling scenarios thoroughly. +- Validate performance under load. + +## Code Organization +- Organize schema files by domain or feature. +- Use schema stitching or federation for large schemas. +- Separate business logic from GraphQL layer. +- Implement proper resolver organization. +- Use consistent file and folder naming conventions. + +## Monitoring and Analytics +- Track query performance and usage patterns. +- Monitor error rates and types. +- Analyze field usage for schema optimization. +- Implement proper logging for debugging. +- Use APM tools for performance monitoring. \ No newline at end of file diff --git a/.github/instructions/html.instructions.md b/.github/instructions/html.instructions.md new file mode 100644 index 0000000..c3a2f8f --- /dev/null +++ b/.github/instructions/html.instructions.md @@ -0,0 +1,101 @@ +--- +description: HTML/Web markup standards and accessibility best practices +applyTo: '**/*.{html,htm,xhtml}' +--- + +# HTML / Web Markup Instructions + +## Scope +Applies to `.html`, `.htm`, `.xhtml` files and HTML markup development. + +## Document Structure +- Use HTML5 semantic elements (`
`, `