<overview>
SmartStack-specific conventions and patterns. This reference is used when reviewing SmartStack projects to ensure compliance with the architecture and security standards.

**IMPORTANT**: All convention validation MUST be delegated to the MCP SmartStack tools. This file documents what to look for; the MCP validates automatically.
</overview>

<mcp_tools>
## MCP SmartStack Tools for Code Review

| Tool | Purpose | When to use |
|------|---------|-------------|
| `mcp__smartstack__validate_conventions` | Validate all SmartStack conventions | Always run first |
| `mcp__smartstack__validate_test_conventions` | Validate test patterns | When tests are in scope |
| `mcp__smartstack__validate_security` | Security-specific checks | Security-focused reviews |
| `mcp__smartstack__analyze_code_quality` | Code metrics analysis | Quality-focused reviews |
| `mcp__smartstack__check_migrations` | EF Core migration conflicts | When migrations are modified |
</mcp_tools>

<architecture>
## SmartStack Architecture (Clean Architecture)

```
SmartStack/
├── SmartStack.Domain/           # Entities, Value Objects, Domain Events
├── SmartStack.Application/      # Services, DTOs, Commands/Queries
├── SmartStack.Infrastructure/   # EF Core, External services
├── SmartStack.Api/              # Controllers, Middleware
└── SmartStack.Web/              # React frontend
```

**Dependency rule**: Dependencies point inward only (Api → Application → Domain).
</architecture>

<entities>
## Entity Conventions

<tenant_aware>
**Tenant-aware entities** (most business entities):
```csharp
public class Order : BaseEntity, ITenantEntity
{
    public Guid TenantId { get; private set; }

    private Order() { } // EF Core constructor

    public static Order Create(Guid tenantId, ...)
    {
        return new Order { TenantId = tenantId, ... };
    }
}
```

**Requirements:**
- [ ] Implements `ITenantEntity`
- [ ] Has `TenantId` property
- [ ] Private parameterless constructor
- [ ] Static `Create()` factory method with `tenantId` as first parameter
</tenant_aware>

<system_entity>
**System entities** (platform-level, no tenant):
```csharp
public class Permission : SystemEntity
{
    private Permission() { }

    public static Permission Create(...)
    {
        return new Permission { ... };
    }
}
```

**Requirements:**
- [ ] Inherits from `SystemEntity`
- [ ] NO `TenantId` property
- [ ] Private parameterless constructor
- [ ] Static `Create()` factory method
</system_entity>
</entities>

<tables>
## Table Naming Conventions

**Schema**: All tables MUST specify schema explicitly.
```csharp
builder.ToTable("auth_users", SchemaConstants.Core);
```

**Prefixes by domain:**
| Prefix | Domain | Examples |
|--------|--------|----------|
| `auth_` | Authentication | auth_users, auth_roles |
| `nav_` | Navigation | nav_menus, nav_routes |
| `cfg_` | Configuration | cfg_settings, cfg_features |
| `ai_` | AI/Prompts | ai_prompts, ai_models |
| `ntf_` | Notifications | ntf_templates, ntf_logs |
| `wkf_` | Workflows | wkf_definitions, wkf_instances |
| `doc_` | Documents | doc_files, doc_versions |
| `tkt_` | Tickets/Support | tkt_tickets, tkt_comments |

**Schemas:**
- `core` (SchemaConstants.Core): SmartStack platform tables
- `extensions` (SchemaConstants.Extensions): Client-specific tables
</tables>

<migrations>
## Migration Naming

**Format**: `{context}_v{version}_{sequence}_{Description}.cs`

**Examples:**
- `core_v1.0.0_001_CreateAuthUsers.cs`
- `core_v1.2.0_001_AddUserProfiles.cs`
- `extensions_v1.0.0_001_CreateClientOrders.cs`

**Rules:**
- [ ] Context: `core` or `extensions`
- [ ] Version: semver format (1.0.0)
- [ ] Sequence: 3-digit padded (001, 002)
- [ ] Description: PascalCase, descriptive
</migrations>

<controllers>
## Controller Conventions

**NavRoute attribute** (preferred):
```csharp
[ApiController]
[NavRoute("platform.administration.users")]
public class UsersController : ControllerBase
{
    // Routes generated from NavRoute: /api/platform/administration/users
}
```

