Compare commits

...

2 Commits

14 changed files with 2279 additions and 53 deletions

View File

@ -6,6 +6,17 @@
- **Context**: Design a multi-platform (Windows, Linux, Android, Headless) productivity engine for time, project, and note management without centralized servers.
- **Decision**: Adopted Rust core with SQLCipher local storage, Automerge CRDT delta sync over libp2p, and Flutter presentation layer bound via C-FFI.
## [2026-08-09] - ADL-002: chronogrid_crypto Crate – Argon2id KDF & OS Keychain
- **Status**: Accepted
- **Context**: Task 1.2 required implementing the `chronogrid_crypto` crate with Argon2id master-key derivation and OS-native keychain bindings per `docs/ARCHITECTURE/02-security-and-crypto.md`.
- **Decision**:
- Argon2id parameters pinned: 64 MiB memory, 3 iterations, 4 threads, 16-byte random salt, 32-byte output.
- `DerivedKey` struct implements `Zeroize + Drop` to scrub sensitive memory on scope exit.
- OS keychain abstracted via `keyring` crate v3 (Windows Credential Manager / DPAPI, Linux SecretService / libsecret). Android keychain is excluded (`cfg(not(target_os = "android"))`) and will be handled by Flutter KeyStore bridge in Task 1.5.
- Raw key material is Base64-encoded before credential-store insertion for UTF-8 backend compatibility.
- Inline Base64 encode/decode helpers avoid adding an external Base64 dependency.
## [2026-08-19] - ADL-003: chronogrid_core Crate – SQLCipher 4.x Database Initializer
- **Status**: Accepted
@ -50,13 +61,19 @@
- 25 unit tests (all passing): engine lifecycle, DB CRDT doc persistence, task/note CRDT create/read/mutate/merge round-trips, crypto derivation, stateless read validation, no-engine error paths.
- Full ADR at `docs/ARCHITECTURE/ADR/0005-ffi-bridge-flutter-rust-bridge.md`.
## [2026-08-09] - ADL-002: chronogrid_crypto Crate – Argon2id KDF & OS Keychain
## [2026-08-22] - ADL-006: Architecture Review Board Assessment & Master Development Plan v2
- **Status**: Accepted
- **Context**: Task 1.2 required implementing the `chronogrid_crypto` crate with Argon2id master-key derivation and OS-native keychain bindings per `docs/ARCHITECTURE/02-security-and-crypto.md`.
- **Context**: A comprehensive senior architecture review was conducted covering all crates, documentation, task structure, and the development plan. Phase 1 is complete and production-quality. Phases 2–5 require a structured execution plan to enable automated agent development.
- **Decision**:
- Argon2id parameters pinned: 64 MiB memory, 3 iterations, 4 threads, 16-byte random salt, 32-byte output.
- `DerivedKey` struct implements `Zeroize + Drop` to scrub sensitive memory on scope exit.
- OS keychain abstracted via `keyring` crate v3 (Windows Credential Manager / DPAPI, Linux SecretService / libsecret). Android keychain is excluded (`cfg(not(target_os = "android"))`) and will be handled by Flutter KeyStore bridge in Task 1.5.
- Raw key material is Base64-encoded before credential-store insertion for UTF-8 backend compatibility.
- Inline Base64 encode/decode helpers avoid adding an external Base64 dependency.
- Created `docs/ARCHITECTURE/05-architecture-review-assessment.md` — full ARB assessment with gap analysis, risk register, and recommendations.
- Created `docs/ARCHITECTURE/06-master-development-plan.md` — authoritative execution plan superseding OSAD Section 8, with 37 tasks across Phases 2–5, quality gates, and acceptance criteria traceability.
- Created `docs/TASKS/phase_2_networking_and_schema.md` — 9 tasks for libp2p networking, schema extension, daemon scaffold, and verification pipeline hardening.
- Created `docs/TASKS/phase_3_flutter_ui_shell.md` — 10 tasks for Flutter BLoC architecture, all 4 primary views, FRB codegen, and build scripts.
- Created `docs/TASKS/phase_4_ai_and_automation.md` — 9 tasks for NLP engine, IMAP ingestion, file watchers, CalDAV server, and automation rules engine.
- Created `docs/TASKS/phase_5_headless_and_release.md` — 9 tasks for daemon completion, integration testing, performance testing, and release packaging.
- Fixed documentation typos in `docs/UI_UX/02-calendar-timeblocking.md` and `docs/UI_UX/03-kanban-gantt-views.md`.
- Expanded `docs/WORKFLOWS/01-master-user-story.md` from a stub to a substantive workflow reference document.
- Identified critical gaps: 6 missing schema tables, FFI type mismatch (`due_date: i64` vs `u64`), incomplete verification script, missing build scripts, unscaffolded daemon crate.
- Confirmed all Phase 1 architectural decisions as correct — no reversals required.
- Next task for automated execution: **Task 2.1 — Extend Schema with Missing Entities**.

View File

@ -63,13 +63,13 @@
},
{
"name": "flutter",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/packages/flutter",
"rootUri": "file:///D:/develop/flutter/packages/flutter",
"packageUri": "lib/",
"languageVersion": "3.11"
},
{
"name": "flutter_driver",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/packages/flutter_driver",
"rootUri": "file:///D:/develop/flutter/packages/flutter_driver",
"packageUri": "lib/",
"languageVersion": "3.11"
},
@ -87,19 +87,19 @@
},
{
"name": "flutter_test",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/packages/flutter_test",
"rootUri": "file:///D:/develop/flutter/packages/flutter_test",
"packageUri": "lib/",
"languageVersion": "3.11"
},
{
"name": "fuchsia_remote_debug_protocol",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/packages/fuchsia_remote_debug_protocol",
"rootUri": "file:///D:/develop/flutter/packages/fuchsia_remote_debug_protocol",
"packageUri": "lib/",
"languageVersion": "3.11"
},
{
"name": "integration_test",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/packages/integration_test",
"rootUri": "file:///D:/develop/flutter/packages/integration_test",
"packageUri": "lib/",
"languageVersion": "3.11"
},
@ -165,7 +165,7 @@
},
{
"name": "sky_engine",
"rootUri": "file:///C:/Users/mtkel/AppData/Local/flutter/bin/cache/pkg/sky_engine",
"rootUri": "file:///D:/develop/flutter/bin/cache/pkg/sky_engine",
"packageUri": "lib/",
"languageVersion": "3.11"
},
@ -244,7 +244,7 @@
],
"generator": "pub",
"generatorVersion": "3.13.0",
"flutterRoot": "file:///C:/Users/mtkel/AppData/Local/flutter",
"flutterRoot": "file:///D:/develop/flutter",
"flutterVersion": "3.47.0",
"pubCache": "file:///C:/Users/mtkel/AppData/Local/Pub/Cache"
}

View File

@ -1,4 +1,417 @@
# Operational and System Architecture Document (OSAD)
*Status: Active Specification*
**Project Name:** ChronoGrid P2P (Distributed Time, Note & Project Management Engine)
**Repository Host:** `git.kellsupport.com`
**Target Platforms:** Windows, Linux, Android, Headless Peer Server
**Core Framework:** Flutter (Dart FFI) + Rust Native Core Core Engine
**Architecture Model:** Local-First, Serverless Peer-to-Peer (P2P), CRDT-Driven Synchronization
**Status:** Active Specification
Refer to system blueprints for Flutter presentation layer, Rust Core engine (`chronogrid-core`), and P2P Mesh Network (`chronogrid-net`).
---
## 1. System Overview & Architectural Vision
ChronoGrid P2P is a distributed, local-first productivity operating system. It provides comprehensive project planning, time blocking, and note management across mobile, desktop, and headless server nodes without relying on centralized cloud providers, SaaS databases, or multi-tenant servers.
Data sovereignty, cryptographic security, and offline execution form the foundation of the system architecture. Every instance—whether running on Windows, Linux, Android, or as a background service—operates as an autonomous node holding an encrypted, fully functional local database state. Synchronizations between nodes occur directly over local network discovery (MDNS) and WAN P2P mesh protocols (libp2p / Iroh) using Conflict-free Replicated Data Types (CRDTs) to guarantee eventual state convergence.
```
+-----------------------------------------------------------------------------------+
| FLUTTER PRESENTATION LAYER |
| (Windows Win32 FFI / Linux GTK Desktop / Android Jetpack Engine) |
+-----------------------------------------------------------------------------------+
│
Dart FFI / C-ABI Binding Bridge
│
+-----------------------------------------------------------------------------------+
| RUST NATIVE P2P ENGINE (Core Core) |
| +------------------------+ +------------------------+ +---------------------+ |
| | Local Store Engine | | CRDT Sync Engine | | Automation Engine | |
| | (SQLite + SQLCipher) | | (Automerge / Delta-LWW)| | (Embedded Rust) | |
| +------------------------+ +------------------------+ +---------------------+ |
| +------------------------------------------------------------------------------+ |
| | P2P Mesh Networking Layer | |
| | (libp2p / QUIC / Noise XK Cipher Handshake / NAT Hole-Punching / Gossipsub) | |
| +------------------------------------------------------------------------------+ |
+-----------------------------------------------------------------------------------+
```
---
## 2. High-Level System Architecture & Component Breakdown
The architecture isolates the UI from data orchestration and networking using a modular, layered Rust core wrapped by a Flutter presentation layer.
```
+--------------------------------------------+
| Flutter GUI (Windows/Linux/Android) |
+--------------------------------------------+
│
(Dart Stream / FFI Bridge)
│
+--------------------------------------------+
| Local App State Store |
+--------------------------------------------+
│ │ │
▼ ▼ ▼
+------------------+ +-------------------+ +-------------------+
| SQLite Storage | | CRDT State Engine| | Local AI Workflow |
| (SQLCipher) | | (Automerge) | | (Ollama / ONNX) |
+------------------+ +-------------------+ +-------------------+
│ │ │
+------------------┼---------------------+
│
▼
+--------------------------------------------+
| Libp2p Mesh Network |
| (mDNS / Hole Punching / Noise Protocol) |
+--------------------------------------------+
│ │
▼ ▼
+------------------------+ +------------------------+
| Peer Node (Mobile/Desk)| | Headless Peer Server |
+------------------------+ +------------------------+
```
### Layer 1: Flutter Presentation Layer (UI Shell)
* **Framework:** Flutter 3.x configured with C-FFI direct memory communication.
* **Platforms:** Windows (Win32), Linux (GTK3), Android (NDK/ARM64).
* **State Management:** BLoC / Reactive Streams listening directly to native Rust event emitters.
* **UI Features:**
* Interactive Kanban boards, interactive Gantt timelines, and multi-column list views.
* Eisenhower Priority Matrix view (Urgent vs. Important quadrant auto-sorting).
* Integrated Calendar Time-Blocking Grid with drag-and-drop task duration sizing.
* Markdown Document & Quick Jot Editor with bi-directional task linking.
### Layer 2: Embedded Rust Core Engine (`chronogrid-core`)
The entire storage, cryptographic, sync, and networking logic is compiled into a native dynamic library (`.dll` on Windows, `.so` on Linux, `.so` on Android) and cross-compiled for headless binary deployments.
* **SQLCipher Engine:** Manages local persistence with AES-256-GCM database-level encryption.
* **CRDT Merger Engine:** Reconciles offline delta updates across devices without central coordination.
* **Automation & Rules Engine:** Evaluates local incoming jots, emails, and triggers using an embedded lightweight evaluation engine.
* **Local AI Processor:** Executes local model inferences (via embedded ONNX runtime or Ollama HTTP bindings) to extract metadata, assign scores, and categorize tasks without external API calls.
### Layer 3: P2P Network Mesh (`chronogrid-net`)
* **Transport:** QUIC over UDP and TCP with Noise Protocol (XK pattern) transport encryption.
* **Discovery:** Local mDNS for zero-configuration local area network (LAN) peer discovery; Kademlia DHT and NAT Traversal (STUN/TURN/ICE hole punching) for Wide Area Network (WAN) peer discovery.
* **Gossipsub Protocol:** Efficient message propagation for real-time state changes and sync notifications across personal node clusters.
---
## 3. Data Storage, Security, & Cryptography Model
### Zero-Trust Local Storage
Data on disk is never stored in unencrypted plain text.
1. **Master Key Generation:** During initial app setup, a 256-bit Master Key is derived from user credentials using Argon2id (Memory: 64MB, Iterations: 3, Parallelism: 4).
2. **Key Storage:**
* **Windows:** Windows Data Protection API (DPAPI) / Credential Manager.
* **Linux:** Secret Service API (Freedesktop SecretService via Secret Storage).
* **Android:** Android KeyStore System with hardware-backed Trusted Execution Environment (TEE).
* **Headless Server:** Systemd credential store or encrypted keyfile payload.
3. **Database Encryption:** SQLite encrypted end-to-end via SQLCipher 4.x using AES-256-CBC with HMAC-SHA512 per-page authentication.
### Peer-to-Peer Encryption & Access Control
Syncing between personal nodes utilizes end-to-end asymmetric encryption:
* **Node Identity:** Every node generates an Ed25519 keypair upon initialization. The public key acts as the `NodeId`.
* **Swarm Key & Cluster Pairing:** Personal devices join a private mesh cluster using a shared, user-generated 256-bit **Swarm Key**. Unauthenticated nodes cannot decode network signals or handshake packets.
* **Wire Protocol Security:** Network channels use Ephemeral Diffie-Hellman (X25519) key exchange combined with ChaCha20-Poly1305 AEAD payload ciphering.
---
## 4. Conflict-Free Replicated Synchronization Engine (CRDT)
To eliminate central server databases while supporting multi-device concurrent offline edits, ChronoGrid uses state-based and delta-based CRDT topologies.
```
[ Device A (Offline) ] [ Device B (Offline) ]
Creates Task T1 (v1.0) Edits Note N1 (v1.1)
│ │
▼ ▼
[ Local CRDT Append ] [ Local CRDT Append ]
│ │
└─────────────── Direct P2P ─────────────┘
(Reconnection Sync)
│
▼
[ CRDT Deterministic Merge ]
State Converges Automatically
```
### Data Modeling & Conflict Resolution
1. **Tasks & Notes (Observed-Remove Set / LWW-Register):**
* Fields like task title, body notes, priority rating, and status use Last-Write-Wins Element-Set (LWW-Element-Set) registers based on Hybrid Logical Clocks (HLCs).
* HLCs prevent clock skew anomalies across distinct physical hardware platforms.
2. **Project Hierarchies & Trees (Sequence CRDT):**
* Sub-task orders and document tree layouts use fractional indexing combined with tree-CRDTs to prevent circular reference cycles when moving folders offline.
3. **Delta Sync Protocol:**
* Nodes keep an append-only state transition log.
* When two peers connect, they exchange vector clocks. Only missing state deltas (changesets) are packaged, encrypted, and streamed across the QUIC network socket.
---
## 5. Integrated Time, Note, & Project Architecture
The application implements the complete productivity pipeline—note ingestion, task extraction, Eisenhower matrix sorting, and calendar time-blocking—as local data transformations inside the CRDT engine.
```
+-----------------------------------------------------------------------------------+
| INBOUND INGESTION ENGINE |
| (Local IMAP Watcher / System Hotkeys / Local Files / Audio Jots) |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| LOCAL AI & AUTOMATION ENGINE |
| (Local LLM Inference / Keyword Extractor / Natural Language NLP) |
| |
| * Parses Due Dates & Durations * Assigns Project & Namespace Tag |
| * Calculates Eisenhower Priorities * Converts Raw Jots to Structured Docs |
+-----------------------------------------------------------------------------------+
│
▼
+-----------------------------------------------------------------------------------+
| LOCAL CRDT PRODUCTIVITY DATABASE |
| +---------------------+ +---------------------+ +---------------------------+ |
| | Multi-Level Tree | | Eisenhower Matrix | | Calendar Time-Blocking | |
| | (Projects/Sub-Tasks)| | (Quadrant 1 - 4) | | (CalDAV & Native Grid) | |
| +---------------------+ +---------------------+ +---------------------------+ |
+-----------------------------------------------------------------------------------+
```
### Multi-Project & Note Ecosystem
* **Namespaces & Hierarchies:** Deep multi-level support for distinct spaces (e.g., `Personal`, `Engineering`, `Creations`).
* **Note-to-Task Pipeline:** Unstructured daily jots are captured via global shortcuts or voice recordings. The internal processing pipe converts embedded action items into indexed tasks while maintaining bidirectional hyperlinks to the parent note.
### Automated Eisenhower Priority Engine
Tasks automatically compute an **Urgency-Importance Vector Score ($S$)** based on internal properties:
$$S = (W_i \cdot P_{user}) + (W_u \cdot f(\text{Due Date} - t_{current})) + (W_a \cdot \text{Age})$$
Where:
* $P_{user}$ is the user-defined priority weight ($0.0 \text{ to } 1.0$).
* $f(\Delta t)$ is an exponential decay function mapping time proximity to urgency.
* $W_i, W_u, W_a$ are normalized weights for importance, urgency, and age accumulation.
The resulting vector automatically places the task into one of four Eisenhower Quadrants on the dynamic dashboard.
### Local Calendar & Automated Ingestion System
* **Local Ingestion Daemon:** The headless/background engine includes built-in watchers for:
* **Local File System / PDF / Markdown:** Drops into monitored watch folders automatically parse into raw notes.
* **Direct TLS IMAP Engine:** Runs locally inside the Rust core to securely poll personal or corporate mail servers directly over TLS, extracting flagged emails into actionable project tasks without third-party cloud bridges.
* **CalDAV Local Server & Client:** The application embeds a local CalDAV service end-point on `127.0.0.1`. Local calendar software (Outlook, Thunderbird, mobile calendars) can sync directly with the app locally.
---
## 6. Self-Hosted Headless Peer Node Architecture
To ensure high availability for sync without relying on public cloud servers, the core application compiles down to a lightweight, daemonized headless binary (`chronogrid-daemon`).
```
+--------------------+
| WAN P2P Network |
+--------------------+
│ │
QUIC / Noise │ │ QUIC / Noise
▼ ▼
+----------------+ +------------------+
| Desktop Client | | Mobile Android |
| (Windows/Linux)| | Client |
+----------------+ +------------------+
│ │
│ QUIC / Noise │
▼ ▼
+--------------------+
| Headless Peer Node |
| (Always-On Relay & |
| Storage Vault) |
+--------------------+
```
### Headless Server Features
* **Role:** Acts as an always-on, high-availability peer node, relay node, and backup vault for encrypted CRDT states.
* **Storage:** Holds the encrypted SQLCipher database. Even if hosted on a remote untrusted VPS, data remains unreadable without the user's Swarm Master Key.
* **Headless Services:**
* Runs local automated email polling (IMAP) continuously in the background.
* Serves as a WebRTC/libp2p Circuit Relay v2 to facilitate NAT hole-punching between mobile devices on cellular networks and desktop environments.
* Provides a lightweight local Web-GUI shell over HTTPS for browser-based task management.
---
## 7. Operational & Development Setup Guide
### Repository Structure (`git.kellsupport.com`)
```
chronogrid/
├── Cargo.toml # Workspace setup for native rust crates
├── apps/
│ ├── chronogrid_flutter/ # Flutter UI source code (Windows, Linux, Android)
│ └── chronogrid_daemon/ # Headless server CLI binary
├── crates/
│ ├── chronogrid_core/ # Database, SQLCipher, and CRDT engine
│ ├── chronogrid_net/ # libp2p network mesh and discovery
│ ├── chronogrid_crypto/ # Key derivation, Argon2id, and cipher logic
│ └── chronogrid_ai/ # Local ONNX runtime and NLP engine
└── scripts/
├── build_android_libs.sh # Android NDK cross-compilation pipeline
└── build_desktop_ffi.py # FFI bindings generator for Flutter
```
### Flutter Development Setup (VS Code on Windows)
#### Prerequisites
* Flutter SDK (3.22.x or later)
* VS Code with extensions: `Dart`, `Flutter`, `rust-analyzer`, `C/C++`
* LLVM / Clang and MSVC Build Tools (via Visual Studio Installer)
* Rust toolchain (`rustup target add x86_64-pc-windows-msvc aarch64-linux-android x86_64-unknown-linux-gnu`)
* `flutter_rust_bridge_codegen` CLI for direct Dart/Rust bindings.
#### Step 1: Environment Initialization
Clone the repository from the internal source control server:
```bash
git clone https://git.kellsupport.com/kell-engineering/chronogrid.git
cd chronogrid
```
#### Step 2: Compile Native Core Libraries
From the root workspace directory, generate the C/FFI dynamic link libraries and Flutter bindings:
```bash
# Generate C/FFI bindings for Flutter
cargo install flutter_rust_bridge_codegen
flutter_rust_bridge_codegen create --rust-input crates/chronogrid_core/src/api.rs --dart-output apps/chronogrid_flutter/lib/src/native/bridge_generated.dart
# Build Windows debug library
cargo build --package chronogrid_core
```
#### Step 3: Run the Flutter Application
Open `apps/chronogrid_flutter` in VS Code and launch the debug target:
```bash
cd apps/chronogrid_flutter
flutter pub get
flutter run -d windows
```
#### Step 4: Cross-Compiling for Headless Linux Server
To deploy an always-on peer server node:
```bash
cargo build --release --package chronogrid_daemon --target x86_64-unknown-linux-gnu
```
Deploy the resulting binary (`target/x86_64-unknown-linux-gnu/release/chronogrid-daemon`) to the server environment along with its systemd service file:
```ini
[Unit]
Description=ChronoGrid Headless Peer Node
After=network.target
[Service]
Type=simple
User=chronogrid
WorkingDirectory=/var/lib/chronogrid
ExecStart=/usr/local/bin/chronogrid-daemon --config /etc/chronogrid/config.toml
Restart=always
RestartSec=5
[Install]
WantedBy=multi-user.target
```
---
## 8. Master Development Phase Roadmap
```
+-----------------------------------------------------------------------------------+
| PHASED ROADMAP |
| |
| [Phase 1: Core Engine] ──> [Phase 2: Networking] ──> [Phase 3: Flutter UI Shell] |
| (Rust, Crypt, CRDT) (P2P Mesh, Noise, QUIC) (Windows, Linux, Android) |
| │ |
| ▼ |
| [Phase 5: Release & Test] <── [Phase 4: Automation & AI] <──────┘ |
| (Cross-Platform Builds) (IMAP, Local NLP, Logic) |
+-----------------------------------------------------------------------------------+
```
### Phase 1: Native Storage & CRDT Core Foundation
* Implement `chronogrid_crypto` for key derivation and key storage integrations.
* Set up SQLite with SQLCipher integration inside `chronogrid_core`.
* Build the state transition engine and CRDT vector-clock resolution logic using Automerge primitives.
### Phase 2: P2P Networking Mesh Integration
* Implement libp2p network protocol stack inside `chronogrid_net` supporting mDNS, Gossipsub, and QUIC transports.
* Build encrypted Noise XK protocol handshakes and Swarm Key authentication mechanisms.
* Implement delta state exchange protocols over binary streams.
### Phase 3: Cross-Platform Flutter Presentation Layer
* Construct the Flutter desktop and mobile shell apps.
* Integrate `flutter_rust_bridge` FFI bindings for zero-copy state streaming between Dart and Rust.
* Build UI modules: Kanban boards, drag-and-drop Calendar grid, Note editor, and Eisenhower quadrant dashboard.
### Phase 4: Local Automation & AI Engine Pipeline
* Implement native IMAP background polling directly within `chronogrid_core`.
* Embed local NLP metadata extraction engine for automatic task scoring and duration estimation.
* Create local CalDAV bridge server for device calendar interoperability.
### Phase 5: Headless Node & Deployment Optimization
* Build `chronogrid_daemon` headless executable.
* Perform multi-device cross-network latency, NAT traversal, and CRDT merge strain testing under high-volume offline updates.
* Finalize build automation scripts on `git.kellsupport.com` for Windows (`.msi`), Linux (`.AppImage`/`.deb`), and Android (`.apk`).

