From d21679bb1e69c5337d2bfb1eb6b55478e8793049 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 21 Dec 2025 10:29:40 +0000 Subject: [PATCH 1/3] =?UTF-8?q?=F0=9F=93=9D=20docs:=20add=20comprehensive?= =?UTF-8?q?=20project=20documentation=20with=20TOGAF=20EA=20principles?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - Create docs/PROJECT-OVERVIEW.md with complete product specification - Executive summary and vision statement - Stakeholder personas and role matrix - Core UX principles (glanceable, zero-distraction, etc.) - Comprehensive functional scope (10 feature areas) - Non-functional requirements (reliability, performance, security) - Create docs/ARCHITECTURE.md with TOGAF-compliant architecture - Architecture principles (business, data, application, technology) - Business capability model and process maps - Data architecture with domain models and storage strategy - Application architecture with bounded contexts - Technology reference model and platform matrix - Security and integration architecture - Deployment architecture for self-hosting - Create docs/ROADMAP.md with phased implementation plan - Six development phases from Foundation to Ecosystem - Detailed scope items per phase with checklists - Dependency map and critical path - Risk register for technical and product risks - Create 7 Architecture Decision Records (ADRs): - ADR-001: TypeScript as Primary Language - ADR-002: React as UI Framework - ADR-003: Local-First Data Architecture - ADR-004: Two-Way Sync Initially Google-Only - ADR-005: Magic Import Requires Approval - ADR-006: Zero-Distraction Design Principle - ADR-007: Self-Hosting as Primary Model - Update CLAUDE.md with TOGAF EA principles and governance - Add links to new documentation - Add Architecture Development Method (ADM) phases - Add core architecture principles (BP, DP, AP, TP) - Add architecture governance process - Expand scopes for new functional areas --- CLAUDE.md | 98 ++ docs/ARCHITECTURE.md | 906 ++++++++++++++++++ docs/PROJECT-OVERVIEW.md | 653 +++++++++++++ docs/ROADMAP.md | 708 ++++++++++++++ docs/adr/ADR-000-template.md | 94 ++ .../ADR-001-typescript-primary-language.md | 147 +++ docs/adr/ADR-002-react-ui-framework.md | 159 +++ docs/adr/ADR-003-local-first-architecture.md | 169 ++++ docs/adr/ADR-004-two-way-sync-google-first.md | 184 ++++ docs/adr/ADR-005-magic-import-approval.md | 183 ++++ .../adr/ADR-006-zero-distraction-principle.md | 179 ++++ docs/adr/ADR-007-self-hosting-first.md | 200 ++++ docs/adr/README.md | 38 + 13 files changed, 3718 insertions(+) create mode 100644 docs/ARCHITECTURE.md create mode 100644 docs/PROJECT-OVERVIEW.md create mode 100644 docs/ROADMAP.md create mode 100644 docs/adr/ADR-000-template.md create mode 100644 docs/adr/ADR-001-typescript-primary-language.md create mode 100644 docs/adr/ADR-002-react-ui-framework.md create mode 100644 docs/adr/ADR-003-local-first-architecture.md create mode 100644 docs/adr/ADR-004-two-way-sync-google-first.md create mode 100644 docs/adr/ADR-005-magic-import-approval.md create mode 100644 docs/adr/ADR-006-zero-distraction-principle.md create mode 100644 docs/adr/ADR-007-self-hosting-first.md create mode 100644 docs/adr/README.md diff --git a/CLAUDE.md b/CLAUDE.md index 499a4a9..c297b93 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -6,6 +6,93 @@ This document defines the expectations, standards, and development practices for **Luminous** is a digital family command center designed for large, portrait-mounted touchscreens. It provides a calm, glanceable view of household schedules, tasks, and reminders. +For comprehensive project documentation, see: +- [Project Overview](./docs/PROJECT-OVERVIEW.md) - Complete product specification +- [Architecture](./docs/ARCHITECTURE.md) - Technical architecture documentation +- [Roadmap](./docs/ROADMAP.md) - Development phases and milestones +- [Architecture Decision Records](./docs/adr/) - Key design decisions + +--- + +## TOGAF Enterprise Architecture Principles + +Luminous follows TOGAF (The Open Group Architecture Framework) principles for enterprise architecture. All architectural decisions must align with these principles. + +### Architecture Development Method (ADM) + +We follow TOGAF ADM phases in our development process: + +| Phase | Description | Luminous Application | +|-------|-------------|---------------------| +| **Preliminary** | Framework and principles | Establish guidelines (this document) | +| **A: Vision** | Architecture vision | Project overview and goals | +| **B: Business** | Business architecture | Feature capabilities and processes | +| **C: Information** | Data architecture | Domain models and data flows | +| **C: Application** | Application architecture | Component design and boundaries | +| **D: Technology** | Technology architecture | Technology stack decisions | +| **E: Opportunities** | Solutions and migration | Roadmap phases | +| **F: Migration** | Planning | Phase transitions | +| **G: Governance** | Implementation governance | Code reviews, ADRs | +| **H: Change** | Architecture change | Version updates, migrations | + +### Core Architecture Principles + +#### Business Principles + +| ID | Principle | Description | +|----|-----------|-------------| +| BP-1 | **Family-Centric Design** | All features must serve real family coordination needs | +| BP-2 | **Zero Distraction** | The product differentiates by what it omits | +| BP-3 | **Inclusive by Default** | Design for all ages and abilities | +| BP-4 | **Privacy as a Feature** | Users own and control their data | + +#### Data Principles + +| ID | Principle | Description | +|----|-----------|-------------| +| DP-1 | **Local-First Data** | Data stored locally first; sync is secondary | +| DP-2 | **User Data Ownership** | Users can export and self-host | +| DP-3 | **Single Source of Truth** | Clear ownership rules per data type | +| DP-4 | **Data Minimization** | Collect only what's necessary | + +#### Application Principles + +| ID | Principle | Description | +|----|-----------|-------------| +| AP-1 | **Modular Composability** | Features evolve independently | +| AP-2 | **Cross-Platform Consistency** | Unified experience across platforms | +| AP-3 | **Graceful Degradation** | Partial failures shouldn't block usage | +| AP-4 | **Performance on Constraints** | Optimize for modest hardware | + +#### Technology Principles + +| ID | Principle | Description | +|----|-----------|-------------| +| TP-1 | **Open Source Stack** | No proprietary dependencies in core | +| TP-2 | **Commodity Hardware** | ARM and x86 support; no specialized hardware | +| TP-3 | **Standards-Based Integration** | OAuth 2.0, CalDAV, REST/GraphQL | +| TP-4 | **Operational Simplicity** | Auto-updates, self-healing, minimal config | + +### Architecture Governance + +1. **All significant decisions require an ADR** + - New technology choices + - Architectural pattern changes + - Integration approaches + - Data model changes + +2. **ADRs must follow the template** in `/docs/adr/ADR-000-template.md` + +3. **Review process** + - ADRs proposed via pull request + - Minimum one reviewer approval + - Discussion period before acceptance + +4. **Principle compliance checks** in code reviews: + - Does this change align with architecture principles? + - Does it follow the bounded context boundaries? + - Is it appropriately documented? + --- ## Core Development Principles @@ -149,14 +236,25 @@ Use scopes to indicate the affected area: - `calendar` - Calendar-related changes - `tasks` - Task/chore management +- `routines` - Routine management +- `rewards` - Rewards and gamification +- `meals` - Meal planning and recipes +- `lists` - List management +- `profiles` - Profile and household management - `notes` - Notes and reminders - `ui` - General UI components - `display` - Display/kiosk mode +- `mobile` - Mobile application +- `web` - Web application +- `sync` - Synchronization engine +- `import` - Magic import feature - `config` - Configuration - `api` - API/backend changes - `auth` - Authentication - `db` - Database changes - `infra` - Infrastructure +- `docs` - Documentation +- `adr` - Architecture Decision Records ### Commit Examples diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md new file mode 100644 index 0000000..7030364 --- /dev/null +++ b/docs/ARCHITECTURE.md @@ -0,0 +1,906 @@ +# Luminous Architecture Document + +> **Document Version:** 1.0.0 +> **Last Updated:** 2025-12-21 +> **Status:** Draft +> **TOGAF Phase:** Phase B-D (Architecture Development) + +--- + +## Table of Contents + +1. [Architecture Principles](#architecture-principles) +2. [Architecture Vision](#architecture-vision) +3. [Business Architecture](#business-architecture) +4. [Data Architecture](#data-architecture) +5. [Application Architecture](#application-architecture) +6. [Technology Architecture](#technology-architecture) +7. [Security Architecture](#security-architecture) +8. [Integration Architecture](#integration-architecture) +9. [Deployment Architecture](#deployment-architecture) +10. [Architecture Decisions](#architecture-decisions) + +--- + +## Architecture Principles + +Following TOGAF Enterprise Architecture principles, Luminous adheres to these foundational principles across all architecture domains: + +### Business Principles + +| Principle | Rationale | Implications | +|-----------|-----------|--------------| +| **BP-1: Family-Centric Design** | All features must serve real family coordination needs | Features are validated against family use cases; no feature creep toward entertainment | +| **BP-2: Zero Distraction** | The product differentiates by what it omits | Explicitly exclude entertainment, browsing, and social features | +| **BP-3: Inclusive by Default** | Families include members of all ages and abilities | Design for youngest (6+) and oldest users; accessibility is mandatory | +| **BP-4: Privacy as a Feature** | Families trust us with sensitive information | Self-hosting option; no mandatory telemetry; data minimization | + +### Data Principles + +| Principle | Rationale | Implications | +|-----------|-----------|--------------| +| **DP-1: Local-First Data** | Reliability requires offline capability | Data stored locally first; sync is secondary; no cloud dependency | +| **DP-2: User Data Ownership** | Families own their information | Export in open formats; no lock-in; self-hosting support | +| **DP-3: Single Source of Truth** | Conflicts create confusion | Clear ownership rules per data type; deterministic conflict resolution | +| **DP-4: Data Minimization** | Collect only what's necessary | No tracking; minimal metadata; privacy by design | + +### Application Principles + +| Principle | Rationale | Implications | +|-----------|-----------|--------------| +| **AP-1: Modular Composability** | Features evolve independently | Bounded contexts; clean interfaces; plugin architecture | +| **AP-2: Cross-Platform Consistency** | Experience must be unified | Shared design system; consistent behavior across display/mobile/web | +| **AP-3: Graceful Degradation** | Partial failures shouldn't block usage | Offline mode; fallback behaviors; error boundaries | +| **AP-4: Performance on Constraints** | Target hardware is modest | Optimize for Raspberry Pi 4; minimize memory; efficient rendering | + +### Technology Principles + +| Principle | Rationale | Implications | +|-----------|-----------|--------------| +| **TP-1: Open Source Stack** | Aligned with project values; community contribution | No proprietary dependencies in core; permissive or copyleft licenses | +| **TP-2: Commodity Hardware** | Accessibility and affordability | ARM and x86 support; no specialized hardware requirements | +| **TP-3: Standards-Based Integration** | Interoperability with existing systems | OAuth 2.0; CalDAV/ICS; REST/GraphQL APIs; OpenAPI specs | +| **TP-4: Operational Simplicity** | Self-hosters need low maintenance | Auto-updates; self-healing; minimal configuration | + +--- + +## Architecture Vision + +### Target State Architecture + +``` ++------------------------------------------------------------------+ +| LUMINOUS ECOSYSTEM | ++------------------------------------------------------------------+ +| | +| +-------------------+ +-------------------+ +----------------+ | +| | DISPLAY APP | | MOBILE APP | | WEB APP | | +| | (Kiosk Mode) | | (iOS/Android) | | (Browser) | | +| +--------+----------+ +--------+----------+ +-------+--------+ | +| | | | | +| +----------------------+---------------------+ | +| | | +| +-------------v--------------+ | +| | LUMINOUS CORE | | +| | (Shared Domain Logic) | | +| +-------------+--------------+ | +| | | +| +----------------------+---------------------+ | +| | | | | +| +--------v----------+ +--------v----------+ +-------v--------+ | +| | LOCAL STORAGE | | SYNC ENGINE | | INTEGRATIONS | | +| | (SQLite/OPFS) | | (CRDT-based) | | (Calendar, | | +| +-------------------+ +-------------------+ | Weather) | | +| +----------------+ | +| | ++------------------------------------------------------------------+ + | + v ++------------------------------------------------------------------+ +| OPTIONAL SYNC SERVER | +| +-------------------+ +-------------------+ +----------------+ | +| | AUTH SERVICE | | SYNC SERVICE | | PUSH SERVICE | | +| +-------------------+ +-------------------+ +----------------+ | ++------------------------------------------------------------------+ +``` + +### Key Architecture Characteristics + +| Characteristic | Priority | Description | +|----------------|----------|-------------| +| **Reliability** | Critical | 24/7 operation; auto-recovery; crash resilience | +| **Usability** | Critical | Child-friendly; glanceable; intuitive | +| **Performance** | High | Fast rendering; low latency; efficient memory | +| **Scalability** | Medium | Support large families; many calendars | +| **Portability** | High | Cross-platform; commodity hardware | +| **Maintainability** | High | Clean code; comprehensive testing; documentation | + +--- + +## Business Architecture + +### Business Capability Model + +``` +LUMINOUS FAMILY HUB +├── SCHEDULING CAPABILITY +│ ├── Calendar Aggregation +│ ├── Event Management +│ ├── Reminder Management +│ └── Schedule Sharing +│ +├── TASK MANAGEMENT CAPABILITY +│ ├── Chore Management +│ ├── Routine Management +│ ├── Progress Tracking +│ └── Reward Management +│ +├── HOUSEHOLD MANAGEMENT CAPABILITY +│ ├── Profile Management +│ ├── Meal Planning +│ ├── List Management +│ └── Caregiver Coordination +│ +├── INFORMATION DISPLAY CAPABILITY +│ ├── Dashboard Rendering +│ ├── Notification Display +│ ├── Ambient Information +│ └── Privacy Mode +│ +└── PLATFORM CAPABILITY + ├── Authentication & Authorization + ├── Data Synchronization + ├── External Integration + └── System Administration +``` + +### Business Process Map + +#### BP-001: Daily Family Coordination + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ DAILY FAMILY COORDINATION │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ Morning │───▶│ View │───▶│ Complete │───▶│ Receive │ │ +│ │ Wake │ │ Today │ │ Routines │ │ Rewards │ │ +│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ +│ │ │ +│ ▼ │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ Check │───▶│ Handle │───▶│ Update │ │ +│ │ Calendar │ │ Events │ │ Status │ │ +│ └──────────┘ └──────────┘ └──────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Actor-Role Matrix + +| Actor | Calendar | Chores | Lists | Profiles | Settings | +|-------|----------|--------|-------|----------|----------| +| **Household Admin** | Full | Full | Full | Full | Full | +| **Adult Member** | Full | Full | Full | Own | View | +| **Teen Member** | Own + Family | Own | Shared | Own | None | +| **Child Member** | View | Complete | View | View | None | +| **External Caregiver** | View (limited) | View | View | View (care info) | None | + +--- + +## Data Architecture + +### Domain Model + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ DOMAIN MODEL │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ HOUSEHOLD │────────▶│ PROFILE │ │ +│ │ (Aggregate) │ 1 * │ (Entity) │ │ +│ └────────┬────────┘ └────────┬────────┘ │ +│ │ │ │ +│ │ 1 │ * │ +│ ▼ ▼ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ CALENDAR │ │ CHORE │ │ +│ │ CONNECTION │ │ (Entity) │ │ +│ │ (Entity) │ └────────┬────────┘ │ +│ └────────┬────────┘ │ │ +│ │ │ │ +│ │ * │ * │ +│ ▼ ▼ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ EVENT │ │ COMPLETION │ │ +│ │ (Entity) │ │ (Value Obj) │ │ +│ └─────────────────┘ └─────────────────┘ │ +│ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ ROUTINE │────────▶│ ROUTINE STEP │ │ +│ │ (Aggregate) │ 1 * │ (Value Obj) │ │ +│ └─────────────────┘ └─────────────────┘ │ +│ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ LIST │────────▶│ LIST ITEM │ │ +│ │ (Aggregate) │ 1 * │ (Entity) │ │ +│ └─────────────────┘ └─────────────────┘ │ +│ │ +│ ┌─────────────────┐ ┌─────────────────┐ │ +│ │ MEAL PLAN │────────▶│ RECIPE │ │ +│ │ (Aggregate) │ * * │ (Entity) │ │ +│ └─────────────────┘ └─────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Core Entities + +#### Household (Aggregate Root) + +```typescript +interface Household { + id: HouseholdId; + name: string; + timezone: Timezone; + createdAt: DateTime; + settings: HouseholdSettings; + profiles: Profile[]; + calendarConnections: CalendarConnection[]; +} +``` + +#### Profile + +```typescript +interface Profile { + id: ProfileId; + householdId: HouseholdId; + displayName: string; + avatarUrl?: string; + color: HexColor; + role: ProfileRole; // ADMIN | ADULT | TEEN | CHILD | PET + birthday?: LocalDate; + caregiverInfo?: CaregiverInfo; + permissions: Permission[]; + pinHash?: string; + createdAt: DateTime; +} + +interface CaregiverInfo { + allergies: string[]; + medications: string[]; + emergencyContacts: Contact[]; + doctorInfo?: Contact; + notes: string; +} +``` + +#### Event + +```typescript +interface Event { + id: EventId; + householdId: HouseholdId; + calendarConnectionId?: CalendarConnectionId; + externalId?: string; + title: string; + description?: string; + location?: Location; + startTime: DateTime; + endTime: DateTime; + allDay: boolean; + recurrence?: RecurrenceRule; + assignedProfiles: ProfileId[]; + reminders: Reminder[]; + isCountdown: boolean; + createdAt: DateTime; + updatedAt: DateTime; + syncStatus: SyncStatus; +} +``` + +#### Chore + +```typescript +interface Chore { + id: ChoreId; + householdId: HouseholdId; + title: string; + description?: string; + icon: IconId; + assignedProfiles: ProfileId[]; // empty = "anyone" + recurrence?: RecurrenceRule; + dueTime?: LocalTime; + pointValue: number; + priority?: Priority; + completions: ChoreCompletion[]; + createdAt: DateTime; +} + +interface ChoreCompletion { + date: LocalDate; + completedBy: ProfileId; + completedAt: DateTime; + pointsAwarded: number; +} +``` + +### Data Storage Strategy + +| Data Type | Storage | Sync Strategy | Conflict Resolution | +|-----------|---------|---------------|---------------------| +| **Household Config** | Local SQLite | Full sync | Last-write-wins with vector clock | +| **Profiles** | Local SQLite | Full sync | Server authority | +| **Events (internal)** | Local SQLite | CRDT merge | Operational transform | +| **Events (external)** | Cached | Pull from source | Source authority | +| **Chores/Routines** | Local SQLite | CRDT merge | Operational transform | +| **Lists** | Local SQLite | CRDT merge | Append-only with tombstones | +| **Completions** | Local SQLite | Append-only | No conflicts (immutable) | +| **Media (avatars)** | Local filesystem | Hash-addressed | Content-addressed (no conflicts) | + +### Data Flow Diagram + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ DATA FLOW ARCHITECTURE │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ EXTERNAL SOURCES │ +│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ +│ │ Google │ │ Outlook │ │ iCloud │ │ ICS │ │ +│ │ Calendar │ │ Calendar │ │ Calendar │ │ Feeds │ │ +│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ +│ │ │ │ │ │ +│ └─────────────┴──────┬──────┴─────────────┘ │ +│ ▼ │ +│ ┌─────────────────┐ │ +│ │ SYNC ENGINE │ │ +│ │ (Adapter per │ │ +│ │ provider) │ │ +│ └────────┬────────┘ │ +│ │ │ +│ ▼ │ +│ ┌────────────────────────────────────────────────────────┐ │ +│ │ LOCAL DATA STORE │ │ +│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ +│ │ │ Events │ │ Chores │ │ Lists │ ... │ │ +│ │ └──────────┘ └──────────┘ └──────────┘ │ │ +│ └────────────────────────┬───────────────────────────────┘ │ +│ │ │ +│ ┌───────────────────┼───────────────────┐ │ +│ ▼ ▼ ▼ │ +│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ +│ │ DISPLAY │ │ MOBILE │ │ WEB │ │ +│ │ APP │◀───▶│ APP │◀───▶│ APP │ │ +│ └────────────┘ └────────────┘ └────────────┘ │ +│ │ │ │ │ +│ └───────────────────┴───────────────────┘ │ +│ │ │ +│ ▼ │ +│ ┌─────────────────┐ │ +│ │ SYNC SERVER │ (Optional) │ +│ │ (Multi-device) │ │ +│ └─────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +--- + +## Application Architecture + +### Bounded Contexts + +Following Domain-Driven Design, Luminous is organized into these bounded contexts: + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ BOUNDED CONTEXTS │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ SCHEDULING │ │ TASK MANAGEMENT │ │ HOUSEHOLD │ │ +│ │ CONTEXT │ │ CONTEXT │ │ CONTEXT │ │ +│ │ │ │ │ │ │ │ +│ │ - Calendar │ │ - Chore │ │ - Profile │ │ +│ │ - Event │ │ - Routine │ │ - Household │ │ +│ │ - CalendarConn │ │ - Completion │ │ - CaregiverInfo │ │ +│ │ - Reminder │ │ - Reward │ │ - Permission │ │ +│ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ +│ │ +│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ MEAL PLANNING │ │ LIST MANAGEMENT │ │ DISPLAY │ │ +│ │ CONTEXT │ │ CONTEXT │ │ CONTEXT │ │ +│ │ │ │ │ │ │ │ +│ │ - MealPlan │ │ - List │ │ - Dashboard │ │ +│ │ - Recipe │ │ - ListItem │ │ - Widget │ │ +│ │ - Ingredient │ │ - Template │ │ - PrivacyMode │ │ +│ │ - DietaryPref │ │ │ │ - SleepMode │ │ +│ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ +│ │ +│ ┌──────────────────┐ ┌──────────────────┐ │ +│ │ MAGIC IMPORT │ │ INTEGRATION │ │ +│ │ CONTEXT │ │ CONTEXT │ │ +│ │ │ │ │ │ +│ │ - ImportRequest │ │ - CalendarSync │ │ +│ │ - ParsedContent │ │ - WeatherFetch │ │ +│ │ - ApprovalQueue │ │ - InstacartLink │ │ +│ │ │ │ - PushNotify │ │ +│ └──────────────────┘ └──────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Application Component Model + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ APPLICATION COMPONENTS │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ PRESENTATION LAYER │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ │ +│ │ │ Display │ │ Mobile │ │ Web │ │ Caregiver │ │ │ +│ │ │ App │ │ App │ │ App │ │ Portal │ │ │ +│ │ └────┬────┘ └────┬────┘ └────┬────┘ └──────┬──────┘ │ │ +│ └───────┼────────────┼────────────┼──────────────┼───────────┘ │ +│ │ │ │ │ │ +│ └────────────┴─────┬──────┴──────────────┘ │ +│ │ │ +│ SHARED UI LAYER ▼ │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ DESIGN SYSTEM │ │ +│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ │ +│ │ │ Theme │ │ Core │ │ Form │ │ Composite │ │ │ +│ │ │ Tokens │ │ Widgets │ │ Elements│ │ Components │ │ │ +│ │ └─────────┘ └─────────┘ └─────────┘ └─────────────┘ │ │ +│ └─────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ DOMAIN LAYER ▼ │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ LUMINOUS CORE │ │ +│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │ +│ │ │ Domain │ │ Domain │ │ Domain │ ... │ │ +│ │ │ Models │ │ Services │ │ Events │ │ │ +│ │ └───────────┘ └───────────┘ └───────────┘ │ │ +│ └─────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ INFRASTRUCTURE LAYER ▼ │ +│ ┌─────────────────────────────────────────────────────────────┐ │ +│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │ +│ │ │ Data │ │ Sync │ │ External │ │ │ +│ │ │Repository │ │ Engine │ │ Adapters │ │ │ +│ │ └───────────┘ └───────────┘ └───────────┘ │ │ +│ └─────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Module Structure + +``` +luminous/ +├── packages/ +│ ├── core/ # Shared domain logic +│ │ ├── src/ +│ │ │ ├── domain/ # Domain models and entities +│ │ │ │ ├── household/ +│ │ │ │ ├── scheduling/ +│ │ │ │ ├── tasks/ +│ │ │ │ ├── lists/ +│ │ │ │ └── meals/ +│ │ │ ├── services/ # Domain services +│ │ │ ├── events/ # Domain events +│ │ │ └── ports/ # Repository interfaces +│ │ └── package.json +│ │ +│ ├── ui/ # Shared design system +│ │ ├── src/ +│ │ │ ├── tokens/ # Design tokens +│ │ │ ├── primitives/ # Base components +│ │ │ ├── components/ # Composite components +│ │ │ └── themes/ # Theme definitions +│ │ └── package.json +│ │ +│ ├── sync/ # Synchronization engine +│ │ ├── src/ +│ │ │ ├── crdt/ # CRDT implementations +│ │ │ ├── adapters/ # Calendar provider adapters +│ │ │ └── engine/ # Sync orchestration +│ │ └── package.json +│ │ +│ └── import/ # Magic import service +│ ├── src/ +│ │ ├── parsers/ # Input parsers (email, photo, etc.) +│ │ ├── extractors/ # Content extractors +│ │ └── queue/ # Approval queue +│ └── package.json +│ +├── apps/ +│ ├── display/ # Wall display application +│ │ ├── src/ +│ │ │ ├── views/ # Main display views +│ │ │ ├── widgets/ # Display widgets +│ │ │ ├── kiosk/ # Kiosk mode management +│ │ │ └── store/ # State management +│ │ └── package.json +│ │ +│ ├── mobile/ # Mobile application +│ │ ├── src/ +│ │ │ ├── screens/ # App screens +│ │ │ ├── navigation/ # Navigation config +│ │ │ ├── push/ # Push notification handling +│ │ │ └── store/ # State management +│ │ └── package.json +│ │ +│ ├── web/ # Web application +│ │ ├── src/ +│ │ │ ├── pages/ # Page components +│ │ │ ├── layouts/ # Layout components +│ │ │ └── store/ # State management +│ │ └── package.json +│ │ +│ └── server/ # Optional sync server +│ ├── src/ +│ │ ├── api/ # REST/GraphQL API +│ │ ├── auth/ # Authentication +│ │ ├── sync/ # Sync coordination +│ │ └── push/ # Push notification service +│ └── package.json +│ +├── tools/ # Development tools +│ ├── cli/ # CLI tooling +│ └── scripts/ # Build scripts +│ +└── docs/ # Documentation + ├── adr/ # Architecture Decision Records + └── api/ # API documentation +``` + +--- + +## Technology Architecture + +### Technology Stack + +| Layer | Technology | Rationale | +|-------|------------|-----------| +| **Language** | TypeScript | Type safety, tooling, ecosystem | +| **UI Framework** | React | Component model, ecosystem, cross-platform (React Native) | +| **State Management** | Zustand | Lightweight, TypeScript-first, easy testing | +| **Local Database** | SQLite (via sql.js) / OPFS | Offline-first, portable, performant | +| **Sync Protocol** | Custom CRDT-based | Conflict-free offline operation | +| **Mobile** | React Native | Code sharing with display/web | +| **Desktop/Display** | Electron or Tauri | Native kiosk capabilities | +| **Server (Optional)** | Node.js + Fastify | TypeScript consistency, performance | +| **Build System** | Turborepo | Monorepo management, caching | +| **Testing** | Vitest + Playwright | Fast unit tests, E2E coverage | + +### Technology Reference Model + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ TECHNOLOGY REFERENCE MODEL │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ DEVELOPMENT PLATFORM │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ TypeScript 5.x │ Node.js 20 LTS │ pnpm │ Turborepo │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ APPLICATION FRAMEWORKS │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ React 19 │ React Native │ Electron/Tauri │ Fastify │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ UI/UX INFRASTRUCTURE │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ Tailwind CSS │ Radix UI │ Framer Motion │ React Aria │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ DATA INFRASTRUCTURE │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ SQLite (sql.js) │ OPFS │ IndexedDB │ Yjs (CRDT) │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ INTEGRATION INFRASTRUCTURE │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ OAuth 2.0 │ CalDAV │ REST │ WebSocket │ Web Push │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ QUALITY INFRASTRUCTURE │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ Vitest │ Playwright │ ESLint │ Prettier │ TypeScript ESLint │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ DEPLOYMENT INFRASTRUCTURE │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ Docker │ GitHub Actions │ Renovate │ Changesets │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Platform Matrix + +| Platform | Runtime | Database | Notes | +|----------|---------|----------|-------| +| **Display (Linux)** | Electron | SQLite | Kiosk mode, ARM64 support | +| **Display (Raspberry Pi)** | Electron/Chromium | SQLite | Optimized for Pi 4/5 | +| **Mobile (iOS)** | React Native | SQLite | App Store distribution | +| **Mobile (Android)** | React Native | SQLite | Play Store + sideload | +| **Web** | Browser | OPFS/IndexedDB | Progressive Web App | +| **Server** | Node.js | PostgreSQL/SQLite | Docker deployment | + +--- + +## Security Architecture + +### Security Model + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ SECURITY ARCHITECTURE │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ AUTHENTICATION │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ +│ │ │ Local PIN │ │ OAuth 2.0 │ │ Passkey │ │ │ +│ │ │ (Display) │ │ (Mobile) │ │ (Future) │ │ │ +│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ AUTHORIZATION │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ Role-Based Access Control (RBAC) │ │ +│ │ ┌────────────────────────────────────────────────────────┐ │ │ +│ │ │ ADMIN → ADULT → TEEN → CHILD → CAREGIVER (External) │ │ │ +│ │ └────────────────────────────────────────────────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +│ DATA PROTECTION │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ +│ │ │ Encryption │ │ Encryption │ │ Secure │ │ │ +│ │ │ at Rest │ │ in Transit │ │ Backup │ │ │ +│ │ │ (SQLCipher) │ │ (TLS 1.3) │ │ │ │ │ +│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Role Permission Matrix + +| Capability | Admin | Adult | Teen | Child | Caregiver | +|------------|-------|-------|------|-------|-----------| +| View all calendars | Yes | Yes | Limited | Limited | Limited | +| Edit events | Yes | Yes | Own | No | No | +| Create chores | Yes | Yes | No | No | No | +| Complete chores | Yes | Yes | Own | Own | No | +| Manage profiles | Yes | No | No | No | No | +| View caregiver info | Yes | Yes | No | No | Own-assigned | +| System settings | Yes | No | No | No | No | +| Invite caregivers | Yes | Yes | No | No | No | + +### Security Requirements + +| Category | Requirement | Implementation | +|----------|-------------|----------------| +| **Authentication** | Multi-factor for admin actions | PIN + device auth | +| **Session** | Automatic timeout on mobile | 15-minute idle logout | +| **Data** | Encryption at rest | SQLCipher for local data | +| **Transit** | TLS for all connections | TLS 1.3 minimum | +| **Secrets** | No secrets in code | Environment variables, secret manager | +| **Dependencies** | Regular vulnerability scans | Renovate + npm audit | +| **Audit** | Log security-relevant actions | Immutable audit log | + +--- + +## Integration Architecture + +### External Integration Points + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ INTEGRATION ARCHITECTURE │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ LUMINOUS │ +│ │ │ +│ ┌─────────────────────┼─────────────────────┐ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ CALENDAR │ │ WEATHER │ │ GROCERY │ │ +│ │ PROVIDERS │ │ SERVICE │ │ DELIVERY │ │ +│ ├─────────────┤ ├─────────────┤ ├─────────────┤ │ +│ │ Google Cal │ │ OpenWeather │ │ Instacart │ │ +│ │ Outlook/M365│ │ NWS API │ │ (Future) │ │ +│ │ iCloud │ │ Pirate │ │ │ │ +│ │ CalDAV │ │ Weather │ │ │ │ +│ │ ICS URLs │ │ │ │ │ │ +│ └─────────────┘ └─────────────┘ └─────────────┘ │ +│ │ +│ ┌─────────────────────┼─────────────────────┐ │ +│ │ │ │ │ +│ ▼ ▼ ▼ │ +│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ +│ │ PUSH │ │ MAGIC │ │ MAPS │ │ +│ │ NOTIFY │ │ IMPORT │ │ SERVICE │ │ +│ ├─────────────┤ ├─────────────┤ ├─────────────┤ │ +│ │ Apple APNS │ │ OCR Service │ │ OpenStreet │ │ +│ │ Google FCM │ │ Email Parse │ │ Map │ │ +│ │ Web Push │ │ LLM Extract │ │ │ │ +│ └─────────────┘ └─────────────┘ └─────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Calendar Integration Patterns + +| Provider | Protocol | Sync Direction | Auth Method | +|----------|----------|----------------|-------------| +| **Google Calendar** | REST API | Two-way | OAuth 2.0 | +| **Microsoft 365** | Graph API | Two-way | OAuth 2.0 | +| **iCloud** | CalDAV | Read-only (initially) | App-specific password | +| **CalDAV Generic** | CalDAV | Read-only | Basic / OAuth | +| **ICS URL** | HTTP(S) | Read-only | None / Basic | + +### Integration API Design + +All external integrations follow the Adapter pattern: + +```typescript +interface CalendarAdapter { + readonly providerId: CalendarProviderId; + + authenticate(credentials: AuthCredentials): Promise; + refreshToken(session: AuthSession): Promise; + + listCalendars(session: AuthSession): Promise; + + fetchEvents( + session: AuthSession, + calendarId: string, + range: DateRange + ): Promise; + + createEvent?( + session: AuthSession, + calendarId: string, + event: EventCreateInput + ): Promise; + + updateEvent?( + session: AuthSession, + calendarId: string, + eventId: string, + event: EventUpdateInput + ): Promise; + + deleteEvent?( + session: AuthSession, + calendarId: string, + eventId: string + ): Promise; +} +``` + +--- + +## Deployment Architecture + +### Self-Hosted Deployment + +``` +┌─────────────────────────────────────────────────────────────────────┐ +│ SELF-HOSTED DEPLOYMENT │ +├─────────────────────────────────────────────────────────────────────┤ +│ │ +│ HOME NETWORK │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ │ │ +│ │ ┌────────────────┐ ┌────────────────┐ │ │ +│ │ │ WALL DISPLAY │ │ SYNC SERVER │ (Optional) │ │ +│ │ │ (Kiosk Mode) │◀───────▶│ (Raspberry Pi │ │ │ +│ │ │ │ LAN │ or NAS) │ │ │ +│ │ └────────────────┘ └────────┬───────┘ │ │ +│ │ │ │ │ +│ │ │ LAN │ │ +│ │ ┌────────────────┐ │ │ │ +│ │ │ MOBILE APPS │◀─────────────────┘ │ │ +│ │ │ (on WiFi) │ │ │ +│ │ └────────────────┘ │ │ +│ │ │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ │ +│ │ Internet (for calendar sync) │ +│ ▼ │ +│ ┌────────────────────────────────────────────────────────────────┐ │ +│ │ EXTERNAL SERVICES │ │ +│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ +│ │ │ Google │ │ Outlook │ │ Weather │ │ Push │ │ │ +│ │ │ Calendar │ │ Calendar │ │ API │ │ Services │ │ │ +│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ +│ └────────────────────────────────────────────────────────────────┘ │ +│ │ +└─────────────────────────────────────────────────────────────────────┘ +``` + +### Display Hardware Specifications + +| Tier | Device | RAM | Storage | Notes | +|------|--------|-----|---------|-------| +| **Budget** | Raspberry Pi 4 | 4GB | 32GB SD | Minimum viable | +| **Recommended** | Raspberry Pi 5 | 8GB | 64GB SD | Smooth experience | +| **Premium** | Intel NUC / Mini PC | 8GB+ | 128GB SSD | Best performance | +| **Tablet** | iPad / Android Tablet | 4GB+ | 64GB+ | No kiosk hardware needed | + +### Container Deployment (Server) + +```yaml +# docker-compose.yml (example) +version: '3.8' +services: + luminous-server: + image: luminous/server:latest + ports: + - "3000:3000" + volumes: + - luminous-data:/data + environment: + - DATABASE_URL=file:/data/luminous.db + - PUSH_VAPID_PUBLIC_KEY=${VAPID_PUBLIC} + - PUSH_VAPID_PRIVATE_KEY=${VAPID_PRIVATE} + restart: unless-stopped + +volumes: + luminous-data: +``` + +--- + +## Architecture Decisions + +All significant architecture decisions are documented as Architecture Decision Records (ADRs) in the `/docs/adr/` directory. + +### ADR Index + +| ADR | Title | Status | Date | +|-----|-------|--------|------| +| [ADR-001](./adr/ADR-001-typescript-primary-language.md) | TypeScript as Primary Language | Accepted | 2025-12-21 | +| [ADR-002](./adr/ADR-002-react-ui-framework.md) | React as UI Framework | Accepted | 2025-12-21 | +| [ADR-003](./adr/ADR-003-local-first-architecture.md) | Local-First Data Architecture | Accepted | 2025-12-21 | +| [ADR-004](./adr/ADR-004-two-way-sync-google-first.md) | Two-Way Sync Initially Google-Only | Accepted | 2025-12-21 | +| [ADR-005](./adr/ADR-005-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | +| [ADR-006](./adr/ADR-006-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | +| [ADR-007](./adr/ADR-007-self-hosting-first.md) | Self-Hosting as Primary Model | Accepted | 2025-12-21 | + +--- + +## Related Documents + +- [Project Overview](./PROJECT-OVERVIEW.md) +- [Development Roadmap](./ROADMAP.md) +- [Architecture Decision Records](./adr/) +- [CLAUDE.md (Development Guidelines)](../CLAUDE.md) + +--- + +## Document History + +| Version | Date | Author | Changes | +|---------|------|--------|---------| +| 1.0.0 | 2025-12-21 | Luminous Team | Initial architecture document | diff --git a/docs/PROJECT-OVERVIEW.md b/docs/PROJECT-OVERVIEW.md new file mode 100644 index 0000000..57057ba --- /dev/null +++ b/docs/PROJECT-OVERVIEW.md @@ -0,0 +1,653 @@ +# Luminous Project Overview + +> **Document Version:** 1.0.0 +> **Last Updated:** 2025-12-21 +> **Status:** Draft +> **TOGAF Phase:** Architecture Vision (Phase A) + +--- + +## Table of Contents + +1. [Executive Summary](#executive-summary) +2. [Business Context](#business-context) +3. [Product Definition](#product-definition) +4. [Stakeholders and Personas](#stakeholders-and-personas) +5. [Core UX Principles](#core-ux-principles) +6. [Functional Scope](#functional-scope) +7. [Non-Functional Requirements](#non-functional-requirements) +8. [Design Constraints](#design-constraints) +9. [Key Design Decisions](#key-design-decisions) +10. [Success Metrics](#success-metrics) +11. [Glossary](#glossary) + +--- + +## Executive Summary + +**Luminous** is a wall-mounted, always-on, distraction-free family hub designed for large portrait-mounted touchscreens. It provides a calm, glanceable view of household schedules, tasks, chores, meal plans, and shared lists, making family coordination visible, actionable, and accessible to all ages. + +### Vision Statement + +> To create the calm center of household coordination - a single, always-visible source of truth that brings families together through shared awareness and reduced mental load. + +### Mission + +Luminous aims to eliminate the chaos of family scheduling by providing: +- A unified view of all household activities +- Kid-friendly interfaces that encourage participation +- Caregiver sharing for extended family coordination +- Zero-distraction design that respects attention and focus + +--- + +## Business Context + +### Problem Statement + +Modern families struggle with: +- **Fragmented information**: Schedules scattered across multiple calendars, apps, and paper +- **Communication gaps**: Caregivers, grandparents, and babysitters lack visibility +- **Chore coordination**: No clear accountability for household tasks +- **Mental load**: One person typically carries the burden of family logistics +- **Screen addiction**: Smart displays often become entertainment devices + +### Market Opportunity + +The family organization space is served by products like Skylight, Hearth, and Cozi, each with limitations: +- Proprietary hardware lock-in +- Limited integration capabilities +- Subscription fatigue +- Lack of open-source alternatives + +### Strategic Goals + +| Goal | Description | Priority | +|------|-------------|----------| +| SG-1 | Provide a fully open-source family command center | Critical | +| SG-2 | Support diverse hardware (tablets, displays, DIY solutions) | High | +| SG-3 | Enable self-hosting for privacy-conscious families | High | +| SG-4 | Create an ecosystem of companion apps | Medium | +| SG-5 | Build a community of contributors and users | Medium | + +--- + +## Product Definition + +### Core Value Proposition + +A wall-mounted, always-on, distraction-free family hub that makes schedules, chores/routines, meal plans, and shared lists visible, actionable, and kid-friendly, with mobile companion control and caregiver sharing. + +### Design Constraint: Zero Distraction + +**Critical Design Decision:** Luminous explicitly excludes: +- Web browsing capabilities +- App installation +- Video streaming +- Social media integration +- Voice assistants with open-ended queries +- Games or entertainment features + +This constraint is intentional and strategic, aligning with research showing that multi-purpose smart displays often become sources of distraction rather than productivity. + +--- + +## Stakeholders and Personas + +### Primary Stakeholders + +| Stakeholder | Role | Concerns | Success Criteria | +|-------------|------|----------|------------------| +| Household Admin(s) | System owner, primary configurer | Setup complexity, data privacy, cost | Easy setup, full control, reliable operation | +| Family Members | Daily users (kids to adults) | Usability, fun factor, autonomy | Intuitive interface, personal accountability | +| External Caregivers | Shared-access users | Limited scope, clear information | View-only access, relevant information only | +| Developers | Contributors | Code quality, documentation | Clean architecture, comprehensive docs | +| Self-Hosters | Advanced users | Control, privacy, customization | Easy deployment, full data ownership | + +### Persona Definitions + +#### Persona 1: The Household Admin (Primary) + +**Name:** Alex (Parent, 35-45) +**Role:** Household Admin +**Technical Skill:** Moderate to High + +**Goals:** +- Reduce time spent coordinating family logistics +- Ensure all family members are informed and accountable +- Maintain privacy and control over family data + +**Pain Points:** +- Tired of being the "family scheduler" +- Frustrated with subscription costs for family apps +- Wants something the whole family will actually use + +**Needs:** +- Quick setup with sensible defaults +- Mobile app for on-the-go management +- Integration with existing calendars +- Caregiver sharing without complexity + +--- + +#### Persona 2: The Family Member (Child) + +**Name:** Jordan (Child, 6-12) +**Role:** Family Member +**Technical Skill:** Low to Moderate + +**Goals:** +- Know what's happening today +- Complete chores and earn rewards +- Feel included in family activities + +**Pain Points:** +- Forgets tasks and appointments +- Can't read complex schedules +- Gets distracted by other screens + +**Needs:** +- Big, colorful, simple interface +- Visual routines with icons +- Fun reward system +- Profile with their favorite color + +--- + +#### Persona 3: The Family Member (Teen/Adult) + +**Name:** Riley (Teen/Adult, 13+) +**Role:** Family Member +**Technical Skill:** Moderate to High + +**Goals:** +- Quick access to personal schedule +- Independence in managing own tasks +- Privacy for personal events + +**Pain Points:** +- Doesn't want to be micromanaged +- Needs mobile access, not just wall display +- Wants personal vs. family separation + +**Needs:** +- Personal calendar view +- Private task lists +- Notification preferences +- Mobile app access + +--- + +#### Persona 4: The External Caregiver + +**Name:** Sam (Grandparent/Babysitter) +**Role:** External Caregiver +**Technical Skill:** Variable + +**Goals:** +- Know what needs to happen during care time +- Access emergency information +- Feel confident about the plan + +**Pain Points:** +- Often left out of the loop +- Can't remember complex instructions +- Worried about handling emergencies + +**Needs:** +- Read-only access to relevant schedules +- Caregiver info (allergies, contacts, routines) +- Simple, uncluttered view +- No app installation required (web access) + +--- + +## Core UX Principles + +### Principle 1: Glanceable First + +The primary interface must answer "What's next?" within 2 seconds of glancing at the display. + +**Implementation:** +- Today's view is always the default +- Next 24 hours prominently displayed +- Color-coded by person +- Large, readable text (viewable from 10+ feet) + +### Principle 2: Color + Profile-First + +Every item is instantly attributable to a family member through consistent visual coding. + +**Implementation:** +- Each profile has a unique color +- Avatar/photo displayed alongside items +- Color-blind friendly palette options +- Consistent color usage across all views + +### Principle 3: Two Input Paths + +Support both structured and unstructured data entry. + +**Path A: Structured Editing** +- Traditional form-based input +- Available on device and mobile app +- Full control over all fields +- Templates for common items + +**Path B: Magic Import Assistant** +- Forward emails to create events +- Photo/scan handwritten lists +- Parse PDFs (school schedules, activities) +- AI-assisted extraction with review step +- Nothing published without approval + +### Principle 4: Safe by Default + +Protect against accidental changes and ensure age-appropriate access. + +**Implementation:** +- Kid mode limits destructive actions +- PIN/parental lock for sensitive settings +- Confirmation dialogs for deletions +- Undo available for recent actions +- Audit log for admin review + +### Principle 5: Always Recovers + +The system must be resilient to failures and require zero manual intervention. + +**Implementation:** +- Auto-start kiosk mode on boot +- Watchdog process for UI crashes +- Offline mode with cached "today" view +- Automatic reconnection on network restore +- Graceful degradation of features + +--- + +## Functional Scope + +### 1. Calendar and Scheduling + +#### 1.1 Calendar Aggregation +- **CAL-001**: Connect and display multiple external calendars (Google, Outlook/Office 365, iCloud, CalDAV) +- **CAL-002**: Support URL-based subscribed calendars (ICS feeds from schools, sports teams, etc.) +- **CAL-003**: Calendar-to-profile mapping (reassign which calendars belong to which family members) +- **CAL-004**: Two-way sync with supported providers (initial: Google Calendar) + +#### 1.2 Calendar Views +- **CAL-010**: Day view (current day, including "next 24 hours" mode) +- **CAL-011**: Week view (7-day overview) +- **CAL-012**: Month view (traditional calendar grid) +- **CAL-013**: Agenda view (chronological list) +- **CAL-014**: Family filter (show all or filter by profile) + +#### 1.3 Event Management +- **CAL-020**: Create/edit/delete events on device and mobile +- **CAL-021**: Recurring event support (daily, weekly, monthly, yearly, custom) +- **CAL-022**: Event reminders and notifications +- **CAL-023**: Location support with maps link +- **CAL-024**: Attendee management (family members) +- **CAL-025**: Countdown tiles for major events (birthdays, trips, holidays) + +#### 1.4 Calendar Sharing +- **CAL-030**: Invite external caregivers with controlled visibility +- **CAL-031**: Permission levels (view-only, can add, full edit) +- **CAL-032**: Share link generation for quick access + +--- + +### 2. Magic Import Assistant + +#### 2.1 Input Channels +- **IMP-001**: Email forwarding (dedicated family inbox) +- **IMP-002**: Photo/screenshot upload (OCR processing) +- **IMP-003**: Text paste (natural language parsing) +- **IMP-004**: PDF upload (school schedules, activity calendars) +- **IMP-005**: URL extraction (event pages, schedules) + +#### 2.2 Output Types +- **IMP-010**: Calendar events (single and recurring) +- **IMP-011**: Meal plans (weekly with recipes) +- **IMP-012**: List items (grocery, to-do, custom) +- **IMP-013**: Chore assignments + +#### 2.3 Approval Workflow +- **IMP-020**: All imports require explicit approval before publishing +- **IMP-021**: Preview with ability to edit before approval +- **IMP-022**: Batch approval for multiple items +- **IMP-023**: Rejection with feedback for learning +- **IMP-024**: Audit trail of all imports + +--- + +### 3. Tasks, Chores, and Routines + +#### 3.1 Chores and To-Dos +- **CHR-001**: Create chores with title, description, and icon +- **CHR-002**: Assign to one or multiple profiles +- **CHR-003**: "Anyone" bucket for shared household tasks +- **CHR-004**: Recurrence support (daily, weekly, custom) +- **CHR-005**: Due date and time settings +- **CHR-006**: Completion tracking with timestamps +- **CHR-007**: Priority levels (optional) +- **CHR-008**: "Today's Focus" filter for kid-friendly view + +#### 3.2 Routines +- **RTN-001**: Step-by-step routines with kid-friendly icons +- **RTN-002**: Multiple display modes (list, cards, slideshow) +- **RTN-003**: Timer/duration per step (optional) +- **RTN-004**: Audio cues for step completion (optional) +- **RTN-005**: Streak tracking for motivation +- **RTN-006**: Starter routine library (morning, bedtime, homework, etc.) +- **RTN-007**: Custom routine builder +- **RTN-008**: Profile-specific routines + +--- + +### 4. Rewards and Motivation + +#### 4.1 Points System +- **RWD-001**: Stars/points assigned to chores and routines +- **RWD-002**: Per-profile point tracking +- **RWD-003**: Point history and statistics + +#### 4.2 Rewards +- **RWD-010**: Custom reward definitions (screen time, allowance, privileges) +- **RWD-011**: Point cost per reward +- **RWD-012**: Reward request and approval workflow +- **RWD-013**: Reward history + +#### 4.3 Gamification +- **RWD-020**: Progress-to-goal visualization +- **RWD-021**: Celebratory animations on completion +- **RWD-022**: Streaks and achievements +- **RWD-023**: Non-reader-friendly design (emoji, icons) + +--- + +### 5. Meal Planning and Recipes + +#### 5.1 Meal Plans +- **MEL-001**: Weekly meal plan view (by day) +- **MEL-002**: Meal slots (breakfast, lunch, dinner, snacks) +- **MEL-003**: Assign meals per family member (dietary needs) +- **MEL-004**: Meal templates for quick planning +- **MEL-005**: Copy/rotate previous weeks + +#### 5.2 Recipes +- **MEL-010**: Recipe storage with ingredients and instructions +- **MEL-011**: Recipe import from URLs +- **MEL-012**: Recipe photos +- **MEL-013**: Scaling for servings +- **MEL-014**: Nutritional information (optional) + +#### 5.3 Integration +- **MEL-020**: "Add ingredients to grocery list" one-click action +- **MEL-021**: AI-generated meal plans with preferences (allergies, cuisine, budget) +- **MEL-022**: Leftover/ingredient-based suggestions + +--- + +### 6. Lists + +#### 6.1 List Management +- **LST-001**: Unlimited custom lists +- **LST-002**: List templates (grocery, packing, school supplies) +- **LST-003**: Private lists in mobile app (e.g., gift lists) +- **LST-004**: Shared vs. personal list designation +- **LST-005**: Archive completed lists + +#### 6.2 List Views +- **LST-010**: Checklist view (simple checkbox list) +- **LST-011**: Board/kanban view (columns for categorization) +- **LST-012**: Category grouping (produce, dairy, etc.) +- **LST-013**: Sort options (alphabetical, checked status, custom) + +#### 6.3 List Features +- **LST-020**: Quantity and units per item +- **LST-021**: Notes per item +- **LST-022**: Assign items to shoppers +- **LST-023**: Recently added / frequently used suggestions +- **LST-024**: Instacart integration (US only, configurable) + +--- + +### 7. Profiles and Household Directory + +#### 7.1 Profile Management +- **PRF-001**: Unlimited profiles (family members and pets) +- **PRF-002**: Photo/avatar support +- **PRF-003**: Nickname and display name +- **PRF-004**: Profile color selection +- **PRF-005**: Birthday and age tracking + +#### 7.2 Caregiver Information +- **PRF-010**: Allergies and medical notes +- **PRF-011**: Emergency contact numbers +- **PRF-012**: Doctor/dentist information +- **PRF-013**: School/activity information +- **PRF-014**: Important notes for caregivers + +#### 7.3 Permissions +- **PRF-020**: Role assignment (Admin, Member, Child, Caregiver) +- **PRF-021**: Per-role permission matrix +- **PRF-022**: PIN codes per profile (optional) +- **PRF-023**: Caregiver time-limited access + +--- + +### 8. Companion Experience + +#### 8.1 Mobile App +- **MOB-001**: Full control of calendars, chores, lists, meals, profiles +- **MOB-002**: Push notifications for events and reminders +- **MOB-003**: Chore completion notifications +- **MOB-004**: Offline capability with sync +- **MOB-005**: iOS and Android support + +#### 8.2 Mobile Widgets +- **MOB-010**: Today's schedule widget +- **MOB-011**: Grocery list widget +- **MOB-012**: Chore status widget + +#### 8.3 Web Access +- **MOB-020**: Responsive web interface +- **MOB-021**: Caregiver web portal (no app required) +- **MOB-022**: Full admin capabilities via web + +--- + +### 9. Ambient Information + +#### 9.1 Weather +- **AMB-001**: Current weather display +- **AMB-002**: Multi-day forecast +- **AMB-003**: Location/address-based +- **AMB-004**: Unit preferences (Fahrenheit/Celsius) +- **AMB-005**: Weather alerts + +#### 9.2 Additional Widgets (Future) +- **AMB-010**: Clock with timezone support +- **AMB-011**: Photo frame mode (slideshow of family photos) +- **AMB-012**: Quote of the day +- **AMB-013**: Household announcements/notes + +--- + +### 10. Display Modes and Privacy + +#### 10.1 Privacy Mode +- **DSP-001**: One-tap privacy mode (swap to wallpaper/clock) +- **DSP-002**: Automatic privacy mode after timeout +- **DSP-003**: Motion sensor integration (optional, wake on approach) + +#### 10.2 Sleep Mode +- **DSP-010**: Scheduled screen-off times +- **DSP-011**: Manual sleep toggle +- **DSP-012**: Wake on touch or schedule + +#### 10.3 Display Settings +- **DSP-020**: Auto-brightness with ambient light sensor +- **DSP-021**: Manual brightness override +- **DSP-022**: Night mode color temperature +- **DSP-023**: Screen saver options + +--- + +## Non-Functional Requirements + +### Reliability + +| Requirement | Description | Target | +|-------------|-------------|--------| +| NFR-REL-001 | Auto-start kiosk shell on boot | 100% | +| NFR-REL-002 | Watchdog recovery from UI crashes | < 30 seconds | +| NFR-REL-003 | Offline resilience (cached today view) | Yes | +| NFR-REL-004 | Uptime target | 99.9% | +| NFR-REL-005 | Data sync recovery on reconnection | Automatic | + +### Performance + +| Requirement | Description | Target | +|-------------|-------------|--------| +| NFR-PRF-001 | Initial load time | < 5 seconds | +| NFR-PRF-002 | View transition time | < 300ms | +| NFR-PRF-003 | Touch response latency | < 100ms | +| NFR-PRF-004 | Memory usage (display app) | < 512MB | +| NFR-PRF-005 | 24/7 operation without memory leaks | Yes | + +### Security + +| Requirement | Description | Target | +|-------------|-------------|--------| +| NFR-SEC-001 | Local device lock with PIN | Required | +| NFR-SEC-002 | Role-based access control | Required | +| NFR-SEC-003 | Edit audit logging | Required | +| NFR-SEC-004 | Encrypted data at rest | Required | +| NFR-SEC-005 | Encrypted data in transit (HTTPS) | Required | +| NFR-SEC-006 | OAuth 2.0 for external integrations | Required | + +### Accessibility + +| Requirement | Description | Target | +|-------------|-------------|--------| +| NFR-A11Y-001 | WCAG 2.1 AA compliance | Required | +| NFR-A11Y-002 | Large text mode | Required | +| NFR-A11Y-003 | High contrast mode | Required | +| NFR-A11Y-004 | Touch target size | 44x44px minimum | +| NFR-A11Y-005 | Dyslexia-friendly font option | Required | +| NFR-A11Y-006 | Screen reader support (mobile) | Required | +| NFR-A11Y-007 | Text readability from 10+ feet | Required | + +### Updates and Maintenance + +| Requirement | Description | Target | +|-------------|-------------|--------| +| NFR-UPD-001 | OTA update capability | Required | +| NFR-UPD-002 | Automatic background updates | Optional (configurable) | +| NFR-UPD-003 | Rollback capability | Required | +| NFR-UPD-004 | Update notification | Required | + +--- + +## Design Constraints + +### Technical Constraints + +1. **Platform Agnostic**: Must run on commodity hardware (tablets, mini PCs, Raspberry Pi) +2. **Self-Hostable**: Full functionality without cloud dependency +3. **Offline-First**: Core features must work without internet +4. **Low Power**: Optimized for always-on, low-power devices +5. **Portrait Display**: Primary design for vertical/portrait orientation + +### Business Constraints + +1. **Open Source**: AGPL-3.0 license for all core functionality +2. **No Vendor Lock-in**: No proprietary hardware requirements +3. **Privacy-First**: No mandatory data collection or telemetry +4. **Community Driven**: Transparent roadmap and contribution process + +### Design Constraints + +1. **Zero Distraction**: No web browsing, apps, video, or entertainment features +2. **Kid-Friendly**: All interfaces usable by children 6+ +3. **Caregiver Simple**: External users need no training +4. **Always Visible**: No screensavers or idle states that hide information + +--- + +## Key Design Decisions + +Detailed Architecture Decision Records (ADRs) are maintained in `/docs/adr/`. Key decisions include: + +| ADR | Title | Status | +|-----|-------|--------| +| ADR-001 | Use TypeScript for all application code | Accepted | +| ADR-002 | React for display and mobile applications | Accepted | +| ADR-003 | Local-first data architecture with sync | Accepted | +| ADR-004 | Two-way sync initially limited to Google Calendar | Accepted | +| ADR-005 | Magic Import requires explicit approval | Accepted | +| ADR-006 | Zero-distraction principle (no entertainment) | Accepted | +| ADR-007 | Self-hosting as primary deployment model | Accepted | + +--- + +## Success Metrics + +### User Adoption + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Daily active display usage | 100% of days | Display uptime | +| Family member engagement | 80% of profiles active weekly | Interaction logs | +| Chore completion rate | 70% of assigned chores | Completion records | + +### Technical Health + +| Metric | Target | Measurement | +|--------|--------|-------------| +| Display uptime | 99.9% | System monitoring | +| Sync latency | < 60 seconds | Sync timestamps | +| Crash-free sessions | 99.5% | Error tracking | + +### Community Growth + +| Metric | Target | Measurement | +|--------|--------|-------------| +| GitHub stars | 1,000 in year 1 | GitHub API | +| Active contributors | 20 in year 1 | Git history | +| Community deployments | 500 in year 1 | Opt-in telemetry | + +--- + +## Glossary + +| Term | Definition | +|------|------------| +| **Chore** | A single task or to-do item assigned to family members | +| **Display** | The wall-mounted device running the Luminous display app | +| **External Caregiver** | Non-household members with shared access (grandparents, babysitters) | +| **Household Admin** | Primary account owner with full configuration access | +| **Magic Import** | AI-powered feature to parse unstructured inputs into structured data | +| **Profile** | A family member or pet represented in the system | +| **Routine** | A sequence of steps that form a repeated activity (morning routine, etc.) | +| **Kiosk Mode** | Locked-down display mode that prevents exit to other apps | +| **Two-Way Sync** | Calendar updates flow both to and from external providers | + +--- + +## Document History + +| Version | Date | Author | Changes | +|---------|------|--------|---------| +| 1.0.0 | 2025-12-21 | Luminous Team | Initial draft | + +--- + +## Related Documents + +- [Architecture Overview](./ARCHITECTURE.md) +- [Development Roadmap](./ROADMAP.md) +- [Architecture Decision Records](./adr/) +- [CLAUDE.md (Development Guidelines)](../CLAUDE.md) diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md new file mode 100644 index 0000000..a40a0f2 --- /dev/null +++ b/docs/ROADMAP.md @@ -0,0 +1,708 @@ +# Luminous Development Roadmap + +> **Document Version:** 1.0.0 +> **Last Updated:** 2025-12-21 +> **Status:** Draft +> **TOGAF Phase:** Phase E/F (Opportunities, Solutions & Migration Planning) + +--- + +## Table of Contents + +1. [Roadmap Overview](#roadmap-overview) +2. [Implementation Phases](#implementation-phases) +3. [Phase 0: Foundation](#phase-0-foundation) +4. [Phase 1: Core Display](#phase-1-core-display) +5. [Phase 2: Task Management](#phase-2-task-management) +6. [Phase 3: Mobile Companion](#phase-3-mobile-companion) +7. [Phase 4: Household Management](#phase-4-household-management) +8. [Phase 5: Intelligence Layer](#phase-5-intelligence-layer) +9. [Phase 6: Ecosystem Expansion](#phase-6-ecosystem-expansion) +10. [Future Vision](#future-vision) +11. [Dependency Map](#dependency-map) +12. [Risk Register](#risk-register) + +--- + +## Roadmap Overview + +### Strategic Themes + +| Theme | Description | Primary Phases | +|-------|-------------|----------------| +| **Foundation** | Establish architecture, tooling, and core infrastructure | Phase 0 | +| **Visibility** | Make family schedules and tasks visible at a glance | Phase 1-2 | +| **Mobility** | Enable management and notifications on the go | Phase 3 | +| **Coordination** | Expand to meal planning, lists, and caregiver sharing | Phase 4 | +| **Intelligence** | Add AI-powered features (Magic Import, suggestions) | Phase 5 | +| **Ecosystem** | Platform extensions, integrations, community | Phase 6+ | + +### Release Philosophy + +Following TOGAF's principle of iterative architecture development: + +1. **Minimum Viable Product (MVP)**: Phases 0-1 deliver a functional calendar display +2. **Minimum Lovable Product (MLP)**: Phase 2 adds task management and rewards +3. **Full Product**: Phases 3-4 complete the companion apps and household features +4. **Platform**: Phases 5-6 enable extensibility and community contributions + +### Architecture Building Blocks by Phase + +``` +Phase 0: Foundation +├── Development Environment +├── Monorepo Structure +├── Core Domain Models +└── Design System Foundation + +Phase 1: Core Display +├── Display Application Shell +├── Calendar Context +├── Event Display Widgets +└── Offline Data Layer + +Phase 2: Task Management +├── Chore/Task Context +├── Routine Context +├── Rewards Context +└── Progress Visualization + +Phase 3: Mobile Companion +├── Mobile Application Shell +├── Push Notification Service +├── Sync Engine +└── Remote Data Layer + +Phase 4: Household Management +├── Profile Management +├── Meal Planning Context +├── List Management Context +└── Caregiver Portal + +Phase 5: Intelligence +├── Magic Import Service +├── AI Suggestion Engine +├── Natural Language Processing +└── Learning Pipeline + +Phase 6: Ecosystem +├── Plugin Architecture +├── API Gateway +├── Third-Party Integrations +└── Community Contributions +``` + +--- + +## Implementation Phases + +### Phase Summary + +| Phase | Name | Focus | Key Deliverables | +|-------|------|-------|------------------| +| **0** | Foundation | Infrastructure | Monorepo, CI/CD, design system, domain models | +| **1** | Core Display | Calendar visibility | Display app, calendar integration, offline mode | +| **2** | Task Management | Chores and routines | Task creation, completion tracking, rewards | +| **3** | Mobile Companion | Mobile control | iOS/Android apps, push notifications, sync | +| **4** | Household Management | Expanded features | Profiles, meals, lists, caregiver sharing | +| **5** | Intelligence Layer | AI features | Magic import, suggestions, automation | +| **6** | Ecosystem Expansion | Platform growth | Plugins, APIs, community tools | + +--- + +## Phase 0: Foundation + +### Objective + +Establish the technical foundation, development environment, and architectural patterns that all subsequent phases will build upon. + +### Scope + +#### 0.1 Development Environment + +- [ ] **0.1.1** Initialize monorepo with Turborepo +- [ ] **0.1.2** Configure TypeScript with strict settings +- [ ] **0.1.3** Set up ESLint and Prettier configurations +- [ ] **0.1.4** Configure Vitest for unit testing +- [ ] **0.1.5** Set up Playwright for E2E testing +- [ ] **0.1.6** Implement pre-commit hooks (Husky + lint-staged) +- [ ] **0.1.7** Configure Changesets for versioning + +#### 0.2 CI/CD Pipeline + +- [ ] **0.2.1** GitHub Actions workflow for linting +- [ ] **0.2.2** GitHub Actions workflow for testing +- [ ] **0.2.3** GitHub Actions workflow for building +- [ ] **0.2.4** Dependabot/Renovate for dependency updates +- [ ] **0.2.5** Code coverage reporting +- [ ] **0.2.6** Release automation pipeline + +#### 0.3 Core Package Structure + +- [ ] **0.3.1** Create `packages/core` with domain model stubs +- [ ] **0.3.2** Create `packages/ui` with design system foundation +- [ ] **0.3.3** Create `packages/sync` with sync engine interfaces +- [ ] **0.3.4** Configure package inter-dependencies +- [ ] **0.3.5** Set up path aliases and TypeScript references + +#### 0.4 Design System Foundation + +- [ ] **0.4.1** Define design tokens (colors, typography, spacing) +- [ ] **0.4.2** Create base theme configuration +- [ ] **0.4.3** Implement primitive components (Button, Input, Text) +- [ ] **0.4.4** Set up Storybook for component development +- [ ] **0.4.5** Document accessibility requirements per component + +#### 0.5 Domain Model Implementation + +- [ ] **0.5.1** Implement `Household` aggregate +- [ ] **0.5.2** Implement `Profile` entity +- [ ] **0.5.3** Implement `Event` entity +- [ ] **0.5.4** Implement `Chore` entity +- [ ] **0.5.5** Implement shared value objects (DateTime, Color, etc.) +- [ ] **0.5.6** Define domain events +- [ ] **0.5.7** Implement repository interfaces (ports) + +#### 0.6 Documentation + +- [ ] **0.6.1** Complete PROJECT-OVERVIEW.md +- [ ] **0.6.2** Complete ARCHITECTURE.md +- [ ] **0.6.3** Complete ROADMAP.md +- [ ] **0.6.4** Create initial ADRs +- [ ] **0.6.5** Set up documentation site (optional) + +### Exit Criteria + +- All packages build and lint successfully +- Unit test framework operational with example tests +- Design system Storybook accessible +- Domain models pass validation tests +- CI pipeline runs on all pull requests + +--- + +## Phase 1: Core Display + +### Objective + +Deliver a functional wall-mounted display that shows family calendars in a glanceable format with offline capability. + +### Scope + +#### 1.1 Display Application Shell + +- [ ] **1.1.1** Create `apps/display` with Electron/Tauri +- [ ] **1.1.2** Implement kiosk mode (fullscreen, no escape) +- [ ] **1.1.3** Auto-start on system boot +- [ ] **1.1.4** Watchdog for crash recovery +- [ ] **1.1.5** Basic settings screen (PIN-protected) + +#### 1.2 Calendar Context Implementation + +- [ ] **1.2.1** Implement Google Calendar adapter +- [ ] **1.2.2** Implement ICS URL subscription adapter +- [ ] **1.2.3** OAuth flow for Google authentication +- [ ] **1.2.4** Calendar-to-profile assignment +- [ ] **1.2.5** Recurring event support +- [ ] **1.2.6** Event color mapping + +#### 1.3 Calendar Views + +- [ ] **1.3.1** Day view (next 24 hours focus) +- [ ] **1.3.2** Week view (7-day overview) +- [ ] **1.3.3** Month view (calendar grid) +- [ ] **1.3.4** Agenda view (chronological list) +- [ ] **1.3.5** View switching and navigation +- [ ] **1.3.6** Profile filtering + +#### 1.4 Event Display Widgets + +- [ ] **1.4.1** Event card component (color-coded by profile) +- [ ] **1.4.2** "What's Next" widget (next 3 events) +- [ ] **1.4.3** Countdown widget (days until major events) +- [ ] **1.4.4** Today summary widget + +#### 1.5 Ambient Widgets + +- [ ] **1.5.1** Clock widget (with timezone) +- [ ] **1.5.2** Weather widget (current + forecast) +- [ ] **1.5.3** Weather API integration (configurable provider) + +#### 1.6 Display Modes + +- [ ] **1.6.1** Normal display mode +- [ ] **1.6.2** Privacy mode (wallpaper/clock only) +- [ ] **1.6.3** Sleep mode (screen off on schedule) +- [ ] **1.6.4** Auto-brightness (if hardware supports) + +#### 1.7 Offline Capability + +- [ ] **1.7.1** SQLite database setup (sql.js) +- [ ] **1.7.2** Local event cache +- [ ] **1.7.3** Offline indicator +- [ ] **1.7.4** Sync status indicator +- [ ] **1.7.5** Automatic sync on reconnection + +#### 1.8 Accessibility + +- [ ] **1.8.1** Large text mode +- [ ] **1.8.2** High contrast mode +- [ ] **1.8.3** Touch target sizing (44x44px minimum) +- [ ] **1.8.4** Readable from 10+ feet + +### Exit Criteria + +- Display shows events from connected Google Calendar +- Display functions offline with cached data +- Privacy and sleep modes functional +- Tested on Raspberry Pi 4 target hardware +- WCAG 2.1 AA compliance verified + +--- + +## Phase 2: Task Management + +### Objective + +Add chores, routines, and rewards to transform the display from view-only to interactive family coordination. + +### Scope + +#### 2.1 Chore/Task Context + +- [ ] **2.1.1** Chore creation UI +- [ ] **2.1.2** Chore assignment (profiles or "anyone") +- [ ] **2.1.3** Recurrence patterns +- [ ] **2.1.4** Due date/time support +- [ ] **2.1.5** Priority levels (optional) +- [ ] **2.1.6** Chore completion flow (touch to complete) +- [ ] **2.1.7** Completion history + +#### 2.2 Routine Context + +- [ ] **2.2.1** Routine builder (sequence of steps) +- [ ] **2.2.2** Step icons (kid-friendly library) +- [ ] **2.2.3** Timer per step (optional) +- [ ] **2.2.4** Multiple display modes (list, cards, slideshow) +- [ ] **2.2.5** Routine progress tracking +- [ ] **2.2.6** Streak tracking + +#### 2.3 Starter Content + +- [ ] **2.3.1** Morning routine template +- [ ] **2.3.2** Bedtime routine template +- [ ] **2.3.3** After-school routine template +- [ ] **2.3.4** Common chore templates +- [ ] **2.3.5** Icon library (100+ kid-friendly icons) + +#### 2.4 Rewards System + +- [ ] **2.4.1** Point assignment to chores/routines +- [ ] **2.4.2** Per-profile point balance +- [ ] **2.4.3** Custom reward definitions +- [ ] **2.4.4** Reward request/approval workflow +- [ ] **2.4.5** Progress-to-goal visualization +- [ ] **2.4.6** Celebration animations + +#### 2.5 Task Display Widgets + +- [ ] **2.5.1** "Today's Tasks" widget +- [ ] **2.5.2** Profile task summary +- [ ] **2.5.3** Routine progress widget +- [ ] **2.5.4** Points/rewards widget +- [ ] **2.5.5** Streak display + +#### 2.6 Kid Mode + +- [ ] **2.6.1** Simplified UI for children +- [ ] **2.6.2** Large touch targets +- [ ] **2.6.3** Emoji/icon-based labels +- [ ] **2.6.4** Non-reader friendly design +- [ ] **2.6.5** Limited destructive actions + +### Exit Criteria + +- Chores can be created, assigned, and completed on display +- Routines guide children through multi-step processes +- Points accumulate and rewards can be claimed +- Kid mode is intuitive for 6+ year olds +- All task data persists offline + +--- + +## Phase 3: Mobile Companion + +### Objective + +Deliver iOS and Android companion apps that provide full control and notifications, keeping family members informed on the go. + +### Scope + +#### 3.1 Mobile Application Shell + +- [ ] **3.1.1** React Native project setup +- [ ] **3.1.2** Navigation structure +- [ ] **3.1.3** Authentication flow +- [ ] **3.1.4** Offline capability +- [ ] **3.1.5** Deep linking support + +#### 3.2 Sync Engine + +- [ ] **3.2.1** CRDT-based sync protocol +- [ ] **3.2.2** Conflict resolution logic +- [ ] **3.2.3** Sync status indicators +- [ ] **3.2.4** Background sync +- [ ] **3.2.5** Manual sync trigger + +#### 3.3 Mobile Calendar Features + +- [ ] **3.3.1** Calendar views (day, week, month, agenda) +- [ ] **3.3.2** Event creation and editing +- [ ] **3.3.3** Calendar connection management +- [ ] **3.3.4** Profile filtering + +#### 3.4 Mobile Task Features + +- [ ] **3.4.1** Chore creation and management +- [ ] **3.4.2** Routine creation and management +- [ ] **3.4.3** Task completion (for self) +- [ ] **3.4.4** Reward management + +#### 3.5 Push Notifications + +- [ ] **3.5.1** Push notification service (APNs + FCM) +- [ ] **3.5.2** Event reminders +- [ ] **3.5.3** Chore due notifications +- [ ] **3.5.4** Completion notifications (kids completed X) +- [ ] **3.5.5** Notification preferences + +#### 3.6 Mobile Widgets + +- [ ] **3.6.1** iOS Today widget (schedule) +- [ ] **3.6.2** iOS lock screen widget +- [ ] **3.6.3** Android widget support + +#### 3.7 Sync Server (Optional) + +- [ ] **3.7.1** Server application shell +- [ ] **3.7.2** REST API for sync +- [ ] **3.7.3** WebSocket for real-time updates +- [ ] **3.7.4** User authentication (OAuth) +- [ ] **3.7.5** Push notification dispatch +- [ ] **3.7.6** Docker deployment + +### Exit Criteria + +- Mobile apps available on iOS and Android +- Changes sync between display and mobile within 60 seconds +- Push notifications delivered reliably +- Offline mode functional on mobile +- App Store / Play Store ready + +--- + +## Phase 4: Household Management + +### Objective + +Complete the household coordination features including profiles, meal planning, lists, and caregiver access. + +### Scope + +#### 4.1 Profile Management + +- [ ] **4.1.1** Profile creation and editing +- [ ] **4.1.2** Avatar/photo upload +- [ ] **4.1.3** Color selection +- [ ] **4.1.4** Birthday tracking +- [ ] **4.1.5** Caregiver info section +- [ ] **4.1.6** Pet profiles +- [ ] **4.1.7** Role assignment + +#### 4.2 Meal Planning Context + +- [ ] **4.2.1** Weekly meal plan view +- [ ] **4.2.2** Meal slots (breakfast, lunch, dinner, snacks) +- [ ] **4.2.3** Recipe storage +- [ ] **4.2.4** Recipe import from URLs +- [ ] **4.2.5** Ingredient management +- [ ] **4.2.6** "Add to grocery list" action +- [ ] **4.2.7** Per-profile dietary preferences +- [ ] **4.2.8** Meal plan templates + +#### 4.3 List Management Context + +- [ ] **4.3.1** Custom list creation +- [ ] **4.3.2** List templates (grocery, packing, etc.) +- [ ] **4.3.3** Checklist view +- [ ] **4.3.4** Board/kanban view +- [ ] **4.3.5** Category grouping +- [ ] **4.3.6** Item quantities and notes +- [ ] **4.3.7** Private lists (mobile only) +- [ ] **4.3.8** List sharing + +#### 4.4 Caregiver Access + +- [ ] **4.4.1** Caregiver invitation flow +- [ ] **4.4.2** Time-limited access tokens +- [ ] **4.4.3** Caregiver portal (web, no app required) +- [ ] **4.4.4** View-only calendar access +- [ ] **4.4.5** Caregiver info display +- [ ] **4.4.6** Configurable visibility + +#### 4.5 Display Enhancements + +- [ ] **4.5.1** Meal plan widget on display +- [ ] **4.5.2** Grocery list widget +- [ ] **4.5.3** Profile quick-view +- [ ] **4.5.4** Dashboard customization + +#### 4.6 Grocery Integration (Optional) + +- [ ] **4.6.1** Instacart API integration (US only) +- [ ] **4.6.2** Send list to Instacart +- [ ] **4.6.3** Alternative delivery services + +### Exit Criteria + +- Complete profile management across all platforms +- Meal planning functional with recipe storage +- Lists usable for grocery and custom purposes +- Caregivers can access via web link +- All features sync across devices + +--- + +## Phase 5: Intelligence Layer + +### Objective + +Add AI-powered features that reduce manual data entry and provide intelligent suggestions. + +### Scope + +#### 5.1 Magic Import Service + +- [ ] **5.1.1** Email forwarding inbox +- [ ] **5.1.2** Email parsing (ics attachments, event detection) +- [ ] **5.1.3** Photo/screenshot OCR +- [ ] **5.1.4** PDF parsing (school schedules) +- [ ] **5.1.5** Natural language text parsing +- [ ] **5.1.6** URL scraping (event pages) +- [ ] **5.1.7** Approval queue UI +- [ ] **5.1.8** Batch approval + +#### 5.2 Content Extraction + +- [ ] **5.2.1** Event extraction (date, time, location, title) +- [ ] **5.2.2** Recurring pattern detection +- [ ] **5.2.3** Meal/recipe extraction from photos +- [ ] **5.2.4** List item extraction from photos +- [ ] **5.2.5** Handwriting recognition + +#### 5.3 AI Suggestions + +- [ ] **5.3.1** Meal plan suggestions (based on preferences) +- [ ] **5.3.2** Chore assignment suggestions +- [ ] **5.3.3** Schedule conflict detection +- [ ] **5.3.4** Routine optimization tips +- [ ] **5.3.5** Grocery list suggestions (from meal plan) + +#### 5.4 Learning Pipeline + +- [ ] **5.4.1** Feedback collection (approvals/rejections) +- [ ] **5.4.2** Model fine-tuning (if self-hosted) +- [ ] **5.4.3** Privacy-preserving learning + +#### 5.5 Voice Input (Optional, Constrained) + +- [ ] **5.5.1** Wake word detection (local) +- [ ] **5.5.2** Voice-to-text for specific commands +- [ ] **5.5.3** "Add event" voice command +- [ ] **5.5.4** "Add to list" voice command +- [ ] **5.5.5** No open-ended queries (zero distraction) + +### Exit Criteria + +- Emails can be forwarded to create calendar events +- Photos of schedules are parsed with high accuracy +- Approval queue prevents unwanted automatic changes +- AI suggestions are helpful and non-intrusive +- Privacy maintained (local processing preferred) + +--- + +## Phase 6: Ecosystem Expansion + +### Objective + +Transform Luminous into a platform that supports community contributions, third-party integrations, and extensibility. + +### Scope + +#### 6.1 Plugin Architecture + +- [ ] **6.1.1** Plugin manifest format +- [ ] **6.1.2** Plugin sandboxing +- [ ] **6.1.3** Plugin lifecycle management +- [ ] **6.1.4** Widget plugins (custom display widgets) +- [ ] **6.1.5** Integration plugins (new calendar providers) +- [ ] **6.1.6** Plugin marketplace/registry + +#### 6.2 API Gateway + +- [ ] **6.2.1** Public REST API +- [ ] **6.2.2** GraphQL API (optional) +- [ ] **6.2.3** API documentation (OpenAPI) +- [ ] **6.2.4** API key management +- [ ] **6.2.5** Rate limiting +- [ ] **6.2.6** Webhook support + +#### 6.3 Additional Integrations + +- [ ] **6.3.1** Microsoft 365 two-way sync +- [ ] **6.3.2** iCloud CalDAV two-way sync +- [ ] **6.3.3** TeamSnap integration +- [ ] **6.3.4** School calendar integrations +- [ ] **6.3.5** Home automation (Home Assistant) +- [ ] **6.3.6** Smart display (non-Luminous) API + +#### 6.4 Community Tools + +- [ ] **6.4.1** Routine template sharing +- [ ] **6.4.2** Icon pack contributions +- [ ] **6.4.3** Theme sharing +- [ ] **6.4.4** Translation contributions (i18n) +- [ ] **6.4.5** Community forum/Discord + +#### 6.5 Enterprise Features (Optional) + +- [ ] **6.5.1** Multi-household support +- [ ] **6.5.2** Centralized administration +- [ ] **6.5.3** SSO/SAML integration +- [ ] **6.5.4** Audit logging + +### Exit Criteria + +- Third-party developers can create plugins +- Public API enables automation and integrations +- Community can contribute routines, icons, themes +- Internationalization supports major languages +- Platform is self-sustaining with community contributions + +--- + +## Future Vision + +### Beyond Phase 6 + +These features are under consideration for future development: + +| Feature | Description | Considerations | +|---------|-------------|----------------| +| **Multiple Displays** | Sync across multiple displays in home | Technical complexity, use case validation | +| **AR/VR Integration** | View schedule in AR glasses | Hardware dependency, limited audience | +| **Wearable Support** | Apple Watch / Wear OS companion | Reduced scope, notification focus | +| **Smart Home Routines** | Trigger home automation from routines | Integration complexity | +| **Family Games** | Educational games as rewards | Conflicts with zero-distraction | +| **Photo Frame Mode** | Display family photos when idle | Scope creep risk | +| **Video Messages** | Short video notes for family | Conflicts with zero-distraction | + +### Technology Evolution + +| Current | Future Consideration | Rationale | +|---------|---------------------|-----------| +| Electron | Tauri | Smaller bundle, better performance | +| SQLite | Durable Objects (Cloudflare) | Managed sync infrastructure | +| React | React 19 Server Components | Improved performance | +| Manual Themes | AI-generated themes | Personalization | + +--- + +## Dependency Map + +### Phase Dependencies + +``` +Phase 0 (Foundation) + │ + └──▶ Phase 1 (Core Display) + │ + ├──▶ Phase 2 (Task Management) + │ │ + │ └──▶ Phase 3 (Mobile Companion) + │ │ + │ └──▶ Phase 4 (Household) + │ │ + │ └──▶ Phase 5 (Intelligence) + │ │ + │ └──▶ Phase 6 (Ecosystem) + │ + └──▶ (Parallel) Web App MVP +``` + +### Critical Path + +The critical path for MVP delivery: + +``` +0.1 Dev Environment → 0.3 Core Structure → 0.5 Domain Models → +1.1 Display Shell → 1.2 Calendar Integration → 1.3 Calendar Views → +1.7 Offline → MVP Release +``` + +### Optional Parallel Tracks + +These can be developed in parallel after Phase 0: + +- **Web App MVP**: Basic web access (Phase 1 parallel) +- **Additional Calendar Providers**: Outlook, iCloud (Phase 1+) +- **Sync Server**: Multi-device sync (Phase 3 parallel) + +--- + +## Risk Register + +### Technical Risks + +| Risk | Impact | Probability | Mitigation | +|------|--------|-------------|------------| +| **Electron performance on Pi** | High | Medium | Evaluate Tauri early; optimize bundle | +| **Calendar API rate limits** | Medium | Medium | Aggressive caching; exponential backoff | +| **Sync conflicts** | High | Medium | CRDT-based design; extensive testing | +| **SQLite limitations on web** | Medium | Low | OPFS fallback; sql.js optimization | +| **React Native compatibility** | Medium | Medium | Pin versions; thorough device testing | + +### Product Risks + +| Risk | Impact | Probability | Mitigation | +|------|--------|-------------|------------| +| **Scope creep (entertainment)** | High | Medium | Strict ADR enforcement; design reviews | +| **Kid UX too complex** | High | Medium | User testing with children; iteration | +| **Caregiver adoption** | Medium | Medium | Simplified web portal; no app required | +| **Calendar sync accuracy** | High | Low | Comprehensive sync testing; monitoring | + +### Project Risks + +| Risk | Impact | Probability | Mitigation | +|------|--------|-------------|------------| +| **Contributor availability** | Medium | Medium | Comprehensive docs; maintainer diversity | +| **Technology obsolescence** | Medium | Low | Standard tech choices; migration paths | +| **Legal/licensing issues** | High | Low | AGPL clarity; dependency audit | + +--- + +## Related Documents + +- [Project Overview](./PROJECT-OVERVIEW.md) +- [Architecture Overview](./ARCHITECTURE.md) +- [Architecture Decision Records](./adr/) +- [CLAUDE.md (Development Guidelines)](../CLAUDE.md) + +--- + +## Document History + +| Version | Date | Author | Changes | +|---------|------|--------|---------| +| 1.0.0 | 2025-12-21 | Luminous Team | Initial roadmap | diff --git a/docs/adr/ADR-000-template.md b/docs/adr/ADR-000-template.md new file mode 100644 index 0000000..2b34463 --- /dev/null +++ b/docs/adr/ADR-000-template.md @@ -0,0 +1,94 @@ +# ADR-XXX: [Short Title] + +> **Status:** [Draft | Proposed | Accepted | Deprecated | Superseded by ADR-XXX] +> **Date:** YYYY-MM-DD +> **Deciders:** [List of people involved in the decision] +> **Categories:** [Architecture | Technology | Process | Design] + +## Context + +[Describe the context and problem statement. What is the issue that we're seeing that motivates this decision or change? Include any relevant background information, constraints, or driving forces.] + +## Decision Drivers + +- [Driver 1: e.g., Performance requirements] +- [Driver 2: e.g., Team expertise] +- [Driver 3: e.g., Cost considerations] +- [Driver 4: e.g., Maintainability] + +## Considered Options + +### Option 1: [Name] + +[Description of the option] + +**Pros:** +- [Pro 1] +- [Pro 2] + +**Cons:** +- [Con 1] +- [Con 2] + +### Option 2: [Name] + +[Description of the option] + +**Pros:** +- [Pro 1] +- [Pro 2] + +**Cons:** +- [Con 1] +- [Con 2] + +### Option 3: [Name] + +[Description of the option] + +**Pros:** +- [Pro 1] +- [Pro 2] + +**Cons:** +- [Con 1] +- [Con 2] + +## Decision + +[State the decision that was made. Be specific and clear about what was decided.] + +## Rationale + +[Explain why this decision was made. Connect the decision to the decision drivers and explain why it best addresses them. Acknowledge trade-offs.] + +## Consequences + +### Positive + +- [Positive consequence 1] +- [Positive consequence 2] + +### Negative + +- [Negative consequence 1] +- [Negative consequence 2] + +### Neutral + +- [Neutral consequence / thing to be aware of] + +## Implementation Notes + +[Any specific guidance for implementing this decision] + +## Related Decisions + +- [ADR-XXX: Related decision] +- [ADR-YYY: Another related decision] + +## References + +- [Link to relevant documentation] +- [Link to discussion thread] +- [Link to external resource] diff --git a/docs/adr/ADR-001-typescript-primary-language.md b/docs/adr/ADR-001-typescript-primary-language.md new file mode 100644 index 0000000..31d9195 --- /dev/null +++ b/docs/adr/ADR-001-typescript-primary-language.md @@ -0,0 +1,147 @@ +# ADR-001: TypeScript as Primary Language + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Technology + +## Context + +Luminous is a cross-platform application suite consisting of: +- A display application (desktop/embedded) +- Mobile applications (iOS and Android) +- A web application +- An optional sync server +- Shared domain logic and UI components + +We need to select a primary programming language that can serve all these platforms effectively while maintaining code quality, developer experience, and long-term maintainability. + +## Decision Drivers + +- **Cross-platform capability**: Must support web, mobile, desktop, and server environments +- **Type safety**: Strong typing to catch errors early and improve maintainability +- **Developer ecosystem**: Rich tooling, libraries, and community support +- **Team familiarity**: Common knowledge base for frontend developers +- **Code sharing**: Ability to share domain logic across all platforms +- **Hiring and contributions**: Available talent pool for open-source contributions + +## Considered Options + +### Option 1: TypeScript + +TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. + +**Pros:** +- Excellent type system with gradual typing +- Native support for React, React Native, and Node.js +- Large ecosystem and community +- First-class tooling (VS Code, ESLint, etc.) +- Can share code between all platforms +- Popular among frontend developers + +**Cons:** +- Runtime type checking requires additional libraries +- Build step required +- Some edge cases where types don't match runtime behavior + +### Option 2: JavaScript (ES2024+) + +Modern JavaScript with the latest ECMAScript features. + +**Pros:** +- No build step for type checking +- Universal support +- Simpler toolchain + +**Cons:** +- No static type checking +- Higher maintenance burden at scale +- Runtime errors harder to catch +- Less IDE support for refactoring + +### Option 3: Dart/Flutter + +Cross-platform framework with its own language. + +**Pros:** +- Excellent cross-platform mobile and desktop +- Strong typing +- Hot reload + +**Cons:** +- Separate web ecosystem +- Smaller community than React +- Less code sharing with web technologies +- Different paradigm than most web developers know + +### Option 4: Kotlin Multiplatform + +Kotlin with multiplatform support. + +**Pros:** +- Strong typing +- Native performance on mobile +- Good for Android developers + +**Cons:** +- Immature web support +- Smaller React ecosystem integration +- Steeper learning curve for web developers +- Limited React Native integration + +## Decision + +We will use **TypeScript** as the primary language for all Luminous applications and packages. + +## Rationale + +TypeScript best satisfies our decision drivers: + +1. **Cross-platform**: TypeScript runs natively in all our target environments through existing runtimes (browsers, Node.js, React Native). + +2. **Type safety**: TypeScript's type system catches a large class of bugs at compile time, improving code quality and reducing runtime errors. This is critical for a family coordination app where reliability matters. + +3. **Code sharing**: With TypeScript, we can share domain models, validation logic, and business rules across display, mobile, web, and server applications through a monorepo structure. + +4. **Developer ecosystem**: The TypeScript/React ecosystem is the largest and most mature for our use case, with excellent libraries for state management, testing, and UI. + +5. **Contribution-friendly**: TypeScript is widely known, making it easier for open-source contributors to participate. + +## Consequences + +### Positive + +- Consistent language across all platforms reduces context switching +- Type definitions serve as living documentation +- Refactoring is safer with compiler-checked types +- Excellent IDE support improves developer productivity +- Large pool of potential contributors + +### Negative + +- Build step adds complexity to development workflow +- Type definitions for some libraries may be incomplete or incorrect +- Learning curve for developers new to TypeScript +- Slightly larger bundle size due to some TypeScript patterns + +### Neutral + +- Must maintain TypeScript configuration across all packages +- Team must agree on TypeScript coding conventions (strict mode, type inference, etc.) + +## Implementation Notes + +- Use TypeScript strict mode in all packages +- Configure path aliases for clean imports +- Use project references for monorepo type checking +- Prefer interfaces over types for object shapes +- Use `unknown` over `any` where type is genuinely unknown + +## Related Decisions + +- [ADR-002: React as UI Framework](./ADR-002-react-ui-framework.md) + +## References + +- [TypeScript Official Documentation](https://www.typescriptlang.org/) +- [TypeScript Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals) diff --git a/docs/adr/ADR-002-react-ui-framework.md b/docs/adr/ADR-002-react-ui-framework.md new file mode 100644 index 0000000..43c6606 --- /dev/null +++ b/docs/adr/ADR-002-react-ui-framework.md @@ -0,0 +1,159 @@ +# ADR-002: React as UI Framework + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Technology, Architecture + +## Context + +Luminous requires a UI framework that can power: +- A desktop/embedded display application (Electron or Tauri) +- iOS and Android mobile applications +- A responsive web application +- A caregiver web portal + +We need a framework that enables maximum code sharing while delivering native-feeling experiences on each platform. + +## Decision Drivers + +- **Cross-platform code sharing**: Maximize reuse of UI components and logic +- **Performance**: Smooth 60fps rendering on constrained hardware (Raspberry Pi) +- **Component model**: Support for building a design system +- **Mobile support**: Native-quality mobile applications +- **Ecosystem**: Available libraries for calendar, drag-drop, accessibility +- **Stability**: Long-term support and active maintenance + +## Considered Options + +### Option 1: React + React Native + +React for web/desktop, React Native for mobile. + +**Pros:** +- Largest ecosystem and community +- Excellent TypeScript support +- React Native provides near-native mobile performance +- Huge selection of UI libraries +- Stable and well-documented +- Share business logic and some UI code + +**Cons:** +- Not 100% code sharing between web and native +- React Native requires platform-specific code for some features +- Large bundle size for web + +### Option 2: Flutter + +Cross-platform UI framework using Dart. + +**Pros:** +- True single codebase for all platforms +- Excellent performance +- Built-in widget library +- Good for custom designs + +**Cons:** +- Dart instead of TypeScript (see ADR-001) +- Smaller ecosystem for web +- Different paradigm than web development +- Web performance not as optimized + +### Option 3: Vue + Capacitor + +Vue.js for web, wrapped in Capacitor for mobile. + +**Pros:** +- Single web-based codebase +- Simpler mental model than React +- Good TypeScript support + +**Cons:** +- Mobile apps are essentially webviews (less native feel) +- Performance limitations on low-end devices +- Smaller ecosystem than React +- Less suitable for always-on display + +### Option 4: Svelte + SvelteKit + +Svelte for web with SvelteKit. + +**Pros:** +- Excellent performance (compile-time optimization) +- Smaller bundle size +- Simple syntax + +**Cons:** +- No mature mobile solution +- Smaller ecosystem +- Less proven at scale +- TypeScript support is good but not as mature + +## Decision + +We will use **React** for web and desktop applications, and **React Native** for mobile applications. + +## Rationale + +React + React Native provides the best balance of our decision drivers: + +1. **Code sharing**: While not 100%, we can share: + - All domain logic and state management + - Business validation and rules + - Design tokens and theming + - API and data layer code + - Some UI components with react-native-web + +2. **Performance**: React's virtual DOM and React Native's native bridges provide sufficient performance for our use cases, including the Raspberry Pi display. + +3. **Ecosystem**: React has the largest selection of libraries for our needs: + - Calendar components + - Drag-and-drop for task management + - Accessibility helpers + - Animation libraries + +4. **Stability**: React is maintained by Meta with a strong commitment to backwards compatibility and clear upgrade paths. + +5. **Developer availability**: React is the most popular UI framework, maximizing our contributor pool. + +## Consequences + +### Positive + +- Access to the largest UI ecosystem +- Well-understood patterns and best practices +- Excellent tooling and debugging +- Large talent pool for contributions +- Strong TypeScript integration + +### Negative + +- Platform-specific code required for some mobile features +- Need to maintain separate but similar codebases for web/native +- React Native has some quirks and requires native knowledge for advanced features +- Learning curve for React Native-specific patterns + +### Neutral + +- Must decide on state management solution (Zustand, Redux, etc.) +- Design system needs to account for web vs native differences +- Testing requires different approaches for web and native + +## Implementation Notes + +- Use React 19 features where beneficial +- Consider `react-native-web` for maximum component sharing +- Build design system primitives that abstract platform differences +- Use Zustand for state management (lightweight, TypeScript-first) +- Implement component variants for display (large touch) vs mobile + +## Related Decisions + +- [ADR-001: TypeScript as Primary Language](./ADR-001-typescript-primary-language.md) +- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) + +## References + +- [React Documentation](https://react.dev/) +- [React Native Documentation](https://reactnative.dev/) +- [React Native Web](https://necolas.github.io/react-native-web/) diff --git a/docs/adr/ADR-003-local-first-architecture.md b/docs/adr/ADR-003-local-first-architecture.md new file mode 100644 index 0000000..7ed3fb7 --- /dev/null +++ b/docs/adr/ADR-003-local-first-architecture.md @@ -0,0 +1,169 @@ +# ADR-003: Local-First Data Architecture + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture + +## Context + +Luminous is designed for always-on operation on wall-mounted displays, which presents unique requirements: + +1. **Reliability**: The display must show current information even during internet outages +2. **Privacy**: Families want control over their personal data +3. **Performance**: UI interactions must be immediate, not dependent on network latency +4. **Self-hosting**: Users want the option to run everything locally + +We need to decide on a data architecture that addresses these requirements. + +## Decision Drivers + +- **Offline functionality**: Display must work without internet connection +- **Data ownership**: Users must be able to self-host and own their data +- **Real-time sync**: Changes should propagate quickly across devices +- **Conflict resolution**: Multiple devices may edit the same data +- **Performance**: No waiting for network on user interactions +- **Simplicity**: Architecture should be understandable and maintainable + +## Considered Options + +### Option 1: Local-First with CRDT Sync + +Data stored locally on each device, synchronized using Conflict-free Replicated Data Types. + +**Pros:** +- Works offline by default +- Immediate UI response +- Automatic conflict resolution +- Data stays local (privacy) +- Server is optional for multi-device sync + +**Cons:** +- CRDT complexity for some data types +- Storage duplication across devices +- Initial sync can be slow for large datasets +- Debugging sync issues is complex + +### Option 2: Cloud-First with Offline Cache + +Primary data in cloud, with local caching for offline use. + +**Pros:** +- Single source of truth +- Simpler conflict resolution +- Smaller local storage needs + +**Cons:** +- Requires internet for full functionality +- Privacy concerns with cloud storage +- Latency on all write operations +- Vendor lock-in with cloud provider +- Ongoing hosting costs + +### Option 3: Hybrid (Local Primary, Cloud Backup) + +Local storage as primary, cloud as optional backup and sync. + +**Pros:** +- Best of both approaches +- Optional cloud dependency +- Privacy-preserving by default + +**Cons:** +- Two systems to maintain +- Complex sync logic +- Potential for data divergence + +## Decision + +We will implement a **Local-First architecture** with optional CRDT-based synchronization. + +Core principles: +1. All data is stored locally on each device first +2. UI operations read/write to local storage only +3. Synchronization happens in the background +4. The server is optional and only coordinates sync between devices +5. Conflicts are resolved automatically using CRDTs where possible + +## Rationale + +Local-first architecture best meets our requirements: + +1. **Reliability**: The display always has local data available. Even if the internet is down for days, the calendar shows cached events, chores are visible, and tasks can be completed. + +2. **Privacy**: Data never leaves the home network unless the user explicitly configures sync. Self-hosters can run everything locally. + +3. **Performance**: All UI interactions are instant because they only touch local storage. Sync happens asynchronously. + +4. **User experience**: No loading spinners for basic operations. The app feels native and responsive. + +5. **Self-hosting friendly**: The optional sync server can run on a Raspberry Pi or NAS, keeping all data on the local network. + +## Consequences + +### Positive + +- Display works perfectly offline +- Immediate UI feedback on all actions +- No mandatory cloud dependency +- Strong privacy story +- Works well with self-hosting +- Reduced server infrastructure needs + +### Negative + +- Must implement sync logic (complexity) +- CRDT learning curve for team +- Storage requirements higher (data on all devices) +- Some calendar integrations require internet (unavoidable) +- Conflict resolution edge cases to handle + +### Neutral + +- Need to choose and implement CRDT library +- Must design data models with CRDTs in mind +- Initial sync may take time for new devices +- Testing requires simulating various sync scenarios + +## Implementation Notes + +### Storage Stack + +- **Display/Desktop**: SQLite via sql.js (WebAssembly) +- **Mobile**: SQLite via expo-sqlite or react-native-sqlite +- **Web**: Origin Private File System (OPFS) or IndexedDB fallback + +### Sync Strategy + +1. **Event log approach**: Track all changes as events +2. **CRDT types**: Use Yjs or Automerge for collaborative data +3. **Sync protocol**: WebSocket for real-time, REST for batch + +### Data Model Considerations + +- Design entities with CRDT-friendly IDs (UUIDs) +- Avoid counters (use G-Counters or PN-Counters) +- Prefer append-only where possible (completions, events) +- Use tombstones for deletions (soft delete) + +### Conflict Scenarios + +| Data Type | Conflict Strategy | +|-----------|------------------| +| Events | Last-write-wins with vector clocks | +| Chores | Merge fields, LWW for each field | +| Completions | Append-only (no conflicts) | +| Lists | CRDT set with tombstones | +| Profiles | Server-authoritative (rare edits) | + +## Related Decisions + +- [ADR-001: TypeScript as Primary Language](./ADR-001-typescript-primary-language.md) +- [ADR-004: Two-Way Sync Initially Google-Only](./ADR-004-two-way-sync-google-first.md) + +## References + +- [Local-First Software](https://www.inkandswitch.com/local-first/) +- [Yjs CRDT Library](https://yjs.dev/) +- [Automerge](https://automerge.org/) +- [CRDTs: The Hard Parts](https://www.youtube.com/watch?v=x7drE24geUw) diff --git a/docs/adr/ADR-004-two-way-sync-google-first.md b/docs/adr/ADR-004-two-way-sync-google-first.md new file mode 100644 index 0000000..c4ab17b --- /dev/null +++ b/docs/adr/ADR-004-two-way-sync-google-first.md @@ -0,0 +1,184 @@ +# ADR-004: Two-Way Sync Initially Google-Only + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Technology + +## Context + +Luminous needs to integrate with external calendar providers to aggregate family schedules. The key question is whether to support read-only access (displaying external calendars) or full two-way synchronization (creating/editing events that sync back to the provider). + +Two-way sync is significantly more complex than read-only integration due to: +- Conflict resolution with external system +- Different data models and capabilities per provider +- OAuth token management and refresh +- Rate limiting and API quotas +- Handling provider-specific features (Google Meet, Teams, etc.) + +## Decision Drivers + +- **User expectations**: Users expect changes made in Luminous to appear in their calendar app +- **Implementation complexity**: Each provider has different APIs and behaviors +- **Reliability**: Sync errors can lose or duplicate events +- **Maintenance burden**: APIs change; each provider adds maintenance load +- **Time to market**: Need to ship functional product reasonably quickly +- **Open source sustainability**: Maintainers must be able to support integrations + +## Considered Options + +### Option 1: Two-Way Sync with All Providers from Start + +Full bidirectional sync with Google, Outlook, iCloud, and CalDAV. + +**Pros:** +- Complete feature set at launch +- Matches competitor capabilities + +**Cons:** +- Very high implementation effort +- Delays initial release significantly +- Multiple complex APIs to maintain +- iCloud has significant limitations +- CalDAV has many edge cases + +### Option 2: Read-Only for All, Two-Way for None + +Only display calendars; all event creation is in external apps. + +**Pros:** +- Simplest implementation +- No sync conflicts possible +- Works with any ICS feed + +**Cons:** +- Users must switch apps to add events +- Breaks "single command center" value proposition +- Chore/task completion can't sync to calendars + +### Option 3: Two-Way with Google First, Read-Only Others + +Full sync with Google Calendar initially; read-only with others. + +**Pros:** +- Delivers two-way sync for largest user base +- Manageable implementation scope +- Clear path to add more providers +- Google API is well-documented and stable + +**Cons:** +- Users of other providers have limited functionality +- Feature disparity between providers + +### Option 4: Internal Calendar with Export + +Luminous-only calendar, exportable to other systems. + +**Pros:** +- Full control over data model +- No provider dependencies + +**Cons:** +- Doesn't aggregate existing calendars +- Users manage two calendar systems +- Misses core product value + +## Decision + +We will implement **two-way synchronization with Google Calendar first**, with read-only support for other providers (Outlook/Office 365, iCloud, ICS URLs). + +Expansion to two-way sync with other providers will be prioritized based on user demand and contribution. + +## Rationale + +1. **Market coverage**: Google Calendar has the largest market share for personal/family calendars. Supporting it first covers the most users. + +2. **API quality**: Google Calendar API is mature, well-documented, and has clear OAuth flows. It's the most straightforward to implement correctly. + +3. **Scope management**: Implementing one two-way sync correctly is better than implementing multiple poorly. We can learn from Google integration before adding others. + +4. **User value**: Even with read-only access, users get the core value of seeing all calendars in one place. Two-way sync is additive. + +5. **Contribution opportunity**: Read-only providers are easier for contributors to add, while core team focuses on sync complexity. + +## Consequences + +### Positive + +- Manageable scope for initial implementation +- High-quality Google integration +- Clear roadmap for additional providers +- Read-only still provides aggregation value +- Lower maintenance burden initially + +### Negative + +- Outlook/iCloud users have limited functionality at launch +- Potential perception of "Google-only" product +- Must clearly communicate provider capabilities +- Some users may wait for their provider support + +### Neutral + +- Need to design adapter pattern for easy provider addition +- Documentation must be clear about sync capabilities +- Provider support becomes a contribution opportunity + +## Implementation Notes + +### Google Calendar Integration + +1. **OAuth 2.0 flow** with offline access (refresh tokens) +2. **Incremental sync** using sync tokens +3. **Rate limit handling** with exponential backoff +4. **Webhook support** for real-time updates (where available) + +### Read-Only Providers + +| Provider | Protocol | Notes | +|----------|----------|-------| +| Outlook/M365 | Microsoft Graph API | OAuth 2.0, JSON | +| iCloud | CalDAV | App-specific passwords required | +| Generic CalDAV | CalDAV | Basic or OAuth | +| ICS URLs | HTTP(S) | No authentication typically | + +### Adapter Interface + +```typescript +interface CalendarAdapter { + // All providers + listCalendars(): Promise; + fetchEvents(calendarId: string, range: DateRange): Promise; + + // Two-way only (Google initially) + createEvent?(calendarId: string, event: EventInput): Promise; + updateEvent?(calendarId: string, eventId: string, event: EventInput): Promise; + deleteEvent?(calendarId: string, eventId: string): Promise; +} +``` + +### Sync Status UI + +Users need clear visibility into: +- Which calendars are read-only vs read-write +- Last sync time per calendar +- Sync errors and how to resolve them + +## Migration Path + +Adding two-way sync for additional providers: + +1. **Phase 1** (launch): Google two-way, others read-only +2. **Phase 2**: Microsoft 365/Outlook two-way +3. **Phase 3**: CalDAV two-way (generic) +4. **Future**: iCloud (if Apple improves API access) + +## Related Decisions + +- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) + +## References + +- [Google Calendar API](https://developers.google.com/calendar/api) +- [Microsoft Graph Calendar API](https://learn.microsoft.com/en-us/graph/api/resources/calendar) +- [CalDAV RFC 4791](https://datatracker.ietf.org/doc/html/rfc4791) diff --git a/docs/adr/ADR-005-magic-import-approval.md b/docs/adr/ADR-005-magic-import-approval.md new file mode 100644 index 0000000..9005d48 --- /dev/null +++ b/docs/adr/ADR-005-magic-import-approval.md @@ -0,0 +1,183 @@ +# ADR-005: Magic Import Requires Approval + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Design, Architecture + +## Context + +Luminous includes a "Magic Import" feature that uses AI/ML to extract structured data (calendar events, meals, list items) from unstructured inputs (emails, photos, PDFs, text). This dramatically reduces manual data entry. + +The key question is: should extracted content be automatically published to the family calendar/lists, or should it require explicit approval? + +This decision has significant implications for user trust, data accuracy, and the overall experience. + +## Decision Drivers + +- **Data accuracy**: AI extraction is not perfect; errors can cause real problems (missed appointments, wrong times) +- **User trust**: Families trust us with important scheduling data +- **Convenience**: The value of magic import is reducing manual work +- **Control**: Users want to feel in control of their family data +- **Spam prevention**: Forwarded emails could contain unwanted content +- **Learning**: System needs feedback to improve extraction + +## Considered Options + +### Option 1: Auto-Publish Everything + +All extracted content is immediately added to calendars/lists. + +**Pros:** +- Maximum convenience +- True "magic" experience +- Minimal user effort + +**Cons:** +- Errors go straight to calendar +- Spam emails become events +- Users may miss incorrect data +- Loss of control feeling +- Hard to undo bulk imports + +### Option 2: Always Require Approval + +All imports go to an approval queue; nothing is published without explicit action. + +**Pros:** +- User always in control +- Errors caught before publishing +- Spam filtered naturally +- Provides feedback for model improvement +- Builds trust through transparency + +**Cons:** +- Additional step for every import +- May feel like extra work +- Queue can pile up if ignored +- Reduces "magic" feeling + +### Option 3: Confidence-Based Auto-Publish + +High-confidence extractions auto-publish; low-confidence goes to queue. + +**Pros:** +- Best of both approaches +- Reduces approval burden for clear cases +- Still catches uncertain extractions + +**Cons:** +- Confidence thresholds are arbitrary +- Users may not understand why some auto-publish +- Inconsistent experience +- False confidence can cause errors + +### Option 4: Per-Source Trust Levels + +Users configure which sources auto-publish (e.g., school emails = auto, unknown = review). + +**Pros:** +- User-controlled automation +- Reduces burden for trusted sources +- Clear mental model + +**Cons:** +- Setup complexity +- Users may not configure properly +- Trusted sources can still have errors +- Attackers could spoof trusted sources + +## Decision + +We will require **explicit approval for all Magic Import extractions** before publishing to calendars, lists, or other family data. + +No AI-extracted content will appear on the family calendar or lists until a household admin or adult member approves it. + +## Rationale + +1. **Trust is paramount**: Families are trusting us with their most important coordination data. A single missed soccer game due to an import error could undermine all trust in the system. The approval step makes users partners in the process. + +2. **AI accuracy**: Current extraction technology, while impressive, is not perfect. Time zone issues, date format ambiguities, and OCR errors are common. Human review catches these. + +3. **Spam and security**: Email forwarding opens a potential vector for unwanted content. The approval queue acts as a filter. + +4. **Feedback loop**: Approvals and rejections provide valuable training signal. Users correcting extractions helps the system improve over time. + +5. **Mental model**: Users understand "I forwarded an email, now I approve what was extracted." This is clearer than "sometimes it appears, sometimes it doesn't." + +6. **Industry precedent**: Competitor products (Hearth Helper) use approval workflows and users accept them. + +## Consequences + +### Positive + +- Users feel in control of their data +- Errors are caught before impacting family +- Natural spam filtering +- Training data for model improvement +- Clear, consistent user experience +- Builds trust in the AI features + +### Negative + +- Extra step for every import +- Approval queue requires attention +- May feel less "magical" +- Users must check queue regularly +- Mobile notifications needed for pending imports + +### Neutral + +- Need to design efficient approval UI (batch approve, quick edits) +- Need to handle stale items in queue +- Should track approval/rejection rates for quality monitoring + +## Implementation Notes + +### Approval Queue + +- Visible on display and mobile app +- Push notification for new pending items +- Batch approval with individual editing +- Auto-expire old unapproved items (30 days with warning) +- Show extraction confidence to help users prioritize review + +### Approval UI Features + +``` +┌─────────────────────────────────────────────────────┐ +│ 📬 Magic Import Queue (3 pending) │ +├─────────────────────────────────────────────────────┤ +│ │ +│ ┌─────────────────────────────────────────────────┐ │ +│ │ 📅 Soccer Practice │ │ +│ │ Extracted from: school-email.pdf │ │ +│ │ When: Tuesdays & Thursdays, 4:00 PM │ │ +│ │ Where: Main Field │ │ +│ │ Assign to: [Emma ▼] │ │ +│ │ │ │ +│ │ [✓ Approve] [Edit] [✗ Reject] │ │ +│ └─────────────────────────────────────────────────┘ │ +│ │ +│ [Approve All] [Review Later] │ +│ │ +└─────────────────────────────────────────────────────┘ +``` + +### Future Considerations + +We may revisit this decision if: +- Extraction accuracy reaches very high levels (>99%) +- Users strongly request auto-publish option +- Trusted source configuration proves reliable + +Any such change would be opt-in and default to approval-required. + +## Related Decisions + +- [ADR-006: Zero-Distraction Design Principle](./ADR-006-zero-distraction-principle.md) + +## References + +- [Hearth Display Helper Feature](https://www.hearthapp.com/) +- [Design for Trust in AI Systems](https://www.nngroup.com/articles/ai-trust/) diff --git a/docs/adr/ADR-006-zero-distraction-principle.md b/docs/adr/ADR-006-zero-distraction-principle.md new file mode 100644 index 0000000..743a39c --- /dev/null +++ b/docs/adr/ADR-006-zero-distraction-principle.md @@ -0,0 +1,179 @@ +# ADR-006: Zero-Distraction Design Principle + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Design, Architecture + +## Context + +Smart displays and tablets often become sources of distraction rather than productivity tools. Children (and adults) are drawn to games, videos, and web browsing when these features are available. This undermines the core purpose of a family command center. + +We need to decide whether Luminous should: +- Be a general-purpose smart display with family features +- Be a focused, single-purpose family coordination tool + +This decision fundamentally shapes the product's identity and technical architecture. + +## Decision Drivers + +- **Product differentiation**: What makes Luminous unique in the market +- **Child focus**: Keeping kids on task, not distracted +- **Parent peace of mind**: Knowing the display won't become a distraction +- **Simplicity**: Focused products are easier to build and maintain +- **Feature creep**: Slippery slope from "one game" to "app store" +- **Market positioning**: Aligning with families who actively limit screen time + +## Considered Options + +### Option 1: General-Purpose Smart Display + +Full web browser, app installation, video streaming, voice assistant. + +**Pros:** +- Maximum flexibility +- Competes with Amazon Echo Show, Google Nest Hub +- More features = more value (perception) + +**Cons:** +- Becomes a distraction device +- Kids gravitate to entertainment +- Parental controls become complex +- Competes with well-funded incumbents +- Dilutes core purpose + +### Option 2: Limited Entertainment with Controls + +Some entertainment features (games, videos) with parental controls. + +**Pros:** +- Rewards for chore completion (screen time) +- Appeals to broader audience +- "Balanced" approach + +**Cons:** +- Controls are never perfect +- Kids find workarounds +- Constant negotiation about access +- Maintenance burden for games/videos +- Still a distraction + +### Option 3: Zero-Distraction (Focused Purpose) + +No web browsing, no games, no videos, no general-purpose voice assistant. Only family coordination features. + +**Pros:** +- Clear product identity +- Parents trust it won't distract kids +- Simpler to build and maintain +- Differentiates from smart displays +- Aligns with screen-time-conscious families +- Easier to explain value proposition + +**Cons:** +- Some users may want entertainment +- Perceived as "limited" +- Can't use video calling +- Less "cool factor" + +## Decision + +Luminous will follow a **zero-distraction design principle**. The following capabilities are explicitly excluded: + +### Excluded Features + +| Feature | Reason | +|---------|--------| +| Web browser | Primary distraction vector | +| App installation | Enables distraction apps | +| Video streaming | Entertainment, not coordination | +| Games (beyond reward animations) | Distraction, not coordination | +| Social media | Distraction, privacy concerns | +| Open-ended voice assistant | Leads to entertainment queries | +| News feeds | Distraction, not family-specific | +| Video calling | Scope creep, better done on other devices | + +### Included Features (That Could Be Distracting But Serve Core Purpose) + +| Feature | Justification | +|---------|---------------| +| Weather | Glanceable, helps with planning | +| Photo frame mode (idle) | Ambient, not interactive | +| Celebration animations | Brief, positive reinforcement | +| Audio cues for routines | Functional, not entertainment | + +## Rationale + +1. **Market differentiation**: Every tech company makes smart displays. We differentiate by what we *don't* do. This is our version of Basecamp's "No is easier to do." + +2. **Trust with families**: When a parent mounts Luminous on the wall, they know it won't become another screen kids fight over. This trust is our core value proposition. + +3. **Competitor alignment**: Skylight explicitly markets "no apps, no web browsing" as a feature, and families respond positively. This validates the approach. + +4. **Development focus**: By not building entertainment features, we focus engineering effort on making coordination features excellent. + +5. **Child psychology**: The presence of entertainment options, even if controlled, creates negotiation and conflict. Absence removes the issue entirely. + +6. **Screen time movement**: Many families are actively reducing screen time. Luminous is an ally, not another source of screen conflict. + +## Consequences + +### Positive + +- Clear product positioning and messaging +- Parents trust the display +- No complex parental control systems +- Simpler architecture and codebase +- Focused development roadmap +- Aligns with screen-time-conscious families + +### Negative + +- Some users will want entertainment features +- Cannot use gamification with actual games +- May be perceived as "limited" by some +- Video calling must be done on other devices + +### Neutral + +- Must resist feature requests for entertainment +- Need to clearly communicate product scope +- Rewards system limited to points/achievements, not screen time + +## Implementation Notes + +### Technical Enforcement + +1. **No browser component**: Display app doesn't include web rendering for arbitrary URLs (only specific integrations like weather) + +2. **Kiosk mode**: Display runs in locked-down mode, no escape to OS + +3. **No URL input**: No user-facing way to enter arbitrary URLs + +4. **Curated integrations**: External services are curated and purpose-specific + +### Messaging + +Product messaging should emphasize: +- "Not a smart display, a family display" +- "No distractions, just coordination" +- "The screen you trust your kids with" +- "What it doesn't do is the point" + +### Handling Feature Requests + +When users request entertainment features, respond with: +1. Acknowledge the request +2. Explain the design philosophy +3. Suggest alternative devices for that purpose +4. Point to this ADR for detailed reasoning + +## Related Decisions + +- [ADR-005: Magic Import Requires Approval](./ADR-005-magic-import-approval.md) + +## References + +- [Skylight Calendar - No Apps, No Web](https://www.skylightcal.com/) +- [Center for Humane Technology](https://www.humanetech.com/) +- [Cal Newport - Digital Minimalism](https://www.calnewport.com/books/digital-minimalism/) diff --git a/docs/adr/ADR-007-self-hosting-first.md b/docs/adr/ADR-007-self-hosting-first.md new file mode 100644 index 0000000..f745aaa --- /dev/null +++ b/docs/adr/ADR-007-self-hosting-first.md @@ -0,0 +1,200 @@ +# ADR-007: Self-Hosting as Primary Deployment Model + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Design + +## Context + +Luminous is an open-source project that handles sensitive family data. We need to decide on the primary deployment model: + +1. Cloud-hosted SaaS (we run the infrastructure) +2. Self-hosted (users run their own infrastructure) +3. Hybrid (both options available) + +This decision affects architecture, data ownership, privacy, costs, and the project's sustainability model. + +## Decision Drivers + +- **Privacy**: Families want control over their personal data +- **Data ownership**: Users should own their data outright +- **Cost sustainability**: Open-source projects need sustainable funding +- **Simplicity for users**: Not all users are technical +- **Project control**: Avoiding infrastructure lock-in +- **Open-source ethos**: Aligning with open-source values + +## Considered Options + +### Option 1: Cloud-Only SaaS + +Luminous runs as a cloud service; users connect their displays and apps. + +**Pros:** +- Simple user setup +- Recurring revenue for sustainability +- Easier to push updates +- Centralized support + +**Cons:** +- Users don't control their data +- Infrastructure costs +- Privacy concerns +- Vendor lock-in +- Conflicts with open-source ethos + +### Option 2: Self-Hosting Only + +Users must run their own server; no cloud option provided. + +**Pros:** +- Complete user data ownership +- No infrastructure costs for project +- Maximum privacy +- True open-source model + +**Cons:** +- High barrier to entry +- Limits adoption to technical users +- Support burden for diverse environments +- Updates require user action + +### Option 3: Self-Hosting First, Cloud Optional + +Self-hosting is the primary model; cloud is an optional convenience layer. + +**Pros:** +- Users can self-host with full features +- Cloud option for less technical users +- Potential revenue from cloud tier +- Maintains open-source credibility +- User choice + +**Cons:** +- Must maintain both models +- Cloud still requires infrastructure +- May cannibalize self-hosting + +### Option 4: Local-First (No Server Required) + +Devices sync peer-to-peer; server is optional even for multi-device. + +**Pros:** +- Minimal infrastructure +- True local-first +- Works in isolated networks + +**Cons:** +- Peer-to-peer sync is complex +- Devices must be discoverable +- No remote access without server + +## Decision + +Luminous will use **self-hosting as the primary deployment model**, with the application designed to work fully without any cloud dependency. + +### Deployment Tiers + +| Tier | Description | Target User | +|------|-------------|-------------| +| **Single Device** | Display + mobile apps sync locally | Non-technical families | +| **Self-Hosted Server** | Docker container on home network | Technical families | +| **Cloud-Hosted** | Managed hosting (future, optional) | Convenience seekers | + +## Rationale + +1. **Privacy alignment**: Families increasingly care about data privacy. Self-hosting ensures family schedules, chore data, and personal information never leave the home network. + +2. **Open-source values**: A self-hostable product aligns with open-source principles. Users aren't dependent on our infrastructure or business continuity. + +3. **Cost sustainability**: We don't bear hosting costs for every user. This makes the project more sustainable long-term. + +4. **Local-first synergy**: Our local-first architecture (ADR-003) means the server is only needed for multi-device sync, not for basic operation. This reduces the barrier to self-hosting. + +5. **Differentiation**: Most competitors are cloud-dependent. Self-hosting is a feature for privacy-conscious families. + +6. **Community contribution**: Self-hosters are often the most engaged contributors to open-source projects. + +## Consequences + +### Positive + +- Users own and control their data +- No infrastructure costs for the project +- Strong privacy story +- Attracts privacy-conscious families +- Aligns with open-source community +- Diverse deployment environments strengthen the product + +### Negative + +- Higher setup barrier for non-technical users +- Must support diverse self-hosted environments +- Less visibility into usage patterns +- Harder to push critical updates +- Potential fragmentation of versions + +### Neutral + +- Docker becomes a deployment requirement +- Documentation must cover self-hosting thoroughly +- May offer managed hosting later for revenue + +## Implementation Notes + +### Single-Device Mode (Simplest) + +For families with only one display and one or two mobile devices: +- Display runs embedded sync service +- Mobile apps connect to display on local network +- No separate server needed +- Setup: Install display app, scan QR code on mobile + +### Self-Hosted Server + +For families wanting remote access or multiple displays: +- Docker container with simple configuration +- Runs on Raspberry Pi, NAS, or any Docker host +- Handles sync coordination and push notifications +- Can expose via reverse proxy for remote access + +```yaml +# docker-compose.yml +version: '3.8' +services: + luminous: + image: luminous/server:latest + ports: + - "3000:3000" + volumes: + - ./data:/data + environment: + - LUMINOUS_SECRET_KEY=${SECRET_KEY} + restart: unless-stopped +``` + +### Future Cloud Option + +If we offer managed hosting: +- Same Docker image, managed by us +- Optional, paid tier +- Data export always available +- No feature differentiation from self-hosted + +### Update Strategy + +For self-hosted users: +- Watchtower or Renovate for auto-updates +- In-app update notifications +- Release notes and migration guides +- Semantic versioning for compatibility + +## Related Decisions + +- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) + +## References + +- [Self-Hosting Guide (future)](../guides/self-hosting.md) +- [Open Source Sustainability](https://opensource.guide/getting-paid/) +- [Home Assistant - Self-Hosted Model](https://www.home-assistant.io/) diff --git a/docs/adr/README.md b/docs/adr/README.md new file mode 100644 index 0000000..ddc79f9 --- /dev/null +++ b/docs/adr/README.md @@ -0,0 +1,38 @@ +# Architecture Decision Records + +This directory contains Architecture Decision Records (ADRs) for the Luminous project. + +## What is an ADR? + +An Architecture Decision Record captures an important architectural decision made along with its context and consequences. ADRs are used to document why certain decisions were made and to communicate these decisions to stakeholders. + +## ADR Template + +New ADRs should follow the template in [ADR-000-template.md](./ADR-000-template.md). + +## ADR Index + +| ADR | Title | Status | Date | +|-----|-------|--------|------| +| [ADR-001](./ADR-001-typescript-primary-language.md) | TypeScript as Primary Language | Accepted | 2025-12-21 | +| [ADR-002](./ADR-002-react-ui-framework.md) | React as UI Framework | Accepted | 2025-12-21 | +| [ADR-003](./ADR-003-local-first-architecture.md) | Local-First Data Architecture | Accepted | 2025-12-21 | +| [ADR-004](./ADR-004-two-way-sync-google-first.md) | Two-Way Sync Initially Google-Only | Accepted | 2025-12-21 | +| [ADR-005](./ADR-005-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | +| [ADR-006](./ADR-006-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | +| [ADR-007](./ADR-007-self-hosting-first.md) | Self-Hosting as Primary Model | Accepted | 2025-12-21 | + +## ADR Lifecycle + +- **Draft**: Initial proposal under discussion +- **Proposed**: Ready for review and approval +- **Accepted**: Decision has been approved and adopted +- **Deprecated**: Decision is no longer relevant but kept for historical context +- **Superseded**: Replaced by a newer ADR (reference the new ADR) + +## Creating a New ADR + +1. Copy the template: `cp ADR-000-template.md ADR-XXX-short-title.md` +2. Fill in all sections +3. Submit a pull request for review +4. Update this README index after approval From 28badf2285e08103a055e9b9bceb072528de7b44 Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 21 Dec 2025 11:34:37 +0000 Subject: [PATCH 2/3] =?UTF-8?q?=F0=9F=8F=97=EF=B8=8F=20arch:=20migrate=20t?= =?UTF-8?q?o=20Azure/.NET/Angular=20multi-tenant=20architecture?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Major architectural pivot from local-first TypeScript/React to Azure-hosted multi-tenant SaaS platform: - Backend: C#/.NET 10 with Clean Architecture - Web/Display: TypeScript/Angular 19+ with Electron - Mobile: Native iOS (Swift/SwiftUI) and Android (Kotlin/Compose) - Cloud: Azure PaaS services (CosmosDB, Functions, App Service, B2C) - IaC: Bicep with Azure Verified Modules (AVMs) Updated documentation: - ARCHITECTURE.md: Complete Azure architecture with data models - PROJECT-OVERVIEW.md: Multi-tenant deployment model and device linking - ROADMAP.md: 6-phase implementation plan for new stack - CLAUDE.md: Updated principles and development commands New ADRs (ADR-001 through ADR-010): - .NET 10 backend, Angular web framework, Azure cloud platform - Native mobile apps, CosmosDB data store, multi-tenant architecture - Bicep/AVMs for IaC, Magic Import approval, Zero-distraction principle - Azure AD B2C for identity Removed superseded ADRs (TypeScript, React, local-first, self-hosting) --- CLAUDE.md | 179 ++- docs/ARCHITECTURE.md | 1231 +++++++---------- docs/PROJECT-OVERVIEW.md | 117 +- docs/ROADMAP.md | 666 ++++----- docs/adr/ADR-001-dotnet-backend.md | 131 ++ .../ADR-001-typescript-primary-language.md | 147 -- docs/adr/ADR-002-angular-web-framework.md | 126 ++ docs/adr/ADR-002-react-ui-framework.md | 159 --- docs/adr/ADR-003-azure-cloud-platform.md | 156 +++ docs/adr/ADR-003-local-first-architecture.md | 169 --- docs/adr/ADR-004-native-mobile-apps.md | 163 +++ docs/adr/ADR-004-two-way-sync-google-first.md | 184 --- docs/adr/ADR-005-cosmosdb-data-store.md | 160 +++ docs/adr/ADR-006-multi-tenant-architecture.md | 164 +++ docs/adr/ADR-007-bicep-avm-iac.md | 259 ++++ docs/adr/ADR-007-self-hosting-first.md | 200 --- ...al.md => ADR-008-magic-import-approval.md} | 16 +- ... => ADR-009-zero-distraction-principle.md} | 11 +- docs/adr/ADR-010-azure-ad-b2c-identity.md | 283 ++++ docs/adr/README.md | 28 +- 20 files changed, 2537 insertions(+), 2012 deletions(-) create mode 100644 docs/adr/ADR-001-dotnet-backend.md delete mode 100644 docs/adr/ADR-001-typescript-primary-language.md create mode 100644 docs/adr/ADR-002-angular-web-framework.md delete mode 100644 docs/adr/ADR-002-react-ui-framework.md create mode 100644 docs/adr/ADR-003-azure-cloud-platform.md delete mode 100644 docs/adr/ADR-003-local-first-architecture.md create mode 100644 docs/adr/ADR-004-native-mobile-apps.md delete mode 100644 docs/adr/ADR-004-two-way-sync-google-first.md create mode 100644 docs/adr/ADR-005-cosmosdb-data-store.md create mode 100644 docs/adr/ADR-006-multi-tenant-architecture.md create mode 100644 docs/adr/ADR-007-bicep-avm-iac.md delete mode 100644 docs/adr/ADR-007-self-hosting-first.md rename docs/adr/{ADR-005-magic-import-approval.md => ADR-008-magic-import-approval.md} (90%) rename docs/adr/{ADR-006-zero-distraction-principle.md => ADR-009-zero-distraction-principle.md} (92%) create mode 100644 docs/adr/ADR-010-azure-ad-b2c-identity.md diff --git a/CLAUDE.md b/CLAUDE.md index c297b93..534b7b2 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -50,9 +50,9 @@ We follow TOGAF ADM phases in our development process: | ID | Principle | Description | |----|-----------|-------------| -| DP-1 | **Local-First Data** | Data stored locally first; sync is secondary | -| DP-2 | **User Data Ownership** | Users can export and self-host | -| DP-3 | **Single Source of Truth** | Clear ownership rules per data type | +| DP-1 | **Cloud-First with Local Cache** | Primary data in Azure; local caching for offline support | +| DP-2 | **User Data Ownership** | Users can export their data; multi-tenant isolation guaranteed | +| DP-3 | **Single Source of Truth** | CosmosDB as source; partition isolation per family | | DP-4 | **Data Minimization** | Collect only what's necessary | #### Application Principles @@ -68,10 +68,10 @@ We follow TOGAF ADM phases in our development process: | ID | Principle | Description | |----|-----------|-------------| -| TP-1 | **Open Source Stack** | No proprietary dependencies in core | -| TP-2 | **Commodity Hardware** | ARM and x86 support; no specialized hardware | -| TP-3 | **Standards-Based Integration** | OAuth 2.0, CalDAV, REST/GraphQL | -| TP-4 | **Operational Simplicity** | Auto-updates, self-healing, minimal config | +| TP-1 | **Azure-Native Stack** | Leverage Azure PaaS services; .NET/Angular/native mobile | +| TP-2 | **Commodity Hardware** | ARM and x86 support for displays; any device for mobile | +| TP-3 | **Standards-Based Integration** | OAuth 2.0/OIDC, REST APIs, OpenAPI contracts | +| TP-4 | **Infrastructure as Code** | Bicep with AVMs for reproducible deployments | ### Architecture Governance @@ -142,24 +142,56 @@ All code must be: #### Directory Structure Expectations ``` +# .NET Backend (Clean Architecture) src/ -├── components/ # Reusable UI components -├── features/ # Feature-based modules (vertical slices) -├── domain/ # Domain models and business logic -├── services/ # External service integrations -├── hooks/ # Shared React hooks (if applicable) -├── utils/ # Pure utility functions -├── types/ # TypeScript type definitions -└── config/ # Configuration and constants +├── Luminous.Domain/ # Domain entities, value objects, interfaces +├── Luminous.Application/ # Use cases, DTOs, application services +├── Luminous.Infrastructure/ # Data access, external services, Azure integrations +├── Luminous.Api/ # ASP.NET Core Web API, controllers +└── Luminous.Functions/ # Azure Functions for background processing + +# Angular Web/Display Applications +clients/ +├── web/ # Main web application +│ ├── src/app/ +│ │ ├── core/ # Singleton services, guards, interceptors +│ │ ├── shared/ # Shared components, pipes, directives +│ │ ├── features/ # Feature modules (lazy-loaded) +│ │ └── models/ # TypeScript interfaces and types +├── display/ # Electron display application +└── shared/ # Shared Angular libraries + +# Native Mobile Applications +mobile/ +├── ios/ # Swift/SwiftUI iOS app +└── android/ # Kotlin/Compose Android app + +# Infrastructure as Code +infra/ +├── modules/ # Bicep modules wrapping AVMs +├── environments/ # Parameter files per environment +└── main.bicep # Main orchestration ``` #### Component Guidelines -- One component per file -- Co-locate component tests, styles, and stories -- Props should be typed and documented -- Avoid prop drilling; use context or state management appropriately -- Components should be presentational or container, not both +**Angular (Web/Display)** +- One component per file with co-located template and styles +- Use standalone components (Angular 19+) +- Inputs/Outputs should be typed and documented +- Use services for state management, avoid deep component hierarchies +- Components should be presentational or smart, not both + +**Native Mobile** +- iOS: Follow SwiftUI patterns with ObservableObject for state +- Android: Use Compose with ViewModel and StateFlow +- Share API models via OpenAPI-generated clients + +**.NET Backend** +- Follow Clean Architecture layer separation +- Use MediatR for CQRS pattern +- Repository pattern for data access +- Domain entities should be persistence-ignorant --- @@ -234,6 +266,7 @@ All commits MUST follow the format: Use scopes to indicate the affected area: +**Features** - `calendar` - Calendar-related changes - `tasks` - Task/chore management - `routines` - Routine management @@ -242,19 +275,30 @@ Use scopes to indicate the affected area: - `lists` - List management - `profiles` - Profile and household management - `notes` - Notes and reminders -- `ui` - General UI components -- `display` - Display/kiosk mode -- `mobile` - Mobile application -- `web` - Web application -- `sync` - Synchronization engine - `import` - Magic import feature -- `config` - Configuration -- `api` - API/backend changes -- `auth` - Authentication -- `db` - Database changes -- `infra` - Infrastructure +- `sync` - Real-time synchronization (SignalR) +- `linking` - Device linking flow + +**Applications** +- `api` - .NET API backend +- `functions` - Azure Functions +- `web` - Angular web application +- `display` - Angular/Electron display application +- `ios` - iOS native application +- `android` - Android native application + +**Infrastructure** +- `ui` - General UI components +- `auth` - Authentication (Azure AD B2C) +- `cosmos` - CosmosDB/data layer changes +- `storage` - Blob storage changes +- `infra` - Bicep/IaC infrastructure +- `config` - Configuration and settings + +**Meta** - `docs` - Documentation - `adr` - Architecture Decision Records +- `ci` - CI/CD pipeline changes ### Commit Examples @@ -341,32 +385,91 @@ Luminous must be usable by all household members: ## Build & Development Commands +### Local Development Setup + +```bash +# Start local Azure emulators (CosmosDB, Storage, Redis) +docker-compose up -d + +# .NET API +cd src/Luminous.Api +dotnet restore +dotnet run + +# Angular Web App +cd clients/web +npm install +npm start + +# Angular Display App (Electron) +cd clients/display +npm install +npm run electron:dev +``` + +### .NET Backend Commands + +```bash +# Build solution +dotnet build + +# Run tests +dotnet test + +# Run API with hot reload +dotnet watch run --project src/Luminous.Api + +# Run Azure Functions locally +func start --csharp +``` + +### Angular Frontend Commands + ```bash # Install dependencies npm install -# Run development server -npm run dev +# Development server +npm start # Run tests npm test -# Run tests in watch mode -npm run test:watch - # Build for production npm run build # Lint code npm run lint -# Format code -npm run format - # Type check npm run typecheck ``` +### Infrastructure Commands + +```bash +# Validate Bicep +az bicep build --file infra/main.bicep + +# Deploy to Azure (dev environment) +./infra/scripts/deploy.sh dev + +# Deploy to Azure (prod environment) +./infra/scripts/deploy.sh prod +``` + +### Mobile Development + +```bash +# iOS (requires macOS with Xcode) +cd mobile/ios +xcodebuild -scheme Luminous -sdk iphonesimulator + +# Android +cd mobile/android +./gradlew assembleDebug +``` + --- ## Getting Help diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index 7030364..ec39e54 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -1,6 +1,6 @@ # Luminous Architecture Document -> **Document Version:** 1.0.0 +> **Document Version:** 2.0.0 > **Last Updated:** 2025-12-21 > **Status:** Draft > **TOGAF Phase:** Phase B-D (Architecture Development) @@ -17,8 +17,10 @@ 6. [Technology Architecture](#technology-architecture) 7. [Security Architecture](#security-architecture) 8. [Integration Architecture](#integration-architecture) -9. [Deployment Architecture](#deployment-architecture) -10. [Architecture Decisions](#architecture-decisions) +9. [Azure Cloud Architecture](#azure-cloud-architecture) +10. [Multi-Tenancy Architecture](#multi-tenancy-architecture) +11. [Local Development Architecture](#local-development-architecture) +12. [Architecture Decisions](#architecture-decisions) --- @@ -33,14 +35,14 @@ Following TOGAF Enterprise Architecture principles, Luminous adheres to these fo | **BP-1: Family-Centric Design** | All features must serve real family coordination needs | Features are validated against family use cases; no feature creep toward entertainment | | **BP-2: Zero Distraction** | The product differentiates by what it omits | Explicitly exclude entertainment, browsing, and social features | | **BP-3: Inclusive by Default** | Families include members of all ages and abilities | Design for youngest (6+) and oldest users; accessibility is mandatory | -| **BP-4: Privacy as a Feature** | Families trust us with sensitive information | Self-hosting option; no mandatory telemetry; data minimization | +| **BP-4: Privacy as a Feature** | Families trust us with sensitive information | Data isolation per tenant; compliance with privacy regulations | ### Data Principles | Principle | Rationale | Implications | |-----------|-----------|--------------| -| **DP-1: Local-First Data** | Reliability requires offline capability | Data stored locally first; sync is secondary; no cloud dependency | -| **DP-2: User Data Ownership** | Families own their information | Export in open formats; no lock-in; self-hosting support | +| **DP-1: Cloud-Native Storage** | Scalability and availability requirements | CosmosDB for global distribution; Azure storage for media | +| **DP-2: Tenant Data Isolation** | Multi-family security requirement | Partition strategies per family; no cross-tenant data access | | **DP-3: Single Source of Truth** | Conflicts create confusion | Clear ownership rules per data type; deterministic conflict resolution | | **DP-4: Data Minimization** | Collect only what's necessary | No tracking; minimal metadata; privacy by design | @@ -48,19 +50,19 @@ Following TOGAF Enterprise Architecture principles, Luminous adheres to these fo | Principle | Rationale | Implications | |-----------|-----------|--------------| -| **AP-1: Modular Composability** | Features evolve independently | Bounded contexts; clean interfaces; plugin architecture | -| **AP-2: Cross-Platform Consistency** | Experience must be unified | Shared design system; consistent behavior across display/mobile/web | +| **AP-1: Modular Composability** | Features evolve independently | Bounded contexts; clean interfaces; microservices where appropriate | +| **AP-2: Cross-Platform Consistency** | Experience must be unified | Shared API; consistent behavior across display/mobile/web | | **AP-3: Graceful Degradation** | Partial failures shouldn't block usage | Offline mode; fallback behaviors; error boundaries | -| **AP-4: Performance on Constraints** | Target hardware is modest | Optimize for Raspberry Pi 4; minimize memory; efficient rendering | +| **AP-4: Cloud-First, Local-Ready** | Support both deployment models | Design for Azure; enable local development | ### Technology Principles | Principle | Rationale | Implications | |-----------|-----------|--------------| -| **TP-1: Open Source Stack** | Aligned with project values; community contribution | No proprietary dependencies in core; permissive or copyleft licenses | -| **TP-2: Commodity Hardware** | Accessibility and affordability | ARM and x86 support; no specialized hardware requirements | -| **TP-3: Standards-Based Integration** | Interoperability with existing systems | OAuth 2.0; CalDAV/ICS; REST/GraphQL APIs; OpenAPI specs | -| **TP-4: Operational Simplicity** | Self-hosters need low maintenance | Auto-updates; self-healing; minimal configuration | +| **TP-1: Azure-Native Stack** | Enterprise-grade hosting with managed services | Use PaaS services; AVMs for IaC; Azure-native integrations | +| **TP-2: Platform-Native Mobile** | Best user experience on mobile devices | Swift for iOS; Kotlin for Android; shared API contracts | +| **TP-3: Standards-Based Integration** | Interoperability with existing systems | OAuth 2.0/OpenID Connect; CalDAV/ICS; REST APIs | +| **TP-4: Infrastructure as Code** | Reproducible deployments | Bicep with AVMs; environment parity | --- @@ -69,51 +71,66 @@ Following TOGAF Enterprise Architecture principles, Luminous adheres to these fo ### Target State Architecture ``` -+------------------------------------------------------------------+ -| LUMINOUS ECOSYSTEM | -+------------------------------------------------------------------+ -| | -| +-------------------+ +-------------------+ +----------------+ | -| | DISPLAY APP | | MOBILE APP | | WEB APP | | -| | (Kiosk Mode) | | (iOS/Android) | | (Browser) | | -| +--------+----------+ +--------+----------+ +-------+--------+ | -| | | | | -| +----------------------+---------------------+ | -| | | -| +-------------v--------------+ | -| | LUMINOUS CORE | | -| | (Shared Domain Logic) | | -| +-------------+--------------+ | -| | | -| +----------------------+---------------------+ | -| | | | | -| +--------v----------+ +--------v----------+ +-------v--------+ | -| | LOCAL STORAGE | | SYNC ENGINE | | INTEGRATIONS | | -| | (SQLite/OPFS) | | (CRDT-based) | | (Calendar, | | -| +-------------------+ +-------------------+ | Weather) | | -| +----------------+ | -| | -+------------------------------------------------------------------+ - | - v -+------------------------------------------------------------------+ -| OPTIONAL SYNC SERVER | -| +-------------------+ +-------------------+ +----------------+ | -| | AUTH SERVICE | | SYNC SERVICE | | PUSH SERVICE | | -| +-------------------+ +-------------------+ +----------------+ | -+------------------------------------------------------------------+ ++-----------------------------------------------------------------------------------+ +| LUMINOUS CLOUD PLATFORM | ++-----------------------------------------------------------------------------------+ +| | +| CLIENT TIER | +| +-------------------+ +-------------------+ +----------------+ +------------+ | +| | DISPLAY APP | | iOS APP | | ANDROID APP | | WEB APP | | +| | (Angular/ | | (Swift/ | | (Kotlin/ | | (Angular) | | +| | Electron) | | SwiftUI) | | Compose) | | | | +| +--------+----------+ +--------+----------+ +-------+--------+ +-----+------+ | +| | | | | | +| +----------------------+---------------------+-----------------+ | +| | | +| API TIER v | +| +-------------------------------------------------------------------------+ | +| | AZURE API MANAGEMENT | | +| +--------------------------------+----------------------------------------+ | +| | | +| +------------------+----+----+------------------+ | +| | | | | | +| v v v v | +| +-----------------+ +--------------+ +-------------+ +------------------+ | +| | APP SERVICE | | FUNCTION APP | | FUNCTION APP| | APP SERVICE | | +| | (Core API) | | (Sync Jobs) | | (Import) | | (SignalR) | | +| | .NET 10 | | .NET 10 | | .NET 10 | | .NET 10 | | +| +-----------------+ +--------------+ +-------------+ +------------------+ | +| | | | | | +| DATA TIER | | | | +| +---------------------------+---------------+----------------+--------------+ | +| | | | +| | +----------------+ +------------------+ +----------------+ | | +| | | COSMOS DB | | BLOB STORAGE | | SERVICE BUS | | | +| | | (Core Data) | | (Media/Files) | | (Messaging) | | | +| | +----------------+ +------------------+ +----------------+ | | +| | | | +| | +----------------+ +------------------+ +----------------+ | | +| | | REDIS CACHE | | KEY VAULT | | APP CONFIG | | | +| | | (Sessions) | | (Secrets) | | (Settings) | | | +| | +----------------+ +------------------+ +----------------+ | | +| | | | +| +---------------------------------------------------------------------------+ | +| | +| IDENTITY TIER | +| +-------------------------------------------------------------------------+ | +| | AZURE AD B2C / ENTRA EXTERNAL ID | | +| +-------------------------------------------------------------------------+ | +| | ++------------------------------------------------------------------------------------+ ``` ### Key Architecture Characteristics | Characteristic | Priority | Description | |----------------|----------|-------------| -| **Reliability** | Critical | 24/7 operation; auto-recovery; crash resilience | +| **Scalability** | Critical | Multi-tenant; handle thousands of families | +| **Reliability** | Critical | 99.9% uptime; auto-recovery; geo-redundancy | +| **Security** | Critical | Tenant isolation; OAuth 2.0; encryption | | **Usability** | Critical | Child-friendly; glanceable; intuitive | -| **Performance** | High | Fast rendering; low latency; efficient memory | -| **Scalability** | Medium | Support large families; many calendars | -| **Portability** | High | Cross-platform; commodity hardware | -| **Maintainability** | High | Clean code; comprehensive testing; documentation | +| **Performance** | High | Fast API response; real-time sync | +| **Maintainability** | High | Clean code; comprehensive testing; IaC | --- @@ -122,271 +139,210 @@ Following TOGAF Enterprise Architecture principles, Luminous adheres to these fo ### Business Capability Model ``` -LUMINOUS FAMILY HUB -├── SCHEDULING CAPABILITY -│ ├── Calendar Aggregation -│ ├── Event Management -│ ├── Reminder Management -│ └── Schedule Sharing -│ -├── TASK MANAGEMENT CAPABILITY -│ ├── Chore Management -│ ├── Routine Management -│ ├── Progress Tracking -│ └── Reward Management -│ -├── HOUSEHOLD MANAGEMENT CAPABILITY -│ ├── Profile Management -│ ├── Meal Planning -│ ├── List Management -│ └── Caregiver Coordination -│ -├── INFORMATION DISPLAY CAPABILITY -│ ├── Dashboard Rendering -│ ├── Notification Display -│ ├── Ambient Information -│ └── Privacy Mode -│ -└── PLATFORM CAPABILITY - ├── Authentication & Authorization - ├── Data Synchronization - ├── External Integration - └── System Administration +LUMINOUS FAMILY HUB (MULTI-TENANT) +| ++-- PLATFORM CAPABILITY +| +-- Tenant Management +| +-- User Authentication (Azure AD B2C) +| +-- Device Registration (Board Linking) +| +-- Subscription Management +| +-- Usage Analytics +| ++-- SCHEDULING CAPABILITY +| +-- Calendar Aggregation +| +-- Event Management +| +-- Reminder Management +| +-- Schedule Sharing +| ++-- TASK MANAGEMENT CAPABILITY +| +-- Chore Management +| +-- Routine Management +| +-- Progress Tracking +| +-- Reward Management +| ++-- HOUSEHOLD MANAGEMENT CAPABILITY +| +-- Profile Management +| +-- Meal Planning +| +-- List Management +| +-- Caregiver Coordination +| ++-- INFORMATION DISPLAY CAPABILITY +| +-- Dashboard Rendering +| +-- Notification Display +| +-- Ambient Information +| +-- Privacy Mode +| ++-- INTEGRATION CAPABILITY + +-- Calendar Provider Integration + +-- Push Notification Service + +-- Magic Import Processing + +-- External API Access ``` -### Business Process Map - -#### BP-001: Daily Family Coordination +### Multi-Tenant Business Model ``` -┌─────────────────────────────────────────────────────────────────────┐ -│ DAILY FAMILY COORDINATION │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Morning │───▶│ View │───▶│ Complete │───▶│ Receive │ │ -│ │ Wake │ │ Today │ │ Routines │ │ Rewards │ │ -│ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ -│ │ │ -│ ▼ │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Check │───▶│ Handle │───▶│ Update │ │ -│ │ Calendar │ │ Events │ │ Status │ │ -│ └──────────┘ └──────────┘ └──────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ ++---------------------------------------------------------------------+ +| TENANT LIFECYCLE | ++---------------------------------------------------------------------+ +| | +| +----------+ +----------+ +----------+ +----------+ | +| | Sign Up |--->| Create |--->| Invite |--->| Link | | +| | (User) | | Family | | Members | | Boards | | +| +----------+ +----------+ +----------+ +----------+ | +| | +| User registers --> Creates family --> Invites family --> Links | +| via Azure AD B2C (tenant) members display | +| | ++---------------------------------------------------------------------+ ``` ### Actor-Role Matrix -| Actor | Calendar | Chores | Lists | Profiles | Settings | -|-------|----------|--------|-------|----------|----------| -| **Household Admin** | Full | Full | Full | Full | Full | -| **Adult Member** | Full | Full | Full | Own | View | -| **Teen Member** | Own + Family | Own | Shared | Own | None | -| **Child Member** | View | Complete | View | View | None | -| **External Caregiver** | View (limited) | View | View | View (care info) | None | +| Actor | Family Scope | Calendar | Chores | Lists | Profiles | Settings | +|-------|--------------|----------|--------|-------|----------|----------| +| **Family Owner** | Single | Full | Full | Full | Full | Full | +| **Admin Member** | Single | Full | Full | Full | Full | Limited | +| **Adult Member** | Single | Full | Full | Full | Own | View | +| **Teen Member** | Single | Own + Family | Own | Shared | Own | None | +| **Child Member** | Single | View | Complete | View | View | None | +| **External Caregiver** | Limited | View | View | View | View (care) | None | --- ## Data Architecture -### Domain Model +### CosmosDB Data Model ``` -┌─────────────────────────────────────────────────────────────────────┐ -│ DOMAIN MODEL │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ HOUSEHOLD │────────▶│ PROFILE │ │ -│ │ (Aggregate) │ 1 * │ (Entity) │ │ -│ └────────┬────────┘ └────────┬────────┘ │ -│ │ │ │ -│ │ 1 │ * │ -│ ▼ ▼ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ CALENDAR │ │ CHORE │ │ -│ │ CONNECTION │ │ (Entity) │ │ -│ │ (Entity) │ └────────┬────────┘ │ -│ └────────┬────────┘ │ │ -│ │ │ │ -│ │ * │ * │ -│ ▼ ▼ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ EVENT │ │ COMPLETION │ │ -│ │ (Entity) │ │ (Value Obj) │ │ -│ └─────────────────┘ └─────────────────┘ │ -│ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ ROUTINE │────────▶│ ROUTINE STEP │ │ -│ │ (Aggregate) │ 1 * │ (Value Obj) │ │ -│ └─────────────────┘ └─────────────────┘ │ -│ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ LIST │────────▶│ LIST ITEM │ │ -│ │ (Aggregate) │ 1 * │ (Entity) │ │ -│ └─────────────────┘ └─────────────────┘ │ -│ │ -│ ┌─────────────────┐ ┌─────────────────┐ │ -│ │ MEAL PLAN │────────▶│ RECIPE │ │ -│ │ (Aggregate) │ * * │ (Entity) │ │ -│ └─────────────────┘ └─────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ ++---------------------------------------------------------------------+ +| COSMOS DB CONTAINERS | ++---------------------------------------------------------------------+ +| | +| CONTAINER: families | +| Partition Key: /id | +| +---------------------------------------------------------------+ | +| | { id, name, timezone, settings, createdAt, subscription } | | +| +---------------------------------------------------------------+ | +| | +| CONTAINER: users | +| Partition Key: /familyId | +| +---------------------------------------------------------------+ | +| | { id, familyId, email, displayName, role, profile, ... } | | +| +---------------------------------------------------------------+ | +| | +| CONTAINER: events | +| Partition Key: /familyId | +| +---------------------------------------------------------------+ | +| | { id, familyId, title, start, end, assignees, source, ... } | | +| +---------------------------------------------------------------+ | +| | +| CONTAINER: chores | +| Partition Key: /familyId | +| +---------------------------------------------------------------+ | +| | { id, familyId, title, assignees, recurrence, points, ... } | | +| +---------------------------------------------------------------+ | +| | +| CONTAINER: devices | +| Partition Key: /familyId | +| +---------------------------------------------------------------+ | +| | { id, familyId, deviceType, linkCode, linkedAt, ... } | | +| +---------------------------------------------------------------+ | +| | +| (Additional: lists, meals, routines, completions, ...) | +| | ++---------------------------------------------------------------------+ ``` ### Core Entities -#### Household (Aggregate Root) - -```typescript -interface Household { - id: HouseholdId; - name: string; - timezone: Timezone; - createdAt: DateTime; - settings: HouseholdSettings; - profiles: Profile[]; - calendarConnections: CalendarConnection[]; +#### Family (Tenant Root) + +```csharp +public class Family +{ + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string Name { get; set; } = string.Empty; + public string Timezone { get; set; } = "UTC"; + public FamilySettings Settings { get; set; } = new(); + public SubscriptionInfo? Subscription { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; + public string CreatedBy { get; set; } = string.Empty; } -``` -#### Profile - -```typescript -interface Profile { - id: ProfileId; - householdId: HouseholdId; - displayName: string; - avatarUrl?: string; - color: HexColor; - role: ProfileRole; // ADMIN | ADULT | TEEN | CHILD | PET - birthday?: LocalDate; - caregiverInfo?: CaregiverInfo; - permissions: Permission[]; - pinHash?: string; - createdAt: DateTime; +public class FamilySettings +{ + public string DefaultView { get; set; } = "day"; + public bool PrivacyModeEnabled { get; set; } = true; + public TimeSpan PrivacyModeTimeout { get; set; } = TimeSpan.FromMinutes(5); + public SleepModeSettings SleepMode { get; set; } = new(); } +``` -interface CaregiverInfo { - allergies: string[]; - medications: string[]; - emergencyContacts: Contact[]; - doctorInfo?: Contact; - notes: string; +#### User (Family Member) + +```csharp +public class User +{ + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string FamilyId { get; set; } = string.Empty; // Partition key + public string ExternalId { get; set; } = string.Empty; // Azure AD B2C ID + public string Email { get; set; } = string.Empty; + public string DisplayName { get; set; } = string.Empty; + public UserRole Role { get; set; } = UserRole.Member; + public UserProfile Profile { get; set; } = new(); + public CaregiverInfo? CaregiverInfo { get; set; } + public DateTime CreatedAt { get; set; } = DateTime.UtcNow; } -``` -#### Event - -```typescript -interface Event { - id: EventId; - householdId: HouseholdId; - calendarConnectionId?: CalendarConnectionId; - externalId?: string; - title: string; - description?: string; - location?: Location; - startTime: DateTime; - endTime: DateTime; - allDay: boolean; - recurrence?: RecurrenceRule; - assignedProfiles: ProfileId[]; - reminders: Reminder[]; - isCountdown: boolean; - createdAt: DateTime; - updatedAt: DateTime; - syncStatus: SyncStatus; +public enum UserRole +{ + Owner, // Can delete family, manage billing + Admin, // Full access except billing + Adult, // Full feature access + Teen, // Limited access + Child, // View and complete only + Caregiver // External, view only } ``` -#### Chore - -```typescript -interface Chore { - id: ChoreId; - householdId: HouseholdId; - title: string; - description?: string; - icon: IconId; - assignedProfiles: ProfileId[]; // empty = "anyone" - recurrence?: RecurrenceRule; - dueTime?: LocalTime; - pointValue: number; - priority?: Priority; - completions: ChoreCompletion[]; - createdAt: DateTime; +#### Device (Linked Board) + +```csharp +public class Device +{ + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string FamilyId { get; set; } = string.Empty; // Partition key + public DeviceType Type { get; set; } = DeviceType.Display; + public string Name { get; set; } = string.Empty; + public string? LinkCode { get; set; } // 6-digit code for linking + public DateTime? LinkCodeExpiry { get; set; } + public DateTime? LinkedAt { get; set; } + public string? LinkedBy { get; set; } + public DeviceSettings Settings { get; set; } = new(); + public DateTime LastSeenAt { get; set; } } -interface ChoreCompletion { - date: LocalDate; - completedBy: ProfileId; - completedAt: DateTime; - pointsAwarded: number; +public enum DeviceType +{ + Display, // Wall-mounted display + Mobile, // iOS or Android app + Web // Web browser } ``` ### Data Storage Strategy -| Data Type | Storage | Sync Strategy | Conflict Resolution | -|-----------|---------|---------------|---------------------| -| **Household Config** | Local SQLite | Full sync | Last-write-wins with vector clock | -| **Profiles** | Local SQLite | Full sync | Server authority | -| **Events (internal)** | Local SQLite | CRDT merge | Operational transform | -| **Events (external)** | Cached | Pull from source | Source authority | -| **Chores/Routines** | Local SQLite | CRDT merge | Operational transform | -| **Lists** | Local SQLite | CRDT merge | Append-only with tombstones | -| **Completions** | Local SQLite | Append-only | No conflicts (immutable) | -| **Media (avatars)** | Local filesystem | Hash-addressed | Content-addressed (no conflicts) | - -### Data Flow Diagram - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ DATA FLOW ARCHITECTURE │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ EXTERNAL SOURCES │ -│ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ -│ │ Google │ │ Outlook │ │ iCloud │ │ ICS │ │ -│ │ Calendar │ │ Calendar │ │ Calendar │ │ Feeds │ │ -│ └────┬─────┘ └────┬─────┘ └────┬─────┘ └────┬─────┘ │ -│ │ │ │ │ │ -│ └─────────────┴──────┬──────┴─────────────┘ │ -│ ▼ │ -│ ┌─────────────────┐ │ -│ │ SYNC ENGINE │ │ -│ │ (Adapter per │ │ -│ │ provider) │ │ -│ └────────┬────────┘ │ -│ │ │ -│ ▼ │ -│ ┌────────────────────────────────────────────────────────┐ │ -│ │ LOCAL DATA STORE │ │ -│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ -│ │ │ Events │ │ Chores │ │ Lists │ ... │ │ -│ │ └──────────┘ └──────────┘ └──────────┘ │ │ -│ └────────────────────────┬───────────────────────────────┘ │ -│ │ │ -│ ┌───────────────────┼───────────────────┐ │ -│ ▼ ▼ ▼ │ -│ ┌────────────┐ ┌────────────┐ ┌────────────┐ │ -│ │ DISPLAY │ │ MOBILE │ │ WEB │ │ -│ │ APP │◀───▶│ APP │◀───▶│ APP │ │ -│ └────────────┘ └────────────┘ └────────────┘ │ -│ │ │ │ │ -│ └───────────────────┴───────────────────┘ │ -│ │ │ -│ ▼ │ -│ ┌─────────────────┐ │ -│ │ SYNC SERVER │ (Optional) │ -│ │ (Multi-device) │ │ -│ └─────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` +| Data Type | Storage | Partition Strategy | Notes | +|-----------|---------|-------------------|-------| +| **Families** | CosmosDB | By family ID | Tenant root | +| **Users** | CosmosDB | By family ID | Includes Azure AD B2C link | +| **Events** | CosmosDB | By family ID | Calendar events | +| **Chores** | CosmosDB | By family ID | Tasks and assignments | +| **Devices** | CosmosDB | By family ID | Board registrations | +| **Media** | Blob Storage | By family ID container | Avatars, recipe photos | +| **Sessions** | Redis Cache | By session ID | Real-time sync state | +| **Secrets** | Key Vault | N/A | API keys, certificates | --- @@ -396,169 +352,52 @@ interface ChoreCompletion { Following Domain-Driven Design, Luminous is organized into these bounded contexts: -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ BOUNDED CONTEXTS │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ -│ │ SCHEDULING │ │ TASK MANAGEMENT │ │ HOUSEHOLD │ │ -│ │ CONTEXT │ │ CONTEXT │ │ CONTEXT │ │ -│ │ │ │ │ │ │ │ -│ │ - Calendar │ │ - Chore │ │ - Profile │ │ -│ │ - Event │ │ - Routine │ │ - Household │ │ -│ │ - CalendarConn │ │ - Completion │ │ - CaregiverInfo │ │ -│ │ - Reminder │ │ - Reward │ │ - Permission │ │ -│ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ -│ │ -│ ┌──────────────────┐ ┌──────────────────┐ ┌──────────────────┐ │ -│ │ MEAL PLANNING │ │ LIST MANAGEMENT │ │ DISPLAY │ │ -│ │ CONTEXT │ │ CONTEXT │ │ CONTEXT │ │ -│ │ │ │ │ │ │ │ -│ │ - MealPlan │ │ - List │ │ - Dashboard │ │ -│ │ - Recipe │ │ - ListItem │ │ - Widget │ │ -│ │ - Ingredient │ │ - Template │ │ - PrivacyMode │ │ -│ │ - DietaryPref │ │ │ │ - SleepMode │ │ -│ └──────────────────┘ └──────────────────┘ └──────────────────┘ │ -│ │ -│ ┌──────────────────┐ ┌──────────────────┐ │ -│ │ MAGIC IMPORT │ │ INTEGRATION │ │ -│ │ CONTEXT │ │ CONTEXT │ │ -│ │ │ │ │ │ -│ │ - ImportRequest │ │ - CalendarSync │ │ -│ │ - ParsedContent │ │ - WeatherFetch │ │ -│ │ - ApprovalQueue │ │ - InstacartLink │ │ -│ │ │ │ - PushNotify │ │ -│ └──────────────────┘ └──────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` +| Context | Entities | Responsibility | +|---------|----------|----------------| +| **Identity** | Family, User, Device, Invitation | Authentication, authorization, multi-tenancy | +| **Scheduling** | Calendar, Event, CalendarConnection, Reminder | Calendar aggregation and management | +| **Task Management** | Chore, Routine, Completion, Reward | Chores, routines, and gamification | +| **Meal Planning** | MealPlan, Recipe, Ingredient, DietaryPref | Meal planning and recipes | +| **List Management** | List, ListItem, Template | Grocery and custom lists | +| **Display** | Dashboard, Widget, PrivacyMode, DeviceConfig | Display rendering and modes | +| **Magic Import** | ImportRequest, ParsedContent, ApprovalQueue | AI-powered content extraction | +| **Notification** | Notification, PushToken, Preference | Push notifications | -### Application Component Model - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ APPLICATION COMPONENTS │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ PRESENTATION LAYER │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ │ -│ │ │ Display │ │ Mobile │ │ Web │ │ Caregiver │ │ │ -│ │ │ App │ │ App │ │ App │ │ Portal │ │ │ -│ │ └────┬────┘ └────┬────┘ └────┬────┘ └──────┬──────┘ │ │ -│ └───────┼────────────┼────────────┼──────────────┼───────────┘ │ -│ │ │ │ │ │ -│ └────────────┴─────┬──────┴──────────────┘ │ -│ │ │ -│ SHARED UI LAYER ▼ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ DESIGN SYSTEM │ │ -│ │ ┌─────────┐ ┌─────────┐ ┌─────────┐ ┌─────────────┐ │ │ -│ │ │ Theme │ │ Core │ │ Form │ │ Composite │ │ │ -│ │ │ Tokens │ │ Widgets │ │ Elements│ │ Components │ │ │ -│ │ └─────────┘ └─────────┘ └─────────┘ └─────────────┘ │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -│ │ │ -│ DOMAIN LAYER ▼ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ LUMINOUS CORE │ │ -│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │ -│ │ │ Domain │ │ Domain │ │ Domain │ ... │ │ -│ │ │ Models │ │ Services │ │ Events │ │ │ -│ │ └───────────┘ └───────────┘ └───────────┘ │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -│ │ │ -│ INFRASTRUCTURE LAYER ▼ │ -│ ┌─────────────────────────────────────────────────────────────┐ │ -│ │ ┌───────────┐ ┌───────────┐ ┌───────────┐ │ │ -│ │ │ Data │ │ Sync │ │ External │ │ │ -│ │ │Repository │ │ Engine │ │ Adapters │ │ │ -│ │ └───────────┘ └───────────┘ └───────────┘ │ │ -│ └─────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` - -### Module Structure +### Solution Structure ``` luminous/ -├── packages/ -│ ├── core/ # Shared domain logic -│ │ ├── src/ -│ │ │ ├── domain/ # Domain models and entities -│ │ │ │ ├── household/ -│ │ │ │ ├── scheduling/ -│ │ │ │ ├── tasks/ -│ │ │ │ ├── lists/ -│ │ │ │ └── meals/ -│ │ │ ├── services/ # Domain services -│ │ │ ├── events/ # Domain events -│ │ │ └── ports/ # Repository interfaces -│ │ └── package.json -│ │ -│ ├── ui/ # Shared design system -│ │ ├── src/ -│ │ │ ├── tokens/ # Design tokens -│ │ │ ├── primitives/ # Base components -│ │ │ ├── components/ # Composite components -│ │ │ └── themes/ # Theme definitions -│ │ └── package.json -│ │ -│ ├── sync/ # Synchronization engine -│ │ ├── src/ -│ │ │ ├── crdt/ # CRDT implementations -│ │ │ ├── adapters/ # Calendar provider adapters -│ │ │ └── engine/ # Sync orchestration -│ │ └── package.json -│ │ -│ └── import/ # Magic import service -│ ├── src/ -│ │ ├── parsers/ # Input parsers (email, photo, etc.) -│ │ ├── extractors/ # Content extractors -│ │ └── queue/ # Approval queue -│ └── package.json -│ -├── apps/ -│ ├── display/ # Wall display application -│ │ ├── src/ -│ │ │ ├── views/ # Main display views -│ │ │ ├── widgets/ # Display widgets -│ │ │ ├── kiosk/ # Kiosk mode management -│ │ │ └── store/ # State management -│ │ └── package.json -│ │ -│ ├── mobile/ # Mobile application -│ │ ├── src/ -│ │ │ ├── screens/ # App screens -│ │ │ ├── navigation/ # Navigation config -│ │ │ ├── push/ # Push notification handling -│ │ │ └── store/ # State management -│ │ └── package.json -│ │ -│ ├── web/ # Web application -│ │ ├── src/ -│ │ │ ├── pages/ # Page components -│ │ │ ├── layouts/ # Layout components -│ │ │ └── store/ # State management -│ │ └── package.json -│ │ -│ └── server/ # Optional sync server -│ ├── src/ -│ │ ├── api/ # REST/GraphQL API -│ │ ├── auth/ # Authentication -│ │ ├── sync/ # Sync coordination -│ │ └── push/ # Push notification service -│ └── package.json -│ -├── tools/ # Development tools -│ ├── cli/ # CLI tooling -│ └── scripts/ # Build scripts -│ -└── docs/ # Documentation - ├── adr/ # Architecture Decision Records - └── api/ # API documentation +| ++-- src/ +| +-- Luminous.Domain/ # Domain models, interfaces +| +-- Luminous.Application/ # Application services, CQRS +| +-- Luminous.Infrastructure/ # Data access, external services +| +-- Luminous.Api/ # ASP.NET Core Web API +| +-- Luminous.Functions/ # Azure Functions +| +-- Luminous.Shared/ # Shared DTOs, contracts +| ++-- clients/ +| +-- web/ # Angular web application +| +-- display/ # Angular + Electron display app +| +-- ios/ # Native iOS app (Swift) +| +-- android/ # Native Android app (Kotlin) +| ++-- infra/ +| +-- bicep/ # Bicep IaC with AVMs +| | +-- main.bicep +| | +-- modules/ +| | +-- parameters/ +| +-- scripts/ +| ++-- tests/ +| +-- Luminous.Domain.Tests/ +| +-- Luminous.Application.Tests/ +| +-- Luminous.Api.Tests/ +| +-- Luminous.Integration.Tests/ +| ++-- docs/ +| ++-- Luminous.sln ``` --- @@ -567,326 +406,302 @@ luminous/ ### Technology Stack -| Layer | Technology | Rationale | -|-------|------------|-----------| -| **Language** | TypeScript | Type safety, tooling, ecosystem | -| **UI Framework** | React | Component model, ecosystem, cross-platform (React Native) | -| **State Management** | Zustand | Lightweight, TypeScript-first, easy testing | -| **Local Database** | SQLite (via sql.js) / OPFS | Offline-first, portable, performant | -| **Sync Protocol** | Custom CRDT-based | Conflict-free offline operation | -| **Mobile** | React Native | Code sharing with display/web | -| **Desktop/Display** | Electron or Tauri | Native kiosk capabilities | -| **Server (Optional)** | Node.js + Fastify | TypeScript consistency, performance | -| **Build System** | Turborepo | Monorepo management, caching | -| **Testing** | Vitest + Playwright | Fast unit tests, E2E coverage | - -### Technology Reference Model - -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ TECHNOLOGY REFERENCE MODEL │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ DEVELOPMENT PLATFORM │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ TypeScript 5.x │ Node.js 20 LTS │ pnpm │ Turborepo │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ APPLICATION FRAMEWORKS │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ React 19 │ React Native │ Electron/Tauri │ Fastify │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ UI/UX INFRASTRUCTURE │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ Tailwind CSS │ Radix UI │ Framer Motion │ React Aria │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ DATA INFRASTRUCTURE │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ SQLite (sql.js) │ OPFS │ IndexedDB │ Yjs (CRDT) │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ INTEGRATION INFRASTRUCTURE │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ OAuth 2.0 │ CalDAV │ REST │ WebSocket │ Web Push │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ QUALITY INFRASTRUCTURE │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ Vitest │ Playwright │ ESLint │ Prettier │ TypeScript ESLint │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ DEPLOYMENT INFRASTRUCTURE │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ Docker │ GitHub Actions │ Renovate │ Changesets │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` +| Layer | Technology | Version | Rationale | +|-------|------------|---------|-----------| +| **Backend Runtime** | .NET | 10 | LTS, performance, Azure integration | +| **Backend Framework** | ASP.NET Core | 10 | Web API, SignalR, middleware | +| **Serverless** | Azure Functions | .NET 10 isolated | Event-driven processing | +| **Web Frontend** | Angular | 19+ | Enterprise-grade, TypeScript-first | +| **Display App** | Angular + Electron | Latest | Cross-platform desktop | +| **iOS App** | Swift/SwiftUI | iOS 17+ | Native performance, UX | +| **Android App** | Kotlin/Compose | Android 13+ | Native performance, UX | +| **Database** | Azure Cosmos DB | Latest | Global scale, multi-model | +| **Cache** | Azure Redis Cache | Latest | Session, real-time state | +| **Storage** | Azure Blob Storage | Latest | Media, files | +| **Messaging** | Azure Service Bus | Latest | Async processing | +| **Real-time** | Azure SignalR Service | Latest | WebSocket at scale | +| **Identity** | Azure AD B2C | Latest | Consumer identity | +| **IaC** | Bicep + AVMs | Latest | Azure-native, verified modules | ### Platform Matrix -| Platform | Runtime | Database | Notes | -|----------|---------|----------|-------| -| **Display (Linux)** | Electron | SQLite | Kiosk mode, ARM64 support | -| **Display (Raspberry Pi)** | Electron/Chromium | SQLite | Optimized for Pi 4/5 | -| **Mobile (iOS)** | React Native | SQLite | App Store distribution | -| **Mobile (Android)** | React Native | SQLite | Play Store + sideload | -| **Web** | Browser | OPFS/IndexedDB | Progressive Web App | -| **Server** | Node.js | PostgreSQL/SQLite | Docker deployment | +| Platform | Technology | Distribution | +|----------|------------|--------------| +| **Web App** | Angular, Static Web App | Azure Static Web Apps | +| **Display App** | Angular + Electron | Direct download, auto-update | +| **iOS App** | Swift/SwiftUI | Apple App Store | +| **Android App** | Kotlin/Compose | Google Play Store | +| **API** | .NET 10, App Service | Azure App Service | +| **Functions** | .NET 10 isolated | Azure Functions | --- ## Security Architecture -### Security Model +### Identity and Access Management ``` -┌─────────────────────────────────────────────────────────────────────┐ -│ SECURITY ARCHITECTURE │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ AUTHENTICATION │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ -│ │ │ Local PIN │ │ OAuth 2.0 │ │ Passkey │ │ │ -│ │ │ (Display) │ │ (Mobile) │ │ (Future) │ │ │ -│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ -│ │ │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ AUTHORIZATION │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ Role-Based Access Control (RBAC) │ │ -│ │ ┌────────────────────────────────────────────────────────┐ │ │ -│ │ │ ADMIN → ADULT → TEEN → CHILD → CAREGIVER (External) │ │ │ -│ │ └────────────────────────────────────────────────────────┘ │ │ -│ │ │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -│ DATA PROTECTION │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ ┌──────────────┐ ┌──────────────┐ ┌──────────────┐ │ │ -│ │ │ Encryption │ │ Encryption │ │ Secure │ │ │ -│ │ │ at Rest │ │ in Transit │ │ Backup │ │ │ -│ │ │ (SQLCipher) │ │ (TLS 1.3) │ │ │ │ │ -│ │ └──────────────┘ └──────────────┘ └──────────────┘ │ │ -│ │ │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ ++---------------------------------------------------------------------+ +| IDENTITY ARCHITECTURE | ++---------------------------------------------------------------------+ +| | +| +---------------------------------------------------------------+ | +| | AZURE AD B2C | | +| | | | +| | +--------------+ +--------------+ +--------------+ | | +| | | Sign Up | | Sign In | | Password | | | +| | | Flow | | Flow | | Reset | | | +| | +--------------+ +--------------+ +--------------+ | | +| | | | +| | +--------------+ +--------------+ | | +| | | Social | | MFA | | | +| | | Providers | | (Optional) | | | +| | | (Google, | | | | | +| | | Apple) | | | | | +| | +--------------+ +--------------+ | | +| | | | +| +---------------------------------------------------------------+ | +| | | +| v | +| +---------------------------------------------------------------+ | +| | JWT ACCESS TOKEN | | +| | { sub, family_id, roles, permissions, exp, ... } | | +| +---------------------------------------------------------------+ | +| | | +| v | +| +---------------------------------------------------------------+ | +| | API AUTHORIZATION | | +| | | | +| | [Authorize(Policy = "FamilyMember")] | | +| | [Authorize(Policy = "FamilyAdmin")] | | +| | [Authorize(Policy = "DeviceAccess")] | | +| | | | +| +---------------------------------------------------------------+ | +| | ++---------------------------------------------------------------------+ ``` -### Role Permission Matrix +### Device Linking Flow -| Capability | Admin | Adult | Teen | Child | Caregiver | -|------------|-------|-------|------|-------|-----------| -| View all calendars | Yes | Yes | Limited | Limited | Limited | -| Edit events | Yes | Yes | Own | No | No | -| Create chores | Yes | Yes | No | No | No | -| Complete chores | Yes | Yes | Own | Own | No | -| Manage profiles | Yes | No | No | No | No | -| View caregiver info | Yes | Yes | No | No | Own-assigned | -| System settings | Yes | No | No | No | No | -| Invite caregivers | Yes | Yes | No | No | No | +1. **Display requests link code** - Generates 6-digit code with 15-minute expiry +2. **User opens mobile app** - Logs in with Azure AD B2C +3. **User enters code** - Associates device with their family +4. **Display receives confirmation** - Gets device token for API access +5. **Display syncs family data** - Pulls events, chores, settings ### Security Requirements | Category | Requirement | Implementation | |----------|-------------|----------------| -| **Authentication** | Multi-factor for admin actions | PIN + device auth | -| **Session** | Automatic timeout on mobile | 15-minute idle logout | -| **Data** | Encryption at rest | SQLCipher for local data | -| **Transit** | TLS for all connections | TLS 1.3 minimum | -| **Secrets** | No secrets in code | Environment variables, secret manager | -| **Dependencies** | Regular vulnerability scans | Renovate + npm audit | -| **Audit** | Log security-relevant actions | Immutable audit log | +| **Authentication** | OAuth 2.0 / OpenID Connect | Azure AD B2C | +| **Authorization** | Role-based + Family-scoped | Custom policies | +| **Data Isolation** | Tenant data separation | CosmosDB partitioning | +| **Data Encryption** | At rest and in transit | Azure managed encryption, TLS 1.3 | +| **Secrets** | Secure secret storage | Azure Key Vault | +| **API Security** | Rate limiting, validation | API Management + middleware | +| **Device Auth** | Secure device tokens | JWT with refresh rotation | --- -## Integration Architecture +## Azure Cloud Architecture -### External Integration Points +### Resource Architecture ``` -┌─────────────────────────────────────────────────────────────────────┐ -│ INTEGRATION ARCHITECTURE │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ LUMINOUS │ -│ │ │ -│ ┌─────────────────────┼─────────────────────┐ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -│ │ CALENDAR │ │ WEATHER │ │ GROCERY │ │ -│ │ PROVIDERS │ │ SERVICE │ │ DELIVERY │ │ -│ ├─────────────┤ ├─────────────┤ ├─────────────┤ │ -│ │ Google Cal │ │ OpenWeather │ │ Instacart │ │ -│ │ Outlook/M365│ │ NWS API │ │ (Future) │ │ -│ │ iCloud │ │ Pirate │ │ │ │ -│ │ CalDAV │ │ Weather │ │ │ │ -│ │ ICS URLs │ │ │ │ │ │ -│ └─────────────┘ └─────────────┘ └─────────────┘ │ -│ │ -│ ┌─────────────────────┼─────────────────────┐ │ -│ │ │ │ │ -│ ▼ ▼ ▼ │ -│ ┌─────────────┐ ┌─────────────┐ ┌─────────────┐ │ -│ │ PUSH │ │ MAGIC │ │ MAPS │ │ -│ │ NOTIFY │ │ IMPORT │ │ SERVICE │ │ -│ ├─────────────┤ ├─────────────┤ ├─────────────┤ │ -│ │ Apple APNS │ │ OCR Service │ │ OpenStreet │ │ -│ │ Google FCM │ │ Email Parse │ │ Map │ │ -│ │ Web Push │ │ LLM Extract │ │ │ │ -│ └─────────────┘ └─────────────┘ └─────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ +RESOURCE GROUP: rg-luminous-{env} +| ++-- COMPUTE +| +-- App Service (API): app-lum-api-{env} +| +-- Function App (Sync): func-lum-sync-{env} +| +-- Function App (Import): func-lum-import-{env} +| ++-- DATA +| +-- Cosmos DB: cosmos-lum-{env} +| +-- Redis Cache: redis-lum-{env} +| +-- Storage Account: stlum{env} +| ++-- MESSAGING +| +-- Service Bus: sb-lum-{env} +| +-- SignalR Service: sigr-lum-{env} +| ++-- SECURITY +| +-- Key Vault: kv-lum-{env} +| +-- App Configuration: appcs-lum-{env} +| ++-- WEB +| +-- Static Web App: stapp-lum-{env} +| ++-- MONITORING + +-- Application Insights: appi-lum-{env} + +-- Log Analytics: log-lum-{env} ``` -### Calendar Integration Patterns - -| Provider | Protocol | Sync Direction | Auth Method | -|----------|----------|----------------|-------------| -| **Google Calendar** | REST API | Two-way | OAuth 2.0 | -| **Microsoft 365** | Graph API | Two-way | OAuth 2.0 | -| **iCloud** | CalDAV | Read-only (initially) | App-specific password | -| **CalDAV Generic** | CalDAV | Read-only | Basic / OAuth | -| **ICS URL** | HTTP(S) | Read-only | None / Basic | - -### Integration API Design - -All external integrations follow the Adapter pattern: - -```typescript -interface CalendarAdapter { - readonly providerId: CalendarProviderId; - - authenticate(credentials: AuthCredentials): Promise; - refreshToken(session: AuthSession): Promise; - - listCalendars(session: AuthSession): Promise; - - fetchEvents( - session: AuthSession, - calendarId: string, - range: DateRange - ): Promise; - - createEvent?( - session: AuthSession, - calendarId: string, - event: EventCreateInput - ): Promise; - - updateEvent?( - session: AuthSession, - calendarId: string, - eventId: string, - event: EventUpdateInput - ): Promise; - - deleteEvent?( - session: AuthSession, - calendarId: string, - eventId: string - ): Promise; +### Bicep with Azure Verified Modules (AVMs) + +```bicep +// main.bicep - Using Azure Verified Modules +targetScope = 'subscription' + +@description('Environment name') +@allowed(['dev', 'staging', 'prod']) +param environment string + +@description('Azure region') +param location string = 'eastus2' + +// Resource Group +module resourceGroup 'br/public:avm/res/resources/resource-group:0.2.0' = { + name: 'rg-luminous-${environment}' + params: { + name: 'rg-luminous-${environment}' + location: location + } } + +// Cosmos DB using AVM +module cosmosDb 'br/public:avm/res/document-db/database-account:0.6.0' = { + name: 'cosmos-luminous-${environment}' + scope: resourceGroup + params: { + name: 'cosmos-lum-${environment}' + location: location + sqlDatabases: [ + { + name: 'luminous' + containers: [ + { name: 'families', partitionKeyPath: '/id' } + { name: 'users', partitionKeyPath: '/familyId' } + { name: 'events', partitionKeyPath: '/familyId' } + { name: 'chores', partitionKeyPath: '/familyId' } + { name: 'devices', partitionKeyPath: '/familyId' } + ] + } + ] + } +} + +// App Service using AVM +module appService 'br/public:avm/res/web/site:0.3.0' = { + name: 'api-luminous-${environment}' + scope: resourceGroup + params: { + name: 'app-lum-api-${environment}' + location: location + kind: 'app' + serverFarmResourceId: appServicePlan.outputs.resourceId + } +} + +// Additional modules... ``` +### Environment Strategy + +| Environment | Purpose | Resources | +|-------------|---------|-----------| +| **dev** | Development | Minimal SKUs, single region | +| **staging** | Pre-production testing | Production-like, single region | +| **prod** | Production | Full SKUs, multi-region optional | + --- -## Deployment Architecture +## Multi-Tenancy Architecture -### Self-Hosted Deployment +### Tenant Isolation Strategy -``` -┌─────────────────────────────────────────────────────────────────────┐ -│ SELF-HOSTED DEPLOYMENT │ -├─────────────────────────────────────────────────────────────────────┤ -│ │ -│ HOME NETWORK │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ │ │ -│ │ ┌────────────────┐ ┌────────────────┐ │ │ -│ │ │ WALL DISPLAY │ │ SYNC SERVER │ (Optional) │ │ -│ │ │ (Kiosk Mode) │◀───────▶│ (Raspberry Pi │ │ │ -│ │ │ │ LAN │ or NAS) │ │ │ -│ │ └────────────────┘ └────────┬───────┘ │ │ -│ │ │ │ │ -│ │ │ LAN │ │ -│ │ ┌────────────────┐ │ │ │ -│ │ │ MOBILE APPS │◀─────────────────┘ │ │ -│ │ │ (on WiFi) │ │ │ -│ │ └────────────────┘ │ │ -│ │ │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ │ -│ │ Internet (for calendar sync) │ -│ ▼ │ -│ ┌────────────────────────────────────────────────────────────────┐ │ -│ │ EXTERNAL SERVICES │ │ -│ │ ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌──────────┐ │ │ -│ │ │ Google │ │ Outlook │ │ Weather │ │ Push │ │ │ -│ │ │ Calendar │ │ Calendar │ │ API │ │ Services │ │ │ -│ │ └──────────┘ └──────────┘ └──────────┘ └──────────┘ │ │ -│ └────────────────────────────────────────────────────────────────┘ │ -│ │ -└─────────────────────────────────────────────────────────────────────┘ -``` +| Layer | Isolation Method | Description | +|-------|-----------------|-------------| +| **Data** | CosmosDB Partitioning | Each family's data in separate logical partition | +| **Storage** | Container per family | Blob storage organized by family ID | +| **API** | JWT Claims | Family ID in token, validated on every request | +| **SignalR** | Groups | Real-time updates scoped to family group | -### Display Hardware Specifications +### Family Onboarding Flow -| Tier | Device | RAM | Storage | Notes | -|------|--------|-----|---------|-------| -| **Budget** | Raspberry Pi 4 | 4GB | 32GB SD | Minimum viable | -| **Recommended** | Raspberry Pi 5 | 8GB | 64GB SD | Smooth experience | -| **Premium** | Intel NUC / Mini PC | 8GB+ | 128GB SSD | Best performance | -| **Tablet** | iPad / Android Tablet | 4GB+ | 64GB+ | No kiosk hardware needed | +1. **User Registration** - Azure AD B2C sign-up (email/password or social) +2. **Family Creation** - POST /api/families creates tenant +3. **Profile Setup** - Add family member profiles +4. **Calendar Connection** - OAuth to Google/Outlook +5. **Device Linking** - Link wall display to family + +--- -### Container Deployment (Server) +## Local Development Architecture + +### Local Development Stack + +``` ++---------------------------------------------------------------------+ +| LOCAL DEVELOPMENT ENVIRONMENT | ++---------------------------------------------------------------------+ +| | +| EMULATORS / LOCAL SERVICES | +| +---------------------------------------------------------------+ | +| | +----------------+ +----------------+ +----------------+ | | +| | | Cosmos DB | | Azurite | | Local Redis | | | +| | | Emulator | | (Blob/Queue) | | (Docker) | | | +| | +----------------+ +----------------+ +----------------+ | | +| +---------------------------------------------------------------+ | +| | +| DEVELOPMENT SERVERS | +| +---------------------------------------------------------------+ | +| | +----------------+ +----------------+ +----------------+ | | +| | | .NET API | | Angular | | Electron | | | +| | | (Kestrel) | | (ng serve) | | (dev mode) | | | +| | | :5000 | | :4200 | | | | | +| | +----------------+ +----------------+ +----------------+ | | +| +---------------------------------------------------------------+ | +| | ++---------------------------------------------------------------------+ +``` + +### Docker Compose for Local Development ```yaml -# docker-compose.yml (example) +# docker-compose.yml version: '3.8' + services: - luminous-server: - image: luminous/server:latest + cosmosdb: + image: mcr.microsoft.com/cosmosdb/linux/azure-cosmos-emulator:latest ports: - - "3000:3000" - volumes: - - luminous-data:/data + - "8081:8081" + - "10251-10254:10251-10254" environment: - - DATABASE_URL=file:/data/luminous.db - - PUSH_VAPID_PUBLIC_KEY=${VAPID_PUBLIC} - - PUSH_VAPID_PRIVATE_KEY=${VAPID_PRIVATE} - restart: unless-stopped + - AZURE_COSMOS_EMULATOR_PARTITION_COUNT=10 + - AZURE_COSMOS_EMULATOR_ENABLE_DATA_PERSISTENCE=true + + redis: + image: redis:7-alpine + ports: + - "6379:6379" -volumes: - luminous-data: + azurite: + image: mcr.microsoft.com/azure-storage/azurite:latest + ports: + - "10000:10000" # Blob + - "10001:10001" # Queue + - "10002:10002" # Table ``` --- ## Architecture Decisions -All significant architecture decisions are documented as Architecture Decision Records (ADRs) in the `/docs/adr/` directory. - ### ADR Index | ADR | Title | Status | Date | |-----|-------|--------|------| -| [ADR-001](./adr/ADR-001-typescript-primary-language.md) | TypeScript as Primary Language | Accepted | 2025-12-21 | -| [ADR-002](./adr/ADR-002-react-ui-framework.md) | React as UI Framework | Accepted | 2025-12-21 | -| [ADR-003](./adr/ADR-003-local-first-architecture.md) | Local-First Data Architecture | Accepted | 2025-12-21 | -| [ADR-004](./adr/ADR-004-two-way-sync-google-first.md) | Two-Way Sync Initially Google-Only | Accepted | 2025-12-21 | -| [ADR-005](./adr/ADR-005-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | -| [ADR-006](./adr/ADR-006-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | -| [ADR-007](./adr/ADR-007-self-hosting-first.md) | Self-Hosting as Primary Model | Accepted | 2025-12-21 | +| [ADR-001](./adr/ADR-001-dotnet-backend.md) | .NET 10 as Backend Platform | Accepted | 2025-12-21 | +| [ADR-002](./adr/ADR-002-angular-web-framework.md) | Angular as Web Framework | Accepted | 2025-12-21 | +| [ADR-003](./adr/ADR-003-azure-cloud-platform.md) | Azure as Cloud Platform | Accepted | 2025-12-21 | +| [ADR-004](./adr/ADR-004-native-mobile-apps.md) | Native iOS and Android Apps | Accepted | 2025-12-21 | +| [ADR-005](./adr/ADR-005-cosmosdb-data-store.md) | CosmosDB as Primary Data Store | Accepted | 2025-12-21 | +| [ADR-006](./adr/ADR-006-multi-tenant-architecture.md) | Multi-Tenant Architecture | Accepted | 2025-12-21 | +| [ADR-007](./adr/ADR-007-bicep-avm-iac.md) | Bicep with AVMs for IaC | Accepted | 2025-12-21 | +| [ADR-008](./adr/ADR-008-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | +| [ADR-009](./adr/ADR-009-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | +| [ADR-010](./adr/ADR-010-azure-ad-b2c-identity.md) | Azure AD B2C for Identity | Accepted | 2025-12-21 | --- @@ -895,6 +710,7 @@ All significant architecture decisions are documented as Architecture Decision R - [Project Overview](./PROJECT-OVERVIEW.md) - [Development Roadmap](./ROADMAP.md) - [Architecture Decision Records](./adr/) +- [Azure Infrastructure](./AZURE-INFRASTRUCTURE.md) - [CLAUDE.md (Development Guidelines)](../CLAUDE.md) --- @@ -904,3 +720,4 @@ All significant architecture decisions are documented as Architecture Decision R | Version | Date | Author | Changes | |---------|------|--------|---------| | 1.0.0 | 2025-12-21 | Luminous Team | Initial architecture document | +| 2.0.0 | 2025-12-21 | Luminous Team | Updated for Azure/.NET/Angular stack, multi-tenancy | diff --git a/docs/PROJECT-OVERVIEW.md b/docs/PROJECT-OVERVIEW.md index 57057ba..46cd779 100644 --- a/docs/PROJECT-OVERVIEW.md +++ b/docs/PROJECT-OVERVIEW.md @@ -1,6 +1,6 @@ # Luminous Project Overview -> **Document Version:** 1.0.0 +> **Document Version:** 2.0.0 > **Last Updated:** 2025-12-21 > **Status:** Draft > **TOGAF Phase:** Architecture Vision (Phase A) @@ -12,14 +12,15 @@ 1. [Executive Summary](#executive-summary) 2. [Business Context](#business-context) 3. [Product Definition](#product-definition) -4. [Stakeholders and Personas](#stakeholders-and-personas) -5. [Core UX Principles](#core-ux-principles) -6. [Functional Scope](#functional-scope) -7. [Non-Functional Requirements](#non-functional-requirements) -8. [Design Constraints](#design-constraints) -9. [Key Design Decisions](#key-design-decisions) -10. [Success Metrics](#success-metrics) -11. [Glossary](#glossary) +4. [Deployment Model](#deployment-model) +5. [Stakeholders and Personas](#stakeholders-and-personas) +6. [Core UX Principles](#core-ux-principles) +7. [Functional Scope](#functional-scope) +8. [Non-Functional Requirements](#non-functional-requirements) +9. [Design Constraints](#design-constraints) +10. [Key Design Decisions](#key-design-decisions) +11. [Success Metrics](#success-metrics) +12. [Glossary](#glossary) --- @@ -64,11 +65,12 @@ The family organization space is served by products like Skylight, Hearth, and C | Goal | Description | Priority | |------|-------------|----------| -| SG-1 | Provide a fully open-source family command center | Critical | -| SG-2 | Support diverse hardware (tablets, displays, DIY solutions) | High | -| SG-3 | Enable self-hosting for privacy-conscious families | High | -| SG-4 | Create an ecosystem of companion apps | Medium | -| SG-5 | Build a community of contributors and users | Medium | +| SG-1 | Provide a cloud-hosted family command center with Azure | Critical | +| SG-2 | Support multi-tenant architecture for family sign-up | Critical | +| SG-3 | Enable native mobile apps for iOS and Android | High | +| SG-4 | Support diverse hardware for display (tablets, mini PCs) | High | +| SG-5 | Enable local development alongside cloud deployment | Medium | +| SG-6 | Build a community of contributors and users | Medium | --- @@ -92,6 +94,93 @@ This constraint is intentional and strategic, aligning with research showing tha --- +## Deployment Model + +### Cloud-Hosted Multi-Tenant Platform + +Luminous is deployed as a cloud-hosted platform on Microsoft Azure, supporting multiple families (tenants) with complete data isolation. + +#### Platform Architecture + +| Component | Description | Azure Service | +|-----------|-------------|---------------| +| **Web Application** | Angular-based web interface | Azure Static Web Apps | +| **API Backend** | .NET 10 REST API | Azure App Service | +| **Real-time Sync** | WebSocket-based synchronization | Azure SignalR Service | +| **Data Storage** | Document database per family | Azure Cosmos DB | +| **File Storage** | Media and file uploads | Azure Blob Storage | +| **Identity** | User authentication and authorization | Azure AD B2C | +| **Background Jobs** | Calendar sync, import processing | Azure Functions | + +#### Multi-Tenancy Model + +Each family represents a **tenant** with complete data isolation: + +1. **Sign-Up Flow**: Users register via Azure AD B2C (email/password or social login) +2. **Family Creation**: First user creates a family (tenant) and becomes the Owner +3. **Member Invitation**: Owner invites family members via email or link +4. **Device Linking**: Wall displays are linked to families via 6-digit codes + +#### Device Linking Flow + +``` ++------------------+ +------------------+ +| DISPLAY APP | | MOBILE APP | ++------------------+ +------------------+ + | | + | 1. Display shows | + | 6-digit link code | + | (expires in 15 min) | + | | + | 2. User logs in + | via Azure AD B2C + | | + | 3. User enters + | link code + | | + | 4. API validates code | + | and links device | + | to family | + |<--------------------------------------| + | | + | 5. Display receives | + | device token and | + | syncs family data | + | | ++------------------+ +------------------+ +``` + +### Native Mobile Applications + +Companion apps are built as **native applications** for optimal user experience: + +| Platform | Technology | Distribution | +|----------|------------|--------------| +| **iOS** | Swift / SwiftUI | Apple App Store | +| **Android** | Kotlin / Jetpack Compose | Google Play Store | + +Native apps provide: +- Push notifications via APNs (iOS) and FCM (Android) +- Biometric authentication +- Offline capability with local caching +- Platform-specific UI/UX patterns + +### Local Development Environment + +Developers can run the full stack locally using: + +| Service | Local Alternative | +|---------|-------------------| +| Cosmos DB | Cosmos DB Emulator | +| Blob Storage | Azurite | +| Redis Cache | Docker Redis | +| Azure Functions | Azure Functions Core Tools | +| Azure AD B2C | Dev B2C tenant or local JWT issuer | + +See [Local Development Guide](./DEVELOPMENT.md) for setup instructions. + +--- + ## Stakeholders and Personas ### Primary Stakeholders diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index a40a0f2..0dbed77 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -1,6 +1,6 @@ # Luminous Development Roadmap -> **Document Version:** 1.0.0 +> **Document Version:** 2.0.0 > **Last Updated:** 2025-12-21 > **Status:** Draft > **TOGAF Phase:** Phase E/F (Opportunities, Solutions & Migration Planning) @@ -50,46 +50,48 @@ Following TOGAF's principle of iterative architecture development: ``` Phase 0: Foundation -├── Development Environment -├── Monorepo Structure -├── Core Domain Models -└── Design System Foundation - -Phase 1: Core Display -├── Display Application Shell -├── Calendar Context -├── Event Display Widgets -└── Offline Data Layer - -Phase 2: Task Management -├── Chore/Task Context -├── Routine Context -├── Rewards Context -└── Progress Visualization - -Phase 3: Mobile Companion -├── Mobile Application Shell -├── Push Notification Service -├── Sync Engine -└── Remote Data Layer - -Phase 4: Household Management -├── Profile Management -├── Meal Planning Context -├── List Management Context -└── Caregiver Portal - -Phase 5: Intelligence -├── Magic Import Service -├── AI Suggestion Engine -├── Natural Language Processing -└── Learning Pipeline - -Phase 6: Ecosystem -├── Plugin Architecture -├── API Gateway -├── Third-Party Integrations -└── Community Contributions ++-- Azure Infrastructure (Bicep/AVMs) ++-- .NET 10 Solution Structure ++-- Angular Web Application Shell ++-- Azure AD B2C Configuration ++-- Local Development Environment + +Phase 1: Core Platform ++-- Multi-Tenant API ++-- CosmosDB Data Layer ++-- User Registration & Family Creation ++-- Device Linking Flow ++-- Web Dashboard MVP + +Phase 2: Display & Calendar ++-- Display Application (Angular + Electron) ++-- Calendar Integration (Google, Outlook) ++-- Event Display Widgets ++-- Real-time Sync (SignalR) + +Phase 3: Native Mobile Apps ++-- iOS App (Swift/SwiftUI) ++-- Android App (Kotlin/Compose) ++-- Push Notification Service ++-- Mobile-specific UX + +Phase 4: Task Management ++-- Chore/Task Context ++-- Routine Context ++-- Rewards System ++-- Progress Visualization + +Phase 5: Household Features ++-- Profile Management ++-- Meal Planning ++-- List Management ++-- Caregiver Portal + +Phase 6: Intelligence & Ecosystem ++-- Magic Import Service ++-- AI Suggestions ++-- Third-Party Integrations ++-- API for Extensions ``` --- @@ -100,13 +102,13 @@ Phase 6: Ecosystem | Phase | Name | Focus | Key Deliverables | |-------|------|-------|------------------| -| **0** | Foundation | Infrastructure | Monorepo, CI/CD, design system, domain models | -| **1** | Core Display | Calendar visibility | Display app, calendar integration, offline mode | -| **2** | Task Management | Chores and routines | Task creation, completion tracking, rewards | -| **3** | Mobile Companion | Mobile control | iOS/Android apps, push notifications, sync | -| **4** | Household Management | Expanded features | Profiles, meals, lists, caregiver sharing | -| **5** | Intelligence Layer | AI features | Magic import, suggestions, automation | -| **6** | Ecosystem Expansion | Platform growth | Plugins, APIs, community tools | +| **0** | Foundation | Infrastructure | Azure IaC, .NET solution, Angular shell, Azure AD B2C | +| **1** | Core Platform | Multi-tenancy | Family sign-up, device linking, CosmosDB, web MVP | +| **2** | Display & Calendar | Calendar visibility | Display app, calendar integration, SignalR sync | +| **3** | Native Mobile | Mobile apps | iOS (Swift), Android (Kotlin), push notifications | +| **4** | Task Management | Chores and routines | Task creation, completion tracking, rewards | +| **5** | Household Features | Expanded features | Profiles, meals, lists, caregiver portal | +| **6** | Intelligence & Ecosystem | AI and extensions | Magic import, suggestions, third-party APIs | --- @@ -114,481 +116,382 @@ Phase 6: Ecosystem ### Objective -Establish the technical foundation, development environment, and architectural patterns that all subsequent phases will build upon. +Establish the Azure infrastructure, .NET backend, Angular frontend, and development environment that all subsequent phases will build upon. ### Scope -#### 0.1 Development Environment +#### 0.1 Azure Infrastructure (Bicep with AVMs) -- [ ] **0.1.1** Initialize monorepo with Turborepo -- [ ] **0.1.2** Configure TypeScript with strict settings -- [ ] **0.1.3** Set up ESLint and Prettier configurations -- [ ] **0.1.4** Configure Vitest for unit testing -- [ ] **0.1.5** Set up Playwright for E2E testing -- [ ] **0.1.6** Implement pre-commit hooks (Husky + lint-staged) -- [ ] **0.1.7** Configure Changesets for versioning +- [ ] **0.1.1** Create Bicep modules for all Azure resources using AVMs +- [ ] **0.1.2** Configure Cosmos DB with required containers +- [ ] **0.1.3** Set up Azure AD B2C tenant and user flows +- [ ] **0.1.4** Configure App Service for .NET API +- [ ] **0.1.5** Set up Azure Static Web Apps for Angular +- [ ] **0.1.6** Configure Key Vault for secrets +- [ ] **0.1.7** Set up environment parameter files (dev, staging, prod) -#### 0.2 CI/CD Pipeline +#### 0.2 .NET Solution Structure -- [ ] **0.2.1** GitHub Actions workflow for linting -- [ ] **0.2.2** GitHub Actions workflow for testing -- [ ] **0.2.3** GitHub Actions workflow for building -- [ ] **0.2.4** Dependabot/Renovate for dependency updates -- [ ] **0.2.5** Code coverage reporting -- [ ] **0.2.6** Release automation pipeline +- [ ] **0.2.1** Create solution with Clean Architecture layers +- [ ] **0.2.2** Set up Luminous.Domain with entities and value objects +- [ ] **0.2.3** Set up Luminous.Application with CQRS handlers +- [ ] **0.2.4** Set up Luminous.Infrastructure with CosmosDB repositories +- [ ] **0.2.5** Set up Luminous.Api with controllers and middleware +- [ ] **0.2.6** Configure dependency injection and options pattern +- [ ] **0.2.7** Set up xUnit test projects -#### 0.3 Core Package Structure +#### 0.3 Angular Web Application -- [ ] **0.3.1** Create `packages/core` with domain model stubs -- [ ] **0.3.2** Create `packages/ui` with design system foundation -- [ ] **0.3.3** Create `packages/sync` with sync engine interfaces -- [ ] **0.3.4** Configure package inter-dependencies -- [ ] **0.3.5** Set up path aliases and TypeScript references +- [ ] **0.3.1** Initialize Angular 19+ project with strict mode +- [ ] **0.3.2** Configure Angular Material or Tailwind CSS +- [ ] **0.3.3** Set up core module with authentication service +- [ ] **0.3.4** Implement MSAL integration for Azure AD B2C +- [ ] **0.3.5** Create shared component library +- [ ] **0.3.6** Configure environment-based API URLs -#### 0.4 Design System Foundation +#### 0.4 Local Development Environment -- [ ] **0.4.1** Define design tokens (colors, typography, spacing) -- [ ] **0.4.2** Create base theme configuration -- [ ] **0.4.3** Implement primitive components (Button, Input, Text) -- [ ] **0.4.4** Set up Storybook for component development -- [ ] **0.4.5** Document accessibility requirements per component +- [ ] **0.4.1** Create Docker Compose for local services +- [ ] **0.4.2** Document Cosmos DB Emulator setup +- [ ] **0.4.3** Create local development scripts (PowerShell/Bash) +- [ ] **0.4.4** Configure launch profiles for debugging +- [ ] **0.4.5** Set up local JWT issuer for development -#### 0.5 Domain Model Implementation +#### 0.5 CI/CD Pipeline -- [ ] **0.5.1** Implement `Household` aggregate -- [ ] **0.5.2** Implement `Profile` entity -- [ ] **0.5.3** Implement `Event` entity -- [ ] **0.5.4** Implement `Chore` entity -- [ ] **0.5.5** Implement shared value objects (DateTime, Color, etc.) -- [ ] **0.5.6** Define domain events -- [ ] **0.5.7** Implement repository interfaces (ports) +- [ ] **0.5.1** GitHub Actions for .NET build and test +- [ ] **0.5.2** GitHub Actions for Angular build and test +- [ ] **0.5.3** GitHub Actions for Bicep deployment +- [ ] **0.5.4** Configure environment-specific deployments +- [ ] **0.5.5** Set up Dependabot for dependency updates #### 0.6 Documentation - [ ] **0.6.1** Complete PROJECT-OVERVIEW.md - [ ] **0.6.2** Complete ARCHITECTURE.md - [ ] **0.6.3** Complete ROADMAP.md -- [ ] **0.6.4** Create initial ADRs -- [ ] **0.6.5** Set up documentation site (optional) +- [ ] **0.6.4** Create ADRs for technology decisions +- [ ] **0.6.5** Create local development setup guide ### Exit Criteria -- All packages build and lint successfully -- Unit test framework operational with example tests -- Design system Storybook accessible -- Domain models pass validation tests -- CI pipeline runs on all pull requests +- Azure infrastructure deploys successfully to dev environment +- .NET API runs locally with Cosmos DB Emulator +- Angular app authenticates via Azure AD B2C +- CI/CD pipeline runs on all pull requests +- Documentation complete and reviewed --- -## Phase 1: Core Display +## Phase 1: Core Platform ### Objective -Deliver a functional wall-mounted display that shows family calendars in a glanceable format with offline capability. +Deliver the multi-tenant platform with user registration, family creation, device linking, and a basic web dashboard. ### Scope -#### 1.1 Display Application Shell +#### 1.1 Multi-Tenant API -- [ ] **1.1.1** Create `apps/display` with Electron/Tauri -- [ ] **1.1.2** Implement kiosk mode (fullscreen, no escape) -- [ ] **1.1.3** Auto-start on system boot -- [ ] **1.1.4** Watchdog for crash recovery -- [ ] **1.1.5** Basic settings screen (PIN-protected) +- [ ] **1.1.1** Implement family (tenant) creation endpoint +- [ ] **1.1.2** Implement user registration and profile creation +- [ ] **1.1.3** Implement JWT claims with family context +- [ ] **1.1.4** Add family-scoped authorization policies +- [ ] **1.1.5** Implement tenant data isolation in repositories -#### 1.2 Calendar Context Implementation +#### 1.2 Device Linking -- [ ] **1.2.1** Implement Google Calendar adapter -- [ ] **1.2.2** Implement ICS URL subscription adapter -- [ ] **1.2.3** OAuth flow for Google authentication -- [ ] **1.2.4** Calendar-to-profile assignment -- [ ] **1.2.5** Recurring event support -- [ ] **1.2.6** Event color mapping +- [ ] **1.2.1** Implement link code generation endpoint +- [ ] **1.2.2** Implement link code validation and device registration +- [ ] **1.2.3** Implement device token issuance +- [ ] **1.2.4** Create device management endpoints +- [ ] **1.2.5** Implement device heartbeat/status tracking -#### 1.3 Calendar Views +#### 1.3 Family Member Management -- [ ] **1.3.1** Day view (next 24 hours focus) -- [ ] **1.3.2** Week view (7-day overview) -- [ ] **1.3.3** Month view (calendar grid) -- [ ] **1.3.4** Agenda view (chronological list) -- [ ] **1.3.5** View switching and navigation -- [ ] **1.3.6** Profile filtering +- [ ] **1.3.1** Implement member invitation flow +- [ ] **1.3.2** Implement role assignment (Owner, Admin, Adult, Teen, Child) +- [ ] **1.3.3** Create profile management endpoints +- [ ] **1.3.4** Implement caregiver access tokens -#### 1.4 Event Display Widgets +#### 1.4 Web Dashboard MVP -- [ ] **1.4.1** Event card component (color-coded by profile) -- [ ] **1.4.2** "What's Next" widget (next 3 events) -- [ ] **1.4.3** Countdown widget (days until major events) -- [ ] **1.4.4** Today summary widget - -#### 1.5 Ambient Widgets - -- [ ] **1.5.1** Clock widget (with timezone) -- [ ] **1.5.2** Weather widget (current + forecast) -- [ ] **1.5.3** Weather API integration (configurable provider) - -#### 1.6 Display Modes - -- [ ] **1.6.1** Normal display mode -- [ ] **1.6.2** Privacy mode (wallpaper/clock only) -- [ ] **1.6.3** Sleep mode (screen off on schedule) -- [ ] **1.6.4** Auto-brightness (if hardware supports) - -#### 1.7 Offline Capability - -- [ ] **1.7.1** SQLite database setup (sql.js) -- [ ] **1.7.2** Local event cache -- [ ] **1.7.3** Offline indicator -- [ ] **1.7.4** Sync status indicator -- [ ] **1.7.5** Automatic sync on reconnection - -#### 1.8 Accessibility - -- [ ] **1.8.1** Large text mode -- [ ] **1.8.2** High contrast mode -- [ ] **1.8.3** Touch target sizing (44x44px minimum) -- [ ] **1.8.4** Readable from 10+ feet +- [ ] **1.4.1** Create family dashboard layout +- [ ] **1.4.2** Implement family settings page +- [ ] **1.4.3** Create member management UI +- [ ] **1.4.4** Implement device management UI +- [ ] **1.4.5** Create responsive design for mobile web ### Exit Criteria -- Display shows events from connected Google Calendar -- Display functions offline with cached data -- Privacy and sleep modes functional -- Tested on Raspberry Pi 4 target hardware -- WCAG 2.1 AA compliance verified +- Users can sign up and create families via Azure AD B2C +- Device linking flow works end-to-end +- Family members can be invited and managed +- Web dashboard displays family information +- All data properly isolated per tenant --- -## Phase 2: Task Management +## Phase 2: Display & Calendar ### Objective -Add chores, routines, and rewards to transform the display from view-only to interactive family coordination. +Deliver the display application with calendar integration, real-time sync, and glanceable views. ### Scope -#### 2.1 Chore/Task Context +#### 2.1 Display Application (Angular + Electron) -- [ ] **2.1.1** Chore creation UI -- [ ] **2.1.2** Chore assignment (profiles or "anyone") -- [ ] **2.1.3** Recurrence patterns -- [ ] **2.1.4** Due date/time support -- [ ] **2.1.5** Priority levels (optional) -- [ ] **2.1.6** Chore completion flow (touch to complete) -- [ ] **2.1.7** Completion history +- [ ] **2.1.1** Create Angular Electron project structure +- [ ] **2.1.2** Implement kiosk mode (fullscreen, no escape) +- [ ] **2.1.3** Auto-start on system boot +- [ ] **2.1.4** Watchdog for crash recovery +- [ ] **2.1.5** Device token authentication +- [ ] **2.1.6** Local caching for offline capability -#### 2.2 Routine Context +#### 2.2 Calendar Integration -- [ ] **2.2.1** Routine builder (sequence of steps) -- [ ] **2.2.2** Step icons (kid-friendly library) -- [ ] **2.2.3** Timer per step (optional) -- [ ] **2.2.4** Multiple display modes (list, cards, slideshow) -- [ ] **2.2.5** Routine progress tracking -- [ ] **2.2.6** Streak tracking +- [ ] **2.2.1** Google Calendar OAuth integration +- [ ] **2.2.2** Microsoft Graph (Outlook) integration +- [ ] **2.2.3** ICS URL subscription support +- [ ] **2.2.4** Calendar-to-profile assignment +- [ ] **2.2.5** Azure Function for calendar sync jobs +- [ ] **2.2.6** Recurring event support -#### 2.3 Starter Content +#### 2.3 Calendar Views -- [ ] **2.3.1** Morning routine template -- [ ] **2.3.2** Bedtime routine template -- [ ] **2.3.3** After-school routine template -- [ ] **2.3.4** Common chore templates -- [ ] **2.3.5** Icon library (100+ kid-friendly icons) +- [ ] **2.3.1** Day view (next 24 hours focus) +- [ ] **2.3.2** Week view (7-day overview) +- [ ] **2.3.3** Month view (calendar grid) +- [ ] **2.3.4** Agenda view (chronological list) +- [ ] **2.3.5** Profile filtering -#### 2.4 Rewards System +#### 2.4 Display Widgets -- [ ] **2.4.1** Point assignment to chores/routines -- [ ] **2.4.2** Per-profile point balance -- [ ] **2.4.3** Custom reward definitions -- [ ] **2.4.4** Reward request/approval workflow -- [ ] **2.4.5** Progress-to-goal visualization -- [ ] **2.4.6** Celebration animations +- [ ] **2.4.1** "What's Next" widget +- [ ] **2.4.2** Countdown widget for major events +- [ ] **2.4.3** Weather widget +- [ ] **2.4.4** Clock widget -#### 2.5 Task Display Widgets +#### 2.5 Real-time Sync (SignalR) -- [ ] **2.5.1** "Today's Tasks" widget -- [ ] **2.5.2** Profile task summary -- [ ] **2.5.3** Routine progress widget -- [ ] **2.5.4** Points/rewards widget -- [ ] **2.5.5** Streak display +- [ ] **2.5.1** Azure SignalR Service integration +- [ ] **2.5.2** Family-scoped message groups +- [ ] **2.5.3** Push updates to connected displays +- [ ] **2.5.4** Connection recovery handling -#### 2.6 Kid Mode +#### 2.6 Display Modes -- [ ] **2.6.1** Simplified UI for children -- [ ] **2.6.2** Large touch targets -- [ ] **2.6.3** Emoji/icon-based labels -- [ ] **2.6.4** Non-reader friendly design -- [ ] **2.6.5** Limited destructive actions +- [ ] **2.6.1** Normal display mode +- [ ] **2.6.2** Privacy mode (wallpaper only) +- [ ] **2.6.3** Sleep mode (scheduled) ### Exit Criteria -- Chores can be created, assigned, and completed on display -- Routines guide children through multi-step processes -- Points accumulate and rewards can be claimed -- Kid mode is intuitive for 6+ year olds -- All task data persists offline +- Display app runs in kiosk mode on various hardware +- Calendar events sync from Google and Outlook +- Real-time updates via SignalR +- Offline mode works with cached data +- WCAG 2.1 AA compliance verified --- -## Phase 3: Mobile Companion +## Phase 3: Native Mobile Apps ### Objective -Deliver iOS and Android companion apps that provide full control and notifications, keeping family members informed on the go. +Deliver native iOS and Android apps with full feature access and push notifications. ### Scope -#### 3.1 Mobile Application Shell +#### 3.1 iOS App (Swift/SwiftUI) -- [ ] **3.1.1** React Native project setup -- [ ] **3.1.2** Navigation structure -- [ ] **3.1.3** Authentication flow -- [ ] **3.1.4** Offline capability -- [ ] **3.1.5** Deep linking support +- [ ] **3.1.1** Xcode project with SwiftUI +- [ ] **3.1.2** MSAL integration for Azure AD B2C +- [ ] **3.1.3** API client with async/await +- [ ] **3.1.4** Core Data for offline caching +- [ ] **3.1.5** Navigation structure (TabView) +- [ ] **3.1.6** Push notifications (APNs) -#### 3.2 Sync Engine +#### 3.2 Android App (Kotlin/Compose) -- [ ] **3.2.1** CRDT-based sync protocol -- [ ] **3.2.2** Conflict resolution logic -- [ ] **3.2.3** Sync status indicators -- [ ] **3.2.4** Background sync -- [ ] **3.2.5** Manual sync trigger +- [ ] **3.2.1** Android Studio project with Jetpack Compose +- [ ] **3.2.2** MSAL integration for Azure AD B2C +- [ ] **3.2.3** Retrofit API client with coroutines +- [ ] **3.2.4** Room for offline caching +- [ ] **3.2.5** Navigation component +- [ ] **3.2.6** Push notifications (FCM) #### 3.3 Mobile Calendar Features -- [ ] **3.3.1** Calendar views (day, week, month, agenda) +- [ ] **3.3.1** Calendar views (day, week, month) - [ ] **3.3.2** Event creation and editing - [ ] **3.3.3** Calendar connection management - [ ] **3.3.4** Profile filtering -#### 3.4 Mobile Task Features - -- [ ] **3.4.1** Chore creation and management -- [ ] **3.4.2** Routine creation and management -- [ ] **3.4.3** Task completion (for self) -- [ ] **3.4.4** Reward management - -#### 3.5 Push Notifications - -- [ ] **3.5.1** Push notification service (APNs + FCM) -- [ ] **3.5.2** Event reminders -- [ ] **3.5.3** Chore due notifications -- [ ] **3.5.4** Completion notifications (kids completed X) -- [ ] **3.5.5** Notification preferences - -#### 3.6 Mobile Widgets - -- [ ] **3.6.1** iOS Today widget (schedule) -- [ ] **3.6.2** iOS lock screen widget -- [ ] **3.6.3** Android widget support +#### 3.4 Mobile Device Features -#### 3.7 Sync Server (Optional) - -- [ ] **3.7.1** Server application shell -- [ ] **3.7.2** REST API for sync -- [ ] **3.7.3** WebSocket for real-time updates -- [ ] **3.7.4** User authentication (OAuth) -- [ ] **3.7.5** Push notification dispatch -- [ ] **3.7.6** Docker deployment +- [ ] **3.4.1** Device linking via code entry +- [ ] **3.4.2** Family member management +- [ ] **3.4.3** Biometric authentication +- [ ] **3.4.4** Widget support (iOS/Android) ### Exit Criteria -- Mobile apps available on iOS and Android -- Changes sync between display and mobile within 60 seconds -- Push notifications delivered reliably -- Offline mode functional on mobile -- App Store / Play Store ready +- iOS app available on App Store (TestFlight initially) +- Android app available on Play Store (Beta track initially) +- Push notifications work for events and reminders +- Apps authenticate via Azure AD B2C +- Offline mode with local caching --- -## Phase 4: Household Management +## Phase 4: Task Management ### Objective -Complete the household coordination features including profiles, meal planning, lists, and caregiver access. +Add chores, routines, and rewards system across all platforms. ### Scope -#### 4.1 Profile Management - -- [ ] **4.1.1** Profile creation and editing -- [ ] **4.1.2** Avatar/photo upload -- [ ] **4.1.3** Color selection -- [ ] **4.1.4** Birthday tracking -- [ ] **4.1.5** Caregiver info section -- [ ] **4.1.6** Pet profiles -- [ ] **4.1.7** Role assignment - -#### 4.2 Meal Planning Context - -- [ ] **4.2.1** Weekly meal plan view -- [ ] **4.2.2** Meal slots (breakfast, lunch, dinner, snacks) -- [ ] **4.2.3** Recipe storage -- [ ] **4.2.4** Recipe import from URLs -- [ ] **4.2.5** Ingredient management -- [ ] **4.2.6** "Add to grocery list" action -- [ ] **4.2.7** Per-profile dietary preferences -- [ ] **4.2.8** Meal plan templates +#### 4.1 Chore Management -#### 4.3 List Management Context +- [ ] **4.1.1** Chore creation API and UI +- [ ] **4.1.2** Assignment to profiles or "anyone" +- [ ] **4.1.3** Recurrence patterns +- [ ] **4.1.4** Due date/time support +- [ ] **4.1.5** Chore completion flow +- [ ] **4.1.6** Completion history -- [ ] **4.3.1** Custom list creation -- [ ] **4.3.2** List templates (grocery, packing, etc.) -- [ ] **4.3.3** Checklist view -- [ ] **4.3.4** Board/kanban view -- [ ] **4.3.5** Category grouping -- [ ] **4.3.6** Item quantities and notes -- [ ] **4.3.7** Private lists (mobile only) -- [ ] **4.3.8** List sharing +#### 4.2 Routine Management -#### 4.4 Caregiver Access +- [ ] **4.2.1** Routine builder (sequence of steps) +- [ ] **4.2.2** Step icons and images +- [ ] **4.2.3** Timer per step (optional) +- [ ] **4.2.4** Routine progress tracking +- [ ] **4.2.5** Streak tracking -- [ ] **4.4.1** Caregiver invitation flow -- [ ] **4.4.2** Time-limited access tokens -- [ ] **4.4.3** Caregiver portal (web, no app required) -- [ ] **4.4.4** View-only calendar access -- [ ] **4.4.5** Caregiver info display -- [ ] **4.4.6** Configurable visibility +#### 4.3 Rewards System -#### 4.5 Display Enhancements +- [ ] **4.3.1** Point assignment to chores/routines +- [ ] **4.3.2** Per-profile point balance +- [ ] **4.3.3** Custom reward definitions +- [ ] **4.3.4** Reward request/approval workflow +- [ ] **4.3.5** Progress visualization +- [ ] **4.3.6** Celebration animations -- [ ] **4.5.1** Meal plan widget on display -- [ ] **4.5.2** Grocery list widget -- [ ] **4.5.3** Profile quick-view -- [ ] **4.5.4** Dashboard customization +#### 4.4 Display Task Widgets -#### 4.6 Grocery Integration (Optional) - -- [ ] **4.6.1** Instacart API integration (US only) -- [ ] **4.6.2** Send list to Instacart -- [ ] **4.6.3** Alternative delivery services +- [ ] **4.4.1** "Today's Tasks" widget +- [ ] **4.4.2** Routine progress widget +- [ ] **4.4.3** Points/rewards widget +- [ ] **4.4.4** Kid-friendly mode ### Exit Criteria -- Complete profile management across all platforms -- Meal planning functional with recipe storage -- Lists usable for grocery and custom purposes -- Caregivers can access via web link -- All features sync across devices +- Chores can be created and completed on all platforms +- Routines guide children through multi-step processes +- Points accumulate and rewards can be claimed +- Real-time sync of task status --- -## Phase 5: Intelligence Layer +## Phase 5: Household Features ### Objective -Add AI-powered features that reduce manual data entry and provide intelligent suggestions. +Complete the household coordination features including profiles, meal planning, lists, and caregiver access. ### Scope -#### 5.1 Magic Import Service - -- [ ] **5.1.1** Email forwarding inbox -- [ ] **5.1.2** Email parsing (ics attachments, event detection) -- [ ] **5.1.3** Photo/screenshot OCR -- [ ] **5.1.4** PDF parsing (school schedules) -- [ ] **5.1.5** Natural language text parsing -- [ ] **5.1.6** URL scraping (event pages) -- [ ] **5.1.7** Approval queue UI -- [ ] **5.1.8** Batch approval +#### 5.1 Profile Management -#### 5.2 Content Extraction +- [ ] **5.1.1** Enhanced profile editing +- [ ] **5.1.2** Avatar/photo upload to Blob Storage +- [ ] **5.1.3** Caregiver info section +- [ ] **5.1.4** Pet profiles -- [ ] **5.2.1** Event extraction (date, time, location, title) -- [ ] **5.2.2** Recurring pattern detection -- [ ] **5.2.3** Meal/recipe extraction from photos -- [ ] **5.2.4** List item extraction from photos -- [ ] **5.2.5** Handwriting recognition +#### 5.2 Meal Planning -#### 5.3 AI Suggestions +- [ ] **5.2.1** Weekly meal plan view +- [ ] **5.2.2** Recipe storage and import +- [ ] **5.2.3** Ingredient management +- [ ] **5.2.4** "Add to grocery list" action +- [ ] **5.2.5** Dietary preferences -- [ ] **5.3.1** Meal plan suggestions (based on preferences) -- [ ] **5.3.2** Chore assignment suggestions -- [ ] **5.3.3** Schedule conflict detection -- [ ] **5.3.4** Routine optimization tips -- [ ] **5.3.5** Grocery list suggestions (from meal plan) +#### 5.3 List Management -#### 5.4 Learning Pipeline +- [ ] **5.3.1** Custom list creation +- [ ] **5.3.2** List templates +- [ ] **5.3.3** Checklist and board views +- [ ] **5.3.4** List sharing -- [ ] **5.4.1** Feedback collection (approvals/rejections) -- [ ] **5.4.2** Model fine-tuning (if self-hosted) -- [ ] **5.4.3** Privacy-preserving learning +#### 5.4 Caregiver Portal -#### 5.5 Voice Input (Optional, Constrained) - -- [ ] **5.5.1** Wake word detection (local) -- [ ] **5.5.2** Voice-to-text for specific commands -- [ ] **5.5.3** "Add event" voice command -- [ ] **5.5.4** "Add to list" voice command -- [ ] **5.5.5** No open-ended queries (zero distraction) +- [ ] **5.4.1** Web-based caregiver access +- [ ] **5.4.2** Time-limited access tokens +- [ ] **5.4.3** Read-only calendar view +- [ ] **5.4.4** Caregiver info display ### Exit Criteria -- Emails can be forwarded to create calendar events -- Photos of schedules are parsed with high accuracy -- Approval queue prevents unwanted automatic changes -- AI suggestions are helpful and non-intrusive -- Privacy maintained (local processing preferred) +- Complete profile management across all platforms +- Meal planning with recipe storage +- Lists usable for grocery and custom purposes +- Caregivers can access via web link --- -## Phase 6: Ecosystem Expansion +## Phase 6: Intelligence & Ecosystem ### Objective -Transform Luminous into a platform that supports community contributions, third-party integrations, and extensibility. +Add AI-powered features and platform extensibility for community contributions and third-party integrations. ### Scope -#### 6.1 Plugin Architecture +#### 6.1 Magic Import Service (Azure Function) -- [ ] **6.1.1** Plugin manifest format -- [ ] **6.1.2** Plugin sandboxing -- [ ] **6.1.3** Plugin lifecycle management -- [ ] **6.1.4** Widget plugins (custom display widgets) -- [ ] **6.1.5** Integration plugins (new calendar providers) -- [ ] **6.1.6** Plugin marketplace/registry +- [ ] **6.1.1** Email forwarding with Azure Logic Apps +- [ ] **6.1.2** Azure Cognitive Services for OCR +- [ ] **6.1.3** PDF parsing with Azure Form Recognizer +- [ ] **6.1.4** Approval queue in web/mobile apps +- [ ] **6.1.5** Azure OpenAI for content extraction -#### 6.2 API Gateway +#### 6.2 AI Suggestions -- [ ] **6.2.1** Public REST API -- [ ] **6.2.2** GraphQL API (optional) -- [ ] **6.2.3** API documentation (OpenAPI) -- [ ] **6.2.4** API key management -- [ ] **6.2.5** Rate limiting -- [ ] **6.2.6** Webhook support +- [ ] **6.2.1** Meal plan suggestions +- [ ] **6.2.2** Schedule conflict detection +- [ ] **6.2.3** Chore assignment suggestions -#### 6.3 Additional Integrations +#### 6.3 Public API -- [ ] **6.3.1** Microsoft 365 two-way sync -- [ ] **6.3.2** iCloud CalDAV two-way sync -- [ ] **6.3.3** TeamSnap integration -- [ ] **6.3.4** School calendar integrations -- [ ] **6.3.5** Home automation (Home Assistant) -- [ ] **6.3.6** Smart display (non-Luminous) API +- [ ] **6.3.1** API Management configuration +- [ ] **6.3.2** OpenAPI documentation +- [ ] **6.3.3** API key management +- [ ] **6.3.4** Rate limiting +- [ ] **6.3.5** Webhook support -#### 6.4 Community Tools +#### 6.4 Additional Integrations -- [ ] **6.4.1** Routine template sharing -- [ ] **6.4.2** Icon pack contributions -- [ ] **6.4.3** Theme sharing -- [ ] **6.4.4** Translation contributions (i18n) -- [ ] **6.4.5** Community forum/Discord +- [ ] **6.4.1** iCloud CalDAV sync +- [ ] **6.4.2** TeamSnap integration +- [ ] **6.4.3** School calendar integrations +- [ ] **6.4.4** Home automation APIs -#### 6.5 Enterprise Features (Optional) +#### 6.5 Community Tools -- [ ] **6.5.1** Multi-household support -- [ ] **6.5.2** Centralized administration -- [ ] **6.5.3** SSO/SAML integration -- [ ] **6.5.4** Audit logging +- [ ] **6.5.1** Routine template sharing +- [ ] **6.5.2** Icon pack contributions +- [ ] **6.5.3** Theme sharing +- [ ] **6.5.4** Internationalization (i18n) ### Exit Criteria -- Third-party developers can create plugins -- Public API enables automation and integrations -- Community can contribute routines, icons, themes -- Internationalization supports major languages -- Platform is self-sustaining with community contributions +- Magic Import processes forwarded emails and photos +- AI suggestions are helpful and privacy-preserving +- Public API enables third-party integrations +- Community can contribute content --- @@ -613,9 +516,10 @@ These features are under consideration for future development: | Current | Future Consideration | Rationale | |---------|---------------------|-----------| | Electron | Tauri | Smaller bundle, better performance | -| SQLite | Durable Objects (Cloudflare) | Managed sync infrastructure | -| React | React 19 Server Components | Improved performance | -| Manual Themes | AI-generated themes | Personalization | +| Angular | Angular with Signals | Reactive improvements | +| Cosmos DB | Azure Cosmos DB Serverless | Cost optimization for smaller deployments | +| Azure AD B2C | Entra External ID | Unified identity platform | +| Azure Functions | Azure Container Apps | More flexibility for long-running jobs | --- diff --git a/docs/adr/ADR-001-dotnet-backend.md b/docs/adr/ADR-001-dotnet-backend.md new file mode 100644 index 0000000..34fe179 --- /dev/null +++ b/docs/adr/ADR-001-dotnet-backend.md @@ -0,0 +1,131 @@ +# ADR-001: .NET 10 as Backend Platform + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Technology + +## Context + +Luminous requires a robust backend platform that can: +- Host REST APIs for all client applications +- Run serverless functions for background processing +- Integrate seamlessly with Azure services +- Support high-performance, multi-tenant operations + +We need to select a backend platform that aligns with our Azure-first hosting strategy. + +## Decision Drivers + +- **Azure integration**: First-class support for Azure services +- **Performance**: High throughput for API operations +- **Type safety**: Strong typing to catch errors at compile time +- **Ecosystem**: Rich libraries for web APIs, data access, and authentication +- **Team expertise**: Available talent and community support +- **Long-term support**: Stable platform with clear upgrade paths + +## Considered Options + +### Option 1: .NET 10 (C#) + +Microsoft's flagship application platform with C# language. + +**Pros:** +- Best-in-class Azure integration +- Excellent performance (among fastest web frameworks) +- Mature ecosystem (Entity Framework, ASP.NET Core) +- Strong typing with modern C# features +- Native support for Azure Functions +- Long-term support from Microsoft + +**Cons:** +- Separate language from frontend (TypeScript) +- Larger runtime compared to some alternatives +- Learning curve for non-.NET developers + +### Option 2: Node.js (TypeScript) + +JavaScript runtime with TypeScript for type safety. + +**Pros:** +- Same language as Angular frontend +- Large npm ecosystem +- Good Azure Functions support +- Familiar to web developers + +**Cons:** +- Single-threaded model limits performance +- TypeScript types are compile-time only +- Less mature ORM ecosystem +- Azure integration not as deep + +### Option 3: Go + +Google's systems programming language. + +**Pros:** +- Excellent performance +- Simple, fast compilation +- Good for microservices + +**Cons:** +- Limited Azure-native integration +- Smaller ecosystem for web APIs +- Less common for enterprise applications +- No native Azure Functions support + +## Decision + +We will use **.NET 10** with C# as the backend platform for all Luminous server-side components. + +## Rationale + +1. **Azure Integration**: .NET has the deepest integration with Azure services. Azure SDKs for .NET are first-class, with features like Managed Identity working seamlessly. + +2. **Performance**: ASP.NET Core consistently ranks among the highest-performing web frameworks. This is critical for a multi-tenant platform serving many families. + +3. **Azure Functions**: .NET isolated worker model provides the best experience for serverless functions with dependency injection and testability. + +4. **Enterprise Ready**: .NET has mature patterns for building enterprise applications including CQRS, domain-driven design, and clean architecture. + +5. **Cosmos DB Integration**: The Azure Cosmos DB SDK for .NET is the most feature-complete, supporting all API operations. + +## Consequences + +### Positive + +- Seamless Azure service integration +- High API performance +- Mature tooling and debugging experience +- Strong community and Microsoft support +- Clear patterns for enterprise architecture + +### Negative + +- Different language from Angular frontend (C# vs TypeScript) +- Requires .NET knowledge for backend contributions +- Larger container images compared to Go + +### Neutral + +- Need to define API contracts for frontend/backend communication +- Must maintain separate build pipelines for .NET and Angular + +## Implementation Notes + +- Use .NET 10 (latest LTS when available) +- Follow Clean Architecture with separate Domain, Application, Infrastructure, and API layers +- Use MediatR for CQRS pattern +- Use FluentValidation for request validation +- Configure dependency injection with built-in DI container + +## Related Decisions + +- [ADR-002: Angular as Web Framework](./ADR-002-angular-web-framework.md) +- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) +- [ADR-005: CosmosDB as Primary Data Store](./ADR-005-cosmosdb-data-store.md) + +## References + +- [ASP.NET Core Documentation](https://learn.microsoft.com/aspnet/core) +- [.NET Performance](https://www.techempower.com/benchmarks/) diff --git a/docs/adr/ADR-001-typescript-primary-language.md b/docs/adr/ADR-001-typescript-primary-language.md deleted file mode 100644 index 31d9195..0000000 --- a/docs/adr/ADR-001-typescript-primary-language.md +++ /dev/null @@ -1,147 +0,0 @@ -# ADR-001: TypeScript as Primary Language - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Technology - -## Context - -Luminous is a cross-platform application suite consisting of: -- A display application (desktop/embedded) -- Mobile applications (iOS and Android) -- A web application -- An optional sync server -- Shared domain logic and UI components - -We need to select a primary programming language that can serve all these platforms effectively while maintaining code quality, developer experience, and long-term maintainability. - -## Decision Drivers - -- **Cross-platform capability**: Must support web, mobile, desktop, and server environments -- **Type safety**: Strong typing to catch errors early and improve maintainability -- **Developer ecosystem**: Rich tooling, libraries, and community support -- **Team familiarity**: Common knowledge base for frontend developers -- **Code sharing**: Ability to share domain logic across all platforms -- **Hiring and contributions**: Available talent pool for open-source contributions - -## Considered Options - -### Option 1: TypeScript - -TypeScript is a typed superset of JavaScript that compiles to plain JavaScript. - -**Pros:** -- Excellent type system with gradual typing -- Native support for React, React Native, and Node.js -- Large ecosystem and community -- First-class tooling (VS Code, ESLint, etc.) -- Can share code between all platforms -- Popular among frontend developers - -**Cons:** -- Runtime type checking requires additional libraries -- Build step required -- Some edge cases where types don't match runtime behavior - -### Option 2: JavaScript (ES2024+) - -Modern JavaScript with the latest ECMAScript features. - -**Pros:** -- No build step for type checking -- Universal support -- Simpler toolchain - -**Cons:** -- No static type checking -- Higher maintenance burden at scale -- Runtime errors harder to catch -- Less IDE support for refactoring - -### Option 3: Dart/Flutter - -Cross-platform framework with its own language. - -**Pros:** -- Excellent cross-platform mobile and desktop -- Strong typing -- Hot reload - -**Cons:** -- Separate web ecosystem -- Smaller community than React -- Less code sharing with web technologies -- Different paradigm than most web developers know - -### Option 4: Kotlin Multiplatform - -Kotlin with multiplatform support. - -**Pros:** -- Strong typing -- Native performance on mobile -- Good for Android developers - -**Cons:** -- Immature web support -- Smaller React ecosystem integration -- Steeper learning curve for web developers -- Limited React Native integration - -## Decision - -We will use **TypeScript** as the primary language for all Luminous applications and packages. - -## Rationale - -TypeScript best satisfies our decision drivers: - -1. **Cross-platform**: TypeScript runs natively in all our target environments through existing runtimes (browsers, Node.js, React Native). - -2. **Type safety**: TypeScript's type system catches a large class of bugs at compile time, improving code quality and reducing runtime errors. This is critical for a family coordination app where reliability matters. - -3. **Code sharing**: With TypeScript, we can share domain models, validation logic, and business rules across display, mobile, web, and server applications through a monorepo structure. - -4. **Developer ecosystem**: The TypeScript/React ecosystem is the largest and most mature for our use case, with excellent libraries for state management, testing, and UI. - -5. **Contribution-friendly**: TypeScript is widely known, making it easier for open-source contributors to participate. - -## Consequences - -### Positive - -- Consistent language across all platforms reduces context switching -- Type definitions serve as living documentation -- Refactoring is safer with compiler-checked types -- Excellent IDE support improves developer productivity -- Large pool of potential contributors - -### Negative - -- Build step adds complexity to development workflow -- Type definitions for some libraries may be incomplete or incorrect -- Learning curve for developers new to TypeScript -- Slightly larger bundle size due to some TypeScript patterns - -### Neutral - -- Must maintain TypeScript configuration across all packages -- Team must agree on TypeScript coding conventions (strict mode, type inference, etc.) - -## Implementation Notes - -- Use TypeScript strict mode in all packages -- Configure path aliases for clean imports -- Use project references for monorepo type checking -- Prefer interfaces over types for object shapes -- Use `unknown` over `any` where type is genuinely unknown - -## Related Decisions - -- [ADR-002: React as UI Framework](./ADR-002-react-ui-framework.md) - -## References - -- [TypeScript Official Documentation](https://www.typescriptlang.org/) -- [TypeScript Design Goals](https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals) diff --git a/docs/adr/ADR-002-angular-web-framework.md b/docs/adr/ADR-002-angular-web-framework.md new file mode 100644 index 0000000..968f93d --- /dev/null +++ b/docs/adr/ADR-002-angular-web-framework.md @@ -0,0 +1,126 @@ +# ADR-002: Angular as Web Framework + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Technology + +## Context + +Luminous requires a web framework for: +- The main web application (accessed by family members) +- The wall-mounted display application (Angular + Electron) +- The caregiver portal + +We need a framework that supports enterprise-grade applications with strong TypeScript integration. + +## Decision Drivers + +- **TypeScript-first**: Strong typing throughout the application +- **Enterprise features**: Built-in routing, forms, HTTP client, dependency injection +- **Performance**: Fast rendering for always-on display +- **Desktop support**: Can be packaged with Electron for display app +- **Maintainability**: Clear patterns for large applications +- **Long-term stability**: Backed by major organization with clear roadmap + +## Considered Options + +### Option 1: Angular + +Google's enterprise web framework with TypeScript. + +**Pros:** +- TypeScript-first with decorators and DI +- Complete framework (routing, forms, HTTP, DI built-in) +- Excellent enterprise adoption +- Clear upgrade path and long-term support +- Works well with Electron +- Strong testing infrastructure + +**Cons:** +- Larger bundle size than some alternatives +- Steeper learning curve +- More opinionated structure + +### Option 2: React + +Meta's component library with TypeScript support. + +**Pros:** +- Largest ecosystem +- Flexible architecture +- React Native for mobile code sharing + +**Cons:** +- Not a complete framework (need many libraries) +- We're using native mobile, so no RN code sharing +- Less opinionated (can lead to inconsistency) + +### Option 3: Vue + +Progressive framework with TypeScript support. + +**Pros:** +- Gentle learning curve +- Good TypeScript support +- Smaller bundle size + +**Cons:** +- Smaller enterprise adoption +- Less mature tooling +- Fewer resources for complex apps + +## Decision + +We will use **Angular 19+** as the web framework for all web-based Luminous applications. + +## Rationale + +1. **TypeScript Integration**: Angular is built with TypeScript and uses it idiomatically with decorators, interfaces, and dependency injection. + +2. **Complete Framework**: Angular includes everything needed for enterprise applications (routing, forms, HTTP, state management) without needing to assemble many libraries. + +3. **Electron Compatibility**: Angular works excellently with Electron for the display application, with good patterns for main/renderer process communication. + +4. **Enterprise Patterns**: Angular's dependency injection and module system align well with our Clean Architecture backend, creating a consistent codebase. + +5. **Google Support**: Long-term support and clear upgrade paths from Google. + +## Consequences + +### Positive + +- Consistent TypeScript throughout frontend +- Built-in features reduce dependency decisions +- Clear patterns for large applications +- Works well with Electron for display app +- Strong form handling for family data entry + +### Negative + +- Larger bundle size (mitigated by lazy loading) +- Steeper learning curve for new contributors +- No direct mobile code sharing (using native instead) + +### Neutral + +- Need to stay current with Angular versions +- Must follow Angular style guide for consistency + +## Implementation Notes + +- Use Angular 19+ with standalone components +- Configure strict TypeScript settings +- Use Angular Material or Tailwind CSS for styling +- Implement lazy loading for feature modules +- Use MSAL Angular for Azure AD B2C authentication + +## Related Decisions + +- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) +- [ADR-004: Native iOS and Android Apps](./ADR-004-native-mobile-apps.md) + +## References + +- [Angular Documentation](https://angular.io) +- [Angular + Electron](https://www.electronjs.org/) diff --git a/docs/adr/ADR-002-react-ui-framework.md b/docs/adr/ADR-002-react-ui-framework.md deleted file mode 100644 index 43c6606..0000000 --- a/docs/adr/ADR-002-react-ui-framework.md +++ /dev/null @@ -1,159 +0,0 @@ -# ADR-002: React as UI Framework - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Technology, Architecture - -## Context - -Luminous requires a UI framework that can power: -- A desktop/embedded display application (Electron or Tauri) -- iOS and Android mobile applications -- A responsive web application -- A caregiver web portal - -We need a framework that enables maximum code sharing while delivering native-feeling experiences on each platform. - -## Decision Drivers - -- **Cross-platform code sharing**: Maximize reuse of UI components and logic -- **Performance**: Smooth 60fps rendering on constrained hardware (Raspberry Pi) -- **Component model**: Support for building a design system -- **Mobile support**: Native-quality mobile applications -- **Ecosystem**: Available libraries for calendar, drag-drop, accessibility -- **Stability**: Long-term support and active maintenance - -## Considered Options - -### Option 1: React + React Native - -React for web/desktop, React Native for mobile. - -**Pros:** -- Largest ecosystem and community -- Excellent TypeScript support -- React Native provides near-native mobile performance -- Huge selection of UI libraries -- Stable and well-documented -- Share business logic and some UI code - -**Cons:** -- Not 100% code sharing between web and native -- React Native requires platform-specific code for some features -- Large bundle size for web - -### Option 2: Flutter - -Cross-platform UI framework using Dart. - -**Pros:** -- True single codebase for all platforms -- Excellent performance -- Built-in widget library -- Good for custom designs - -**Cons:** -- Dart instead of TypeScript (see ADR-001) -- Smaller ecosystem for web -- Different paradigm than web development -- Web performance not as optimized - -### Option 3: Vue + Capacitor - -Vue.js for web, wrapped in Capacitor for mobile. - -**Pros:** -- Single web-based codebase -- Simpler mental model than React -- Good TypeScript support - -**Cons:** -- Mobile apps are essentially webviews (less native feel) -- Performance limitations on low-end devices -- Smaller ecosystem than React -- Less suitable for always-on display - -### Option 4: Svelte + SvelteKit - -Svelte for web with SvelteKit. - -**Pros:** -- Excellent performance (compile-time optimization) -- Smaller bundle size -- Simple syntax - -**Cons:** -- No mature mobile solution -- Smaller ecosystem -- Less proven at scale -- TypeScript support is good but not as mature - -## Decision - -We will use **React** for web and desktop applications, and **React Native** for mobile applications. - -## Rationale - -React + React Native provides the best balance of our decision drivers: - -1. **Code sharing**: While not 100%, we can share: - - All domain logic and state management - - Business validation and rules - - Design tokens and theming - - API and data layer code - - Some UI components with react-native-web - -2. **Performance**: React's virtual DOM and React Native's native bridges provide sufficient performance for our use cases, including the Raspberry Pi display. - -3. **Ecosystem**: React has the largest selection of libraries for our needs: - - Calendar components - - Drag-and-drop for task management - - Accessibility helpers - - Animation libraries - -4. **Stability**: React is maintained by Meta with a strong commitment to backwards compatibility and clear upgrade paths. - -5. **Developer availability**: React is the most popular UI framework, maximizing our contributor pool. - -## Consequences - -### Positive - -- Access to the largest UI ecosystem -- Well-understood patterns and best practices -- Excellent tooling and debugging -- Large talent pool for contributions -- Strong TypeScript integration - -### Negative - -- Platform-specific code required for some mobile features -- Need to maintain separate but similar codebases for web/native -- React Native has some quirks and requires native knowledge for advanced features -- Learning curve for React Native-specific patterns - -### Neutral - -- Must decide on state management solution (Zustand, Redux, etc.) -- Design system needs to account for web vs native differences -- Testing requires different approaches for web and native - -## Implementation Notes - -- Use React 19 features where beneficial -- Consider `react-native-web` for maximum component sharing -- Build design system primitives that abstract platform differences -- Use Zustand for state management (lightweight, TypeScript-first) -- Implement component variants for display (large touch) vs mobile - -## Related Decisions - -- [ADR-001: TypeScript as Primary Language](./ADR-001-typescript-primary-language.md) -- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) - -## References - -- [React Documentation](https://react.dev/) -- [React Native Documentation](https://reactnative.dev/) -- [React Native Web](https://necolas.github.io/react-native-web/) diff --git a/docs/adr/ADR-003-azure-cloud-platform.md b/docs/adr/ADR-003-azure-cloud-platform.md new file mode 100644 index 0000000..ca1aa6c --- /dev/null +++ b/docs/adr/ADR-003-azure-cloud-platform.md @@ -0,0 +1,156 @@ +# ADR-003: Azure as Cloud Platform + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Technology + +## Context + +Luminous needs a cloud platform to host: +- Multi-tenant API backend +- Serverless functions for background processing +- Database for family data +- File storage for media +- Identity services for authentication +- Real-time messaging for sync + +We need to choose between major cloud providers or a multi-cloud/self-hosted approach. + +## Decision Drivers + +- **Enterprise readiness**: Production-grade services with SLAs +- **.NET integration**: Seamless experience with our backend platform +- **Identity services**: Consumer identity management (B2C) +- **Global availability**: Multi-region support for future expansion +- **Cost management**: Predictable pricing for SaaS model +- **Developer experience**: Good tooling and documentation + +## Considered Options + +### Option 1: Microsoft Azure + +Microsoft's cloud platform with .NET-first approach. + +**Pros:** +- Best .NET SDK and tooling integration +- Azure AD B2C for consumer identity +- Cosmos DB for global-scale NoSQL +- Azure Static Web Apps for Angular +- Excellent Azure Functions experience +- Bicep for native IaC + +**Cons:** +- Some services more expensive than alternatives +- Occasional service complexity +- Steeper learning curve for some services + +### Option 2: AWS + +Amazon's comprehensive cloud platform. + +**Pros:** +- Largest market share +- Mature services +- Competitive pricing + +**Cons:** +- .NET is second-class citizen +- No built-in B2C identity (need Cognito) +- Terraform required for IaC (not native) + +### Option 3: Google Cloud + +Google's cloud platform. + +**Pros:** +- Strong in data and AI +- Good Kubernetes support + +**Cons:** +- Smallest enterprise adoption +- .NET support limited +- No B2C identity service + +### Option 4: Self-Hosted + +Run on own infrastructure or VPS. + +**Pros:** +- Full control +- No vendor lock-in + +**Cons:** +- Significant operational burden +- No managed identity service +- Limited scalability +- Requires DevOps expertise + +## Decision + +We will use **Microsoft Azure** as the cloud platform for Luminous. + +## Rationale + +1. **.NET First**: Azure is the natural home for .NET applications with first-class SDKs, tooling, and documentation. + +2. **Azure AD B2C**: Provides consumer identity management out of the box, including social logins (Google, Apple), MFA, and custom policies. + +3. **Cosmos DB**: Global-scale NoSQL database with excellent .NET SDK, ideal for multi-tenant family data. + +4. **Serverless**: Azure Functions with .NET isolated model provides the best experience for our background jobs. + +5. **Bicep with AVMs**: Azure's native IaC with verified modules reduces infrastructure code complexity. + +6. **SignalR Service**: Managed WebSocket infrastructure for real-time sync between devices. + +## Consequences + +### Positive + +- Seamless .NET development experience +- Managed identity without building auth from scratch +- Global scale with Cosmos DB +- Native IaC with Bicep +- Single vendor for all services + +### Negative + +- Vendor lock-in to Microsoft +- Some services more expensive than alternatives +- Learning curve for Azure-specific services + +### Neutral + +- Need Azure subscription management +- Should implement cost monitoring and alerts +- Consider Azure credits for development + +## Azure Services Used + +| Service | Purpose | +|---------|---------| +| **App Service** | API hosting | +| **Azure Functions** | Serverless compute | +| **Cosmos DB** | Document database | +| **Blob Storage** | File storage | +| **Azure AD B2C** | Consumer identity | +| **SignalR Service** | Real-time messaging | +| **Key Vault** | Secrets management | +| **App Configuration** | Feature flags, settings | +| **Redis Cache** | Session and cache | +| **Service Bus** | Message queuing | +| **Static Web Apps** | Angular hosting | +| **Application Insights** | Monitoring | + +## Related Decisions + +- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) +- [ADR-005: CosmosDB as Primary Data Store](./ADR-005-cosmosdb-data-store.md) +- [ADR-007: Bicep with AVMs for IaC](./ADR-007-bicep-avm-iac.md) +- [ADR-010: Azure AD B2C for Identity](./ADR-010-azure-ad-b2c-identity.md) + +## References + +- [Azure Documentation](https://learn.microsoft.com/azure) +- [Azure for .NET Developers](https://learn.microsoft.com/dotnet/azure/) diff --git a/docs/adr/ADR-003-local-first-architecture.md b/docs/adr/ADR-003-local-first-architecture.md deleted file mode 100644 index 7ed3fb7..0000000 --- a/docs/adr/ADR-003-local-first-architecture.md +++ /dev/null @@ -1,169 +0,0 @@ -# ADR-003: Local-First Data Architecture - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Architecture - -## Context - -Luminous is designed for always-on operation on wall-mounted displays, which presents unique requirements: - -1. **Reliability**: The display must show current information even during internet outages -2. **Privacy**: Families want control over their personal data -3. **Performance**: UI interactions must be immediate, not dependent on network latency -4. **Self-hosting**: Users want the option to run everything locally - -We need to decide on a data architecture that addresses these requirements. - -## Decision Drivers - -- **Offline functionality**: Display must work without internet connection -- **Data ownership**: Users must be able to self-host and own their data -- **Real-time sync**: Changes should propagate quickly across devices -- **Conflict resolution**: Multiple devices may edit the same data -- **Performance**: No waiting for network on user interactions -- **Simplicity**: Architecture should be understandable and maintainable - -## Considered Options - -### Option 1: Local-First with CRDT Sync - -Data stored locally on each device, synchronized using Conflict-free Replicated Data Types. - -**Pros:** -- Works offline by default -- Immediate UI response -- Automatic conflict resolution -- Data stays local (privacy) -- Server is optional for multi-device sync - -**Cons:** -- CRDT complexity for some data types -- Storage duplication across devices -- Initial sync can be slow for large datasets -- Debugging sync issues is complex - -### Option 2: Cloud-First with Offline Cache - -Primary data in cloud, with local caching for offline use. - -**Pros:** -- Single source of truth -- Simpler conflict resolution -- Smaller local storage needs - -**Cons:** -- Requires internet for full functionality -- Privacy concerns with cloud storage -- Latency on all write operations -- Vendor lock-in with cloud provider -- Ongoing hosting costs - -### Option 3: Hybrid (Local Primary, Cloud Backup) - -Local storage as primary, cloud as optional backup and sync. - -**Pros:** -- Best of both approaches -- Optional cloud dependency -- Privacy-preserving by default - -**Cons:** -- Two systems to maintain -- Complex sync logic -- Potential for data divergence - -## Decision - -We will implement a **Local-First architecture** with optional CRDT-based synchronization. - -Core principles: -1. All data is stored locally on each device first -2. UI operations read/write to local storage only -3. Synchronization happens in the background -4. The server is optional and only coordinates sync between devices -5. Conflicts are resolved automatically using CRDTs where possible - -## Rationale - -Local-first architecture best meets our requirements: - -1. **Reliability**: The display always has local data available. Even if the internet is down for days, the calendar shows cached events, chores are visible, and tasks can be completed. - -2. **Privacy**: Data never leaves the home network unless the user explicitly configures sync. Self-hosters can run everything locally. - -3. **Performance**: All UI interactions are instant because they only touch local storage. Sync happens asynchronously. - -4. **User experience**: No loading spinners for basic operations. The app feels native and responsive. - -5. **Self-hosting friendly**: The optional sync server can run on a Raspberry Pi or NAS, keeping all data on the local network. - -## Consequences - -### Positive - -- Display works perfectly offline -- Immediate UI feedback on all actions -- No mandatory cloud dependency -- Strong privacy story -- Works well with self-hosting -- Reduced server infrastructure needs - -### Negative - -- Must implement sync logic (complexity) -- CRDT learning curve for team -- Storage requirements higher (data on all devices) -- Some calendar integrations require internet (unavoidable) -- Conflict resolution edge cases to handle - -### Neutral - -- Need to choose and implement CRDT library -- Must design data models with CRDTs in mind -- Initial sync may take time for new devices -- Testing requires simulating various sync scenarios - -## Implementation Notes - -### Storage Stack - -- **Display/Desktop**: SQLite via sql.js (WebAssembly) -- **Mobile**: SQLite via expo-sqlite or react-native-sqlite -- **Web**: Origin Private File System (OPFS) or IndexedDB fallback - -### Sync Strategy - -1. **Event log approach**: Track all changes as events -2. **CRDT types**: Use Yjs or Automerge for collaborative data -3. **Sync protocol**: WebSocket for real-time, REST for batch - -### Data Model Considerations - -- Design entities with CRDT-friendly IDs (UUIDs) -- Avoid counters (use G-Counters or PN-Counters) -- Prefer append-only where possible (completions, events) -- Use tombstones for deletions (soft delete) - -### Conflict Scenarios - -| Data Type | Conflict Strategy | -|-----------|------------------| -| Events | Last-write-wins with vector clocks | -| Chores | Merge fields, LWW for each field | -| Completions | Append-only (no conflicts) | -| Lists | CRDT set with tombstones | -| Profiles | Server-authoritative (rare edits) | - -## Related Decisions - -- [ADR-001: TypeScript as Primary Language](./ADR-001-typescript-primary-language.md) -- [ADR-004: Two-Way Sync Initially Google-Only](./ADR-004-two-way-sync-google-first.md) - -## References - -- [Local-First Software](https://www.inkandswitch.com/local-first/) -- [Yjs CRDT Library](https://yjs.dev/) -- [Automerge](https://automerge.org/) -- [CRDTs: The Hard Parts](https://www.youtube.com/watch?v=x7drE24geUw) diff --git a/docs/adr/ADR-004-native-mobile-apps.md b/docs/adr/ADR-004-native-mobile-apps.md new file mode 100644 index 0000000..333a48d --- /dev/null +++ b/docs/adr/ADR-004-native-mobile-apps.md @@ -0,0 +1,163 @@ +# ADR-004: Native iOS and Android Apps + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Technology, Architecture + +## Context + +Luminous needs companion mobile apps for iOS and Android that provide: +- Full access to family calendar, chores, and lists +- Push notifications for reminders and updates +- Device linking (entering codes to link displays) +- Offline capability with local caching +- Platform-native user experience + +We need to decide between cross-platform frameworks and native development. + +## Decision Drivers + +- **User experience**: Best possible UX on each platform +- **Push notifications**: Reliable APNs and FCM integration +- **Offline support**: Robust local data persistence +- **Performance**: Smooth animations and fast startup +- **Platform features**: Widgets, biometrics, deep linking +- **App Store approval**: Reliable acceptance on both stores + +## Considered Options + +### Option 1: Native (Swift for iOS, Kotlin for Android) + +Separate native applications for each platform. + +**Pros:** +- Best possible UX and performance +- Full access to platform APIs +- Most reliable push notifications +- Platform-native patterns and conventions +- Best App Store acceptance rates +- Mature tooling (Xcode, Android Studio) + +**Cons:** +- Two codebases to maintain +- Different languages (Swift, Kotlin) +- Higher development cost +- Separate teams/skills needed + +### Option 2: React Native + +Cross-platform JavaScript/TypeScript framework. + +**Pros:** +- Single codebase (mostly) +- JavaScript/TypeScript language +- Could share code with React web (not applicable here) + +**Cons:** +- Not using React for web (Angular) +- Bridge overhead affects performance +- Native module updates can lag +- Push notification setup still complex + +### Option 3: Flutter + +Cross-platform Dart framework. + +**Pros:** +- Single codebase +- Great performance +- Beautiful UI toolkit + +**Cons:** +- Dart language (not TypeScript) +- Separate ecosystem from web +- Large app size +- Less mature than native + +### Option 4: Kotlin Multiplatform + +Shared Kotlin code with native UI. + +**Pros:** +- Shared business logic +- Native UI on both platforms +- Better than full cross-platform + +**Cons:** +- Relatively new technology +- iOS support still maturing +- Smaller community + +## Decision + +We will build **native mobile apps**: Swift/SwiftUI for iOS and Kotlin/Jetpack Compose for Android. + +## Rationale + +1. **User Experience**: Native apps provide the best possible experience on each platform, following platform conventions and guidelines. + +2. **Push Notifications**: Direct APNs and FCM integration is more reliable than cross-platform abstraction layers. + +3. **Offline/Caching**: Native persistence (Core Data, Room) is more robust and performant than cross-platform alternatives. + +4. **Platform Features**: Widgets, biometrics, and other platform features work best with native code. + +5. **App Store Success**: Native apps have highest acceptance rates and best store presence. + +6. **No Code Sharing Need**: Since web uses Angular (not React), there's no code sharing benefit from React Native. We're building separate clients anyway. + +## Consequences + +### Positive + +- Best possible user experience on each platform +- Most reliable push notifications +- Full access to platform features +- Highest App Store acceptance rates +- Platform-native offline support + +### Negative + +- Two separate codebases +- Need Swift and Kotlin expertise +- Higher development effort +- API contract must be well-defined + +### Neutral + +- Can hire platform specialists +- Need shared API client design +- Must maintain feature parity between platforms + +## Implementation Notes + +### iOS (Swift/SwiftUI) +- SwiftUI for modern declarative UI +- Core Data for offline persistence +- MSAL for Azure AD B2C authentication +- APNs for push notifications +- WidgetKit for home screen widgets + +### Android (Kotlin/Compose) +- Jetpack Compose for modern UI +- Room for offline persistence +- MSAL for Azure AD B2C authentication +- FCM for push notifications +- Glance for app widgets + +### Shared +- OpenAPI-generated API clients +- Common API contract +- Feature parity checklist + +## Related Decisions + +- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) +- [ADR-010: Azure AD B2C for Identity](./ADR-010-azure-ad-b2c-identity.md) + +## References + +- [SwiftUI Documentation](https://developer.apple.com/xcode/swiftui/) +- [Jetpack Compose Documentation](https://developer.android.com/jetpack/compose) +- [MSAL for iOS and Android](https://learn.microsoft.com/azure/active-directory/develop/msal-overview) diff --git a/docs/adr/ADR-004-two-way-sync-google-first.md b/docs/adr/ADR-004-two-way-sync-google-first.md deleted file mode 100644 index c4ab17b..0000000 --- a/docs/adr/ADR-004-two-way-sync-google-first.md +++ /dev/null @@ -1,184 +0,0 @@ -# ADR-004: Two-Way Sync Initially Google-Only - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Architecture, Technology - -## Context - -Luminous needs to integrate with external calendar providers to aggregate family schedules. The key question is whether to support read-only access (displaying external calendars) or full two-way synchronization (creating/editing events that sync back to the provider). - -Two-way sync is significantly more complex than read-only integration due to: -- Conflict resolution with external system -- Different data models and capabilities per provider -- OAuth token management and refresh -- Rate limiting and API quotas -- Handling provider-specific features (Google Meet, Teams, etc.) - -## Decision Drivers - -- **User expectations**: Users expect changes made in Luminous to appear in their calendar app -- **Implementation complexity**: Each provider has different APIs and behaviors -- **Reliability**: Sync errors can lose or duplicate events -- **Maintenance burden**: APIs change; each provider adds maintenance load -- **Time to market**: Need to ship functional product reasonably quickly -- **Open source sustainability**: Maintainers must be able to support integrations - -## Considered Options - -### Option 1: Two-Way Sync with All Providers from Start - -Full bidirectional sync with Google, Outlook, iCloud, and CalDAV. - -**Pros:** -- Complete feature set at launch -- Matches competitor capabilities - -**Cons:** -- Very high implementation effort -- Delays initial release significantly -- Multiple complex APIs to maintain -- iCloud has significant limitations -- CalDAV has many edge cases - -### Option 2: Read-Only for All, Two-Way for None - -Only display calendars; all event creation is in external apps. - -**Pros:** -- Simplest implementation -- No sync conflicts possible -- Works with any ICS feed - -**Cons:** -- Users must switch apps to add events -- Breaks "single command center" value proposition -- Chore/task completion can't sync to calendars - -### Option 3: Two-Way with Google First, Read-Only Others - -Full sync with Google Calendar initially; read-only with others. - -**Pros:** -- Delivers two-way sync for largest user base -- Manageable implementation scope -- Clear path to add more providers -- Google API is well-documented and stable - -**Cons:** -- Users of other providers have limited functionality -- Feature disparity between providers - -### Option 4: Internal Calendar with Export - -Luminous-only calendar, exportable to other systems. - -**Pros:** -- Full control over data model -- No provider dependencies - -**Cons:** -- Doesn't aggregate existing calendars -- Users manage two calendar systems -- Misses core product value - -## Decision - -We will implement **two-way synchronization with Google Calendar first**, with read-only support for other providers (Outlook/Office 365, iCloud, ICS URLs). - -Expansion to two-way sync with other providers will be prioritized based on user demand and contribution. - -## Rationale - -1. **Market coverage**: Google Calendar has the largest market share for personal/family calendars. Supporting it first covers the most users. - -2. **API quality**: Google Calendar API is mature, well-documented, and has clear OAuth flows. It's the most straightforward to implement correctly. - -3. **Scope management**: Implementing one two-way sync correctly is better than implementing multiple poorly. We can learn from Google integration before adding others. - -4. **User value**: Even with read-only access, users get the core value of seeing all calendars in one place. Two-way sync is additive. - -5. **Contribution opportunity**: Read-only providers are easier for contributors to add, while core team focuses on sync complexity. - -## Consequences - -### Positive - -- Manageable scope for initial implementation -- High-quality Google integration -- Clear roadmap for additional providers -- Read-only still provides aggregation value -- Lower maintenance burden initially - -### Negative - -- Outlook/iCloud users have limited functionality at launch -- Potential perception of "Google-only" product -- Must clearly communicate provider capabilities -- Some users may wait for their provider support - -### Neutral - -- Need to design adapter pattern for easy provider addition -- Documentation must be clear about sync capabilities -- Provider support becomes a contribution opportunity - -## Implementation Notes - -### Google Calendar Integration - -1. **OAuth 2.0 flow** with offline access (refresh tokens) -2. **Incremental sync** using sync tokens -3. **Rate limit handling** with exponential backoff -4. **Webhook support** for real-time updates (where available) - -### Read-Only Providers - -| Provider | Protocol | Notes | -|----------|----------|-------| -| Outlook/M365 | Microsoft Graph API | OAuth 2.0, JSON | -| iCloud | CalDAV | App-specific passwords required | -| Generic CalDAV | CalDAV | Basic or OAuth | -| ICS URLs | HTTP(S) | No authentication typically | - -### Adapter Interface - -```typescript -interface CalendarAdapter { - // All providers - listCalendars(): Promise; - fetchEvents(calendarId: string, range: DateRange): Promise; - - // Two-way only (Google initially) - createEvent?(calendarId: string, event: EventInput): Promise; - updateEvent?(calendarId: string, eventId: string, event: EventInput): Promise; - deleteEvent?(calendarId: string, eventId: string): Promise; -} -``` - -### Sync Status UI - -Users need clear visibility into: -- Which calendars are read-only vs read-write -- Last sync time per calendar -- Sync errors and how to resolve them - -## Migration Path - -Adding two-way sync for additional providers: - -1. **Phase 1** (launch): Google two-way, others read-only -2. **Phase 2**: Microsoft 365/Outlook two-way -3. **Phase 3**: CalDAV two-way (generic) -4. **Future**: iCloud (if Apple improves API access) - -## Related Decisions - -- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) - -## References - -- [Google Calendar API](https://developers.google.com/calendar/api) -- [Microsoft Graph Calendar API](https://learn.microsoft.com/en-us/graph/api/resources/calendar) -- [CalDAV RFC 4791](https://datatracker.ietf.org/doc/html/rfc4791) diff --git a/docs/adr/ADR-005-cosmosdb-data-store.md b/docs/adr/ADR-005-cosmosdb-data-store.md new file mode 100644 index 0000000..e850ae2 --- /dev/null +++ b/docs/adr/ADR-005-cosmosdb-data-store.md @@ -0,0 +1,160 @@ +# ADR-005: CosmosDB as Primary Data Store + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Technology + +## Context + +Luminous needs a database that can: +- Store family data (events, chores, lists, profiles) +- Support multi-tenant data isolation +- Scale to thousands of families +- Provide low-latency reads for real-time displays +- Handle flexible document schemas + +## Decision Drivers + +- **Multi-tenancy**: Clean isolation between family data +- **Scalability**: Handle growth from MVP to thousands of families +- **Performance**: Low-latency reads for always-on displays +- **Flexibility**: Schema evolution without migrations +- **Azure integration**: Native integration with our cloud platform +- **Global distribution**: Option for multi-region in future + +## Considered Options + +### Option 1: Azure Cosmos DB (SQL API) + +Microsoft's globally distributed, multi-model database. + +**Pros:** +- Native Azure integration with managed identity +- Horizontal scaling with partitioning +- Low-latency global distribution +- Flexible JSON document model +- Automatic indexing +- Built-in change feed for sync + +**Cons:** +- Cost can grow with scale +- Requires partition key design +- RU model takes learning + +### Option 2: Azure SQL Database + +Traditional relational database on Azure. + +**Pros:** +- Familiar SQL model +- Strong consistency +- Rich query capabilities + +**Cons:** +- Schema migrations needed +- Less flexible for document data +- Harder to partition for multi-tenant +- Scaling more complex + +### Option 3: PostgreSQL (Azure) + +Open-source relational database. + +**Pros:** +- Open standard +- JSON support +- Lower cost + +**Cons:** +- Manual scaling configuration +- Schema management overhead +- Less Azure-native integration + +### Option 4: MongoDB Atlas + +Managed MongoDB service. + +**Pros:** +- Popular document database +- Good developer experience + +**Cons:** +- Third-party service (not Azure-native) +- Separate billing relationship +- Less Azure integration + +## Decision + +We will use **Azure Cosmos DB with SQL API** as the primary data store for Luminous. + +## Rationale + +1. **Multi-Tenant Partitioning**: Cosmos DB's partition key (familyId) provides clean data isolation and horizontal scaling for multi-tenant architecture. + +2. **Azure Native**: Seamless integration with managed identity, Azure Functions, and other Azure services. + +3. **Document Flexibility**: JSON documents adapt well to our domain (events, chores, profiles) without rigid schema migrations. + +4. **Change Feed**: Built-in change feed enables real-time sync to connected displays. + +5. **Performance**: Guaranteed single-digit millisecond latency at any scale. + +6. **Global Distribution**: Option to expand to multiple regions as we grow. + +## Consequences + +### Positive + +- Clean multi-tenant isolation via partitioning +- Flexible schema for domain evolution +- Low-latency reads for displays +- Change feed for real-time sync +- Automatic indexing + +### Negative + +- RU-based pricing requires monitoring +- Partition key design is critical upfront +- Cross-partition queries are expensive +- Learning curve for RU model + +### Neutral + +- Need to design documents and partition strategy carefully +- Should use provisioned throughput for predictability +- Consider autoscale for variable workloads + +## Data Model + +### Partition Strategy + +| Container | Partition Key | Reasoning | +|-----------|---------------|-----------| +| families | /id | One document per family | +| users | /familyId | All users in same family together | +| events | /familyId | Query events by family | +| chores | /familyId | Query chores by family | +| devices | /familyId | Devices belong to family | +| lists | /familyId | Lists belong to family | + +### RU Estimation (MVP) + +| Operation | Frequency | Estimated RUs | +|-----------|-----------|---------------| +| Read today's events | High | ~5 RUs | +| Write event | Medium | ~10 RUs | +| Read chores | Medium | ~5 RUs | +| Complete chore | Low | ~10 RUs | + +Start with 400 RU/s provisioned, enable autoscale as needed. + +## Related Decisions + +- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) +- [ADR-006: Multi-Tenant Architecture](./ADR-006-multi-tenant-architecture.md) + +## References + +- [Azure Cosmos DB Documentation](https://learn.microsoft.com/azure/cosmos-db/) +- [Cosmos DB Partitioning](https://learn.microsoft.com/azure/cosmos-db/partitioning-overview) diff --git a/docs/adr/ADR-006-multi-tenant-architecture.md b/docs/adr/ADR-006-multi-tenant-architecture.md new file mode 100644 index 0000000..abca304 --- /dev/null +++ b/docs/adr/ADR-006-multi-tenant-architecture.md @@ -0,0 +1,164 @@ +# ADR-006: Multi-Tenant Architecture + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture + +## Context + +Luminous serves multiple families, each with their own data and users. We need to decide how to architect the system to support multiple tenants (families) while ensuring: +- Complete data isolation between families +- Easy onboarding of new families +- Efficient resource utilization +- Secure access control + +## Decision Drivers + +- **Data isolation**: Families must never see each other's data +- **Scalability**: Support growth from tens to thousands of families +- **Cost efficiency**: Share infrastructure where appropriate +- **Onboarding**: Quick self-service family creation +- **Security**: Strong tenant boundaries + +## Considered Options + +### Option 1: Shared Database with Partition Key + +Single database with all families, partitioned by family ID. + +**Pros:** +- Most cost-efficient +- Simple infrastructure +- Easy to manage +- Fast onboarding (create documents) + +**Cons:** +- Requires careful partition key design +- Cross-tenant queries possible if bugs exist +- Single point of failure + +### Option 2: Database per Tenant + +Separate database for each family. + +**Pros:** +- Complete physical isolation +- Easy to backup/restore per tenant + +**Cons:** +- Expensive at scale +- Complex provisioning +- Management overhead +- Slow onboarding + +### Option 3: Schema per Tenant + +Shared database with separate schemas/containers per family. + +**Pros:** +- Good isolation +- Moderate cost + +**Cons:** +- Complex container management +- Provisioning overhead +- Not natural for Cosmos DB + +## Decision + +We will use a **shared database with partition key isolation** (Option 1), with familyId as the partition key for all tenant data. + +## Rationale + +1. **Cost Efficiency**: Single Cosmos DB account with shared throughput is most cost-effective for a SaaS model. + +2. **Natural Fit**: Cosmos DB's partition model naturally isolates data by family ID, with each family's data in its own logical partition. + +3. **Fast Onboarding**: Creating a new family only requires inserting documents, no infrastructure provisioning. + +4. **Azure AD B2C Integration**: JWT tokens contain family_id claim, making authorization straightforward. + +5. **Scalability**: Cosmos DB automatically distributes partitions as we grow. + +## Tenant Isolation Layers + +### Layer 1: Data Partitioning + +All tenant data partitioned by familyId in Cosmos DB. + +```csharp +// Every query includes partition key +var events = await container + .GetItemLinqQueryable() + .Where(e => e.FamilyId == currentUserFamilyId) + .ToListAsync(); +``` + +### Layer 2: Authorization + +JWT tokens include family_id claim, validated on every request. + +```csharp +[Authorize(Policy = "FamilyMember")] +public async Task GetEvents() +{ + var familyId = User.GetFamilyId(); // From JWT claim + // All operations scoped to this family +} +``` + +### Layer 3: Blob Storage + +Blob containers organized by family: +``` +/families/{familyId}/avatars/ +/families/{familyId}/recipes/ +``` + +### Layer 4: SignalR Groups + +Real-time updates scoped to family groups: +```csharp +await Clients.Group($"family:{familyId}").SendAsync("EventUpdated", event); +``` + +## Consequences + +### Positive + +- Cost-effective for SaaS model +- Fast family onboarding (seconds) +- Simple infrastructure management +- Natural Cosmos DB pattern +- Scales automatically + +### Negative + +- Bugs could theoretically leak data (mitigated by layers) +- Cross-tenant reporting requires care +- All data in single database + +### Neutral + +- Must enforce partition key in all queries +- Need comprehensive testing for isolation +- Should implement tenant ID validation middleware + +## Security Measures + +1. **Partition Key Enforcement**: Repository base class always includes familyId +2. **Claim Validation**: Middleware validates JWT family_id claim +3. **Query Auditing**: Log all data access with tenant context +4. **Penetration Testing**: Regular testing for tenant isolation +5. **Code Review**: Check all queries include partition scope + +## Related Decisions + +- [ADR-005: CosmosDB as Primary Data Store](./ADR-005-cosmosdb-data-store.md) +- [ADR-010: Azure AD B2C for Identity](./ADR-010-azure-ad-b2c-identity.md) + +## References + +- [Multi-tenant SaaS patterns](https://learn.microsoft.com/azure/architecture/guide/multitenant/overview) +- [Cosmos DB multi-tenancy](https://learn.microsoft.com/azure/cosmos-db/how-to-multi-master) diff --git a/docs/adr/ADR-007-bicep-avm-iac.md b/docs/adr/ADR-007-bicep-avm-iac.md new file mode 100644 index 0000000..45dec73 --- /dev/null +++ b/docs/adr/ADR-007-bicep-avm-iac.md @@ -0,0 +1,259 @@ +# ADR-007: Bicep with AVMs for Infrastructure as Code + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Technology + +## Context + +Luminous requires infrastructure as code (IaC) to provision and manage Azure resources consistently across environments. We need to decide on the IaC approach that provides: +- Reproducible deployments +- Version-controlled infrastructure +- Environment parity (dev/staging/production) +- Secure credential handling +- Easy maintenance + +## Decision Drivers + +- **Azure-native**: Best integration with Azure resources +- **Maintainability**: Easy to understand and modify +- **Community support**: Reusable modules and patterns +- **CI/CD integration**: Works with GitHub Actions +- **Security**: Proper secrets management +- **Type safety**: Catch errors before deployment + +## Considered Options + +### Option 1: Bicep with Azure Verified Modules (AVMs) + +Azure's native IaC language with Microsoft-maintained modules. + +**Pros:** +- Native Azure integration +- Type-safe with IntelliSense +- Simpler syntax than ARM templates +- AVMs are enterprise-tested and security-reviewed +- Built-in parameter validation +- Direct Azure CLI integration + +**Cons:** +- Azure-only (not multi-cloud) +- Newer than Terraform (smaller community) +- AVMs can have version updates + +### Option 2: Terraform + +HashiCorp's multi-cloud IaC tool. + +**Pros:** +- Multi-cloud support +- Large community +- Mature tooling +- State management + +**Cons:** +- Third-party tool for Azure +- HCL learning curve +- State file management complexity +- Azure provider can lag behind features + +### Option 3: Azure ARM Templates + +Azure's original JSON-based IaC. + +**Pros:** +- Fully supported +- No transpilation + +**Cons:** +- Verbose JSON syntax +- Hard to read and maintain +- No native modularity +- Error-prone + +### Option 4: Pulumi + +Programming language-based IaC. + +**Pros:** +- Use TypeScript/C# +- Full programming language features + +**Cons:** +- Additional service to manage +- State management complexity +- Steeper learning curve + +## Decision + +We will use **Bicep with Azure Verified Modules (AVMs)** for all infrastructure as code. + +## Rationale + +1. **Azure Native**: Bicep is the native IaC for Azure, with first-class support and immediate access to new features. + +2. **Azure Verified Modules**: AVMs are Microsoft-maintained, security-reviewed modules that follow best practices and reduce boilerplate. + +3. **Type Safety**: Bicep provides compile-time type checking, catching errors before deployment. + +4. **Simplicity**: Cleaner syntax than ARM templates, easier to read and maintain than Terraform HCL. + +5. **CI/CD Integration**: Direct integration with Azure CLI and GitHub Actions without additional tools. + +6. **No State Management**: Unlike Terraform, Bicep doesn't require separate state file management. + +## Consequences + +### Positive + +- Clean, readable infrastructure code +- Enterprise-tested modules via AVMs +- Type-safe with IntelliSense support +- No external state management +- Direct Azure integration +- Security-reviewed modules + +### Negative + +- Azure-only (not portable) +- Smaller community than Terraform +- AVM versions need monitoring +- Limited third-party integrations + +### Neutral + +- Need to learn Bicep syntax +- Should pin AVM versions in production +- Requires Azure CLI for deployments + +## Implementation + +### Project Structure + +``` +infra/ +├── main.bicep # Main orchestration +├── main.bicepparam # Parameter file +├── modules/ +│ ├── app-service.bicep # App Service wrapper +│ ├── cosmos-db.bicep # Cosmos DB wrapper +│ ├── storage.bicep # Storage account wrapper +│ └── ... +├── environments/ +│ ├── dev.bicepparam # Development parameters +│ ├── staging.bicepparam # Staging parameters +│ └── prod.bicepparam # Production parameters +└── scripts/ + ├── deploy.sh # Deployment script + └── validate.sh # Validation script +``` + +### AVM Usage Example + +```bicep +// Using Azure Verified Module for App Service +module appService 'br/public:avm/res/web/site:0.3.0' = { + name: 'appServiceDeployment' + params: { + name: 'luminous-api-${environment}' + location: location + kind: 'app' + serverFarmResourceId: appServicePlan.outputs.resourceId + managedIdentities: { + systemAssigned: true + } + appSettingsKeyValuePairs: { + AZURE_COSMOS_ENDPOINT: cosmosDb.outputs.endpoint + } + } +} + +// Using AVM for Cosmos DB +module cosmosDb 'br/public:avm/res/document-db/database-account:0.6.0' = { + name: 'cosmosDbDeployment' + params: { + name: 'luminous-cosmos-${environment}' + location: location + sqlDatabases: [ + { + name: 'luminous' + containers: [ + { + name: 'families' + partitionKeyPath: '/id' + } + { + name: 'users' + partitionKeyPath: '/familyId' + } + ] + } + ] + } +} +``` + +### Deployment Script + +```bash +#!/bin/bash +# deploy.sh + +ENVIRONMENT=${1:-dev} +LOCATION=${2:-eastus2} +RESOURCE_GROUP="luminous-${ENVIRONMENT}-rg" + +# Create resource group if needed +az group create --name $RESOURCE_GROUP --location $LOCATION + +# Deploy infrastructure +az deployment group create \ + --resource-group $RESOURCE_GROUP \ + --template-file main.bicep \ + --parameters "environments/${ENVIRONMENT}.bicepparam" \ + --name "luminous-deploy-$(date +%Y%m%d%H%M%S)" +``` + +### GitHub Actions Integration + +```yaml +# .github/workflows/deploy-infra.yml +name: Deploy Infrastructure + +on: + push: + branches: [main] + paths: ['infra/**'] + +jobs: + deploy: + runs-on: ubuntu-latest + steps: + - uses: actions/checkout@v4 + + - uses: azure/login@v2 + with: + client-id: ${{ secrets.AZURE_CLIENT_ID }} + tenant-id: ${{ secrets.AZURE_TENANT_ID }} + subscription-id: ${{ secrets.AZURE_SUBSCRIPTION_ID }} + + - name: Deploy Bicep + uses: azure/arm-deploy@v2 + with: + resourceGroupName: luminous-prod-rg + template: ./infra/main.bicep + parameters: ./infra/environments/prod.bicepparam +``` + +## Related Decisions + +- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) +- [ADR-005: CosmosDB as Primary Data Store](./ADR-005-cosmosdb-data-store.md) +- [ADR-010: Azure AD B2C for Identity](./ADR-010-azure-ad-b2c-identity.md) + +## References + +- [Bicep Documentation](https://learn.microsoft.com/azure/azure-resource-manager/bicep/) +- [Azure Verified Modules](https://azure.github.io/Azure-Verified-Modules/) +- [AVM Bicep Module Index](https://azure.github.io/Azure-Verified-Modules/indexes/bicep/) diff --git a/docs/adr/ADR-007-self-hosting-first.md b/docs/adr/ADR-007-self-hosting-first.md deleted file mode 100644 index f745aaa..0000000 --- a/docs/adr/ADR-007-self-hosting-first.md +++ /dev/null @@ -1,200 +0,0 @@ -# ADR-007: Self-Hosting as Primary Deployment Model - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Architecture, Design - -## Context - -Luminous is an open-source project that handles sensitive family data. We need to decide on the primary deployment model: - -1. Cloud-hosted SaaS (we run the infrastructure) -2. Self-hosted (users run their own infrastructure) -3. Hybrid (both options available) - -This decision affects architecture, data ownership, privacy, costs, and the project's sustainability model. - -## Decision Drivers - -- **Privacy**: Families want control over their personal data -- **Data ownership**: Users should own their data outright -- **Cost sustainability**: Open-source projects need sustainable funding -- **Simplicity for users**: Not all users are technical -- **Project control**: Avoiding infrastructure lock-in -- **Open-source ethos**: Aligning with open-source values - -## Considered Options - -### Option 1: Cloud-Only SaaS - -Luminous runs as a cloud service; users connect their displays and apps. - -**Pros:** -- Simple user setup -- Recurring revenue for sustainability -- Easier to push updates -- Centralized support - -**Cons:** -- Users don't control their data -- Infrastructure costs -- Privacy concerns -- Vendor lock-in -- Conflicts with open-source ethos - -### Option 2: Self-Hosting Only - -Users must run their own server; no cloud option provided. - -**Pros:** -- Complete user data ownership -- No infrastructure costs for project -- Maximum privacy -- True open-source model - -**Cons:** -- High barrier to entry -- Limits adoption to technical users -- Support burden for diverse environments -- Updates require user action - -### Option 3: Self-Hosting First, Cloud Optional - -Self-hosting is the primary model; cloud is an optional convenience layer. - -**Pros:** -- Users can self-host with full features -- Cloud option for less technical users -- Potential revenue from cloud tier -- Maintains open-source credibility -- User choice - -**Cons:** -- Must maintain both models -- Cloud still requires infrastructure -- May cannibalize self-hosting - -### Option 4: Local-First (No Server Required) - -Devices sync peer-to-peer; server is optional even for multi-device. - -**Pros:** -- Minimal infrastructure -- True local-first -- Works in isolated networks - -**Cons:** -- Peer-to-peer sync is complex -- Devices must be discoverable -- No remote access without server - -## Decision - -Luminous will use **self-hosting as the primary deployment model**, with the application designed to work fully without any cloud dependency. - -### Deployment Tiers - -| Tier | Description | Target User | -|------|-------------|-------------| -| **Single Device** | Display + mobile apps sync locally | Non-technical families | -| **Self-Hosted Server** | Docker container on home network | Technical families | -| **Cloud-Hosted** | Managed hosting (future, optional) | Convenience seekers | - -## Rationale - -1. **Privacy alignment**: Families increasingly care about data privacy. Self-hosting ensures family schedules, chore data, and personal information never leave the home network. - -2. **Open-source values**: A self-hostable product aligns with open-source principles. Users aren't dependent on our infrastructure or business continuity. - -3. **Cost sustainability**: We don't bear hosting costs for every user. This makes the project more sustainable long-term. - -4. **Local-first synergy**: Our local-first architecture (ADR-003) means the server is only needed for multi-device sync, not for basic operation. This reduces the barrier to self-hosting. - -5. **Differentiation**: Most competitors are cloud-dependent. Self-hosting is a feature for privacy-conscious families. - -6. **Community contribution**: Self-hosters are often the most engaged contributors to open-source projects. - -## Consequences - -### Positive - -- Users own and control their data -- No infrastructure costs for the project -- Strong privacy story -- Attracts privacy-conscious families -- Aligns with open-source community -- Diverse deployment environments strengthen the product - -### Negative - -- Higher setup barrier for non-technical users -- Must support diverse self-hosted environments -- Less visibility into usage patterns -- Harder to push critical updates -- Potential fragmentation of versions - -### Neutral - -- Docker becomes a deployment requirement -- Documentation must cover self-hosting thoroughly -- May offer managed hosting later for revenue - -## Implementation Notes - -### Single-Device Mode (Simplest) - -For families with only one display and one or two mobile devices: -- Display runs embedded sync service -- Mobile apps connect to display on local network -- No separate server needed -- Setup: Install display app, scan QR code on mobile - -### Self-Hosted Server - -For families wanting remote access or multiple displays: -- Docker container with simple configuration -- Runs on Raspberry Pi, NAS, or any Docker host -- Handles sync coordination and push notifications -- Can expose via reverse proxy for remote access - -```yaml -# docker-compose.yml -version: '3.8' -services: - luminous: - image: luminous/server:latest - ports: - - "3000:3000" - volumes: - - ./data:/data - environment: - - LUMINOUS_SECRET_KEY=${SECRET_KEY} - restart: unless-stopped -``` - -### Future Cloud Option - -If we offer managed hosting: -- Same Docker image, managed by us -- Optional, paid tier -- Data export always available -- No feature differentiation from self-hosted - -### Update Strategy - -For self-hosted users: -- Watchtower or Renovate for auto-updates -- In-app update notifications -- Release notes and migration guides -- Semantic versioning for compatibility - -## Related Decisions - -- [ADR-003: Local-First Data Architecture](./ADR-003-local-first-architecture.md) - -## References - -- [Self-Hosting Guide (future)](../guides/self-hosting.md) -- [Open Source Sustainability](https://opensource.guide/getting-paid/) -- [Home Assistant - Self-Hosted Model](https://www.home-assistant.io/) diff --git a/docs/adr/ADR-005-magic-import-approval.md b/docs/adr/ADR-008-magic-import-approval.md similarity index 90% rename from docs/adr/ADR-005-magic-import-approval.md rename to docs/adr/ADR-008-magic-import-approval.md index 9005d48..4dc496e 100644 --- a/docs/adr/ADR-005-magic-import-approval.md +++ b/docs/adr/ADR-008-magic-import-approval.md @@ -1,4 +1,4 @@ -# ADR-005: Magic Import Requires Approval +# ADR-008: Magic Import Requires Approval > **Status:** Accepted > **Date:** 2025-12-21 @@ -164,6 +164,16 @@ No AI-extracted content will appear on the family calendar or lists until a hous └─────────────────────────────────────────────────────┘ ``` +### Azure Implementation + +The Magic Import pipeline runs as Azure Functions: + +1. **Import Trigger Function**: Receives emails/uploads via Azure Blob Storage +2. **Extraction Function**: Uses Azure AI Document Intelligence for OCR and extraction +3. **Queue Storage**: Pending imports stored in Cosmos DB with `status: 'pending'` +4. **Approval API**: .NET API endpoint for approve/reject actions +5. **SignalR Notification**: Real-time updates when new imports arrive + ### Future Considerations We may revisit this decision if: @@ -175,9 +185,11 @@ Any such change would be opt-in and default to approval-required. ## Related Decisions -- [ADR-006: Zero-Distraction Design Principle](./ADR-006-zero-distraction-principle.md) +- [ADR-009: Zero-Distraction Design Principle](./ADR-009-zero-distraction-principle.md) +- [ADR-005: CosmosDB as Primary Data Store](./ADR-005-cosmosdb-data-store.md) ## References - [Hearth Display Helper Feature](https://www.hearthapp.com/) - [Design for Trust in AI Systems](https://www.nngroup.com/articles/ai-trust/) +- [Azure AI Document Intelligence](https://learn.microsoft.com/azure/ai-services/document-intelligence/) diff --git a/docs/adr/ADR-006-zero-distraction-principle.md b/docs/adr/ADR-009-zero-distraction-principle.md similarity index 92% rename from docs/adr/ADR-006-zero-distraction-principle.md rename to docs/adr/ADR-009-zero-distraction-principle.md index 743a39c..9272f34 100644 --- a/docs/adr/ADR-006-zero-distraction-principle.md +++ b/docs/adr/ADR-009-zero-distraction-principle.md @@ -1,4 +1,4 @@ -# ADR-006: Zero-Distraction Design Principle +# ADR-009: Zero-Distraction Design Principle > **Status:** Accepted > **Date:** 2025-12-21 @@ -144,14 +144,16 @@ Luminous will follow a **zero-distraction design principle**. The following capa ### Technical Enforcement -1. **No browser component**: Display app doesn't include web rendering for arbitrary URLs (only specific integrations like weather) +1. **No browser component**: Angular app doesn't include arbitrary URL rendering (only specific integrations like weather APIs) -2. **Kiosk mode**: Display runs in locked-down mode, no escape to OS +2. **Kiosk mode**: Electron display app runs in locked-down kiosk mode, no escape to OS 3. **No URL input**: No user-facing way to enter arbitrary URLs 4. **Curated integrations**: External services are curated and purpose-specific +5. **Mobile app focus**: Native iOS and Android apps are similarly focused on coordination only + ### Messaging Product messaging should emphasize: @@ -170,7 +172,8 @@ When users request entertainment features, respond with: ## Related Decisions -- [ADR-005: Magic Import Requires Approval](./ADR-005-magic-import-approval.md) +- [ADR-008: Magic Import Requires Approval](./ADR-008-magic-import-approval.md) +- [ADR-002: Angular as Web Framework](./ADR-002-angular-web-framework.md) ## References diff --git a/docs/adr/ADR-010-azure-ad-b2c-identity.md b/docs/adr/ADR-010-azure-ad-b2c-identity.md new file mode 100644 index 0000000..c31a966 --- /dev/null +++ b/docs/adr/ADR-010-azure-ad-b2c-identity.md @@ -0,0 +1,283 @@ +# ADR-010: Azure AD B2C for Identity + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Security + +## Context + +Luminous is a multi-tenant SaaS platform serving multiple families. We need an identity solution that supports: +- Consumer sign-up and sign-in (not enterprise/corporate) +- Social logins (Google, Apple, Microsoft) +- Multi-factor authentication +- Custom claims (family_id, roles) +- Device linking flow +- Multiple platforms (web, mobile, display) + +## Decision Drivers + +- **Consumer identity**: Not enterprise Azure AD, but consumer-focused B2C +- **Social logins**: Families expect Google/Apple sign-in options +- **Security**: MFA, secure token handling, password policies +- **Custom claims**: Need family_id and role claims in tokens +- **Azure integration**: Native integration with our Azure services +- **Platform support**: SDKs for .NET, Angular, iOS, Android + +## Considered Options + +### Option 1: Azure AD B2C + +Microsoft's consumer identity platform. + +**Pros:** +- Native Azure integration +- Social identity providers built-in +- Custom policies for complex flows +- Custom claims support +- MSAL libraries for all platforms +- Scales automatically +- Compliant (SOC 2, GDPR) + +**Cons:** +- Complex custom policy XML +- Learning curve for advanced scenarios +- Per-authentication pricing + +### Option 2: Auth0 + +Third-party identity platform. + +**Pros:** +- Developer-friendly +- Good documentation +- Social connections + +**Cons:** +- Third-party service (not Azure-native) +- Separate billing +- Integration overhead +- Higher cost at scale + +### Option 3: Firebase Authentication + +Google's authentication service. + +**Pros:** +- Easy to set up +- Good mobile SDKs + +**Cons:** +- Not Azure-native +- Limited custom claims +- Google ecosystem dependency + +### Option 4: Custom Authentication + +Build our own authentication system. + +**Pros:** +- Full control + +**Cons:** +- Security risk +- Significant development effort +- Maintenance burden +- No social login out of box +- Not recommended for consumer apps + +## Decision + +We will use **Azure AD B2C** for all identity and authentication in Luminous. + +## Rationale + +1. **Azure Native**: Seamless integration with Azure App Service, Functions, and Cosmos DB via managed identity and token validation. + +2. **Consumer Focus**: B2C is designed for consumer applications, unlike Azure AD which targets enterprises. + +3. **Social Logins**: Built-in support for Google, Apple, Microsoft, and Facebook with minimal configuration. + +4. **Custom Claims**: JWT tokens can include custom claims like `family_id` and `role` for authorization. + +5. **MSAL Libraries**: Microsoft Authentication Library available for .NET, Angular, iOS, and Android. + +6. **Compliance**: SOC 2, HIPAA, GDPR compliant out of the box. + +## Consequences + +### Positive + +- Enterprise-grade security without building it +- Social logins reduce friction +- Custom claims enable family-based authorization +- Single identity across all platforms +- MFA built-in +- Automatic scaling + +### Negative + +- Custom policies have learning curve +- Per-authentication costs (though minimal) +- Azure lock-in for identity +- Complex XML for advanced flows + +### Neutral + +- Need to design custom claims structure +- Should use user flows for simple scenarios, custom policies for complex +- Token validation required in API + +## Implementation + +### User Flows + +| Flow | Purpose | +|------|---------| +| Sign Up / Sign In | Combined flow for new and returning users | +| Password Reset | Self-service password recovery | +| Profile Edit | Update name, email, preferences | + +### Custom Claims + +```json +{ + "sub": "user-guid", + "email": "user@example.com", + "name": "John Doe", + "family_id": "family-guid", + "role": "admin", + "aud": "luminous-api-client-id", + "iss": "https://luminous.b2clogin.com/..." +} +``` + +### Token Validation (.NET API) + +```csharp +// Program.cs +builder.Services + .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) + .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C")); + +// appsettings.json +{ + "AzureAdB2C": { + "Instance": "https://luminous.b2clogin.com", + "Domain": "luminous.onmicrosoft.com", + "ClientId": "api-client-id", + "SignUpSignInPolicyId": "B2C_1_SignUpSignIn" + } +} +``` + +### Angular Integration + +```typescript +// app.config.ts +import { MsalModule, MsalInterceptor } from '@azure/msal-angular'; + +export const appConfig: ApplicationConfig = { + providers: [ + importProvidersFrom( + MsalModule.forRoot({ + auth: { + clientId: 'web-client-id', + authority: 'https://luminous.b2clogin.com/luminous.onmicrosoft.com/B2C_1_SignUpSignIn', + redirectUri: 'https://app.luminous.family' + } + }, { + interactionType: InteractionType.Redirect + }, { + interactionType: InteractionType.Redirect, + protectedResourceMap: new Map([ + ['https://api.luminous.family/*', ['api-scope']] + ]) + }) + ), + { + provide: HTTP_INTERCEPTORS, + useClass: MsalInterceptor, + multi: true + } + ] +}; +``` + +### Mobile Integration (iOS) + +```swift +import MSAL + +class AuthService { + private let authority = "https://luminous.b2clogin.com/tfp/luminous.onmicrosoft.com/B2C_1_SignUpSignIn" + private let clientId = "ios-client-id" + + func signIn() async throws -> MSALResult { + let config = MSALPublicClientApplicationConfig(clientId: clientId) + config.authority = try MSALAuthority(url: URL(string: authority)!) + + let application = try MSALPublicClientApplication(configuration: config) + let parameters = MSALInteractiveTokenParameters( + scopes: ["api-scope"], + webviewParameters: MSALWebviewParameters() + ) + + return try await application.acquireToken(with: parameters) + } +} +``` + +### Device Linking Flow + +For wall displays that don't have keyboards for login: + +1. **Display shows 6-digit code**: Generated by API, stored with expiry +2. **User enters code in mobile app**: While logged in on mobile +3. **API validates and links**: Associates device with user's family +4. **Display receives tokens**: Via SignalR, device is authenticated + +```csharp +// DeviceLinkingService.cs +public async Task GenerateDeviceCodeAsync(string deviceId) +{ + var code = GenerateSecureCode(); // 6 alphanumeric characters + await _cache.SetAsync($"device-code:{code}", new DeviceLink { + DeviceId = deviceId, + ExpiresAt = DateTime.UtcNow.AddMinutes(10) + }); + return code; +} + +public async Task LinkDeviceAsync(string code, string familyId, string userId) +{ + var link = await _cache.GetAsync($"device-code:{code}"); + if (link == null || link.ExpiresAt < DateTime.UtcNow) + return false; + + await _deviceRepository.UpdateFamilyAsync(link.DeviceId, familyId, userId); + await _cache.RemoveAsync($"device-code:{code}"); + return true; +} +``` + +## Security Considerations + +1. **Token Validation**: All APIs validate JWT tokens with proper issuer and audience checks +2. **Refresh Tokens**: Secure storage on mobile (Keychain/Keystore), rotation enabled +3. **MFA**: Enabled for admin operations and sensitive actions +4. **Session Management**: Reasonable token lifetimes, refresh token rotation +5. **Device Codes**: Short expiry (10 minutes), single-use, secure random generation + +## Related Decisions + +- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) +- [ADR-006: Multi-Tenant Architecture](./ADR-006-multi-tenant-architecture.md) +- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) + +## References + +- [Azure AD B2C Documentation](https://learn.microsoft.com/azure/active-directory-b2c/) +- [MSAL for .NET](https://learn.microsoft.com/azure/active-directory/develop/msal-net-initializing-client-applications) +- [MSAL Angular](https://github.com/AzureAD/microsoft-authentication-library-for-js) +- [MSAL iOS](https://github.com/AzureAD/microsoft-authentication-library-for-objc) diff --git a/docs/adr/README.md b/docs/adr/README.md index ddc79f9..53c44ff 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -14,13 +14,27 @@ New ADRs should follow the template in [ADR-000-template.md](./ADR-000-template. | ADR | Title | Status | Date | |-----|-------|--------|------| -| [ADR-001](./ADR-001-typescript-primary-language.md) | TypeScript as Primary Language | Accepted | 2025-12-21 | -| [ADR-002](./ADR-002-react-ui-framework.md) | React as UI Framework | Accepted | 2025-12-21 | -| [ADR-003](./ADR-003-local-first-architecture.md) | Local-First Data Architecture | Accepted | 2025-12-21 | -| [ADR-004](./ADR-004-two-way-sync-google-first.md) | Two-Way Sync Initially Google-Only | Accepted | 2025-12-21 | -| [ADR-005](./ADR-005-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | -| [ADR-006](./ADR-006-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | -| [ADR-007](./ADR-007-self-hosting-first.md) | Self-Hosting as Primary Model | Accepted | 2025-12-21 | +| [ADR-001](./ADR-001-dotnet-backend.md) | .NET 10 as Backend Platform | Accepted | 2025-12-21 | +| [ADR-002](./ADR-002-angular-web-framework.md) | Angular as Web Framework | Accepted | 2025-12-21 | +| [ADR-003](./ADR-003-azure-cloud-platform.md) | Azure as Cloud Platform | Accepted | 2025-12-21 | +| [ADR-004](./ADR-004-native-mobile-apps.md) | Native iOS and Android Apps | Accepted | 2025-12-21 | +| [ADR-005](./ADR-005-cosmosdb-data-store.md) | CosmosDB as Primary Data Store | Accepted | 2025-12-21 | +| [ADR-006](./ADR-006-multi-tenant-architecture.md) | Multi-Tenant Architecture | Accepted | 2025-12-21 | +| [ADR-007](./ADR-007-bicep-avm-iac.md) | Bicep with AVMs for IaC | Accepted | 2025-12-21 | +| [ADR-008](./ADR-008-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | +| [ADR-009](./ADR-009-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | +| [ADR-010](./ADR-010-azure-ad-b2c-identity.md) | Azure AD B2C for Identity | Accepted | 2025-12-21 | + +## Superseded ADRs (Historical Reference) + +The following ADRs from the initial architecture have been superseded: + +| Old ADR | Title | Superseded By | +|---------|-------|---------------| +| ADR-001-typescript | TypeScript as Primary Language | ADR-001, ADR-002 (C#/TypeScript) | +| ADR-002-react | React as UI Framework | ADR-002 (Angular) | +| ADR-003-local-first | Local-First Data Architecture | ADR-003 (Azure Cloud) | +| ADR-007-self-hosting | Self-Hosting as Primary Model | ADR-003 (Azure Cloud) | ## ADR Lifecycle From d0255a51d276c7eac10cddd69f137d24359a5b0c Mon Sep 17 00:00:00 2001 From: Claude Date: Sun, 21 Dec 2025 12:09:46 +0000 Subject: [PATCH 3/3] =?UTF-8?q?=F0=9F=94=90=20auth:=20migrate=20from=20Azu?= =?UTF-8?q?re=20AD=20B2C=20to=20in-house=20passwordless=20authentication?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Replace external identity provider with in-house passwordless-first authentication system supporting: - Passkeys (WebAuthn/FIDO2) as primary method - Hardware security keys (YubiKey, etc.) - Email OTP / Magic links for passwordless - Social sign-on (Google, Apple, Microsoft) - Email/password with MFA as fallback Updated documentation: - ADR-010: Complete rewrite for passwordless architecture - ARCHITECTURE.md: Updated security diagrams and requirements - ROADMAP.md: Updated auth tasks for passkey integration - CLAUDE.md: Updated auth scope description Key benefits: - Phishing-resistant authentication - Better UX with biometrics - No per-authentication costs - Full control over auth flows --- CLAUDE.md | 2 +- docs/ARCHITECTURE.md | 47 +- docs/ROADMAP.md | 22 +- docs/adr/ADR-010-azure-ad-b2c-identity.md | 283 --------- .../ADR-010-passwordless-authentication.md | 557 ++++++++++++++++++ docs/adr/README.md | 2 +- 6 files changed, 595 insertions(+), 318 deletions(-) delete mode 100644 docs/adr/ADR-010-azure-ad-b2c-identity.md create mode 100644 docs/adr/ADR-010-passwordless-authentication.md diff --git a/CLAUDE.md b/CLAUDE.md index 534b7b2..866268e 100644 --- a/CLAUDE.md +++ b/CLAUDE.md @@ -289,7 +289,7 @@ Use scopes to indicate the affected area: **Infrastructure** - `ui` - General UI components -- `auth` - Authentication (Azure AD B2C) +- `auth` - Authentication (Passkeys/WebAuthn/OAuth) - `cosmos` - CosmosDB/data layer changes - `storage` - Blob storage changes - `infra` - Bicep/IaC infrastructure diff --git a/docs/ARCHITECTURE.md b/docs/ARCHITECTURE.md index ec39e54..952452d 100644 --- a/docs/ARCHITECTURE.md +++ b/docs/ARCHITECTURE.md @@ -115,7 +115,7 @@ Following TOGAF Enterprise Architecture principles, Luminous adheres to these fo | | | IDENTITY TIER | | +-------------------------------------------------------------------------+ | -| | AZURE AD B2C / ENTRA EXTERNAL ID | | +| | IN-HOUSE IDENTITY (Passkeys / WebAuthn / OAuth) | | | +-------------------------------------------------------------------------+ | | | +------------------------------------------------------------------------------------+ @@ -143,7 +143,7 @@ LUMINOUS FAMILY HUB (MULTI-TENANT) | +-- PLATFORM CAPABILITY | +-- Tenant Management -| +-- User Authentication (Azure AD B2C) +| +-- User Authentication (Passkeys/WebAuthn) | +-- Device Registration (Board Linking) | +-- Subscription Management | +-- Usage Analytics @@ -192,7 +192,7 @@ LUMINOUS FAMILY HUB (MULTI-TENANT) | +----------+ +----------+ +----------+ +----------+ | | | | User registers --> Creates family --> Invites family --> Links | -| via Azure AD B2C (tenant) members display | +| via Passkey/Email (tenant) members display | | | +---------------------------------------------------------------------+ ``` @@ -286,7 +286,7 @@ public class User { public string Id { get; set; } = Guid.NewGuid().ToString(); public string FamilyId { get; set; } = string.Empty; // Partition key - public string ExternalId { get; set; } = string.Empty; // Azure AD B2C ID + public string ExternalId { get; set; } = string.Empty; // Internal auth ID public string Email { get; set; } = string.Empty; public string DisplayName { get; set; } = string.Empty; public UserRole Role { get; set; } = UserRole.Member; @@ -336,7 +336,7 @@ public enum DeviceType | Data Type | Storage | Partition Strategy | Notes | |-----------|---------|-------------------|-------| | **Families** | CosmosDB | By family ID | Tenant root | -| **Users** | CosmosDB | By family ID | Includes Azure AD B2C link | +| **Users** | CosmosDB | By family ID | Includes auth credentials link | | **Events** | CosmosDB | By family ID | Calendar events | | **Chores** | CosmosDB | By family ID | Tasks and assignments | | **Devices** | CosmosDB | By family ID | Board registrations | @@ -420,7 +420,7 @@ luminous/ | **Storage** | Azure Blob Storage | Latest | Media, files | | **Messaging** | Azure Service Bus | Latest | Async processing | | **Real-time** | Azure SignalR Service | Latest | WebSocket at scale | -| **Identity** | Azure AD B2C | Latest | Consumer identity | +| **Identity** | In-house (FIDO2/WebAuthn) | Latest | Passwordless-first auth | | **IaC** | Bicep + AVMs | Latest | Azure-native, verified modules | ### Platform Matrix @@ -442,30 +442,31 @@ luminous/ ``` +---------------------------------------------------------------------+ -| IDENTITY ARCHITECTURE | +| PASSWORDLESS IDENTITY ARCHITECTURE | +---------------------------------------------------------------------+ | | | +---------------------------------------------------------------+ | -| | AZURE AD B2C | | +| | IN-HOUSE IDENTITY SERVICE | | | | | | +| | PRIMARY (PASSWORDLESS) FALLBACK | | | | +--------------+ +--------------+ +--------------+ | | -| | | Sign Up | | Sign In | | Password | | | -| | | Flow | | Flow | | Reset | | | +| | | Passkeys | | Email OTP | | Password | | | +| | | (WebAuthn) | | (Magic Link) | | (+ MFA) | | | | | +--------------+ +--------------+ +--------------+ | | | | | | -| | +--------------+ +--------------+ | | -| | | Social | | MFA | | | -| | | Providers | | (Optional) | | | -| | | (Google, | | | | | -| | | Apple) | | | | | -| | +--------------+ +--------------+ | | +| | ADDITIONAL METHODS | | +| | +--------------+ +--------------+ +--------------+ | | +| | | Hardware | | Social | | TOTP | | | +| | | Tokens | | (Google, | | (MFA) | | | +| | | (YubiKey) | | Apple) | | | | | +| | +--------------+ +--------------+ +--------------+ | | | | | | | +---------------------------------------------------------------+ | | | | | v | | +---------------------------------------------------------------+ | | | JWT ACCESS TOKEN | | -| | { sub, family_id, roles, permissions, exp, ... } | | +| | { sub, family_id, role, auth_method, mfa_verified, exp, ... } | | | +---------------------------------------------------------------+ | | | | | v | @@ -484,7 +485,7 @@ luminous/ ### Device Linking Flow 1. **Display requests link code** - Generates 6-digit code with 15-minute expiry -2. **User opens mobile app** - Logs in with Azure AD B2C +2. **User opens mobile app** - Logs in with passkey or other method 3. **User enters code** - Associates device with their family 4. **Display receives confirmation** - Gets device token for API access 5. **Display syncs family data** - Pulls events, chores, settings @@ -493,10 +494,12 @@ luminous/ | Category | Requirement | Implementation | |----------|-------------|----------------| -| **Authentication** | OAuth 2.0 / OpenID Connect | Azure AD B2C | -| **Authorization** | Role-based + Family-scoped | Custom policies | +| **Authentication** | Passwordless-first | Passkeys (WebAuthn), Email OTP, Social OAuth | +| **MFA** | Required for password users | TOTP, hardware tokens, passkey as 2FA | +| **Authorization** | Role-based + Family-scoped | JWT claims, custom policies | | **Data Isolation** | Tenant data separation | CosmosDB partitioning | | **Data Encryption** | At rest and in transit | Azure managed encryption, TLS 1.3 | +| **Credential Storage** | Secure key storage | Argon2id hashing, encrypted WebAuthn keys | | **Secrets** | Secure secret storage | Azure Key Vault | | **API Security** | Rate limiting, validation | API Management + middleware | | **Device Auth** | Secure device tokens | JWT with refresh rotation | @@ -618,7 +621,7 @@ module appService 'br/public:avm/res/web/site:0.3.0' = { ### Family Onboarding Flow -1. **User Registration** - Azure AD B2C sign-up (email/password or social) +1. **User Registration** - Sign up with passkey, email OTP, or social login 2. **Family Creation** - POST /api/families creates tenant 3. **Profile Setup** - Add family member profiles 4. **Calendar Connection** - OAuth to Google/Outlook @@ -701,7 +704,7 @@ services: | [ADR-007](./adr/ADR-007-bicep-avm-iac.md) | Bicep with AVMs for IaC | Accepted | 2025-12-21 | | [ADR-008](./adr/ADR-008-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | | [ADR-009](./adr/ADR-009-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | -| [ADR-010](./adr/ADR-010-azure-ad-b2c-identity.md) | Azure AD B2C for Identity | Accepted | 2025-12-21 | +| [ADR-010](./adr/ADR-010-passwordless-authentication.md) | In-House Passwordless Auth | Accepted | 2025-12-21 | --- diff --git a/docs/ROADMAP.md b/docs/ROADMAP.md index 0dbed77..bf26658 100644 --- a/docs/ROADMAP.md +++ b/docs/ROADMAP.md @@ -53,7 +53,7 @@ Phase 0: Foundation +-- Azure Infrastructure (Bicep/AVMs) +-- .NET 10 Solution Structure +-- Angular Web Application Shell -+-- Azure AD B2C Configuration ++-- Passwordless Authentication Setup +-- Local Development Environment Phase 1: Core Platform @@ -102,7 +102,7 @@ Phase 6: Intelligence & Ecosystem | Phase | Name | Focus | Key Deliverables | |-------|------|-------|------------------| -| **0** | Foundation | Infrastructure | Azure IaC, .NET solution, Angular shell, Azure AD B2C | +| **0** | Foundation | Infrastructure | Azure IaC, .NET solution, Angular shell, Passwordless Auth | | **1** | Core Platform | Multi-tenancy | Family sign-up, device linking, CosmosDB, web MVP | | **2** | Display & Calendar | Calendar visibility | Display app, calendar integration, SignalR sync | | **3** | Native Mobile | Mobile apps | iOS (Swift), Android (Kotlin), push notifications | @@ -124,7 +124,7 @@ Establish the Azure infrastructure, .NET backend, Angular frontend, and developm - [ ] **0.1.1** Create Bicep modules for all Azure resources using AVMs - [ ] **0.1.2** Configure Cosmos DB with required containers -- [ ] **0.1.3** Set up Azure AD B2C tenant and user flows +- [ ] **0.1.3** Set up in-house identity service with WebAuthn/passkey support - [ ] **0.1.4** Configure App Service for .NET API - [ ] **0.1.5** Set up Azure Static Web Apps for Angular - [ ] **0.1.6** Configure Key Vault for secrets @@ -145,7 +145,7 @@ Establish the Azure infrastructure, .NET backend, Angular frontend, and developm - [ ] **0.3.1** Initialize Angular 19+ project with strict mode - [ ] **0.3.2** Configure Angular Material or Tailwind CSS - [ ] **0.3.3** Set up core module with authentication service -- [ ] **0.3.4** Implement MSAL integration for Azure AD B2C +- [ ] **0.3.4** Implement WebAuthn/passkey authentication integration - [ ] **0.3.5** Create shared component library - [ ] **0.3.6** Configure environment-based API URLs @@ -177,7 +177,7 @@ Establish the Azure infrastructure, .NET backend, Angular frontend, and developm - Azure infrastructure deploys successfully to dev environment - .NET API runs locally with Cosmos DB Emulator -- Angular app authenticates via Azure AD B2C +- Angular app authenticates via passkey or email OTP - CI/CD pipeline runs on all pull requests - Documentation complete and reviewed @@ -224,7 +224,7 @@ Deliver the multi-tenant platform with user registration, family creation, devic ### Exit Criteria -- Users can sign up and create families via Azure AD B2C +- Users can sign up and create families with passkey or email - Device linking flow works end-to-end - Family members can be invited and managed - Web dashboard displays family information @@ -307,7 +307,7 @@ Deliver native iOS and Android apps with full feature access and push notificati #### 3.1 iOS App (Swift/SwiftUI) - [ ] **3.1.1** Xcode project with SwiftUI -- [ ] **3.1.2** MSAL integration for Azure AD B2C +- [ ] **3.1.2** Passkey integration with ASAuthorizationController - [ ] **3.1.3** API client with async/await - [ ] **3.1.4** Core Data for offline caching - [ ] **3.1.5** Navigation structure (TabView) @@ -316,7 +316,7 @@ Deliver native iOS and Android apps with full feature access and push notificati #### 3.2 Android App (Kotlin/Compose) - [ ] **3.2.1** Android Studio project with Jetpack Compose -- [ ] **3.2.2** MSAL integration for Azure AD B2C +- [ ] **3.2.2** Passkey integration with Credential Manager API - [ ] **3.2.3** Retrofit API client with coroutines - [ ] **3.2.4** Room for offline caching - [ ] **3.2.5** Navigation component @@ -333,7 +333,7 @@ Deliver native iOS and Android apps with full feature access and push notificati - [ ] **3.4.1** Device linking via code entry - [ ] **3.4.2** Family member management -- [ ] **3.4.3** Biometric authentication +- [ ] **3.4.3** Biometric authentication (passkey unlock) - [ ] **3.4.4** Widget support (iOS/Android) ### Exit Criteria @@ -341,7 +341,7 @@ Deliver native iOS and Android apps with full feature access and push notificati - iOS app available on App Store (TestFlight initially) - Android app available on Play Store (Beta track initially) - Push notifications work for events and reminders -- Apps authenticate via Azure AD B2C +- Apps authenticate via passkey or social login - Offline mode with local caching --- @@ -518,7 +518,7 @@ These features are under consideration for future development: | Electron | Tauri | Smaller bundle, better performance | | Angular | Angular with Signals | Reactive improvements | | Cosmos DB | Azure Cosmos DB Serverless | Cost optimization for smaller deployments | -| Azure AD B2C | Entra External ID | Unified identity platform | +| In-house Auth | External IdP | Consider delegating if maintenance burden increases | | Azure Functions | Azure Container Apps | More flexibility for long-running jobs | --- diff --git a/docs/adr/ADR-010-azure-ad-b2c-identity.md b/docs/adr/ADR-010-azure-ad-b2c-identity.md deleted file mode 100644 index c31a966..0000000 --- a/docs/adr/ADR-010-azure-ad-b2c-identity.md +++ /dev/null @@ -1,283 +0,0 @@ -# ADR-010: Azure AD B2C for Identity - -> **Status:** Accepted -> **Date:** 2025-12-21 -> **Deciders:** Luminous Core Team -> **Categories:** Architecture, Security - -## Context - -Luminous is a multi-tenant SaaS platform serving multiple families. We need an identity solution that supports: -- Consumer sign-up and sign-in (not enterprise/corporate) -- Social logins (Google, Apple, Microsoft) -- Multi-factor authentication -- Custom claims (family_id, roles) -- Device linking flow -- Multiple platforms (web, mobile, display) - -## Decision Drivers - -- **Consumer identity**: Not enterprise Azure AD, but consumer-focused B2C -- **Social logins**: Families expect Google/Apple sign-in options -- **Security**: MFA, secure token handling, password policies -- **Custom claims**: Need family_id and role claims in tokens -- **Azure integration**: Native integration with our Azure services -- **Platform support**: SDKs for .NET, Angular, iOS, Android - -## Considered Options - -### Option 1: Azure AD B2C - -Microsoft's consumer identity platform. - -**Pros:** -- Native Azure integration -- Social identity providers built-in -- Custom policies for complex flows -- Custom claims support -- MSAL libraries for all platforms -- Scales automatically -- Compliant (SOC 2, GDPR) - -**Cons:** -- Complex custom policy XML -- Learning curve for advanced scenarios -- Per-authentication pricing - -### Option 2: Auth0 - -Third-party identity platform. - -**Pros:** -- Developer-friendly -- Good documentation -- Social connections - -**Cons:** -- Third-party service (not Azure-native) -- Separate billing -- Integration overhead -- Higher cost at scale - -### Option 3: Firebase Authentication - -Google's authentication service. - -**Pros:** -- Easy to set up -- Good mobile SDKs - -**Cons:** -- Not Azure-native -- Limited custom claims -- Google ecosystem dependency - -### Option 4: Custom Authentication - -Build our own authentication system. - -**Pros:** -- Full control - -**Cons:** -- Security risk -- Significant development effort -- Maintenance burden -- No social login out of box -- Not recommended for consumer apps - -## Decision - -We will use **Azure AD B2C** for all identity and authentication in Luminous. - -## Rationale - -1. **Azure Native**: Seamless integration with Azure App Service, Functions, and Cosmos DB via managed identity and token validation. - -2. **Consumer Focus**: B2C is designed for consumer applications, unlike Azure AD which targets enterprises. - -3. **Social Logins**: Built-in support for Google, Apple, Microsoft, and Facebook with minimal configuration. - -4. **Custom Claims**: JWT tokens can include custom claims like `family_id` and `role` for authorization. - -5. **MSAL Libraries**: Microsoft Authentication Library available for .NET, Angular, iOS, and Android. - -6. **Compliance**: SOC 2, HIPAA, GDPR compliant out of the box. - -## Consequences - -### Positive - -- Enterprise-grade security without building it -- Social logins reduce friction -- Custom claims enable family-based authorization -- Single identity across all platforms -- MFA built-in -- Automatic scaling - -### Negative - -- Custom policies have learning curve -- Per-authentication costs (though minimal) -- Azure lock-in for identity -- Complex XML for advanced flows - -### Neutral - -- Need to design custom claims structure -- Should use user flows for simple scenarios, custom policies for complex -- Token validation required in API - -## Implementation - -### User Flows - -| Flow | Purpose | -|------|---------| -| Sign Up / Sign In | Combined flow for new and returning users | -| Password Reset | Self-service password recovery | -| Profile Edit | Update name, email, preferences | - -### Custom Claims - -```json -{ - "sub": "user-guid", - "email": "user@example.com", - "name": "John Doe", - "family_id": "family-guid", - "role": "admin", - "aud": "luminous-api-client-id", - "iss": "https://luminous.b2clogin.com/..." -} -``` - -### Token Validation (.NET API) - -```csharp -// Program.cs -builder.Services - .AddAuthentication(JwtBearerDefaults.AuthenticationScheme) - .AddMicrosoftIdentityWebApi(builder.Configuration.GetSection("AzureAdB2C")); - -// appsettings.json -{ - "AzureAdB2C": { - "Instance": "https://luminous.b2clogin.com", - "Domain": "luminous.onmicrosoft.com", - "ClientId": "api-client-id", - "SignUpSignInPolicyId": "B2C_1_SignUpSignIn" - } -} -``` - -### Angular Integration - -```typescript -// app.config.ts -import { MsalModule, MsalInterceptor } from '@azure/msal-angular'; - -export const appConfig: ApplicationConfig = { - providers: [ - importProvidersFrom( - MsalModule.forRoot({ - auth: { - clientId: 'web-client-id', - authority: 'https://luminous.b2clogin.com/luminous.onmicrosoft.com/B2C_1_SignUpSignIn', - redirectUri: 'https://app.luminous.family' - } - }, { - interactionType: InteractionType.Redirect - }, { - interactionType: InteractionType.Redirect, - protectedResourceMap: new Map([ - ['https://api.luminous.family/*', ['api-scope']] - ]) - }) - ), - { - provide: HTTP_INTERCEPTORS, - useClass: MsalInterceptor, - multi: true - } - ] -}; -``` - -### Mobile Integration (iOS) - -```swift -import MSAL - -class AuthService { - private let authority = "https://luminous.b2clogin.com/tfp/luminous.onmicrosoft.com/B2C_1_SignUpSignIn" - private let clientId = "ios-client-id" - - func signIn() async throws -> MSALResult { - let config = MSALPublicClientApplicationConfig(clientId: clientId) - config.authority = try MSALAuthority(url: URL(string: authority)!) - - let application = try MSALPublicClientApplication(configuration: config) - let parameters = MSALInteractiveTokenParameters( - scopes: ["api-scope"], - webviewParameters: MSALWebviewParameters() - ) - - return try await application.acquireToken(with: parameters) - } -} -``` - -### Device Linking Flow - -For wall displays that don't have keyboards for login: - -1. **Display shows 6-digit code**: Generated by API, stored with expiry -2. **User enters code in mobile app**: While logged in on mobile -3. **API validates and links**: Associates device with user's family -4. **Display receives tokens**: Via SignalR, device is authenticated - -```csharp -// DeviceLinkingService.cs -public async Task GenerateDeviceCodeAsync(string deviceId) -{ - var code = GenerateSecureCode(); // 6 alphanumeric characters - await _cache.SetAsync($"device-code:{code}", new DeviceLink { - DeviceId = deviceId, - ExpiresAt = DateTime.UtcNow.AddMinutes(10) - }); - return code; -} - -public async Task LinkDeviceAsync(string code, string familyId, string userId) -{ - var link = await _cache.GetAsync($"device-code:{code}"); - if (link == null || link.ExpiresAt < DateTime.UtcNow) - return false; - - await _deviceRepository.UpdateFamilyAsync(link.DeviceId, familyId, userId); - await _cache.RemoveAsync($"device-code:{code}"); - return true; -} -``` - -## Security Considerations - -1. **Token Validation**: All APIs validate JWT tokens with proper issuer and audience checks -2. **Refresh Tokens**: Secure storage on mobile (Keychain/Keystore), rotation enabled -3. **MFA**: Enabled for admin operations and sensitive actions -4. **Session Management**: Reasonable token lifetimes, refresh token rotation -5. **Device Codes**: Short expiry (10 minutes), single-use, secure random generation - -## Related Decisions - -- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) -- [ADR-006: Multi-Tenant Architecture](./ADR-006-multi-tenant-architecture.md) -- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) - -## References - -- [Azure AD B2C Documentation](https://learn.microsoft.com/azure/active-directory-b2c/) -- [MSAL for .NET](https://learn.microsoft.com/azure/active-directory/develop/msal-net-initializing-client-applications) -- [MSAL Angular](https://github.com/AzureAD/microsoft-authentication-library-for-js) -- [MSAL iOS](https://github.com/AzureAD/microsoft-authentication-library-for-objc) diff --git a/docs/adr/ADR-010-passwordless-authentication.md b/docs/adr/ADR-010-passwordless-authentication.md new file mode 100644 index 0000000..7c9b43c --- /dev/null +++ b/docs/adr/ADR-010-passwordless-authentication.md @@ -0,0 +1,557 @@ +# ADR-010: In-House Passwordless Authentication + +> **Status:** Accepted +> **Date:** 2025-12-21 +> **Deciders:** Luminous Core Team +> **Categories:** Architecture, Security + +## Context + +Luminous is a multi-tenant SaaS platform serving multiple families. We need an identity solution that supports: +- Consumer sign-up and sign-in +- Modern passwordless authentication (passkeys, hardware tokens) +- Social logins (Google, Apple, Microsoft) +- Multi-factor authentication +- Custom claims (family_id, roles) +- Device linking flow +- Multiple platforms (web, mobile, display) + +## Decision Drivers + +- **Passwordless-first**: Passkeys and WebAuthn are the future of authentication +- **Security**: Phishing-resistant authentication methods +- **User experience**: Frictionless sign-in with biometrics +- **Flexibility**: Full control over authentication flows +- **Platform support**: Cross-platform passkey support +- **Fallback options**: Email/password for users who need it +- **Cost control**: Avoid per-authentication pricing of external providers + +## Considered Options + +### Option 1: Azure AD B2C / Entra External ID + +Microsoft's consumer identity platform. + +**Pros:** +- Managed service +- Social providers built-in +- Compliant (SOC 2, GDPR) + +**Cons:** +- Limited passkey support +- Complex custom policy XML +- Per-authentication pricing +- Vendor lock-in +- Limited customization of auth UI + +### Option 2: Auth0 / Okta + +Third-party identity platforms. + +**Pros:** +- Developer-friendly +- Good passkey support +- Social connections + +**Cons:** +- Expensive at scale +- External dependency +- Limited control over flows + +### Option 3: In-House with Modern Standards (Selected) + +Build authentication using established libraries and standards. + +**Pros:** +- Full control over authentication experience +- Native passkey/WebAuthn support +- No per-authentication costs +- Customizable UI for family-friendly experience +- Can optimize for our specific use cases + +**Cons:** +- Development effort required +- Security responsibility +- Must maintain ourselves + +## Decision + +We will build **in-house passwordless authentication** using established .NET libraries and security standards, with the following priority order: + +1. **Passkeys** (WebAuthn/FIDO2) - Primary, passwordless +2. **Hardware tokens** (YubiKey, etc.) - For security-conscious users +3. **Email OTP** - Passwordless alternative +4. **Social sign-on** - Google, Apple, Microsoft +5. **Email/password** - Fallback only + +## Rationale + +1. **Passkeys are the future**: Apple, Google, and Microsoft have unified behind passkeys. Building native support positions us well. + +2. **Better UX**: Face ID, Touch ID, Windows Hello provide superior experience to passwords. + +3. **Phishing resistant**: WebAuthn is cryptographically bound to domains, eliminating phishing attacks. + +4. **Cost control**: No per-authentication fees means predictable costs as we scale. + +5. **Full customization**: We can build a family-friendly authentication experience without vendor constraints. + +6. **Proven libraries**: .NET has excellent support via FIDO2 libraries and ASP.NET Core Identity. + +## Authentication Methods + +### Priority 1: Passkeys (WebAuthn/FIDO2) + +| Feature | Description | +|---------|-------------| +| Platform passkeys | Synced via iCloud Keychain, Google Password Manager, Windows Hello | +| Cross-device | QR code flow for signing in on new devices | +| Biometric | Face ID, Touch ID, fingerprint, Windows Hello | +| Discoverable | Usernameless login where supported | + +### Priority 2: Hardware Security Keys + +| Feature | Description | +|---------|-------------| +| FIDO2 keys | YubiKey, Google Titan, Feitian | +| USB/NFC/BLE | Multiple transport options | +| Backup method | For recovery when passkey unavailable | + +### Priority 3: Email OTP (Passwordless) + +| Feature | Description | +|---------|-------------| +| Magic links | Click-to-login email links | +| 6-digit codes | Time-limited verification codes | +| No password needed | True passwordless experience | + +### Priority 4: Social Sign-On + +| Provider | Implementation | +|----------|----------------| +| Google | OAuth 2.0 / OpenID Connect | +| Apple | Sign in with Apple | +| Microsoft | Microsoft Account OAuth | + +### Priority 5: Email/Password (Fallback) + +| Feature | Description | +|---------|-------------| +| Strong passwords | Minimum requirements enforced | +| Breach detection | Check against haveibeenpwned | +| Rate limiting | Prevent brute force attacks | +| MFA required | Mandatory second factor | + +## Multi-Factor Authentication + +MFA is **required** for email/password authentication and **optional** (but encouraged) for passkey users. + +| MFA Method | Use Case | +|------------|----------| +| Passkey as 2FA | Add passkey as second factor to password | +| TOTP apps | Authenticator apps (Google, Microsoft, Authy) | +| Email OTP | Fallback verification via email | +| Hardware key | YubiKey or similar FIDO2 device | + +## Consequences + +### Positive + +- Industry-leading passwordless experience +- Phishing-resistant authentication +- No per-authentication costs +- Full control over user experience +- Better mobile experience with biometrics +- Future-proof authentication stack + +### Negative + +- Initial development investment +- Security responsibility is ours +- Must keep up with WebAuthn spec evolution +- Need to build admin tooling + +### Neutral + +- Need to design credential recovery flows +- Should implement gradual passkey enrollment +- Must handle cross-device scenarios + +## Implementation + +### Technology Stack + +| Component | Technology | +|-----------|------------| +| WebAuthn Server | FIDO2 library for .NET (fido2-net-lib) | +| Identity Core | ASP.NET Core Identity | +| Token Format | JWT with custom claims | +| Session Store | Redis for distributed sessions | +| Credential Store | CosmosDB (encrypted) | +| Social OAuth | ASP.NET Core Authentication | + +### Database Schema + +```csharp +// UserCredential.cs - Stores all credential types +public class UserCredential +{ + public string Id { get; set; } = Guid.NewGuid().ToString(); + public string UserId { get; set; } = string.Empty; + public CredentialType Type { get; set; } + public string? CredentialId { get; set; } // For WebAuthn + public byte[]? PublicKey { get; set; } // For WebAuthn + public string? ProviderKey { get; set; } // For social logins + public string? ProviderName { get; set; } // For social logins + public string? PasswordHash { get; set; } // For password fallback + public DateTime CreatedAt { get; set; } + public DateTime? LastUsedAt { get; set; } + public string? DeviceName { get; set; } // "John's iPhone" + public bool IsBackup { get; set; } // Recovery credential +} + +public enum CredentialType +{ + Passkey, + HardwareKey, + Password, + SocialGoogle, + SocialApple, + SocialMicrosoft, + EmailOtp, + Totp +} +``` + +### JWT Claims Structure + +```json +{ + "sub": "user-guid", + "email": "user@example.com", + "name": "John Doe", + "family_id": "family-guid", + "role": "admin", + "auth_method": "passkey", + "mfa_verified": true, + "aud": "luminous-api", + "iss": "https://auth.luminous.family", + "exp": 1234567890, + "iat": 1234567890 +} +``` + +### .NET API Authentication Setup + +```csharp +// Program.cs +builder.Services.AddAuthentication(options => +{ + options.DefaultAuthenticateScheme = JwtBearerDefaults.AuthenticationScheme; + options.DefaultChallengeScheme = JwtBearerDefaults.AuthenticationScheme; +}) +.AddJwtBearer(options => +{ + options.Authority = builder.Configuration["Auth:Authority"]; + options.Audience = builder.Configuration["Auth:Audience"]; + options.TokenValidationParameters = new TokenValidationParameters + { + ValidateIssuer = true, + ValidateAudience = true, + ValidateLifetime = true, + ValidateIssuerSigningKey = true, + ClockSkew = TimeSpan.FromMinutes(1) + }; +}); + +// Add FIDO2/WebAuthn support +builder.Services.AddFido2(options => +{ + options.ServerDomain = "luminous.family"; + options.ServerName = "Luminous"; + options.Origins = new HashSet { "https://app.luminous.family" }; +}); + +// Add social authentication +builder.Services.AddAuthentication() + .AddGoogle(options => + { + options.ClientId = builder.Configuration["Auth:Google:ClientId"]!; + options.ClientSecret = builder.Configuration["Auth:Google:ClientSecret"]!; + }) + .AddApple(options => + { + options.ClientId = builder.Configuration["Auth:Apple:ClientId"]!; + options.TeamId = builder.Configuration["Auth:Apple:TeamId"]!; + options.KeyId = builder.Configuration["Auth:Apple:KeyId"]!; + options.PrivateKey = builder.Configuration["Auth:Apple:PrivateKey"]!; + }) + .AddMicrosoftAccount(options => + { + options.ClientId = builder.Configuration["Auth:Microsoft:ClientId"]!; + options.ClientSecret = builder.Configuration["Auth:Microsoft:ClientSecret"]!; + }); +``` + +### WebAuthn Registration Flow + +```csharp +// AuthController.cs +[HttpPost("passkey/register/begin")] +public async Task> BeginPasskeyRegistration() +{ + var user = await GetCurrentUserAsync(); + + var options = _fido2.RequestNewCredential( + new Fido2User + { + Id = Encoding.UTF8.GetBytes(user.Id), + Name = user.Email, + DisplayName = user.DisplayName + }, + existingCredentials: await GetExistingCredentialsAsync(user.Id), + authenticatorSelection: new AuthenticatorSelection + { + ResidentKey = ResidentKeyRequirement.Preferred, + UserVerification = UserVerificationRequirement.Preferred + }, + attestationPreference: AttestationConveyancePreference.None + ); + + HttpContext.Session.SetString("fido2.attestationOptions", options.ToJson()); + return Ok(options); +} + +[HttpPost("passkey/register/complete")] +public async Task CompletePasskeyRegistration( + [FromBody] AuthenticatorAttestationRawResponse response) +{ + var options = CredentialCreateOptions.FromJson( + HttpContext.Session.GetString("fido2.attestationOptions")); + + var result = await _fido2.MakeNewCredentialAsync( + response, options, IsCredentialIdUniqueAsync); + + await SaveCredentialAsync(result.Result); + return Ok(new { success = true }); +} +``` + +### Angular Auth Service + +```typescript +// auth.service.ts +@Injectable({ providedIn: 'root' }) +export class AuthService { + private readonly http = inject(HttpClient); + private readonly currentUser = signal(null); + + // Passkey registration + async registerPasskey(): Promise { + const options = await firstValueFrom( + this.http.post( + '/api/auth/passkey/register/begin', {} + ) + ); + + const credential = await navigator.credentials.create({ + publicKey: this.decodeOptions(options) + }); + + await firstValueFrom( + this.http.post('/api/auth/passkey/register/complete', + this.encodeCredential(credential)) + ); + } + + // Passkey authentication + async signInWithPasskey(): Promise { + const options = await firstValueFrom( + this.http.post( + '/api/auth/passkey/authenticate/begin', {} + ) + ); + + const assertion = await navigator.credentials.get({ + publicKey: this.decodeOptions(options) + }); + + const response = await firstValueFrom( + this.http.post('/api/auth/passkey/authenticate/complete', + this.encodeAssertion(assertion)) + ); + + this.setTokens(response); + } + + // Email OTP + async requestEmailOtp(email: string): Promise { + await firstValueFrom( + this.http.post('/api/auth/email-otp/request', { email }) + ); + } + + async verifyEmailOtp(email: string, code: string): Promise { + const response = await firstValueFrom( + this.http.post('/api/auth/email-otp/verify', + { email, code }) + ); + this.setTokens(response); + } +} +``` + +### iOS Passkey Integration + +```swift +import AuthenticationServices + +class AuthService: NSObject, ASAuthorizationControllerDelegate { + + func signInWithPasskey() async throws { + let challenge = try await fetchChallenge() + + let provider = ASAuthorizationPlatformPublicKeyCredentialProvider( + relyingPartyIdentifier: "luminous.family" + ) + + let request = provider.createCredentialAssertionRequest( + challenge: challenge + ) + + let controller = ASAuthorizationController( + authorizationRequests: [request] + ) + controller.delegate = self + controller.performRequests() + } + + func registerPasskey() async throws { + let options = try await fetchRegistrationOptions() + + let provider = ASAuthorizationPlatformPublicKeyCredentialProvider( + relyingPartyIdentifier: "luminous.family" + ) + + let request = provider.createCredentialRegistrationRequest( + challenge: options.challenge, + name: options.userName, + userID: options.userId + ) + + let controller = ASAuthorizationController( + authorizationRequests: [request] + ) + controller.delegate = self + controller.performRequests() + } +} +``` + +### Device Linking Flow + +For wall displays without keyboards: + +1. **Display generates code** - 6-character alphanumeric, 15-minute expiry +2. **User authenticates on mobile** - Using passkey or other method +3. **User enters code** - Associates display with family +4. **Display receives device token** - Long-lived token for API access + +```csharp +// DeviceLinkingService.cs +public async Task GenerateDeviceCodeAsync(string deviceId) +{ + var code = GenerateSecureCode(); // 6 alphanumeric, case-insensitive + + var linkCode = new DeviceLinkCode + { + Code = code, + DeviceId = deviceId, + ExpiresAt = DateTime.UtcNow.AddMinutes(15), + CreatedAt = DateTime.UtcNow + }; + + await _cache.SetAsync($"device-link:{code.ToUpper()}", linkCode, + TimeSpan.FromMinutes(15)); + + return linkCode; +} + +public async Task LinkDeviceAsync( + string code, + string familyId, + string userId) +{ + var linkCode = await _cache.GetAsync( + $"device-link:{code.ToUpper()}"); + + if (linkCode == null || linkCode.ExpiresAt < DateTime.UtcNow) + throw new InvalidCodeException(); + + // Create device record + var device = new Device + { + Id = linkCode.DeviceId, + FamilyId = familyId, + LinkedByUserId = userId, + LinkedAt = DateTime.UtcNow + }; + + await _deviceRepository.UpsertAsync(device); + await _cache.RemoveAsync($"device-link:{code.ToUpper()}"); + + // Generate long-lived device token + return GenerateDeviceToken(device); +} +``` + +## Security Considerations + +1. **Credential Storage** + - WebAuthn public keys stored encrypted in CosmosDB + - Password hashes use Argon2id + - No plaintext credentials ever stored + +2. **Token Security** + - Short-lived access tokens (15 minutes) + - Refresh token rotation on each use + - Device binding for refresh tokens + - Secure storage (Keychain/Keystore on mobile) + +3. **Rate Limiting** + - Email OTP: 3 requests per 10 minutes per email + - Password attempts: 5 per 15 minutes, then lockout + - Registration: 3 per hour per IP + +4. **Recovery** + - Multiple credential types encouraged + - Recovery codes for account recovery + - Email verification for sensitive operations + +5. **Monitoring** + - Failed authentication alerts + - New device notifications + - Credential addition notifications + +## Migration Path + +For users transitioning from passwords: + +1. **Prompt passkey enrollment** after password sign-in +2. **Gradual migration** - don't force, encourage +3. **Keep password** as backup until passkey registered +4. **Celebrate** passwordless achievement in UI + +## Related Decisions + +- [ADR-003: Azure as Cloud Platform](./ADR-003-azure-cloud-platform.md) +- [ADR-006: Multi-Tenant Architecture](./ADR-006-multi-tenant-architecture.md) +- [ADR-001: .NET 10 as Backend Platform](./ADR-001-dotnet-backend.md) + +## References + +- [WebAuthn Specification](https://www.w3.org/TR/webauthn-2/) +- [FIDO2 .NET Library](https://github.com/passwordless-lib/fido2-net-lib) +- [Apple Passkeys Documentation](https://developer.apple.com/documentation/authenticationservices/public-private_key_authentication/supporting_passkeys) +- [Android Credential Manager](https://developer.android.com/training/sign-in/passkeys) +- [Passkeys.dev](https://passkeys.dev/) diff --git a/docs/adr/README.md b/docs/adr/README.md index 53c44ff..cf796ad 100644 --- a/docs/adr/README.md +++ b/docs/adr/README.md @@ -23,7 +23,7 @@ New ADRs should follow the template in [ADR-000-template.md](./ADR-000-template. | [ADR-007](./ADR-007-bicep-avm-iac.md) | Bicep with AVMs for IaC | Accepted | 2025-12-21 | | [ADR-008](./ADR-008-magic-import-approval.md) | Magic Import Requires Approval | Accepted | 2025-12-21 | | [ADR-009](./ADR-009-zero-distraction-principle.md) | Zero-Distraction Design Principle | Accepted | 2025-12-21 | -| [ADR-010](./ADR-010-azure-ad-b2c-identity.md) | Azure AD B2C for Identity | Accepted | 2025-12-21 | +| [ADR-010](./ADR-010-passwordless-authentication.md) | In-House Passwordless Authentication | Accepted | 2025-12-21 | ## Superseded ADRs (Historical Reference)