uto_manager/phased_development_plan.md

883 lines
41 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

# Phased Development Plan
## Flutter-Based Military Unit Task Organization (UTO) Manager
### U.S. Army 2026 Doctrine — Cross-Platform Enterprise System
---
## Overview
This document breaks the master development plan into five structured phases spanning **24 weeks**. Each phase defines concrete deliverables, technical tasks, acceptance criteria, and inter-phase dependencies. The system targets **Windows x64**, **Web (WASM/CanvasKit)**, and **Android** from a single Dart codebase.
---
## Architecture Summary
```text
[Presentation Layer: CustomPainter / InteractiveViewer / Responsive Shell]
│
▼
[Application State Layer: BLoC / Signals / Super Drag-and-Drop Pipeline]
│
▼
[Domain Layer: MTOE Doctrinal Rules Engine / Structural Validation]
│
▼
[Infrastructure Layer: Drift SQLite / IndexedDB / Protobuf Codecs]
```
---
## Phase 1: Architecture & Data Foundations ✅ COMPLETE (2026-08-07)
> **Status:** All Phase 1 deliverables completed and merged to `main`.
> 94/94 tests passing. `flutter analyze` — No issues found.
> Branch: `feature/phase-1-foundations` → merged 2026-08-07.
### Weeks 1 – 4
**Objective:** Establish the layered clean architecture codebase, define all core Dart domain entities, construct serialization schemas, and configure CI/CD pipelines for all three target platforms.
---
### 1.1 — Project Scaffolding & Clean Architecture Setup (Week 1)
**Tasks:**
- Initialize Flutter project with multi-platform targets: `windows`, `web`, `android`
- Establish clean architecture folder structure:
```text
lib/
├── domain/ # Entities, value objects, repository interfaces
├── application/ # BLoC / use cases / state management
├── infrastructure/ # Drift DB, IndexedDB adapters, Protobuf codecs
└── presentation/ # Widgets, painters, responsive shell
```
- Configure `flutter_lints`, `very_good_analysis`, and project-wide lint rules
- Set up `pubspec.yaml` with initial dependency declarations
- Initialize Git repository with branch protection rules (`main`, `develop`, `feature/*`)
**Deliverables:**
- Compilable Flutter project skeleton on all three targets
- Passing `flutter analyze` with zero lint violations
- Git repository with CI trigger configuration
**Acceptance Criteria:**
- `flutter run -d windows`, `flutter run -d chrome`, and `flutter run -d android` all launch a blank scaffold without errors
---
### 1.2 — Core Domain Entity Definitions (Weeks 1–2)
**Tasks:**
- Define Dart sealed classes and enums for all domain primitives:
- `Echelon` enum: `Brigade`, `Battalion`, `Company`, `Platoon`, `Section`, `Squad`, `Team`
- `DoctrinalBranch` enum: `Infantry`, `Medical`, `Fires`, `Signal`, `CyberEW`, `Aviation`, `Logistics`, `Engineer`
- `AuthorizedRank` enum: `E1`–`E9`, `W1`–`W5`, `O1`–`O10`
- `UnitNode` entity: `unitId (UUID)`, `echelon`, `branch`, `parentUnitId`, `name`, `isKeyLeader`
- `PositionSlot` entity: `slotId (UUID)`, `unitId`, `positionTitle`, `dutyMOS`, `authorizedRank`, `isKeyLeader`, `assignedPersonnelId?`
- `PersonnelRecord` entity: `soldierId (UUID)`, `name`, `primaryMOS`, `payGrade`, `qualifications[]`, `readinessState`
- `DutyMOS` value object with validation against standardized 3-character MOS dictionary
- Define position slot dictionaries for all functional branches:
- **Infantry & Maneuver:** Platoon Leader (11A), Platoon Sergeant (11B/E-7), Squad Leader (11B/E-6), Team Leader (11B/E-5), Automatic Rifleman (11B/E-4), Grenadier (11B/E-4), Rifleman (11B/E-3), sUAS Operator (15W/11B)
- **Medical (CMF 68):** Combat Medic Specialist (68W/E-4), Medical Evacuation NCO (68W/E-6), Treatment NCO (68W/E-6)
- **Field Artillery (CMF 13):** Joint Fire Support Specialist (13F/E-4–E-6), FAATDS Operator (13D/E-4)
- **Signal (CMF 25):** Network Comms Specialist (25H/E-4), Cyber/IT Specialist (25B/E-4)
- **Cyber/EW (CMF 17):** EW Specialist (17E/E-4–E-6)
- **Logistics (CMF 91/92):** Unit Supply Specialist (92Y/E-4), Automated Logistical Specialist (92A/E-4), Vehicle Mechanic (91B/91A/E-4)
- **Engineers (CMF 12):** Combat Engineer (12B/E-4–E-6)
- Implement `UnitRepository` and `PersonnelRepository` abstract interfaces
**Deliverables:**
- Complete domain entity library with unit tests
- MOS dictionary data file (JSON) covering all defined specialties
- Repository interface contracts
**Acceptance Criteria:**
- 100% unit test coverage on all domain entity validation logic
- MOS validation rejects invalid codes and accepts all defined specialties
---
### 1.3 — Database Schema & Infrastructure Layer (Weeks 2–3)
**Tasks:**
- Add `drift` package and configure for Windows/Android (SQLite) and Web (IndexedDB via `drift_web`)
- Define Drift table schemas:
| Table | Primary Key | Foreign Keys | Purpose |
|---|---|---|---|
| `units` | `unit_id (UUID)` | `parent_unit_id → units(unit_id)` | Organizational hierarchy |
| `position_slots` | `slot_id (UUID)` | `unit_id → units(unit_id)` | Authorized duty positions |
| `personnel` | `soldier_id (UUID)` | `slot_id → position_slots(slot_id)` | Soldier profiles & readiness |
| `templates` | `template_id (UUID)` | None | Serialized 2026 force templates |
- Implement Drift DAOs for CRUD operations on all four tables
- Configure database migrations framework (versioned migration files)
- Implement `JsonTemplateCodec` for serializing/deserializing unit tree structures
- Stub Protobuf schema definitions for future export pipeline (Phase 4)
**Deliverables:**
- Fully functional Drift database with all four tables
- DAO implementations with integration tests against in-memory SQLite
- JSON codec for unit tree serialization
**Acceptance Criteria:**
- Integration tests pass: create, read, update, delete operations on all tables
- Database migrations run cleanly from version 1 → current
- JSON round-trip serialization produces identical domain objects
---
### 1.4 — CI/CD Pipeline Configuration (Week 4)
**Tasks:**
- Configure GitHub Actions (or equivalent) with three build matrix targets:
- `flutter build windows`
- `flutter build web --wasm`
- `flutter build apk`
- Add automated test stages: `flutter test`, `flutter analyze`
- Configure artifact upload for build outputs (`.exe`, `web/`, `.apk`)
- Set up code coverage reporting (minimum 80% threshold gate)
**Deliverables:**
- Passing CI pipeline on all three platform targets
- Automated test and lint gates on pull requests
- Build artifact storage configured
**Acceptance Criteria:**
- All three platform builds succeed in CI without manual intervention
- Pull requests blocked on failing tests or lint violations
---
### Phase 1 Exit Criteria
- [ ] Clean architecture folder structure established and enforced by linting
- [ ] All domain entities defined with full unit test coverage
- [ ] Drift database operational on Windows, Web, and Android
- [ ] CI/CD pipeline passing on all three platform targets
- [ ] MOS dictionary data file complete for all functional branches
---
## Phase 2: Canvas Graphics Engine & Gesture Subsystem
### Weeks 5 – 9
**Objective:** Build the bespoke `CustomPainter` rendering layer, implement Quadtree spatial indexing, integrate matrix viewport transformations, and construct the cross-platform drag-and-drop state machine.
---
### 2.1 — CustomPainter Canvas Engine Foundation (Weeks 5–6)
**Tasks:**
- Implement `UtoCanvasPainter extends CustomPainter` with:
- `paint(Canvas canvas, Size size)` rendering loop
- `shouldRepaint()` optimized to dirty-flag comparison (not full equality)
- Node rendering via `canvas.drawRect()`, `canvas.drawPath()`, `canvas.drawParagraph()`
- Parent-child connection line rendering via `canvas.drawLine()` / `canvas.drawPath()`
- Wrap painter inside `InteractiveViewer` with:
- Configurable `minScale` / `maxScale` bounds
- `TransformationController` exposing the 4×4 viewport matrix `M`
- Implement viewport culling using inverse matrix transform:
```text
Viewport_visible = M⁻¹ × S
```
- Skip rendering nodes/lines outside the calculated visible bounding box
- Benchmark: maintain 60 FPS at 5,000+ nodes on Windows, 2,000+ on Web, 1,500+ on Android
- Implement `NodeRenderModel` — a flat list of pre-computed render primitives consumed by the painter (decoupled from domain entities)
**Deliverables:**
- Functional canvas painter rendering placeholder node boxes and connection lines
- Viewport culling active and measurable via Flutter DevTools frame timeline
- `NodeRenderModel` data structure defined
**Acceptance Criteria:**
- 60 FPS maintained with 500 placeholder nodes on all three platforms
- Viewport culling demonstrably skips off-screen nodes (verified via paint call counters)
---
### 2.2 — Reingold-Tilford Tree Layout Algorithm (Week 6)
**Tasks:**
- Implement the adapted Reingold-Tilford hierarchical tree layout algorithm in a dedicated `layout/` module:
- Calculate subtree widths bottom-up for all echelon levels
- Assign `(x, y)` canvas coordinates to each node based on subtree width and echelon depth
- Enforce horizontal separation across functional branches (Maneuver, Fires, Recon, Engineer, Sustainment)
- Enforce vertical alignment across echelons (Brigade → Battalion → Company → Platoon → Squad → Team → Individual)
- Offload layout computation to a **Dart Isolate** to prevent UI thread blocking
- Implement `LayoutResult` message passing between isolate and main thread
- Trigger layout recalculation on: node add, node remove, node re-parent, template load
**Deliverables:**
- Reingold-Tilford layout engine producing correct `(x, y)` coordinates for arbitrary unit trees
- Isolate-based async layout computation
- Layout recalculation triggered correctly on all structural change events
**Acceptance Criteria:**
- Layout algorithm correctly positions a full Brigade Combat Team (500+ nodes) without visual overlap
- Layout computation completes in < 100ms for a full BCT on Windows
- UI thread remains unblocked during layout recalculation (verified via DevTools)
---
### 2.3 — Quadtree Spatial Index (Week 7)
**Tasks:**
- Implement a `Quadtree<NodeId>` spatial index in pure Dart:
- Insert node bounding boxes on layout completion
- Query nearest-neighbor candidates within a configurable proximity radius
- Update index on node position changes (drag operations)
- Remove entries on node deletion
- Integrate Quadtree with the canvas hit-testing pipeline:
- Map screen-space tap/click coordinates through `M⁻¹` to canvas space
- Query Quadtree for the node at the transformed coordinate
- Return `null` for taps on empty canvas space
**Deliverables:**
- Pure Dart Quadtree implementation with unit tests
- Hit-testing pipeline correctly identifying nodes from screen-space coordinates
**Acceptance Criteria:**
- Quadtree hit-testing correctly identifies nodes in a 1,000-node tree with < 1ms query time
- No false positives or missed hits in unit tests covering edge cases (overlapping bounds, boundary nodes)
---
### 2.4 — Cross-Platform Drag-and-Drop State Machine (Weeks 7–9)
**Tasks:**
- Implement the drag-and-drop event state machine with four deterministic states:
1. **`Idle`** — No active drag; canvas responds to pan/zoom gestures
2. **`DragInitiated`** — Node selected; subordinate subtree isolated into overlay render layer; drag payload captured
3. **`DragInProgress`** — Dragged node moves across canvas; Quadtree proximity queries identify candidate parent nodes; doctrinal validation highlights valid (green) / invalid (red) drop targets
4. **`DropExecuted`** — Re-parenting command issued; relational keys updated in local store; Reingold-Tilford layout recalculated; painter notified via `shouldRepaint`
- Implement platform-adaptive gesture thresholds:
- **Desktop (mouse):** Drag initiates after 2-pixel movement threshold
- **Mobile/Tablet (touch):** Drag requires 200ms long-press + haptic feedback before node unlinks
- Integrate `super_drag_and_drop` package for cross-component drag payload integrity
- Implement `DragOverlayPainter` as a separate `RepaintBoundary` layer above the main canvas (prevents full canvas repaint during drag)
- Implement `AttachNodeCommand` and `DetachNodeCommand` as undoable command objects
**Deliverables:**
- Fully functional drag-and-drop re-parenting on Windows (mouse) and Android (touch)
- Visual feedback: green highlight for valid drop targets, red for invalid
- Undo/redo stack for node re-parenting operations
- Drag overlay rendered in isolated `RepaintBoundary` layer
**Acceptance Criteria:**
- Dragging a Rifle Squad to an Infantry Platoon shows green highlight and completes re-parenting
- Dragging a Fire Team directly to a Brigade HQ shows red invalid indicator
- Long-press threshold (200ms) correctly prevents accidental drags on touch devices
- Undo (Ctrl+Z / gesture) correctly reverses re-parenting operations
- Drag overlay does not trigger full canvas repaint (verified via DevTools)
---
### Phase 2 Exit Criteria
- [ ] CustomPainter canvas engine rendering nodes and connection lines with viewport culling
- [ ] Reingold-Tilford layout algorithm operational in background Dart Isolate
- [ ] Quadtree spatial index integrated with hit-testing pipeline
- [ ] Cross-platform drag-and-drop state machine functional on Windows and Android
- [ ] 60 FPS maintained at target node counts on all three platforms
---
## Phase 3: 2026 Doctrinal Templates & Symbology Engine ✅ COMPLETE (2026-08-09)
> **Status:** Phase 3 template library and import/export deliverables completed and merged to `main`.
> 191/191 tests passing. `flutter analyze` — No issues found.
> Branch: `feature/phase-3-templates-validation-export` → merged 2026-08-09.
>
> **Completed in this phase:**
>
> - `DoctrinalTemplates` — all five 2026 BCT templates (MBCT, SBCT, ABCT, CAB-Heavy, CAB-Light)
> - `TemplateInstantiator` — converts `UnitDefinition` trees to live domain objects
> - `MtoeValidationEngine` — 7 validation rules (V001–V007) covering MOS/rank mismatch, vacant key leaders, missing medic/FSO, hierarchy violations, manning below 70%
> - `UnitTreeCodec` — JSON encode/decode with schema versioning and full round-trip fidelity
> - `TemplateCubit` — extended with `instantiateDoctrinalTemplate`, `exportToJson`, `importFromJson`
> - `ValidationCubit` — wraps validation engine, exposes findings by severity
> - `DutyMos` — extended to accept 4-character aviation AOC codes (e.g., `153A`)
> - 54 new tests (191 total)
>
> **Deferred to Phase 4:** MIL-STD-2525D symbology engine, three-pane UI shell enhancements,
> validation findings as canvas node indicators, background Isolate offloading for validation.
### Weeks 10 – 14
**Objective:** Construct pre-configured 2026 doctrinal template libraries for all four BCT types and implement the hybrid MIL-STD-2525D symbology rendering pipeline.
---
### 3.1 — Doctrinal Template Library (Weeks 10–12)
**Tasks:**
- Implement JSON-driven template loader that parses externalized force structure definition files at runtime (no hardcoded unit structures in binary)
- Build complete 2026 doctrinal templates as JSON schema files:
**Mobile Brigade Combat Team (MBCT):**
- 3× Mobile Infantry Battalions (each with HHC, 3× Rifle Companies, Weapons Company)
- Rifle Company: 3× Rifle Platoons + Weapons Platoon
- Rifle Platoon: HQ (PL 11A/O-2, PSG 11B/E-7, RTO 25H/E-3, Medic 68W/E-4, FSO 13F/E-6) + 3× Rifle Squads + Weapons Section
- Rifle Squad (SaaS): SL (11B/E-6), 2× TL (11B/E-5), 2× Auto Rifleman XM250 (11B/E-4), 2× Grenadier XM7+M320 (11B/E-4), 1× Rifleman/sUAS Operator (15W/11B/E-4), 1× Rifleman (11B/E-3)
- 1× Cavalry Squadron (HHT + 3× Cav Troops + Anti-Tank Troop)
- 1× Field Artillery Battalion (2× 105mm batteries + 1× 155mm towed battery)
- Multi-Domain Effects Platoon (MDEP): EW (17E), C-sUAS, EMSO
- Hunter-Killer Platoon (HKP): sUAS + precision targeting assets
- Brigade Engineer Battalion
- Brigade Support Battalion
**Stryker Brigade Combat Team (SBCT):**
- 3× Stryker Infantry Battalions (HHC with organic medical 68W, signal 25H, sniper sections)
- Cavalry Reconnaissance Squadron (HHT + 3× Stryker Cav Troops + Anti-Tank Troop with 9× Stryker ATGM)
- Field Artillery Battalion (3× batteries, 24× M777A2 155mm towed howitzers)
- Brigade Engineer Battalion (signal 25H, MI, combat engineer 12B companies)
- Brigade Support Battalion (medical, distribution, maintenance)
**Armored Brigade Combat Team (ABCT):**
- 2× Armor-Heavy CABs: HHC + 2× Tank Companies (14× M1A2 SEPv3 each) + 1× Mech Infantry Company (14× M2A3/A4 Bradley)
- 1× Infantry-Heavy CAB
- HHC elements: Battalion Medical Platoon (68W), Mechanic Sections (91A/91B), Scout Platoons
- Armored Cavalry Squadron (HHT + 3× Armored Cav Troops + 1× Tank Troop with 14× M1A2)
- Field Artillery Battalion (3× batteries, 18× M109A7 Paladin 155mm SPH)
- Brigade Engineer Battalion (Sapper platoons 12B organic to each CAB)
**Combat Aviation Brigade (CAB) — Heavy:**
- Attack Aviation Battalion (24× AH-64E Apache, pilots 153A, crew chiefs 15T)
- Assault Helicopter Battalion (30× UH-60M Black Hawk + 12× CH-47F Chinook)
- Air Ambulance Company (15× HH-60M, 68W flight medics + 153A aviators)
- Aviation Support Battalion (intermediate maintenance 15B/15D/15G, supply 92Y)
**Combat Aviation Brigade (CAB) — Light:**
- Attack Reconnaissance Battalion (AH-64E + Troop F MQ-9A/sUAS)
- Assault Helicopter Battalion (UH-60M + CH-47F)
- Assault Helicopter Battalion (Medical)
- Aviation Support Battalion
- Implement `TemplateInstantiator` service that converts a JSON template into a full `UnitNode` tree and persists it to the Drift database in a single transaction
- Implement runtime template update mechanism: updated JSON files reload without binary recompilation
**Deliverables:**
- JSON template files for all five BCT configurations (MBCT, SBCT, ABCT, CAB-Heavy, CAB-Light)
- `TemplateInstantiator` service with integration tests
- Runtime template reload mechanism
**Acceptance Criteria:**
- Instantiating an MBCT template creates the correct number of units, position slots, and personnel records in the database
- Template instantiation completes in < 2 seconds for a full BCT
- Updated JSON template files reload correctly without app restart
---
### 3.2 — MIL-STD-2525D Symbology Engine (Weeks 12–14)
**Tasks:**
- Implement hybrid symbology pipeline:
**Web Target (milsymbol.js via JS Interop):**
- Integrate `milsymbol.js` via `dart:js_interop`
- Pass 15-digit Symbol Identification Codes (SIDC) to JS library
- Receive inline SVG path data and render via `canvas.drawPath()`
**Native Targets (Windows & Android — Pure Dart SVG Parser):**
- Bundle modular SVG component asset files for all required symbol elements:
- Affiliation frames (Friendly blue, Hostile red, Neutral green, Unknown yellow)
- Function icons: infantry cross-rifles, medical cross, signal lightning bolt, artillery cannon, engineer castle, aviation rotor, EW lightning, UAV silhouette, logistics wheel
- Echelon modifiers: Team (•), Squad (••), Section (•••), Platoon (|), Company (||), Battalion (|||), Brigade (X), Division (XX)
- Parse SVG paths using `path_drawing` package into immutable `Path` objects at app launch
- Cache parsed `Path` objects in thread-safe LRU cache indexed by SIDC
- Render tactical symbols by layering primitives:
```text
Tactical Symbol = Frame_Affiliation + Icon_Function + Modifier_Echelon + Text_Designator
```
- Implement `SidcResolver` that maps `(DoctrinalBranch, Echelon, Affiliation)` tuples to 15-digit SIDC codes
- Implement `TacticalSymbolPainter` that draws complete MIL-STD-2525D symbols on the GPU canvas
- Integrate symbol rendering into the main `UtoCanvasPainter` node rendering loop
**Deliverables:**
- Functional MIL-STD-2525D symbol rendering on all three platforms
- LRU symbol cache with configurable capacity
- `SidcResolver` mapping all defined branches and echelons to valid SIDC codes
- SVG asset bundle for all required symbol components
**Acceptance Criteria:**
- All defined branch/echelon combinations render correct MIL-STD-2525D symbols
- Symbol cache hit rate > 95% during normal canvas rendering (verified via cache metrics)
- Symbol rendering adds < 2ms overhead per frame on Android (verified via DevTools)
- Web target renders symbols via milsymbol.js without visible quality difference from native
---
### 3.3 — Three-Pane UI Shell (Weeks 13–14)
**Tasks:**
- Implement responsive three-pane workstation layout:
**Windows / Web Desktop:**
```text
┌─────────────────────────────────────────────────────────────────────┐
│ Header: Echelon Selector | Doctrinal Mode | Export Tools │
├──────────────────┬──────────────────────────────┬───────────────────┤
│ Left Panel: │ Central Canvas Workspace │ Right Panel: │
│ Template Palette │ (Pan / Zoom / Drag-and-Drop) │ Node Inspector │
├──────────────────┴──────────────────────────────┴───────────────────┤
│ Status Bar: Scale Factor | Active Node Count | MTOE Validation │
└─────────────────────────────────────────────────────────────────────┘
```
- Left panel: collapsible sidebar with template drag sources (MBCT, SBCT, ABCT, CAB, echelon blocks, individual duty slots)
- Right panel: context-sensitive inspector updating on node selection (unit ID, MOS, personnel search, weapon assignment, readiness status)
- Keyboard shortcuts: `Ctrl+Z` undo, `Ctrl+Y` redo, `Ctrl+F` search, `Ctrl+D` duplicate subtree, `Ctrl+S` save
- Mouse-wheel pan/zoom, multi-node box selection, right-click context menus
**Android Tablet/Mobile:**
- Replace left panel with navigation drawer (slide-out)
- Replace right panel with bottom sheet inspector (slide-up)
- Minimum touch target size: 48×48 dp
- Tap-and-hold radial menus replace right-click context menus
- Haptic feedback on drag initiation
**Deliverables:**
- Responsive three-pane layout functional on Windows and Web
- Adaptive mobile layout with drawer and bottom sheet on Android
- All keyboard shortcuts implemented on desktop
- Touch-optimized gesture targets on Android
**Acceptance Criteria:**
- Three-pane layout renders correctly at 1920×1080 and 2560×1440 on Windows
- Mobile layout correctly switches to drawer/bottom-sheet at Android tablet and phone breakpoints
- All keyboard shortcuts function correctly on Windows and Web
- Touch targets meet 48×48 dp minimum on Android
---
### Phase 3 Exit Criteria
- [x] All five BCT doctrinal templates (MBCT, SBCT, ABCT, CAB-Heavy, CAB-Light) instantiable from JSON
- [ ] MIL-STD-2525D symbology rendering on all three platforms _(deferred to Phase 4)_
- [x] Three-pane UI shell functional on desktop _(basic shell from Phase 2; full enhancements deferred)_
- [x] Runtime template reload mechanism operational (JSON codec + `importFromJson`)
---
## Phase 4: Persistence, Validation Rules, & Export Engine ✅ COMPLETE (2026-08-09)
> **Status:** Phase 4 reporting & analytics deliverables completed and merged to `main`.
> 263/263 tests passing. `flutter analyze` — No issues found.
> Branch: `feature/phase-4-reporting-analytics` → merged 2026-08-09.
>
> **Completed in this phase:**
>
> - `CommandEventStore` — append-only event log with `CommandEvent`, `CommandEventType`, `CommandPayloads`
> - `DeltaSynchronizer` — offline-first sync helper with `syncIfOnline()` and `isOnline` control
> - `IsolateValidationRunner` — background-isolate wrapper for `MtoeValidationEngine` with `ValidationResponse`
> - `ProtobufCodec` — binary encode/decode with 12-byte UTOB header + zlib-compressed JSON payload
> - `PdfChartExporter` — pure-Dart PDF 1.4 org-chart generator (letter/A4/tabloid, UNCLASSIFIED banner)
> - `ValidationCubit` — extended with `startIsolate()`, `disposeIsolate()`, `validateAsync()`
> - `HomeScreen` — validation node indicators, PDF/binary export actions, findings inspector panel
> - 72 new tests (263 total)
>
> **Deferred to Phase 5:** Real network transport for `DeltaSynchronizer`, true Protobuf schema,
> single-transaction template instantiation, MIL-STD-2525D symbology engine.
### Weeks 15 – 19
**Objective:** Integrate the full Drift transactional database, construct the real-time MTOE domain validation engine, implement offline-first delta synchronization, and develop data export modules.
---
### 4.1 — Full Persistence Integration & Offline-First Architecture (Weeks 15–16)
**Tasks:**
- Complete Drift repository implementations for all four tables (units, position_slots, personnel, templates)
- Implement reactive streams: Drift `watchAll()` queries feeding BLoC state streams
- Implement `CommandEventStore` for offline-first operation:
- All structural changes (node re-parent, personnel assign, slot modify) write as atomic `CommandEvent` records
- Events queue locally when network is unavailable
- `DeltaSynchronizer` transmits queued events on connectivity restoration
- Event types: `AttachNodeEvent`, `DetachNodeEvent`, `AssignPersonnelEvent`, `UnassignPersonnelEvent`, `ModifySlotEvent`
- Implement conflict resolution strategy for concurrent edits (last-write-wins with timestamp, flagging conflicts for manual review)
- Configure `drift_web` for IndexedDB persistence on Web target
- Implement database backup/restore functionality (export to encrypted JSON archive)
**Deliverables:**
- Full reactive persistence layer with Drift streams feeding UI state
- `CommandEventStore` with offline queue and delta synchronizer
- Conflict resolution mechanism
- Database backup/restore functionality
**Acceptance Criteria:**
- Application continues full operation with zero network connectivity (offline-first verified)
- Delta synchronizer transmits only changed events (not full model) on reconnection
- Reactive streams update UI within 16ms of database write (one frame budget)
- Backup/restore round-trip produces identical database state
---
### 4.2 — Real-Time MTOE Domain Validation Engine (Weeks 16–18)
**Tasks:**
- Implement `MtoeValidationEngine` running in a background Dart Isolate:
- **MOS Mismatch Detection:** Flag when assigned soldier's primary MOS ≠ slot's authorized duty MOS
- **Rank Mismatch Detection:** Flag when assigned soldier's pay grade ≠ slot's authorized rank
- **Vacant Leadership Slot Detection:** Flag unfilled Key Leader positions (Squad Leader, Platoon Leader, Platoon Sergeant, Company Commander, etc.)
- **Missing Critical Support Role Detection:** Flag maneuver platoons lacking attached 68W Combat Medic or 13F Fire Support Specialist
- **Structural Hierarchy Violation Detection:** Flag invalid parent-child echelon relationships (e.g., Squad directly under Brigade)
- **Doctrinal Strength Deviation:** Flag units with manning levels below 70% of authorized strength
- Implement validation result model: `ValidationFinding(severity, unitId, slotId, findingCode, description)`
- Severity levels: `Critical` (red), `Warning` (amber), `Advisory` (blue)
- Integrate validation findings into:
- Status bar (aggregate finding counts by severity)
- Node visual indicators (colored border/badge on nodes with findings)
- Right panel inspector (detailed finding list for selected node)
- Implement drag-and-drop pre-validation: evaluate proposed re-parenting before drop execution
**Deliverables:**
- `MtoeValidationEngine` with all defined validation rules
- Real-time validation findings displayed in status bar, node indicators, and inspector panel
- Pre-validation during drag-and-drop operations
- Validation engine running in background Isolate (no UI thread impact)
**Acceptance Criteria:**
- All defined validation rules correctly identify violations in test unit trees
- Validation engine processes a full BCT (500+ nodes) in < 500ms in background Isolate
- Node visual indicators update within one frame of validation completion
- Dragging a Fire Team to Brigade HQ shows red pre-validation indicator before drop
---
### 4.3 — Data Export Engine (Weeks 18–19)
**Tasks:**
- Implement **JSON Export:** Full unit tree serialization to structured JSON (human-readable, importable)
- Implement **Protobuf Export:** Binary-encoded unit tree using pre-defined `.proto` schema (compact, network-efficient)
- Implement **Vector PDF Chart Export:**
- Render the full organizational chart to a PDF document using `pdf` package
- Preserve MIL-STD-2525D symbols as vector paths in PDF output
- Support configurable page sizes (Letter, A4, Tabloid/A3 for large formations)
- Include cover page with unit designation, date, classification marking placeholder
- Implement **Import Pipeline:** JSON import with validation against current doctrinal rules
- Implement export UI: export dialog with format selection, scope selection (full tree / selected subtree), and file save dialog
**Deliverables:**
- JSON, Protobuf, and vector PDF export modules
- JSON import pipeline with validation
- Export UI dialog integrated into application header
**Acceptance Criteria:**
- JSON export/import round-trip produces identical unit tree (verified by deep equality test)
- Protobuf export file size < 50% of equivalent JSON for a full BCT
- PDF export renders all MIL-STD-2525D symbols as vector paths (not rasterized)
- PDF export completes in < 10 seconds for a full BCT on Windows
---
### Phase 4 Exit Criteria
- [ ] Full reactive Drift persistence layer operational on all three platforms
- [ ] Offline-first operation verified with delta synchronization
- [ ] MTOE validation engine detecting all defined violation types in real time
- [ ] JSON, Protobuf, and vector PDF export modules functional
- [ ] JSON import pipeline with doctrinal validation
---
## Phase 5: Platform Optimization, Profiling, & Hardening
### Weeks 20 – 24
**Objective:** Execute comprehensive performance profiling, apply rendering optimizations, harden the application for production deployment, and assemble release packages for all three platforms.
---
### 5.1 — Performance Profiling & Rendering Optimization (Weeks 20–21)
**Tasks:**
- Profile all three platform targets using Flutter DevTools:
- Frame timeline analysis: identify jank frames (> 16ms) and their root causes
- Memory profiler: identify heap growth patterns and object retention issues
- CPU profiler: identify hot paths in layout, painting, and validation logic
- Apply `RepaintBoundary` isolation strategy:
- Static layer: grid lines, parent-child connection lines (repaints only on zoom/pan)
- Dynamic layer: active drag preview overlay (repaints only during drag)
- Node layer: individual unit nodes (repaints only on state change)
- Optimize Reingold-Tilford layout: cache subtree width calculations, skip unchanged subtrees
- Optimize Quadtree: implement bulk-insert for template instantiation, lazy rebuild on large structural changes
- Optimize symbol cache: tune LRU capacity per platform (Windows: 2,000 entries, Android: 500 entries, Web: 1,000 entries)
- Implement progressive loading for large templates: render visible viewport nodes first, load off-screen nodes asynchronously
**Performance Targets:**
| Platform | Node Count | Target FPS | Max Frame Time |
|---|---|---|---|
| Windows x64 | 5,000+ | 60 FPS | 16ms |
| Web (WASM) | 2,000+ | 60 FPS | 16ms |
| Android | 1,500+ | 60 FPS | 16ms |
**Deliverables:**
- DevTools profiling reports for all three platforms
- Applied `RepaintBoundary` isolation across all canvas layers
- Performance benchmark suite (automated frame rate tests at target node counts)
**Acceptance Criteria:**
- All three platforms meet target FPS at specified node counts (verified by automated benchmarks)
- No memory leaks detected over 30-minute continuous operation sessions
- Dart Isolate offloading verified: main thread frame time < 8ms during layout recalculation
---
### 5.2 — Heavy Computation Isolate Offloading (Week 21)
**Tasks:**
- Audit all computationally intensive operations and confirm Isolate offloading:
- Reingold-Tilford layout computation → background Isolate ✓ (Phase 2)
- MTOE validation engine → background Isolate ✓ (Phase 4)
- JSON/Protobuf serialization for large exports → background Isolate
- PDF rendering for large formations → background Isolate
- Implement `IsolatePool` for managing multiple concurrent background computations
- Implement progress reporting from Isolates to UI (progress indicators for long operations)
- Implement Isolate cancellation for superseded layout requests (cancel in-flight layout when new structural change arrives)
**Deliverables:**
- All heavy computations confirmed offloaded to background Isolates
- `IsolatePool` managing concurrent background tasks
- Progress indicators for long-running operations (export, large template instantiation)
**Acceptance Criteria:**
- Main UI thread frame time remains < 8ms during any background computation
- Isolate cancellation correctly aborts superseded layout requests
- Progress indicators display for all operations > 500ms
---
### 5.3 — Platform-Specific Hardening (Weeks 22–23)
**Tasks:**
**Windows x64:**
- Implement multi-window support (open multiple UTO workspaces simultaneously)
- Implement high-DPI scaling (verify at 100%, 125%, 150%, 200% display scaling)
- Implement system tray integration and window state persistence (size, position, panel widths)
- Configure `.msi` installer with proper registry entries and uninstall support
- Implement Windows file association for `.uto` project files
**Web (WASM/CanvasKit):**
- Optimize WASM bundle size (tree-shaking, deferred loading of template assets)
- Implement IndexedDB storage quota management (warn user when approaching browser storage limits)
- Implement memory-bounded canvas surface allocation (prevent OOM on low-memory browser tabs)
- Configure service worker for offline PWA capability
- Test across Chrome, Edge, and Firefox
**Android:**
- Implement battery profiling: reduce background Isolate activity when battery < 20%
- Verify touch target sizes meet 48×48 dp minimum across all interactive elements
- Implement Android back-gesture handling for panel navigation
- Configure `.aab` release build with ProGuard/R8 optimization
- Test on Android 12, 13, and 14 across tablet and phone form factors
**Deliverables:**
- Windows `.msi` installer with file association
- Web PWA with offline capability and storage quota management
- Android `.aab` release build optimized for tablet and phone
**Acceptance Criteria:**
- Windows installer installs/uninstalls cleanly; `.uto` file association opens correct workspace
- Web app functions offline after initial load (PWA service worker active)
- Android app passes battery profiling: no excessive background drain
- All touch targets verified ≥ 48×48 dp on Android
---
### 5.4 — Security, Accessibility, & Final QA (Weeks 23–24)
**Tasks:**
- Implement classification marking placeholder system (UNCLASSIFIED / FOR OFFICIAL USE ONLY banners)
- Implement data-at-rest encryption for local Drift database (SQLCipher integration)
- Conduct accessibility audit:
- Screen reader compatibility (Windows Narrator, Android TalkBack)
- Minimum contrast ratios for all text elements (WCAG 2.1 AA)
- Keyboard-only navigation completeness on Windows/Web
- Execute end-to-end test suite covering all critical user workflows:
- Template instantiation → drag-and-drop re-parenting → personnel assignment → export
- Offline operation → reconnection → delta synchronization
- Validation finding detection → resolution → re-validation
- Conduct load testing: instantiate 10 simultaneous full BCT templates, verify stability
**Deliverables:**
- SQLCipher database encryption integrated
- Accessibility audit report with all critical issues resolved
- End-to-end test suite passing on all three platforms
- Load test results documented
**Acceptance Criteria:**
- Database encryption verified: raw SQLite file is unreadable without key
- All WCAG 2.1 AA contrast requirements met
- End-to-end test suite passes with 100% success rate on all three platforms
- Load test: 10 simultaneous BCT templates stable for 10 minutes without crash or memory leak
---
### 5.5 — Release Package Assembly (Week 24)
**Tasks:**
- Assemble Windows release: signed `.msi` installer + portable `.exe` archive
- Assemble Web release: optimized WASM bundle + static hosting configuration
- Assemble Android release: signed `.aab` for Google Play + sideload `.apk`
- Generate release notes documenting all features, known limitations, and upgrade instructions
- Tag release in version control (`v1.0.0`)
- Archive build artifacts with SHA-256 checksums
**Deliverables:**
- Signed Windows `.msi` installer
- Optimized Web WASM bundle
- Signed Android `.aab` and `.apk`
- Release notes and SHA-256 checksums
**Acceptance Criteria:**
- All three release packages install and launch correctly on clean target systems
- SHA-256 checksums verified for all artifacts
- Release tagged in version control
---
### Phase 5 Exit Criteria
- [ ] All three platforms meet FPS targets at specified node counts
- [ ] All heavy computations confirmed offloaded to background Isolates
- [ ] Platform-specific hardening complete (Windows multi-window, Web PWA, Android battery profiling)
- [ ] Database encryption integrated
- [ ] End-to-end test suite passing on all three platforms
- [ ] Release packages assembled and signed for all three platforms
---
## Inter-Phase Dependency Map
```text
Phase 1 (Architecture & Data)
│
├──► Phase 2 (Canvas Engine) [Requires: Domain entities, DB schema]
│ │
│ └──► Phase 3 (Templates & Symbology) [Requires: Canvas engine, Layout algorithm]
│ │
│ └──► Phase 4 (Persistence & Validation) [Requires: Templates, Full DB]
│ │
│ └──► Phase 5 (Optimization & Release) [Requires: All prior phases]
│
└──► Phase 3 (partial: JSON template schema) [Requires: Domain entities only]
```
---
## Technology Stack Summary
| Layer | Technology | Rationale |
|---|---|---|
| UI Framework | Flutter (Dart) | Single codebase for Windows, Web, Android |
| Rendering Engine | CustomPainter + InteractiveViewer | GPU-direct drawing; bypasses widget tree overhead |
| State Management | BLoC + Signals | Reactive atomic state; prevents full widget tree rebuilds |
| Drag-and-Drop | super_drag_and_drop | Cross-platform payload integrity |
| Local Database | Drift (SQLite / IndexedDB) | Type-safe reactive ORM; offline-first |
| Encryption | SQLCipher | Data-at-rest protection |
| Symbology (Web) | milsymbol.js via dart:js_interop | Full MIL-STD-2525D compliance on Web |
| Symbology (Native) | path_drawing + SVG assets + LRU cache | Zero external runtime dependencies on Windows/Android |
| Background Compute | Dart Isolates | Offload layout, validation, export from UI thread |
| Serialization | JSON + Protobuf | Human-readable + compact binary export formats |
| PDF Export | pdf package | Vector-quality organizational chart output |
| CI/CD | GitHub Actions | Automated multi-platform build and test matrix |
---
## Risk Register
| Risk | Probability | Impact | Mitigation |
|---|---|---|---|
| WASM performance below 2,000-node target | Medium | High | Early benchmark in Phase 2; apply aggressive culling and canvas surface limits |
| milsymbol.js JS Interop latency on Web | Low | Medium | Cache SVG output; pre-render symbols at app load |
| Drift IndexedDB storage quota exceeded on Web | Medium | Medium | Implement quota monitoring and user warnings in Phase 5 |
| Reingold-Tilford layout time exceeds 100ms for large BCTs | Low | Medium | Incremental layout: only recalculate affected subtrees |
| Android touch gesture ambiguity (pan vs. drag) | Medium | High | 200ms long-press threshold + haptic feedback (Phase 2); user testing in Phase 5 |
| Army doctrinal template changes post-release | High | Low | Externalized JSON templates; runtime reload without binary update |
| SQLCipher key management complexity | Low | High | Use platform keychain (Windows Credential Manager, Android Keystore) for key storage |
---
Document Version: 1.0 | Generated: 2026-08-07 | Based on: master_development_plan.md