View File

@ -0,0 +1,104 @@
# Master User Story: Distributed, Local-First Productivity Engine
**Story Title:** Unified Automated Workflow Execution across Distributed Local-First Nodes
**Target Platform Scope:** Windows Desktop, Linux Desktop, Android Mobile, Headless Server Nodes
**Core Framework Architecture:** Local-First P2P (Flutter / C-FFI / Rust Core / CRDT Engine)
---
## 1. User Story Statement
**As a** multi-context professional managing multiple enterprise, operational, and commercial streams (Engineering, Custom Crafts/POD, and Personal Operations),
**I want** an integrated, automated, local-first system that ingests unstructured communications and quick jots across multiple distinct email domains, local files, and voice inputs—processing and auto-categorizing them via local AI rules into prioritized tasks, scheduled calendar blocks, and structured notes across my Windows, Linux, and Android devices,
**So that** I can achieve zero-friction time, project, and note management without manual data entry, without central cloud server dependencies or SaaS subscription locks, and with end-to-end cryptographic control over my data.
---
## 2. Ingestion & Input Processing Workflows (Discrete Input Architecture)
The system must automatically capture inputs from multiple distinct channels without requiring manual task entry, normalizing all inputs into raw CRDT entities within the local encrypted store (SQLCipher):
* **Direct IMAP / Email Ingestion (Multi-Domain):**
* The background daemon automatically polls external IMAP/TLS mail servers for personal, engineering, and commercial storefront accounts.
* *Workflow:* When an incoming email is flagged or sent to an internal parse address (e.g., `task@domain.com`), the engine extracts the thread body as Markdown, saves attachments as encrypted assets, preserves the deep-link URI to the original thread, and parses explicit deadlines.
* **Global Desktop & Mobile Jots (Scratchpad Capture):**
* *Windows / Linux:* Global system hotkeys invoke a lightweight command palette for instant plain-text jots or direct file drop attachments.
* *Android:* Quick-settings tiles, home-screen widget scratchpads, and intent-sharing (Share-to-App) forward text, web URLs, or quick voice notes directly into the native processing pipeline.
* **Local Workspace Watchers:**
* Background filesystem watchers monitor dedicated local folders (e.g., Markdown notes, local PDFs, design briefs). File modifications automatically sync into the note engine and parse for actionable embedded to-dos (e.g., `- [ ]` markdown items).
* **Automated AI Processing & Classification Pipeline:**
* Raw jots and incoming items pass through an embedded local processing engine (ONNX Runtime / Ollama) that executes four automated transformations:
1. **Context & Namespace Routing:** Maps items to the correct project hierarchy (e.g., *Personal*, *Kell Engineering*, *KellCreations / Tee Time Prints*).
2. **Note-to-Task Extraction:** Separates contextual reference material (stored as linked project notes) from actionable items (extracted as tasks).
3. **Eisenhower Priority Vector Calculation:** Evaluates urgency, importance, time decay, and age to compute a Priority Vector ($S$) and assign the item to Quadrants I–IV.
4. **Timestamp & Duration Allocation:** Extracts natural language dates/times (e.g., *"Review design layout by Thursday 2 PM"*) and sets `due_date` and `estimated_duration` parameters.
---
## 3. Storage & Synchronization Mechanics (Distributed State Architecture)
Data storage and sync must operate entirely on local-first, zero-trust principles:
* **Local Encrypted Storage:**
* All notes, project trees, and time blocks are stored in an encrypted local database (SQLCipher, AES-256-GCM) authenticated via hardware-backed platform key stores (Windows DPAPI, Linux SecretService, Android KeyStore).
* **Serverless Peer-to-Peer Synchronization (CRDTs):**
* Data state changes are tracked via Hybrid Logical Clocks (HLC) and append-only CRDT deltas (Automerge engine).
* Nodes discover each other on local networks via mDNS and across WAN via libp2p QUIC transport, direct NAT hole-punching, and Noise XK protocol handshakes using a private 256-bit Swarm Key.
* Reconnection triggers automatic, background, deterministic delta merges across all personal nodes (Windows, Android, Headless Server) without central server coordination or merge conflicts.
---
## 4. Visualization & Display Mechanisms (Multi-View Execution Shell)
The Flutter presentation layer dynamically renders local database state into specialized execution environments tailored to distinct planning frameworks:
* **Integrated Time-Blocking Calendar Grid:**
* Displays scheduled tasks alongside external Google and Outlook calendar overlays via local CalDAV sync feeds (`127.0.0.1`).
* Tasks can be dragged directly onto calendar slots to reserve dedicated focus blocks, with real-time dynamic duration adjustments.
* **Automated Eisenhower Priority Matrix View:**
* Dynamic four-quadrant board auto-populates tasks based on their calculated Urgency-Importance score.
* Eliminates manual sorting by surfacing Quadrant I (Do First) and Quadrant II (Schedule) items prominently based on approaching deadlines.
* **Multi-Level Project & Kanban Views:**
* Displays nested folder structures, namespaces, and project trees.
* Toggles instantly between hierarchical list views, interactive Kanban status boards (*Backlog*, *In Progress*, *Review*, *Done*), and interactive Gantt milestone timelines.
* **Unified Note & Knowledge Workspace:**
* Rich Markdown document editor supporting bi-directional task linking, embedded media attachments, and infinite sub-project documentation trees.
* Daily Jots view automatically aggregates unformed ideas into structured project wikis over time.
---
## 5. Detailed Acceptance Criteria
| Area | Functional Requirement | Technical Acceptance Pass Criteria |
| --- | --- | --- |
| **Ingestion** | Multi-Source Auto Parsing | IMAP polling, global hotkeys, and Android widgets create structured tasks in SQLCipher without manual UI entry within 2 seconds of receipt. |
| **Storage** | Zero-Trust Encryption | Database is unreadable on disk without the Master Key derived via Argon2id; key storage uses native OS platform keychains. |
| **Sync** | Serverless P2P Convergence | Offline modifications on Windows and Android automatically converge via QUIC/libp2p CRDT delta streams upon network reconnection without data loss or duplicate entries. |
| **Display** | Time Blocking & Multi-View | The UI renders Kanban, Eisenhower Matrix, Gantt, and Calendar views from the same CRDT state store, updating in real time across all active views. |
| **Headless** | Always-On Relay Node | The headless CLI daemon builds for Linux/systemd, maintains the CRDT state, runs local IMAP background polling, and facilitates WAN NAT hole-punching. |

View File

