refactor: restructure docs as submodule, add dev-docs/ and AGENTS.md
- Move ASPICE docs to chanoraapp/docs submodule at docs/ - Move development docs to dev-docs/ (superpowers, offline-knowledge, impl-mapping) - Add AGENTS.md with project conventions for AI agents - Add impl-mapping.md (SAD component → source file mapping) - Archive completed plans to dev-docs/superpowers/plans/_archived/ - Remove AGENTS.md from .gitignore (now tracked)
This commit is contained in:
@@ -0,0 +1,689 @@
|
||||
# Chanora Server Prefetch Crate Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Move server-resolution prefetch policy from `chanora_core` into a focused crate named `chanora_prefetch` without changing Flutter APIs, resolver behavior, protocol dialing behavior, or Android connect UX.
|
||||
|
||||
**Architecture:** Add `crates/chanora_prefetch` as a workspace member. The new crate owns normalization, single-entry TTL cache, generation rejection, resolver-backed async warming, and fresh exact-match lookup. `chanora_core` keeps the trust boundary for `ConnectConfig.resolved_address`, using the prefetcher only to populate one-time dial config while keeping stored/reconnect config sanitized.
|
||||
|
||||
**Tech Stack:** Rust workspace, `tokio`, `tracing`, `thiserror`, `chanora_resolver`, `chanora_core`, `chanora_protocol`, Flutter Android smoke via ADB.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Create `crates/chanora_prefetch/Cargo.toml`: package metadata and dependencies.
|
||||
- Create `crates/chanora_prefetch/src/lib.rs`: public `ServerPrefetcher`, public `ServerPrefetchError`, internal cache entry/state, resolver-backed prefetch logic, and unit tests.
|
||||
- Modify `Cargo.toml`: add `crates/chanora_prefetch` to workspace members and update the workspace layout comment.
|
||||
- Modify `core/chanora_core/Cargo.toml`: replace the direct `chanora_resolver` dependency with `chanora_prefetch`.
|
||||
- Modify `core/chanora_core/src/lib.rs`: remove private prefetch cache/resolver helpers, add `ServerPrefetcher`, delegate `prefetch_server_resolution`, and keep connect config sanitization tests.
|
||||
- Modify `Cargo.lock`: generated by `cargo test`/`cargo check` after adding the crate.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add `chanora_prefetch` Crate With Cache Policy Tests
|
||||
|
||||
**Files:**
|
||||
- Modify: `Cargo.toml`
|
||||
- Create: `crates/chanora_prefetch/Cargo.toml`
|
||||
- Create: `crates/chanora_prefetch/src/lib.rs`
|
||||
|
||||
- [ ] **Step 1: Add the workspace member and package files**
|
||||
|
||||
In top-level `Cargo.toml`, update the layout comment and members:
|
||||
|
||||
```toml
|
||||
# crates/chanora_prefetch — server-resolution prefetch cache/policy
|
||||
# crates/chanora_bridge/ — Flutter/Rust typed DTOs + glue
|
||||
```
|
||||
|
||||
```toml
|
||||
members = [
|
||||
"core/chanora_core",
|
||||
"crates/chanora_protocol",
|
||||
"crates/chanora_state",
|
||||
"crates/chanora_audio",
|
||||
"crates/chanora_storage",
|
||||
"crates/chanora_diagnostics",
|
||||
"crates/chanora_prefetch",
|
||||
"crates/chanora_bridge",
|
||||
"crates/chanora_resolver",
|
||||
]
|
||||
```
|
||||
|
||||
Create `crates/chanora_prefetch/Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[package]
|
||||
name = "chanora_prefetch"
|
||||
description = "Chanora — server-address prefetch cache and policy built on chanora_resolver."
|
||||
version.workspace = true
|
||||
edition.workspace = true
|
||||
rust-version.workspace = true
|
||||
authors.workspace = true
|
||||
license.workspace = true
|
||||
repository.workspace = true
|
||||
publish.workspace = true
|
||||
|
||||
[dependencies]
|
||||
chanora_resolver = { path = "../chanora_resolver" }
|
||||
thiserror.workspace = true
|
||||
tracing.workspace = true
|
||||
tokio = { version = "1", features = ["sync", "rt", "macros"] }
|
||||
|
||||
[features]
|
||||
test-support = []
|
||||
```
|
||||
|
||||
Create `crates/chanora_prefetch/src/lib.rs` with the initial crate implementation and tests:
|
||||
|
||||
```rust
|
||||
//! Server-address prefetch cache and policy for Chanora.
|
||||
//!
|
||||
//! This crate owns speculative server-resolution warming. It does not
|
||||
//! decide whether a connection should use a prefetched address; callers
|
||||
//! must still apply their own trust boundary before dialing.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
use std::sync::Arc;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use thiserror::Error;
|
||||
use tokio::sync::Mutex;
|
||||
use tracing::{info, warn};
|
||||
|
||||
const SERVER_PREFETCH_TTL: Duration = Duration::from_secs(120);
|
||||
|
||||
#[derive(Debug, Error)]
|
||||
pub enum ServerPrefetchError {
|
||||
#[error("resolver initialization failed: {0}")]
|
||||
ResolverInit(String),
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ServerPrefetchEntry {
|
||||
normalized_host: String,
|
||||
resolved_address: SocketAddr,
|
||||
completed_at: Instant,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ServerPrefetchCache {
|
||||
latest_generation: u64,
|
||||
entry: Option<ServerPrefetchEntry>,
|
||||
last_failure: Option<String>,
|
||||
}
|
||||
|
||||
impl ServerPrefetchCache {
|
||||
fn begin(&mut self, host: &str) -> u64 {
|
||||
if normalize_host(host).is_empty() {
|
||||
return self.latest_generation;
|
||||
}
|
||||
self.latest_generation = self.latest_generation.saturating_add(1);
|
||||
self.last_failure = None;
|
||||
self.latest_generation
|
||||
}
|
||||
|
||||
fn store_success(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
host: &str,
|
||||
resolved_address: SocketAddr,
|
||||
completed_at: Instant,
|
||||
) {
|
||||
if generation != self.latest_generation {
|
||||
return;
|
||||
}
|
||||
self.entry = Some(ServerPrefetchEntry {
|
||||
normalized_host: normalize_host(host),
|
||||
resolved_address,
|
||||
completed_at,
|
||||
generation,
|
||||
});
|
||||
self.last_failure = None;
|
||||
}
|
||||
|
||||
fn store_failure(&mut self, generation: u64, error: String) {
|
||||
if generation != self.latest_generation {
|
||||
return;
|
||||
}
|
||||
self.last_failure = Some(error);
|
||||
}
|
||||
|
||||
fn fresh_match(&self, host: &str, now: Instant) -> Option<SocketAddr> {
|
||||
let normalized = normalize_host(host);
|
||||
let entry = self.entry.as_ref()?;
|
||||
if entry.normalized_host != normalized {
|
||||
return None;
|
||||
}
|
||||
if entry.generation != self.latest_generation {
|
||||
return None;
|
||||
}
|
||||
if now.duration_since(entry.completed_at) > SERVER_PREFETCH_TTL {
|
||||
return None;
|
||||
}
|
||||
Some(entry.resolved_address)
|
||||
}
|
||||
}
|
||||
|
||||
#[derive(Debug, Clone, Default)]
|
||||
pub struct ServerPrefetcher {
|
||||
cache: Arc<Mutex<ServerPrefetchCache>>,
|
||||
}
|
||||
|
||||
impl ServerPrefetcher {
|
||||
pub fn new() -> Self {
|
||||
Self::default()
|
||||
}
|
||||
|
||||
pub async fn prefetch(&self, host: String) -> Result<(), ServerPrefetchError> {
|
||||
let normalized = normalize_host(&host);
|
||||
if normalized.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let generation = {
|
||||
let mut cache = self.cache.lock().await;
|
||||
cache.begin(&normalized)
|
||||
};
|
||||
let cache = self.cache.clone();
|
||||
tokio::spawn(async move {
|
||||
info!(target: "chanora_prefetch", host = %normalized, "resolution prefetch started");
|
||||
let result = resolve_socket(&normalized).await;
|
||||
let mut guard = cache.lock().await;
|
||||
match result {
|
||||
Ok(addr) => {
|
||||
info!(
|
||||
target: "chanora_prefetch",
|
||||
host = %normalized,
|
||||
resolved = %addr,
|
||||
"resolution prefetch result"
|
||||
);
|
||||
guard.store_success(generation, &normalized, addr, Instant::now());
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
target: "chanora_prefetch",
|
||||
host = %normalized,
|
||||
error = %err,
|
||||
"resolution prefetch failed"
|
||||
);
|
||||
guard.store_failure(generation, err.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
|
||||
pub async fn fresh_match(&self, host: &str) -> Option<SocketAddr> {
|
||||
let resolved = {
|
||||
let cache = self.cache.lock().await;
|
||||
cache.fresh_match(host, Instant::now())
|
||||
};
|
||||
match resolved {
|
||||
Some(addr) => {
|
||||
info!(
|
||||
target: "chanora_prefetch",
|
||||
host = %host,
|
||||
resolved = %addr,
|
||||
"connect using prefetched resolution"
|
||||
);
|
||||
Some(addr)
|
||||
}
|
||||
None => {
|
||||
info!(target: "chanora_prefetch", host = %host, "connect prefetch miss or stale");
|
||||
None
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub async fn begin_for_test(&self, host: &str) -> u64 {
|
||||
let mut cache = self.cache.lock().await;
|
||||
cache.begin(host)
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub async fn store_success_for_test(
|
||||
&self,
|
||||
generation: u64,
|
||||
host: &str,
|
||||
resolved_address: SocketAddr,
|
||||
completed_at: Instant,
|
||||
) {
|
||||
let mut cache = self.cache.lock().await;
|
||||
cache.store_success(generation, host, resolved_address, completed_at);
|
||||
}
|
||||
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub async fn latest_generation_for_test(&self) -> u64 {
|
||||
let cache = self.cache.lock().await;
|
||||
cache.latest_generation
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_host(host: &str) -> String {
|
||||
host.trim().to_lowercase()
|
||||
}
|
||||
|
||||
async fn resolve_socket(host: &str) -> Result<SocketAddr, ServerPrefetchError> {
|
||||
let resolver = chanora_resolver::ChanoraResolver::new()
|
||||
.map_err(|err| ServerPrefetchError::ResolverInit(err.to_string()))?;
|
||||
let resolved = resolver
|
||||
.resolve_client_address(host)
|
||||
.await
|
||||
.map_err(|err| ServerPrefetchError::ResolverInit(err.to_string()))?;
|
||||
Ok(resolved.connection_addr())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[tokio::test]
|
||||
async fn fresh_exact_match_returns_socket_address() {
|
||||
let prefetcher = ServerPrefetcher::new();
|
||||
let generation = prefetcher.begin_for_test(" Example.COM ").await;
|
||||
let addr = "127.0.0.1:9987".parse().unwrap();
|
||||
prefetcher
|
||||
.store_success_for_test(generation, "example.com", addr, Instant::now())
|
||||
.await;
|
||||
|
||||
assert_eq!(prefetcher.fresh_match("example.com").await, Some(addr));
|
||||
assert_eq!(prefetcher.fresh_match(" EXAMPLE.com ").await, Some(addr));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_entries_are_ignored() {
|
||||
let prefetcher = ServerPrefetcher::new();
|
||||
let generation = prefetcher.begin_for_test("example.com").await;
|
||||
let addr = "127.0.0.1:9987".parse().unwrap();
|
||||
prefetcher
|
||||
.store_success_for_test(
|
||||
generation,
|
||||
"example.com",
|
||||
addr,
|
||||
Instant::now() - SERVER_PREFETCH_TTL - Duration::from_secs(1),
|
||||
)
|
||||
.await;
|
||||
|
||||
assert_eq!(prefetcher.fresh_match("example.com").await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn different_hosts_are_ignored() {
|
||||
let prefetcher = ServerPrefetcher::new();
|
||||
let generation = prefetcher.begin_for_test("example.com").await;
|
||||
let addr = "127.0.0.1:9987".parse().unwrap();
|
||||
prefetcher
|
||||
.store_success_for_test(generation, "example.com", addr, Instant::now())
|
||||
.await;
|
||||
|
||||
assert_eq!(prefetcher.fresh_match("other.example.com").await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_generation_completions_are_ignored() {
|
||||
let prefetcher = ServerPrefetcher::new();
|
||||
let old_generation = prefetcher.begin_for_test("old.example.com").await;
|
||||
let _new_generation = prefetcher.begin_for_test("new.example.com").await;
|
||||
let old_addr = "127.0.0.1:9987".parse().unwrap();
|
||||
prefetcher
|
||||
.store_success_for_test(old_generation, "old.example.com", old_addr, Instant::now())
|
||||
.await;
|
||||
|
||||
assert_eq!(prefetcher.fresh_match("old.example.com").await, None);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn blank_hosts_do_not_update_generation() {
|
||||
let prefetcher = ServerPrefetcher::new();
|
||||
let before = prefetcher.latest_generation_for_test().await;
|
||||
|
||||
prefetcher.prefetch(" ".to_string()).await.unwrap();
|
||||
|
||||
assert_eq!(prefetcher.latest_generation_for_test().await, before);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run new crate tests**
|
||||
|
||||
Run: `cargo test -p chanora_prefetch --lib`
|
||||
|
||||
Expected: the new crate compiles and all 5 tests pass.
|
||||
|
||||
- [ ] **Step 3: Commit Task 1**
|
||||
|
||||
```bash
|
||||
git add Cargo.toml Cargo.lock crates/chanora_prefetch
|
||||
git commit -m "feat(prefetch): add server prefetch crate"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Wire Core to `ServerPrefetcher`
|
||||
|
||||
**Files:**
|
||||
- Modify: `core/chanora_core/Cargo.toml`
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
|
||||
- [ ] **Step 1: Replace the core dependency**
|
||||
|
||||
In `core/chanora_core/Cargo.toml`, replace:
|
||||
|
||||
```toml
|
||||
chanora_resolver = { path = "../../crates/chanora_resolver" }
|
||||
```
|
||||
|
||||
with:
|
||||
|
||||
```toml
|
||||
chanora_prefetch = { path = "../../crates/chanora_prefetch" }
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Remove private prefetch cache implementation from core**
|
||||
|
||||
In `core/chanora_core/src/lib.rs`, remove these private items:
|
||||
|
||||
```rust
|
||||
const RESOLUTION_PREFETCH_TTL: Duration = Duration::from_secs(120);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ResolutionPrefetchEntry { ... }
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ResolutionPrefetchCache { ... }
|
||||
|
||||
impl ResolutionPrefetchCache { ... }
|
||||
|
||||
fn normalize_prefetch_host(host: &str) -> String { ... }
|
||||
|
||||
async fn resolve_prefetch_socket(host: &str) -> Result<std::net::SocketAddr, CoreError> { ... }
|
||||
```
|
||||
|
||||
Add this import near the other crate imports:
|
||||
|
||||
```rust
|
||||
use chanora_prefetch::ServerPrefetcher;
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Replace the session field and constructor initialization**
|
||||
|
||||
Change the `ChanoraSession` field from:
|
||||
|
||||
```rust
|
||||
resolution_prefetch: Arc<Mutex<ResolutionPrefetchCache>>,
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```rust
|
||||
server_prefetch: ServerPrefetcher,
|
||||
```
|
||||
|
||||
Change the constructor initialization from:
|
||||
|
||||
```rust
|
||||
resolution_prefetch: Arc::new(Mutex::new(ResolutionPrefetchCache::default())),
|
||||
```
|
||||
|
||||
to:
|
||||
|
||||
```rust
|
||||
server_prefetch: ServerPrefetcher::new(),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Delegate prefetch and fresh-match lookup**
|
||||
|
||||
Replace `prefetch_server_resolution` with:
|
||||
|
||||
```rust
|
||||
pub async fn prefetch_server_resolution(&self, host: String) -> Result<(), CoreError> {
|
||||
self.server_prefetch
|
||||
.prefetch(host)
|
||||
.await
|
||||
.map_err(|err| CoreError::Protocol(chanora_protocol::ProtocolError::DnsFailed {
|
||||
host: "prefetch".to_string(),
|
||||
reason: err.to_string(),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
Replace `apply_prefetched_resolution` with:
|
||||
|
||||
```rust
|
||||
async fn apply_prefetched_resolution(&self, cfg: &mut ConnectConfig) {
|
||||
cfg.resolved_address = None;
|
||||
let host = cfg.address.trim();
|
||||
if host.is_empty() {
|
||||
return;
|
||||
}
|
||||
if let Some(addr) = self.server_prefetch.fresh_match(host).await {
|
||||
cfg.resolved_address = Some(addr);
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
Keep `prepare_connect_configs` unchanged except that it calls the updated `apply_prefetched_resolution`.
|
||||
|
||||
- [ ] **Step 5: Update core tests to use the prefetcher seam**
|
||||
|
||||
Keep these existing core tests:
|
||||
|
||||
```rust
|
||||
session_clears_untrusted_prefetched_resolution_on_cache_miss
|
||||
connect_config_without_prefetched_resolution_clears_only_resolved_address
|
||||
connect_config_preparation_keeps_prefetched_address_out_of_stored_config
|
||||
```
|
||||
|
||||
Replace any direct access to `session.resolution_prefetch` with calls to public test-support methods on `ServerPrefetcher`. In `crates/chanora_prefetch/src/lib.rs`, keep these methods gated with `#[cfg(any(test, feature = "test-support"))]`:
|
||||
|
||||
```rust
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub async fn store_success_for_test(
|
||||
&self,
|
||||
generation: u64,
|
||||
host: &str,
|
||||
resolved_address: SocketAddr,
|
||||
completed_at: Instant,
|
||||
)
|
||||
```
|
||||
|
||||
and:
|
||||
|
||||
```rust
|
||||
#[cfg(any(test, feature = "test-support"))]
|
||||
pub async fn begin_for_test(&self, host: &str) -> u64
|
||||
```
|
||||
|
||||
Enable the feature for `chanora_core` tests by adding this dev-dependency in `core/chanora_core/Cargo.toml`:
|
||||
|
||||
```toml
|
||||
[dev-dependencies]
|
||||
chanora_prefetch = { path = "../../crates/chanora_prefetch", features = ["test-support"] }
|
||||
```
|
||||
|
||||
Then core test setup should look like:
|
||||
|
||||
```rust
|
||||
let generation = session.server_prefetch.begin_for_test("example.com").await;
|
||||
session
|
||||
.server_prefetch
|
||||
.store_success_for_test(generation, "example.com", cached, std::time::Instant::now())
|
||||
.await;
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run core tests and fix compile errors**
|
||||
|
||||
Run: `cargo test -p chanora_core --lib`
|
||||
|
||||
Expected: all core lib tests pass.
|
||||
|
||||
- [ ] **Step 7: Commit Task 2**
|
||||
|
||||
```bash
|
||||
git add Cargo.toml Cargo.lock core/chanora_core/Cargo.toml core/chanora_core/src/lib.rs crates/chanora_prefetch
|
||||
git commit -m "refactor(core): use server prefetch crate"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Remove Duplicated Core Cache Tests and Verify Protocol Is Unchanged
|
||||
|
||||
**Files:**
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
- Inspect only: `crates/chanora_protocol/src/adapter.rs`
|
||||
|
||||
- [ ] **Step 1: Remove core tests moved to the prefetch crate**
|
||||
|
||||
Delete these tests from `core/chanora_core/src/lib.rs` because they now belong in `chanora_prefetch`:
|
||||
|
||||
```rust
|
||||
resolution_prefetch_cache_returns_fresh_exact_match
|
||||
resolution_prefetch_cache_ignores_stale_entries
|
||||
resolution_prefetch_cache_ignores_different_hosts
|
||||
resolution_prefetch_cache_ignores_stale_generation_completion
|
||||
```
|
||||
|
||||
Do not delete core trust-boundary tests:
|
||||
|
||||
```rust
|
||||
session_uses_fresh_prefetched_resolution_for_connect_config
|
||||
session_clears_untrusted_prefetched_resolution_on_cache_miss
|
||||
connect_config_without_prefetched_resolution_clears_only_resolved_address
|
||||
connect_config_preparation_keeps_prefetched_address_out_of_stored_config
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Confirm protocol source is untouched**
|
||||
|
||||
Run: `git diff -- crates/chanora_protocol/src/adapter.rs`
|
||||
|
||||
Expected: no diff. If there is a diff, revert only accidental protocol edits by manually restoring the changed lines from `HEAD`; do not use destructive git checkout/reset.
|
||||
|
||||
- [ ] **Step 3: Run combined Rust tests**
|
||||
|
||||
Run: `cargo test -p chanora_prefetch -p chanora_core -p chanora_protocol --lib`
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 4: Commit Task 3**
|
||||
|
||||
```bash
|
||||
git add core/chanora_core/src/lib.rs Cargo.lock
|
||||
git commit -m "test(core): keep prefetch tests at crate boundary"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Final Verification and Android Smoke
|
||||
|
||||
**Files:**
|
||||
- No source edits expected.
|
||||
|
||||
- [ ] **Step 1: Run full focused Rust verification**
|
||||
|
||||
Run: `cargo test -p chanora_resolver -p chanora_prefetch -p chanora_protocol -p chanora_core --lib`
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 2: Run focused Flutter tests**
|
||||
|
||||
Run from `apps/chanora_flutter`:
|
||||
|
||||
```bash
|
||||
flutter test test/services/server_resolution_prefetch_scheduler_test.dart test/services/connection_phase_state_test.dart test/services/ts3_server_link_test.dart
|
||||
```
|
||||
|
||||
Expected: all tests pass.
|
||||
|
||||
- [ ] **Step 3: Build Android APK**
|
||||
|
||||
Run from `apps/chanora_flutter`:
|
||||
|
||||
```bash
|
||||
flutter build apk --debug
|
||||
```
|
||||
|
||||
Expected: build succeeds and produces `build/app/outputs/flutter-apk/app-debug.apk`.
|
||||
|
||||
- [ ] **Step 4: Run fresh-launch Android prefetch/connect smoke**
|
||||
|
||||
Run from `apps/chanora_flutter` with an emulator/device attached:
|
||||
|
||||
```bash
|
||||
adb install -r "build/app/outputs/flutter-apk/app-debug.apk"
|
||||
adb shell am force-stop app.chanora.chanora_flutter
|
||||
adb logcat -c
|
||||
adb shell monkey -p app.chanora.chanora_flutter -c android.intent.category.LAUNCHER 1
|
||||
sleep 5
|
||||
adb shell input tap 354 1363
|
||||
sleep 8
|
||||
adb logcat -d -v time | rg "resolution prefetch|prefetched|client request resolution|server address resolved|FATAL|AndroidRuntime|ANR"
|
||||
adb shell uiautomator dump /sdcard/window.xml
|
||||
adb exec-out cat /sdcard/window.xml
|
||||
```
|
||||
|
||||
Expected logs include:
|
||||
|
||||
```text
|
||||
resolution prefetch started
|
||||
resolution prefetch result
|
||||
connect using prefetched resolution
|
||||
using prefetched server address
|
||||
```
|
||||
|
||||
Expected UI hierarchy includes:
|
||||
|
||||
```text
|
||||
Vigorous Pro
|
||||
Leave server
|
||||
Default Channel
|
||||
ChanoraBeta
|
||||
```
|
||||
|
||||
No app `FATAL`, app `AndroidRuntime` crash, or `ANR` lines should appear. `AndroidRuntime` lines from `monkey` or `uiautomator` are not app crashes.
|
||||
|
||||
- [ ] **Step 5: Run one channel switch smoke**
|
||||
|
||||
With the app still connected, run:
|
||||
|
||||
```bash
|
||||
adb logcat -c
|
||||
adb shell input tap 300 1705
|
||||
sleep 2
|
||||
adb shell input tap 300 1465
|
||||
sleep 2
|
||||
adb logcat -d -v time | rg "voice_join|client_move|FATAL|AndroidRuntime|ANR"
|
||||
adb shell uiautomator dump /sdcard/window.xml
|
||||
adb exec-out cat /sdcard/window.xml
|
||||
```
|
||||
|
||||
Expected logs include successful moves to channel IDs similar to:
|
||||
|
||||
```text
|
||||
voice_join accepted by server
|
||||
client_move resolved by authoritative self channel change
|
||||
```
|
||||
|
||||
Expected final UI has `ChanoraBeta` under `Default Channel`.
|
||||
|
||||
- [ ] **Step 6: Check final git state**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
git log --oneline -5
|
||||
```
|
||||
|
||||
Expected: only unrelated untracked `config.json` remains, unless the user has added other unrelated work. The latest commits should be the prefetch crate split commits.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: the plan adds `chanora_prefetch`, moves cache policy and resolver-backed warming there, keeps core as trust boundary, preserves Flutter/protocol behavior, and includes Android connect smoke verification.
|
||||
- Placeholder scan: no `TBD`, `TODO`, or unspecified edge handling remains.
|
||||
- Type consistency: the plan uses `ServerPrefetcher`, `ServerPrefetchError`, `prefetch`, and `fresh_match` consistently across crate and core tasks.
|
||||
@@ -0,0 +1,899 @@
|
||||
# Server Resolution Prefetch Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add invisible server-address resolution prefetch so the active host field can warm Rust resolver state before Connect without changing connection semantics.
|
||||
|
||||
**Architecture:** Flutter schedules debounced prefetch calls for the active host field only. Rust owns resolution prefetch state, TTL, exact-match validation, and connect-time reuse. The protocol layer accepts an optional already-resolved socket address so Connect can skip resolver work only when the core cache says it is safe.
|
||||
|
||||
**Tech Stack:** Flutter/Dart, flutter_rust_bridge generated bindings, Rust async Tokio, `chanora_core`, `chanora_protocol`, `chanora_resolver`, Flutter widget/service tests, Rust unit tests.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
- Modify `core/chanora_core/src/lib.rs`: add a session-owned prefetch cache, prefetch API, connect-time cache lookup, and unit tests for TTL/exact-match/generation behavior.
|
||||
- Modify `crates/chanora_protocol/src/adapter.rs`: add `resolved_address: Option<SocketAddr>` to `ConnectConfig` and skip `resolve_server_socket()` when present.
|
||||
- Modify `crates/chanora_bridge/src/api.rs`: add `prefetch_server_resolution(host: String)` bridge function and pass cache-aware connects through `ChanoraSession`.
|
||||
- Regenerate `crates/chanora_bridge/src/frb_generated.rs`: generated Rust bridge bindings.
|
||||
- Regenerate `apps/chanora_flutter/lib/src/rust/api.dart`, `api.freezed.dart`, and `frb_generated.dart`: generated Dart bridge bindings.
|
||||
- Create `apps/chanora_flutter/lib/services/server_resolution_prefetch_scheduler.dart`: small testable debounce helper for host-field prefetch scheduling.
|
||||
- Modify `apps/chanora_flutter/lib/main.dart`: wire `_hostCtl` listener, settings-loaded prefetch, and disposal.
|
||||
- Create `apps/chanora_flutter/test/services/server_resolution_prefetch_scheduler_test.dart`: Flutter/Dart tests for debounce and empty-host behavior.
|
||||
|
||||
Keep all prefetch UI invisible. Do not prefetch bookmarks in bulk.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Protocol Config Accepts Prefetched Socket
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/chanora_protocol/src/adapter.rs`
|
||||
|
||||
- [ ] **Step 1: Add a failing protocol config test**
|
||||
|
||||
Add this test inside the existing `#[cfg(test)] mod tests` in `crates/chanora_protocol/src/adapter.rs`:
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn connect_config_can_carry_prefetched_socket_address() {
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
let cfg = ConnectConfig {
|
||||
address: "example.com".to_string(),
|
||||
nickname: "Tester".to_string(),
|
||||
password: None,
|
||||
identity: None,
|
||||
ready_timeout: Duration::from_secs(1),
|
||||
resolved_address: Some(addr),
|
||||
};
|
||||
|
||||
assert_eq!(cfg.resolved_address, Some(addr));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `cargo test -p chanora_protocol connect_config_can_carry_prefetched_socket_address`
|
||||
|
||||
Expected: FAIL to compile with a message like `struct ConnectConfig has no field named resolved_address`.
|
||||
|
||||
- [ ] **Step 3: Add the minimal config field**
|
||||
|
||||
Update `ConnectConfig` in `crates/chanora_protocol/src/adapter.rs`:
|
||||
|
||||
```rust
|
||||
#[derive(Debug, Clone)]
|
||||
pub struct ConnectConfig {
|
||||
/// Server address: `hostname[:port]` or TSDNS name.
|
||||
pub address: String,
|
||||
/// Optional already-resolved socket address from core's invisible
|
||||
/// prefetch cache. When present, the protocol layer skips address
|
||||
/// resolution but still opens a normal TS3 connection only after
|
||||
/// the user requested Connect.
|
||||
pub resolved_address: Option<std::net::SocketAddr>,
|
||||
/// Nickname to use on the server.
|
||||
pub nickname: String,
|
||||
/// Optional server password.
|
||||
pub password: Option<String>,
|
||||
/// Optional pre-existing identity (base64 string accepted by
|
||||
/// `tsclientlib::Identity::new_from_str`). If `None`, a fresh
|
||||
/// identity is generated and **not persisted** — production callers
|
||||
/// should provide one from secure identity storage.
|
||||
pub identity: Option<String>,
|
||||
/// How long to wait for the initial state snapshot before
|
||||
/// returning `ProtocolError::Timeout`.
|
||||
pub ready_timeout: Duration,
|
||||
}
|
||||
|
||||
impl Default for ConnectConfig {
|
||||
fn default() -> Self {
|
||||
Self {
|
||||
address: String::new(),
|
||||
resolved_address: None,
|
||||
nickname: "Chanora".to_string(),
|
||||
password: None,
|
||||
identity: None,
|
||||
ready_timeout: Duration::from_secs(10),
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run the focused test**
|
||||
|
||||
Run: `cargo test -p chanora_protocol connect_config_can_carry_prefetched_socket_address`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/chanora_protocol/src/adapter.rs
|
||||
git commit -m "feat(protocol): accept prefetched server address"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Protocol Connect Skips Resolver On Prefetch Hit
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/chanora_protocol/src/adapter.rs`
|
||||
|
||||
- [ ] **Step 1: Add a failing helper test**
|
||||
|
||||
Add a private helper next to `resolve_server_socket()` only after this failing test is added. First add this test in `#[cfg(test)] mod tests`:
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn server_socket_from_config_prefers_prefetched_address() {
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
let cfg = ConnectConfig {
|
||||
address: "example.com".to_string(),
|
||||
resolved_address: Some(addr),
|
||||
nickname: "Tester".to_string(),
|
||||
password: None,
|
||||
identity: None,
|
||||
ready_timeout: Duration::from_secs(1),
|
||||
};
|
||||
|
||||
assert_eq!(server_socket_from_config(&cfg), Some(addr));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `cargo test -p chanora_protocol server_socket_from_config_prefers_prefetched_address`
|
||||
|
||||
Expected: FAIL to compile with `cannot find function server_socket_from_config`.
|
||||
|
||||
- [ ] **Step 3: Add the helper and wire connection task**
|
||||
|
||||
Add this helper near `resolve_server_socket()`:
|
||||
|
||||
```rust
|
||||
fn server_socket_from_config(cfg: &ConnectConfig) -> Option<SocketAddr> {
|
||||
cfg.resolved_address
|
||||
}
|
||||
```
|
||||
|
||||
Find the call in `connection_task` that currently resolves the address, shaped like:
|
||||
|
||||
```rust
|
||||
let server = resolve_server_socket(&cfg.address).await?;
|
||||
```
|
||||
|
||||
Replace it with:
|
||||
|
||||
```rust
|
||||
let server = match server_socket_from_config(&cfg) {
|
||||
Some(addr) => {
|
||||
info!(
|
||||
target: "chanora_protocol",
|
||||
input = %cfg.address,
|
||||
resolved = %addr,
|
||||
"using prefetched server address"
|
||||
);
|
||||
addr
|
||||
}
|
||||
None => resolve_server_socket(&cfg.address).await?,
|
||||
};
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run protocol tests**
|
||||
|
||||
Run: `cargo test -p chanora_protocol server_socket_from_config_prefers_prefetched_address`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Run broader protocol tests**
|
||||
|
||||
Run: `cargo test -p chanora_protocol`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/chanora_protocol/src/adapter.rs
|
||||
git commit -m "fix(protocol): reuse prefetched server address"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Core Prefetch Cache Data Model
|
||||
|
||||
**Files:**
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
|
||||
- [ ] **Step 1: Write failing cache tests**
|
||||
|
||||
Add these tests inside `#[cfg(test)] mod tests` in `core/chanora_core/src/lib.rs`:
|
||||
|
||||
```rust
|
||||
#[test]
|
||||
fn resolution_prefetch_cache_returns_fresh_exact_match() {
|
||||
let mut cache = ResolutionPrefetchCache::default();
|
||||
let now = std::time::Instant::now();
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
let generation = cache.begin(" Example.COM ");
|
||||
cache.store_success(generation, " Example.COM ", addr, now);
|
||||
|
||||
assert_eq!(cache.fresh_match("example.com", now), Some(addr));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_prefetch_cache_ignores_stale_entries() {
|
||||
let mut cache = ResolutionPrefetchCache::default();
|
||||
let now = std::time::Instant::now();
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
let generation = cache.begin("example.com");
|
||||
cache.store_success(generation, "example.com", addr, now - RESOLUTION_PREFETCH_TTL - std::time::Duration::from_secs(1));
|
||||
|
||||
assert_eq!(cache.fresh_match("example.com", now), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_prefetch_cache_ignores_different_hosts() {
|
||||
let mut cache = ResolutionPrefetchCache::default();
|
||||
let now = std::time::Instant::now();
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
let generation = cache.begin("example.com");
|
||||
cache.store_success(generation, "example.com", addr, now);
|
||||
|
||||
assert_eq!(cache.fresh_match("other.example.com", now), None);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn resolution_prefetch_cache_ignores_stale_generation_completion() {
|
||||
let mut cache = ResolutionPrefetchCache::default();
|
||||
let now = std::time::Instant::now();
|
||||
let first: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
let second: std::net::SocketAddr = "127.0.0.2:9987".parse().unwrap();
|
||||
|
||||
let old_generation = cache.begin("example.com");
|
||||
let new_generation = cache.begin("example.com");
|
||||
cache.store_success(new_generation, "example.com", second, now);
|
||||
cache.store_success(old_generation, "example.com", first, now);
|
||||
|
||||
assert_eq!(cache.fresh_match("example.com", now), Some(second));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `cargo test -p chanora_core resolution_prefetch_cache --lib`
|
||||
|
||||
Expected: FAIL to compile with missing `ResolutionPrefetchCache` and `RESOLUTION_PREFETCH_TTL`.
|
||||
|
||||
- [ ] **Step 3: Add the cache model**
|
||||
|
||||
Add near `NetworkDiagnostics` in `core/chanora_core/src/lib.rs`:
|
||||
|
||||
```rust
|
||||
const RESOLUTION_PREFETCH_TTL: Duration = Duration::from_secs(120);
|
||||
|
||||
#[derive(Debug, Clone)]
|
||||
struct ResolutionPrefetchEntry {
|
||||
normalized_host: String,
|
||||
resolved_address: std::net::SocketAddr,
|
||||
completed_at: std::time::Instant,
|
||||
generation: u64,
|
||||
}
|
||||
|
||||
#[derive(Debug, Default)]
|
||||
struct ResolutionPrefetchCache {
|
||||
latest_generation: u64,
|
||||
entry: Option<ResolutionPrefetchEntry>,
|
||||
last_failure: Option<String>,
|
||||
}
|
||||
|
||||
impl ResolutionPrefetchCache {
|
||||
fn begin(&mut self, host: &str) -> u64 {
|
||||
self.latest_generation = self.latest_generation.saturating_add(1);
|
||||
self.last_failure = None;
|
||||
let _ = normalize_prefetch_host(host);
|
||||
self.latest_generation
|
||||
}
|
||||
|
||||
fn store_success(
|
||||
&mut self,
|
||||
generation: u64,
|
||||
host: &str,
|
||||
resolved_address: std::net::SocketAddr,
|
||||
completed_at: std::time::Instant,
|
||||
) {
|
||||
if generation != self.latest_generation {
|
||||
return;
|
||||
}
|
||||
self.entry = Some(ResolutionPrefetchEntry {
|
||||
normalized_host: normalize_prefetch_host(host),
|
||||
resolved_address,
|
||||
completed_at,
|
||||
generation,
|
||||
});
|
||||
self.last_failure = None;
|
||||
}
|
||||
|
||||
fn store_failure(&mut self, generation: u64, error: String) {
|
||||
if generation != self.latest_generation {
|
||||
return;
|
||||
}
|
||||
self.last_failure = Some(error);
|
||||
}
|
||||
|
||||
fn fresh_match(&self, host: &str, now: std::time::Instant) -> Option<std::net::SocketAddr> {
|
||||
let normalized = normalize_prefetch_host(host);
|
||||
let entry = self.entry.as_ref()?;
|
||||
if entry.normalized_host != normalized {
|
||||
return None;
|
||||
}
|
||||
if now.duration_since(entry.completed_at) > RESOLUTION_PREFETCH_TTL {
|
||||
return None;
|
||||
}
|
||||
Some(entry.resolved_address)
|
||||
}
|
||||
}
|
||||
|
||||
fn normalize_prefetch_host(host: &str) -> String {
|
||||
host.trim().to_lowercase()
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run focused core tests**
|
||||
|
||||
Run: `cargo test -p chanora_core resolution_prefetch_cache --lib`
|
||||
|
||||
Expected: all four tests PASS.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add core/chanora_core/src/lib.rs
|
||||
git commit -m "feat(core): add resolution prefetch cache"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Core Prefetch API And Connect Cache Lookup
|
||||
|
||||
**Files:**
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
|
||||
- [ ] **Step 1: Write failing session tests**
|
||||
|
||||
Add this test in `#[cfg(test)] mod tests` in `core/chanora_core/src/lib.rs`:
|
||||
|
||||
```rust
|
||||
#[tokio::test]
|
||||
async fn session_uses_fresh_prefetched_resolution_for_connect_config() {
|
||||
let session = ChanoraSession::new();
|
||||
let addr: std::net::SocketAddr = "127.0.0.1:9987".parse().unwrap();
|
||||
|
||||
{
|
||||
let mut cache = session.resolution_prefetch.lock().await;
|
||||
let generation = cache.begin("example.com");
|
||||
cache.store_success(generation, "example.com", addr, std::time::Instant::now());
|
||||
}
|
||||
|
||||
let mut cfg = ConnectConfig::default();
|
||||
cfg.address = " example.com ".to_string();
|
||||
session.apply_prefetched_resolution(&mut cfg).await;
|
||||
|
||||
assert_eq!(cfg.resolved_address, Some(addr));
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run the test to verify it fails**
|
||||
|
||||
Run: `cargo test -p chanora_core session_uses_fresh_prefetched_resolution_for_connect_config --lib`
|
||||
|
||||
Expected: FAIL to compile with missing `resolution_prefetch` and `apply_prefetched_resolution`.
|
||||
|
||||
- [ ] **Step 3: Add session field and constructor initialization**
|
||||
|
||||
Add to `ChanoraSession`:
|
||||
|
||||
```rust
|
||||
/// Invisible server-address prefetch cache. Warmed by Flutter typing
|
||||
/// but validated by Rust before Connect can reuse it.
|
||||
resolution_prefetch: Arc<Mutex<ResolutionPrefetchCache>>,
|
||||
```
|
||||
|
||||
Initialize in `ChanoraSession::new()`:
|
||||
|
||||
```rust
|
||||
resolution_prefetch: Arc::new(Mutex::new(ResolutionPrefetchCache::default())),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Add connect-time cache lookup helper**
|
||||
|
||||
Add methods inside `impl ChanoraSession` before `connect()`:
|
||||
|
||||
```rust
|
||||
async fn apply_prefetched_resolution(&self, cfg: &mut ConnectConfig) {
|
||||
let host = cfg.address.trim();
|
||||
if host.is_empty() {
|
||||
return;
|
||||
}
|
||||
let resolved = {
|
||||
let cache = self.resolution_prefetch.lock().await;
|
||||
cache.fresh_match(host, std::time::Instant::now())
|
||||
};
|
||||
match resolved {
|
||||
Some(addr) => {
|
||||
info!(
|
||||
target: "chanora_core",
|
||||
host = %host,
|
||||
resolved = %addr,
|
||||
"connect using prefetched resolution"
|
||||
);
|
||||
cfg.resolved_address = Some(addr);
|
||||
}
|
||||
None => {
|
||||
info!(target: "chanora_core", host = %host, "connect prefetch miss or stale");
|
||||
}
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
In `connect()`, after identity resolution and before `ProtocolClient::connect(cfg.clone())`, add:
|
||||
|
||||
```rust
|
||||
self.apply_prefetched_resolution(&mut cfg).await;
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Add prefetch scheduling API in core**
|
||||
|
||||
Add this method in `impl ChanoraSession`:
|
||||
|
||||
```rust
|
||||
pub async fn prefetch_server_resolution(&self, host: String) -> Result<(), CoreError> {
|
||||
let normalized = normalize_prefetch_host(&host);
|
||||
if normalized.is_empty() {
|
||||
return Ok(());
|
||||
}
|
||||
|
||||
let generation = {
|
||||
let mut cache = self.resolution_prefetch.lock().await;
|
||||
cache.begin(&normalized)
|
||||
};
|
||||
let cache = self.resolution_prefetch.clone();
|
||||
tokio::spawn(async move {
|
||||
info!(target: "chanora_core", host = %normalized, "resolution prefetch started");
|
||||
let result = resolve_prefetch_socket(&normalized).await;
|
||||
let mut guard = cache.lock().await;
|
||||
match result {
|
||||
Ok(addr) => {
|
||||
info!(
|
||||
target: "chanora_core",
|
||||
host = %normalized,
|
||||
resolved = %addr,
|
||||
"resolution prefetch result"
|
||||
);
|
||||
guard.store_success(generation, &normalized, addr, std::time::Instant::now());
|
||||
}
|
||||
Err(err) => {
|
||||
warn!(
|
||||
target: "chanora_core",
|
||||
host = %normalized,
|
||||
error = %err,
|
||||
"resolution prefetch failed"
|
||||
);
|
||||
guard.store_failure(generation, err.to_string());
|
||||
}
|
||||
}
|
||||
});
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
Add this helper outside `impl ChanoraSession`:
|
||||
|
||||
```rust
|
||||
async fn resolve_prefetch_socket(host: &str) -> Result<std::net::SocketAddr, CoreError> {
|
||||
let resolver = chanora_resolver::ChanoraResolver::new()
|
||||
.map_err(|err| CoreError::Protocol(chanora_protocol::ProtocolError::DnsFailed {
|
||||
host: host.to_string(),
|
||||
reason: format!("resolver initialization failed: {err}"),
|
||||
}))?;
|
||||
let resolved = resolver
|
||||
.resolve_client_address(host)
|
||||
.await
|
||||
.map_err(|err| CoreError::Protocol(chanora_protocol::ProtocolError::DnsFailed {
|
||||
host: host.to_string(),
|
||||
reason: err.to_string(),
|
||||
}))?;
|
||||
resolved
|
||||
.parse::<std::net::SocketAddr>()
|
||||
.map_err(|err| CoreError::Protocol(chanora_protocol::ProtocolError::DnsFailed {
|
||||
host: host.to_string(),
|
||||
reason: format!("resolver returned invalid socket address '{resolved}': {err}"),
|
||||
}))
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run focused core tests**
|
||||
|
||||
Run: `cargo test -p chanora_core session_uses_fresh_prefetched_resolution_for_connect_config --lib`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 7: Run core tests**
|
||||
|
||||
Run: `cargo test -p chanora_core --lib`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 8: Commit**
|
||||
|
||||
```bash
|
||||
git add core/chanora_core/src/lib.rs
|
||||
git commit -m "feat(core): prefetch server resolution"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Bridge API Exposes Prefetch
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/chanora_bridge/src/api.rs`
|
||||
- Regenerate: `crates/chanora_bridge/src/frb_generated.rs`
|
||||
- Regenerate: `apps/chanora_flutter/lib/src/rust/api.dart`
|
||||
- Regenerate: `apps/chanora_flutter/lib/src/rust/api.freezed.dart`
|
||||
- Regenerate: `apps/chanora_flutter/lib/src/rust/frb_generated.dart`
|
||||
|
||||
- [ ] **Step 1: Add bridge function**
|
||||
|
||||
Add after `connect()` in `crates/chanora_bridge/src/api.rs`:
|
||||
|
||||
```rust
|
||||
/// Warm server address resolution for the active host field. This is
|
||||
/// intentionally fire-and-forget from the UI perspective: it schedules
|
||||
/// Rust-side prefetch work and never opens a TS3 session.
|
||||
pub async fn prefetch_server_resolution(host: String) -> Result<(), BridgeError> {
|
||||
runtime()
|
||||
.spawn(async move { session().prefetch_server_resolution(host).await })
|
||||
.await
|
||||
.map_err(|e| task_join_error("prefetch_server_resolution", e))??;
|
||||
Ok(())
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Regenerate flutter_rust_bridge bindings**
|
||||
|
||||
Run from repo root:
|
||||
|
||||
```bash
|
||||
flutter_rust_bridge_codegen generate
|
||||
```
|
||||
|
||||
Expected: generated files update and `apps/chanora_flutter/lib/src/rust/api.dart` contains:
|
||||
|
||||
```dart
|
||||
Future<void> prefetchServerResolution({required String host}) => RustLib
|
||||
.instance
|
||||
.api
|
||||
.crateApiPrefetchServerResolution(host: host);
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Run bridge/core compile check**
|
||||
|
||||
Run: `cargo test -p chanora_bridge --lib`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Run Flutter analyzer smoke check**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
|
||||
Expected: no new errors related to generated bindings.
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add crates/chanora_bridge/src/api.rs crates/chanora_bridge/src/frb_generated.rs apps/chanora_flutter/lib/src/rust/api.dart apps/chanora_flutter/lib/src/rust/api.freezed.dart apps/chanora_flutter/lib/src/rust/frb_generated.dart
|
||||
git commit -m "feat(bridge): expose resolution prefetch"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: Flutter Prefetch Scheduler Helper
|
||||
|
||||
**Files:**
|
||||
- Create: `apps/chanora_flutter/lib/services/server_resolution_prefetch_scheduler.dart`
|
||||
- Create: `apps/chanora_flutter/test/services/server_resolution_prefetch_scheduler_test.dart`
|
||||
|
||||
- [ ] **Step 1: Write failing scheduler tests**
|
||||
|
||||
Create `apps/chanora_flutter/test/services/server_resolution_prefetch_scheduler_test.dart`:
|
||||
|
||||
```dart
|
||||
import 'package:flutter_test/flutter_test.dart';
|
||||
|
||||
import 'package:chanora_flutter/services/server_resolution_prefetch_scheduler.dart';
|
||||
|
||||
void main() {
|
||||
test('debounces host edits and prefetches latest trimmed host', () async {
|
||||
final calls = <String>[];
|
||||
final scheduler = ServerResolutionPrefetchScheduler(
|
||||
delay: const Duration(milliseconds: 20),
|
||||
prefetch: (host) async => calls.add(host),
|
||||
);
|
||||
|
||||
scheduler.schedule(' first.example.com ');
|
||||
scheduler.schedule(' second.example.com ');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 35));
|
||||
|
||||
expect(calls, ['second.example.com']);
|
||||
scheduler.dispose();
|
||||
});
|
||||
|
||||
test('skips empty hosts', () async {
|
||||
final calls = <String>[];
|
||||
final scheduler = ServerResolutionPrefetchScheduler(
|
||||
delay: const Duration(milliseconds: 10),
|
||||
prefetch: (host) async => calls.add(host),
|
||||
);
|
||||
|
||||
scheduler.schedule(' ');
|
||||
await Future<void>.delayed(const Duration(milliseconds: 25));
|
||||
|
||||
expect(calls, isEmpty);
|
||||
scheduler.dispose();
|
||||
});
|
||||
|
||||
test('dispose cancels pending prefetch', () async {
|
||||
final calls = <String>[];
|
||||
final scheduler = ServerResolutionPrefetchScheduler(
|
||||
delay: const Duration(milliseconds: 30),
|
||||
prefetch: (host) async => calls.add(host),
|
||||
);
|
||||
|
||||
scheduler.schedule('example.com');
|
||||
scheduler.dispose();
|
||||
await Future<void>.delayed(const Duration(milliseconds: 45));
|
||||
|
||||
expect(calls, isEmpty);
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Run tests to verify they fail**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter test test/services/server_resolution_prefetch_scheduler_test.dart`
|
||||
|
||||
Expected: FAIL to compile with missing `server_resolution_prefetch_scheduler.dart`.
|
||||
|
||||
- [ ] **Step 3: Implement scheduler**
|
||||
|
||||
Create `apps/chanora_flutter/lib/services/server_resolution_prefetch_scheduler.dart`:
|
||||
|
||||
```dart
|
||||
import 'dart:async';
|
||||
|
||||
typedef ServerResolutionPrefetch = Future<void> Function(String host);
|
||||
|
||||
class ServerResolutionPrefetchScheduler {
|
||||
ServerResolutionPrefetchScheduler({
|
||||
required this.prefetch,
|
||||
this.delay = const Duration(milliseconds: 700),
|
||||
});
|
||||
|
||||
final ServerResolutionPrefetch prefetch;
|
||||
final Duration delay;
|
||||
|
||||
Timer? _timer;
|
||||
bool _disposed = false;
|
||||
|
||||
void schedule(String rawHost) {
|
||||
if (_disposed) return;
|
||||
_timer?.cancel();
|
||||
final host = rawHost.trim();
|
||||
if (host.isEmpty) return;
|
||||
_timer = Timer(delay, () {
|
||||
if (_disposed) return;
|
||||
unawaited(prefetch(host));
|
||||
});
|
||||
}
|
||||
|
||||
void dispose() {
|
||||
_disposed = true;
|
||||
_timer?.cancel();
|
||||
_timer = null;
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run scheduler tests**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter test test/services/server_resolution_prefetch_scheduler_test.dart`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 5: Format Dart files**
|
||||
|
||||
Run: `cd apps/chanora_flutter && dart format lib/services/server_resolution_prefetch_scheduler.dart test/services/server_resolution_prefetch_scheduler_test.dart`
|
||||
|
||||
Expected: files formatted, no errors.
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/services/server_resolution_prefetch_scheduler.dart apps/chanora_flutter/test/services/server_resolution_prefetch_scheduler_test.dart
|
||||
git commit -m "feat(ui): add resolution prefetch scheduler"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 7: Wire Prefetch Scheduler Into Home UI
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart`
|
||||
|
||||
- [ ] **Step 1: Add imports and state fields**
|
||||
|
||||
In `apps/chanora_flutter/lib/main.dart`, add:
|
||||
|
||||
```dart
|
||||
import 'services/server_resolution_prefetch_scheduler.dart';
|
||||
```
|
||||
|
||||
Inside `_BetaHomeState`, add:
|
||||
|
||||
```dart
|
||||
late final ServerResolutionPrefetchScheduler _resolutionPrefetch;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Initialize scheduler and listener**
|
||||
|
||||
In `initState()`, before `_eventsSub = rust.eventsStream().listen(_onEvent);`, add:
|
||||
|
||||
```dart
|
||||
_resolutionPrefetch = ServerResolutionPrefetchScheduler(
|
||||
prefetch: (host) => rust.prefetchServerResolution(host: host),
|
||||
);
|
||||
_hostCtl.addListener(_onHostEdited);
|
||||
```
|
||||
|
||||
Add method in `_BetaHomeState`:
|
||||
|
||||
```dart
|
||||
void _onHostEdited() {
|
||||
_resolutionPrefetch.schedule(_hostCtl.text);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Schedule prefetch after settings load**
|
||||
|
||||
In `_loadUiSettings()`, after setting host/nickname from settings and before the `catch`, add:
|
||||
|
||||
```dart
|
||||
if (settings.host.isNotEmpty) {
|
||||
_resolutionPrefetch.schedule(settings.host);
|
||||
}
|
||||
```
|
||||
|
||||
Ensure this is not duplicated if an existing `_hostCtl.text = settings.host;` listener already schedules it. If both paths fire, keep only the explicit `_resolutionPrefetch.schedule(settings.host);` and temporarily remove/re-add the listener around `_hostCtl.text = settings.host`, or accept the duplicate because scheduler debounce collapses it. Prefer accepting the duplicate for minimal change.
|
||||
|
||||
- [ ] **Step 4: Dispose scheduler and listener**
|
||||
|
||||
In `dispose()`, before `_hostCtl.dispose();`, add:
|
||||
|
||||
```dart
|
||||
_hostCtl.removeListener(_onHostEdited);
|
||||
_resolutionPrefetch.dispose();
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run focused Flutter tests**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter test test/services/server_resolution_prefetch_scheduler_test.dart test/services/connection_phase_state_test.dart`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Run analyzer**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
|
||||
Expected: no new analyzer errors.
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/main.dart
|
||||
git commit -m "feat(ui): prefetch active server address"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 8: End-To-End Verification On Android
|
||||
|
||||
**Files:**
|
||||
- No source changes expected unless verification finds a bug.
|
||||
|
||||
- [ ] **Step 1: Run focused Rust tests**
|
||||
|
||||
Run: `cargo test -p chanora_resolver -p chanora_protocol -p chanora_core --lib`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 2: Run focused Flutter tests**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter test test/services/server_resolution_prefetch_scheduler_test.dart test/services/connection_phase_state_test.dart test/services/ts3_server_link_test.dart`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Build Android debug APK**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter build apk --debug`
|
||||
|
||||
Expected: `✓ Built build/app/outputs/flutter-apk/app-debug.apk`.
|
||||
|
||||
- [ ] **Step 4: Install and launch through ADB**
|
||||
|
||||
Run from `apps/chanora_flutter`:
|
||||
|
||||
```bash
|
||||
adb install -r "build/app/outputs/flutter-apk/app-debug.apk"
|
||||
adb shell am force-stop app.chanora.chanora_flutter
|
||||
adb logcat -c
|
||||
adb shell monkey -p app.chanora.chanora_flutter -c android.intent.category.LAUNCHER 1
|
||||
```
|
||||
|
||||
Expected: install success and app launches.
|
||||
|
||||
- [ ] **Step 5: Allow prefetch, connect, and inspect logs**
|
||||
|
||||
Run from repo root:
|
||||
|
||||
```bash
|
||||
sleep 2
|
||||
adb shell input tap 354 1363
|
||||
sleep 8
|
||||
adb logcat -d -v time | rg "resolution prefetch|prefetched|client request resolution|server address resolved|FATAL|AndroidRuntime"
|
||||
```
|
||||
|
||||
Expected:
|
||||
|
||||
- No app `FATAL` lines.
|
||||
- Logs include `resolution prefetch started` and either `resolution prefetch result` or safe failure.
|
||||
- If prefetch completed before tap, logs include `connect using prefetched resolution` and protocol logs include `using prefetched server address`.
|
||||
- If prefetch did not complete before tap, connect still succeeds through normal resolver path.
|
||||
|
||||
- [ ] **Step 6: Inspect UI hierarchy**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
adb shell uiautomator dump /sdcard/window.xml
|
||||
adb exec-out cat /sdcard/window.xml
|
||||
```
|
||||
|
||||
Expected: connected server view with channel count, not stuck on `Synchronizing...`.
|
||||
|
||||
- [ ] **Step 7: Final status check**
|
||||
|
||||
Run: `git status --short`
|
||||
|
||||
Expected: no unintended source changes. Unrelated existing `config.json` may remain untracked and must not be committed.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- Active-field-only prefetch: Tasks 6 and 7.
|
||||
- Rust-owned resolver cache and exact-match validation: Tasks 3 and 4.
|
||||
- 2-minute TTL: Task 3.
|
||||
- Invisible UI: Tasks 6 and 7 avoid any UI status changes.
|
||||
- No bookmark fan-out: Task 7 wires only `_hostCtl` and settings-loaded host.
|
||||
- No TS3 session before Connect: Task 4 only resolves address; Task 2 only uses resolved address during actual protocol connect.
|
||||
- Diagnostics: Tasks 2 and 4 add logs for prefetch and cache hit/miss.
|
||||
- Testing and Android smoke: Task 8.
|
||||
|
||||
Completeness scan: no incomplete markers are used. Each code-changing task includes concrete code snippets and commands.
|
||||
|
||||
Type consistency: `resolved_address` is added to protocol `ConnectConfig`, core uses `cfg.resolved_address`, bridge exposes `prefetch_server_resolution`, and Dart uses generated `prefetchServerResolution`.
|
||||
@@ -0,0 +1,642 @@
|
||||
# Chat Panel Switching Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Enable in-place conversation switching in the expanded 3-panel layout, add per-conversation draft persistence, and improve unread awareness — matching industry-standard UX patterns from Discord/Slack/Telegram/Element.
|
||||
|
||||
**Architecture:** The expanded layout (≥1024dp) shows voice controls | channel tree | inline chat panel. Currently the chat panel locks to one conversation with no way to switch from the channel tree. The fix adds channel→chat triggers, in-place target swapping, per-target draft storage, and preserves chat state across switches. The state machine (`_inlineChatTarget` + `_chatOpen`) already supports switching — we just need UI affordances and draft persistence.
|
||||
|
||||
**Tech Stack:** Flutter/Dart, existing `BridgeMessageTarget` sealed class, existing `ChatDetailView` / `ChatPanel` / `SnapshotView` widgets.
|
||||
|
||||
**Design research basis:** Discord (in-place swap, dot/badge unread hierarchy), Telegram Desktop (adaptive 3-tier layout, per-conversation drafts + scroll anchoring), Element (per-room panel state, toggleable right panel), Slack (bold sidebar for unread, split view). All apps treat DMs and channels identically for switching behavior.
|
||||
|
||||
---
|
||||
|
||||
## Current State
|
||||
|
||||
| UX Element | Status |
|
||||
|---|---|
|
||||
| Unread indicator | Single global badge count on app bar chat button |
|
||||
| Channel → chat trigger | **None.** Channel tiles only join voice |
|
||||
| Client → DM trigger | Works (right-click → "Direct Message") |
|
||||
| Header chat button when panel open | Idempotent — re-uses same `_inlineChatTarget` |
|
||||
| Draft persistence | None — single `TextEditingController`, lost on switch |
|
||||
| Scroll position memory | None — always auto-scrolls to bottom |
|
||||
| Per-conversation unread | None |
|
||||
|
||||
## Scope
|
||||
|
||||
**In scope (this plan):**
|
||||
- Channel → chat switching in expanded layout
|
||||
- Channel right-click → "Chat" option
|
||||
- Header chat button → switch to current voice channel chat when panel already open
|
||||
- Per-target draft persistence (in-memory `Map`)
|
||||
- Close = dismiss (remember last target and draft)
|
||||
- Unread dot indicator on channels in `SnapshotView`
|
||||
|
||||
**Out of scope (future):**
|
||||
- Scroll position memory per target
|
||||
- "New messages" divider
|
||||
- Per-target unread counts / badge numbers
|
||||
- Notification tiering (dot/badge/mention)
|
||||
- Split view (Slack power-user feature)
|
||||
|
||||
## Responsive Behavior
|
||||
|
||||
| Tier | Width | Chat Mode | Changes in this plan |
|
||||
|---|---|---|---|
|
||||
| **Expanded** | ≥1024dp | Inline `ChatPanel` (right column) | ✅ All changes apply here |
|
||||
| **Medium** | 600–1023dp | Full-screen `ChatPage` route | No changes needed (already works) |
|
||||
| **Compact** | <600dp | Full-screen `ChatPage` route | No changes needed (already works) |
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
| File | Action | Responsibility |
|
||||
|---|---|---|
|
||||
| `apps/chanora_flutter/lib/widgets/snapshot_view.dart` | **Modify** | Add `onOpenChannelChat` callback, channel context menu with "Chat" option, unread dot on channels |
|
||||
| `apps/chanora_flutter/lib/main.dart` | **Modify** | Add `_chatDrafts` map, wire `onOpenChannelChat`, fix header chat button to switch to current channel, fix `_closeInlineChat` to preserve last target |
|
||||
| `apps/chanora_flutter/lib/widgets/chat_panel.dart` | **Modify** | Accept `onSwitchTarget` callback, pass draft state through |
|
||||
| `apps/chanora_flutter/lib/widgets/chat_views.dart` | **Modify** | `ChatDetailView` accepts external draft text, exposes draft text on target change |
|
||||
| `apps/chanora_flutter/lib/design/breakpoints.dart` | **No changes** | Breakpoints unchanged |
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add `onOpenChannelChat` callback to `SnapshotView`
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/snapshot_view.dart:26-63` (constructor params)
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/snapshot_view.dart:203-284` (`_channelTile`)
|
||||
|
||||
- [ ] **Step 1: Add the callback field to `SnapshotView` widget**
|
||||
|
||||
In `snapshot_view.dart`, add a new optional callback field after `onOpenClientPoke` (around line 71):
|
||||
|
||||
```dart
|
||||
/// Open chat for a channel.
|
||||
final ValueChanged<rust.BridgeChannel>? onOpenChannelChat;
|
||||
```
|
||||
|
||||
Update the constructor to include it (around line 32, after `onOpenClientPoke`):
|
||||
|
||||
```dart
|
||||
this.onOpenChannelChat,
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add a right-click/long-press context menu to `_channelTile`**
|
||||
|
||||
Replace the `InkWell` in `_channelTile` (lines 243-284) with a context menu wrapper. The channel tile should support:
|
||||
- **Tap**: join voice (existing behavior, unchanged)
|
||||
- **Right-click / long-press**: show a popup menu with "Open chat" option
|
||||
|
||||
```dart
|
||||
return InkWell(
|
||||
onTap: onTap,
|
||||
onLongPress: widget.onOpenChannelChat != null
|
||||
? () => widget.onOpenChannelChat!(channel)
|
||||
: null,
|
||||
child: PopupMenuButton<String>(
|
||||
position: PopupMenuPosition.under,
|
||||
enabled: widget.onOpenChannelChat != null,
|
||||
onSelected: (value) {
|
||||
if (value == 'chat') {
|
||||
widget.onOpenChannelChat?.call(channel);
|
||||
}
|
||||
},
|
||||
itemBuilder: (context) => [
|
||||
PopupMenuItem(
|
||||
value: 'chat',
|
||||
child: Row(
|
||||
children: [
|
||||
const Icon(Icons.chat_bubble_outline, size: 18),
|
||||
const SizedBox(width: 12),
|
||||
Text(AppLocalizations.of(context)!.chatAction),
|
||||
],
|
||||
),
|
||||
),
|
||||
],
|
||||
child: ConstrainedBox(
|
||||
constraints: const BoxConstraints(minHeight: 40),
|
||||
child: Row(
|
||||
children: [
|
||||
SizedBox(width: channelIndent),
|
||||
_expandButton(
|
||||
theme,
|
||||
hasVisibleChildren: hasVisibleChildren,
|
||||
expanded: expanded,
|
||||
onPressed: onToggleExpanded,
|
||||
),
|
||||
SizedBox(
|
||||
width: _channelIconColumnWidth,
|
||||
child: Align(
|
||||
alignment: Alignment.centerLeft,
|
||||
child: Icon(
|
||||
Icons.tag,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
),
|
||||
),
|
||||
const SizedBox(width: _channelTextGap),
|
||||
Expanded(
|
||||
child: Text(
|
||||
channel.name,
|
||||
maxLines: 1,
|
||||
overflow: TextOverflow.ellipsis,
|
||||
),
|
||||
),
|
||||
if (channel.hasPassword) ...[
|
||||
const SizedBox(width: 8),
|
||||
Icon(
|
||||
Icons.lock_outline,
|
||||
color: theme.colorScheme.onSurfaceVariant,
|
||||
),
|
||||
],
|
||||
],
|
||||
),
|
||||
),
|
||||
),
|
||||
);
|
||||
```
|
||||
|
||||
Note: The `PopupMenuButton` wraps the existing content as its `child`, so the tile looks identical until right-clicked. The `onTap` on `InkWell` continues to handle voice join.
|
||||
|
||||
- [ ] **Step 3: Run `flutter analyze`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: No new errors (the callback is optional, so existing call sites compile without changes)
|
||||
|
||||
- [ ] **Step 4: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/widgets/snapshot_view.dart
|
||||
git commit -m "feat(chat): add onOpenChannelChat callback with context menu to channel tiles"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 2: Wire `onOpenChannelChat` in `main.dart` and add per-target draft storage
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart:370-374` (state fields)
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart:2521-2540` (SnapshotView constructor)
|
||||
|
||||
- [ ] **Step 1: Add draft storage map**
|
||||
|
||||
Add a new state field near line 374 (after `_inlineChatCollapseNoticeShown`):
|
||||
|
||||
```dart
|
||||
/// Per-target draft text. Populated when switching away from a conversation
|
||||
/// so the user's unfinished message is preserved.
|
||||
final Map<String, String> _chatDrafts = {};
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add `_lastDismissedTarget` field**
|
||||
|
||||
Add a new state field to remember the last dismissed target so reopening returns to it:
|
||||
|
||||
```dart
|
||||
/// The last chat target before the panel was closed. Used to restore the
|
||||
/// previous conversation when the user reopens chat.
|
||||
rust.BridgeMessageTarget? _lastDismissedTarget;
|
||||
String _lastDismissedClientName = '';
|
||||
```
|
||||
|
||||
- [ ] **Step 3: Wire `onOpenChannelChat` in `SnapshotView` constructor**
|
||||
|
||||
In the `SnapshotView(...)` constructor around line 2512, add the new callback:
|
||||
|
||||
```dart
|
||||
onOpenChannelChat: (channel) => unawaited(
|
||||
_onOpenChat(
|
||||
target: rust.BridgeMessageTarget.channel(channel.id),
|
||||
),
|
||||
),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run `flutter analyze`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: No new errors
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/main.dart
|
||||
git commit -m "feat(chat): add per-target draft storage and wire onOpenChannelChat"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 3: Fix `_onOpenChat` to support switching and draft save/restore
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart:1628-1685` (`_onOpenChat` and `_closeInlineChat`)
|
||||
|
||||
- [ ] **Step 1: Update `_onOpenChat` to save current draft and restore new target's draft**
|
||||
|
||||
Replace the `_onOpenChat` method (lines 1628-1676) with logic that:
|
||||
1. Saves the current `_inlineChatTarget` draft before switching
|
||||
2. Restores the new target's draft (if any)
|
||||
3. When called with no explicit target and panel is already open, switches to current voice channel's chat
|
||||
|
||||
```dart
|
||||
Future<void> _onOpenChat({
|
||||
rust.BridgeMessageTarget? target,
|
||||
String clientName = '',
|
||||
}) async {
|
||||
final initialSnapshot = _snapshot!;
|
||||
|
||||
// Resolve the new target.
|
||||
// If no target passed and panel is already open, switch to current voice channel.
|
||||
// If no target passed and panel is closed, resolve from history or default.
|
||||
rust.BridgeMessageTarget newTarget;
|
||||
if (target != null) {
|
||||
newTarget = target;
|
||||
} else if (_chatOpen && _currentVoiceChannelId != null) {
|
||||
newTarget = rust.BridgeMessageTarget.channel(_currentVoiceChannelId!);
|
||||
} else if (_inlineChatTarget != null) {
|
||||
newTarget = _inlineChatTarget!;
|
||||
} else {
|
||||
newTarget = resolveInitialChatTarget(
|
||||
messages: _chatMessages,
|
||||
currentVoiceChannelId: _currentVoiceChannelId,
|
||||
) ?? const rust.BridgeMessageTarget.server();
|
||||
}
|
||||
|
||||
final newClientName = clientName.isNotEmpty
|
||||
? clientName
|
||||
: (newTarget == _inlineChatTarget) ? _inlineChatClientName : '';
|
||||
|
||||
final isExpanded =
|
||||
layoutClassFromWidth(MediaQuery.sizeOf(context).width) ==
|
||||
LayoutClass.expanded;
|
||||
if (isExpanded) {
|
||||
setState(() {
|
||||
// Save draft for the current target before switching.
|
||||
_saveCurrentDraft();
|
||||
_chatUnread = 0;
|
||||
_chatOpen = true;
|
||||
_inlineChatTarget = newTarget;
|
||||
_inlineChatClientName = newClientName;
|
||||
_inlineChatCollapseNoticeShown = false;
|
||||
});
|
||||
return;
|
||||
}
|
||||
setState(() {
|
||||
_chatUnread = 0;
|
||||
_chatOpen = true;
|
||||
});
|
||||
await Navigator.of(context).push(
|
||||
MaterialPageRoute(
|
||||
builder: (_) => ChatPage(
|
||||
messages: _chatMessages,
|
||||
snapshot: initialSnapshot,
|
||||
messagesSource: () => _chatMessages,
|
||||
snapshotSource: () => _snapshot ?? initialSnapshot,
|
||||
refreshListenable: _chatFeedRevision,
|
||||
initialTarget: newTarget,
|
||||
initialClientName: newClientName,
|
||||
onTs3ServerLink: _onTs3ServerLink,
|
||||
),
|
||||
),
|
||||
);
|
||||
if (mounted) setState(() => _chatOpen = false);
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add `_saveCurrentDraft` and `_draftKeyForTarget` helper methods**
|
||||
|
||||
Add these near `_onOpenChat`:
|
||||
|
||||
```dart
|
||||
/// Converts a [rust.BridgeMessageTarget] to a stable string key for draft storage.
|
||||
String _draftKeyForTarget(rust.BridgeMessageTarget target) {
|
||||
return switch (target) {
|
||||
rust.BridgeMessageTarget_Server() => 'server',
|
||||
rust.BridgeMessageTarget_Channel(:final id) => 'channel:$id',
|
||||
rust.BridgeMessageTarget_Client(:final id) => 'client:$id',
|
||||
rust.BridgeMessageTarget_Poke(:final id) => 'poke:$id',
|
||||
};
|
||||
}
|
||||
|
||||
/// Saves the current draft text (if any) for the current inline chat target.
|
||||
/// Called before switching targets or closing the panel.
|
||||
void _saveCurrentDraft() {
|
||||
// Note: The actual draft text is read from ChatDetailView's
|
||||
// TextEditingController via a callback. This is wired in Task 4.
|
||||
}
|
||||
```
|
||||
|
||||
Note: `_saveCurrentDraft` will be completed in Task 4 when we wire the draft callback from `ChatDetailView`.
|
||||
|
||||
- [ ] **Step 3: Update `_closeInlineChat` to preserve last target instead of nulling it**
|
||||
|
||||
Replace `_closeInlineChat` (lines 1678-1685):
|
||||
|
||||
```dart
|
||||
void _closeInlineChat() {
|
||||
setState(() {
|
||||
// Save draft before closing.
|
||||
_saveCurrentDraft();
|
||||
// Remember the last target so reopening returns to it.
|
||||
_lastDismissedTarget = _inlineChatTarget;
|
||||
_lastDismissedClientName = _inlineChatClientName;
|
||||
_chatOpen = false;
|
||||
// Do NOT null _inlineChatTarget — we want to remember it for reopen.
|
||||
});
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Run `flutter analyze`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: No new errors
|
||||
|
||||
- [ ] **Step 5: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/main.dart
|
||||
git commit -m "feat(chat): switch chat target on channel click, save draft before switching, preserve target on close"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 4: Add draft save/restore callback to `ChatDetailView` and `ChatPanel`
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/chat_views.dart:1054-1098` (`ChatDetailView` constructor + state)
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/chat_panel.dart:12-75` (`ChatPanel` constructor + build)
|
||||
|
||||
- [ ] **Step 1: Add draft callbacks to `ChatDetailView`**
|
||||
|
||||
Add two new optional callbacks to `ChatDetailView` (after `messageMaxWidth` around line 1066):
|
||||
|
||||
```dart
|
||||
/// External draft text to restore when the widget initializes or the target changes.
|
||||
final String? restoredDraft;
|
||||
|
||||
/// Called with the current draft text whenever the target changes or the widget is disposed.
|
||||
final ValueChanged<String>? onDraftChanged;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Implement draft restore in `_ChatDetailViewState`**
|
||||
|
||||
In `_ChatDetailViewState` (line 1100), add `initState` and `didUpdateWidget` to handle drafts:
|
||||
|
||||
```dart
|
||||
@override
|
||||
void initState() {
|
||||
super.initState();
|
||||
if (widget.restoredDraft != null && widget.restoredDraft!.isNotEmpty) {
|
||||
_textCtl.text = widget.restoredDraft!;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void didUpdateWidget(covariant ChatDetailView oldWidget) {
|
||||
super.didUpdateWidget(oldWidget);
|
||||
if (oldWidget.target != widget.target) {
|
||||
// Save draft for old target before switching.
|
||||
if (oldWidget.onDraftChanged != null && _textCtl.text.isNotEmpty) {
|
||||
oldWidget.onDraftChanged!(_textCtl.text);
|
||||
}
|
||||
// Restore draft for new target.
|
||||
_textCtl.text = widget.restoredDraft ?? '';
|
||||
_lastRenderedTarget = null;
|
||||
}
|
||||
}
|
||||
|
||||
@override
|
||||
void dispose() {
|
||||
// Emit the current draft so the parent can save it.
|
||||
if (widget.onDraftChanged != null && _textCtl.text.isNotEmpty) {
|
||||
widget.onDraftChanged!(_textCtl.text);
|
||||
}
|
||||
_textCtl.dispose();
|
||||
_scrollCtl.dispose();
|
||||
super.dispose();
|
||||
}
|
||||
```
|
||||
|
||||
Remove the existing `dispose` method (lines 1127-1132) — it's replaced by the new one above.
|
||||
|
||||
- [ ] **Step 3: Thread draft callbacks through `ChatPanel`**
|
||||
|
||||
Update `ChatPanel` to accept and pass through the new callbacks. Add fields:
|
||||
|
||||
```dart
|
||||
/// External draft text to restore in the chat detail view.
|
||||
final String? restoredDraft;
|
||||
|
||||
/// Called when the draft text changes.
|
||||
final ValueChanged<String>? onDraftChanged;
|
||||
```
|
||||
|
||||
Pass them through in `build()` where `ChatDetailView` is constructed (line 58):
|
||||
|
||||
```dart
|
||||
child: ChatDetailView(
|
||||
messages: messages,
|
||||
snapshot: snapshot,
|
||||
target: target,
|
||||
clientName: clientName,
|
||||
currentChannelId: currentChannelId,
|
||||
channelName: channelName,
|
||||
onTs3ServerLink: onTs3ServerLink,
|
||||
restoredDraft: restoredDraft,
|
||||
onDraftChanged: onDraftChanged,
|
||||
messageMaxWidth: 500,
|
||||
headerTrailing: IconButton(
|
||||
tooltip: 'Close chat',
|
||||
icon: const Icon(Icons.close),
|
||||
onPressed: onClose,
|
||||
),
|
||||
),
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Wire draft callbacks in `main.dart`**
|
||||
|
||||
In the `ChatPanel(...)` constructor around line 2567, add the draft callbacks:
|
||||
|
||||
```dart
|
||||
ChatPanel(
|
||||
messages: _chatMessages,
|
||||
snapshot: _snapshot!,
|
||||
target: inlineChatTarget,
|
||||
clientName: _inlineChatClientName,
|
||||
onTs3ServerLink: _onTs3ServerLink,
|
||||
restoredDraft: _chatDrafts[_draftKeyForTarget(inlineChatTarget)],
|
||||
onDraftChanged: (text) {
|
||||
_chatDrafts[_draftKeyForTarget(_inlineChatTarget!)] = text;
|
||||
},
|
||||
onClose: _closeInlineChat,
|
||||
),
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Complete `_saveCurrentDraft` in `main.dart`**
|
||||
|
||||
The `_saveCurrentDraft` method is called from `_onOpenChat` (before switching) and `_closeInlineChat`. Since `ChatDetailView` emits drafts via `onDraftChanged` and `dispose`, the parent always has the latest draft in `_chatDrafts`. The method body stays as a no-op safety net:
|
||||
|
||||
```dart
|
||||
void _saveCurrentDraft() {
|
||||
// Drafts are continuously saved via onDraftChanged callback.
|
||||
// This method exists as an explicit save point for any future
|
||||
// snapshot-based draft capture.
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 6: Run `flutter analyze`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: No new errors
|
||||
|
||||
- [ ] **Step 7: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/widgets/chat_views.dart apps/chanora_flutter/lib/widgets/chat_panel.dart apps/chanora_flutter/lib/main.dart
|
||||
git commit -m "feat(chat): per-target draft persistence with save/restore on switch"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 5: Add unread dot indicator to channel tiles in `SnapshotView`
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/snapshot_view.dart` (add unread indicator)
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart` (pass unread channel set)
|
||||
|
||||
- [ ] **Step 1: Add unread channel IDs parameter to `SnapshotView`**
|
||||
|
||||
Add a new required field to `SnapshotView` (after `canJoinVoiceChannel` around line 57):
|
||||
|
||||
```dart
|
||||
/// Set of channel IDs that have unread chat messages.
|
||||
final Set<BigInt> unreadChannelIds;
|
||||
```
|
||||
|
||||
- [ ] **Step 2: Add unread dot to `_channelTile`**
|
||||
|
||||
In `_channelTile`, inside the `Row` children (after the channel name `Expanded` widget, around line 273), add an unread dot:
|
||||
|
||||
```dart
|
||||
// Unread indicator.
|
||||
if (widget.unreadChannelIds.contains(channel.id)) ...[
|
||||
const SizedBox(width: 8),
|
||||
Container(
|
||||
width: 8,
|
||||
height: 8,
|
||||
decoration: BoxDecoration(
|
||||
color: theme.colorScheme.primary,
|
||||
shape: BoxShape.circle,
|
||||
),
|
||||
),
|
||||
],
|
||||
```
|
||||
|
||||
This must come before the password lock icon check (line 274).
|
||||
|
||||
- [ ] **Step 3: Compute unread channel set in `main.dart`**
|
||||
|
||||
Add a getter in `_BetaHomeState` that computes which channels have unread messages:
|
||||
|
||||
```dart
|
||||
/// Channel IDs that have unread chat messages (used for dot indicators).
|
||||
Set<BigInt> get _unreadChannelIds {
|
||||
if (_chatOpen) return const {};
|
||||
final ids = <BigInt>{};
|
||||
for (final entry in _chatMessages) {
|
||||
if (!entry.countsTowardUnread || entry.isSelf) continue;
|
||||
if (entry.target case rust.BridgeMessageTarget_Channel(:final id)) {
|
||||
ids.add(id);
|
||||
}
|
||||
}
|
||||
return ids;
|
||||
}
|
||||
```
|
||||
|
||||
- [ ] **Step 4: Pass unread channel set to `SnapshotView`**
|
||||
|
||||
In the `SnapshotView(...)` constructor around line 2512, add:
|
||||
|
||||
```dart
|
||||
unreadChannelIds: _unreadChannelIds,
|
||||
```
|
||||
|
||||
- [ ] **Step 5: Run `flutter analyze`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: No new errors
|
||||
|
||||
- [ ] **Step 6: Commit**
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/widgets/snapshot_view.dart apps/chanora_flutter/lib/main.dart
|
||||
git commit -m "feat(chat): unread dot indicator on channel tiles with unread messages"
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
### Task 6: End-to-end verification
|
||||
|
||||
**Files:** All modified files.
|
||||
|
||||
- [ ] **Step 1: Run `flutter analyze` on the full project**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter analyze`
|
||||
Expected: Zero issues
|
||||
|
||||
- [ ] **Step 2: Run `flutter test`**
|
||||
|
||||
Run: `cd apps/chanora_flutter && flutter test`
|
||||
Expected: All tests pass (same baseline as before — 180 passed, 2 skipped)
|
||||
|
||||
- [ ] **Step 3: Build macOS release**
|
||||
|
||||
Run: `bash tools/build-macos.sh`
|
||||
Expected: Successful build producing `chanora-v0.2.0-beta.1-macos-aarch64.zip`
|
||||
|
||||
- [ ] **Step 4: Manual QA checklist**
|
||||
|
||||
Launch the app and verify:
|
||||
|
||||
1. **Channel → chat switching**: With window ≥1024dp and chat panel open showing Server chat, click a channel in the tree. The chat panel should switch to that channel's chat (messages filter to that channel). Voice join should also happen.
|
||||
|
||||
2. **Channel right-click → Chat**: Right-click a channel → "Open chat". Chat panel should switch to that channel's chat without joining voice.
|
||||
|
||||
3. **Header chat button toggle**: With chat panel open showing a DM, click the header chat button. It should switch to the current voice channel's chat.
|
||||
|
||||
4. **Draft persistence**: Type "hello" in chat input but don't send. Click a different channel. Type "world" in that channel's chat. Switch back to the first channel. The input should show "hello".
|
||||
|
||||
5. **Close and reopen**: Close the chat panel. Click the header chat button. It should reopen to the last conversation with the draft intact.
|
||||
|
||||
6. **Unread dots**: Close the chat panel. Have someone send a message to a specific channel. That channel in the tree should show a blue dot.
|
||||
|
||||
7. **Medium/compact unchanged**: Narrow the window below 1024dp. Open chat. It should still push a full-screen route as before. No regressions.
|
||||
|
||||
8. **DM switching still works**: Right-click a client → "Direct Message". Chat panel should switch to that DM. Right-click another client → "Direct Message". Should switch again.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
### Spec coverage
|
||||
|
||||
| Requirement | Task |
|
||||
|---|---|
|
||||
| Channel → chat switching (tap) | Task 2 (wiring) + Task 3 (target resolution) |
|
||||
| Channel → chat (context menu) | Task 1 |
|
||||
| Header button switches when open | Task 3 |
|
||||
| Per-target draft persistence | Task 4 |
|
||||
| Close = dismiss (remember state) | Task 3 |
|
||||
| Unread dot on channels | Task 5 |
|
||||
| Medium/compact unchanged | No changes to those paths |
|
||||
|
||||
### Placeholder scan
|
||||
No TBD, TODO, or placeholder steps found. All code blocks contain complete implementations.
|
||||
|
||||
### Type consistency
|
||||
- `BridgeMessageTarget.channel(id)` uses `BigInt` — matches `channel.id` type
|
||||
- `_chatDrafts` uses `String` keys from `_draftKeyForTarget` — consistent
|
||||
- `onOpenChannelChat` callback type `ValueChanged<rust.BridgeChannel>?` — matches widget pattern
|
||||
- `unreadChannelIds` uses `Set<BigInt>` — matches channel ID type
|
||||
@@ -0,0 +1,95 @@
|
||||
# Core Internal Split Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Improve `chanora_core` maintainability by moving stable event DTOs and network diagnostic state out of the oversized `lib.rs` while preserving the public crate Interface.
|
||||
|
||||
**Architecture:** Keep `lib.rs` as the public Interface and session orchestration entry point. Move event-facing DTOs to `events.rs` and private network diagnostic ring-buffer state to `network_diagnostics.rs`; re-export public event types from `lib.rs` so downstream callers keep using `chanora_core::SessionEvent` and related names unchanged.
|
||||
|
||||
**Tech Stack:** Rust 2021, Tokio broadcast/watch channels, `thiserror`, existing Cargo workspace tests.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Move Core Event DTOs
|
||||
|
||||
**Files:**
|
||||
- Create: `core/chanora_core/src/events.rs`
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
- Verify: `cargo test -p chanora_core`
|
||||
|
||||
- [ ] **Step 1: Preserve current public Interface with tests**
|
||||
|
||||
Run: `cargo test -p chanora_core`
|
||||
Expected: PASS. Existing bridge-facing tests and compile checks prove the current public event names are valid.
|
||||
|
||||
- [ ] **Step 2: Create `events.rs` with the moved public event DTOs**
|
||||
|
||||
Move these exact public types from `lib.rs` to `events.rs`:
|
||||
- `PttDescriptorSnapshot`
|
||||
- `PersistedPttBinding`
|
||||
- `SessionEvent`
|
||||
- `VoiceJoinSyncState`
|
||||
- `VoiceJoinErrorCode`
|
||||
- `NetworkState`
|
||||
|
||||
Use local imports in `events.rs` for `chanora_audio::{AudioRoute, PttBackendDescriptor}` and `chanora_protocol::MessageTarget`.
|
||||
|
||||
- [ ] **Step 3: Re-export moved types from `lib.rs`**
|
||||
|
||||
Add `mod events;` and `pub use events::{...};` for all moved public types. Remove the original definitions from `lib.rs`.
|
||||
|
||||
- [ ] **Step 4: Run tests**
|
||||
|
||||
Run: `cargo test -p chanora_core`
|
||||
Expected: PASS with no public Interface break.
|
||||
|
||||
### Task 2: Move Core Network Diagnostics State
|
||||
|
||||
**Files:**
|
||||
- Create: `core/chanora_core/src/network_diagnostics.rs`
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
- Verify: `cargo test -p chanora_core network_diagnostics`
|
||||
|
||||
- [ ] **Step 1: Move `NetworkDiagnostics` into a private module**
|
||||
|
||||
Move the private `NetworkDiagnostics` struct and its methods from `lib.rs` into `network_diagnostics.rs`. Keep methods `pub(crate)` because `ChanoraSession` records connection/loss events and exports summaries.
|
||||
|
||||
- [ ] **Step 2: Move the regression test with the module**
|
||||
|
||||
Move `network_diagnostics_keeps_last_eight_loss_reasons` from the `lib.rs` test module into `network_diagnostics.rs` so the behaviour test lives next to the Implementation it protects.
|
||||
|
||||
- [ ] **Step 3: Import the private module from `lib.rs`**
|
||||
|
||||
Add `mod network_diagnostics;` and `use network_diagnostics::NetworkDiagnostics;`. Remove `VecDeque` from the `lib.rs` imports.
|
||||
|
||||
- [ ] **Step 4: Run targeted and workspace verification**
|
||||
|
||||
Run: `cargo test -p chanora_core network_diagnostics`
|
||||
Expected: PASS.
|
||||
|
||||
Run: `cargo test --workspace`
|
||||
Expected: PASS.
|
||||
|
||||
### Task 3: Format and Check Workspace
|
||||
|
||||
**Files:**
|
||||
- Modify: Rust files touched above only, except existing formatter-only churn may remain from prior `cargo fmt --all`.
|
||||
|
||||
- [ ] **Step 1: Format Rust code**
|
||||
|
||||
Run: `cargo fmt --all`
|
||||
Expected: no command output.
|
||||
|
||||
- [ ] **Step 2: Compile workspace**
|
||||
|
||||
Run: `cargo check --workspace`
|
||||
Expected: finishes successfully.
|
||||
|
||||
- [ ] **Step 3: Inspect diff**
|
||||
|
||||
Run: `git diff --stat`
|
||||
Expected: new `events.rs` and `network_diagnostics.rs`; smaller `core/chanora_core/src/lib.rs`; no public API renames.
|
||||
|
||||
---
|
||||
|
||||
Self-review: This plan covers the recommended Core split first slice, avoids public Interface changes, has no placeholders, and keeps testing tied to the moved Implementations.
|
||||
@@ -0,0 +1,608 @@
|
||||
# Maintainability Continuation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Continue the current maintainability review with safe simplifications, full code-review remediation, current documentation, explicit fail-safe evidence, and Android runtime verification status.
|
||||
|
||||
**Current status:** Task 0 and the audio-realtime portion of Task 0.1 have landed in commits `d835394` and `8606eb4`. Task 0.2 is a documentation/status alignment slice only; it must not claim Android or iOS runtime success.
|
||||
|
||||
**Architecture:** Treat the existing uncommitted maintainability changes as the baseline slice. Fix safety and hidden-bug findings before broad Module splits. Preserve public Rust Core, Bridge, Protocol, Audio, and Flutter responsibilities while applying only tested simplifications and risk-reducing refactors. Record larger seam decisions as follow-up findings unless a huge Module must be split to make a safety fix testable.
|
||||
|
||||
**Tech Stack:** Rust 2021 Cargo workspace, Flutter/Dart 3.11, Flutter Rust Bridge 2.12, Android ADB, Markdown governance and verification documents.
|
||||
|
||||
---
|
||||
|
||||
## File Structure
|
||||
|
||||
Implementation should keep the following responsibilities stable:
|
||||
|
||||
- `core/chanora_core/src/lib.rs`: public Core API, session orchestration, public re-exports, and integration-facing methods.
|
||||
- `core/chanora_core/src/events.rs`: Core public event DTOs re-exported by `lib.rs`.
|
||||
- `core/chanora_core/src/network_diagnostics.rs`: private bounded network diagnostic history and its local regression tests.
|
||||
- `crates/chanora_audio/src/voice_render.rs`: shared render/downmix helpers.
|
||||
- `crates/chanora_audio/src/ios_raw_unit.rs`, `ios_voice_unit.rs`, `android_voice_unit.rs`, `engine.rs`: platform/audio backends; avoid broad rewrites without device evidence.
|
||||
- `crates/chanora_audio/src/ptt_backends/mod.rs`: PTT backend descriptor and error definitions.
|
||||
- `crates/chanora_state/src/lib.rs`: snapshot reducers and state deltas.
|
||||
- `crates/chanora_protocol/src/adapter.rs`: protocol adapter event ordering and DTO projection.
|
||||
- `crates/chanora_bridge/src/api.rs`: bridge-facing API and DTO mapping; generated files are not manually edited.
|
||||
- `crates/chanora_diagnostics/src/lib.rs`: bounded diagnostics, redaction, and export data.
|
||||
- `docs/governance/maintainability-review-2026-06-08.md`: working review record and fail-safe gap log.
|
||||
- `docs/governance/document-index.md`: navigation index for review records.
|
||||
- `docs/architecture/sad.md`, `docs/architecture/sdd.md`: architecture updates for seams and implementation boundaries.
|
||||
- `docs/implementation-status-2026-05-28.md`: implementation status updates.
|
||||
- `docs/verification/swe4-unit-verification-plan.md`, `docs/verification/swe5-software-integration-verification-plan.md`: verification evidence and requirements updates.
|
||||
|
||||
## Review Findings To Remediate First
|
||||
|
||||
The full review added these priority fixes before the original maintainability cleanup sequence:
|
||||
|
||||
- Flutter privacy fail-safe: talk-power recovery must not clear a user/manual mute. Fixed in commit `d835394`.
|
||||
- Flutter stuck-transmit fail-safe: touch PTT must release when disposed while held. Fixed in commit `d835394`.
|
||||
- Flutter/iOS fail-safe: iOS audio-session activation errors must be caught, and activation should be moved before Rust VoiceProcessingIO startup where the current app flow allows. Missing-plugin/error hardening fixed in commit `d835394`; iOS device runtime verification remains required.
|
||||
- Rust realtime safety: Android and iOS raw render-reference buffers must not use unsynchronized mutable aliasing. Callback-path hardening fixed in commit `8606eb4`; the full lock-free `AudioHandler` / config / debug-recorder redesign remains a follow-up.
|
||||
- Rust realtime safety: Android input callback must not block on a mutex, and non-48 kHz capture should not allocate/clone per callback. Focused callback-path hardening fixed in commit `8606eb4`; Android target compilation and runtime verification remain blocked locally until the missing NDK compiler and an authorized ADB target are available.
|
||||
- Rust control-plane safety: disconnect and protocol control requests must remain bounded under broken transport or sustained voice traffic.
|
||||
- Governance correctness: README/release/VAD/Android API/product-decision docs must not contradict code or verification status.
|
||||
|
||||
## Task 0: Fix Flutter Privacy and Stuck-Transmit Fail-Safes
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart`
|
||||
- Modify: `apps/chanora_flutter/lib/widgets/voice_compact.dart`
|
||||
- Modify: `apps/chanora_flutter/lib/services/ios_audio_session_controller.dart`
|
||||
- Test: `apps/chanora_flutter/test/widgets/voice_compact_test.dart`
|
||||
- Test: existing Flutter tests under `apps/chanora_flutter/test/`
|
||||
|
||||
- [ ] **Step 1: Add failing touch PTT disposal regression test**
|
||||
|
||||
Create or update `apps/chanora_flutter/test/widgets/voice_compact_test.dart` with a widget test that presses the touch PTT button, replaces the widget without sending pointer-up, and expects the callback sequence `[true, false]`.
|
||||
|
||||
- [ ] **Step 2: Run touch PTT test and verify RED**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter test test/widgets/voice_compact_test.dart`
|
||||
|
||||
Expected before production fix: FAIL because disposal does not emit `false`.
|
||||
|
||||
- [ ] **Step 3: Implement touch PTT release-on-dispose**
|
||||
|
||||
Add `dispose()` to the touch PTT button state so an active press calls `widget.onHeldChanged(false)` exactly once before disposal.
|
||||
|
||||
- [ ] **Step 4: Run touch PTT test and verify GREEN**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter test test/widgets/voice_compact_test.dart`
|
||||
|
||||
Expected after fix: PASS.
|
||||
|
||||
- [ ] **Step 5: Add or preserve mute-owner regression coverage**
|
||||
|
||||
If an existing pure reducer seam is available, add a failing test for manual mute true -> talk power blocked -> talk power restored. If no testable seam exists, first extract the smallest voice mute owner helper from `main.dart` and test it directly.
|
||||
|
||||
- [ ] **Step 6: Implement independent mute owners**
|
||||
|
||||
Ensure talk-power recovery clears only the talk-power owner and does not clear manual/user mute or permission mute. Effective hard mute is the OR of manual, permission, and talk-power owners.
|
||||
|
||||
- [ ] **Step 7: Harden iOS audio-session controller errors**
|
||||
|
||||
Add tests for `MissingPluginException` in `ios_audio_session_controller_test.dart`, then catch `MissingPluginException` or `Object` so activation/deactivation failures do not become unhandled async errors.
|
||||
|
||||
- [ ] **Step 8: Run focused Flutter verification**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter test test/widgets/voice_compact_test.dart test/services/ios_audio_session_controller_test.dart && flutter analyze`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 9: Commit Flutter fail-safe slice**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add apps/chanora_flutter/lib/main.dart apps/chanora_flutter/lib/widgets/voice_compact.dart apps/chanora_flutter/lib/services/ios_audio_session_controller.dart apps/chanora_flutter/test/widgets/voice_compact_test.dart apps/chanora_flutter/test/services/ios_audio_session_controller_test.dart
|
||||
git commit -m "fix(voice): preserve mute owners and release touch ptt"
|
||||
```
|
||||
|
||||
Expected: one commit containing only Flutter fail-safe fixes and tests.
|
||||
|
||||
## Task 0.1: Fix Rust Realtime and Control-Plane Safety Findings
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/chanora_audio/src/android_voice_unit.rs`
|
||||
- Modify: `crates/chanora_audio/src/ios_raw_unit.rs`
|
||||
- Modify: `crates/chanora_audio/src/engine.rs`
|
||||
- Modify: `crates/chanora_protocol/src/adapter.rs`
|
||||
- Modify: `core/chanora_core/src/lib.rs`
|
||||
- Test: Rust tests in affected crates
|
||||
|
||||
- [ ] **Step 1: Add failing bounded-buffer regression for render-reference handoff**
|
||||
|
||||
Add host-testable unit coverage around the render-reference buffer behavior so a writer can publish a frame and a reader can read a complete latest frame without unsynchronized mutation.
|
||||
|
||||
- [ ] **Step 2: Replace unsafe shared mutable render-reference buffers**
|
||||
|
||||
Replace unsynchronized mutable aliasing in Android and iOS raw render-reference buffers with a realtime-safe handoff such as an `ArrayQueue` of complete frames or a documented atomic double-buffer. Do not add mutex locking to realtime callbacks.
|
||||
|
||||
- [ ] **Step 3: Add failing protocol progress regression where feasible**
|
||||
|
||||
Add or isolate a test proving control requests are not starved by sustained voice packet drain.
|
||||
|
||||
- [ ] **Step 4: Bound voice draining and disconnect shutdown**
|
||||
|
||||
Cap voice packet draining per protocol loop and make disconnect/shutdown bounded so UI/Core locks are not held across unbounded transport waits.
|
||||
|
||||
- [ ] **Step 5: Run focused Rust verification**
|
||||
|
||||
Run: `cargo test -p chanora_audio -p chanora_protocol -p chanora_core`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 6: Commit Rust safety slice**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_audio/src/android_voice_unit.rs crates/chanora_audio/src/ios_raw_unit.rs crates/chanora_audio/src/engine.rs crates/chanora_protocol/src/adapter.rs core/chanora_core/src/lib.rs
|
||||
git commit -m "fix(audio): harden realtime and protocol fail-safes"
|
||||
```
|
||||
|
||||
Expected: one commit containing only Rust safety fixes and tests.
|
||||
|
||||
## Task 0.2: Align Review Findings With Specs, Plans, and Governance Docs
|
||||
|
||||
**Status:** In progress / documentation-only alignment. Do not commit from this task unless explicitly requested.
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/superpowers/specs/2026-06-08-maintainability-continuation-design.md`
|
||||
- Modify: `docs/superpowers/plans/2026-06-08-maintainability-continuation.md`
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md`
|
||||
- Modify: `README.md`
|
||||
- Modify if needed: `CHANGELOG.md`
|
||||
- Modify if needed: `docs/governance/product-decision-register.md`
|
||||
- Modify if needed: `docs/release/release-readiness-go-nogo-record.md`
|
||||
- Modify if needed: `docs/release/dv-waiver-register.md`
|
||||
- Modify if needed: `docs/verification/verification-master-plan.md`
|
||||
- Modify if needed: `docs/verification/sys4-system-integration-verification-plan.md`
|
||||
|
||||
- [x] **Step 1: Record full-review findings in maintainability review**
|
||||
|
||||
Update `docs/governance/maintainability-review-2026-06-08.md` with the full code-review findings, fixed items, blocked items, and follow-up Module split candidates.
|
||||
|
||||
- [x] **Step 2: Fix stale platform/release claims**
|
||||
|
||||
Update Android minimum runtime claims to API 28 where code and requirements require it. Update release metadata so Flutter app version/build and Rust workspace version are clearly distinguished.
|
||||
|
||||
- [x] **Step 3: Clarify VAD/VoiceActivity status**
|
||||
|
||||
Document the difference between VAD scaffolding/assets/tests and product-enabled VoiceActivity behavior. Do not claim runtime VoiceActivity is shipped unless verified.
|
||||
|
||||
- [x] **Step 4: Promote Android runtime verification blocker**
|
||||
|
||||
Add Android ADB/build/install/smoke as a blocker or waiver in governing release/verification docs when no authorized target is connected.
|
||||
|
||||
- [ ] **Step 5: Commit plan/spec/governance alignment slice**
|
||||
|
||||
Skipped in this subagent run because the instruction for Task 0.2 explicitly says not to commit.
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add docs/superpowers/specs/2026-06-08-maintainability-continuation-design.md docs/superpowers/plans/2026-06-08-maintainability-continuation.md docs/governance/maintainability-review-2026-06-08.md README.md CHANGELOG.md docs/governance/product-decision-register.md docs/release/release-readiness-go-nogo-record.md docs/release/dv-waiver-register.md docs/verification/verification-master-plan.md docs/verification/sys4-system-integration-verification-plan.md
|
||||
git commit -m "docs: align review findings and verification gates"
|
||||
```
|
||||
|
||||
Expected: one documentation/governance commit, with unavailable optional files omitted only if unchanged.
|
||||
|
||||
## Task 1: Verify Current Branch Baseline
|
||||
|
||||
**Files:**
|
||||
- Read: `docs/governance/maintainability-review-2026-06-08.md`
|
||||
- Read: `docs/superpowers/plans/2026-06-08-core-internal-split.md`
|
||||
- Inspect: all currently modified files from `git status --short`
|
||||
- Modify: none unless verification exposes a small mechanical fix
|
||||
|
||||
- [ ] **Step 1: Inspect current status**
|
||||
|
||||
Run: `git status --short`
|
||||
|
||||
Expected: output includes the existing maintainability branch changes and no staged files from unrelated work.
|
||||
|
||||
- [ ] **Step 2: Inspect current diff summary**
|
||||
|
||||
Run: `git diff --stat`
|
||||
|
||||
Expected: diff remains focused on Core split, Audio simplifications, State/Protocol/Bridge/Diagnostics cleanup, and documentation updates.
|
||||
|
||||
- [ ] **Step 3: Verify Rust formatting**
|
||||
|
||||
Run: `cargo fmt --all --check`
|
||||
|
||||
Expected: PASS with no output. If it fails, run `cargo fmt --all`, inspect the resulting diff, and include formatter-only changes in the smallest relevant commit.
|
||||
|
||||
- [ ] **Step 4: Verify Rust compilation**
|
||||
|
||||
Run: `cargo check --workspace`
|
||||
|
||||
Expected: PASS for the full workspace.
|
||||
|
||||
- [ ] **Step 5: Verify Rust tests**
|
||||
|
||||
Run: `cargo test --workspace`
|
||||
|
||||
Expected: PASS for the full workspace.
|
||||
|
||||
- [ ] **Step 6: Verify Flutter analysis**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter analyze`
|
||||
|
||||
Expected: PASS with no new analyzer errors.
|
||||
|
||||
- [ ] **Step 7: Verify Flutter tests**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter test --exclude-tags e2e`
|
||||
|
||||
Expected: PASS for non-e2e Flutter tests.
|
||||
|
||||
- [ ] **Step 8: Check Android device availability**
|
||||
|
||||
Run: `adb devices -l`
|
||||
|
||||
Expected if a target is connected: at least one `device` row. Expected if no target is connected: only the header and no `device` row; record Android runtime verification as blocked in `docs/governance/maintainability-review-2026-06-08.md`.
|
||||
|
||||
- [ ] **Step 9: Commit verified existing slice**
|
||||
|
||||
Only after Steps 1-8 have been completed or any blocked Android status has been documented, stage the smallest coherent existing slice.
|
||||
|
||||
Recommended first slice if tests pass:
|
||||
|
||||
```bash
|
||||
git add core/chanora_core/src/lib.rs core/chanora_core/src/events.rs core/chanora_core/src/network_diagnostics.rs docs/superpowers/plans/2026-06-08-core-internal-split.md
|
||||
git commit -m "refactor(core): split event and diagnostics internals"
|
||||
```
|
||||
|
||||
Expected: one commit containing only the Core split and its plan.
|
||||
|
||||
## Task 2: Commit Existing Built-In and Helper Reuse Simplifications
|
||||
|
||||
**Files:**
|
||||
- Modify or stage: `crates/chanora_audio/src/ptt_backends/mod.rs`
|
||||
- Modify or stage: `crates/chanora_audio/src/voice_render.rs`
|
||||
- Modify or stage: `crates/chanora_audio/src/ios_raw_unit.rs`
|
||||
- Modify or stage: `crates/chanora_diagnostics/src/lib.rs`
|
||||
- Modify or stage: `crates/chanora_state/src/lib.rs`
|
||||
- Modify or stage: `crates/chanora_resolver/Cargo.toml`
|
||||
- Modify or stage: `Cargo.lock`
|
||||
|
||||
- [ ] **Step 1: Inspect simplification diffs**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git diff -- crates/chanora_audio/src/ptt_backends/mod.rs crates/chanora_audio/src/voice_render.rs crates/chanora_audio/src/ios_raw_unit.rs crates/chanora_diagnostics/src/lib.rs crates/chanora_state/src/lib.rs crates/chanora_resolver/Cargo.toml Cargo.lock
|
||||
```
|
||||
|
||||
Expected: diffs show built-in/helper reuse only: `thiserror::Error`, `VecDeque`, render helper reuse, reducer reuse, and workspace metadata inheritance.
|
||||
|
||||
- [ ] **Step 2: Run focused Rust tests for changed areas**
|
||||
|
||||
Run: `cargo test -p chanora_audio -p chanora_diagnostics -p chanora_state -p chanora_resolver`
|
||||
|
||||
Expected: PASS for all listed crates.
|
||||
|
||||
- [ ] **Step 3: Run workspace Rust verification**
|
||||
|
||||
Run: `cargo check --workspace && cargo test --workspace`
|
||||
|
||||
Expected: PASS for workspace compile and tests.
|
||||
|
||||
- [ ] **Step 4: Commit built-in/helper reuse slice**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_audio/src/ptt_backends/mod.rs crates/chanora_audio/src/voice_render.rs crates/chanora_audio/src/ios_raw_unit.rs crates/chanora_diagnostics/src/lib.rs crates/chanora_state/src/lib.rs crates/chanora_resolver/Cargo.toml Cargo.lock
|
||||
git commit -m "refactor: reuse built-ins and shared helpers"
|
||||
```
|
||||
|
||||
Expected: one commit containing only the built-in/helper reuse simplifications.
|
||||
|
||||
## Task 3: Review Remaining Audio Platform Diffs Before Committing
|
||||
|
||||
**Files:**
|
||||
- Inspect: `crates/chanora_audio/src/android_voice_unit.rs`
|
||||
- Inspect: `crates/chanora_audio/src/engine.rs`
|
||||
- Inspect: `crates/chanora_audio/src/ios_voice_unit.rs`
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md` if Android runtime verification is blocked or audio fail-safe evidence changes
|
||||
|
||||
- [ ] **Step 1: Inspect platform-audio diffs**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git diff -- crates/chanora_audio/src/android_voice_unit.rs crates/chanora_audio/src/engine.rs crates/chanora_audio/src/ios_voice_unit.rs
|
||||
```
|
||||
|
||||
Expected: diffs are understandable as local simplification or fail-safe improvements. If a diff changes platform runtime behavior and no Android/iOS device evidence is available, keep it separate from non-platform commits.
|
||||
|
||||
- [ ] **Step 2: Run audio crate tests**
|
||||
|
||||
Run: `cargo test -p chanora_audio`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Check Android runtime availability**
|
||||
|
||||
Run: `adb devices -l`
|
||||
|
||||
Expected if connected: at least one target row with `device`. Expected if blocked: no target row.
|
||||
|
||||
- [ ] **Step 4: Run Android build when a target is available**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter build apk --debug`
|
||||
|
||||
Expected: PASS and a debug APK is produced.
|
||||
|
||||
- [ ] **Step 5: Run Android install and smoke when a target is available**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter install`
|
||||
|
||||
Expected: PASS and app installs on the connected target.
|
||||
|
||||
Manual smoke expectations:
|
||||
|
||||
- App launches without crash.
|
||||
- Permission UI can be reached.
|
||||
- Audio device/permission screen does not crash.
|
||||
- Voice controls remain responsive.
|
||||
|
||||
- [ ] **Step 6: Record blocked Android evidence if no target is available**
|
||||
|
||||
Modify `docs/governance/maintainability-review-2026-06-08.md` Section 6 so it includes the exact `adb devices -l` result and states Android runtime verification is blocked until a device or emulator is connected.
|
||||
|
||||
- [ ] **Step 7: Commit platform-audio slice**
|
||||
|
||||
If Android runtime was verified, run:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_audio/src/android_voice_unit.rs crates/chanora_audio/src/engine.rs crates/chanora_audio/src/ios_voice_unit.rs docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "refactor(audio): simplify platform voice internals"
|
||||
```
|
||||
|
||||
If Android runtime was blocked, run:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_audio/src/android_voice_unit.rs crates/chanora_audio/src/engine.rs crates/chanora_audio/src/ios_voice_unit.rs docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "refactor(audio): simplify platform voice internals"
|
||||
```
|
||||
|
||||
Expected: commit message is the same, but the maintainability review explicitly records the blocked Android runtime evidence.
|
||||
|
||||
## Task 4: Review Protocol and Bridge Diffs as One Boundary Slice
|
||||
|
||||
**Files:**
|
||||
- Inspect: `crates/chanora_protocol/src/adapter.rs`
|
||||
- Inspect: `crates/chanora_bridge/src/api.rs`
|
||||
- Modify: `docs/architecture/sad.md`
|
||||
- Modify: `docs/architecture/sdd.md`
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md`
|
||||
|
||||
- [ ] **Step 1: Inspect protocol/bridge diffs**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git diff -- crates/chanora_protocol/src/adapter.rs crates/chanora_bridge/src/api.rs
|
||||
```
|
||||
|
||||
Expected: diffs preserve protocol isolation and bridge DTO shape unless bridge generation and Flutter tests are included.
|
||||
|
||||
- [ ] **Step 2: Verify protocol tests**
|
||||
|
||||
Run: `cargo test -p chanora_protocol`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Verify bridge tests and compile**
|
||||
|
||||
Run: `cargo test -p chanora_bridge`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 4: Verify Flutter after bridge/API changes**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter analyze && flutter test --exclude-tags e2e`
|
||||
|
||||
Expected: PASS for analyzer and non-e2e tests.
|
||||
|
||||
- [ ] **Step 5: Document seam findings**
|
||||
|
||||
Update `docs/governance/maintainability-review-2026-06-08.md` so remaining bridge DTO drift and protocol voice packet seam risks are listed under fail-safe gaps or follow-up opportunities.
|
||||
|
||||
- [ ] **Step 6: Update architecture docs if seam wording changed**
|
||||
|
||||
If the code diff clarifies protocol/bridge boundaries, update `docs/architecture/sad.md` and `docs/architecture/sdd.md` with one concise note each. The note should state whether protocol voice packet handling is an intentional exception and whether bridge DTO mirrors remain required by Flutter Rust Bridge.
|
||||
|
||||
- [ ] **Step 7: Commit protocol/bridge slice**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_protocol/src/adapter.rs crates/chanora_bridge/src/api.rs docs/architecture/sad.md docs/architecture/sdd.md docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "refactor: clarify protocol bridge boundaries"
|
||||
```
|
||||
|
||||
Expected: one commit for protocol/bridge boundary cleanup plus matching architecture documentation.
|
||||
|
||||
## Task 5: Run a Second-Pass Simplification Search
|
||||
|
||||
**Files:**
|
||||
- Inspect: Rust and Dart source files only
|
||||
- Modify: only if the simplification is mechanical, local, and covered by tests
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md`
|
||||
|
||||
- [ ] **Step 1: Search for custom queue front removal**
|
||||
|
||||
Run: `rg "remove\(0\)|removeAt\(0\)" core crates apps/chanora_flutter/lib apps/chanora_flutter/test`
|
||||
|
||||
Expected: no results. If results exist, replace with `VecDeque` in Rust or a clearer Dart queue structure only when behavior is covered by a local test.
|
||||
|
||||
- [ ] **Step 2: Search for manual Rust error formatting**
|
||||
|
||||
Run: `rg "impl (std::fmt::)?Display for .*Error|impl std::error::Error for" core crates`
|
||||
|
||||
Expected: only intentional manual implementations remain. For simple enum error types, replace with `thiserror::Error` and add or preserve tests for user-facing strings.
|
||||
|
||||
- [ ] **Step 3: Search for duplicate mono downmix loops**
|
||||
|
||||
Run: `rg "chunks_exact\(2\)|downmix|mono" crates/chanora_audio/src`
|
||||
|
||||
Expected: duplicate i16/f32 mono downmix code is either absent or justified. If a duplicate remains, route it through an existing helper and run `cargo test -p chanora_audio`.
|
||||
|
||||
- [ ] **Step 4: Search for shallow modules worth documenting**
|
||||
|
||||
Run: `rg "^pub struct|^pub enum|^pub fn|^fn" crates/chanora_audio/src/processor crates/chanora_prefetch/src crates/chanora_resolver/src core/chanora_core/src`
|
||||
|
||||
Expected: identify candidates, but do not merge modules in this task. Record speculative merges in `docs/governance/maintainability-review-2026-06-08.md` unless a candidate is trivial and already covered by tests.
|
||||
|
||||
- [ ] **Step 5: Commit second-pass mechanical simplifications if any**
|
||||
|
||||
If code changed, run the relevant focused tests plus `cargo check --workspace && cargo test --workspace`, then inspect the changed files:
|
||||
|
||||
```bash
|
||||
git status --short
|
||||
```
|
||||
|
||||
Stage only the files changed by the second-pass mechanical simplification. Example for a Rust-only diagnostics simplification:
|
||||
|
||||
```bash
|
||||
git add crates/chanora_diagnostics/src/lib.rs docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "refactor: apply second-pass mechanical simplifications"
|
||||
```
|
||||
|
||||
Expected: commit contains only local mechanical simplifications and the review record.
|
||||
|
||||
- [ ] **Step 6: Commit review-only findings if no code changed**
|
||||
|
||||
If no code changed and only findings were added, run:
|
||||
|
||||
```bash
|
||||
git add docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "docs: record maintainability follow-up findings"
|
||||
```
|
||||
|
||||
Expected: documentation-only commit.
|
||||
|
||||
## Task 6: Final Documentation Alignment
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md`
|
||||
- Modify: `docs/governance/document-index.md`
|
||||
- Modify: `docs/implementation-status-2026-05-28.md`
|
||||
- Modify: `docs/verification/swe4-unit-verification-plan.md`
|
||||
- Modify: `docs/verification/swe5-software-integration-verification-plan.md`
|
||||
- Modify if needed: `docs/architecture/sad.md`
|
||||
- Modify if needed: `docs/architecture/sdd.md`
|
||||
|
||||
- [ ] **Step 1: Update maintainability review completion status**
|
||||
|
||||
Edit `docs/governance/maintainability-review-2026-06-08.md` so these sections are current:
|
||||
|
||||
- Changes applied
|
||||
- Remaining simplification opportunities
|
||||
- Fail-safe gaps that need evidence
|
||||
- Verification policy
|
||||
- Android ADB status
|
||||
- Git policy
|
||||
|
||||
- [ ] **Step 2: Update document index**
|
||||
|
||||
Ensure `docs/governance/document-index.md` includes `docs/governance/maintainability-review-2026-06-08.md` and this plan/spec if the repository convention indexes superpowers documents.
|
||||
|
||||
- [ ] **Step 3: Update implementation status**
|
||||
|
||||
Ensure `docs/implementation-status-2026-05-28.md` describes maintainability review results without claiming production readiness.
|
||||
|
||||
- [ ] **Step 4: Update SWE.4 verification plan**
|
||||
|
||||
Ensure `docs/verification/swe4-unit-verification-plan.md` lists Rust unit verification expectations for Core, Audio, State, Protocol, Bridge, Diagnostics, Resolver, and Prefetch when those crates are touched.
|
||||
|
||||
- [ ] **Step 5: Update SWE.5 verification plan**
|
||||
|
||||
Ensure `docs/verification/swe5-software-integration-verification-plan.md` lists integration expectations for Bridge DTO drift, protocol event folding, Flutter analyze/test, and Android runtime smoke evidence.
|
||||
|
||||
- [ ] **Step 6: Run documentation cross-link search**
|
||||
|
||||
Run: `rg "maintainability-review-2026-06-08|core-internal-split|maintainability-continuation" docs README.md`
|
||||
|
||||
Expected: references point to existing files and no stale path is introduced.
|
||||
|
||||
- [ ] **Step 7: Commit final documentation alignment**
|
||||
|
||||
Run:
|
||||
|
||||
```bash
|
||||
git add docs/governance/maintainability-review-2026-06-08.md docs/governance/document-index.md docs/implementation-status-2026-05-28.md docs/verification/swe4-unit-verification-plan.md docs/verification/swe5-software-integration-verification-plan.md docs/architecture/sad.md docs/architecture/sdd.md
|
||||
git commit -m "docs: align maintainability verification records"
|
||||
```
|
||||
|
||||
Expected: one documentation-focused commit.
|
||||
|
||||
## Task 7: Final Verification and Android Evidence
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/governance/maintainability-review-2026-06-08.md` only if final verification status changes
|
||||
|
||||
- [ ] **Step 1: Run full Rust verification**
|
||||
|
||||
Run: `cargo fmt --all --check && cargo check --workspace && cargo test --workspace`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 2: Run full Flutter verification**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter analyze && flutter test --exclude-tags e2e`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [ ] **Step 3: Run ADB check**
|
||||
|
||||
Run: `adb devices -l`
|
||||
|
||||
Expected if connected: at least one target row with `device`. Expected if blocked: no target row and the maintainability review states Android runtime verification is blocked.
|
||||
|
||||
- [ ] **Step 4: Run Android build/install/smoke when connected**
|
||||
|
||||
Run from `apps/chanora_flutter`: `flutter build apk --debug && flutter install`
|
||||
|
||||
Expected: PASS. Manually verify app launch, permission screen access, audio settings access, and voice control responsiveness.
|
||||
|
||||
- [ ] **Step 5: Commit final verification evidence if docs changed**
|
||||
|
||||
If the maintainability review was updated with final verification evidence, run:
|
||||
|
||||
```bash
|
||||
git add docs/governance/maintainability-review-2026-06-08.md
|
||||
git commit -m "docs: record maintainability verification evidence"
|
||||
```
|
||||
|
||||
Expected: one small evidence-only documentation commit.
|
||||
|
||||
- [ ] **Step 6: Inspect final history and status**
|
||||
|
||||
Run: `git status --short && git log --oneline -10`
|
||||
|
||||
Expected: no unexpected unstaged changes related to this work; recent commits are small and logically separated.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
Spec coverage:
|
||||
|
||||
- Safe simplifications are covered by Tasks 1, 2, 3, 4, and 5.
|
||||
- Built-in replacement opportunities are covered by Tasks 2 and 5.
|
||||
- Fail-safe gaps are covered by Tasks 3, 4, 6, and 7.
|
||||
- Rust, Flutter, and Android verification are covered by Tasks 1 and 7, with focused verification in Tasks 2 through 4.
|
||||
- Documentation updates are covered by Tasks 4, 6, and 7.
|
||||
- Small commit policy is covered by every task's dedicated commit step.
|
||||
|
||||
Placeholder scan: The plan contains no open placeholders. Task 5 uses `git status --short` before staging because the exact second-pass files are only known after the search runs; the example command shows the required staging style.
|
||||
|
||||
Type consistency: The plan does not introduce new APIs or types. It preserves current crate and file boundaries from the approved design.
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,114 @@
|
||||
# DV Evidence Pack Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Create a document set that lets a DV meeting review Chanora's current verification posture, traceability, release blockers, waivers, and evidence without implying incomplete work is complete.
|
||||
|
||||
**Architecture:** The pack is documentation-only. Verification plans live under `docs/verification/`; release decision evidence lives under `docs/release/`; cross-document traceability lives under `docs/governance/`; security, privacy, and legal gate summaries live in their existing README-advertised folders.
|
||||
|
||||
**Tech Stack:** Markdown, existing SysRS/SysDes/SRS baselines, implementation status report, CI workflow definitions.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Create Verification Plan Set
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/verification/verification-master-plan.md`
|
||||
- Create: `docs/verification/swe4-unit-verification-plan.md`
|
||||
- Create: `docs/verification/swe5-software-integration-verification-plan.md`
|
||||
- Create: `docs/verification/swe6-software-verification-plan.md`
|
||||
- Create: `docs/verification/sys4-system-integration-verification-plan.md`
|
||||
|
||||
- [x] **Step 1: Write master plan**
|
||||
|
||||
Create `docs/verification/verification-master-plan.md` with lifecycle scope, evidence rules, entry/exit criteria, current evidence sources, open gates, and reviewer decision framing.
|
||||
|
||||
- [x] **Step 2: Write SWE.4 plan**
|
||||
|
||||
Create `docs/verification/swe4-unit-verification-plan.md` with unit verification scope for Rust crates, Flutter services/widgets, diagnostics, storage, state reducers, audio DSP, and known unit-test gaps.
|
||||
|
||||
- [x] **Step 3: Write SWE.5 plan**
|
||||
|
||||
Create `docs/verification/swe5-software-integration-verification-plan.md` with cross-component integration scope for Flutter-bridge-core, protocol-state, audio-platform, secure storage, diagnostics export, resolver prefetch, and packaging hooks.
|
||||
|
||||
- [x] **Step 4: Write SWE.6 plan**
|
||||
|
||||
Create `docs/verification/swe6-software-verification-plan.md` with SRS-level acceptance scope and the SysRS-241 through SysRS-257 MVP acceptance matrix.
|
||||
|
||||
- [x] **Step 5: Write SYS.4 plan**
|
||||
|
||||
Create `docs/verification/sys4-system-integration-verification-plan.md` with system-level integration scope for external compatible servers, OS services, hardware, network, app stores, diagnostics, and release evidence.
|
||||
|
||||
### Task 2: Create Release and DV Decision Records
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/release/release-readiness-go-nogo-record.md`
|
||||
- Create: `docs/release/dv-waiver-register.md`
|
||||
|
||||
- [x] **Step 1: Write release readiness record**
|
||||
|
||||
Create `docs/release/release-readiness-go-nogo-record.md` with current candidate metadata, decision state, platform readiness, verification status, legal/security/privacy gates, blockers, and meeting recommendation.
|
||||
|
||||
- [x] **Step 2: Write waiver register**
|
||||
|
||||
Create `docs/release/dv-waiver-register.md` with explicit waivers for DEC-012, Android Keystore DEK, iOS voice-processing mode, source-build-only desktop/iOS artifacts, state reducer coverage, and VAD deferral.
|
||||
|
||||
### Task 3: Create Traceability and Gate Summaries
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/governance/traceability-matrix.md`
|
||||
- Create: `docs/security/security-privacy-legal-guideline.md`
|
||||
- Create: `docs/security/dependency-and-supply-chain-report.md`
|
||||
- Create: `docs/privacy/privacy-policy.md`
|
||||
- Create: `docs/legal/trademark-and-attribution-review.md`
|
||||
|
||||
- [x] **Step 1: Write traceability matrix**
|
||||
|
||||
Create `docs/governance/traceability-matrix.md` summarizing SysRS to SysDes to SRS to verification coverage, including the MVP acceptance and verification handoff items.
|
||||
|
||||
- [x] **Step 2: Write security/privacy/legal guideline**
|
||||
|
||||
Create `docs/security/security-privacy-legal-guideline.md` summarizing release gates and evidence expectations for secure storage, diagnostics redaction, dependency review, privacy policy, and affiliation wording.
|
||||
|
||||
- [x] **Step 3: Write dependency report**
|
||||
|
||||
Create `docs/security/dependency-and-supply-chain-report.md` summarizing current CI checks and open evidence gaps without claiming DEC-012 completion.
|
||||
|
||||
- [x] **Step 4: Write privacy policy baseline**
|
||||
|
||||
Create `docs/privacy/privacy-policy.md` as an engineering release-candidate privacy baseline covering local storage, permissions, diagnostics, and the no automatic telemetry posture.
|
||||
|
||||
- [x] **Step 5: Write trademark review**
|
||||
|
||||
Create `docs/legal/trademark-and-attribution-review.md` with current non-affiliation wording requirement and open legal sign-off state.
|
||||
|
||||
### Task 4: Verify Documentation Pack
|
||||
|
||||
**Files:**
|
||||
- Inspect all created files.
|
||||
|
||||
- [x] **Step 1: Search for forbidden sentinel text**
|
||||
|
||||
Run the sentinel-language scan over `docs/verification`, `docs/release`, `docs/governance`, `docs/security`, `docs/privacy`, and `docs/legal`.
|
||||
|
||||
Expected: no matches introduced by the DV evidence pack except intentional historical references in source documents outside these folders.
|
||||
|
||||
- [x] **Step 2: Confirm expected files exist**
|
||||
|
||||
Run: `ls docs/verification docs/release docs/governance docs/security docs/privacy docs/legal`
|
||||
|
||||
Expected: all DV evidence pack files are listed.
|
||||
|
||||
- [x] **Step 3: Inspect git status and diff**
|
||||
|
||||
Run: `git diff -- docs/verification docs/release docs/governance docs/security docs/privacy docs/legal docs/superpowers/plans/2026-05-29-dv-evidence-pack.md`
|
||||
|
||||
Expected: only intended Markdown additions are present.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: covers verification plan set, release decision evidence, waiver register, traceability matrix, and minimum security/privacy/legal gate summaries.
|
||||
- Placeholder scan: plan contains no incomplete instructions.
|
||||
- Type consistency: document paths match the README-advertised folders and task file list.
|
||||
@@ -0,0 +1,79 @@
|
||||
# Finish DV Document Tree Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Fill the README-advertised document tree with baseline candidate documents so DV reviewers can navigate all required gates.
|
||||
|
||||
**Architecture:** Keep canonical large baselines at current root paths and add README-path stubs or summaries where needed. Governance, release, security, privacy, legal, UI/UX, i18n, and references each get explicit baseline documents that state current evidence and open gates honestly.
|
||||
|
||||
**Tech Stack:** Markdown documentation aligned to SysRS, SysDes, SRS, SAD, SDD, verification, release, and implementation status.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Add Requirements Path Wrappers
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/requirements/sysrs.md`
|
||||
- Create: `docs/requirements/srs.md`
|
||||
|
||||
- [x] **Step 1: Create README entry records that point to canonical root documents and summarize DV review anchors**
|
||||
|
||||
These wrappers preserve README paths without duplicating the canonical baselines.
|
||||
|
||||
### Task 2: Add Governance Baselines
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/governance/document-index.md`
|
||||
- Create: `docs/governance/document-naming-convention.md`
|
||||
- Create: `docs/governance/baseline-approval-record.md`
|
||||
- Create: `docs/governance/baseline-candidate-validation-report.md`
|
||||
- Create: `docs/governance/document-review-report.md`
|
||||
- Create: `docs/governance/product-decision-register.md`
|
||||
- Create: `docs/governance/decision-impact-assessment.md`
|
||||
- Create: `docs/governance/git-commit-message-convention.md`
|
||||
- Create: `docs/governance/repo-format-validation-report.md`
|
||||
- Create: `docs/governance/path-migration-map.md`
|
||||
|
||||
- [x] **Step 1: Write governance records**
|
||||
|
||||
Each record summarizes status for DV, identifies owner expectations, and avoids claiming final release approval.
|
||||
|
||||
### Task 3: Add Remaining Release, Security, UI/UX, I18n, Reference Docs
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/release/platform-release-policy.md`
|
||||
- Create: `docs/security/threat-model.md`
|
||||
- Create: `docs/security/secure-storage-audit-report.md`
|
||||
- Create: `docs/security/diagnostic-redaction-audit-report.md`
|
||||
- Create: `docs/ui-ux/material3-guideline.md`
|
||||
- Create: `docs/ui-ux/material3-design-tokens.md`
|
||||
- Create: `docs/ui-ux/material3-component-catalog.md`
|
||||
- Create: `docs/ui-ux/adaptive-layout-platform-guide.md`
|
||||
- Create: `docs/i18n/localization-architecture.md`
|
||||
- Create: `docs/references/external-references.md`
|
||||
- Create: `docs/references/aspice-swe2-swe3-integration-note.md`
|
||||
|
||||
- [x] **Step 1: Write remaining baseline docs**
|
||||
|
||||
Use concise DV-ready records that reference current implementation and open gaps.
|
||||
|
||||
### Task 4: Verify Complete Tree
|
||||
|
||||
**Files:**
|
||||
- Inspect all created documents.
|
||||
|
||||
- [x] **Step 1: Check README paths exist**
|
||||
|
||||
Run a shell `test -f` command over every README-advertised path.
|
||||
|
||||
- [x] **Step 2: Sentinel-language scan**
|
||||
|
||||
Run the sentinel-language scan over `docs/requirements`, `docs/architecture`, `docs/verification`, `docs/release`, `docs/security`, `docs/privacy`, `docs/legal`, `docs/ui-ux`, `docs/i18n`, `docs/governance`, and `docs/references`; expect no matches.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: fills all README-advertised document paths except already existing files.
|
||||
- Placeholder scan: plan contains no incomplete document instructions.
|
||||
- Type consistency: file paths match README tree.
|
||||
@@ -0,0 +1,108 @@
|
||||
# State Sync and UI Settings Validation Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Complete validation-backed state-sync evidence and UI settings persistence while updating DV documents.
|
||||
|
||||
**Architecture:** State reducer work stays in `crates/chanora_state/src/lib.rs` with Rust unit tests. UI settings persistence stays in `apps/chanora_flutter/lib/services/ui_preferences_service.dart` with Flutter service tests; app-level theme application is wired in `apps/chanora_flutter/lib/main.dart` only if needed by the persisted setting.
|
||||
|
||||
**Tech Stack:** Rust/cargo tests, Flutter/Dart, shared_preferences, Markdown documentation.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: State Reducer Validation
|
||||
|
||||
**Files:**
|
||||
- Modify: `crates/chanora_state/src/lib.rs`
|
||||
|
||||
- [x] **Step 1: Write failing regression test**
|
||||
|
||||
Add `channel_delete_removes_clients_in_deleted_channel` proving channel deletion removes clients assigned to that channel and emits client-removal deltas before the channel-removal delta.
|
||||
|
||||
- [x] **Step 2: Verify RED**
|
||||
|
||||
Run: `cargo test -p chanora_state channel_delete_removes_clients_in_deleted_channel --locked`
|
||||
|
||||
Expected: FAIL because deleted-channel clients remain in state.
|
||||
|
||||
- [x] **Step 3: Implement minimal reducer fix**
|
||||
|
||||
In `StateEvent::ChannelDeleted`, collect clients whose `client.channel == id`, remove them from `clients` and `client_order`, then emit deterministic `ClientRemoved` deltas before `ChannelRemoved`.
|
||||
|
||||
- [x] **Step 4: Verify GREEN**
|
||||
|
||||
Run: `cargo test -p chanora_state channel_delete_removes_clients_in_deleted_channel --locked`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [x] **Step 5: Run full state crate tests**
|
||||
|
||||
Run: `cargo test -p chanora_state --locked`
|
||||
|
||||
Expected: all state crate tests pass.
|
||||
|
||||
### Task 2: UI Settings Persistence
|
||||
|
||||
**Files:**
|
||||
- Modify: `apps/chanora_flutter/lib/services/ui_preferences_service.dart`
|
||||
- Modify: `apps/chanora_flutter/test/services/ui_preferences_service_test.dart`
|
||||
- Modify: `apps/chanora_flutter/lib/main.dart`
|
||||
|
||||
- [x] **Step 1: Add failing tests for theme persistence**
|
||||
|
||||
Add tests for default `system` theme mode, saving `dark`, saving `light`, and invalid stored value fallback to `system`.
|
||||
|
||||
- [x] **Step 2: Verify RED**
|
||||
|
||||
Run: `flutter test test/services/ui_preferences_service_test.dart`
|
||||
|
||||
Expected: FAIL because `UiThemeMode`, `themeMode`, and `saveThemeMode` do not exist.
|
||||
|
||||
- [x] **Step 3: Implement minimal service changes**
|
||||
|
||||
Add `UiThemeMode`, `UiSettings.themeMode`, persisted key `ui.theme_mode`, and `saveThemeMode`.
|
||||
|
||||
- [x] **Step 4: Verify GREEN**
|
||||
|
||||
Run: `flutter test test/services/ui_preferences_service_test.dart`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
- [x] **Step 5: Wire app theme mode**
|
||||
|
||||
Make `ChanoraApp` load persisted theme mode and pass `themeMode` into `MaterialApp`.
|
||||
|
||||
- [x] **Step 6: Run focused Flutter tests**
|
||||
|
||||
Run: `flutter test test/services/ui_preferences_service_test.dart`
|
||||
|
||||
Expected: PASS.
|
||||
|
||||
### Task 3: Documentation Updates
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/implementation-status-2026-05-28.md`
|
||||
- Modify: `docs/release/dv-waiver-register.md`
|
||||
- Modify: `docs/verification/swe4-unit-verification-plan.md`
|
||||
- Modify: `docs/verification/swe6-software-verification-plan.md`
|
||||
- Modify: `docs/architecture/sdd.md`
|
||||
|
||||
- [x] **Step 1: Update implementation status**
|
||||
|
||||
Mark `chanora_state` scaffold statement as superseded by reducer implementation/tests and mark UI settings persistence implemented for SharedPreferences scope.
|
||||
|
||||
- [x] **Step 2: Update waiver and verification docs**
|
||||
|
||||
Record reducer evidence and leave event replay as the remaining P1 state-sync gap.
|
||||
|
||||
- [x] **Step 3: Verify docs**
|
||||
|
||||
Run sentinel-language scan over edited docs.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: covers reducer evidence, UI settings persistence, and document updates.
|
||||
- Placeholder scan: plan contains no incomplete implementation instructions.
|
||||
- Type consistency: `UiThemeMode`, `themeMode`, and `saveThemeMode` names are used consistently.
|
||||
@@ -0,0 +1,68 @@
|
||||
# SWE.2/SWE.3 Baselines Implementation Plan
|
||||
|
||||
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
|
||||
|
||||
**Goal:** Add reviewable SWE.2/SAD and SWE.3/SDD baselines so the DV document chain is no longer missing the architecture and detailed design layers.
|
||||
|
||||
**Architecture:** Keep SWE.2 in `docs/architecture/sad.md` and SWE.3 in `docs/architecture/sdd.md`, matching the README document tree. Update DV traceability and verification-plan wording to consume these baselines while preserving honest limitations for areas that still need deeper detail.
|
||||
|
||||
**Tech Stack:** Markdown, existing SysDes/SRS baselines, current Flutter/Rust workspace structure.
|
||||
|
||||
---
|
||||
|
||||
### Task 1: Write SWE.2 SAD Baseline
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/architecture/sad.md`
|
||||
|
||||
- [x] **Step 1: Create SAD with architecture views**
|
||||
|
||||
Write sections for purpose, upstream sources, components, static view, runtime flows, interface catalogue, dependency rules, non-functional allocation, architectural decisions, verification handoff, traceability, and open architecture risks.
|
||||
|
||||
### Task 2: Write SWE.3 SDD Baseline
|
||||
|
||||
**Files:**
|
||||
- Create: `docs/architecture/sdd.md`
|
||||
|
||||
- [x] **Step 1: Create SDD with module designs**
|
||||
|
||||
Write sections for purpose, upstream sources, module catalogue, detailed API/data/state design, persistence, diagnostics, platform adapters, build/release design, verification hooks, traceability, and open detailed-design risks.
|
||||
|
||||
### Task 3: Update DV Traceability
|
||||
|
||||
**Files:**
|
||||
- Modify: `docs/governance/traceability-matrix.md`
|
||||
- Modify: `docs/verification/verification-master-plan.md`
|
||||
|
||||
- [x] **Step 1: Remove SAD/SDD missing limitation**
|
||||
|
||||
Update traceability text so it says SAD and SDD baselines exist, with known depth limitations instead of missing-document limitations.
|
||||
|
||||
- [x] **Step 2: Update verification plan inputs**
|
||||
|
||||
Update verification master plan to reference SAD and SDD as current inputs for SWE.4/SWE.5.
|
||||
|
||||
### Task 4: Verify SWE.2/SWE.3 Pack
|
||||
|
||||
**Files:**
|
||||
- Inspect created and updated docs.
|
||||
|
||||
- [x] **Step 1: Sentinel-language scan**
|
||||
|
||||
Run the sentinel-language scan over `docs/architecture`, `docs/governance`, and `docs/verification`.
|
||||
|
||||
Expected: no matches introduced by this baseline pack.
|
||||
|
||||
- [x] **Step 2: File presence check**
|
||||
|
||||
Run: `ls docs/architecture`
|
||||
|
||||
Expected: `sad.md` and `sdd.md` are listed.
|
||||
|
||||
---
|
||||
|
||||
## Self-Review
|
||||
|
||||
- Spec coverage: creates SAD and SDD baselines and updates DV traceability consumers.
|
||||
- Placeholder scan: no incomplete instructions are present.
|
||||
- Type consistency: document names match README paths.
|
||||
@@ -0,0 +1,116 @@
|
||||
# Chanora Server Prefetch Crate Design
|
||||
|
||||
Date: 2026-05-28
|
||||
|
||||
## Goal
|
||||
|
||||
Move server-resolution prefetch policy out of `chanora_core` into a focused Rust crate named `chanora_prefetch`, without changing connection behavior, Flutter APIs, or protocol dialing semantics.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- Do not change resolver behavior or DNS/SRV/TSDNS ordering.
|
||||
- Do not change `ConnectConfig.resolved_address` semantics in `chanora_protocol`.
|
||||
- Do not expose prefetch state in the UI.
|
||||
- Do not prefetch bookmarks or additional hosts.
|
||||
- Do not persist prefetched addresses.
|
||||
|
||||
## Architecture
|
||||
|
||||
Add a workspace member at `crates/chanora_prefetch`.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Normalize server host keys by trimming and lowercasing.
|
||||
- Track one active prefetch generation.
|
||||
- Store at most one successful prefetched socket address.
|
||||
- Reject stale async completions by generation.
|
||||
- Return a prefetched address only for an exact normalized host match.
|
||||
- Enforce the 2-minute freshness TTL.
|
||||
- Resolve server addresses by calling `chanora_resolver::ChanoraResolver::resolve_client_address`.
|
||||
- Log prefetch start, success, miss/stale, and failure diagnostics.
|
||||
|
||||
Dependencies:
|
||||
|
||||
- `chanora_resolver` for actual server address resolution.
|
||||
- `tokio` for `Mutex` and spawned prefetch tasks.
|
||||
- `tracing` for diagnostics.
|
||||
- `thiserror` for a narrow `ServerPrefetchError` public error type.
|
||||
|
||||
## Public API
|
||||
|
||||
The crate exposes this small async owner type:
|
||||
|
||||
```rust
|
||||
pub struct ServerPrefetcher { ... }
|
||||
|
||||
impl ServerPrefetcher {
|
||||
pub fn new() -> Self;
|
||||
pub async fn prefetch(&self, host: String) -> Result<(), ServerPrefetchError>;
|
||||
pub async fn fresh_match(&self, host: &str) -> Option<std::net::SocketAddr>;
|
||||
}
|
||||
```
|
||||
|
||||
`prefetch` returns after scheduling work, preserving the current invisible, non-blocking behavior. Empty normalized hosts are ignored successfully. Resolution failures are stored only as diagnostics and do not affect connect semantics.
|
||||
|
||||
## Core Integration
|
||||
|
||||
`chanora_core` replaces its private prefetch cache fields and helpers with `ServerPrefetcher`.
|
||||
|
||||
Core remains the trust boundary for connection config:
|
||||
|
||||
- It clears any caller-provided `ConnectConfig.resolved_address` before lookup.
|
||||
- It asks `ServerPrefetcher::fresh_match` for the current host.
|
||||
- It sets `dial_cfg.resolved_address` only from a fresh exact cache hit.
|
||||
- It stores supervisor/reconnect config with `resolved_address: None`.
|
||||
|
||||
The Flutter bridge keeps calling the same core API, `prefetch_server_resolution(host)`. No Dart API change is intended.
|
||||
|
||||
## Data Flow
|
||||
|
||||
1. Flutter host editing schedules `ChanoraSession::prefetch_server_resolution(host)`.
|
||||
2. Core delegates to `ServerPrefetcher::prefetch(host)`.
|
||||
3. The prefetcher normalizes the host, increments generation, and spawns resolver work.
|
||||
4. On success, the prefetcher stores the resolved socket address if the generation is still current.
|
||||
5. On connect, core prepares `(stored_cfg, dial_cfg)`.
|
||||
6. Core clears untrusted `resolved_address`, asks the prefetcher for a fresh exact match, and applies the result only to `dial_cfg`.
|
||||
7. Protocol uses `dial_cfg.resolved_address` if present; otherwise it resolves normally.
|
||||
|
||||
## Error Handling
|
||||
|
||||
- Prefetch failures remain invisible to users.
|
||||
- Prefetch failures are logged through `tracing`.
|
||||
- If prefetch misses, is stale, or fails, connect falls back to normal protocol resolution.
|
||||
- A caller-supplied `resolved_address` is never trusted by core.
|
||||
|
||||
## Testing
|
||||
|
||||
Move cache-policy tests from `chanora_core` into `chanora_prefetch`:
|
||||
|
||||
- fresh exact match returns the socket address.
|
||||
- stale entries are ignored.
|
||||
- different hosts are ignored.
|
||||
- stale generation completions are ignored.
|
||||
- blank normalized hosts return `Ok(())` and do not update generation or spawn resolver work.
|
||||
|
||||
Keep core tests for connection trust-boundary behavior:
|
||||
|
||||
- untrusted `resolved_address` is cleared on cache miss.
|
||||
- prepared stored/supervisor config has `resolved_address: None`.
|
||||
- prepared dial config can receive a fresh prefetched address.
|
||||
|
||||
Run at minimum:
|
||||
|
||||
- `cargo test -p chanora_prefetch --lib`
|
||||
- `cargo test -p chanora_core --lib`
|
||||
- `cargo test -p chanora_protocol --lib`
|
||||
|
||||
For final confidence, rerun the Android server connect smoke path that verifies prefetch logs and connected UI.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Workspace builds with the new crate member.
|
||||
- `chanora_core` no longer owns the prefetch cache implementation.
|
||||
- `chanora_prefetch` owns prefetch normalization, TTL, generation, storage, and resolver-backed warming.
|
||||
- Public Flutter and Rust protocol behavior is unchanged.
|
||||
- Existing server connect and reconnect safety tests pass.
|
||||
- Android connect still reaches the connected server UI and does not get stuck in `Connecting` or `Synchronizing`.
|
||||
@@ -0,0 +1,203 @@
|
||||
# Server Resolution Prefetch Design
|
||||
|
||||
Date: 2026-05-28
|
||||
|
||||
## Purpose
|
||||
|
||||
Reduce perceived server join latency by resolving the active TeamSpeak server address before the user taps Connect. Prefetch must be invisible, conservative, and safe: it may warm resolver state, but it must not change connection semantics or surface background errors to the user.
|
||||
|
||||
Recent Android testing showed resolver latency can dominate the first part of the connect flow. A prior fix bounded slow TS3 SRV discovery and removed Android's forced Cloudflare resolver. Prefetch builds on that by hiding remaining address-resolution work when the user has already entered or loaded a likely server address.
|
||||
|
||||
## Goals
|
||||
|
||||
- Prefetch only the active server address field.
|
||||
- Keep the feature invisible to users.
|
||||
- Reuse prefetched results only for exact normalized host matches.
|
||||
- Keep prefetched results fresh for 2 minutes.
|
||||
- Preserve today's Connect behavior when prefetch misses, fails, or is stale.
|
||||
- Avoid prefetching all bookmarks.
|
||||
- Avoid opening a TS3 session before the user taps Connect.
|
||||
|
||||
## Non-Goals
|
||||
|
||||
- No visible resolving, ready, or failed UI state.
|
||||
- No bookmark fan-out prefetch.
|
||||
- No persisted resolver cache across app launches.
|
||||
- No password, channel, or permission validation during prefetch.
|
||||
- No server reachability probe beyond address resolution.
|
||||
- No connection warm-up or pre-authentication.
|
||||
|
||||
## Chosen Approach
|
||||
|
||||
Use a Rust-owned resolver prefetch cache with Flutter-owned scheduling.
|
||||
|
||||
Flutter knows when the active host field changes, so it schedules prefetch requests. Rust owns resolver correctness, normalization, cache validity, and connect-time reuse. This keeps Flutter from depending on resolver internals and ensures Connect can independently decide whether a prefetched result is safe to use.
|
||||
|
||||
Other approaches considered:
|
||||
|
||||
- Flutter-only prefetch: rejected because it pushes resolver state into Dart and creates a weaker boundary between UI and connection behavior.
|
||||
- Resolver-internal repeated-call cache only: rejected because it does not hide first-click latency from the active host field.
|
||||
|
||||
## Behavior
|
||||
|
||||
Prefetch starts for the active host value in two cases:
|
||||
|
||||
- After `_loadUiSettings()` loads the last-used host into `_hostCtl`.
|
||||
- After the user stops editing the host field for about 700 ms.
|
||||
|
||||
The feature is invisible:
|
||||
|
||||
- No SnackBars.
|
||||
- No inline status text.
|
||||
- No disabled Connect button.
|
||||
- No user-facing error if prefetch fails.
|
||||
|
||||
Connect behavior:
|
||||
|
||||
- If the current normalized host exactly matches a fresh prefetched entry, Connect uses the cached resolved address.
|
||||
- If the cache is missing, stale, failed, or for a different host, Connect resolves normally.
|
||||
- Connect remains the only operation that opens a TS3 session.
|
||||
|
||||
## Architecture
|
||||
|
||||
### Flutter Scheduling
|
||||
|
||||
`_BetaHomeState` owns the host text field. It should add a listener to `_hostCtl` and manage a short debounce timer.
|
||||
|
||||
Responsibilities:
|
||||
|
||||
- Trim the host input before scheduling.
|
||||
- Skip empty values.
|
||||
- Reset the debounce timer on each edit.
|
||||
- Call a bridge prefetch API after about 700 ms of idle typing.
|
||||
- Schedule one prefetch after settings load if the loaded host is non-empty.
|
||||
- Dispose the listener and timer with the widget state.
|
||||
|
||||
Flutter does not store resolved addresses and does not decide whether Connect can use a prefetched result.
|
||||
|
||||
### Bridge API
|
||||
|
||||
Add a fire-and-forget bridge function shaped like:
|
||||
|
||||
```text
|
||||
prefetch_server_resolution(host: String) -> Result<(), BridgeError>
|
||||
```
|
||||
|
||||
The bridge call should return after the prefetch task has been accepted by the Rust runtime. It must not wait for resolution to complete. Background completion or failure is reported only through diagnostics/logging.
|
||||
|
||||
### Rust Resolver Cache
|
||||
|
||||
Rust stores a small prefetch cache owned near the session/resolver boundary. A single latest-host entry is enough for v1, because the design only prefetches the active field.
|
||||
|
||||
Cache entry fields:
|
||||
|
||||
- Normalized input host.
|
||||
- Resolved `host:port` address.
|
||||
- Resolution method.
|
||||
- Completion timestamp.
|
||||
- Generation or request id.
|
||||
- Optional sanitized failure metadata for diagnostics.
|
||||
|
||||
The cache TTL is 2 minutes.
|
||||
|
||||
### Connect Integration
|
||||
|
||||
Connect should ask Rust for a fresh exact-match prefetched result before running normal resolution.
|
||||
|
||||
Rules:
|
||||
|
||||
- Exact normalized host match is required.
|
||||
- Entry age must be at most 2 minutes.
|
||||
- Failed entries must not block normal connect resolution.
|
||||
- Stale entries must be ignored.
|
||||
- Missing cache must behave exactly like today.
|
||||
|
||||
## Data Flow
|
||||
|
||||
1. App starts.
|
||||
2. `_loadUiSettings()` loads the last-used host into `_hostCtl`.
|
||||
3. Flutter schedules invisible prefetch for that host.
|
||||
4. User edits the host field.
|
||||
5. Flutter cancels the pending debounce timer and starts a new one.
|
||||
6. After 700 ms idle, Flutter calls Rust prefetch with the latest trimmed host.
|
||||
7. Rust normalizes and resolves the host through the same resolver path used by Connect.
|
||||
8. Rust stores the result if it still matches the latest generation for that normalized host.
|
||||
9. User taps Connect.
|
||||
10. Rust Connect checks the cache for a fresh exact-match result.
|
||||
11. Cache hit: Connect uses the prefetched address.
|
||||
12. Cache miss/stale/failure: Connect resolves normally.
|
||||
|
||||
## Cancellation And Staleness
|
||||
|
||||
Cancellation can be logical rather than hard task cancellation.
|
||||
|
||||
- Flutter prevents obsolete debounce timers from firing.
|
||||
- Rust tags requests by normalized host and generation.
|
||||
- Late completions for stale generations must not replace newer successful entries.
|
||||
- Duplicate prefetches for the same normalized host may coalesce or refresh the same entry.
|
||||
|
||||
This avoids complexity while preventing old input values from poisoning the cache.
|
||||
|
||||
## Error Handling
|
||||
|
||||
Prefetch failures are diagnostic-only.
|
||||
|
||||
- Empty host: skip prefetch.
|
||||
- Invalid host shape: skip or fail silently with debug diagnostics.
|
||||
- Resolver failure: store optional sanitized failure metadata for diagnostics only.
|
||||
- Connect after failure: normal connect path runs and surfaces errors as it does today.
|
||||
- App resume and network changes: no special invalidation in v1; TTL handles staleness.
|
||||
- Disconnect: cache may remain because it is independent of the TS3 session.
|
||||
|
||||
## Diagnostics
|
||||
|
||||
Add privacy-safe logs for:
|
||||
|
||||
- Prefetch started.
|
||||
- Prefetch result.
|
||||
- Prefetch failed.
|
||||
- Connect using prefetched resolution.
|
||||
- Connect prefetch miss or stale entry.
|
||||
|
||||
Do not log passwords, channel passwords, or nickname. Host and resolved address are acceptable because resolver/connect logging already includes them today.
|
||||
|
||||
## Testing
|
||||
|
||||
Rust tests:
|
||||
|
||||
- Fresh exact-match prefetched result is reusable.
|
||||
- Stale prefetched result is ignored.
|
||||
- Different normalized host is ignored.
|
||||
- Failed prefetch does not block normal resolution.
|
||||
- Late stale generation cannot overwrite a newer cache entry.
|
||||
|
||||
Flutter tests should cover the scheduling logic through a small testable helper if wiring directly through `_BetaHomeState` would be brittle:
|
||||
|
||||
- Host edits debounce prefetch scheduling.
|
||||
- Empty host does not prefetch.
|
||||
- Settings-loaded host schedules one prefetch.
|
||||
|
||||
Manual Android smoke test:
|
||||
|
||||
- Install debug APK.
|
||||
- Launch app.
|
||||
- Wait for last-used host prefetch or type host and wait past debounce.
|
||||
- Tap Connect.
|
||||
- Confirm UI reaches connected server view.
|
||||
- Confirm logcat shows either a prefetch cache hit or safe fallback behavior.
|
||||
|
||||
## Acceptance Criteria
|
||||
|
||||
- Typing or loading a valid host can warm resolver state before Connect.
|
||||
- Connect never fails because prefetch failed.
|
||||
- Connect never uses a prefetched result for a different normalized host.
|
||||
- Prefetched entries older than 2 minutes are ignored.
|
||||
- No visible UI is added for prefetch state.
|
||||
- Bookmarks are not prefetched in bulk.
|
||||
- Android debug build and focused resolver/Flutter tests pass.
|
||||
|
||||
## Implementation Notes
|
||||
|
||||
- Prefer a single latest-host cache unless implementation reveals an existing cache abstraction that makes a tiny map simpler.
|
||||
- Prefer minimal bridge API surface: one prefetch call and connect-time internal cache lookup.
|
||||
- Keep the resolver cache near existing Rust session/connect code so future non-Flutter clients can benefit from the same behavior.
|
||||
@@ -0,0 +1,70 @@
|
||||
# State Sync and UI Settings Validation Design
|
||||
|
||||
**Date:** 2026-05-29
|
||||
**Status:** Approved for implementation
|
||||
**Scope:** P0/P1 validation-based completion for state-sync evidence and UI settings persistence
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Close the current DV/P0-P1 gaps for reducer/state-sync evidence and UI settings persistence with tests first, minimal behavior changes, and updated documentation evidence.
|
||||
|
||||
## 2. State-Sync Design
|
||||
|
||||
`chanora_state` remains the reducer owner. The validation pass adds focused tests for known reducer contracts rather than broad refactoring. Missing behavior is implemented only when a test proves a gap.
|
||||
|
||||
Required evidence covers:
|
||||
|
||||
| Contract | Evidence |
|
||||
|---|---|
|
||||
| Snapshot creates ready state and deterministic normalized order | Existing and expanded reducer tests |
|
||||
| Reconnect discards stale state and reconnect snapshot replaces state | Existing reducer tests |
|
||||
| Disconnected/lost states suppress live deltas | Existing reducer tests |
|
||||
| Duplicate IDs are normalized deterministically | Existing reducer tests |
|
||||
| Unknown client voice activity is ignored | Existing reducer tests |
|
||||
| Channel deletion removes clients in deleted channel | New reducer regression test and implementation |
|
||||
| Same event sequence produces same state and deltas | Existing reducer determinism test |
|
||||
|
||||
## 3. UI Settings Design
|
||||
|
||||
`UiPreferencesService` remains a Flutter service backed by `shared_preferences`. This is the minimal P0/P1-complete implementation because the current app already uses SharedPreferences and no current behavior requires SQLite-backed UI settings.
|
||||
|
||||
`UiSettings` gains a typed `themeMode` field with values:
|
||||
|
||||
| Value | Meaning |
|
||||
|---|---|
|
||||
| `system` | Follow platform theme |
|
||||
| `light` | Force light theme |
|
||||
| `dark` | Force dark theme |
|
||||
|
||||
The service persists the selected theme mode, falls back to `system` for invalid stored values, and preserves independent saves for host and nickname.
|
||||
|
||||
## 4. App Wiring
|
||||
|
||||
`ChanoraApp` becomes stateful enough to load and apply persisted theme mode. `_BetaHome` continues to load/save host and nickname through `UiPreferencesService`. UI controls for selecting theme mode are out of this slice unless already present; this slice provides persistence and app-level application.
|
||||
|
||||
## 5. Documentation Updates
|
||||
|
||||
After tests pass:
|
||||
|
||||
| Document | Update |
|
||||
|---|---|
|
||||
| `docs/implementation-status-2026-05-28.md` | Mark reducer scaffold statement stale/resolved and UI settings persistence implemented for SharedPreferences scope |
|
||||
| `docs/release/dv-waiver-register.md` | Close or soften reducer waiver; keep event replay as P1 gap |
|
||||
| `docs/verification/swe4-unit-verification-plan.md` | Record reducer test evidence and UI settings tests |
|
||||
| `docs/verification/swe6-software-verification-plan.md` | Update state sync and UI settings DV status |
|
||||
| `docs/architecture/sdd.md` | Record UI settings persistence design |
|
||||
|
||||
## 6. Validation
|
||||
|
||||
Run focused tests:
|
||||
|
||||
```text
|
||||
cargo test -p chanora_state --locked
|
||||
flutter test test/services/ui_preferences_service_test.dart
|
||||
```
|
||||
|
||||
Run wider checks if touched app-shell behavior requires it:
|
||||
|
||||
```text
|
||||
flutter test --exclude-tags e2e
|
||||
```
|
||||
@@ -0,0 +1,266 @@
|
||||
# Chanora Adaptive 3-Panel Layout Design
|
||||
|
||||
**Date:** 2026-06-05
|
||||
**Status:** Draft
|
||||
**Scope:** Desktop adaptive layout for ≥1024dp three-panel mode, centralized breakpoint system, and chat panel integration.
|
||||
|
||||
---
|
||||
|
||||
## 1. Problem Statement
|
||||
|
||||
Chanora's current responsive layout uses a single breakpoint (`_wideBreakpoint = 600dp`) scattered across 9 files in 8 duplicatable clusters (5 `LayoutBuilder` sites, 7 `MediaQuery.sizeOf` sites). The desktop layout is a 2-panel split (VoiceBar 320px + SnapshotView flex) with no persistent chat surface.
|
||||
|
||||
Research across Discord, Mattermost, Rocket.Chat, Element, and hardware resolution data shows:
|
||||
|
||||
- **1024dp** is the industry-standard threshold where a third panel becomes viable (Discord member list, Mattermost RHS, Rocket.Chat contextual bar all use this value).
|
||||
- At 1024dp, Chanora's math works: `320 + 12 + 300 + 12 + 380 = 1024` — minimum viable for VoicePanel + ChannelTree + ChatPanel.
|
||||
- Production apps use **push/replace navigation** for chat on constrained widths, reserving persistent panels for ≥1024dp.
|
||||
- Centralized breakpoint logic is standard practice (Rocket.Chat `LayoutProvider`, Mattermost `WindowSizes`).
|
||||
|
||||
## 2. Design Decisions
|
||||
|
||||
| Decision | Choice | Rationale |
|
||||
|---|---|---|
|
||||
| 3-panel activation threshold | **1024dp** | Industry consensus (Discord, Mattermost, Rocket.Chat). Chanora math: center pane = 300dp minimum. |
|
||||
| Chat behavior at 600–1023dp | **Push route (unchanged)** | Research validates current pattern. Overlays are for contextual info, not primary conversation. |
|
||||
| Chat behavior at ≥1024dp | **Inline panel** | Chat renders in a 380dp right panel alongside the channel tree. No route push. |
|
||||
| Centralized breakpoints | **New `ChanoraBreakpoints` + `ViewportInfo`** | Replaces 8 duplicated responsive clusters with single source of truth. |
|
||||
| Architecture approach | **Adaptive Scaffold Shell** | Extends existing widget tree with centralized layout logic. Not a full rewrite. |
|
||||
| AdaptiveScaffold package | **Not used** | Package discontinued (flutter/flutter#162965). Manual layout gives better control for voice-first UX. |
|
||||
|
||||
## 3. Breakpoint System
|
||||
|
||||
### 3.1 Layout Classes
|
||||
|
||||
Three tiers, aligned with Material 3 adaptive guidance:
|
||||
|
||||
| Class | Width Range | Primary Behavior |
|
||||
|---|---|---|
|
||||
| `compact` | < 600dp | Single column. VoiceStatusChip at bottom. Chat as pushed route. |
|
||||
| `medium` | 600–1023dp | 2-panel row (VoicePanel 320px + SnapshotView flex). Chat as pushed route. |
|
||||
| `expanded` | ≥ 1024dp | 3-panel row (VoicePanel 320px + SnapshotView flex + ChatPanel 380px). Chat inline. |
|
||||
|
||||
### 3.2 New Files
|
||||
|
||||
**`lib/design/breakpoints.dart`** — canonical breakpoint tokens:
|
||||
|
||||
```dart
|
||||
class ChanoraBreakpoints {
|
||||
static const double compact = 0;
|
||||
static const double medium = 600;
|
||||
static const double expanded = 1024;
|
||||
|
||||
static const double voicePanelWidth = 320;
|
||||
static const double chatPanelWidth = 380;
|
||||
static const double panelGap = 12;
|
||||
}
|
||||
|
||||
enum LayoutClass { compact, medium, expanded }
|
||||
|
||||
LayoutClass layoutClassFromWidth(double width) {
|
||||
if (width >= ChanoraBreakpoints.expanded) return LayoutClass.expanded;
|
||||
if (width >= ChanoraBreakpoints.medium) return LayoutClass.medium;
|
||||
return LayoutClass.compact;
|
||||
}
|
||||
```
|
||||
|
||||
**`lib/design/viewport_info.dart`** — inherited widget that computes layout class once per frame:
|
||||
|
||||
```dart
|
||||
class ViewportInfo extends InheritedWidget {
|
||||
const ViewportInfo({
|
||||
super.key,
|
||||
required this.layoutClass,
|
||||
required this.width,
|
||||
required this.height,
|
||||
required super.child,
|
||||
});
|
||||
|
||||
final LayoutClass layoutClass;
|
||||
final double width;
|
||||
final double height;
|
||||
|
||||
static ViewportInfo of(BuildContext context) {
|
||||
final info = context.dependOnInheritedWidgetOfExactType<ViewportInfo>();
|
||||
assert(info != null, 'No ViewportInfo found in widget tree');
|
||||
return info!;
|
||||
}
|
||||
|
||||
bool get isCompact => layoutClass == LayoutClass.compact;
|
||||
bool get isMedium => layoutClass == LayoutClass.medium;
|
||||
bool get isExpanded => layoutClass == LayoutClass.expanded;
|
||||
|
||||
@override
|
||||
bool updateShouldNotify(ViewportInfo old) =>
|
||||
layoutClass != old.layoutClass ||
|
||||
width != old.width ||
|
||||
height != old.height;
|
||||
}
|
||||
```
|
||||
|
||||
### 3.3 What This Replaces
|
||||
|
||||
The audit identified these duplicatable clusters that get consolidated:
|
||||
|
||||
| Cluster | Current Locations | Replacement |
|
||||
|---|---|---|
|
||||
| 600dp breakpoint (×3) | `main.dart:304,2280,2468` | `ChanoraBreakpoints.medium` |
|
||||
| 400px cap (×2) | `connect_widgets.dart`, `voice_settings.dart` | Named token in `ChanoraBreakpoints` |
|
||||
| 72% modal height (×2) | `audio_output_tile.dart`, `ptt_capability_badge.dart` | Named token |
|
||||
| 320px voice bar width | `main.dart:2467` | `ChanoraBreakpoints.voicePanelWidth` |
|
||||
| Platform capability branching | `voice_settings.dart`, `voice_compact.dart`, `audio_processing_config_state.dart` | Centralized capability helper |
|
||||
|
||||
## 4. Adaptive Shell
|
||||
|
||||
### 4.1 Widget Tree
|
||||
|
||||
The existing `_BetaHome` widget tree is restructured to use `ViewportInfo`:
|
||||
|
||||
```
|
||||
_BetaHome
|
||||
├─ macOS: Scaffold with traffic-light padding (unchanged)
|
||||
├─ Mobile: ChanoraMobileScaffold (unchanged)
|
||||
└─ bodyContent:
|
||||
└─ LayoutBuilder
|
||||
└─ ViewportInfo (computes layoutClass from constraints)
|
||||
├─ compact: Column [SnapshotView, VoiceStatusChip, PTT]
|
||||
├─ medium: Row [VoicePanel, SnapshotView]
|
||||
└─ expanded: Row [VoicePanel, SnapshotView, ChatPanel]
|
||||
```
|
||||
|
||||
`AdaptiveShell` is a pure layout widget — it reads `ViewportInfo` and composes the appropriate children. All state remains in `_BetaHome`.
|
||||
|
||||
### 4.2 Platform Handling
|
||||
|
||||
Platform-specific scaffolding stays at the top level, unchanged:
|
||||
|
||||
- **macOS**: `Scaffold` with `_macOSTrafficLightPad` top padding (28dp)
|
||||
- **Mobile**: `ChanoraMobileScaffold` with compact idle chrome
|
||||
- **Windows/Linux**: Default `Scaffold`
|
||||
|
||||
The `ViewportInfo` + layout switch only affects the body content inside the scaffold.
|
||||
|
||||
## 5. Chat Panel Behavior
|
||||
|
||||
### 5.1 Compact (< 600dp)
|
||||
|
||||
No change. Chat opens as a pushed `MaterialPageRoute`:
|
||||
|
||||
```
|
||||
main.dart:_onOpenChat → Navigator.push(ChatPage)
|
||||
```
|
||||
|
||||
Channel tree is fully replaced. Back button returns to main view.
|
||||
|
||||
### 5.2 Medium (600–1023dp)
|
||||
|
||||
Same as compact. Chat is a pushed route. The 2-panel layout (VoicePanel + SnapshotView) stays as the home screen.
|
||||
|
||||
### 5.3 Expanded (≥ 1024dp)
|
||||
|
||||
Chat renders inline in a 380dp right panel. The flow:
|
||||
|
||||
1. User taps "Open Text Chat" on a client, or taps the chat badge
|
||||
2. `_onOpenChat` reads `ViewportInfo.of(context).isExpanded`
|
||||
3. If expanded: sets `_inlineChatTarget` state → `ChatPanel` renders in the third column
|
||||
4. If not expanded: pushes `ChatPage` route (unchanged behavior)
|
||||
|
||||
### 5.4 ChatPanel Widget
|
||||
|
||||
New widget for ≥1024dp only:
|
||||
|
||||
```
|
||||
ChatPanel (380dp fixed width)
|
||||
├─ Header: target name + close button
|
||||
├─ Message list (scrollable, max-width ~500dp for readability)
|
||||
└─ Input field
|
||||
```
|
||||
|
||||
**State sharing:** The `_chatMessages` list and `_chatFeedRevision` listenable in `_BetaHome` already track all messages. `ChatPanel` reads from the same source — no duplication.
|
||||
|
||||
**Close behavior:** User taps close button → `_inlineChatTarget` set to null → `ChatPanel` removed from tree.
|
||||
|
||||
### 5.5 Width Transition
|
||||
|
||||
When the user resizes from ≥1024dp to <1024dp while chat is open inline:
|
||||
|
||||
1. `ChatPanel` disappears (it's only in the expanded layout branch)
|
||||
2. A brief snackbar appears: "Tap the chat button to continue your conversation"
|
||||
3. The `_inlineChatTarget` state is preserved — tapping the chat button reopens the pushed `ChatPage` route with the same target
|
||||
|
||||
This matches Discord's behavior when the member list collapses on resize.
|
||||
|
||||
## 6. Panel Sizing
|
||||
|
||||
| Element | Width | Behavior |
|
||||
|---|---|---|
|
||||
| VoicePanel (left) | 320dp fixed | VoiceBar, connection status, PTT controls. Unchanged. |
|
||||
| Panel gaps | 12dp | Between each panel. Unchanged. |
|
||||
| SnapshotView (center) | flex (1fr) | Grows to fill remaining space. |
|
||||
| ChatPanel (right) | 380dp fixed | Only rendered at ≥1024dp. |
|
||||
| Chat messages | max-width ~500dp | Centered within ChatPanel for readability. |
|
||||
| macOS traffic light pad | 28dp top | Unchanged. Only affects height. |
|
||||
|
||||
**Center pane widths at common viewports:**
|
||||
|
||||
| Viewport | Center Width | Feel |
|
||||
|---|---|---|
|
||||
| 1024dp | 300dp | Minimum viable (matches Discord at same width) |
|
||||
| 1200dp | 476dp | Comfortable |
|
||||
| 1280dp | 556dp | Spacious (Chanora's default window size) |
|
||||
| 1440dp | 716dp | Very spacious |
|
||||
| 1920dp | 1184dp | Ultra-wide — consider capping center max-width post-MVP |
|
||||
|
||||
## 7. Migration Map
|
||||
|
||||
| File | Change | Scope |
|
||||
|---|---|---|
|
||||
| `lib/design/breakpoints.dart` | **New** — breakpoint tokens + `LayoutClass` enum | New file |
|
||||
| `lib/design/viewport_info.dart` | **New** — `ViewportInfo` inherited widget | New file |
|
||||
| `lib/main.dart` | Replace `_wideBreakpoint = 600.0` with `ChanoraBreakpoints.medium`. Wrap body in `ViewportInfo`. Add `_inlineChatTarget` state. Branch `_onOpenChat` for expanded vs compact/medium. Add `ChatPanel` to expanded Row. | Significant |
|
||||
| `lib/widgets/chat_views.dart` | Replace `_chatMobileBreakpoint` with `ChanoraBreakpoints.medium`. No structural changes. | Token swap |
|
||||
| `lib/widgets/connect_widgets.dart` | Replace hardcoded 400px with token. | Token swap |
|
||||
| `lib/widgets/app_snack_bar.dart` | Replace hardcoded 600/560px with tokens. | Token swap |
|
||||
| `lib/widgets/snapshot_view.dart` | No changes. Local spacer math stays local. | None |
|
||||
| `lib/widgets/voice_compact.dart` | Replace platform branching with centralized helper (optional, post-MVP). | Optional |
|
||||
|
||||
**Unchanged:** macOS scaffold, ChanoraMobileScaffold, all voice controls, channel tree, chat route for compact/medium, all Rust bridge code.
|
||||
|
||||
## 8. Hardware Coverage
|
||||
|
||||
The 1024dp threshold coverage based on 2026 resolution data:
|
||||
|
||||
| Setup | Logical Width | Sees 3-Panel? |
|
||||
|---|---|---|
|
||||
| 1920×1080 @100% fullscreen | 1920dp | Yes |
|
||||
| 1920×1080 @125% fullscreen | 1536dp | Yes |
|
||||
| 1920×1080 @150% fullscreen | 1280dp | Yes |
|
||||
| 1366×768 @100% fullscreen | 1366dp | Yes |
|
||||
| 1366×768 @125% fullscreen | 1093dp | Yes |
|
||||
| 1366×768 @125% windowed (~85%) | ~930dp | No (2-panel) |
|
||||
| 2560×1440 @100% half-screen | ~1280dp | Yes |
|
||||
| 2560×1440 @125% half-screen | ~1024dp | Yes (edge) |
|
||||
| MacBook 13" Split View | ~708dp | No (2-panel) |
|
||||
| MacBook 14" Split View | ~744dp | No (2-panel) |
|
||||
| MacBook 16" Split View | ~852dp | No (2-panel) |
|
||||
|
||||
Chanora's default window (1280×720 on Windows/Linux) starts in 3-panel mode immediately.
|
||||
|
||||
## 9. Out of Scope (Post-MVP)
|
||||
|
||||
- Resizable panels (drag-to-resize VoicePanel/ChatPanel width)
|
||||
- NavigationRail for ultra-wide monitors
|
||||
- ChatPanel showing user profile or channel info
|
||||
- Center pane max-width cap for ultra-wide monitors
|
||||
- Centralized platform capability helper (consolidating voice_settings/voice_compact/audio_processing branching)
|
||||
- Animated transitions between layout classes
|
||||
- ChatPanel as a sheet/drawer on medium widths
|
||||
|
||||
## 10. References
|
||||
|
||||
- Discord member list collapse at 1024px: [compact-discord](https://github.com/asportnoy/compact-discord)
|
||||
- Mattermost RHS persistent at ≥1024px: [structure.scss](https://github.com/mattermost/mattermost/blob/3440453d82613b1d8d67c93011c11d56a1380869/webapp/channels/src/sass/base/_structure.scss)
|
||||
- Rocket.Chat contextual bar persistent at ≥1024px (lg breakpoint): [fuselage-tokens](https://github.com/RocketChat/fuselage/blob/ed91cb04db9fd6c35b43390190cbf7327c3eab9e/packages/fuselage-tokens/src/breakpoints.jsonc)
|
||||
- Flutter AdaptiveScaffold discontinued: [flutter/flutter#162965](https://github.com/flutter/flutter/issues/162965)
|
||||
- Material 3 canonical breakpoints: [m3.material.io/foundations/layout](https://m3.material.io/foundations/layout/breakpoints/overview)
|
||||
- Chanora adaptive layout policy: [docs/ui-ux/adaptive-layout-platform-guide.md](../ui-ux/adaptive-layout-platform-guide.md)
|
||||
@@ -0,0 +1,160 @@
|
||||
# Maintainability Continuation Design
|
||||
|
||||
**Date:** 2026-06-08
|
||||
**Status:** Approved design for implementation and full code-review remediation; Task 0 and focused audio-realtime fixes landed, documentation/governance alignment in progress
|
||||
**Scope:** Continue the current working-branch maintainability pass, add full code-review findings, and fix high-risk bugs before broad rewrites.
|
||||
|
||||
## Purpose
|
||||
|
||||
This design continues the project review already present in the working tree. The goal is to simplify the project where changes are low-risk, testable, and documented, while avoiding speculative architecture churn.
|
||||
|
||||
The work covers unnecessary functions, structs, files, modules, duplicated custom implementations, built-in replacement opportunities, outdated documents, fail-safe gaps, Android runtime verification requirements, and full code-review remediation for hidden bugs.
|
||||
|
||||
## Recommended Approach
|
||||
|
||||
Use a targeted continuation of the current maintainability pass, now ordered by safety risk.
|
||||
|
||||
The existing branch already contains a first slice of simplification: core event DTO extraction, network diagnostics locality, `VecDeque` queue improvements, derived PTT backend errors, render downmix helper reuse, state reducer reuse, workspace metadata cleanup, and documentation updates. This design treats those changes as the baseline, but the full review found privacy, realtime-audio, disconnect, and documentation-governance issues that take priority over cosmetic simplification.
|
||||
|
||||
The remediation order is:
|
||||
|
||||
- Privacy and stuck-transmit fail-safes in Flutter voice state. Fixed in commit `d835394`.
|
||||
- iOS audio-session error hardening before Rust VoiceProcessingIO startup. Missing-plugin/error handling fixed in commit `d835394`; iOS device runtime verification remains required.
|
||||
- Rust realtime audio safety, especially unsynchronized render-reference buffers and blocking/allocating callbacks. Focused callback-path hardening fixed in commit `8606eb4`; full lock-free `AudioHandler` / config / debug-recorder redesign remains a follow-up.
|
||||
- Bounded disconnect/control-plane progress in Rust protocol/core. Pending unless later code-review evidence closes it.
|
||||
- Documentation and release/governance contradictions that can cause wrong verification claims. Addressed by Task 0.2 documentation alignment.
|
||||
- Larger Module splits after behavior is protected by tests.
|
||||
|
||||
Rejected alternatives:
|
||||
|
||||
- Documentation-only audit: safer, but leaves clear simplifications unimplemented.
|
||||
- Broad architectural cleanup: may produce long-term wins, but is too risky for this pass because bridge, protocol, audio, and Android behavior have high regression cost.
|
||||
|
||||
## Architecture Boundaries
|
||||
|
||||
The existing responsibilities remain intact:
|
||||
|
||||
- Flutter owns presentation, navigation, Material 3 behavior, accessibility, localization presentation, and platform UI behavior.
|
||||
- Flutter Rust Bridge owns typed DTO/API glue and generated bindings.
|
||||
- Rust Core owns session orchestration, cross-crate coordination, bridge-facing public events, and stable public APIs.
|
||||
- Protocol owns TeamSpeak-compatible protocol isolation behind `tsclientlib`.
|
||||
- Audio owns capture, render, processing, PTT backends, platform audio behavior, and voice packet handling where explicitly documented.
|
||||
- Diagnostics owns redaction, logs, export records, and bounded diagnostic history.
|
||||
|
||||
Public interfaces should stay stable unless a change clearly removes duplicated or unnecessary code and has direct verification.
|
||||
|
||||
## Review Targets
|
||||
|
||||
The implementation review should inspect these areas first:
|
||||
|
||||
- `core/chanora_core/src/lib.rs`, `events.rs`, `network_diagnostics.rs`, and `ptt.rs`
|
||||
- `crates/chanora_audio`, especially duplicated render, capture, PTT, and platform-audio helpers
|
||||
- `crates/chanora_state` reducer paths
|
||||
- `crates/chanora_protocol` adapter ordering, event, and DTO mapping paths
|
||||
- `crates/chanora_bridge/src/api.rs`, excluding generated bridge files unless regeneration is intentionally part of a change
|
||||
- `crates/chanora_diagnostics/src/lib.rs`
|
||||
- `crates/chanora_prefetch` and `crates/chanora_resolver` as a documented follow-up seam decision unless a trivial cleanup appears
|
||||
- `apps/chanora_flutter/lib`, excluding generated localization and bridge files unless an API change requires updates
|
||||
- governance, architecture, implementation-status, and verification documents affected by the code review
|
||||
|
||||
Full code-review remediation targets:
|
||||
|
||||
- `apps/chanora_flutter/lib/main.dart`: mute ownership, iOS audio-session preflight, chat/unread follow-ups, and oversized session-controller extraction candidates.
|
||||
- `apps/chanora_flutter/lib/widgets/voice_compact.dart`: touch PTT release-on-dispose fail-safe.
|
||||
- `apps/chanora_flutter/lib/services/ios_audio_session_controller.dart`: missing-plugin fail-safe handling.
|
||||
- `apps/chanora_flutter/lib/services/audio_lifecycle_service.dart`: macOS route/default-device no-op documentation or future adapter seam.
|
||||
- `crates/chanora_audio/src/android_voice_unit.rs`, `ios_raw_unit.rs`, `ios_voice_unit.rs`, and `engine.rs`: realtime callback safety and platform lifecycle rollback.
|
||||
- `core/chanora_core/src/lib.rs` and `crates/chanora_protocol/src/adapter.rs`: bounded disconnect and control-plane progress under voice load.
|
||||
- `README.md`, `CHANGELOG.md`, `docs/release/*`, `docs/verification/*`, and `docs/governance/product-decision-register.md`: stale platform, release, VAD, Android runtime, and decision-register claims.
|
||||
|
||||
## Simplification Rules
|
||||
|
||||
Every code change must satisfy these rules:
|
||||
|
||||
- Prefer deletion, built-in APIs, derives, or reuse of existing helpers over new abstractions.
|
||||
- Merge files or modules only when the merged unit has a clearer single responsibility.
|
||||
- Split files only when it improves locality around a stable responsibility and preserves public API shape.
|
||||
- Do not manually edit generated files unless the generation process is part of the verified change.
|
||||
- Do not introduce backward-compatibility shims unless there is a persisted-data, shipped-API, external-consumer, or explicit product need.
|
||||
- Record larger architectural opportunities in the maintainability review instead of forcing them into this pass.
|
||||
|
||||
Full code-review fix rules:
|
||||
|
||||
- Fix safety bugs before Module split work.
|
||||
- Use test-driven development for production behavior changes: write the failing test, run it, implement the minimal fix, then rerun the test.
|
||||
- Keep manual/generated bridge files out of direct edits unless regeneration is intentionally verified.
|
||||
- Split huge Modules only when the split creates a deeper Module with leverage and locality; file-size-only sharding is not sufficient.
|
||||
- Compare architecture choices against established voice/chat client practice: Mumble-style bounded voice/control separation, Discord/TeamSpeak-style independent mute owners, WebRTC-style realtime callback minimalism, and Matrix/Element-style coherent state replication.
|
||||
|
||||
## Testing Design
|
||||
|
||||
Verification is tied to change type:
|
||||
|
||||
- Rust-only changes require `cargo fmt --all`, `cargo check --workspace`, and `cargo test --workspace`.
|
||||
- Flutter changes require `flutter analyze` and `flutter test --exclude-tags e2e` from `apps/chanora_flutter`.
|
||||
- Bridge DTO/API changes require Rust verification, bridge generation check, Flutter analyze, and Flutter tests.
|
||||
- Android platform, permission, lifecycle, or audio changes require Rust and Flutter verification plus Android NDK target compilation, `adb devices -l`, Android build/install, and a device or emulator smoke test.
|
||||
- Documentation-only changes require affected docs and cross-links to be read and checked; code tests are not required unless the docs describe a code change just made.
|
||||
|
||||
If no ADB target is connected, Android runtime verification must be recorded as blocked. If Android target compilation cannot find the NDK compiler, for example `aarch64-linux-android-clang`, Android build evidence must also be recorded as blocked. The implementation must not claim Android runtime success without build/install/smoke evidence from an authorized device or emulator.
|
||||
|
||||
## Fail-Safe Review
|
||||
|
||||
The review must identify fail-safe gaps and either verify them, fix them, or record the missing evidence.
|
||||
|
||||
Priority fail-safe areas:
|
||||
|
||||
- User mute ownership must not be cleared by talk-power or permission recovery.
|
||||
- Touch and keyboard PTT must release on cancellation, disposal, disconnect, lifecycle transition, or missed-up conditions.
|
||||
- iOS AVAudioSession must be configured and activated before VoiceProcessingIO startup.
|
||||
- Realtime callbacks must not block, allocate repeatedly, or use unsynchronized mutable aliasing.
|
||||
- Disconnect and control requests must be bounded and must not hold global session locks across unbounded transport waits.
|
||||
- Android and iOS device runtime behavior must be verified on hardware or an authorized emulator/simulator where applicable before platform success is claimed.
|
||||
- Android secure storage and Keystore-backed data-encryption-key handling
|
||||
- Android permission and audio lifecycle behavior
|
||||
- Stuck PTT prevention and missed-key-up recovery
|
||||
- Diagnostic redaction and privacy-sensitive event export
|
||||
- Bridge DTO drift between Core, Bridge, and Dart generated bindings
|
||||
- Protocol isolation exceptions for voice packet handling
|
||||
- Runtime behavior gaps not covered by unit tests
|
||||
|
||||
No release-readiness or production-safety claim should be made without matching evidence.
|
||||
|
||||
## Documentation Design
|
||||
|
||||
The working review record remains `docs/governance/maintainability-review-2026-06-08.md`.
|
||||
|
||||
Documents to update when affected:
|
||||
|
||||
- `README.md`
|
||||
- `CHANGELOG.md`
|
||||
- `docs/governance/document-index.md`
|
||||
- `docs/governance/product-decision-register.md`
|
||||
- `docs/architecture/sad.md`
|
||||
- `docs/architecture/sdd.md`
|
||||
- `docs/implementation-status-2026-05-28.md`
|
||||
- `docs/verification/swe4-unit-verification-plan.md`
|
||||
- `docs/verification/swe5-software-integration-verification-plan.md`
|
||||
- `docs/verification/verification-master-plan.md`
|
||||
- `docs/verification/sys4-system-integration-verification-plan.md`
|
||||
- `docs/release/release-readiness-go-nogo-record.md`
|
||||
- `docs/release/dv-waiver-register.md`
|
||||
- release or fail-safe records if verification status changes
|
||||
|
||||
Documentation should distinguish completed changes, follow-up opportunities, blocked verification, and release limitations.
|
||||
|
||||
## Commit Policy
|
||||
|
||||
No commit is created automatically. A commit happens only when explicitly requested, after inspecting `git status`, `git diff`, and recent commits.
|
||||
|
||||
## Success Criteria
|
||||
|
||||
This work is successful when:
|
||||
|
||||
- Safe simplifications are implemented or recorded as follow-up opportunities.
|
||||
- Built-in replacement opportunities are applied only when behavior remains covered by tests.
|
||||
- Fail-safe gaps are documented with required evidence or fixed with verification.
|
||||
- Rust and Flutter verification are run as required by the touched files, including targeted regression tests for every fixed bug.
|
||||
- Android ADB runtime verification is run when a target is available or explicitly recorded as blocked.
|
||||
- Documents reflect the final code and verification state.
|
||||
- Full code-review findings are either fixed, downgraded with evidence, or recorded as follow-up risks with verification requirements.
|
||||
@@ -0,0 +1,176 @@
|
||||
# Poke Without Message Design
|
||||
|
||||
**Date:** 2026-06-09
|
||||
**Status:** Approved design for implementation
|
||||
**Scope:** Allow intentional TeamSpeak-compatible pokes without message text while preserving empty-message blocking for normal chat targets.
|
||||
|
||||
## 1. Goal
|
||||
|
||||
Chanora should let a user poke another connected client without typing a message. A poke is an attention event, not an empty chat message. The UI should make that distinction explicit so the empty state is intentional, understandable, and safe from accidental spam.
|
||||
|
||||
The implementation target is narrow:
|
||||
|
||||
- Sending a poke with an empty message is allowed.
|
||||
- Sending an empty normal chat message remains blocked.
|
||||
- Incoming and historical empty pokes continue to render as poke events, not blank chat bubbles.
|
||||
- Existing poke notification behavior remains compatible with message and no-message pokes.
|
||||
|
||||
## 2. Research Summary
|
||||
|
||||
TeamSpeak-compatible poke behavior is command-like: the ServerQuery shape is `clientpoke clid={clientID} msg={text}`, backed by poke permissions such as `i_client_poke_power` and `i_client_needed_poke_power`. The product semantics are closer to an attention nudge than to a private text message.
|
||||
|
||||
Client behavior and community expectations point to two UX risks:
|
||||
|
||||
- The action can be useful without text because the sender often only wants attention.
|
||||
- The action can be abused as interruption spam, so the UI must keep the action deliberate and preserve existing receiver-side suppression and notification preferences.
|
||||
|
||||
The approved product direction is therefore to model no-message poke as a first-class attention event with optional text, rather than as an exception in the normal chat composer.
|
||||
|
||||
## 3. Recommended UX
|
||||
|
||||
Poke uses a poke-specific sending surface. The surface may reuse the current chat detail implementation internally, but the user-facing copy and validation must make the target type clear.
|
||||
|
||||
Required poke-target behavior:
|
||||
|
||||
| Element | Behavior |
|
||||
|---|---|
|
||||
| Header | Shows that the current surface is for poking the selected user. |
|
||||
| Text field | Optional message input. Placeholder should communicate that the message is optional. |
|
||||
| Primary action | Label is `Poke`, not `Send`. Enabled even when the trimmed message is empty. |
|
||||
| Empty send | Sends an intentional poke with `message: ''`. |
|
||||
| Non-empty send | Sends a poke with the typed message. |
|
||||
| History row | Empty poke renders as an attention event such as `Alice poked you`, never as a blank message. |
|
||||
|
||||
Required non-poke chat behavior:
|
||||
|
||||
| Target | Empty text behavior |
|
||||
|---|---|
|
||||
| Channel chat | Block send. |
|
||||
| Server chat | Block send. |
|
||||
| Private chat | Block send. |
|
||||
| Any future text-chat target | Block send unless it is explicitly modeled as a poke-like attention event. |
|
||||
|
||||
## 4. Architecture Boundaries
|
||||
|
||||
The change should stay inside the existing UI and bridge boundaries:
|
||||
|
||||
- Flutter owns presentation, composer validation, button enablement, localization copy, and widget tests.
|
||||
- Flutter Rust Bridge continues to pass typed `BridgeMessageTarget` and message text across the bridge.
|
||||
- Rust Core and Protocol continue to route `MessageTarget::Poke(client_id)` through the existing poke send path.
|
||||
- Protocol remains the only layer that knows how `tsclientlib` sends a TeamSpeak-compatible poke.
|
||||
|
||||
No new protocol concept is required. The existing bridge/protocol model already has `BridgeMessageTarget.poke` / `MessageTarget::Poke(u64)` and `client.poke(message)`. The key design change is target-aware composer validation in Flutter.
|
||||
|
||||
## 5. Implementation Design
|
||||
|
||||
The implementation should use a target-aware send policy.
|
||||
|
||||
For `BridgeMessageTarget.poke`:
|
||||
|
||||
- Do not reject an empty trimmed input.
|
||||
- Send the original or trimmed message according to the existing chat composer convention. If the current send path trims normal messages before sending, apply the same text normalization before passing the poke message.
|
||||
- Clear the composer after successful send, including empty-poke sends.
|
||||
- Preserve existing error and snackbar behavior for failed sends.
|
||||
|
||||
For all other `BridgeMessageTarget` variants:
|
||||
|
||||
- Keep the existing empty-trimmed-text guard.
|
||||
- Keep current button enablement and keyboard submit behavior unless those paths need target-aware adjustment to preserve the same empty-message block.
|
||||
|
||||
A simple policy helper is preferred over scattered conditionals. Example shape:
|
||||
|
||||
```dart
|
||||
bool canSendMessage({
|
||||
required BridgeMessageTarget target,
|
||||
required String text,
|
||||
}) {
|
||||
if (target is BridgeMessageTarget_Poke) {
|
||||
return true;
|
||||
}
|
||||
return text.trim().isNotEmpty;
|
||||
}
|
||||
```
|
||||
|
||||
The exact Dart type checks should follow the generated bridge type names used in the current codebase.
|
||||
|
||||
## 6. Notification And History Behavior
|
||||
|
||||
Existing no-message receiving behavior should remain the reference behavior:
|
||||
|
||||
- Incoming empty poke notification body falls back to text equivalent to `Alice pokes you`.
|
||||
- Incoming poke with message includes the message in the notification body.
|
||||
- Active-chat suppression and muted-sender preferences continue to apply.
|
||||
- Poke history rows distinguish poke events from normal chat rows.
|
||||
|
||||
The send-side change must not introduce a new blank message row shape. If the sender's local history records sent pokes, empty poke history should render as a poke action line with no empty bubble.
|
||||
|
||||
## 7. Abuse And Safety Rules
|
||||
|
||||
This slice does not add new anti-spam controls. It relies on existing TeamSpeak-compatible permissions, inbound poke strength/rate suppression, notification preferences, active-chat suppression, and muted sender handling.
|
||||
|
||||
The implementation must not weaken any existing receiver-side controls. If testing reveals that empty sent pokes bypass suppression, notification preferences, or history classification, that is a bug to fix in the same implementation pass.
|
||||
|
||||
Future follow-ups, not part of this slice:
|
||||
|
||||
- Per-sender or per-server outbound poke cooldown UI.
|
||||
- Receiver-side "never show poke dialog" equivalent beyond current notification preferences.
|
||||
- Dedicated poke inbox or grouped poke history.
|
||||
|
||||
## 8. Files Expected To Change
|
||||
|
||||
Expected implementation targets:
|
||||
|
||||
| File | Expected change |
|
||||
|---|---|
|
||||
| `apps/chanora_flutter/lib/widgets/chat_views.dart` | Make composer validation and action enablement target-aware for poke. Update poke placeholder/action copy if needed. |
|
||||
| `apps/chanora_flutter/test/widgets/chat_views_test.dart` | Add widget coverage for empty poke send and normal empty chat blocking. |
|
||||
|
||||
Optional targets if the implementation exposes missing copy or routing seams:
|
||||
|
||||
| File | Possible change |
|
||||
|---|---|
|
||||
| `apps/chanora_flutter/lib/main.dart` | Only if opening a poke target needs a clearer poke-specific title or route configuration. |
|
||||
| `apps/chanora_flutter/lib/l10n/*.arb` | Only if current copy cannot express optional poke messages without hard-coded strings. |
|
||||
| `apps/chanora_flutter/test/services/poke_notification_service_test.dart` | Only if send-side changes affect notification payload assumptions. |
|
||||
|
||||
The Rust protocol path should not need behavior changes unless tests prove that empty strings are blocked below Flutter.
|
||||
|
||||
## 9. Test Design
|
||||
|
||||
Required tests:
|
||||
|
||||
- Poke target shows an enabled primary `Poke` action when the text field is empty.
|
||||
- Tapping `Poke` on an empty poke target calls the send callback with `BridgeMessageTarget.poke` and an empty message.
|
||||
- Poke target still sends a typed message when text is present.
|
||||
- Normal channel/server/private chat targets keep blocking empty sends.
|
||||
- Empty poke history renders as a poke event line, not an empty text bubble.
|
||||
|
||||
Useful regression checks if already easy to target:
|
||||
|
||||
- Keyboard submit follows the same target-aware validation as the button.
|
||||
- Failed empty-poke send keeps existing error presentation.
|
||||
- Incoming empty poke notification tests still pass unchanged.
|
||||
|
||||
## 10. Validation
|
||||
|
||||
For the implementation branch, run focused Flutter verification first:
|
||||
|
||||
```text
|
||||
flutter test test/widgets/chat_views_test.dart
|
||||
flutter test test/services/poke_notification_service_test.dart
|
||||
flutter test test/services/poke_active_chat_test.dart
|
||||
flutter analyze
|
||||
```
|
||||
|
||||
If Rust or bridge files are touched, also run the matching Rust and bridge checks for the touched layer. Documentation-only changes require reading the affected spec and checking the diff; code tests are not required for this design commit.
|
||||
|
||||
## 11. Success Criteria
|
||||
|
||||
This design is implemented successfully when:
|
||||
|
||||
- A user can send a poke with no typed message.
|
||||
- Normal chat targets still reject empty sends.
|
||||
- The poke composer communicates that message text is optional.
|
||||
- Empty pokes are represented as poke events in history and notifications.
|
||||
- Existing poke notification preferences and suppression behavior remain intact.
|
||||
- Focused widget/service tests and `flutter analyze` pass, or any unrelated pre-existing failure is named with evidence.
|
||||
@@ -0,0 +1,472 @@
|
||||
# Documentation Site & ASPICE Traceability System Design
|
||||
|
||||
**Date:** 2026-06-13
|
||||
**Status:** Approved design for implementation
|
||||
**Scope:** Docusaurus doc site, git submodule separation, tag-based ASPICE traceability with custom validation plugin, Cloudflare Pages hosting with access control
|
||||
|
||||
## 1. Purpose
|
||||
|
||||
Replace the current flat markdown documentation tree with a browseable, searchable, access-controlled doc site that serves three audiences: developers, ASPICE assessors, and non-technical stakeholders. Introduce automated traceability enforcement that validates the ASPICE requirement chain on every build.
|
||||
|
||||
## 2. Current State
|
||||
|
||||
- 65+ markdown files in `docs/` with no sidebar, no search, no visual hierarchy
|
||||
- ASPICE traceability maintained in manual markdown tables (`traceability-matrix.md`)
|
||||
- Cross-references are backtick-quoted paths in prose, not clickable links
|
||||
- Link coverage report found 2 broken links + 5 broken path references
|
||||
- No CI enforcement of traceability integrity
|
||||
- No access control — docs only viewable via GitHub repo browsing or local clone
|
||||
|
||||
## 3. Design Decisions
|
||||
|
||||
| Decision | Choice | Rationale |
|
||||
|---|---|---|
|
||||
| Repo structure | Git submodule (`docs/` → `chanora-docs` repo) | Cleaner separation, access control, CI independence, separate versioning |
|
||||
| Doc site generator | Docusaurus | Meta-maintained, full plugin API, built-in tags and versioning, active ecosystem |
|
||||
| Traceability mechanism | Tag-based + custom Docusaurus plugin | Tags for browsing, plugin for automated chain validation and coverage reports |
|
||||
| Hosting | Cloudflare Pages | Free tier, global CDN, auto-deploy from CI |
|
||||
| Access control | Cloudflare Access | Free for up to 50 users, email-based auth, SSO support |
|
||||
| Code path references in docs | Remove from ASPICE docs, move to `impl-mapping.md` | ASPICE traces requirement IDs, not file paths. Code paths are developer convenience |
|
||||
| Provenance records | Deferred | Completed ASPICE-related plans archived in `dev-docs/superpowers/plans/_archived/` for now |
|
||||
|
||||
## 4. Repo Structure
|
||||
|
||||
### 4.1 Docs submodule (`chanora-docs` repo)
|
||||
|
||||
```
|
||||
chanora-docs/
|
||||
├── mkdocs.yml
|
||||
├── requirements.txt
|
||||
├── pyproject.toml
|
||||
├── docs/
|
||||
│ ├── index.md
|
||||
│ ├── .meta.yml
|
||||
│ ├── requirements/
|
||||
│ │ ├── .meta.yml
|
||||
│ │ ├── sysrs.md
|
||||
│ │ ├── sysdes.md
|
||||
│ │ └── srs.md
|
||||
│ ├── architecture/
|
||||
│ │ ├── .meta.yml
|
||||
│ │ ├── sad.md
|
||||
│ │ ├── sdd.md
|
||||
│ │ ├── file-transfer-design.md
|
||||
│ │ ├── file-transfer-research.md
|
||||
│ │ ├── file-transfer-implementation-plan.md
|
||||
│ │ └── desktop-ptt-architecture.md
|
||||
│ ├── verification/
|
||||
│ │ ├── .meta.yml
|
||||
│ │ ├── verification-master-plan.md
|
||||
│ │ ├── swe4-unit-verification-plan.md
|
||||
│ │ ├── swe5-software-integration-verification-plan.md
|
||||
│ │ ├── swe6-software-verification-plan.md
|
||||
│ │ └── sys4-system-integration-verification-plan.md
|
||||
│ ├── governance/
|
||||
│ │ ├── .meta.yml
|
||||
│ │ ├── document-index.md
|
||||
│ │ ├── traceability-matrix.md
|
||||
│ │ ├── product-decision-register.md
|
||||
│ │ ├── baseline-approval-record.md
|
||||
│ │ ├── baseline-candidate-validation-report.md
|
||||
│ │ ├── document-review-report.md
|
||||
│ │ ├── document-naming-convention.md
|
||||
│ │ ├── decision-impact-assessment.md
|
||||
│ │ ├── git-commit-message-convention.md
|
||||
│ │ ├── repo-format-validation-report.md
|
||||
│ │ ├── path-migration-map.md
|
||||
│ │ └── maintainability-review-2026-06-08.md
|
||||
│ ├── security/
|
||||
│ │ ├── .meta.yml
|
||||
│ │ ├── security-privacy-legal-guideline.md
|
||||
│ │ ├── threat-model.md
|
||||
│ │ ├── secure-storage-audit-report.md
|
||||
│ │ ├── diagnostic-redaction-audit-report.md
|
||||
│ │ ├── dependency-and-supply-chain-report.md
|
||||
│ │ ├── license-inventory.md
|
||||
│ │ └── flutter-license-inventory.md
|
||||
│ ├── privacy/
|
||||
│ │ └── privacy-policy.md
|
||||
│ ├── legal/
|
||||
│ │ └── trademark-and-attribution-review.md
|
||||
│ ├── release/
|
||||
│ │ ├── platform-release-policy.md
|
||||
│ │ ├── release-readiness-go-nogo-record.md
|
||||
│ │ └── dv-waiver-register.md
|
||||
│ ├── references/
|
||||
│ │ ├── aspice-swe2-swe3-integration-note.md
|
||||
│ │ ├── external-references.md
|
||||
│ │ ├── yatqa-en.md (moved from offline-knowledge/external/)
|
||||
│ │ ├── yatqa-de.md (moved from offline-knowledge/external/)
|
||||
│ │ ├── teaspeak-overview.md (moved from offline-knowledge/external/)
|
||||
│ │ └── respeak-overview.md (moved from offline-knowledge/external/)
|
||||
│ ├── ui-ux/
|
||||
│ │ ├── material3-guideline.md
|
||||
│ │ ├── material3-design-tokens.md
|
||||
│ │ ├── material3-component-catalog.md
|
||||
│ │ └── adaptive-layout-platform-guide.md
|
||||
│ ├── i18n/
|
||||
│ │ └── localization-architecture.md
|
||||
│ └── tags.md
|
||||
├── plugins/
|
||||
│ └── traceability/
|
||||
│ ├── __init__.py
|
||||
│ └── traceability.py
|
||||
├── scripts/
|
||||
│ └── validate_traceability.py
|
||||
├── .github/
|
||||
│ └── workflows/
|
||||
│ └── deploy.yml
|
||||
├── wrangler.toml
|
||||
└── README.md
|
||||
```
|
||||
|
||||
### 4.2 Code repo local files
|
||||
|
||||
```
|
||||
chanora/
|
||||
├── docs/ → chanora-docs (submodule)
|
||||
├── dev-docs/
|
||||
│ ├── superpowers/
|
||||
│ │ ├── specs/
|
||||
│ │ │ ├── 2026-05-28-server-resolution-prefetch-design.md
|
||||
│ │ │ ├── 2026-05-28-chanora-server-prefetch-crate-design.md
|
||||
│ │ │ ├── 2026-05-29-state-sync-ui-settings-validation-design.md
|
||||
│ │ │ ├── 2026-06-05-adaptive-3-panel-layout-design.md
|
||||
│ │ │ ├── 2026-06-08-maintainability-continuation-design.md
|
||||
│ │ │ ├── 2026-06-09-poke-without-message-design.md
|
||||
│ │ │ └── 2026-06-13-documentation-site-design.md
|
||||
│ │ └── plans/
|
||||
│ │ ├── _archived/
|
||||
│ │ │ ├── 2026-05-29-finish-dv-document-tree.md
|
||||
│ │ │ ├── 2026-05-29-dv-evidence-pack.md
|
||||
│ │ │ ├── 2026-05-29-swe2-swe3-baselines.md
|
||||
│ │ │ └── 2026-05-29-state-sync-ui-settings-validation.md
|
||||
│ │ ├── 2026-05-28-server-resolution-prefetch.md
|
||||
│ │ ├── 2026-05-28-chanora-server-prefetch-crate.md
|
||||
│ │ ├── 2026-06-06-chat-panel-switching.md
|
||||
│ │ ├── 2026-06-08-core-internal-split.md
|
||||
│ │ └── 2026-06-08-maintainability-continuation.md
|
||||
│ ├── offline-knowledge/
|
||||
│ │ ├── coverage-analysis.md
|
||||
│ │ ├── doc-quality-analysis.md
|
||||
│ │ ├── link-coverage-report.md
|
||||
│ │ └── reviews/
|
||||
│ ├── implementation-status-2026-05-28.md
|
||||
│ ├── release/ios-build.md
|
||||
│ └── impl-mapping.md
|
||||
├── apps/, crates/, core/
|
||||
├── AGENTS.md
|
||||
└── README.md
|
||||
```
|
||||
|
||||
## 5. Docusaurus Configuration
|
||||
|
||||
### 5.1 Site configuration (`docusaurus.config.js`)
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
title: 'Chanora Engineering Docs',
|
||||
tagline: 'ASPICE-compliant engineering documentation with automated traceability',
|
||||
url: 'https://docs.chanora.dev',
|
||||
baseUrl: '/',
|
||||
organizationName: 'chanoraapp',
|
||||
projectName: 'docs',
|
||||
onBrokenLinks: 'throw',
|
||||
onBrokenMarkdownLinks: 'warn',
|
||||
i18n: { defaultLocale: 'en', locales: ['en'] },
|
||||
themes: ['@docusaurus/theme-classic'],
|
||||
plugins: [
|
||||
'./plugins/traceability',
|
||||
],
|
||||
themeConfig: {
|
||||
navbar: {
|
||||
title: 'Chanora Docs',
|
||||
items: [
|
||||
{ type: 'doc', position: 'left', label: 'Requirements', docId: 'requirements/sysrs' },
|
||||
{ type: 'doc', position: 'left', label: 'Architecture', docId: 'architecture/sad' },
|
||||
{ type: 'doc', position: 'left', label: 'Verification', docId: 'verification/verification-master-plan' },
|
||||
{ type: 'doc', position: 'left', label: 'Governance', docId: 'governance/document-index' },
|
||||
{ type: 'doc', position: 'left', label: 'Security', docId: 'security/security-privacy-legal-guideline' },
|
||||
{ type: 'doc', position: 'left', label: 'Release', docId: 'release/platform-release-policy' },
|
||||
{ type: 'doc', position: 'left', label: 'References', docId: 'references/external-references' },
|
||||
{ type: 'doc', position: 'left', label: 'UI/UX', docId: 'ui-ux/material3-guideline' },
|
||||
{ type: 'tags' },
|
||||
],
|
||||
},
|
||||
footer: {
|
||||
style: 'dark',
|
||||
links: [
|
||||
{ title: 'Docs', items: [
|
||||
{ label: 'Requirements', to: '/docs/requirements/sysrs' },
|
||||
{ label: 'Architecture', to: '/docs/architecture/sad' },
|
||||
{ label: 'Verification', to: '/docs/verification/verification-master-plan' },
|
||||
]},
|
||||
{ title: 'Governance', items: [
|
||||
{ label: 'Traceability Matrix', to: '/docs/governance/traceability-matrix' },
|
||||
{ label: 'Decision Register', to: '/docs/governance/product-decision-register' },
|
||||
{ label: 'Document Index', to: '/docs/governance/document-index' },
|
||||
]},
|
||||
],
|
||||
},
|
||||
prism: { theme: prismThemes.github, darkTheme: prismThemes.dracula },
|
||||
},
|
||||
};
|
||||
```
|
||||
|
||||
### 5.2 Sidebar (`sidebars.js`)
|
||||
|
||||
```js
|
||||
module.exports = {
|
||||
requirements: [
|
||||
'requirements/sysrs',
|
||||
'requirements/sysdes',
|
||||
'requirements/srs',
|
||||
],
|
||||
architecture: [
|
||||
'architecture/sad',
|
||||
'architecture/sdd',
|
||||
'architecture/file-transfer-design',
|
||||
'architecture/file-transfer-research',
|
||||
'architecture/file-transfer-implementation-plan',
|
||||
'architecture/desktop-ptt-architecture',
|
||||
],
|
||||
verification: [
|
||||
{
|
||||
type: 'category',
|
||||
label: 'System Level',
|
||||
items: ['verification/sys4-system-integration-verification-plan'],
|
||||
},
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Software Integration',
|
||||
items: ['verification/swe5-software-integration-verification-plan'],
|
||||
},
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Unit Level',
|
||||
items: ['verification/swe4-unit-verification-plan'],
|
||||
},
|
||||
{
|
||||
type: 'category',
|
||||
label: 'Software Qualification',
|
||||
items: ['verification/swe6-software-verification-plan'],
|
||||
},
|
||||
'verification/verification-master-plan',
|
||||
],
|
||||
governance: [
|
||||
'governance/document-index',
|
||||
'governance/traceability-matrix',
|
||||
'governance/product-decision-register',
|
||||
'governance/baseline-approval-record',
|
||||
'governance/baseline-candidate-validation-report',
|
||||
'governance/document-review-report',
|
||||
'governance/document-naming-convention',
|
||||
'governance/decision-impact-assessment',
|
||||
'governance/git-commit-message-convention',
|
||||
'governance/repo-format-validation-report',
|
||||
'governance/path-migration-map',
|
||||
'governance/maintainability-review-2026-06-08',
|
||||
],
|
||||
security: [
|
||||
'security/security-privacy-legal-guideline',
|
||||
'security/threat-model',
|
||||
'security/secure-storage-audit-report',
|
||||
'security/diagnostic-redaction-audit-report',
|
||||
'security/dependency-and-supply-chain-report',
|
||||
'security/license-inventory',
|
||||
'security/flutter-license-inventory',
|
||||
'privacy/privacy-policy',
|
||||
'legal/trademark-and-attribution-review',
|
||||
],
|
||||
release: [
|
||||
'release/platform-release-policy',
|
||||
'release/release-readiness-go-nogo-record',
|
||||
'release/dv-waiver-register',
|
||||
],
|
||||
references: [
|
||||
'references/external-references',
|
||||
'references/aspice-swe2-swe3-integration-note',
|
||||
'references/yatqa-en',
|
||||
'references/yatqa-de',
|
||||
'references/teaspeak-overview',
|
||||
'references/respeak-overview',
|
||||
],
|
||||
uiux: [
|
||||
'ui-ux/material3-guideline',
|
||||
'ui-ux/material3-design-tokens',
|
||||
'ui-ux/material3-component-catalog',
|
||||
'ui-ux/adaptive-layout-platform-guide',
|
||||
'i18n/localization-architecture',
|
||||
],
|
||||
};
|
||||
```
|
||||
|
||||
## 6. Tag-Based Traceability
|
||||
|
||||
### 6.1 Front matter schema
|
||||
|
||||
Every document includes YAML front matter:
|
||||
|
||||
```yaml
|
||||
---
|
||||
tags: [swe.2, architecture, SRS-003, SRS-008, SRS-016]
|
||||
upstream: [srs, sysdes] # Custom metadata for traceability plugin
|
||||
downstream: [sdd, swe4, swe5] # Custom metadata for traceability plugin
|
||||
lifecycle: SWE.2 # Custom metadata for traceability plugin
|
||||
status: baseline # Custom metadata for traceability plugin
|
||||
---
|
||||
```
|
||||
|
||||
The `tags` field is consumed by the MkDocs Material tags plugin for browsing. The `upstream`, `downstream`, `lifecycle`, and `status` fields are custom metadata consumed by the traceability plugin for chain validation.
|
||||
|
||||
### 6.2 Tag categories
|
||||
|
||||
| Tag pattern | Purpose | Example |
|
||||
|---|---|---|
|
||||
| `swe.1` through `swe.6`, `sys.4` | ASPICE lifecycle stage | Every doc gets at least one |
|
||||
| `sysrs`, `sysdes`, `srs`, `sad`, `sdd` | Document type | Identifies the doc in the chain |
|
||||
| `requirements`, `architecture`, `verification`, `governance` | Section category | For filtering |
|
||||
| `SysRS-233`, `SRS-045`, `SDD-MOD-009` | Requirement/module IDs | Traceability links |
|
||||
| `baseline`, `draft`, `candidate` | Document status | Assessor visibility |
|
||||
| `dec-012`, `dec-020` | Decision register refs | Cross-ref to governance |
|
||||
|
||||
### 6.3 Section defaults via `.meta.yml`
|
||||
|
||||
```yaml
|
||||
# docs/verification/.meta.yml
|
||||
tags: [verification]
|
||||
status: candidate
|
||||
```
|
||||
|
||||
### 6.4 Verification page trace mappings
|
||||
|
||||
| Verification plan | Upstream traces | Tags |
|
||||
|---|---|---|
|
||||
| SYS.4 System Integration | SysDes, SysRS | `[sys.4, verification, SysDes-102, SysDes-103, ...]` |
|
||||
| SWE.5 Software Integration | SAD (SWE.2) | `[swe.5, verification, sad-component-bridge, ...]` |
|
||||
| SWE.4 Unit Verification | SDD (SWE.3) | `[swe.4, verification, SDD-MOD-001, ...]` |
|
||||
| SWE.6 Software Verification | SRS | `[swe.6, verification, SRS-128, ...]` |
|
||||
|
||||
## 7. Custom Traceability Plugin
|
||||
|
||||
### 7.1 Location
|
||||
|
||||
`plugins/traceability/traceability.py` — MkDocs plugin, ~200 lines Python.
|
||||
|
||||
### 7.2 Behavior
|
||||
|
||||
On `on_page_markdown` event:
|
||||
- Scan each page for requirement ID patterns: `SysRS-\d+`, `SysDes-\d+`, `SRS-\d+`, `SDD-MOD-\d+`, `DEC-\d+`
|
||||
- Build an in-memory traceability graph: upstream ID → downstream document → verification plan
|
||||
|
||||
On `on_post_build` event:
|
||||
- Validate every requirement ID referenced downstream exists in its source document
|
||||
- Validate every upstream document ID has at least one downstream allocation
|
||||
- Flag orphaned references (IDs mentioned but never defined)
|
||||
- Verify bidirectional completeness
|
||||
|
||||
### 7.3 Outputs
|
||||
|
||||
- `traceability-coverage.json` — machine-readable coverage report with chain completeness percentages
|
||||
- Console output with pass/fail summary
|
||||
- Traceability dashboard page with coverage table and broken chain details
|
||||
- Build failure (`sys.exit(1)`) on broken chains when `strict: true`
|
||||
|
||||
### 7.4 Standalone CI validator
|
||||
|
||||
`scripts/validate_traceability.py` — same validation logic, runnable without MkDocs build:
|
||||
|
||||
```
|
||||
python scripts/validate_traceability.py docs/
|
||||
```
|
||||
|
||||
Exit code 0 = all chains valid. Exit code 1 = broken chains with details on stderr.
|
||||
|
||||
## 8. Hosting & Deployment
|
||||
|
||||
### 8.1 Architecture
|
||||
|
||||
```
|
||||
chanora-docs repo → push to main → GitHub Actions
|
||||
→ validate_traceability.py
|
||||
→ mkdocs build --strict
|
||||
→ Cloudflare Pages (via Wrangler)
|
||||
→ Cloudflare Access policy (email-based auth)
|
||||
```
|
||||
|
||||
### 8.2 CI workflow
|
||||
|
||||
On pull request: build + validate only (no deploy).
|
||||
On push to main: build + validate + deploy to Cloudflare Pages.
|
||||
|
||||
### 8.3 Cloudflare Access policy
|
||||
|
||||
- Free tier for up to 50 users
|
||||
- Email-based authentication with optional Google/GitHub SSO
|
||||
- One-time PIN for external assessors
|
||||
- Access rules: allow company emails, specific assessor emails; block all others
|
||||
|
||||
## 9. Migration Plan
|
||||
|
||||
### 9.1 Code path reference cleanup
|
||||
|
||||
SAD and SDD currently list file paths (`crates/chanora_protocol/src/`) in component tables. These references will be:
|
||||
- Replaced with component/module IDs only in the docs submodule
|
||||
- Preserved in `dev-docs/impl-mapping.md` in the code repo for developer convenience
|
||||
|
||||
### 9.2 File moves
|
||||
|
||||
| From (code repo) | To | Action |
|
||||
|---|---|---|
|
||||
| `docs/sysrs.md` | docs submodule | Move + add front matter |
|
||||
| `docs/sysdes.md` | docs submodule | Move + add front matter |
|
||||
| `docs/srs.md` | docs submodule | Move + add front matter |
|
||||
| `docs/requirements/*` | docs submodule | Move (path records) |
|
||||
| `docs/architecture/*` | docs submodule | Move + cleanup code paths |
|
||||
| `docs/verification/*` | docs submodule | Move + add front matter |
|
||||
| `docs/governance/*` | docs submodule | Move + add front matter |
|
||||
| `docs/security/*` | docs submodule | Move + add front matter |
|
||||
| `docs/privacy/*` | docs submodule | Move |
|
||||
| `docs/legal/*` | docs submodule | Move |
|
||||
| `docs/release/policy+go-nogo+waiver` | docs submodule | Move |
|
||||
| `docs/references/*` | docs submodule | Move |
|
||||
| `docs/ui-ux/*` | docs submodule | Move |
|
||||
| `docs/i18n/*` | docs submodule | Move |
|
||||
| `docs/material3-guideline.md` | docs submodule | Move |
|
||||
| `docs/offline-knowledge/external/*` | docs submodule `references/` (flattened) | Move + rename |
|
||||
| `docs/superpowers/*` | `dev-docs/superpowers/` | Move |
|
||||
| `docs/offline-knowledge/` (remaining) | `dev-docs/offline-knowledge/` | Move |
|
||||
| `docs/implementation-status-*` | `dev-docs/` | Move |
|
||||
| `docs/release/ios-build.md` | `dev-docs/release/` | Move |
|
||||
|
||||
### 9.3 Cross-reference updates
|
||||
|
||||
All backtick path references (`docs/srs.md`) should become markdown links (`[SRS](../srs.md)` or `[SRS](srs.md)`) for both GitHub and MkDocs rendering.
|
||||
|
||||
### 9.4 Post-migration
|
||||
|
||||
- Remove `docs/` contents from code repo
|
||||
- Add `chanora-docs` as git submodule at `docs/`
|
||||
- Create `dev-docs/` directory with local-only files
|
||||
- Update README references to new paths
|
||||
- Write `AGENTS.md` with new conventions
|
||||
- Update `opencode.json` or `.opencode/` references
|
||||
|
||||
## 10. AGENTS.md
|
||||
|
||||
An `AGENTS.md` file will be written at the code repo root documenting:
|
||||
- The two-repo model (docs/ as submodule, dev-docs/ as local)
|
||||
- What content goes where
|
||||
- ASPICE traceability chain and rules
|
||||
- Code architecture overview
|
||||
- Verification commands
|
||||
- Agent working conventions (no edits in docs/ without submodule awareness)
|
||||
|
||||
## 11. Deferred Items
|
||||
|
||||
| Item | Reason | When |
|
||||
|---|---|---|
|
||||
| Document provenance records | Convert completed ASPICE plans into provenance evidence | Follow-up task |
|
||||
| Custom MkDocs traceability plugin | Core feature, built during implementation | Phase 1 |
|
||||
| Cloudflare Pages + Access setup | Requires account creation, domain config | During deployment |
|
||||
| `impl-mapping.md` creation | Extract code paths from SAD/SDD during migration | During migration |
|
||||
Reference in New Issue
Block a user