**NavRoute format:**
- Lowercase only
- Dot-separated hierarchy
- Minimum 2 levels: `context.application`
- Full path: `context.application.module`

**Examples:**
- `platform.administration.users`
- `platform.administration.roles`
- `business.crm.contacts`
- `personal.myspace.dashboard`
</controllers>

<services>
## Service Conventions

**Interface pattern:**
```csharp
// Interface
public interface IUserService
{
    Task<UserDto> GetByIdAsync(Guid id, CancellationToken ct);
    Task<UserDto> CreateAsync(CreateUserDto dto, CancellationToken ct);
}

// Implementation
public class UserService : IUserService
{
    // ...
}
```

**Requirements:**
- [ ] Interface named `I{Name}Service`
- [ ] Implementation named `{Name}Service`
- [ ] All methods async with CancellationToken
- [ ] Return DTOs, not entities
</services>

<security>
## SmartStack Security Patterns

<multi_tenant>
**Multi-tenant isolation:**
- ALL queries MUST filter by TenantId (automatic via EF Core global filters)
- NEVER expose TenantId in URLs
- NEVER allow cross-tenant data access
- Create methods MUST require tenantId parameter

**Check for violations:**
```csharp
// BAD: No tenant filter
var users = await _context.Users.ToListAsync();

// GOOD: Tenant filter applied (via global filter or explicit)
var users = await _context.Users
    .Where(u => u.TenantId == _tenantId)
    .ToListAsync();
```
</multi_tenant>

<authorization>
**RBAC with NavRoute:**
- Controllers use `[NavRoute]` for automatic permission mapping
- Permissions follow NavRoute pattern: `{navroute}.{action}`
- Actions: `read`, `create`, `update`, `delete`, `*` (wildcard)

**Example permissions:**
- `platform.administration.users.read`
- `platform.administration.users.create`
- `platform.administration.users.*` (all actions)
</authorization>

<input_validation>
**FluentValidation:**
```csharp
public class CreateUserDtoValidator : AbstractValidator<CreateUserDto>
{
    public CreateUserDtoValidator()
    {
        RuleFor(x => x.Email)
            .NotEmpty()
            .EmailAddress()
            .MaximumLength(256);
    }
}
```
</input_validation>
</security>

<tests>
## Test Conventions

**Naming pattern:** `{Method}_When{Condition}_Should{Result}`
```csharp
public class UserServiceTests
{
    [Fact]
    public async Task GetById_WhenUserExists_ShouldReturnUser() { }

    [Fact]
    public async Task GetById_WhenUserNotFound_ShouldThrowNotFoundException() { }

    [Fact]
    public async Task Create_WhenValidDto_ShouldCreateAndReturnUser() { }
}
```

**Structure:**
```
Tests/
├── Unit/
│   ├── Services/
│   └── Validators/
└── Integration/
    └── Controllers/
```

**Patterns:**
- [ ] AAA pattern (Arrange, Act, Assert)
- [ ] FluentAssertions for assertions
- [ ] Moq for mocking
- [ ] Tenant isolation tests for all tenant-aware services
</tests>

<review_checklist>
## SmartStack Code Review Checklist

**Run MCP validation first:**
```
mcp__smartstack__validate_conventions checks: ["all"]
```

**Then verify manually:**

<security_checks>
### Security (BLOCKING)
- [ ] No hardcoded credentials or secrets
- [ ] TenantId isolation enforced
- [ ] Authorization on all endpoints
- [ ] Input validation present
- [ ] No SQL injection risks (use EF Core properly)
</security_checks>

<architecture_checks>
### Architecture (BLOCKING)
- [ ] Entities use correct base class (BaseEntity/SystemEntity)
- [ ] Services have interfaces
- [ ] Controllers use [NavRoute]
- [ ] Migrations follow naming convention
</architecture_checks>

<quality_checks>
### Quality (SUGGESTION)
- [ ] Tests exist for new functionality
- [ ] Factory methods used for entity creation
- [ ] DTOs used for API boundaries
- [ ] Async methods have CancellationToken
</quality_checks>
</review_checklist>

<sources>
- SmartStack Architecture Documentation
- SmartStack.mcp validation tools
- Clean Architecture by Robert C. Martin
</sources>