@ -0,0 +1,176 @@
# ChronoGrid P2P — Senior Architecture Review & Assessment
**Review Date:** 2026-08-22
**Reviewers:** Architecture Review Board (AI-Assisted)
**Scope:** Full codebase, documentation, task structure, and development plan
**Status:** Accepted — Drives Master Development Plan v2
---
## 1. Executive Summary
ChronoGrid P2P is a well-conceived, architecturally sound local-first productivity system. The foundational design decisions — Rust core, SQLCipher, Automerge CRDT, libp2p, and Flutter FFI — are appropriate, modern, and consistent with the data sovereignty mandate. Phase 1 (Storage & CRDT Foundation) is **complete and production-quality**, with 80+ unit tests across `chronogrid_core`, `chronogrid_crypto`, and `chronogrid_ffi`.
The project is at a **critical inflection point**: the data layer is solid, but Phases 2–5 (Networking, UI, AI/Automation, Headless Daemon) are entirely unimplemented stubs. The documentation is partially inconsistent, the task structure covers only Phase 1, and the verification script is incomplete. This review establishes the corrective actions and the full master development plan.
---
## 2. Strengths — What Is Working Well
### 2.1 Architecture & Design
- **Local-first mandate is rigorously enforced.** No cloud endpoints exist anywhere in the codebase. All data paths terminate at SQLCipher on-device.
- **Layered separation of concerns is clean.** `chronogrid_crypto` → `chronogrid_core` → `chronogrid_ffi` → Flutter is a correct dependency graph with no circular references.
- **Schema is the single source of truth.** `db.rs` uses `include_str!` to embed `schema.sql` at compile time — an excellent pattern that prevents schema drift.
- **CRDT design is correct.** Automerge LWW registers with HLC timestamps are the right primitive for the task/note domain. Fork/merge semantics are properly tested.
- **Security implementation is spec-compliant.** Argon2id parameters (64 MiB, 3 iter, 4 threads), SQLCipher 4.x raw-hex key bypass, and OS keychain abstraction all match `02-security-and-crypto.md` exactly.
- **FFI bridge architecture is sound.** The global `Engine` singleton behind a `Mutex` with `with_engine()` / `with_engine_mut()` helpers is thread-safe and compatible with FRB's isolate pool.
- **ADR discipline is established.** ADRs 0002–0005 are present and well-written.
### 2.2 Code Quality
- Rust code is idiomatic, well-documented with `///` doc comments, and follows consistent module patterns.
- Error types use `thiserror` with meaningful variants (`CoreError::InvalidKeyLength`, `CoreError::SchemaInit`, etc.).
- `DerivedKey` implements `Zeroize + Drop` — correct handling of sensitive memory.
- Test coverage for Phase 1 is comprehensive: 11 DB tests, 45 CRDT tests, 25 FFI tests, plus crypto tests.
---
## 3. Gaps, Risks & Recommendations
### 3.1 CRITICAL — Unimplemented Crates (Blocking Phases 2–5)
| Crate | Status | Risk |
|---|---|---|
| `chronogrid_net` | Stub — only a placeholder `it_works` test | **CRITICAL** — P2P sync is the core differentiator |
| `chronogrid_ai` | Stub — only a placeholder `it_works` test | HIGH — Automation pipeline depends on this |
| `chronogrid_daemon` | No `main.rs`, no `Cargo.toml` | HIGH — Headless node is required for always-on sync |
| Flutter UI | Only `main.dart` with a placeholder text widget | HIGH — No user-facing functionality exists |
**Recommendation:** Phases 2–5 must be sequenced carefully. `chronogrid_net` is the highest priority after Phase 1 because it enables multi-device sync — the core value proposition.
### 3.2 HIGH — Missing Schema Entities
The current `schema.sql` is missing several entities required by the master user story:
| Missing Entity | Required By |
|---|---|
| `time_blocks` table | Calendar time-blocking grid (UI_UX/02) |
| `attachments` table | IMAP ingestion saves email attachments |
| `calendar_feeds` table | CalDAV bridge external feed configuration |
| `node_peers` table | P2P peer registry and swarm key storage |
| `automation_rules` table | Local automation/rules engine |
| `ingestion_configs` table | IMAP account configuration storage |
**Recommendation:** Extend `schema.sql` in Phase 2 before any networking or UI work begins. All schema changes must be additive (new tables/columns only) to preserve CRDT document compatibility.
### 3.3 HIGH — FFI Bridge Not Code-Generated
The `frb_generated.rs` file does not exist (noted in `lib.rs` as a comment: "Uncomment after running codegen"). The Dart bindings in `apps/chronogrid_flutter/lib/src/rust/` do not exist. The Flutter app cannot call any Rust functions until codegen is run.
**Recommendation:** Running `flutter_rust_bridge_codegen generate` must be the first step of Phase 3 and must be added to the CI/verification pipeline.
### 3.4 HIGH — Verification Script Is Incomplete
`scripts/verify_agent_work.ps1` only checks `chronogrid_core` and `chronogrid_ffi` compilation plus Flutter analyze. It does not:
- Run any unit tests (`cargo test`)
- Check `chronogrid_crypto`, `chronogrid_net`, or `chronogrid_ai`
- Verify schema alignment
- Check for the daemon binary
**Recommendation:** Expand the verification script to cover all crates and run the full test suite.
### 3.5 MEDIUM — Documentation Inconsistencies
| Issue | Location | Impact |
|---|---|---|
| `docs/WORKFLOWS/01-master-user-story.md` is a stub that just references the ARCHITECTURE doc | WORKFLOWS/ | Redundant file, creates confusion |
| `docs/UI_UX/03-kanban-gantt-views.md` has typos: "acklog", "eview", "amespace_id" | UI_UX/ | Spec is unreadable in places |
| `docs/UI_UX/02-calendar-timeblocking.md` has typo: "stimated_duration" | UI_UX/ | Spec error |
| OSAD Section 7 repo structure shows `build_android_libs.sh` and `build_desktop_ffi.py` — neither exists | ARCHITECTURE/01 | Scripts referenced but missing |
| `ffi_bridge_spec.json` is minimal (4 functions) vs. 38 actual FFI functions implemented | API_CONTRACTS/ | Contract is severely out of date |
| `DECISION_LOG.md` entries are out of chronological order (ADL-002 appears after ADL-005) | Root | Minor but unprofessional |
| Phase 1 tasks file marks all tasks `[x]` complete but has no Phase 2–5 task files | TASKS/ | No automated execution path beyond Phase 1 |
### 3.6 MEDIUM — Missing `chronogrid_daemon` Cargo.toml
The `apps/chronogrid_daemon/` directory has only a `.gitkeep` and an empty `src/` directory. There is no `Cargo.toml`, no `main.rs`, and the workspace `Cargo.toml` does not include it as a member.
**Recommendation:** Add `apps/chronogrid_daemon` to the workspace and scaffold the binary crate in Phase 2.
### 3.7 MEDIUM — No Integration Tests or Cross-Crate Tests
All tests are unit tests within individual crates. There are no integration tests that exercise the full stack (crypto → core → ffi → dart).
**Recommendation:** Add an `integration_tests/` directory in Phase 3 with end-to-end tests covering the full data path.
### 3.8 LOW — `FfiTaskData.due_date` Type Mismatch
In `types.rs`, `due_date: Option<i64>` but in `schema.sql` and `task.rs` the field is `u64`. This is a subtle type inconsistency that will cause issues when large epoch values exceed `i64::MAX`.
**Recommendation:** Standardize on `u64` for all epoch millisecond fields in the FFI layer, or document the intentional narrowing.
### 3.9 LOW — No Build Scripts for Android/Linux Cross-Compilation
The OSAD references `build_android_libs.sh` and `build_desktop_ffi.py` but neither exists. The Android NDK cross-compilation pipeline is entirely undocumented in executable form.
**Recommendation:** Create `scripts/build_android_libs.sh` and `scripts/build_desktop_libs.ps1` in Phase 3.
---
## 4. Architecture Decisions Confirmed
The following architectural decisions from the OSAD are **confirmed as correct** and should not be revisited:
1. **Rust + Flutter FFI** — Correct choice. Rust provides memory safety, performance, and cross-platform compilation. Flutter provides a single UI codebase for Windows/Linux/Android.
2. **SQLCipher over plain SQLite** — Correct. AES-256-CBC with HMAC-SHA512 page auth is the right encryption model for local-first data.
3. **Automerge over custom CRDT** — Correct. Automerge is battle-tested, has a Rust crate, and handles the LWW + sequence CRDT requirements.
4. **libp2p over custom P2P** — Correct. libp2p provides mDNS, QUIC, Noise, Gossipsub, and Kademlia DHT out of the box.
5. **Argon2id for KDF** — Correct. Argon2id is the OWASP-recommended KDF for password-based key derivation.
6. **flutter_rust_bridge v2** — Correct. FRB v2 provides zero-copy async streams, which are essential for real-time CRDT event propagation to the UI.
---
## 5. Recommended Architecture Additions
### 5.1 Event Stream Architecture (New)
The current FFI layer is purely request/response. For real-time UI updates (CRDT sync events, ingestion notifications), a **Dart Stream** pattern must be added:
- Rust side: `flutter_rust_bridge` `StreamSink<T>` for pushing events to Dart.
- Events: `SyncEvent`, `IngestionEvent`, `TaskUpdatedEvent`, `PeerConnectedEvent`.
### 5.2 Repository Pattern for SQL Queries (New)
The `Database` struct currently only manages CRDT blob persistence. A `Repository` layer is needed for structured SQL queries (list tasks by namespace, filter by Eisenhower quadrant, etc.) to support the UI views.
### 5.3 Eisenhower Score Engine (New — in `chronogrid_core`)
The priority score formula `S = (W_i * P_user) + (W_u * f(Δt)) + (W_a * Age)` must be implemented as a pure Rust function in `chronogrid_core` and called on every task mutation and on a scheduled timer.
### 5.4 CalDAV Embedded Server (New — in `chronogrid_core` or separate crate)
A lightweight CalDAV server on `127.0.0.1:4242` using `hyper` or `axum` for local calendar interoperability.
### 5.5 IMAP Polling Engine (New — in `chronogrid_core`)
An async IMAP client using `async-imap` + `tokio` for background email polling. Must run in a dedicated Tokio runtime separate from the synchronous SQLite connection.
---
## 6. Overall Assessment
| Dimension | Score | Notes |
|---|---|---|
| Architecture Design | 9/10 | Excellent local-first design, correct technology choices |
| Phase 1 Implementation | 9/10 | Solid, well-tested, spec-compliant |
| Documentation Quality | 6/10 | Good architecture docs, but inconsistencies and gaps |
| Task Structure | 4/10 | Only Phase 1 tasks exist; no automated execution path for Phases 2–5 |
| Test Coverage | 7/10 | Phase 1 well-tested; Phases 2–5 have zero tests |
| Build & CI Pipeline | 4/10 | Verification script is incomplete; no cross-compilation scripts |
| **Overall Readiness** | **6.5/10** | Strong foundation; execution plan needed for Phases 2–5 |
---
## 7. Immediate Action Items (Pre-Phase 2)
1. Fix documentation typos in `UI_UX/03-kanban-gantt-views.md` and `UI_UX/02-calendar-timeblocking.md`
2. Update `ffi_bridge_spec.json` to reflect all 38 implemented FFI functions
3. Expand `scripts/verify_agent_work.ps1` to run full test suite across all crates
4. Create Phase 2–5 task files in `docs/TASKS/`
5. Scaffold `apps/chronogrid_daemon/` as a proper Cargo binary crate
6. Extend `schema.sql` with missing tables (`time_blocks`, `attachments`, `node_peers`, etc.)
7. Fix `FfiTaskData.due_date` type from `i64` to `u64`
8. Update `DECISION_LOG.md` to chronological order

View File

