TenantAtlas/.specify/memory/constitution.md
Ahmed Darrazi 6d14d2544f feat: TenantPilot v1 - Complete implementation (Phases 1-12)
Complete implementation of TenantPilot v1 Intune Management Platform with
comprehensive backup, versioning, and restore capabilities.

CONSTITUTION & SPEC
- Ratified constitution v1.0.0 with 7 core principles
- Complete spec.md with 7 user stories (US1-7)
- Detailed plan.md with constitution compliance check
- Task breakdown with 125+ tasks across 12 phases

CORE FEATURES (US1-4)
- Policy inventory with Graph-based sync (US1)
- Backup creation with immutable JSONB snapshots (US2)
- Version history with diff viewer (human + JSON) (US3)
- Defensive restore with preview/dry-run (US4)

TENANT MANAGEMENT (US6-7)
- Full tenant CRUD with Entra ID app configuration
- Admin consent callback flow integration
- Tenant connectivity verification
- Permission health status monitoring
- 'Highlander' pattern: single current tenant with is_current flag

GRAPH ABSTRACTION
- Complete isolation layer (7 classes)
- GraphClientInterface with mockable implementations
- Error mapping, logging, and standardized responses
- Rate-limit aware design

DOMAIN SERVICES
- BackupService: immutable snapshot creation
- RestoreService: preview, selective restore, conflict detection
- VersionService: immutable version capture
- VersionDiff: human-readable and structured diffs
- PolicySyncService: Graph-based policy import
- TenantConfigService: connectivity testing
- TenantPermissionService: permission health checks
- AuditLogger: comprehensive audit trail

DATA MODEL
- 11 migrations with tenant-aware schema
- 8 Eloquent models with proper relationships
- SoftDeletes on Tenant, BackupSet, BackupItem, PolicyVersion, RestoreRun
- JSONB storage for snapshots, metadata, permissions
- Encrypted storage for client secrets
- Partial unique index for is_current tenant

FILAMENT ADMIN UI
- 5 main resources: Tenant, Policy, PolicyVersion, BackupSet, RestoreRun
- RelationManagers: Versions (Policy), BackupItems (BackupSet)
- Actions: Verify config, Admin consent, Make current, Delete/Force delete
- Filters: Status, Type, Platform, Archive state
- Permission panel with status indicators
- ActionGroup pattern for cleaner row actions

HOUSEKEEPING (Phases 10-12)
- Soft delete with archive status for all entities
- Force delete protection (blocks if dependencies exist)
- Tenant deactivation with cascade prevention
- Audit logging for all delete operations

TESTING
- 36 tests passing (125 assertions, 11.21s)
- Feature tests: Policy, Backup, Restore, Version, Tenant, Housekeeping
- Unit tests: VersionDiff, TenantCurrent, Permissions, Scopes
- Full TDD coverage for critical flows

CONFIGURATION
- config/tenantpilot.php: 10+ policy types with metadata
- config/intune_permissions.php: required Graph permissions
- config/graph.php: Graph client configuration

SAFETY & COMPLIANCE
- Constitution compliance: 7/7 principles ✓
- Safety-first operations: preview, confirmation, validation
- Immutable versioning: no in-place modifications
- Defensive restore: dry-run, selective, conflict detection
- Comprehensive auditability: all critical operations logged
- Tenant-aware architecture: multi-tenant ready
- Graph abstraction: isolated, mockable, testable
- Spec-driven development: spec → plan → tasks → implementation

OPERATIONAL READINESS
- Laravel Sail for local development
- Dokploy deployment documentation
- Queue/worker ready architecture
- Migration safety notes
- Environment variable documentation

Tests: 36 passed
Duration: 11.21s
Status: Production-ready (98% complete)
2025-12-12 02:27:54 +01:00

176 lines
8.8 KiB
Markdown