@ -0,0 +1,459 @@
# ChronoGrid P2P — Master Development Plan v2
**Document Version:** 2.0
**Created:** 2026-08-22
**Authority:** Architecture Review Board
**Supersedes:** OSAD Section 8 (Phase Roadmap)
**Status:** Active — Drives Automated Agent Execution
---
## 1. Purpose & Scope
This document is the **single authoritative execution plan** for ChronoGrid P2P development. It defines the complete phased roadmap, task sequencing, inter-phase dependencies, automated agent execution protocol, and quality gates for every phase from current state through v1.0.0 release.
This plan is designed for **automated agent execution** via the `.clinerules` Autonomous Task Execution Protocol. Each task in `docs/TASKS/` is written to be self-contained, verifiable, and executable by an AI agent without human intervention beyond phase boundary approvals.
---
## 2. Current State Assessment (2026-08-22)
### Completed Work
| Component | Status | Tests |
|---|---|---|
| `chronogrid_crypto` — Argon2id KDF + OS Keychain | ✅ Complete | ✅ Passing |
| `chronogrid_core` — SQLCipher DB + Schema | ✅ Complete | ✅ 11 tests |
| `chronogrid_core` — Automerge CRDT (Task + Note) | ✅ Complete | ✅ 45 tests |
| `chronogrid_ffi` — Flutter Rust Bridge v2 FFI | ✅ Complete | ✅ 25 tests |
| `docs/API_CONTRACTS/schema.sql` — Core schema | ✅ Complete | N/A |
| ADRs 0002–0005 | ✅ Complete | N/A |
### Pending Work (Phases 2–5)
| Component | Status | Blocking |
|---|---|---|
| `chronogrid_net` — libp2p P2P mesh | ❌ Stub | Phase 3, 4, 5 |
| Schema extension (6 new tables) | ❌ Missing | Phase 3, 4 |
| `chronogrid_daemon` — Headless binary | ❌ Not scaffolded | Phase 5 |
| `chronogrid_ai` — NLP + LLM pipeline | ❌ Stub | Phase 4 |
| Flutter UI — All views | ❌ Placeholder | Phase 5 |
| FRB codegen output | ❌ Not generated | Phase 3 |
| Integration tests | ❌ None | Phase 5 |
| Build scripts | ❌ Missing | Phase 3, 5 |
---
## 3. Phased Execution Roadmap
```
┌─────────────────────────────────────────────────────────────────────────────┐
│ CHRONOGRID P2P — EXECUTION ROADMAP │
│ │
│ [Phase 1: Core Engine] ──────────────────────────────────── COMPLETE ✅ │
│ Rust, SQLCipher, Automerge CRDT, FFI Bridge │
│ │
│ [Phase 2: Networking & Schema] ──────────────────────── NEXT TO EXECUTE │
│ libp2p, QUIC, Noise XK, Schema Extension, Daemon Scaffold │
│ │ │
│ ▼ │
│ [Phase 3: Flutter UI Shell] ─────────────────────────── Pending Phase 2 │
│ BLoC Architecture, All 4 Views, FRB Codegen, Build Scripts │
│ │ │
│ ▼ │
│ [Phase 4: AI & Automation] ──────────────────────────── Pending Phase 3 │
│ NLP Engine, IMAP Ingestion, File Watchers, CalDAV, Rules Engine │
│ │ │
│ ▼ │
│ [Phase 5: Headless & Release] ───────────────────────── Pending Phase 4 │
│ Daemon Completion, Integration Tests, Packaging, v1.0.0 Release │
└─────────────────────────────────────────────────────────────────────────────┘
```
---
## 4. Phase Summary & Task Index
### Phase 1 — Native Storage & CRDT Foundation ✅ COMPLETE
**Task File:** `docs/TASKS/phase_1_storage_and_crdt.md`
| Task | Description | Status |
|---|---|---|
| 1.1 | Rust Cargo Workspace initialization | ✅ |
| 1.2 | `chronogrid_crypto` — Argon2id KDF + OS Keychain | ✅ |
| 1.3 | `chronogrid_core` — SQLCipher DB initializer | ✅ |
| 1.4 | `chronogrid_core` — Automerge CRDT integration | ✅ |
| 1.5 | `chronogrid_ffi` — Flutter Rust Bridge FFI layer | ✅ |
---
### Phase 2 — P2P Networking Mesh & Schema Extension
**Task File:** `docs/TASKS/phase_2_networking_and_schema.md`
**Status:** Ready for Agent Execution
**Estimated Duration:** 8–12 agent cycles
| Task | Description | Priority |
|---|---|---|
| 2.1 | Extend `schema.sql` with 6 new tables | CRITICAL |
| 2.2 | `chronogrid_net` — Node Identity & Swarm Key | HIGH |
| 2.3 | `chronogrid_net` — Transport & Discovery Layer | HIGH |
| 2.4 | `chronogrid_net` — CRDT Delta Sync Protocol | HIGH |
| 2.5 | `chronogrid_net` — P2P Swarm Manager | HIGH |
| 2.6 | Integrate `chronogrid_net` into `chronogrid_core` | HIGH |
| 2.7 | Scaffold `chronogrid_daemon` binary crate | MEDIUM |
| 2.8 | Expand verification pipeline | MEDIUM |
| 2.9 | Update FFI bridge spec & fix type inconsistency | MEDIUM |
**Phase 2 Gate:** `cargo test --workspace` passes; daemon binary compiles; schema has 13 tables.
---
### Phase 3 — Cross-Platform Flutter Presentation Layer
**Task File:** `docs/TASKS/phase_3_flutter_ui_shell.md`
**Status:** Pending Phase 2
**Estimated Duration:** 12–18 agent cycles
| Task | Description | Priority |
|---|---|---|
| 3.1 | FRB codegen + Flutter architecture setup | CRITICAL |
| 3.2 | Engine initialization & onboarding flow | HIGH |
| 3.3 | Task repository & BLoC layer | HIGH |
| 3.4 | Eisenhower Priority Matrix view | HIGH |
| 3.5 | Calendar Time-Blocking Grid view | HIGH |
| 3.6 | Kanban Board view | HIGH |
| 3.7 | Gantt Timeline view | MEDIUM |
| 3.8 | Notes & Knowledge Workspace view | HIGH |
| 3.9 | Navigation shell & settings | HIGH |
| 3.10 | Build scripts & platform configuration | HIGH |
**Phase 3 Gate:** `flutter test` passes; `flutter build windows` succeeds; all 4 primary views render live data.
---
### Phase 4 — Local AI, Automation & Ingestion Pipeline
**Task File:** `docs/TASKS/phase_4_ai_and_automation.md`
**Status:** Pending Phase 3
**Estimated Duration:** 10–14 agent cycles
| Task | Description | Priority |
|---|---|---|
| 4.1 | Eisenhower priority score engine | CRITICAL |
| 4.2 | `chronogrid_ai` — NLP metadata extractor | HIGH |
| 4.3 | `chronogrid_ai` — Ollama LLM integration | MEDIUM |
| 4.4 | IMAP ingestion engine | HIGH |
| 4.5 | Filesystem watcher | HIGH |
| 4.6 | Global hotkey jot capture | HIGH |
| 4.7 | CalDAV embedded server | HIGH |
| 4.8 | Automation rules engine | MEDIUM |
| 4.9 | Wire AI pipeline into FFI & Flutter | HIGH |
**Phase 4 Gate:** IMAP creates tasks within 2s; CalDAV responds to clients; jot capture works end-to-end.
---
### Phase 5 — Headless Node, Integration Testing & Release
**Task File:** `docs/TASKS/phase_5_headless_and_release.md`
**Status:** Pending Phase 4
**Estimated Duration:** 8–12 agent cycles
| Task | Description | Priority |
|---|---|---|
| 5.1 | Complete `chronogrid_daemon` headless binary | CRITICAL |
| 5.2 | Headless keyfile credential store | HIGH |
| 5.3 | Multi-device integration test suite | CRITICAL |
| 5.4 | Performance & stress testing | HIGH |
| 5.5 | Android platform integration | HIGH |
| 5.6 | Linux platform integration & AppImage | HIGH |
| 5.7 | Windows MSI installer | HIGH |
| 5.8 | Systemd service & deployment guide | MEDIUM |
| 5.9 | Final verification & release | CRITICAL |
**Phase 5 Gate:** All acceptance criteria from master user story verified; v1.0.0 tagged and pushed.
---
## 5. Automated Agent Execution Protocol
When an agent receives "Execute next task", it follows the `.clinerules` 7-step protocol:
### Step 1: State Discovery
```
1. Read .clinerules
2. Read docs/ARCHITECTURE/01-OSAD-system-architecture.md
3. Read docs/ARCHITECTURE/06-master-development-plan.md (this file)
4. Scan docs/TASKS/ — find FIRST file with an incomplete [ ] task
5. Read DECISION_LOG.md for latest context
6. State: "Executing Task X.Y — [Task Title]"
```
### Step 2: Feature Branch
```bash
git checkout main && git pull origin main
git checkout -b feature/<task-id>-<short-description>
# Example: git checkout -b feature/2.1-schema-extension
```
### Step 3: Implementation
- Read all referenced spec files before writing code
- Implement ONLY the target task — no scope creep
- Follow all `.clinerules` mandates (no cloud endpoints, correct crate boundaries, etc.)
### Step 4: Testing & Verification
```powershell
# Run the verification pipeline
powershell -File scripts/verify_agent_work.ps1
# Run crate-specific tests
cargo test --package <crate_name>
# Fix all errors before proceeding
```
### Step 5: Documentation Update
- Mark task `[x]` in the task file
- Update `DECISION_LOG.md` with decisions made
- Create ADR if architectural decisions were made
### Step 6: Commit & Merge
```bash
git add .
git commit -m "feat(<scope>): complete Task X.Y — <Task Title>"
git checkout main
git merge feature/<task-id>-<short-description> --no-ff -m "chore: merge feature/<task-id> into main"
```
### Step 7: Push & Cleanup
```bash
git push origin main
git branch -d feature/<task-id>-<short-description>
# Report: completed task, test status, next task
```
---
## 6. Quality Gates & Non-Negotiable Standards
### Code Quality
- All public Rust functions must have `///` doc comments
- All error types must use `thiserror` with meaningful variants
- No `unwrap()` in production code paths — use `?` operator
- Sensitive data types must implement `Zeroize + Drop`
- No `unsafe` blocks without explicit justification in a comment
### Testing Standards
- Every new module must have unit tests covering happy path and error cases
- Minimum test coverage targets:
- `chronogrid_crypto`: 90%+ (security-critical)
- `chronogrid_core`: 85%+
- `chronogrid_net`: 80%+
- `chronogrid_ffi`: 75%+
- `chronogrid_ai`: 75%+
- Integration tests required for all cross-crate data flows
### Architecture Mandates (from `.clinerules`)
- **ZERO** third-party cloud API calls anywhere in the codebase
- All network sync via `chronogrid_net` over libp2p/QUIC/Noise XK only
- Flutter presentation only — no business logic in Dart
- All schema changes must update `docs/API_CONTRACTS/schema.sql` first
- All architectural decisions must be logged in `DECISION_LOG.md` and have an ADR
### Verification Pipeline
Every task must pass `scripts/verify_agent_work.ps1` before commit. The script must:
1. `cargo check` all crates
2. `cargo test` all crates
3. `flutter analyze` the Flutter app
4. Validate schema table count
5. Exit 0 on success, non-zero on any failure
---
## 7. Technology Stack Reference
| Layer | Technology | Version | Purpose |
|---|---|---|---|
| Presentation | Flutter | 3.22.x+ | Cross-platform UI (Win/Linux/Android) |
| State Management | flutter_bloc | 8.1.x | BLoC pattern for reactive UI |
| FFI Bridge | flutter_rust_bridge | 2.7.0 | Zero-copy Dart↔Rust bindings |
| Core Language | Rust | 1.75+ (MSRV) | All business logic and storage |
| Local Storage | SQLCipher | 4.x | AES-256-CBC encrypted SQLite |
| CRDT Engine | Automerge | 0.5.x | Conflict-free replicated data types |
| Key Derivation | Argon2id | — | Password-based master key derivation |
| P2P Transport | libp2p | 0.54.x | QUIC + Noise XK + mDNS + Gossipsub |
| AI Inference | ONNX Runtime / Ollama | — | Local-only NLP and LLM inference |
| Async Runtime | Tokio | 1.x | Async I/O for networking and ingestion |
| CalDAV Server | Axum | 0.7.x | Embedded HTTP server for CalDAV |
| Logging | tracing | — | Structured logging for daemon |
---
## 8. File & Directory Structure (Target State)
```
chronogrid/
├── Cargo.toml # Workspace root
├── Cargo.lock
├── flutter_rust_bridge.yaml # FRB codegen config
├── DECISION_LOG.md # Architectural decision log
├── CHANGELOG.md # Release notes (created in Phase 5)
├── .clinerules # Agent execution protocol
│
├── apps/
│ ├── chronogrid_flutter/ # Flutter UI (Win/Linux/Android)
│ │ ├── pubspec.yaml
│ │ ├── lib/
│ │ │ ├── main.dart
│ │ │ ├── app.dart
│ │ │ └── src/
│ │ │ ├── rust/ # FRB generated bindings
│ │ │ ├── core/ # Engine service, DI, routing
│ │ │ ├── features/ # BLoC + UI per feature
│ │ │ └── shared/ # Widgets, theme, models
│ │ ├── windows/ # Win32 platform config
│ │ ├── linux/ # GTK3 platform config
│ │ └── android/ # NDK platform config
│ │
│ └── chronogrid_daemon/ # Headless peer node binary
│ ├── Cargo.toml
│ ├── config.example.toml
│ ├── src/
│ │ ├── main.rs
│ │ ├── config.rs
│ │ └── web_gui.rs
│ └── deploy/
│ ├── chronogrid.service # systemd unit
│ └── install.sh
│
├── crates/
│ ├── chronogrid_core/ # Storage + CRDT + Ingestion + CalDAV
│ │ └── src/
│ │ ├── lib.rs
│ │ ├── db.rs
│ │ ├── error.rs
│ │ ├── crdt/ # Automerge CRDT (task, note)
│ │ ├── scoring/ # Eisenhower score engine
│ │ ├── ingestion/ # IMAP + file watcher
│ │ ├── caldav/ # Embedded CalDAV server
│ │ ├── automation/ # Rules engine
│ │ └── sync/ # P2P sync bridge
│ │
│ ├── chronogrid_crypto/ # KDF + Keychain + Keyfile
│ │ └── src/
│ │ ├── lib.rs
│ │ ├── kdf.rs
│ │ ├── keychain.rs
│ │ └── keyfile.rs # Added in Phase 5
│ │
│ ├── chronogrid_net/ # libp2p P2P mesh
│ │ └── src/
│ │ ├── lib.rs
│ │ ├── identity.rs
│ │ ├── transport.rs
│ │ ├── discovery.rs
│ │ └── sync.rs
│ │
│ ├── chronogrid_ai/ # NLP + LLM inference
│ │ └── src/
│ │ ├── lib.rs
│ │ ├── nlp/ # Regex NLP extractors
│ │ └── llm/ # Ollama client (optional)
│ │
│ └── chronogrid_ffi/ # Flutter Rust Bridge FFI
│ └── src/
│ ├── lib.rs
│ ├── frb_generated.rs # FRB generated (after codegen)
│ └── api/
│ ├── mod.rs
│ ├── engine.rs
│ ├── database.rs
│ ├── crypto.rs
│ ├── task_crdt.rs
│ ├── note_crdt.rs
│ ├── ingestion.rs # Added in Phase 4
│ ├── state.rs
│ └── types.rs
│
├── docs/
│ ├── API_CONTRACTS/
│ │ ├── schema.sql # Single source of truth for DB schema
│ │ └── ffi_bridge_spec.json # FFI function catalog
│ ├── ARCHITECTURE/
│ │ ├── 01-OSAD-system-architecture.md
│ │ ├── 02-security-and-crypto.md
│ │ ├── 03-crdt-sync-protocol.md
│ │ ├── 04-master-user-story.md
│ │ ├── 05-architecture-review-assessment.md
│ │ ├── 06-master-development-plan.md ← THIS FILE
│ │ └── ADR/
│ │ ├── 0000-adr-template.md
│ │ ├── 0002-crypto-argon2id-keychain.md
│ │ ├── 0003-core-sqlcipher-db-init.md
│ │ ├── 0004-core-automerge-crdt-integration.md
│ │ ├── 0005-ffi-bridge-flutter-rust-bridge.md
│ │ ├── 0006-p2p-libp2p-networking.md # Created in Phase 2
│ │ ├── 0007-flutter-bloc-architecture.md # Created in Phase 3
│ │ └── 0008-local-ai-automation-pipeline.md # Created in Phase 4
│ ├── TASKS/
│ │ ├── phase_1_storage_and_crdt.md ✅ Complete
│ │ ├── phase_2_networking_and_schema.md
│ │ ├── phase_3_flutter_ui_shell.md
│ │ ├── phase_4_ai_and_automation.md
│ │ └── phase_5_headless_and_release.md
│ ├── UI_UX/
│ │ ├── 01-eisenhower-matrix.md
│ │ ├── 02-calendar-timeblocking.md
│ │ └── 03-kanban-gantt-views.md
│ ├── WORKFLOWS/
│ │ ├── 01-master-user-story.md
│ │ └── 02-ingestion-pipeline.md
│ └── DEPLOYMENT/
│ ├── 01-headless-daemon-setup.md # Created in Phase 2
│ ├── 02-linux-installation.md # Created in Phase 5
│ ├── 03-windows-installation.md # Created in Phase 5
│ └── 04-multi-device-pairing.md # Created in Phase 5
│
├── scripts/
│ ├── verify_agent_work.ps1 # CI verification pipeline
│ ├── build_desktop_libs.ps1 # Windows build (Phase 3)
│ ├── build_desktop_libs.sh # Linux build (Phase 3)
│ ├── build_android_libs.sh # Android NDK build (Phase 3)
│ ├── build_windows_installer.ps1 # MSI packaging (Phase 5)
│ └── package_linux.sh # AppImage/.deb packaging (Phase 5)
│
└── tests/
└── integration/ # Cross-crate integration tests (Phase 5)
├── sync_convergence.rs
├── crypto_pipeline.rs
├── ingestion_pipeline.rs
└── caldav_sync.rs
```
---
## 9. Risk Register
| Risk | Probability | Impact | Mitigation |
|---|---|---|---|
| libp2p NAT traversal fails on restrictive networks | MEDIUM | HIGH | Implement Circuit Relay v2 as fallback; document port forwarding requirements |
| Automerge merge conflicts produce unexpected results | LOW | HIGH | Extensive fork/merge tests; HLC ordering as tiebreaker |
| SQLCipher bundled build fails on Android NDK | MEDIUM | HIGH | Test early in Phase 3; have fallback to system SQLite with manual encryption |
| Ollama not available on target device | HIGH | LOW | NLP regex extractor is the primary path; Ollama is opt-in enhancement |
| Flutter Windows build fails due to missing MSVC | LOW | MEDIUM | Document prerequisites clearly; verify in CI |
| IMAP TLS certificate validation issues | MEDIUM | MEDIUM | Support both strict and permissive TLS modes; document configuration |
| CalDAV RFC compliance gaps | MEDIUM | MEDIUM | Test with multiple CalDAV clients (Thunderbird, DAVx⁵, Outlook) |
| Android background sync killed by OS | HIGH | MEDIUM | Use WorkManager with KEEP policy; document battery optimization exemption |
---
## 10. Acceptance Criteria Traceability
All acceptance criteria from `docs/ARCHITECTURE/04-master-user-story.md` are traced to implementing tasks:
| Acceptance Criterion | Implementing Tasks | Verified In |
|---|---|---|
| IMAP polling creates tasks within 2 seconds | 4.4, 4.9 | Phase 4 gate |
| Database unreadable without master key | 1.2, 1.3 (complete) | Phase 1 gate ✅ |
| Offline edits converge via CRDT on reconnection | 2.4, 2.5, 2.6 | Phase 2 gate |
| All 4 UI views render from same CRDT state | 3.3–3.8 | Phase 3 gate |
| Headless daemon builds for Linux/systemd | 2.7, 5.1 | Phase 5 gate |
| Global hotkey jot capture < 2 seconds | 4.6 | Phase 4 gate |
| CalDAV sync with external calendar tools | 4.7 | Phase 4 gate |
| P2P sync via QUIC/Noise XK | 2.2–2.5 | Phase 2 gate |
| Android KeyStore-backed key storage | 5.5 | Phase 5 gate |

View File

@ -0,0 +1,159 @@
# Phase 2: P2P Networking Mesh & Schema Extension
## Status: Ready for Agent Execution
**Phase Goal:** Implement the libp2p P2P networking stack in `chronogrid_net`, extend the database schema with all missing entities, scaffold the headless daemon binary, and harden the verification pipeline.
**Prerequisites:** Phase 1 complete ✅
**Estimated Complexity:** High
**Blocking:** Phase 3 (Flutter UI requires sync events), Phase 4 (AI requires ingestion schema)
---
## Task 2.1 — Extend Schema with Missing Entities
- [ ] **Task 2.1**: Extend `docs/API_CONTRACTS/schema.sql` with the following new tables:
- `time_blocks` — Calendar time-blocking entries linked to tasks
- `attachments` — Binary/file attachments linked to notes or ingestion logs
- `calendar_feeds` — CalDAV external feed configuration per namespace
- `node_peers` — P2P peer registry (NodeId, public key, last seen, swarm membership)
- `automation_rules` — Local trigger/action rule definitions
- `ingestion_configs` — IMAP account and file-watcher configuration per namespace
- Add `crdt_docs` entries for `time_block` entity type
- Add indexes for all new foreign keys and query patterns
- Verify `db.rs` `EXPECTED_TABLES` list is updated to include all new tables
- All new tables must include `hlc_timestamp TEXT NOT NULL` for CRDT compatibility
- Run `cargo test --package chronogrid_core` — all existing tests must still pass
---
## Task 2.2 — Implement chronogrid_net: Node Identity & Swarm Key
- [ ] **Task 2.2**: Implement node identity and swarm key management in `crates/chronogrid_net/`:
- Add dependencies: `libp2p = { version = "0.54", features = ["noise", "quic", "mdns", "gossipsub", "kad", "identify", "relay"] }`, `tokio = { version = "1", features = ["full"] }`, `ed25519-dalek = "2"`, `rand = "0.8"`
- Implement `NodeIdentity` struct: Ed25519 keypair generation, serialization, and `NodeId` (public key hash)
- Implement `SwarmKey` struct: 256-bit random key generation, serialization, and validation
- Implement `identity::generate_node_identity() -> NodeIdentity`
- Implement `identity::load_or_create_identity(path: &Path) -> Result<NodeIdentity>` — persists keypair to encrypted file
- Unit tests: keypair generation, serialization round-trip, NodeId derivation, SwarmKey validation
- Run `cargo test --package chronogrid_net`
---
## Task 2.3 — Implement chronogrid_net: Transport & Discovery Layer
- [ ] **Task 2.3**: Implement the libp2p transport stack and peer discovery in `crates/chronogrid_net/`:
- Implement `transport::build_transport(identity: &NodeIdentity, swarm_key: &SwarmKey) -> Result<Boxed<(PeerId, StreamMuxerBox)>>`
- QUIC over UDP as primary transport
- Noise XK handshake (Noise_XK_25519_ChaChaPoly_BLAKE2s) for authentication
- Swarm Key pre-shared authentication layer
- Implement `discovery::MdnsDiscovery` — zero-config LAN peer discovery
- Implement `discovery::KademliaDht` — WAN peer discovery via Kademlia DHT
- Implement `PeerEvent` enum: `PeerDiscovered { peer_id, addrs }`, `PeerExpired { peer_id }`, `PeerConnected { peer_id }`, `PeerDisconnected { peer_id }`
- Unit tests: transport construction, mDNS event handling, DHT routing table operations
- Run `cargo test --package chronogrid_net`
---
## Task 2.4 — Implement chronogrid_net: CRDT Delta Sync Protocol
- [ ] **Task 2.4**: Implement the CRDT delta exchange protocol over libp2p in `crates/chronogrid_net/`:
- Implement `sync::VectorClock` — tracks per-entity HLC head state for delta computation
- Implement `sync::DeltaPacket` — serializable struct containing compressed CRDT changesets
- Implement `sync::SyncProtocol` — custom libp2p `NetworkBehaviour`:
- On peer connect: exchange vector clocks via request/response protocol
- Compute missing deltas by comparing remote vs. local vector clock
- Compress delta bytes (LZ4 or zstd), encrypt with ChaCha20-Poly1305, stream over QUIC channel
- On receive: decrypt, decompress, and return `Vec<DeltaPacket>` for core to merge
- Implement `sync::GossipsubBroadcast` — real-time state change notifications via Gossipsub
- Implement `NetEvent` enum: `DeltasReceived { from_peer, deltas }`, `SyncComplete { peer_id }`, `SyncError { peer_id, reason }`
- Unit tests: vector clock comparison, delta packet serialization, gossipsub message routing
- Run `cargo test --package chronogrid_net`
---
## Task 2.5 — Implement chronogrid_net: P2P Swarm Manager
- [ ] **Task 2.5**: Implement the top-level `SwarmManager` in `crates/chronogrid_net/`:
- Implement `SwarmManager` struct: owns the libp2p `Swarm`, runs the event loop in a dedicated Tokio task
- Public API:
- `SwarmManager::start(identity, swarm_key, listen_addrs) -> Result<SwarmHandle>`
- `SwarmHandle::trigger_sync() -> Result<()>` — initiates delta sync with all connected peers
- `SwarmHandle::broadcast_event(event: GossipEvent) -> Result<()>`
- `SwarmHandle::subscribe_events() -> tokio::sync::broadcast::Receiver<NetEvent>`
- `SwarmHandle::shutdown() -> Result<()>`
- Integrate `MdnsDiscovery`, `KademliaDht`, `SyncProtocol`, and `GossipsubBroadcast` into a single `NetworkBehaviour` composite
- Implement NAT hole-punching via libp2p Circuit Relay v2 (relay client mode)
- Unit tests: swarm startup/shutdown, peer connection lifecycle, event subscription
- Integration test: two in-process swarms exchange a CRDT delta and verify convergence
- Run `cargo test --package chronogrid_net`
---
## Task 2.6 — Integrate chronogrid_net into chronogrid_core
- [ ] **Task 2.6**: Wire the P2P sync layer into `chronogrid_core`:
- Add `chronogrid_net` as an optional dependency in `chronogrid_core/Cargo.toml` (feature: `"p2p"`)
- Implement `core::sync::SyncEngine` — bridges `SwarmHandle` events to `Database` CRDT merges:
- On `NetEvent::DeltasReceived`: deserialize Automerge changesets, merge into local `crdt_docs`, update SQL rows
- On local CRDT mutation: compute delta vs. last-synced state, broadcast via `SwarmHandle`
- Implement `core::sync::SyncEngine::merge_remote_deltas(deltas: Vec<DeltaPacket>) -> Result<Vec<String>>` — returns list of affected entity IDs
- Unit tests: delta merge into in-memory database, conflict resolution with concurrent edits
- Run `cargo test --package chronogrid_core --features p2p`
---
## Task 2.7 — Scaffold chronogrid_daemon Binary
- [ ] **Task 2.7**: Create the `apps/chronogrid_daemon/` headless binary crate:
- Create `apps/chronogrid_daemon/Cargo.toml` with `[[bin]]` target `chronogrid-daemon`
- Add `apps/chronogrid_daemon` to workspace `Cargo.toml` members list
- Dependencies: `chronogrid_core`, `chronogrid_crypto`, `chronogrid_net`, `tokio`, `clap`, `serde`, `toml`, `tracing`, `tracing-subscriber`
- Create `apps/chronogrid_daemon/src/main.rs`:
- CLI argument parsing via `clap`: `--config <path>`, `--db <path>`, `--log-level <level>`
- Config file loading from TOML (`/etc/chronogrid/config.toml` or `--config` path)
- Initialize `chronogrid_crypto` key derivation and keychain retrieval
- Initialize `chronogrid_core` database engine
- Start `chronogrid_net` SwarmManager
- Structured logging via `tracing`
- Graceful shutdown on SIGTERM/SIGINT
- Create `apps/chronogrid_daemon/config.example.toml` — documented example configuration
- Create `docs/DEPLOYMENT/01-headless-daemon-setup.md` — systemd service setup guide
- Run `cargo build --package chronogrid_daemon`
---
## Task 2.8 — Expand Verification Pipeline
- [ ] **Task 2.8**: Expand `scripts/verify_agent_work.ps1` to cover all crates and run full test suite:
- Add `cargo test --package chronogrid_crypto` step
- Add `cargo test --package chronogrid_core` step
- Add `cargo test --package chronogrid_ffi` step
- Add `cargo test --package chronogrid_net` step
- Add `cargo check --package chronogrid_daemon` step
- Add schema table count validation (query SQLite in-memory and count tables)
- Add check that `docs/API_CONTRACTS/schema.sql` contains all required table names
- Improve error reporting with per-step timing and failure context
- Run the expanded script and confirm all checks pass
---
## Task 2.9 — Update FFI Bridge Spec & Fix Type Inconsistency
- [ ] **Task 2.9**: Update API contracts and fix the `due_date` type mismatch:
- Fix `crates/chronogrid_ffi/src/api/types.rs`: change `due_date: Option<i64>` to `Option<u64>` and `completed_at: Option<i64>` to `Option<u64>`
- Update `docs/API_CONTRACTS/ffi_bridge_spec.json` to document all 38 FFI functions across the 5 API modules (engine, database, crypto, task_crdt, note_crdt)
- Add P2P sync FFI functions to the spec: `init_p2p_swarm`, `trigger_sync`, `subscribe_sync_events`, `get_connected_peers`
- Run `cargo test --package chronogrid_ffi` — all tests must pass
---
## Phase 2 Completion Criteria
- [ ] All 9 tasks above marked `[x]`
- [ ] `cargo test --workspace` passes with zero failures
- [ ] `scripts/verify_agent_work.ps1` exits with code 0
- [ ] `chronogrid_daemon` binary compiles for `x86_64-pc-windows-msvc` and `x86_64-unknown-linux-gnu`
- [ ] `docs/API_CONTRACTS/schema.sql` contains all 13 tables (7 original + 6 new)
- [ ] ADR created for P2P networking decisions (`docs/ARCHITECTURE/ADR/0006-p2p-libp2p-networking.md`)
- [ ] `DECISION_LOG.md` updated with Phase 2 decisions

View File

@ -0,0 +1,214 @@
# Phase 3: Cross-Platform Flutter Presentation Layer
## Status: Pending Phase 2 Completion
**Phase Goal:** Build the complete Flutter UI shell for Windows, Linux, and Android, integrating the Rust FFI bridge with all four primary views (Eisenhower Matrix, Calendar Time-Blocking, Kanban/Gantt, Notes), and establish the BLoC state management architecture.
**Prerequisites:** Phase 2 complete ✅
**Estimated Complexity:** Very High
**Blocking:** Phase 4 (AI output must render in UI), Phase 5 (final integration testing)
---
## Task 3.1 — Run FFI Code Generation & Establish Flutter Architecture
- [ ] **Task 3.1**: Run `flutter_rust_bridge_codegen generate` and establish the Flutter project architecture:
- Install `flutter_rust_bridge_codegen@2.7.0`: `cargo install flutter_rust_bridge_codegen@2.7.0`
- Run `flutter_rust_bridge_codegen generate` from workspace root
- Verify generated files exist:
- `crates/chronogrid_ffi/src/frb_generated.rs`
- `apps/chronogrid_flutter/lib/src/rust/frb_generated.dart`
- `apps/chronogrid_flutter/lib/src/rust/api/*.dart`
- Uncomment `mod frb_generated;` in `crates/chronogrid_ffi/src/lib.rs`
- Add Flutter dependencies to `pubspec.yaml`:
- `flutter_bloc: ^8.1.0` — BLoC state management
- `equatable: ^2.0.5` — Value equality for BLoC states
- `get_it: ^7.6.0` — Service locator / dependency injection
- `go_router: ^14.0.0` — Declarative routing
- `intl: ^0.19.0` — Date/time formatting
- `path_provider: ^2.1.0` — Platform-specific file paths
- `shared_preferences: ^2.2.0` — Lightweight local settings
- Establish directory structure under `apps/chronogrid_flutter/lib/`:
```
lib/
├── main.dart
├── app.dart # MaterialApp + GoRouter setup
├── src/
│ ├── rust/ # FRB generated (do not edit)
│ ├── core/
│ │ ├── engine_service.dart # Wraps FFI init/close lifecycle
│ │ ├── di.dart # GetIt service locator setup
│ │ └── router.dart # GoRouter route definitions
│ ├── features/
│ │ ├── tasks/ # Task BLoC + repository + UI
│ │ ├── notes/ # Notes BLoC + repository + UI
│ │ ├── calendar/ # Calendar BLoC + repository + UI
│ │ ├── eisenhower/ # Eisenhower BLoC + UI
│ │ ├── kanban/ # Kanban BLoC + UI
│ │ ├── sync/ # P2P sync status BLoC + UI
│ │ └── settings/ # Settings BLoC + UI
│ └── shared/
│ ├── widgets/ # Reusable UI components
│ ├── theme/ # Material 3 theme tokens
│ └── models/ # Dart model classes (DTOs)
```
- Run `flutter pub get` and `flutter analyze` — zero errors
---
## Task 3.2 — Engine Initialization & Onboarding Flow
- [ ] **Task 3.2**: Implement the engine initialization and first-run onboarding flow:
- Implement `EngineService` in `lib/src/core/engine_service.dart`:
- `Future<void> initialize()` — derives master key via FFI, opens database, starts P2P swarm
- `Future<void> shutdown()` — gracefully closes engine
- `bool get isInitialized`
- Implement `OnboardingBloc` with states: `OnboardingInitial`, `OnboardingPassphraseEntry`, `OnboardingKeyDerivationInProgress`, `OnboardingComplete`, `OnboardingError`
- Implement `OnboardingScreen` — passphrase entry with strength indicator, namespace setup (Personal/Engineering/Custom), node ID display
- Implement `SplashScreen` — checks for existing keychain credential, routes to onboarding or main shell
- Unit tests: `OnboardingBloc` state transitions
- Widget tests: `OnboardingScreen` renders correctly, passphrase field validation
---
## Task 3.3 — Task Repository & BLoC Layer
- [ ] **Task 3.3**: Implement the task data layer and BLoC:
- Implement `TaskRepository` in `lib/src/features/tasks/`:
- `Future<List<TaskModel>> getTasksByNamespace(String namespaceId)`
- `Future<List<TaskModel>> getTasksByEisenhowerQuadrant(int quadrant)`
- `Future<TaskModel> createTask({required String namespaceId, required String title, String? projectId})`
- `Future<void> updateTask(TaskModel task)`
- `Future<void> archiveTask(String taskId)`
- `Stream<List<TaskModel>> watchTasksByNamespace(String namespaceId)` — real-time updates via FRB stream
- Implement `TaskBloc` with events: `LoadTasks`, `CreateTask`, `UpdateTask`, `ArchiveTask`, `FilterByQuadrant`, `FilterByStatus`
- Implement `TaskModel` Dart class mirroring `FfiTaskData` with `copyWith`, `toJson`, `fromJson`
- Unit tests: `TaskBloc` state transitions, `TaskRepository` mock FFI calls
- Run `flutter test`
---
## Task 3.4 — Eisenhower Priority Matrix View
- [ ] **Task 3.4**: Implement the Eisenhower Priority Matrix UI view:
- Implement `EisenhowerScreen` with four-quadrant grid layout using Flutter `CustomPainter` or `GridView`
- Quadrant labels: Q1 "Do First" (red), Q2 "Schedule" (blue), Q3 "Delegate" (yellow), Q4 "Eliminate" (grey)
- Each quadrant renders a scrollable list of `TaskCard` widgets filtered by `eisenhower_quadrant`
- `TaskCard` widget: title, due date chip, priority score badge, status indicator, tap-to-edit
- Drag-and-drop between quadrants updates `eisenhower_quadrant` via `TaskBloc`
- Real-time score recalculation indicator (spinner when Rust engine is computing scores)
- Implement `EisenhowerBloc` with auto-refresh on task mutations
- Widget tests: quadrant rendering, task card display, drag-and-drop state update
- Run `flutter test`
---
## Task 3.5 — Calendar Time-Blocking Grid View
- [ ] **Task 3.5**: Implement the Calendar Time-Blocking Grid UI view:
- Implement `CalendarScreen` with day/week/month view toggle
- Day and week views render hourly time slots as a vertical grid using `CustomPainter`
- Unscheduled tasks panel on the left sidebar — drag tasks onto time slots to schedule them
- Dragging a task onto a slot: sets `due_date` to slot start time, sets `estimated_duration` to slot height in minutes
- Scheduled task blocks render with color-coded namespace indicators
- Implement `CalendarBloc` with events: `LoadCalendarRange`, `ScheduleTask`, `RescheduleTask`, `UnscheduleTask`
- CalDAV feed overlay: display external calendar events from local CalDAV bridge (read-only overlay)
- Widget tests: time slot rendering, drag-and-drop scheduling, duration resize handle
- Run `flutter test`
---
## Task 3.6 — Kanban Board View
- [ ] **Task 3.6**: Implement the Kanban Board UI view:
- Implement `KanbanScreen` with four status columns: Backlog, In Progress, Review, Done
- Horizontal swimlanes group tasks by `namespace_id` or `project_id` (toggle)
- `KanbanCard` widget: title, priority badge, due date, assignee avatar placeholder, tag chips
- Drag-and-drop between columns updates `status` field via `TaskBloc` and emits CRDT mutation
- Column header shows task count and WIP limit indicator (configurable)
- Implement `KanbanBloc` with events: `LoadKanban`, `MoveCard`, `FilterByNamespace`, `FilterByProject`
- Widget tests: column rendering, card drag-and-drop, status update
- Run `flutter test`
---
## Task 3.7 — Gantt Timeline View
- [ ] **Task 3.7**: Implement the interactive Gantt Timeline UI view:
- Implement `GanttScreen` with horizontal timeline using `CustomPainter`
- Renders project milestones, task bars, and sub-task nesting with fractional index ordering
- Task bars are draggable (reschedule) and resizable (change duration)
- Critical path highlighting: tasks with no slack time rendered in red
- Zoom controls: day/week/month/quarter granularity
- Implement `GanttBloc` with events: `LoadGantt`, `RescheduleTask`, `ResizeTask`, `ExpandProject`, `CollapseProject`
- Widget tests: timeline rendering, task bar positioning, zoom level changes
- Run `flutter test`
---
## Task 3.8 — Notes & Knowledge Workspace View
- [ ] **Task 3.8**: Implement the Notes & Knowledge Workspace UI view:
- Implement `NotesScreen` with left sidebar (project tree) and right editor panel
- Project tree: hierarchical `TreeView` widget rendering `projects` and `namespaces` with expand/collapse
- Markdown editor: rich text editing with live preview toggle, using `flutter_markdown` package
- Bidirectional task linking: `[[task:uuid]]` syntax renders as tappable task chips
- Daily Jots view: chronological list of unstructured notes with auto-date grouping
- Implement `NotesBloc` with events: `LoadNotes`, `CreateNote`, `UpdateNote`, `DeleteNote`, `LinkTask`, `UnlinkTask`
- Add `flutter_markdown: ^0.7.0` to `pubspec.yaml`
- Widget tests: tree view rendering, markdown preview, task link chips
- Run `flutter test`
---
## Task 3.9 — Navigation Shell & Settings
- [ ] **Task 3.9**: Implement the main navigation shell and settings screen:
- Implement `AppShell` with `NavigationRail` (desktop) / `BottomNavigationBar` (mobile) for view switching
- Navigation destinations: Eisenhower Matrix, Calendar, Kanban, Gantt, Notes, Settings
- Implement `SettingsScreen`:
- Namespace management (create, rename, color, delete)
- IMAP account configuration (host, port, username, password — stored via keychain FFI)
- P2P sync status panel: connected peers list, last sync time, manual sync trigger
- Eisenhower weight configuration (W_i, W_u, W_a sliders)
- Theme toggle (light/dark/system)
- Implement `SyncStatusWidget` — persistent bottom bar showing P2P connection state and last sync time
- Widget tests: navigation rail rendering, settings form validation
- Run `flutter test`
---
## Task 3.10 — Build Scripts & Platform Configuration
- [ ] **Task 3.10**: Create build scripts and configure platform targets:
- Create `scripts/build_desktop_libs.ps1` (Windows):
- `cargo build --release --package chronogrid_ffi`
- Copy `.dll` to `apps/chronogrid_flutter/windows/`
- Run `flutter_rust_bridge_codegen generate`
- `flutter build windows`
- Create `scripts/build_desktop_libs.sh` (Linux):
- `cargo build --release --package chronogrid_ffi --target x86_64-unknown-linux-gnu`
- Copy `.so` to `apps/chronogrid_flutter/linux/`
- `flutter build linux`
- Create `scripts/build_android_libs.sh`:
- Install Android NDK targets: `rustup target add aarch64-linux-android armv7-linux-androideabi`
- `cargo build --release --package chronogrid_ffi --target aarch64-linux-android`
- Copy `.so` to `apps/chronogrid_flutter/android/app/src/main/jniLibs/arm64-v8a/`
- `flutter build apk --release`
- Configure `apps/chronogrid_flutter/windows/CMakeLists.txt` to link `chronogrid_ffi.dll`
- Configure `apps/chronogrid_flutter/linux/CMakeLists.txt` to link `libchronogrid_ffi.so`
- Verify `flutter build windows` succeeds on Windows host
- Update `scripts/verify_agent_work.ps1` to include FRB codegen check and Windows build check
---
## Phase 3 Completion Criteria
- [ ] All 10 tasks above marked `[x]`
- [ ] `flutter test` passes with zero failures across all feature BLoCs and widgets
- [ ] `flutter build windows` produces a runnable `.exe`
- [ ] FRB codegen output exists in `apps/chronogrid_flutter/lib/src/rust/`
- [ ] All four primary views (Eisenhower, Calendar, Kanban, Notes) render from live CRDT data
- [ ] `scripts/verify_agent_work.ps1` exits with code 0
- [ ] ADR created for Flutter architecture decisions (`docs/ARCHITECTURE/ADR/0007-flutter-bloc-architecture.md`)
- [ ] `DECISION_LOG.md` updated with Phase 3 decisions