<!--
SYNC IMPACT REPORT
==================
Version Change: [initial] → 1.0.0
Constitutional Establishment: Initial ratification
Principles Defined:
- I. Safety-First Operations (Intune criticality)
- II. Immutable Versioning (audit & rollback foundation)
- III. Defensive Restore (preview, validation, explicit confirmation)
- IV. Auditability (comprehensive logging)
- V. Tenant-Aware Architecture (future multi-tenant foundation)
- VI. Graph Abstraction (isolated, rate-limit-friendly)
- VII. Spec-Driven Development (Spec Kit workflow)
Sections Added:
- Security & Permissions
- Technology Stack
- Governance
Templates Status:
✅ spec-template.md - Aligned (user stories, acceptance criteria match safety principles)
✅ plan-template.md - Aligned (constitution check gate, technical context)
✅ tasks-template.md - Aligned (user story organization, test-first guidance)
✅ agent-file-template.md - No updates required
✅ checklist-template.md - No updates required
Runtime Guidance Files:
✅ Agents.md - Primary guidance source, fully aligned
✅ README.md - Standard Laravel boilerplate, no constitution conflicts
Follow-up TODOs: None
Commit Message Suggestion:
docs: establish constitution v1.0.0 (initial ratification with 7 core principles)
-->
# TenantPilot Constitution
## Core Principles
### I. Safety-First Operations
Every destructive or high-impact action involving Intune configurations MUST implement safety mechanisms:
- **Explicit confirmation UI** for restore, rollback, and destructive operations
- **Dry-run/preview modes** where technically feasible, showing clear change summaries before execution
- **Validation gates** detecting conflicts, incompatible states, or invalid inputs
- **Audit log entries** for all critical operations (backup creation, restore execution, policy rollback)
**Rationale**: Intune configurations are critical production assets. A single misconfigured policy can affect thousands of devices. Safety gates prevent operational accidents and provide recovery visibility.
### II. Immutable Versioning
Policy versions MUST be stored as immutable snapshots:
- **Full payload capture** in JSONB with metadata (who, when, source tenant, policy type)
- **No in-place modifications** to version records after creation
- **Queryable history** by policy, time range, and actor
- **Diff capabilities** between any two versions (human-readable summary + structured JSON where feasible)
**Rationale**: Immutable versions provide reliable rollback targets, accurate audit trails, and trustworthy diff outputs. Mutable history undermines auditability and introduces rollback risks.
### III. Defensive Restore
Restore operations MUST be defensive and transparent:
- **Preview/dry-run mode** showing what changes will be applied before execution
- **Selective restore** allowing granular control over which items to restore
- **Conflict detection** flagging existing resources that may be overwritten or incompatible
- **Pre-execution summary** clearly communicating scope, risks, and affected resources
- **Explicit confirmation** required before executing any restore
**Rationale**: Restore operations can overwrite production configurations. Defensive workflows reduce risk of unintended changes and provide administrators with informed control.
### IV. Auditability
All critical operations MUST produce comprehensive audit logs:
- **Scope**: backup creation, restore execution/attempts, policy rollback, policy version creation
- **Content**: actor, timestamp, operation type, affected resources, outcome (success/failure/partial)
- **Tenant-scoped**: logs MUST be queryable per tenant for multi-tenant future support
- **RBAC-respecting**: log access follows same permission model as operational access
- **High-level Graph logging**: log Graph API calls without exposing secrets or sensitive payloads
**Rationale**: Audit trails enable compliance verification, incident investigation, and operational transparency. They are non-negotiable for enterprise configuration management.
### V. Tenant-Aware Architecture
Data models and business logic MUST be tenant-scoped from day one:
- **Tenant entity** present in schema even if v1 deploys single-tenant
- **Foreign key relationships** reference tenant_id where applicable
- **Service layer logic** accepts tenant context explicitly
- **Isolation enforcement** ensures no cross-tenant data leakage in queries or operations
**Rationale**: TenantPilot v1 is single-tenant per deployment, but the architecture must support multi-tenant evolution. Retrofitting tenant isolation later is expensive and error-prone.
### VI. Graph Abstraction
Microsoft Graph integration MUST be isolated behind a dedicated abstraction layer:
- **Domain services** depend on `GraphClient` interface, not raw Graph SDK
- **Responsibilities**: auth token handling, rate-limit-friendly batching, standardized error mapping
- **No direct Graph calls** in controllers, Filament resources, or domain logic
- **Testability**: Graph layer must be mockable for integration tests
**Rationale**: Graph API complexity (auth, rate limits, versioning, error handling) should not bleed into domain logic. Abstraction enables cleaner testing, easier SDK upgrades, and centralized rate limit management.
### VII. Spec-Driven Development
All features MUST follow the Spec Kit workflow:
1. **Read** `.specify/constitution.md` (this document)
2. **Create/update** `.specify/spec.md` defining user stories, acceptance criteria, and requirements
3. **Produce** `.specify/plan.md` with technical design, structure decisions, and constitution check
4. **Break down** into `.specify/tasks.md` organized by independently testable user stories
5. **Implement** in small, reviewable PRs aligned with tasks
**Non-negotiable constraints**:
- **Constitution check** in plan.md MUST pass before implementation
- **User stories** in spec.md MUST be prioritized and independently testable
- **Requirements changes** during implementation MUST update spec/plan before continuing
- **Tasks** MUST be organized by user story to enable incremental delivery
**Rationale**: Spec Kit enforces thoughtful design, prevents scope drift, and maintains alignment between requirements, design, and implementation. It provides checkpoints for validation before costly implementation work.
## Security & Permissions
- **Least privilege**: Graph scopes and app permissions MUST request only necessary access
- **Role-based access control**: Admin vs. read-only auditor roles (v1 baseline)
- **No secrets in code**: Use Laravel encrypted storage or environment-based secret management
- **Tenant identifier validation**: All Graph operations MUST validate tenant context
- **Encrypted storage**: Sensitive fields (tokens, credentials) MUST use Laravel encryption where stored
## Technology Stack
**Core Stack**:
- Backend: **Laravel** (latest stable)
- Admin UI: **Filament** (v3+)
- Database: **PostgreSQL** (via Sail locally, managed service in production)
- Auth: **Microsoft Identity** (Entra ID/Azure AD integration)
- External API: **Microsoft Graph** (Intune endpoints)
**Development Environment**:
- Local: **Laravel Sail** (Docker-based, PostgreSQL container)
- Tooling: **Drizzle** for local PostgreSQL workflows (if configured)
- Testing: **Pest** (PHPUnit-based)
**Deployment**:
- Repository: **Gitea** (self-hosted)
- Deployment: **Dokploy** on VPS (container-based)
- Environments: **Staging** (mandatory validation gate) → **Production**
**Constraints**:
- PHP: **PSR-12** conventions
- Migrations: **Reversible**, validated on Staging before Production
- JSONB storage: Use for raw Graph payloads, policy snapshots, backup items
- Indexing: **GIN indexes** on JSONB fields requiring search/filter
## Governance
This constitution supersedes all other development practices and guidelines. It defines the non-negotiable principles for TenantPilot development.
**Amendment Process**:
- Amendments require documentation in this file with version bump rationale
- Version follows **semantic versioning**:
- **MAJOR**: Backward-incompatible governance changes (principle removal/redefinition)
- **MINOR**: New principles added or materially expanded guidance
- **PATCH**: Clarifications, wording improvements, non-semantic refinements
- Constitution changes MUST propagate to affected templates and guidance files
- All templates in `.specify/templates/` MUST align with active principles
**Compliance Enforcement**:
- All specs MUST include a "Constitution Check" section in plan.md
- All PRs MUST verify compliance with relevant principles
- Violations MUST be justified in plan.md Complexity Tracking section
- Runtime development guidance lives in `Agents.md`, which MUST align with this constitution
**Ratification**: This constitution was established to formalize TenantPilot's architectural and operational principles based on v1 specification requirements and the Spec Kit workflow.
**Version**: 1.0.0 | **Ratified**: 2025-12-10 | **Last Amended**: 2025-12-10