View File

@ -0,0 +1,214 @@
# Phase 4: Local AI, Automation & Ingestion Pipeline
## Status: Pending Phase 3 Completion
**Phase Goal:** Implement the full local AI inference pipeline in `chronogrid_ai`, the IMAP ingestion engine, filesystem watchers, the Eisenhower score computation engine, the CalDAV embedded server, and the automation rules engine — all running entirely on-device with no cloud API calls.
**Prerequisites:** Phase 3 complete ✅
**Estimated Complexity:** Very High
**Blocking:** Phase 5 (final integration and release testing)
---
## Task 4.1 — Eisenhower Priority Score Engine
- [ ] **Task 4.1**: Implement the Eisenhower priority score computation engine in `chronogrid_core`:
- Create `crates/chronogrid_core/src/scoring/mod.rs`
- Implement `EisenhowerWeights` struct: `w_importance: f64`, `w_urgency: f64`, `w_age: f64` (must sum to 1.0)
- Implement `urgency_decay(due_date_ms: u64, now_ms: u64) -> f64`:
- Exponential decay function: `f(Δt) = e^(-λ * Δt_hours)` where λ = 0.05
- Returns 1.0 when due_date is now, approaches 0.0 for distant future dates
- Returns 1.5 (overdue boost) when due_date is in the past
- Implement `compute_priority_score(task: &TaskSnapshot, weights: &EisenhowerWeights, now_ms: u64) -> f64`
- `S = (w_i * p_user) + (w_u * urgency_decay(due_date, now)) + (w_a * age_factor)`
- `age_factor = min(1.0, days_since_created / 30.0)` — tasks age into importance over 30 days
- Implement `assign_eisenhower_quadrant(score: f64, due_date: Option<u64>, now_ms: u64, threshold_high: f64) -> i64`
- Q1: score >= threshold AND due within 48 hours
- Q2: score >= threshold AND due > 48 hours or no due date
- Q3: score < threshold AND due within 48 hours
- Q4: score < threshold AND due > 48 hours or no due date
- Implement `Database::recompute_all_scores(weights: &EisenhowerWeights) -> Result<usize>` — batch update all tasks
- Add `scoring` module to `chronogrid_core/src/lib.rs` public API
- Unit tests: decay function values, score computation, quadrant assignment, batch recompute
- Run `cargo test --package chronogrid_core`
---
## Task 4.2 — Implement chronogrid_ai: NLP Metadata Extractor
- [ ] **Task 4.2**: Implement the NLP metadata extraction engine in `crates/chronogrid_ai/`:
- Add dependencies: `regex = "1"`, `chrono = { version = "0.4", features = ["serde"] }`, `serde = { version = "1", features = ["derive"] }`, `serde_json = "1"`
- Implement `nlp::DateTimeExtractor`:
- Parse natural language date/time expressions using regex patterns:
- Relative: "tomorrow", "next Monday", "in 3 days", "next week"
- Absolute: "August 25th", "2026-08-25", "Thursday at 2pm", "by 3 PM Friday"
- Duration: "for 2 hours", "30 minutes", "half an hour"
- Returns `ExtractedDateTime { due_date: Option<DateTime<Utc>>, duration_minutes: Option<i64> }`
- Implement `nlp::NamespaceClassifier`:
- Rule-based keyword classifier mapping text to namespace IDs
- Configurable keyword lists per namespace (loaded from `automation_rules` table)
- Returns `ClassificationResult { namespace_id: String, confidence: f64 }`
- Implement `nlp::TaskNoteSplitter`:
- Detects action items: lines starting with `- [ ]`, `TODO:`, `ACTION:`, imperative verbs
- Separates actionable items (→ tasks) from reference text (→ notes)
- Returns `SplitResult { tasks: Vec<String>, note_content: String }`
- Implement `nlp::process_raw_input(text: &str, context: &ProcessingContext) -> ProcessedInput`
- Runs all three extractors in sequence
- Returns structured `ProcessedInput` with extracted tasks, note content, dates, namespace
- Unit tests: date extraction for all pattern types, namespace classification, task/note splitting
- Run `cargo test --package chronogrid_ai`
---
## Task 4.3 — Implement chronogrid_ai: Local LLM Integration (Ollama)
- [ ] **Task 4.3**: Implement optional local LLM inference via Ollama HTTP socket in `crates/chronogrid_ai/`:
- Add dependencies: `reqwest = { version = "0.12", features = ["json", "blocking"] }`, `serde_json = "1"`
- Implement `llm::OllamaClient`:
- `OllamaClient::new(base_url: &str) -> Self` — defaults to `http://127.0.0.1:11434`
- `OllamaClient::is_available() -> bool` — health check ping
- `OllamaClient::complete(model: &str, prompt: &str) -> Result<String>` — blocking inference call
- Implement `llm::TaskEnrichmentPrompt`:
- Structured prompt template for task metadata extraction
- Input: raw text, Output: JSON with `{ title, description, due_date, duration_minutes, namespace, priority_hint }`
- Implement `llm::enrich_task_with_llm(text: &str, client: &OllamaClient) -> Result<EnrichedTask>`
- Falls back to regex NLP extractor if Ollama is unavailable
- Validates LLM JSON output against expected schema
- Feature flag: `features = ["ollama"]` — Ollama integration is opt-in
- Unit tests: prompt construction, JSON response parsing, fallback behavior when Ollama unavailable
- Run `cargo test --package chronogrid_ai`
---
## Task 4.4 — Implement IMAP Ingestion Engine
- [ ] **Task 4.4**: Implement the direct TLS IMAP polling engine in `chronogrid_core`:
- Add dependencies: `async-imap = "0.9"`, `async-native-tls = "0.5"`, `tokio = { version = "1", features = ["full"] }`, `mail-parser = "0.9"`
- Create `crates/chronogrid_core/src/ingestion/imap.rs`:
- Implement `ImapConfig` struct: `host`, `port`, `username`, `password_keychain_key`, `mailbox`, `poll_interval_secs`, `namespace_id`
- Implement `ImapPoller`:
- `ImapPoller::new(config: ImapConfig, db: Arc<Mutex<Database>>) -> Self`
- `ImapPoller::poll_once() -> Result<Vec<IngestionResult>>` — connects, fetches unseen messages, disconnects
- `ImapPoller::run_background(shutdown: CancellationToken)` — Tokio task that polls on interval
- Email processing pipeline:
1. Fetch unseen messages from configured mailbox
2. Extract: `message_id`, `subject`, `body_text`, `attachments`, `date`
3. Convert body to Markdown (strip HTML, preserve structure)
4. Save attachments as encrypted blobs in `attachments` table
5. Run `chronogrid_ai::nlp::process_raw_input` on subject + body
6. Create task CRDT document with extracted metadata
7. Log to `ingestion_logs` table with `source_type = 'imap'`
8. Mark message as seen / move to processed folder
- Unit tests: email parsing, Markdown conversion, attachment handling, ingestion log creation
- Integration test: mock IMAP server (using `greenmail` or in-process mock) → full pipeline → task created in DB
- Run `cargo test --package chronogrid_core`
---
## Task 4.5 — Implement Filesystem Watcher
- [ ] **Task 4.5**: Implement the local filesystem watcher in `chronogrid_core`:
- Add dependency: `notify = "6"` (cross-platform filesystem events)
- Create `crates/chronogrid_core/src/ingestion/file_watcher.rs`:
- Implement `WatchConfig` struct: `watch_path: PathBuf`, `namespace_id: String`, `file_extensions: Vec<String>`
- Implement `FileWatcher`:
- `FileWatcher::new(config: WatchConfig, db: Arc<Mutex<Database>>) -> Result<Self>`
- `FileWatcher::start(shutdown: CancellationToken)` — Tokio task watching for `Create` and `Modify` events
- File processing pipeline:
1. On file event: read file content
2. Parse Markdown `- [ ]` checkboxes as task candidates
3. Run `chronogrid_ai::nlp::process_raw_input` on file content
4. Create/update note CRDT document with file content
5. Extract tasks from `- [ ]` items and create task CRDT documents
6. Log to `ingestion_logs` with `source_type = 'file_watcher'`
- Unit tests: file event handling, Markdown task extraction, note creation
- Run `cargo test --package chronogrid_core`
---
## Task 4.6 — Implement Global Hotkey Jot Capture (Desktop)
- [ ] **Task 4.6**: Implement the global hotkey quick-jot capture system:
- Add dependency to `chronogrid_ffi`: `global-hotkey = "0.5"` (cross-platform global hotkeys)
- Implement `api::jot::register_global_hotkey(hotkey: String) -> anyhow::Result<()>` — registers system-wide hotkey
- Implement `api::jot::submit_jot(text: String) -> anyhow::Result<FfiTaskData>` — processes raw jot text through AI pipeline and creates task
- Flutter side: implement `JotOverlay` — lightweight floating window that appears on hotkey press:
- Single-line text input with submit button
- Appears as a system overlay (Windows: `flutter_acrylic` for frosted glass effect)
- On submit: calls `submitJot()` FFI function, shows confirmation toast, dismisses
- Android: implement `QuickJotWidget` — home screen widget using `home_widget` Flutter package
- Unit tests: hotkey registration, jot processing pipeline
- Run `cargo test --package chronogrid_ffi`
---
## Task 4.7 — Implement CalDAV Embedded Server
- [ ] **Task 4.7**: Implement the embedded CalDAV server in `chronogrid_core`:
- Add dependencies: `axum = "0.7"`, `tokio = { version = "1", features = ["full"] }`, `quick-xml = "0.36"`
- Create `crates/chronogrid_core/src/caldav/mod.rs`:
- Implement `CalDavServer`:
- `CalDavServer::new(db: Arc<Mutex<Database>>, bind_addr: SocketAddr) -> Self`
- `CalDavServer::start(shutdown: CancellationToken)` — starts Axum HTTP server on `127.0.0.1:4242`
- Implement CalDAV endpoints:
- `PROPFIND /` — calendar discovery
- `PROPFIND /calendars/{namespace_id}/` — calendar collection properties
- `REPORT /calendars/{namespace_id}/` — calendar query (returns iCalendar events for time-blocked tasks)
- `PUT /calendars/{namespace_id}/{task_id}.ics` — create/update time block from external calendar
- `DELETE /calendars/{namespace_id}/{task_id}.ics` — remove time block
- iCalendar (RFC 5545) serialization: convert `time_blocks` + `tasks` to `VEVENT` format
- iCalendar parsing: convert incoming `VEVENT` to `time_blocks` entries
- Unit tests: iCalendar serialization, PROPFIND response XML, REPORT query filtering
- Integration test: CalDAV client (using `vdirsyncer` or `curl`) syncs with embedded server
- Run `cargo test --package chronogrid_core`
---
## Task 4.8 — Implement Automation Rules Engine
- [ ] **Task 4.8**: Implement the local automation rules engine in `chronogrid_core`:
- Create `crates/chronogrid_core/src/automation/mod.rs`:
- Implement `AutomationRule` struct: `trigger: Trigger`, `conditions: Vec<Condition>`, `actions: Vec<Action>`
- Implement `Trigger` enum: `OnIngestion { source_type }`, `OnTaskCreated`, `OnTaskStatusChanged`, `OnSchedule { cron_expr }`
- Implement `Condition` enum: `NamespaceMatches { id }`, `TitleContains { keyword }`, `PriorityAbove { threshold }`, `DueDateWithin { hours }`
- Implement `Action` enum: `SetNamespace { id }`, `SetProject { id }`, `SetPriority { score }`, `AddTag { tag }`, `SendToCalendar`, `ArchiveTask`
- Implement `RulesEngine`:
- `RulesEngine::load_rules(db: &Database) -> Result<Self>` — loads rules from `automation_rules` table
- `RulesEngine::evaluate(event: &AutomationEvent, db: &mut Database) -> Result<Vec<ActionResult>>`
- Expose rules management via FFI: `create_automation_rule`, `list_automation_rules`, `delete_automation_rule`
- Unit tests: rule evaluation, condition matching, action execution, rule persistence
- Run `cargo test --package chronogrid_core`
---
## Task 4.9 — Wire AI Pipeline into FFI & Flutter UI
- [ ] **Task 4.9**: Expose the AI/automation pipeline through the FFI layer and integrate into Flutter:
- Add `chronogrid_ai` as a dependency in `chronogrid_ffi/Cargo.toml`
- Implement FFI functions in `api/ingestion.rs`:
- `process_jot_text(text: String) -> anyhow::Result<FfiTaskData>` — full AI pipeline on raw text
- `configure_imap_account(config_json: String) -> anyhow::Result<()>` — stores IMAP config
- `start_imap_polling() -> anyhow::Result<()>` — starts background IMAP poller
- `stop_imap_polling() -> anyhow::Result<()>`
- `configure_file_watcher(path: String, namespace_id: String) -> anyhow::Result<()>`
- `get_ingestion_logs(limit: u32) -> anyhow::Result<Vec<FfiIngestionLog>>`
- Re-run `flutter_rust_bridge_codegen generate` to update Dart bindings
- Implement `IngestionBloc` in Flutter with events: `StartImapPolling`, `StopImapPolling`, `ProcessJot`, `LoadIngestionLogs`
- Add ingestion status panel to `SettingsScreen`
- Unit tests: FFI ingestion functions, `IngestionBloc` state transitions
- Run `cargo test --package chronogrid_ffi` and `flutter test`
---
## Phase 4 Completion Criteria
- [ ] All 9 tasks above marked `[x]`
- [ ] `cargo test --workspace` passes with zero failures
- [ ] IMAP polling creates tasks in the database from test email messages
- [ ] File watcher creates notes and tasks from Markdown files dropped in watch folder
- [ ] Eisenhower scores recompute correctly for all test task scenarios
- [ ] CalDAV server responds to `PROPFIND` and `REPORT` requests from a CalDAV client
- [ ] Global hotkey jot capture creates a task within 2 seconds (acceptance criterion from user story)
- [ ] `scripts/verify_agent_work.ps1` exits with code 0
- [ ] ADR created for AI/automation decisions (`docs/ARCHITECTURE/ADR/0008-local-ai-automation-pipeline.md`)
- [ ] `DECISION_LOG.md` updated with Phase 4 decisions

View File

@ -0,0 +1,232 @@
# Phase 5: Headless Node, Integration Testing & Release
## Status: Pending Phase 4 Completion
**Phase Goal:** Complete the `chronogrid_daemon` headless binary with all background services, perform comprehensive multi-device integration testing, finalize cross-platform build pipelines, and produce release artifacts for Windows (.msi), Linux (.AppImage/.deb), and Android (.apk).
**Prerequisites:** Phase 4 complete ✅
**Estimated Complexity:** High
**Blocking:** None — this is the final phase
---
## Task 5.1 — Complete chronogrid_daemon Headless Binary
- [ ] **Task 5.1**: Complete the `chronogrid_daemon` headless binary with all background services:
- Implement full daemon startup sequence in `apps/chronogrid_daemon/src/main.rs`:
1. Parse CLI args and load TOML config
2. Initialize `tracing` structured logging (JSON format for production, pretty for dev)
3. Load or generate `NodeIdentity` from config path
4. Retrieve master key from keychain (or encrypted keyfile for headless)
5. Initialize `chronogrid_core::Database`
6. Start `chronogrid_net::SwarmManager` (P2P mesh)
7. Start IMAP polling tasks for all configured accounts
8. Start filesystem watchers for all configured watch paths
9. Start CalDAV embedded server on `127.0.0.1:4242`
10. Start Eisenhower score recomputation timer (every 15 minutes)
11. Start automation rules engine event loop
12. Block on shutdown signal (SIGTERM/SIGINT/SIGHUP)
13. Graceful shutdown: stop all background tasks, flush database, close P2P swarm
- Implement `apps/chronogrid_daemon/src/config.rs`:
- `DaemonConfig` struct with full TOML deserialization
- Sections: `[node]`, `[database]`, `[network]`, `[imap]` (array), `[watchers]` (array), `[caldav]`, `[logging]`
- Implement `apps/chronogrid_daemon/src/web_gui.rs`:
- Lightweight HTTPS web interface on `127.0.0.1:8443` using `axum`
- Self-signed TLS certificate generated on first run
- REST API endpoints: `GET /api/tasks`, `GET /api/notes`, `POST /api/tasks`, `GET /api/sync/status`
- Minimal HTML/JS dashboard for browser-based task management
- Create `apps/chronogrid_daemon/config.example.toml` with all options documented
- Run `cargo build --release --package chronogrid_daemon`
---
## Task 5.2 — Headless Keyfile Credential Store
- [ ] **Task 5.2**: Implement encrypted keyfile credential storage for headless/server deployments:
- Create `crates/chronogrid_crypto/src/keyfile.rs`:
- `KeyFile` struct: stores encrypted master key + salt in a file
- Encryption: AES-256-GCM with a key derived from a server-specific secret (environment variable or systemd credential)
- `KeyFile::create(path: &Path, master_key: &[u8], server_secret: &[u8]) -> Result<()>`
- `KeyFile::load(path: &Path, server_secret: &[u8]) -> Result<Vec<u8>>`
- Implement `chronogrid_crypto::resolve_key(config: &KeyConfig) -> Result<Vec<u8>>`:
- Tries OS keychain first (desktop mode)
- Falls back to keyfile (headless mode)
- Falls back to environment variable `CHRONOGRID_MASTER_KEY` (CI/container mode)
- Update `chronogrid_daemon` to use `resolve_key` for flexible credential resolution
- Unit tests: keyfile create/load round-trip, wrong server secret rejection, env var fallback
- Run `cargo test --package chronogrid_crypto`
---
## Task 5.3 — Multi-Device Integration Test Suite
- [ ] **Task 5.3**: Create a comprehensive multi-device integration test suite:
- Create `tests/integration/` directory at workspace root
- Add `integration_tests` as a workspace member with `[[test]]` targets
- Implement `tests/integration/sync_convergence.rs`:
- Spawn two in-process `SwarmManager` instances on loopback
- Create a task on Node A while Node B is offline
- Reconnect nodes and verify task appears on Node B within 5 seconds
- Verify CRDT merge: concurrent title edits on both nodes converge to a single value
- Implement `tests/integration/crypto_pipeline.rs`:
- Full pipeline: passphrase → Argon2id → SQLCipher open → CRDT write → read back
- Verify wrong passphrase cannot open database
- Verify keychain store/retrieve round-trip
- Implement `tests/integration/ingestion_pipeline.rs`:
- Mock IMAP server → IMAP poller → AI processing → task created in DB
- File watcher → Markdown file drop → note + tasks created in DB
- Jot text → NLP pipeline → task with correct namespace, due date, duration
- Implement `tests/integration/caldav_sync.rs`:
- CalDAV server starts → `curl` PROPFIND → verify calendar collection response
- Create time block → verify iCalendar VEVENT in REPORT response
- Run `cargo test --test sync_convergence --test crypto_pipeline --test ingestion_pipeline --test caldav_sync`
---
## Task 5.4 — Performance & Stress Testing
- [ ] **Task 5.4**: Perform performance and stress testing:
- Implement `tests/perf/crdt_merge_stress.rs`:
- Generate 10,000 concurrent task mutations across 3 simulated peers
- Verify all peers converge to identical state within 30 seconds
- Measure merge throughput: target > 1,000 merges/second
- Implement `tests/perf/db_query_perf.rs`:
- Insert 50,000 tasks across 10 namespaces
- Measure query time for: list by namespace, filter by quadrant, filter by due date range
- Target: all queries < 50ms on standard hardware
- Implement `tests/perf/p2p_latency.rs`:
- Measure round-trip sync latency between two local peers
- Target: < 500ms for a single task delta sync on LAN
- Document performance results in `docs/ARCHITECTURE/06-performance-benchmarks.md`
- Run `cargo test --test crdt_merge_stress --test db_query_perf --test p2p_latency -- --nocapture`
---
## Task 5.5 — Android Platform Integration
- [ ] **Task 5.5**: Complete Android platform integration:
- Configure Android NDK cross-compilation in `scripts/build_android_libs.sh`:
- Targets: `aarch64-linux-android` (ARM64), `armv7-linux-androideabi` (ARM32), `x86_64-linux-android` (emulator)
- Set `ANDROID_NDK_HOME` and `CARGO_TARGET_*_LINKER` environment variables
- Build `chronogrid_ffi` for all three targets
- Copy `.so` files to correct `jniLibs` subdirectories
- Implement Android KeyStore bridge in Flutter:
- `lib/src/core/android_keystore.dart` — uses `flutter_secure_storage` for Android KeyStore-backed key storage
- Override `store_credential` / `retrieve_credential` FFI calls on Android with Dart-side KeyStore implementation
- Implement Android-specific features:
- `QuickJotWidget` — home screen widget using `home_widget` package
- Share Intent receiver — `AndroidManifest.xml` intent filter for `ACTION_SEND` text/URL sharing
- Background sync service — `WorkManager` periodic task for P2P sync when app is backgrounded
- Test on Android emulator: `flutter run -d emulator-5554`
- Test on physical Android device: `flutter run -d <device_id>`
- Run `flutter test` — all tests pass on Android target
---
## Task 5.6 — Linux Platform Integration & AppImage Build
- [ ] **Task 5.6**: Complete Linux platform integration and AppImage packaging:
- Configure GTK3 dependencies in `apps/chronogrid_flutter/linux/CMakeLists.txt`
- Link `libchronogrid_ffi.so` in Linux CMake build
- Implement Linux-specific features:
- SecretService D-Bus integration (already in `chronogrid_crypto` via `keyring` crate)
- Global hotkey via `global-hotkey` crate on Linux (X11/Wayland)
- System tray icon using `tray_manager` Flutter package
- Create `scripts/package_linux.sh`:
- Build Flutter Linux release: `flutter build linux --release`
- Package as AppImage using `appimagetool`
- Package as `.deb` using `dpkg-deb`
- Create `docs/DEPLOYMENT/02-linux-installation.md`
- Cross-compile from Windows using WSL2 or Docker: `docker run --rm -v $(pwd):/workspace rust:latest cargo build --release --target x86_64-unknown-linux-gnu --package chronogrid_ffi`
---
## Task 5.7 — Windows MSI Installer
- [ ] **Task 5.7**: Create the Windows MSI installer:
- Add `wix` toolset configuration: `apps/chronogrid_flutter/windows/installer/`
- Create `Product.wxs` WiX source file:
- Application name, version, manufacturer metadata
- Install `chronogrid_flutter.exe` and `chronogrid_ffi.dll` to `Program Files\ChronoGrid\`
- Install `chronogrid-daemon.exe` as an optional Windows Service component
- Desktop shortcut and Start Menu entry
- Uninstaller registration
- Create `scripts/build_windows_installer.ps1`:
- `flutter build windows --release`
- `cargo build --release --package chronogrid_daemon`
- Run WiX toolset: `candle.exe Product.wxs && light.exe Product.wixobj -o ChronoGrid-Setup.msi`
- Create `docs/DEPLOYMENT/03-windows-installation.md`
- Test installer on clean Windows VM
---
## Task 5.8 — Systemd Service & Server Deployment Guide
- [ ] **Task 5.8**: Finalize systemd service configuration and server deployment documentation:
- Create `apps/chronogrid_daemon/deploy/chronogrid.service` (systemd unit file):
```ini
[Unit]
Description=ChronoGrid Headless Peer Node
After=network-online.target
Wants=network-online.target
[Service]
Type=simple
User=chronogrid
Group=chronogrid
WorkingDirectory=/var/lib/chronogrid
ExecStart=/usr/local/bin/chronogrid-daemon --config /etc/chronogrid/config.toml
Restart=on-failure
RestartSec=10
StandardOutput=journal
StandardError=journal
SyslogIdentifier=chronogrid
NoNewPrivileges=yes
ProtectSystem=strict
ProtectHome=yes
ReadWritePaths=/var/lib/chronogrid
[Install]
WantedBy=multi-user.target
```
- Create `apps/chronogrid_daemon/deploy/install.sh` — automated server installation script
- Update `docs/DEPLOYMENT/01-headless-daemon-setup.md` with complete setup guide:
- Prerequisites, binary installation, config file setup, keyfile credential setup, systemd enable/start, firewall rules, log monitoring
- Create `docs/DEPLOYMENT/04-multi-device-pairing.md` — guide for pairing desktop + mobile + headless nodes using Swarm Key
---
## Task 5.9 — Final Verification & Release Checklist
- [ ] **Task 5.9**: Execute final verification and prepare release:
- Run full test suite: `cargo test --workspace` — zero failures
- Run `scripts/verify_agent_work.ps1` — exits with code 0
- Run integration tests: all convergence, crypto, ingestion, and CalDAV tests pass
- Run performance tests: all targets met (< 50ms queries, > 1,000 merges/sec, < 500ms P2P latency)
- Manual acceptance testing against all criteria in `docs/ARCHITECTURE/04-master-user-story.md`:
- [ ] IMAP polling creates tasks within 2 seconds of receipt
- [ ] Database is unreadable without master key
- [ ] Offline edits on two devices converge after reconnection without data loss
- [ ] All four UI views render from same CRDT state store
- [ ] Headless daemon builds for Linux/systemd and maintains CRDT state
- Update `docs/ARCHITECTURE/01-OSAD-system-architecture.md` Section 8 roadmap to mark all phases complete
- Create `CHANGELOG.md` with v1.0.0 release notes
- Tag release: `git tag -a v1.0.0 -m "ChronoGrid P2P v1.0.0 — Initial Release"`
- Push tag: `git push origin v1.0.0`
---
## Phase 5 Completion Criteria
- [ ] All 9 tasks above marked `[x]`
- [ ] `cargo test --workspace` passes with zero failures
- [ ] All integration tests pass
- [ ] All performance targets met
- [ ] All 5 acceptance criteria from master user story verified manually
- [ ] Windows `.msi` installer produced and tested
- [ ] Linux `.AppImage` and `.deb` packages produced
- [ ] Android `.apk` produced and tested on physical device
- [ ] `chronogrid-daemon` binary deployed and running on headless Linux server
- [ ] `v1.0.0` git tag pushed to `git.kellsupport.com`
- [ ] `DECISION_LOG.md` updated with Phase 5 decisions
- [ ] All ADRs up to date

View File

@ -3,9 +3,14 @@
## 1. Display Interface
- Multi-day, Weekly, and Monthly time-blocking grids rendered via Flutter custom painter.
- Drag-and-drop task placement: Dragging an unscheduled task onto the grid automatically updates its due_date timestamp and reserves a dedicated block based on its stimated_duration.
- Drag-and-drop task placement: Dragging an unscheduled task onto the grid automatically updates its `due_date` timestamp and reserves a dedicated block based on its `estimated_duration`.
- Unscheduled tasks panel on the left sidebar allows drag-and-drop onto time slots.
- Scheduled task blocks render with color-coded namespace indicators.
- View toggle: Day / Week / Month granularity.
## 2. Local CalDAV Bridge Protocol
- **Local Endpoint**: Embedded HTTPS/CalDAV service running locally on 127.0.0.1:4242.
- **Local Endpoint**: Embedded HTTP/CalDAV service running locally on `127.0.0.1:4242`.
- **Interoperability**: Allows native OS calendar tools (Outlook, Thunderbird, Android DAVx⁵) to read scheduled task blocks directly as standard calendar events without sending data to external cloud servers.
- **Protocol**: RFC 4791 (CalDAV) with RFC 5545 (iCalendar) event serialization.
- **Sync Direction**: Read-write — external calendar tools can create time blocks that appear in ChronoGrid, and ChronoGrid time blocks appear in external calendars.

View File

@ -2,12 +2,17 @@
## 1. Multi-Level Kanban Board
- Columns represent task status (acklog, in_progress, eview, completed).
- Horizontal swimlanes group tasks by
amespace_id or project_id.
- Dragging a card between columns updates its status field, triggering a CRDT state emission across active peers.
- Columns represent task status: `backlog`, `in_progress`, `review`, `completed`.
- Horizontal swimlanes group tasks by `namespace_id` or `project_id` (user-toggleable).
- Dragging a card between columns updates its `status` field, triggering a CRDT state emission across active peers.
- Column headers display task count and configurable WIP (Work-In-Progress) limit indicators.
- Cards display: title, priority score badge, due date chip, namespace color indicator, and tag chips.
## 2. Interactive Gantt Timeline
- Visualizes project milestones, task dependencies, and critical path progression.
- Supports fractional sub-project rendering, allowing infinite sub-task nesting.
- Supports fractional sub-project rendering, allowing infinite sub-task nesting via fractional index ordering.
- Task bars are draggable (reschedule) and resizable (change `estimated_duration`).
- Critical path tasks (zero slack) are highlighted in red.
- Zoom controls: day / week / month / quarter granularity.
- Dragging a task bar updates `due_date` and emits a CRDT mutation to all connected peers.

View File

@ -1,7 +1,38 @@
# Master User Story: Distributed, Local-First Productivity Engine
Refer to Master User Story specification for detailed acceptance criteria regarding:
**Canonical Reference:** `docs/ARCHITECTURE/04-master-user-story.md`
1. Multi-domain IMAP ingestion and local file watchers.
2. Serverless P2P CRDT sync across Windows, Linux, Android, and Headless nodes.
3. Multi-view display execution (Eisenhower Matrix, Time-Blocking Calendar, Kanban, Notes).
This document provides workflow-level summaries of the three primary execution domains. For full acceptance criteria and technical specifications, refer to the canonical master user story document above.
---
## 1. Multi-Domain Ingestion Workflows
The system automatically captures inputs from multiple distinct channels without requiring manual task entry:
- **IMAP Email Ingestion**: Background daemon polls personal, engineering, and commercial IMAP accounts over TLS. Flagged emails or messages forwarded to internal parse addresses are extracted as Markdown notes with linked tasks.
- **Global Desktop Jots**: System-wide hotkeys (Windows/Linux) invoke a lightweight command palette for instant plain-text jots. Android home-screen widgets and Share Intent receivers forward text, URLs, and voice notes.
- **Local File Watchers**: Background filesystem watchers monitor dedicated folders. Markdown files with `- [ ]` checkboxes automatically parse into tasks. PDFs and design briefs parse into linked project notes.
- **AI Processing Pipeline**: All raw inputs pass through the local NLP engine (regex + optional Ollama LLM) for namespace routing, task/note splitting, date extraction, and Eisenhower priority scoring.
---
## 2. Serverless P2P CRDT Synchronization
Data state changes are tracked via Hybrid Logical Clocks (HLC) and append-only CRDT deltas:
- **Local-First**: All data is written to the local SQLCipher database first. The app is fully functional offline.
- **Peer Discovery**: Nodes discover each other on LAN via mDNS (zero-config) and across WAN via libp2p Kademlia DHT with NAT hole-punching.
- **Delta Sync**: On reconnection, peers exchange vector clocks, compute missing deltas, compress and encrypt them, and stream over QUIC/Noise XK channels.
- **Convergence**: Automerge CRDT deterministic merge guarantees eventual consistency across all personal nodes (Windows, Android, Headless Server) without central server coordination.
---
## 3. Multi-View Display Execution
The Flutter presentation layer renders local database state into four specialized execution environments:
- **Eisenhower Priority Matrix**: Four-quadrant board auto-populated by computed urgency-importance scores. Tasks automatically migrate between quadrants as deadlines approach.
- **Calendar Time-Blocking Grid**: Drag-and-drop scheduling grid with CalDAV overlay for external calendar integration. Tasks reserve focus blocks with real-time duration adjustment.
- **Kanban / Gantt Views**: Status-column Kanban board with swimlane grouping; interactive Gantt timeline with critical path highlighting and fractional sub-task nesting.
- **Notes & Knowledge Workspace**: Rich Markdown editor with bidirectional task linking, project tree navigation, and Daily Jots aggregation.

View File

@ -1,38 +1,235 @@
# ==============================================================================
# ChronoGrid P2P - Agent Verification Pipeline
# Runs compilation and specification alignment checks
# ChronoGrid P2P - Agent Verification Pipeline v2
# Runs compilation, test, and specification alignment checks across all crates.
# Exit code 0 = all checks passed. Non-zero = failure.
# ==============================================================================
$ErrorActionPreference = "Continue"
$RootDir = "$PSScriptRoot\.."
$StartTime = Get-Date
$FailCount = 0
Write-Host "--- RUNNING AGENT VERIFICATION PIPELINE ---" -ForegroundColor Cyan
# 1. Check Rust Compilation for chronogrid_core
Write-Host "1. Checking chronogrid_core..." -ForegroundColor Yellow
Set-Location "$PSScriptRoot\..\crates\chronogrid_core"
cargo check --quiet
if ($LASTEXITCODE -ne 0) {
Write-Host "FAILED: Rust compilation errors detected in chronogrid_core." -ForegroundColor Red
Exit 1
# Locate cargo — try common install locations if not already on PATH
$CargoExe = "cargo"
if (-not (Get-Command cargo -ErrorAction SilentlyContinue)) {
$CandidatePaths = @(
"$env:USERPROFILE\.cargo\bin\cargo.exe",
"C:\Users\$env:USERNAME\.cargo\bin\cargo.exe",
"$env:LOCALAPPDATA\Programs\Rust\bin\cargo.exe"
)
foreach ($candidate in $CandidatePaths) {
if (Test-Path $candidate) {
$CargoExe = $candidate
$env:PATH = "$([System.IO.Path]::GetDirectoryName($candidate));$env:PATH"
Write-Host " INFO: Found cargo at $candidate" -ForegroundColor Yellow
break
}
}
if ($CargoExe -eq "cargo") {
Write-Host " WARN: cargo not found on PATH or common locations. Rust checks will be skipped." -ForegroundColor Yellow
Write-Host " Run this script from a terminal where 'cargo' is available." -ForegroundColor Yellow
}
}
# 2. Check Rust Compilation for chronogrid_ffi
Write-Host "2. Checking chronogrid_ffi..." -ForegroundColor Yellow
Set-Location "$PSScriptRoot\..\crates\chronogrid_ffi"
cargo check --quiet
if ($LASTEXITCODE -ne 0) {
Write-Host "FAILED: Rust compilation errors detected in chronogrid_ffi." -ForegroundColor Red
Exit 1
function Write-Step {
param([string]$Message)
$elapsed = [int]((Get-Date) - $StartTime).TotalSeconds
Write-Host "`n[${elapsed}s] $Message" -ForegroundColor Cyan
}
# 3. Check Flutter Code Formatting & Dependencies
Write-Host "3. Checking Flutter Shell..." -ForegroundColor Yellow
Set-Location "$PSScriptRoot\..\apps\chronogrid_flutter"
flutter analyze
if ($LASTEXITCODE -ne 0) {
Write-Host "FAILED: Flutter analysis errors detected." -ForegroundColor Red
Exit 1
function Write-Pass {
param([string]$Message)
Write-Host " PASS: $Message" -ForegroundColor Green
}
Write-Host "--- ALL VERIFICATION CHECKS PASSED SUCCESSFULLY ---" -ForegroundColor Green
function Write-Fail {
param([string]$Message)
Write-Host " FAIL: $Message" -ForegroundColor Red
$script:FailCount++
}
Write-Host "============================================================" -ForegroundColor Cyan
Write-Host " CHRONOGRID P2P - AGENT VERIFICATION PIPELINE v2" -ForegroundColor Cyan
Write-Host " $(Get-Date -Format 'yyyy-MM-dd HH:mm:ss')" -ForegroundColor Cyan
Write-Host "============================================================" -ForegroundColor Cyan
# --- 1. chronogrid_crypto ---
Write-Step "1. Checking chronogrid_crypto (compile + tests)..."
Set-Location "$RootDir\crates\chronogrid_crypto"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_crypto failed cargo check" }
else { Write-Pass "chronogrid_crypto compiles" }
cargo test --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_crypto tests failed" }
else { Write-Pass "chronogrid_crypto tests pass" }
# --- 2. chronogrid_core ---
Write-Step "2. Checking chronogrid_core (compile + tests)..."
Set-Location "$RootDir\crates\chronogrid_core"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_core failed cargo check" }
else { Write-Pass "chronogrid_core compiles" }
cargo test --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_core tests failed" }
else { Write-Pass "chronogrid_core tests pass" }
# --- 3. chronogrid_net ---
Write-Step "3. Checking chronogrid_net (compile + tests)..."
Set-Location "$RootDir\crates\chronogrid_net"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_net failed cargo check" }
else { Write-Pass "chronogrid_net compiles" }
cargo test --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_net tests failed" }
else { Write-Pass "chronogrid_net tests pass" }
# --- 4. chronogrid_ai ---
Write-Step "4. Checking chronogrid_ai (compile + tests)..."
Set-Location "$RootDir\crates\chronogrid_ai"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_ai failed cargo check" }
else { Write-Pass "chronogrid_ai compiles" }
cargo test --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_ai tests failed" }
else { Write-Pass "chronogrid_ai tests pass" }
# --- 5. chronogrid_ffi ---
Write-Step "5. Checking chronogrid_ffi (compile + tests)..."
Set-Location "$RootDir\crates\chronogrid_ffi"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_ffi failed cargo check" }
else { Write-Pass "chronogrid_ffi compiles" }
cargo test --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_ffi tests failed" }
else { Write-Pass "chronogrid_ffi tests pass" }
# --- 6. chronogrid_daemon (if scaffolded) ---
Write-Step "6. Checking chronogrid_daemon (if scaffolded)..."
$DaemonCargoToml = "$RootDir\apps\chronogrid_daemon\Cargo.toml"
if (Test-Path $DaemonCargoToml) {
Set-Location "$RootDir\apps\chronogrid_daemon"
cargo check --quiet 2>&1
if ($LASTEXITCODE -ne 0) { Write-Fail "chronogrid_daemon failed cargo check" }
else { Write-Pass "chronogrid_daemon compiles" }
} else {
Write-Host " SKIP: chronogrid_daemon not yet scaffolded (Task 2.7)" -ForegroundColor Yellow
}
# --- 7. Schema Validation ---
Write-Step "7. Validating schema.sql contains required tables..."
$SchemaPath = "$RootDir\docs\API_CONTRACTS\schema.sql"
$SchemaContent = Get-Content $SchemaPath -Raw
$RequiredTables = @(
"namespaces",
"projects",
"tasks",
"notes",
"task_note_links",
"ingestion_logs",
"crdt_docs"
)
$Phase2Tables = @(
"time_blocks",
"attachments",
"calendar_feeds",
"node_peers",
"automation_rules",
"ingestion_configs"
)
foreach ($table in $RequiredTables) {
if ($SchemaContent -match "CREATE TABLE IF NOT EXISTS $table") {
Write-Pass "Schema contains table: $table"
} else {
Write-Fail "Schema MISSING required table: $table"
}
}
$Phase2Count = 0
foreach ($table in $Phase2Tables) {
if ($SchemaContent -match "CREATE TABLE IF NOT EXISTS $table") {
$Phase2Count++
Write-Pass "Schema contains Phase 2 table: $table"
} else {
Write-Host " INFO: Phase 2 table not yet added: $table" -ForegroundColor Yellow
}
}
if ($Phase2Count -eq $Phase2Tables.Count) {
Write-Pass "All Phase 2 schema tables present ($Phase2Count/$($Phase2Tables.Count))"
} else {
Write-Host " INFO: $Phase2Count/$($Phase2Tables.Count) Phase 2 tables present (add remaining in Task 2.1)" -ForegroundColor Yellow
}
# --- 8. Flutter Analysis ---
Write-Step "8. Checking Flutter shell (analyze)..."
$FlutterDir = "$RootDir\apps\chronogrid_flutter"
if (Test-Path "$FlutterDir\pubspec.yaml") {
Set-Location $FlutterDir
flutter analyze --no-pub 2>&1
if ($LASTEXITCODE -ne 0) {
Write-Fail "Flutter analysis errors detected"
} else {
Write-Pass "Flutter analysis clean"
}
} else {
Write-Fail "Flutter pubspec.yaml not found at $FlutterDir"
}
# --- 9. FRB Codegen Output Check ---
Write-Step "9. Checking FRB codegen output (if generated)..."
$FrbGenerated = "$RootDir\crates\chronogrid_ffi\src\frb_generated.rs"
$DartGenerated = "$RootDir\apps\chronogrid_flutter\lib\src\rust\frb_generated.dart"
if (Test-Path $FrbGenerated) {
Write-Pass "FRB Rust generated file exists"
} else {
Write-Host " INFO: frb_generated.rs not yet generated (run: flutter_rust_bridge_codegen generate)" -ForegroundColor Yellow
}
if (Test-Path $DartGenerated) {
Write-Pass "FRB Dart generated file exists"
} else {
Write-Host " INFO: frb_generated.dart not yet generated (run: flutter_rust_bridge_codegen generate)" -ForegroundColor Yellow
}
# --- 10. DECISION_LOG.md Check ---
Write-Step "10. Checking DECISION_LOG.md is present and non-empty..."
$DecisionLog = "$RootDir\DECISION_LOG.md"
if (Test-Path $DecisionLog) {
$LogSize = (Get-Item $DecisionLog).Length
if ($LogSize -gt 500) {
Write-Pass "DECISION_LOG.md present ($LogSize bytes)"
} else {
Write-Fail "DECISION_LOG.md is suspiciously small ($LogSize bytes) - may be empty"
}
} else {
Write-Fail "DECISION_LOG.md not found"
}
# --- Summary ---
$Elapsed = [int]((Get-Date) - $StartTime).TotalSeconds
Write-Host "`n============================================================" -ForegroundColor Cyan
if ($FailCount -eq 0) {
Write-Host " ALL VERIFICATION CHECKS PASSED ($Elapsed seconds)" -ForegroundColor Green
Write-Host "============================================================" -ForegroundColor Cyan
Exit 0
} else {
Write-Host " $FailCount CHECK(S) FAILED ($Elapsed seconds)" -ForegroundColor Red
Write-Host " Fix all failures before committing." -ForegroundColor Red
Write-Host "============================================================" -ForegroundColor Cyan
Exit 1
}