field_ios

In-the-field app for Radroots on iOS
git clone https://radroots.dev/git/field_ios.git
Log | Files | Refs | README | LICENSE

commit f9124ae7f25db38c6e2794f167b77f6bde6e89e7
parent 3415af7fe609038f23aa8aeb83f9a24a72f32796
Author: triesap <tyson@radroots.org>
Date:   Thu,  6 Aug 2026 06:40:25 +0000

mobile: import preserved mobile history

- merge the verified app_rt history at 2441d0d21c33946e11ee7254c7bae5818d799901
- record bundle 9a9ba8e6002ee3d6fcb232e18fb84dbc2885bb37e7bdba736b44a1e5bb6489b0 and commit-map ebd8e2345391cf1e86ed2e2667657a608eca34a606b09d467bbf9608fd70eb60
- activate the private radroots_mobile package cohort at exactly 0.1.0-alpha
- qualify native, wasm, coverage, lifecycle, and renamed UniFFI contracts

Diffstat:
Acore/crates/tera_core/Cargo.toml | 44++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/build.rs | 46++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/error.rs | 140+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/lib.rs | 15+++++++++++++++
Acore/crates/tera_core/src/logging.rs | 248+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/logging/writer.rs | 268+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/app_info.rs | 26++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/builder.rs | 27+++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/info.rs | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/key_management.rs | 214+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/mod.rs | 173+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/nostr.rs | 241+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/product_surface.rs | 3641+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/src/runtime/sdk.rs | 98+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/tests/logging_error.rs | 9+++++++++
Acore/crates/tera_core/tests/sdk_runtime.rs | 52++++++++++++++++++++++++++++++++++++++++++++++++++++
Acore/crates/tera_core/tests/uniffi_contract.rs | 33+++++++++++++++++++++++++++++++++
Acore/provenance/tera_core/LICENSE-GPL-3.0-or-later | 674+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
18 files changed, 6026 insertions(+), 0 deletions(-)

diff --git a/core/crates/tera_core/Cargo.toml b/core/crates/tera_core/Cargo.toml @@ -0,0 +1,44 @@ +[package] +name = "radroots_mobile_core" +version.workspace = true +edition.workspace = true +authors = ["Radroots Authors"] +rust-version.workspace = true +license = "GPL-3.0-or-later" +description = "Application core runtime for Radroots apps" +repository.workspace = true +homepage.workspace = true +readme.workspace = true +publish = false +include = ["src/**", "tests/**", "build.rs", "Cargo.toml"] + +[lib] +crate-type = ["rlib"] + +[lints.rust] +unexpected_cfgs = { level = "warn", check-cfg = ['cfg(coverage_nightly)'] } + +[features] +default = [] +mobile-social = [ + "radroots_sdk/local-signing", + "radroots_sdk/nostr", + "radroots_sdk/sync", +] + +[dependencies] +radroots_sdk = { workspace = true, features = ["memory"] } +chrono = { workspace = true } +serde = { workspace = true, features = ["derive"] } +serde_json = { workspace = true } +thiserror = { workspace = true } +uniffi = { workspace = true } + +[target.'cfg(not(target_arch = "wasm32"))'.dependencies] +tracing = { workspace = true } +tracing-appender = { workspace = true } +tracing-subscriber = { workspace = true } + +[dev-dependencies] +tempfile = { workspace = true } +tokio = { workspace = true, features = ["macros", "rt"] } diff --git a/core/crates/tera_core/build.rs b/core/crates/tera_core/build.rs @@ -0,0 +1,46 @@ +use std::{env, process::Command}; + +fn main() { + println!("cargo:rerun-if-changed=build.rs"); + println!("cargo:rerun-if-env-changed=RUSTC"); + println!("cargo:rerun-if-env-changed=PROFILE"); + println!("cargo:rerun-if-env-changed=RADROOTS_SOURCE_SHA"); + println!("cargo:rerun-if-env-changed=SOURCE_DATE_EPOCH"); + + let rustc = env::var("RUSTC").expect("missing required env var RUSTC"); + if let Ok(output) = Command::new(rustc).arg("--version").output() + && output.status.success() + && let Ok(version) = String::from_utf8(output.stdout) + { + println!("cargo:rustc-env=RUSTC_VERSION={}", version.trim()); + } + + if let Some(source_sha) = optional_source_sha() { + println!("cargo:rustc-env=GIT_HASH={source_sha}"); + } + + let profile = env::var("PROFILE").expect("missing required env var PROFILE"); + println!("cargo:rustc-env=PROFILE={profile}"); + + if let Some(epoch) = optional_source_date_epoch() { + println!("cargo:rustc-env=BUILD_TIME_UNIX={epoch}"); + } +} + +fn optional_source_sha() -> Option<String> { + let value = env::var("RADROOTS_SOURCE_SHA").ok()?; + assert!( + (7..=64).contains(&value.len()) && value.bytes().all(|byte| byte.is_ascii_hexdigit()), + "RADROOTS_SOURCE_SHA must contain 7 to 64 hexadecimal characters" + ); + Some(value.to_ascii_lowercase()) +} + +fn optional_source_date_epoch() -> Option<u64> { + let value = env::var("SOURCE_DATE_EPOCH").ok()?; + Some( + value + .parse() + .expect("SOURCE_DATE_EPOCH must be an unsigned Unix timestamp"), + ) +} diff --git a/core/crates/tera_core/src/error.rs b/core/crates/tera_core/src/error.rs @@ -0,0 +1,140 @@ +use thiserror::Error; + +/// Versioned, secret-safe SDK failure exposed to mobile hosts. +#[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] +pub struct SdkErrorRecord { + pub schema_version: u16, + pub code: String, + pub class: String, + pub retryable: bool, + pub recovery_actions: Vec<String>, + pub operation_id: Option<String>, + pub capability_id: Option<String>, + pub message: String, +} + +#[derive(Debug, Error, uniffi::Error)] +pub enum RadrootsAppError { + #[error("initialization: {0}")] + Initialization(String), + #[error("sdk: {report:?}")] + Sdk { report: SdkErrorRecord }, + #[error("runtime: {0}")] + Runtime(String), + #[error("unsupported: {0}")] + Unsupported(String), + #[error("internal: {0}")] + Internal(String), +} + +impl RadrootsAppError { + pub(crate) fn from_sdk(error: radroots_sdk::Error) -> Self { + let report = error.to_report(); + Self::Sdk { + report: SdkErrorRecord { + schema_version: report.schema_version(), + code: report.code().as_str().to_owned(), + class: debug_label(report.class()), + retryable: report.retryable(), + recovery_actions: report + .recovery_actions() + .iter() + .map(|action| debug_label(*action)) + .collect(), + operation_id: report.operation_id().map(|id| id.as_str().to_owned()), + capability_id: report.capability_id().map(|id| id.as_str().to_owned()), + message: report.message().as_str().to_owned(), + }, + } + } + + pub fn initialization(message: impl Into<String>) -> Self { + Self::Initialization(message.into()) + } + + pub fn runtime(message: impl Into<String>) -> Self { + Self::Runtime(message.into()) + } + + pub fn unsupported(message: impl Into<String>) -> Self { + Self::Unsupported(message.into()) + } + + pub fn internal(message: impl Into<String>) -> Self { + Self::Internal(message.into()) + } +} + +fn debug_label(value: impl std::fmt::Debug) -> String { + let mut label = String::new(); + for (index, character) in format!("{value:?}").chars().enumerate() { + if character.is_ascii_uppercase() && index != 0 { + label.push('_'); + } + label.push(character.to_ascii_lowercase()); + } + label +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::{RadrootsAppError, SdkErrorRecord, debug_label}; + + #[test] + fn sdk_error_records_are_versioned_stable_and_secret_safe() { + let error = radroots_sdk::ClientBuilder::new() + .build() + .expect_err("storage is required"); + let RadrootsAppError::Sdk { report } = RadrootsAppError::from_sdk(error) else { + panic!("expected SDK report"); + }; + assert_eq!( + report, + SdkErrorRecord { + schema_version: 1, + code: "missing_storage".to_owned(), + class: "capability".to_owned(), + retryable: false, + recovery_actions: vec!["configure_storage".to_owned()], + operation_id: None, + capability_id: Some("storage.canonical".to_owned()), + message: "SDK storage capability is not configured".to_owned(), + } + ); + assert!(!format!("{report:?}").contains("source")); + } + + #[test] + fn debug_labels_use_stable_mobile_case() { + assert_eq!( + debug_label(SampleLabel::RetryAfterClose), + "retry_after_close" + ); + } + + #[test] + fn public_error_constructors_preserve_typed_variants() { + assert!(matches!( + RadrootsAppError::initialization("init"), + RadrootsAppError::Initialization(message) if message == "init" + )); + assert!(matches!( + RadrootsAppError::runtime("runtime"), + RadrootsAppError::Runtime(message) if message == "runtime" + )); + assert!(matches!( + RadrootsAppError::unsupported("unsupported"), + RadrootsAppError::Unsupported(message) if message == "unsupported" + )); + assert!(matches!( + RadrootsAppError::internal("internal"), + RadrootsAppError::Internal(message) if message == "internal" + )); + } + + #[derive(Debug)] + enum SampleLabel { + RetryAfterClose, + } +} diff --git a/core/crates/tera_core/src/lib.rs b/core/crates/tera_core/src/lib.rs @@ -0,0 +1,15 @@ +// UniFFI errors are serialized value contracts. Keeping the complete stable +// SDK report on the error is more important than optimizing the Rust enum's +// in-process size; mobile calls cross this boundary by value in all cases. +#![allow(clippy::result_large_err)] +#![cfg_attr(coverage_nightly, feature(coverage_attribute))] + +uniffi::setup_scaffolding!("radroots_mobile_core"); + +pub mod error; +#[cfg(not(target_arch = "wasm32"))] +pub mod logging; +pub mod runtime; + +pub use error::{RadrootsAppError, SdkErrorRecord}; +pub use runtime::RadrootsRuntime; diff --git a/core/crates/tera_core/src/logging.rs b/core/crates/tera_core/src/logging.rs @@ -0,0 +1,248 @@ +mod writer; + +use std::fs; +use std::path::{Component, Path, PathBuf}; +use std::sync::Mutex; + +use tracing_appender::non_blocking::WorkerGuard; +use tracing_subscriber::prelude::*; + +use self::writer::{LogRotation, SizeRotatingWriter}; + +#[derive(Debug, Clone, PartialEq, Eq)] +struct LoggingOptions { + dir: Option<PathBuf>, + file_name: String, + stdout: bool, + rotation: LogRotation, +} + +impl Default for LoggingOptions { + fn default() -> Self { + Self { + dir: None, + file_name: "radroots.log".to_owned(), + stdout: true, + rotation: LogRotation::default(), + } + } +} + +struct ActiveLogging { + options: LoggingOptions, + _file_guard: Option<WorkerGuard>, +} + +static LOGGING: Mutex<Option<ActiveLogging>> = Mutex::new(None); + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +pub fn init_logging( + dir: Option<String>, + file_name: Option<String>, + is_stdout: Option<bool>, +) -> Result<(), crate::RadrootsAppError> { + let opts = logging_options(dir, file_name, is_stdout); + initialize(opts).map_err(crate::RadrootsAppError::initialization) +} + +fn logging_options( + dir: Option<String>, + file_name: Option<String>, + is_stdout: Option<bool>, +) -> LoggingOptions { + LoggingOptions { + dir: dir.map(PathBuf::from), + file_name: file_name.unwrap_or_else(|| "radroots.log".to_string()), + stdout: is_stdout.unwrap_or(true), + ..LoggingOptions::default() + } +} + +fn initialize(options: LoggingOptions) -> Result<(), String> { + validate_options(&options)?; + let mut active = LOGGING + .lock() + .map_err(|_| "logging initialization state is poisoned".to_owned())?; + if let Some(existing) = active.as_ref() { + return if existing.options == options { + Ok(()) + } else { + Err("logging is already initialized with a different configuration".to_owned()) + }; + } + + let (file_writer, file_guard) = build_file_writer(&options)?; + let file_layer = file_writer.as_ref().map(|writer| { + tracing_subscriber::fmt::layer() + .with_writer(writer.clone()) + .with_ansi(false) + .with_target(false) + }); + let stdout_layer = options.stdout.then(|| { + tracing_subscriber::fmt::layer() + .with_writer(std::io::stdout) + .with_target(false) + }); + tracing_subscriber::registry() + .with(file_layer) + .with(stdout_layer) + .try_init() + .map_err(|error| error.to_string())?; + *active = Some(ActiveLogging { + options, + _file_guard: file_guard, + }); + Ok(()) +} + +fn validate_options(options: &LoggingOptions) -> Result<(), String> { + if options.dir.is_none() && !options.stdout { + return Err("logging requires at least one configured output".to_owned()); + } + if options.file_name.is_empty() + || Path::new(&options.file_name).components().count() != 1 + || !matches!( + Path::new(&options.file_name).components().next(), + Some(Component::Normal(_)) + ) + { + return Err("log file_name must be a safe basename".to_owned()); + } + Ok(()) +} + +type FileWriter = tracing_appender::non_blocking::NonBlocking; + +fn build_file_writer( + options: &LoggingOptions, +) -> Result<(Option<FileWriter>, Option<WorkerGuard>), String> { + let Some(dir) = options.dir.as_ref() else { + return Ok((None, None)); + }; + fs::create_dir_all(dir).map_err(|error| error.to_string())?; + let metadata = fs::symlink_metadata(dir).map_err(|error| error.to_string())?; + if metadata.file_type().is_symlink() || !metadata.is_dir() { + return Err("log directory is not a safe directory".to_owned()); + } + let writer = SizeRotatingWriter::new(dir.join(&options.file_name), options.rotation) + .map_err(|error| error.to_string())?; + let (writer, guard) = tracing_appender::non_blocking::NonBlockingBuilder::default() + .buffered_lines_limit(8192) + .lossy(false) + .thread_name("radroots-app-log-writer") + .finish(writer); + Ok((Some(writer), Some(guard))) +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +pub fn init_logging_stdout() -> Result<(), crate::RadrootsAppError> { + initialize(LoggingOptions::default()).map_err(crate::RadrootsAppError::initialization) +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +pub fn log_info(msg: String) -> Result<(), crate::RadrootsAppError> { + tracing::info!("{msg}"); + Ok(()) +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +pub fn log_error(msg: String) -> Result<(), crate::RadrootsAppError> { + tracing::error!("{msg}"); + Ok(()) +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +pub fn log_debug(msg: String) -> Result<(), crate::RadrootsAppError> { + tracing::debug!("{msg}"); + Ok(()) +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::{ + LogRotation, LoggingOptions, build_file_writer, initialize, log_debug, log_error, log_info, + logging_options, validate_options, + }; + use std::path::PathBuf; + + #[test] + fn logging_options_adopt_bounded_library_defaults() { + let options = logging_options( + Some("logs".to_owned()), + Some("mobile.log".to_owned()), + Some(false), + ); + + assert_eq!(options.dir, Some(PathBuf::from("logs"))); + assert_eq!(options.file_name, "mobile.log"); + assert!(!options.stdout); + assert_eq!(options.rotation, LogRotation::default()); + } + + #[test] + fn logging_options_preserve_public_api_defaults() { + let options = logging_options(None, None, None); + + assert_eq!(options.file_name, "radroots.log"); + assert!(options.stdout); + assert_eq!(options, LoggingOptions::default()); + } + + #[test] + fn validation_rejects_missing_outputs_and_unsafe_names() { + let mut options = LoggingOptions { + stdout: false, + ..LoggingOptions::default() + }; + assert!(validate_options(&options).is_err()); + + options.stdout = true; + for name in ["", "../radroots.log", "nested/radroots.log", "."] { + options.file_name = name.to_owned(); + assert!(validate_options(&options).is_err(), "accepted {name:?}"); + } + + options.dir = Some(PathBuf::from("logs")); + options.file_name = "radroots.log".to_owned(); + options.stdout = false; + validate_options(&options).expect("file output is sufficient"); + } + + #[test] + fn file_writer_is_optional_and_rejects_non_directories() { + let options = LoggingOptions::default(); + let (writer, guard) = build_file_writer(&options).expect("stdout only"); + assert!(writer.is_none()); + assert!(guard.is_none()); + + let directory = tempfile::tempdir().expect("temporary directory"); + let file = directory.path().join("not-a-directory"); + std::fs::write(&file, b"not a directory").expect("fixture"); + let options = LoggingOptions { + dir: Some(file), + ..LoggingOptions::default() + }; + assert!(build_file_writer(&options).is_err()); + } + + #[test] + fn logging_entry_points_accept_secret_safe_messages() { + log_info("info".to_owned()).expect("info"); + log_error("error".to_owned()).expect("error"); + log_debug("debug".to_owned()).expect("debug"); + } + + #[test] + fn initialization_is_idempotent_but_rejects_reconfiguration() { + let directory = tempfile::tempdir().expect("temporary directory"); + let options = LoggingOptions { + dir: Some(directory.path().to_owned()), + stdout: false, + ..LoggingOptions::default() + }; + initialize(options.clone()).expect("first initialization"); + initialize(options).expect("idempotent initialization"); + assert!(initialize(LoggingOptions::default()).is_err()); + } +} diff --git a/core/crates/tera_core/src/logging/writer.rs b/core/crates/tera_core/src/logging/writer.rs @@ -0,0 +1,268 @@ +use std::fs::{self, File, OpenOptions}; +use std::io::{self, Write}; +use std::path::{Path, PathBuf}; + +const DEFAULT_MAX_FILE_BYTES: u64 = 10 * 1024 * 1024; +const DEFAULT_RETAINED_FILES: usize = 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub(super) struct LogRotation { + max_file_bytes: u64, + retained_files: usize, +} + +impl Default for LogRotation { + fn default() -> Self { + Self { + max_file_bytes: DEFAULT_MAX_FILE_BYTES, + retained_files: DEFAULT_RETAINED_FILES, + } + } +} + +pub(super) struct SizeRotatingWriter { + path: PathBuf, + file: Option<File>, + bytes_written: u64, + policy: LogRotation, +} + +impl SizeRotatingWriter { + pub(super) fn new(path: PathBuf, policy: LogRotation) -> io::Result<Self> { + reject_unsafe_target(&path)?; + let file = open_append(&path)?; + let bytes_written = file.metadata()?.len(); + let mut writer = Self { + path, + file: Some(file), + bytes_written, + policy, + }; + if writer.bytes_written >= writer.policy.max_file_bytes { + writer.rotate()?; + } + Ok(writer) + } + + fn rotate(&mut self) -> io::Result<()> { + if let Some(mut file) = self.file.take() { + file.flush()?; + file.sync_data()?; + } + if self.policy.retained_files == 1 { + remove_if_present(&self.path)?; + } else { + remove_if_present(&rotated_path(&self.path, self.policy.retained_files - 1))?; + for index in (2..self.policy.retained_files).rev() { + rename_if_present( + &rotated_path(&self.path, index - 1), + &rotated_path(&self.path, index), + )?; + } + rename_if_present(&self.path, &rotated_path(&self.path, 1))?; + } + self.file = Some(open_append(&self.path)?); + self.bytes_written = 0; + Ok(()) + } + + fn file_mut(&mut self) -> io::Result<&mut File> { + self.file + .as_mut() + .ok_or_else(|| io::Error::other("log file is unavailable")) + } +} + +impl Write for SizeRotatingWriter { + fn write(&mut self, buffer: &[u8]) -> io::Result<usize> { + let incoming = u64::try_from(buffer.len()) + .map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "log event is too large"))?; + if incoming > self.policy.max_file_bytes { + return Err(io::Error::new( + io::ErrorKind::InvalidData, + "log event exceeds the configured file limit", + )); + } + if self.bytes_written > 0 + && self.bytes_written.saturating_add(incoming) > self.policy.max_file_bytes + { + self.rotate()?; + } + let written = self.file_mut()?.write(buffer)?; + self.bytes_written = self + .bytes_written + .saturating_add(u64::try_from(written).unwrap_or(u64::MAX)); + Ok(written) + } + + fn flush(&mut self) -> io::Result<()> { + self.file_mut()?.flush() + } +} + +fn reject_unsafe_target(path: &Path) -> io::Result<()> { + match fs::symlink_metadata(path) { + Ok(metadata) if metadata.file_type().is_symlink() || !metadata.is_file() => Err( + io::Error::new(io::ErrorKind::InvalidInput, "log target is not a safe file"), + ), + Ok(_) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } +} + +fn open_append(path: &Path) -> io::Result<File> { + let mut options = OpenOptions::new(); + options.create(true).append(true); + #[cfg(unix)] + { + use std::os::unix::fs::{OpenOptionsExt, PermissionsExt}; + options.mode(0o600); + let file = options.open(path)?; + file.set_permissions(fs::Permissions::from_mode(0o600))?; + Ok(file) + } + #[cfg(not(unix))] + options.open(path) +} + +fn rotated_path(path: &Path, index: usize) -> PathBuf { + let mut value = path.as_os_str().to_owned(); + value.push(format!(".{index}")); + PathBuf::from(value) +} + +fn remove_if_present(path: &Path) -> io::Result<()> { + match fs::remove_file(path) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } +} + +fn rename_if_present(source: &Path, target: &Path) -> io::Result<()> { + match fs::rename(source, target) { + Ok(()) => Ok(()), + Err(error) if error.kind() == io::ErrorKind::NotFound => Ok(()), + Err(error) => Err(error), + } +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::{ + LogRotation, SizeRotatingWriter, reject_unsafe_target, remove_if_present, + rename_if_present, rotated_path, + }; + use std::io::Write; + + #[test] + fn rotation_is_size_bounded_and_retention_is_finite() { + let directory = tempfile::tempdir().expect("temporary log directory"); + let path = directory.path().join("radroots.log"); + let mut writer = SizeRotatingWriter::new( + path.clone(), + LogRotation { + max_file_bytes: 5, + retained_files: 3, + }, + ) + .expect("writer"); + for value in [b"1111", b"2222", b"3333", b"4444"] { + writer.write_all(value).expect("log entry"); + } + writer.flush().expect("flush"); + assert_eq!(std::fs::read(&path).expect("current"), b"4444"); + assert_eq!( + std::fs::read(rotated_path(&path, 1)).expect("first retained"), + b"3333" + ); + assert_eq!( + std::fs::read(rotated_path(&path, 2)).expect("second retained"), + b"2222" + ); + assert!(!rotated_path(&path, 3).exists()); + } + + #[test] + fn single_file_rotation_removes_the_previous_file() { + let directory = tempfile::tempdir().expect("temporary log directory"); + let path = directory.path().join("radroots.log"); + std::fs::write(&path, b"full!").expect("fixture"); + let mut writer = SizeRotatingWriter::new( + path.clone(), + LogRotation { + max_file_bytes: 5, + retained_files: 1, + }, + ) + .expect("writer"); + writer.write_all(b"next").expect("write"); + writer.flush().expect("flush"); + assert_eq!(std::fs::read(path).expect("current"), b"next"); + } + + #[test] + fn oversized_events_and_unavailable_files_fail_closed() { + let directory = tempfile::tempdir().expect("temporary log directory"); + let path = directory.path().join("radroots.log"); + let mut writer = SizeRotatingWriter::new( + path, + LogRotation { + max_file_bytes: 3, + retained_files: 2, + }, + ) + .expect("writer"); + assert_eq!( + writer.write(b"four").expect_err("oversized").kind(), + std::io::ErrorKind::InvalidData + ); + writer.write_all(b"a").expect("first short write"); + writer.write_all(b"b").expect("second short write"); + writer.file = None; + assert_eq!( + writer.flush().expect_err("missing file").kind(), + std::io::ErrorKind::Other + ); + } + + #[test] + fn unsafe_targets_and_absent_rotation_files_are_handled() { + let directory = tempfile::tempdir().expect("temporary directory"); + assert!(reject_unsafe_target(directory.path()).is_err()); + let missing = directory.path().join("missing"); + assert!(reject_unsafe_target(&missing).is_ok()); + assert!(remove_if_present(&missing).is_ok()); + assert!(rename_if_present(&missing, &directory.path().join("target")).is_ok()); + assert!(remove_if_present(directory.path()).is_err()); + + let source = directory.path().join("source"); + std::fs::write(&source, b"source").expect("source"); + assert!(rename_if_present(&source, directory.path()).is_err()); + + #[cfg(unix)] + { + std::os::unix::fs::symlink(directory.path(), &missing).expect("symlink"); + assert!(reject_unsafe_target(&missing).is_err()); + } + } + + #[test] + fn rotation_without_an_open_file_recreates_the_target() { + let directory = tempfile::tempdir().expect("temporary directory"); + let path = directory.path().join("radroots.log"); + let mut writer = SizeRotatingWriter::new( + path, + LogRotation { + max_file_bytes: 3, + retained_files: 2, + }, + ) + .expect("writer"); + writer.file = None; + writer.rotate().expect("rotation"); + writer.write_all(b"ok").expect("write after rotation"); + } +} diff --git a/core/crates/tera_core/src/runtime/app_info.rs b/core/crates/tera_core/src/runtime/app_info.rs @@ -0,0 +1,26 @@ +#[derive(Debug, Clone, Default, serde::Serialize, uniffi::Record)] +pub struct AppInfoPlatform { + pub platform: Option<String>, + pub bundle_id: Option<String>, + pub version: Option<String>, + pub build_number: Option<String>, + pub build_sha: Option<String>, +} + +impl AppInfoPlatform { + pub fn new( + platform: Option<String>, + bundle_id: Option<String>, + version: Option<String>, + build_number: Option<String>, + build_sha: Option<String>, + ) -> Self { + Self { + platform, + bundle_id, + version, + build_number, + build_sha, + } + } +} diff --git a/core/crates/tera_core/src/runtime/builder.rs b/core/crates/tera_core/src/runtime/builder.rs @@ -0,0 +1,27 @@ +use crate::{RadrootsAppError, RadrootsRuntime}; + +/// Host-owned construction boundary for the shared SDK-backed runtime. +#[derive(Default)] +pub struct RuntimeBuilder; + +impl RuntimeBuilder { + #[must_use] + pub const fn new() -> Self { + Self + } + + pub fn build(self) -> Result<RadrootsRuntime, RadrootsAppError> { + RadrootsRuntime::new() + } +} + +#[cfg(test)] +mod tests { + use super::RuntimeBuilder; + + #[test] + fn builder_constructs_the_sdk_backed_runtime() { + let runtime = RuntimeBuilder::new().build().expect("runtime"); + assert!(!runtime.info().sdk_closed); + } +} diff --git a/core/crates/tera_core/src/runtime/info.rs b/core/crates/tera_core/src/runtime/info.rs @@ -0,0 +1,77 @@ +use super::RadrootsRuntime; +use chrono::Utc; +use serde::Serialize; + +#[derive(Debug, Clone, Serialize, Default, uniffi::Record)] +pub struct RuntimeBuildInfo { + pub crate_name: String, + pub crate_version: String, + pub rustc: Option<String>, + pub profile: Option<String>, + pub git_sha: Option<String>, + pub build_time_unix: Option<u64>, +} + +#[derive(Debug, Clone, Serialize, uniffi::Record)] +pub struct AppInfo { + pub build: RuntimeBuildInfo, + pub started_unix_ms: i64, + pub uptime_millis: i64, + pub shutting_down: bool, + pub platform: Option<super::app_info::AppInfoPlatform>, +} + +#[derive(Debug, Clone, Serialize, uniffi::Record)] +pub struct RuntimeInfo { + pub app: AppInfo, + pub sdk: RuntimeBuildInfo, + pub sdk_closed: bool, +} + +pub fn gather_runtime_info(runtime: &RadrootsRuntime) -> RuntimeInfo { + let now_ms = Utc::now().timestamp_millis(); + RuntimeInfo { + app: AppInfo { + build: app_build_info(), + started_unix_ms: runtime.started_unix_ms, + uptime_millis: now_ms - runtime.started_unix_ms, + shutting_down: runtime + .shutting_down + .load(std::sync::atomic::Ordering::SeqCst), + platform: runtime + .platform_app + .read() + .ok() + .and_then(|value| (*value).clone()), + }, + sdk: RuntimeBuildInfo { + crate_name: "radroots_sdk".to_owned(), + crate_version: "0.1.0-alpha".to_owned(), + ..RuntimeBuildInfo::default() + }, + sdk_closed: runtime.client.is_closed(), + } +} + +pub fn app_build_info() -> RuntimeBuildInfo { + RuntimeBuildInfo { + crate_name: env!("CARGO_PKG_NAME").to_owned(), + crate_version: env!("CARGO_PKG_VERSION").to_owned(), + rustc: option_env!("RUSTC_VERSION").map(str::to_owned), + profile: option_env!("PROFILE").map(str::to_owned), + git_sha: option_env!("GIT_HASH").map(str::to_owned), + build_time_unix: option_env!("BUILD_TIME_UNIX").and_then(|value| value.parse().ok()), + } +} + +#[cfg(test)] +mod tests { + #[test] + fn build_info_uses_sdk_identity_without_lower_runtime_metadata() { + let runtime = super::RadrootsRuntime::new().expect("runtime"); + let info = runtime.info(); + assert_eq!(info.sdk.crate_name, "radroots_sdk"); + assert_eq!(info.sdk.crate_version, "0.1.0-alpha"); + assert!(!info.sdk_closed); + } +} diff --git a/core/crates/tera_core/src/runtime/key_management.rs b/core/crates/tera_core/src/runtime/key_management.rs @@ -0,0 +1,214 @@ +//! Host-custodied mobile identity presentation over the SDK signer slot. + +use super::RadrootsRuntime; +use crate::RadrootsAppError; + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrIdentityRecord { + pub id: String, + pub public_key_hex: String, + pub public_key_npub: String, + pub label: Option<String>, + pub is_selected: bool, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrIdentitySnapshot { + pub has_selected_signing_identity: bool, + pub selected_identity_id: Option<String>, + pub selected_npub: Option<String>, + pub identities: Vec<NostrIdentityRecord>, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrHostCustodyIdentity { + pub id: String, + pub public_key_hex: String, + pub public_key_npub: String, +} + +fn host_identity(identity: &radroots_sdk::signing::LocalIdentity) -> NostrHostCustodyIdentity { + let public_key_hex = identity.public_key_hex(); + NostrHostCustodyIdentity { + id: public_key_hex.clone(), + public_key_hex, + public_key_npub: identity.npub().to_owned(), + } +} + +fn identity_record( + identity: &radroots_sdk::signing::LocalIdentity, + label: Option<String>, +) -> NostrIdentityRecord { + let identity = host_identity(identity); + NostrIdentityRecord { + id: identity.id, + public_key_hex: identity.public_key_hex, + public_key_npub: identity.public_key_npub, + label, + is_selected: true, + } +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +impl RadrootsRuntime { + pub fn nostr_identity_has_selected_signing_identity(&self) -> bool { + self.signing_slot.identity().is_some() + } + + pub fn nostr_identity_selected_npub(&self) -> Option<String> { + self.signing_slot + .identity() + .map(|identity| identity.npub().to_owned()) + } + + pub fn nostr_identity_list(&self) -> Result<Vec<NostrIdentityRecord>, RadrootsAppError> { + let Some(identity) = self.signing_slot.identity() else { + return Ok(Vec::new()); + }; + Ok(vec![identity_record(&identity, self.identity_label())]) + } + + pub fn nostr_identity_list_ids(&self) -> Result<Vec<String>, RadrootsAppError> { + Ok(self + .nostr_identity_list()? + .into_iter() + .map(|identity| identity.id) + .collect()) + } + + pub fn nostr_identity_snapshot(&self) -> Result<NostrIdentitySnapshot, RadrootsAppError> { + let identities = self.nostr_identity_list()?; + let selected = identities.first(); + Ok(NostrIdentitySnapshot { + has_selected_signing_identity: selected.is_some(), + selected_identity_id: selected.map(|identity| identity.id.clone()), + selected_npub: selected.map(|identity| identity.public_key_npub.clone()), + identities, + }) + } + + pub fn nostr_identity_validate_host_custody_secret( + &self, + secret_key: String, + ) -> Result<NostrHostCustodyIdentity, RadrootsAppError> { + let slot = radroots_sdk::signing::Slot::new(); + let identity = slot + .install(secret_key.as_str()) + .map_err(|_| RadrootsAppError::runtime("identity secret is invalid"))?; + slot.clear(); + Ok(host_identity(&identity)) + } + + pub fn nostr_identity_restore_host_custody_secret( + &self, + secret_key: String, + label: Option<String>, + make_selected: bool, + ) -> Result<NostrIdentityRecord, RadrootsAppError> { + if !make_selected { + let identity = self.nostr_identity_validate_host_custody_secret(secret_key)?; + return Ok(NostrIdentityRecord { + id: identity.id, + public_key_hex: identity.public_key_hex, + public_key_npub: identity.public_key_npub, + label, + is_selected: false, + }); + } + let identity = self + .signing_slot + .install(secret_key.as_str()) + .map_err(|_| RadrootsAppError::runtime("identity secret is invalid"))?; + self.set_identity_label(label.clone())?; + Ok(identity_record(&identity, label)) + } + + pub fn nostr_identity_select(&self, identity_id: String) -> Result<(), RadrootsAppError> { + let current = self + .signing_slot + .identity() + .ok_or_else(|| RadrootsAppError::runtime("identity is not installed"))?; + if current.public_key_hex() != identity_id { + return Err(RadrootsAppError::runtime("identity is not installed")); + } + Ok(()) + } + + pub fn nostr_identity_remove(&self, identity_id: String) -> Result<(), RadrootsAppError> { + if self + .signing_slot + .identity() + .is_some_and(|identity| identity.public_key_hex() == identity_id) + { + self.signing_slot.clear(); + self.set_identity_label(None)?; + } + Ok(()) + } + + pub fn nostr_identity_lock_host_custody_runtime(&self) -> Result<(), RadrootsAppError> { + self.signing_slot.clear(); + self.set_identity_label(None) + } + + pub fn nostr_identity_reset_host_custody_runtime(&self) -> Result<(), RadrootsAppError> { + self.nostr_identity_lock_host_custody_runtime() + } + + fn identity_label(&self) -> Option<String> { + self.identity_label + .read() + .ok() + .and_then(|label| label.clone()) + } + + fn set_identity_label(&self, label: Option<String>) -> Result<(), RadrootsAppError> { + let mut current = self + .identity_label + .write() + .map_err(|_| RadrootsAppError::runtime("identity label state is unavailable"))?; + *current = label; + Ok(()) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + const SECRET: &str = "0000000000000000000000000000000000000000000000000000000000000001"; + + #[test] + fn validation_does_not_select_and_restore_is_single_slot() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let validated = runtime + .nostr_identity_validate_host_custody_secret(SECRET.to_owned()) + .expect("valid secret"); + assert!(!runtime.nostr_identity_has_selected_signing_identity()); + + let staged = runtime + .nostr_identity_restore_host_custody_secret( + SECRET.to_owned(), + Some("staged".to_owned()), + false, + ) + .expect("staged"); + assert_eq!(staged.id, validated.id); + assert!(!staged.is_selected); + + let selected = runtime + .nostr_identity_restore_host_custody_secret( + SECRET.to_owned(), + Some("selected".to_owned()), + true, + ) + .expect("selected"); + assert!(selected.is_selected); + assert_eq!(runtime.nostr_identity_list().expect("list"), vec![selected]); + runtime + .nostr_identity_lock_host_custody_runtime() + .expect("lock"); + assert!(runtime.nostr_identity_list().expect("list").is_empty()); + } +} diff --git a/core/crates/tera_core/src/runtime/mod.rs b/core/crates/tera_core/src/runtime/mod.rs @@ -0,0 +1,173 @@ +pub mod app_info; +pub mod builder; +pub mod info; +#[cfg(feature = "mobile-social")] +pub mod key_management; +#[cfg(feature = "mobile-social")] +pub mod nostr; +pub mod product_surface; +pub mod sdk; + +use chrono::Utc; +use radroots_sdk::{Client, ClientBuilder}; +use std::sync::{ + RwLock, + atomic::{AtomicBool, Ordering}, +}; + +use self::{ + app_info::AppInfoPlatform, + info::{RuntimeInfo, gather_runtime_info}, +}; +use crate::RadrootsAppError; + +#[derive(uniffi::Object)] +pub struct RadrootsRuntime { + pub(crate) client: Client, + #[cfg(feature = "mobile-social")] + pub(crate) signing_slot: radroots_sdk::signing::Slot, + #[cfg(feature = "mobile-social")] + pub(crate) nostr_slot: radroots_sdk::transport::NostrSlot, + #[cfg(feature = "mobile-social")] + pub(crate) identity_label: RwLock<Option<String>>, + pub(crate) started_unix_ms: i64, + pub(crate) shutting_down: AtomicBool, + pub(crate) platform_app: RwLock<Option<AppInfoPlatform>>, +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +impl RadrootsRuntime { + #[cfg_attr(not(coverage_nightly), uniffi::constructor)] + pub fn new() -> Result<Self, RadrootsAppError> { + #[cfg(feature = "mobile-social")] + let signing_slot = radroots_sdk::signing::Slot::new(); + #[cfg(feature = "mobile-social")] + let nostr_slot = radroots_sdk::transport::NostrSlot::new( + radroots_sdk::transport::RelayUrlPolicy::Public, + ); + let builder = ClientBuilder::memory_default(); + #[cfg(feature = "mobile-social")] + let builder = builder + .signing(radroots_sdk::signing::Provider::slot(signing_slot.clone())) + .nostr(nostr_slot.clone()) + .host_sync(radroots_sdk::sync::HostPolicy::standard()); + let client = builder.build().map_err(RadrootsAppError::from_sdk)?; + + Ok(Self { + client, + #[cfg(feature = "mobile-social")] + signing_slot, + #[cfg(feature = "mobile-social")] + nostr_slot, + #[cfg(feature = "mobile-social")] + identity_label: RwLock::new(None), + started_unix_ms: Utc::now().timestamp_millis(), + shutting_down: AtomicBool::new(false), + platform_app: RwLock::new(None), + }) + } + + /// Closes SDK resources asynchronously across every runtime reference. + /// + /// Dropping the returned future before its first poll has no effect. If a + /// host cancels after close begins, it must call `shutdown` again; the SDK + /// remains unavailable and resumes the explicit close attempt. Completed + /// calls are idempotent and no blocking destructor is installed. + pub async fn shutdown(&self) -> Result<sdk::SdkShutdownRecord, RadrootsAppError> { + let already_closed = self.client.is_closed(); + self.shutting_down.store(true, Ordering::Release); + self.client + .close() + .await + .map_err(RadrootsAppError::from_sdk)?; + Ok(sdk::SdkShutdownRecord { + state: "closed".to_owned(), + already_closed, + }) + } + + pub fn uptime_millis(&self) -> i64 { + Utc::now().timestamp_millis() - self.started_unix_ms + } + + pub fn info(&self) -> RuntimeInfo { + gather_runtime_info(self) + } + + pub fn info_json(&self) -> String { + serde_json::to_string_pretty(&self.info()) + .unwrap_or_else(|error| format!(r#"{{"error":"serialize RuntimeInfo: {error}"}}"#)) + } + + pub fn set_app_info_platform( + &self, + platform: Option<String>, + bundle_id: Option<String>, + version: Option<String>, + build_number: Option<String>, + build_sha: Option<String>, + ) { + let platform_info = + AppInfoPlatform::new(platform, bundle_id, version, build_number, build_sha); + if let Ok(mut guard) = self.platform_app.write() { + *guard = Some(platform_info); + } + } +} + +#[cfg(test)] +mod tests { + use super::RadrootsRuntime; + use radroots_sdk::capability::{Availability, CapabilityId}; + use std::panic::{AssertUnwindSafe, catch_unwind}; + + fn poison_platform_lock(runtime: &RadrootsRuntime) { + let _ = catch_unwind(AssertUnwindSafe(|| { + let _guard = runtime.platform_app.write().expect("lock platform"); + panic!("poison platform lock"); + })); + } + + #[test] + fn runtime_owns_one_sdk_client() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let storage = runtime + .client + .capabilities() + .get(CapabilityId::CANONICAL_STORAGE) + .expect("storage capability"); + assert_eq!(storage.availability(), Availability::Available); + assert!(!runtime.client.is_closed()); + } + + #[test] + fn set_platform_info_handles_poisoned_lock() { + let runtime = RadrootsRuntime::new().expect("runtime"); + runtime.set_app_info_platform( + Some("ios".to_owned()), + Some("org.radroots.app".to_owned()), + Some("1.0.0".to_owned()), + Some("100".to_owned()), + Some("abc123".to_owned()), + ); + assert_eq!( + runtime + .info() + .app + .platform + .as_ref() + .and_then(|value| value.platform.clone()), + Some("ios".to_owned()) + ); + poison_platform_lock(&runtime); + runtime.set_app_info_platform(None, None, None, None, None); + } + + #[test] + fn runtime_metadata_helpers_are_host_safe() { + let runtime = RadrootsRuntime::new().expect("runtime"); + assert!(runtime.uptime_millis() >= 0); + let json = runtime.info_json(); + assert!(json.contains("sdk")); + } +} diff --git a/core/crates/tera_core/src/runtime/nostr.rs b/core/crates/tera_core/src/runtime/nostr.rs @@ -0,0 +1,241 @@ +//! Bounded mobile Nostr presentation over shared SDK operations. + +use super::RadrootsRuntime; +use crate::RadrootsAppError; + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq)] +pub enum NostrLight { + Red, + Yellow, + Green, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrConnectionStatus { + pub light: NostrLight, + pub configured: bool, + pub source_available: bool, + pub sink_available: bool, + pub last_error: Option<String>, +} + +#[derive(uniffi::Record, Debug, Clone, Default, Eq, PartialEq)] +pub struct NostrProfile { + pub name: Option<String>, + pub display_name: Option<String>, + pub nip05: Option<String>, + pub about: Option<String>, + pub website: Option<String>, + pub picture: Option<String>, + pub banner: Option<String>, + pub lud06: Option<String>, + pub lud16: Option<String>, + pub bot: Option<String>, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrProfileEventMetadata { + pub id: String, + pub author: String, + pub published_at: u64, + pub profile: NostrProfile, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrPost { + pub content: String, +} + +#[derive(uniffi::Record, Debug, Clone, Eq, PartialEq)] +pub struct NostrPostEventMetadata { + pub id: String, + pub author: String, + pub published_at: u64, + pub post: NostrPost, +} + +fn map_profile(event: radroots_sdk::client::ProfileEvent) -> NostrProfileEventMetadata { + NostrProfileEventMetadata { + id: event.event_id().to_owned(), + author: event.author().to_owned(), + published_at: event.created_at(), + profile: NostrProfile { + name: event.name().map(str::to_owned), + display_name: event.display_name().map(str::to_owned), + nip05: event.nip05().map(str::to_owned), + about: event.about().map(str::to_owned), + website: None, + picture: event.picture().map(str::to_owned), + banner: event.banner().map(str::to_owned), + lud06: None, + lud16: None, + bot: event.bot().map(|value| value.to_string()), + }, + } +} + +fn map_post(event: radroots_sdk::client::PostEvent) -> NostrPostEventMetadata { + NostrPostEventMetadata { + id: event.event_id().to_owned(), + author: event.author().to_owned(), + published_at: event.created_at(), + post: NostrPost { + content: event.content().to_owned(), + }, + } +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +impl RadrootsRuntime { + pub fn nostr_set_default_relays(&self, relays: Vec<String>) -> Result<(), RadrootsAppError> { + self.nostr_slot + .configure(relays) + .map_err(RadrootsAppError::from_sdk) + } + + /// Validates readiness; relay connections remain operation-scoped. + pub fn nostr_connect_if_key_present(&self) -> Result<(), RadrootsAppError> { + if self.signing_slot.identity().is_none() { + return Err(RadrootsAppError::runtime("identity is not installed")); + } + if self.nostr_slot.targets().is_none() { + return Err(RadrootsAppError::runtime( + "relay selection is not configured", + )); + } + Ok(()) + } + + pub async fn nostr_connection_status(&self) -> Result<NostrConnectionStatus, RadrootsAppError> { + let social = self.client.social().map_err(RadrootsAppError::from_sdk)?; + let health = social + .transport_health() + .await + .map_err(RadrootsAppError::from_sdk)?; + let light = if health.is_source_available() && health.is_sink_available() { + NostrLight::Green + } else if health.is_configured() { + NostrLight::Yellow + } else { + NostrLight::Red + }; + Ok(NostrConnectionStatus { + light, + configured: health.is_configured(), + source_available: health.is_source_available(), + sink_available: health.is_sink_available(), + last_error: None, + }) + } + + pub async fn nostr_profile_for_self( + &self, + ) -> Result<Option<NostrProfileEventMetadata>, RadrootsAppError> { + self.client + .social() + .map_err(RadrootsAppError::from_sdk)? + .fetch_profile_for_signer() + .await + .map(|profile| profile.map(map_profile)) + .map_err(RadrootsAppError::from_sdk) + } + + pub async fn nostr_post_profile( + &self, + name: Option<String>, + display_name: Option<String>, + nip05: Option<String>, + about: Option<String>, + ) -> Result<String, RadrootsAppError> { + let name = name + .filter(|value| !value.trim().is_empty()) + .ok_or_else(|| RadrootsAppError::runtime("profile name is required"))?; + let mut draft = radroots_sdk::client::ProfileDraft::new(name); + if let Some(value) = display_name.filter(|value| !value.is_empty()) { + draft = draft.with_display_name(value); + } + if let Some(value) = nip05.filter(|value| !value.is_empty()) { + draft = draft.with_nip05(value); + } + if let Some(value) = about.filter(|value| !value.is_empty()) { + draft = draft.with_about(value); + } + self.client + .social() + .map_err(RadrootsAppError::from_sdk)? + .publish_profile(draft) + .await + .map(|receipt| receipt.event_id().to_owned()) + .map_err(RadrootsAppError::from_sdk) + } + + pub async fn nostr_post_text_note(&self, content: String) -> Result<String, RadrootsAppError> { + self.client + .social() + .map_err(RadrootsAppError::from_sdk)? + .publish_text(content) + .await + .map(|receipt| receipt.event_id().to_owned()) + .map_err(RadrootsAppError::from_sdk) + } + + pub async fn nostr_fetch_text_notes( + &self, + limit: u16, + since_unix: Option<u64>, + ) -> Result<Vec<NostrPostEventMetadata>, RadrootsAppError> { + self.client + .social() + .map_err(RadrootsAppError::from_sdk)? + .fetch_posts(limit, since_unix) + .await + .map(|events| events.into_iter().map(map_post).collect()) + .map_err(RadrootsAppError::from_sdk) + } + + pub async fn nostr_post_reply( + &self, + parent_event_id_hex: String, + parent_author_hex: String, + content: String, + root_event_id_hex: Option<String>, + ) -> Result<String, RadrootsAppError> { + if root_event_id_hex + .as_deref() + .is_some_and(|root| root != parent_event_id_hex.as_str()) + { + return Err(RadrootsAppError::unsupported( + "nested reply author context is required", + )); + } + self.client + .social() + .map_err(RadrootsAppError::from_sdk)? + .publish_reply( + content, + parent_event_id_hex.as_str(), + parent_author_hex.as_str(), + None, + ) + .await + .map(|receipt| receipt.event_id().to_owned()) + .map_err(RadrootsAppError::from_sdk) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[tokio::test] + async fn relay_configuration_is_explicit_and_status_is_categorical() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let initial = runtime + .nostr_connection_status() + .await + .expect("initial status"); + assert_eq!(initial.light, NostrLight::Red); + assert!(!initial.configured); + assert!(runtime.nostr_set_default_relays(Vec::new()).is_err()); + } +} diff --git a/core/crates/tera_core/src/runtime/product_surface.rs b/core/crates/tera_core/src/runtime/product_surface.rs @@ -0,0 +1,3641 @@ +//! Phase 1 product-surface contracts for native Radroots clients. +//! +//! These DTOs are the shared Rust vocabulary for the iOS `Today | Add` +//! surface. They deliberately model workflow actors, visibility, authority, +//! Today cards, Add actions, object pages, and outbox state separately from +//! low-level Nostr protocol roles or legacy trade/listing APIs. + +use serde::{Deserialize, Serialize}; + +use super::RadrootsRuntime; + +/// Phase 1 workflow actors are product authority roles. Low-level protocol +/// roles such as Farmer, Buyer, Seller, and Service are compatibility roles and +/// are not sufficient authority for Phase 1 workflows. +pub const WORKFLOW_ACTOR_COMPATIBILITY_NOTE: &str = "Phase 1 workflow actors are product authority roles; low-level protocol \ + roles such as Farmer, Buyer, Seller, and Service are compatibility roles \ + and are not sufficient authority."; + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum ContextType { + Regional, + Network, + Farm, + Buyer, + Route, + RoutePartner, + PickupPoint, + TraceRecords, + Hub, + NetworkSteward, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum WorkflowActor { + NetworkMember, + ProducerAdmin, + FarmTeamMember, + HubOperator, + TraceLead, + BuyerSourcingLead, + BuyerReceiver, + PickupPointCoordinator, + RouteCoordinator, + RoutePartner, + NetworkSteward, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum VisibilityClass { + LocalDraft, + FarmPrivate, + WorkspacePrivate, + NetworkVisible, + RouteScoped, + BuyerScoped, + PublicCommunity, + PublicProvenance, + SecretNeverShared, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +pub enum AuthorityDomain { + #[serde(rename = "Relay/group access")] + RelayGroupAccess, + #[serde(rename = "Farm/workspace operations authority")] + FarmWorkspaceOperations, + #[serde(rename = "Buyer workspace authority")] + BuyerWorkspace, + #[serde(rename = "Route coordination authority")] + RouteCoordination, + #[serde(rename = "Route execution authority")] + RouteExecution, + #[serde(rename = "Receipt authority")] + Receipt, + #[serde(rename = "Trace/proof authority")] + TraceProof, + #[serde(rename = "Public publishing authority")] + PublicPublishing, + #[serde(rename = "Network stewardship authority")] + NetworkStewardship, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum AuthorityAction { + Submit, + Publish, + Share, + Assign, + Approve, + Correct, + Close, + Retry, + Search, + NavigateRelatedObject, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum ObjectKind { + Region, + Network, + Farm, + BuyerWorkspace, + Route, + RoutePartner, + PickupPoint, + Hub, + Food, + Ask, + Event, + Place, + Task, + Proof, + Exception, + Provenance, + Update, + AccessMembership, + BuyerPacket, + RouteStop, + Draft, + OutboxItem, + MemberInvite, + Correction, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum ObjectPageFamily { + Network, + NetworkRoute, + FarmWorkspace, + FarmPublicProfile, + BuyerWorkspace, + PickupPointPlace, + Food, + Event, + RouteStop, + Proof, + BuyerPacket, + PublicProvenance, + Exception, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum TodayCardType { + Route, + Food, + Ask, + Event, + Place, + Task, + Proof, + Exception, + Provenance, + Update, + AccessMembership, + SyncOutbox, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum AddActionType { + Photo, + Note, + Ask, + Scan, + Food, + Harvest, + BuyerRequest, + BuyerCommitment, + RouteNeed, + RouteStop, + PickupEvent, + Place, + Proof, + Exception, + PublicUpdate, + Provenance, + MemberInvite, + Correction, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum AddFlowState { + NotStarted, + Draft, + Editing, + ValidationFailed, + ReadyToSubmit, + Submitted, + Queued, + Syncing, + NeedsApproval, + Approved, + Published, + Shared, + Confirmed, + Failed, + Conflict, + Discarded, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum OutboxBehavior { + LocalOnly, + QueueWhenOffline, + RequireOnline, + PublishWhenAuthorized, + ShareWhenAuthorized, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum PrototypePathKind { + ProducerFoodToRoute, + BuyerCommitmentToRoute, + RouteCoordinatorAssignment, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum RouteExecutionFlowKind { + RoutePartnerAssignedStops, + BuyerReceiptConfirmation, + ExceptionRecovery, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum RouteExecutionStepKind { + AssignedRoute, + PickupConfirmation, + DropoffConfirmation, + ReceiptConfirmation, + ExceptionReport, + RecoveryAction, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum ProofProvenanceArtifactKind { + ProofCompleteness, + BuyerPacketDraft, + BuyerPacketShared, + PublicProvenancePreview, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum ProofProvenanceReviewState { + MissingProof, + Complete, + Draft, + ReadyToShare, + Shared, + RedactionRequired, + ReadyToPublish, + Published, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum StewardshipAccessItemKind { + AccessRequestReview, + RoleApproval, + RoutePartnerInvite, + RoutePoolMetadata, + PublicModeration, + InviteAcceptance, + RequestAccess, + AccessDenied, + GroupManagementDeferred, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum OutboxState { + NotQueued, + Draft, + Queued, + Syncing, + AwaitingAuthority, + Published, + Shared, + Failed, + Conflict, + Discarded, +} + +#[derive(uniffi::Enum, Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "PascalCase")] +pub enum SyncState { + Unknown, + Online, + Offline, + Syncing, + Synced, + Stale, + Failed, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ObjectRef { + pub object_type: ObjectKind, + pub object_id: String, + pub display_label: String, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct EventRef { + pub event_id: String, + pub relay_url: Option<String>, + pub kind: Option<u32>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ActiveContext { + pub context_type: ContextType, + pub context_ref: ObjectRef, + pub actor: WorkflowActor, + pub display_label: String, + pub visibility_scope: VisibilityClass, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AuthorityGate { + pub domain: AuthorityDomain, + pub action: AuthorityAction, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub is_required: bool, + pub is_allowed: bool, + pub reason: Option<String>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ObjectPageSummary { + pub object_ref: ObjectRef, + pub family: ObjectPageFamily, + pub primary_context: ActiveContext, + pub title: String, + pub subtitle: Option<String>, + pub visibility: VisibilityClass, + pub visibility_label: String, + pub required_authority: AuthorityGate, + pub sync_state: SyncState, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TodayCardAction { + pub id: String, + pub label: String, + pub action_type: Option<AddActionType>, + pub target_object: Option<ObjectRef>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct TodayCard { + pub id: String, + pub card_type: TodayCardType, + pub source_object_refs: Vec<ObjectRef>, + pub source_event_refs: Vec<EventRef>, + pub primary_context: ActiveContext, + pub actor: WorkflowActor, + pub visibility: VisibilityClass, + pub visibility_label: String, + pub title: String, + pub status_line: String, + pub detail_lines: Vec<String>, + pub pills: Vec<String>, + pub primary_action: TodayCardAction, + pub secondary_action: Option<TodayCardAction>, + pub ranking_reason: String, + pub ranking_features: Vec<String>, + pub sync_state: SyncState, + pub outbox_state: OutboxState, + pub is_stale: bool, + pub is_offline: bool, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RelatedObjectRequirement { + pub object_type: ObjectKind, + pub relationship_label: String, + pub is_required: bool, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ValidationRequirement { + pub id: String, + pub label: String, + pub is_blocking: bool, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct AddAction { + pub action_type: AddActionType, + pub display_label: String, + pub allowed_context_types: Vec<ContextType>, + pub required_authority: AuthorityGate, + pub default_visibility: VisibilityClass, + pub allowed_visibility_options: Vec<VisibilityClass>, + pub created_or_updated_object_type: ObjectKind, + pub related_object_requirements: Vec<RelatedObjectRequirement>, + pub validation_requirements: Vec<ValidationRequirement>, + pub supports_offline: bool, + pub supports_draft: bool, + pub outbox_behavior: OutboxBehavior, + pub primary_submit_label: String, + pub completion_state: AddFlowState, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OutboxItem { + pub id: String, + pub action_type: AddActionType, + pub context: ActiveContext, + pub object_refs: Vec<ObjectRef>, + pub event_refs: Vec<EventRef>, + pub visibility: VisibilityClass, + pub authority_gate: AuthorityGate, + pub flow_state: AddFlowState, + pub outbox_state: OutboxState, + pub sync_state: SyncState, + pub queued_at_unix: Option<u64>, + pub last_attempt_at_unix: Option<u64>, + pub retry_count: u32, + pub last_error: Option<String>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct OutboxRetryDecision { + pub item_id: String, + pub is_retryable: bool, + pub authority_gate: AuthorityGate, + pub reason: Option<String>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct SearchResultSummary { + pub id: String, + pub object_ref: ObjectRef, + pub primary_context: ActiveContext, + pub title: String, + pub subtitle: Option<String>, + pub visibility: VisibilityClass, + pub visibility_label: String, + pub required_authority: AuthorityGate, + pub sync_state: SyncState, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrototypePathStep { + pub id: String, + pub label: String, + pub context: ActiveContext, + pub action_type: Option<AddActionType>, + pub object_ref: Option<ObjectRef>, + pub authority_gate: AuthorityGate, + pub visibility: VisibilityClass, + pub outbox_state: OutboxState, + pub sync_state: SyncState, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PrototypePath { + pub id: String, + pub kind: PrototypePathKind, + pub title: String, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub steps: Vec<PrototypePathStep>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RouteExecutionStep { + pub id: String, + pub kind: RouteExecutionStepKind, + pub label: String, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub route_ref: ObjectRef, + pub object_ref: Option<ObjectRef>, + pub required_authority: AuthorityGate, + pub visibility: VisibilityClass, + pub supports_offline: bool, + pub supports_partial_receipt: bool, + pub uses_receipt_token: bool, + pub outbox_state: OutboxState, + pub sync_state: SyncState, + pub detail_lines: Vec<String>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct RouteExecutionFlow { + pub id: String, + pub kind: RouteExecutionFlowKind, + pub title: String, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub route_ref: ObjectRef, + pub steps: Vec<RouteExecutionStep>, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct ProofProvenanceArtifact { + pub id: String, + pub kind: ProofProvenanceArtifactKind, + pub review_state: ProofProvenanceReviewState, + pub title: String, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub object_ref: ObjectRef, + pub source_object_refs: Vec<ObjectRef>, + pub required_authority: AuthorityGate, + pub visibility: VisibilityClass, + pub is_public_preview: bool, + pub requires_redaction_review: bool, + pub can_publish: bool, + pub public_summary_lines: Vec<String>, + pub redacted_field_labels: Vec<String>, + pub outbox_state: OutboxState, + pub sync_state: SyncState, +} + +#[derive(uniffi::Record, Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct StewardshipAccessItem { + pub id: String, + pub kind: StewardshipAccessItemKind, + pub title: String, + pub actor: WorkflowActor, + pub context: ActiveContext, + pub target_ref: ObjectRef, + pub required_authority: AuthorityGate, + pub visibility: VisibilityClass, + pub is_admin_lite: bool, + pub is_phase_2_deferred: bool, + pub grants_private_access: bool, + pub outbox_state: OutboxState, + pub sync_state: SyncState, + pub detail_lines: Vec<String>, +} + +pub const CANONICAL_CONTEXT_TYPES: [ContextType; 10] = [ + ContextType::Regional, + ContextType::Network, + ContextType::Farm, + ContextType::Buyer, + ContextType::Route, + ContextType::RoutePartner, + ContextType::PickupPoint, + ContextType::TraceRecords, + ContextType::Hub, + ContextType::NetworkSteward, +]; + +pub const CANONICAL_WORKFLOW_ACTORS: [WorkflowActor; 11] = [ + WorkflowActor::NetworkMember, + WorkflowActor::ProducerAdmin, + WorkflowActor::FarmTeamMember, + WorkflowActor::HubOperator, + WorkflowActor::TraceLead, + WorkflowActor::BuyerSourcingLead, + WorkflowActor::BuyerReceiver, + WorkflowActor::PickupPointCoordinator, + WorkflowActor::RouteCoordinator, + WorkflowActor::RoutePartner, + WorkflowActor::NetworkSteward, +]; + +pub const CANONICAL_VISIBILITY_CLASSES: [VisibilityClass; 9] = [ + VisibilityClass::LocalDraft, + VisibilityClass::FarmPrivate, + VisibilityClass::WorkspacePrivate, + VisibilityClass::NetworkVisible, + VisibilityClass::RouteScoped, + VisibilityClass::BuyerScoped, + VisibilityClass::PublicCommunity, + VisibilityClass::PublicProvenance, + VisibilityClass::SecretNeverShared, +]; + +pub const CANONICAL_AUTHORITY_DOMAINS: [AuthorityDomain; 9] = [ + AuthorityDomain::RelayGroupAccess, + AuthorityDomain::FarmWorkspaceOperations, + AuthorityDomain::BuyerWorkspace, + AuthorityDomain::RouteCoordination, + AuthorityDomain::RouteExecution, + AuthorityDomain::Receipt, + AuthorityDomain::TraceProof, + AuthorityDomain::PublicPublishing, + AuthorityDomain::NetworkStewardship, +]; + +pub const CANONICAL_TODAY_CARD_TYPES: [TodayCardType; 12] = [ + TodayCardType::Route, + TodayCardType::Food, + TodayCardType::Ask, + TodayCardType::Event, + TodayCardType::Place, + TodayCardType::Task, + TodayCardType::Proof, + TodayCardType::Exception, + TodayCardType::Provenance, + TodayCardType::Update, + TodayCardType::AccessMembership, + TodayCardType::SyncOutbox, +]; + +pub const TODAY_CARD_RANKING_PRIORITY: [TodayCardType; 12] = [ + TodayCardType::Exception, + TodayCardType::SyncOutbox, + TodayCardType::Route, + TodayCardType::Proof, + TodayCardType::Food, + TodayCardType::Task, + TodayCardType::Provenance, + TodayCardType::Ask, + TodayCardType::Event, + TodayCardType::Place, + TodayCardType::Update, + TodayCardType::AccessMembership, +]; + +pub const CANONICAL_ADD_ACTION_TYPES: [AddActionType; 18] = [ + AddActionType::Photo, + AddActionType::Note, + AddActionType::Ask, + AddActionType::Scan, + AddActionType::Food, + AddActionType::Harvest, + AddActionType::BuyerRequest, + AddActionType::BuyerCommitment, + AddActionType::RouteNeed, + AddActionType::RouteStop, + AddActionType::PickupEvent, + AddActionType::Place, + AddActionType::Proof, + AddActionType::Exception, + AddActionType::PublicUpdate, + AddActionType::Provenance, + AddActionType::MemberInvite, + AddActionType::Correction, +]; + +pub const CANONICAL_ADD_FLOW_STATES: [AddFlowState; 16] = [ + AddFlowState::NotStarted, + AddFlowState::Draft, + AddFlowState::Editing, + AddFlowState::ValidationFailed, + AddFlowState::ReadyToSubmit, + AddFlowState::Submitted, + AddFlowState::Queued, + AddFlowState::Syncing, + AddFlowState::NeedsApproval, + AddFlowState::Approved, + AddFlowState::Published, + AddFlowState::Shared, + AddFlowState::Confirmed, + AddFlowState::Failed, + AddFlowState::Conflict, + AddFlowState::Discarded, +]; + +pub const CANONICAL_OBJECT_PAGE_FAMILIES: [ObjectPageFamily; 13] = [ + ObjectPageFamily::Network, + ObjectPageFamily::NetworkRoute, + ObjectPageFamily::FarmWorkspace, + ObjectPageFamily::FarmPublicProfile, + ObjectPageFamily::BuyerWorkspace, + ObjectPageFamily::PickupPointPlace, + ObjectPageFamily::Food, + ObjectPageFamily::Event, + ObjectPageFamily::RouteStop, + ObjectPageFamily::Proof, + ObjectPageFamily::BuyerPacket, + ObjectPageFamily::PublicProvenance, + ObjectPageFamily::Exception, +]; + +pub const CANONICAL_OUTBOX_STATES: [OutboxState; 10] = [ + OutboxState::NotQueued, + OutboxState::Draft, + OutboxState::Queued, + OutboxState::Syncing, + OutboxState::AwaitingAuthority, + OutboxState::Published, + OutboxState::Shared, + OutboxState::Failed, + OutboxState::Conflict, + OutboxState::Discarded, +]; + +pub const CANONICAL_SYNC_STATES: [SyncState; 7] = [ + SyncState::Unknown, + SyncState::Online, + SyncState::Offline, + SyncState::Syncing, + SyncState::Synced, + SyncState::Stale, + SyncState::Failed, +]; + +pub const CANONICAL_ROUTE_EXECUTION_FLOW_KINDS: [RouteExecutionFlowKind; 3] = [ + RouteExecutionFlowKind::RoutePartnerAssignedStops, + RouteExecutionFlowKind::BuyerReceiptConfirmation, + RouteExecutionFlowKind::ExceptionRecovery, +]; + +pub const CANONICAL_ROUTE_EXECUTION_STEP_KINDS: [RouteExecutionStepKind; 6] = [ + RouteExecutionStepKind::AssignedRoute, + RouteExecutionStepKind::PickupConfirmation, + RouteExecutionStepKind::DropoffConfirmation, + RouteExecutionStepKind::ReceiptConfirmation, + RouteExecutionStepKind::ExceptionReport, + RouteExecutionStepKind::RecoveryAction, +]; + +pub const CANONICAL_PROOF_PROVENANCE_ARTIFACT_KINDS: [ProofProvenanceArtifactKind; 4] = [ + ProofProvenanceArtifactKind::ProofCompleteness, + ProofProvenanceArtifactKind::BuyerPacketDraft, + ProofProvenanceArtifactKind::BuyerPacketShared, + ProofProvenanceArtifactKind::PublicProvenancePreview, +]; + +pub const CANONICAL_PROOF_PROVENANCE_REVIEW_STATES: [ProofProvenanceReviewState; 8] = [ + ProofProvenanceReviewState::MissingProof, + ProofProvenanceReviewState::Complete, + ProofProvenanceReviewState::Draft, + ProofProvenanceReviewState::ReadyToShare, + ProofProvenanceReviewState::Shared, + ProofProvenanceReviewState::RedactionRequired, + ProofProvenanceReviewState::ReadyToPublish, + ProofProvenanceReviewState::Published, +]; + +pub const CANONICAL_STEWARDSHIP_ACCESS_ITEM_KINDS: [StewardshipAccessItemKind; 9] = [ + StewardshipAccessItemKind::AccessRequestReview, + StewardshipAccessItemKind::RoleApproval, + StewardshipAccessItemKind::RoutePartnerInvite, + StewardshipAccessItemKind::RoutePoolMetadata, + StewardshipAccessItemKind::PublicModeration, + StewardshipAccessItemKind::InviteAcceptance, + StewardshipAccessItemKind::RequestAccess, + StewardshipAccessItemKind::AccessDenied, + StewardshipAccessItemKind::GroupManagementDeferred, +]; + +fn object_ref( + object_type: ObjectKind, + object_id: impl Into<String>, + label: impl Into<String>, +) -> ObjectRef { + ObjectRef { + object_type, + object_id: object_id.into(), + display_label: label.into(), + } +} + +fn context_fixture_parts( + context_type: ContextType, +) -> ( + ObjectKind, + &'static str, + &'static str, + WorkflowActor, + VisibilityClass, +) { + match context_type { + ContextType::Regional => ( + ObjectKind::Region, + "region_floripa", + "Floripa regional food network", + WorkflowActor::NetworkMember, + VisibilityClass::PublicCommunity, + ), + ContextType::Network => ( + ObjectKind::Network, + "network_floripa", + "Floripa local food network", + WorkflowActor::NetworkMember, + VisibilityClass::NetworkVisible, + ), + ContextType::Farm => ( + ObjectKind::Farm, + "farm_floripa_001", + "Floripa Farm", + WorkflowActor::ProducerAdmin, + VisibilityClass::FarmPrivate, + ), + ContextType::Buyer => ( + ObjectKind::BuyerWorkspace, + "buyer_workspace_001", + "Kitchen buyer workspace", + WorkflowActor::BuyerSourcingLead, + VisibilityClass::BuyerScoped, + ), + ContextType::Route => ( + ObjectKind::Route, + "route_thursday_001", + "Thursday network loop", + WorkflowActor::RouteCoordinator, + VisibilityClass::RouteScoped, + ), + ContextType::RoutePartner => ( + ObjectKind::RoutePartner, + "route_partner_001", + "Assigned route partner", + WorkflowActor::RoutePartner, + VisibilityClass::RouteScoped, + ), + ContextType::PickupPoint => ( + ObjectKind::PickupPoint, + "pickup_point_001", + "Neighborhood pickup point", + WorkflowActor::PickupPointCoordinator, + VisibilityClass::NetworkVisible, + ), + ContextType::TraceRecords => ( + ObjectKind::Proof, + "trace_records_001", + "Trace and records", + WorkflowActor::TraceLead, + VisibilityClass::WorkspacePrivate, + ), + ContextType::Hub => ( + ObjectKind::Hub, + "hub_001", + "Floripa hub", + WorkflowActor::HubOperator, + VisibilityClass::WorkspacePrivate, + ), + ContextType::NetworkSteward => ( + ObjectKind::AccessMembership, + "network_stewardship_001", + "Network stewardship", + WorkflowActor::NetworkSteward, + VisibilityClass::WorkspacePrivate, + ), + } +} + +fn context_for_type(context_type: ContextType) -> ActiveContext { + let (object_type, object_id, label, actor, visibility_scope) = + context_fixture_parts(context_type); + ActiveContext { + context_type, + context_ref: object_ref(object_type, object_id, label), + actor, + display_label: label.to_string(), + visibility_scope, + } +} + +fn authority_allowed(actor: WorkflowActor, domain: AuthorityDomain) -> bool { + matches!( + (actor, domain), + ( + WorkflowActor::NetworkMember, + AuthorityDomain::RelayGroupAccess + ) | ( + WorkflowActor::ProducerAdmin, + AuthorityDomain::FarmWorkspaceOperations + ) | (WorkflowActor::ProducerAdmin, AuthorityDomain::TraceProof) + | ( + WorkflowActor::ProducerAdmin, + AuthorityDomain::PublicPublishing + ) + | ( + WorkflowActor::FarmTeamMember, + AuthorityDomain::FarmWorkspaceOperations + ) + | ( + WorkflowActor::HubOperator, + AuthorityDomain::FarmWorkspaceOperations + ) + | (WorkflowActor::HubOperator, AuthorityDomain::RouteExecution) + | (WorkflowActor::TraceLead, AuthorityDomain::TraceProof) + | ( + WorkflowActor::BuyerSourcingLead, + AuthorityDomain::BuyerWorkspace + ) + | (WorkflowActor::BuyerReceiver, AuthorityDomain::Receipt) + | ( + WorkflowActor::PickupPointCoordinator, + AuthorityDomain::Receipt + ) + | ( + WorkflowActor::PickupPointCoordinator, + AuthorityDomain::RouteExecution + ) + | ( + WorkflowActor::RouteCoordinator, + AuthorityDomain::RouteCoordination + ) + | (WorkflowActor::RoutePartner, AuthorityDomain::RouteExecution) + | ( + WorkflowActor::NetworkSteward, + AuthorityDomain::RelayGroupAccess + ) + | ( + WorkflowActor::NetworkSteward, + AuthorityDomain::PublicPublishing + ) + | ( + WorkflowActor::NetworkSteward, + AuthorityDomain::NetworkStewardship + ) + ) +} + +pub fn fixture_authority_gate( + actor: WorkflowActor, + context: ActiveContext, + domain: AuthorityDomain, + action: AuthorityAction, +) -> AuthorityGate { + let is_allowed = authority_allowed(actor, domain); + AuthorityGate { + domain, + action, + actor, + context, + is_required: true, + is_allowed, + reason: if is_allowed { + None + } else { + Some("fixture authority denies this actor/domain pair".to_string()) + }, + } +} + +pub fn fixture_active_contexts() -> Vec<ActiveContext> { + CANONICAL_CONTEXT_TYPES + .into_iter() + .map(context_for_type) + .collect() +} + +fn context_by_object_id(context_id: Option<String>) -> Option<ActiveContext> { + let context_id = context_id?; + fixture_active_contexts() + .into_iter() + .find(|context| context.context_ref.object_id == context_id) +} + +fn card_action_for(card_type: TodayCardType) -> Option<AddActionType> { + match card_type { + TodayCardType::Route => Some(AddActionType::RouteStop), + TodayCardType::Food => Some(AddActionType::Food), + TodayCardType::Ask => Some(AddActionType::Ask), + TodayCardType::Event => Some(AddActionType::PickupEvent), + TodayCardType::Place => Some(AddActionType::Place), + TodayCardType::Task => Some(AddActionType::Note), + TodayCardType::Proof => Some(AddActionType::Proof), + TodayCardType::Exception => Some(AddActionType::Exception), + TodayCardType::Provenance => Some(AddActionType::Provenance), + TodayCardType::Update => Some(AddActionType::PublicUpdate), + TodayCardType::AccessMembership => Some(AddActionType::MemberInvite), + TodayCardType::SyncOutbox => None, + } +} + +fn object_kind_for_card(card_type: TodayCardType) -> ObjectKind { + match card_type { + TodayCardType::Route => ObjectKind::Route, + TodayCardType::Food => ObjectKind::Food, + TodayCardType::Ask => ObjectKind::Ask, + TodayCardType::Event => ObjectKind::Event, + TodayCardType::Place => ObjectKind::Place, + TodayCardType::Task => ObjectKind::Task, + TodayCardType::Proof => ObjectKind::Proof, + TodayCardType::Exception => ObjectKind::Exception, + TodayCardType::Provenance => ObjectKind::Provenance, + TodayCardType::Update => ObjectKind::Update, + TodayCardType::AccessMembership => ObjectKind::AccessMembership, + TodayCardType::SyncOutbox => ObjectKind::OutboxItem, + } +} + +fn ranking_reason_for(card_type: TodayCardType) -> &'static str { + match card_type { + TodayCardType::Exception => "blocking exception", + TodayCardType::SyncOutbox => "required sync action", + TodayCardType::Route => "time-window route operation", + TodayCardType::Proof => "route readiness and proof gap", + TodayCardType::Food => "commitment window", + TodayCardType::Task => "assigned task", + TodayCardType::Provenance => "provenance candidate", + TodayCardType::Ask => "food availability and ask", + TodayCardType::Event => "event window", + TodayCardType::Place => "place context", + TodayCardType::Update => "community update", + TodayCardType::AccessMembership => "network access state", + } +} + +fn ranking_features_for(card_type: TodayCardType) -> Vec<String> { + match card_type { + TodayCardType::Exception => vec!["blocking".to_string(), "recovery".to_string()], + TodayCardType::SyncOutbox => vec!["outbox".to_string(), "retry".to_string()], + TodayCardType::Route => vec!["time_window".to_string(), "route".to_string()], + TodayCardType::Proof => vec!["proof_gap".to_string(), "trace".to_string()], + TodayCardType::Food => vec!["commitment".to_string(), "availability".to_string()], + TodayCardType::Task => vec!["assigned".to_string(), "work".to_string()], + TodayCardType::Provenance => vec!["candidate".to_string(), "public_review".to_string()], + TodayCardType::Ask => vec!["ask".to_string(), "network_need".to_string()], + TodayCardType::Event => vec!["event".to_string(), "calendar".to_string()], + TodayCardType::Place => vec!["place".to_string(), "local_context".to_string()], + TodayCardType::Update => vec!["update".to_string(), "community".to_string()], + TodayCardType::AccessMembership => vec!["access".to_string(), "membership".to_string()], + } +} + +fn status_line_for(card_type: TodayCardType) -> &'static str { + match card_type { + TodayCardType::Exception => "Needs review", + TodayCardType::SyncOutbox => "Retry required", + TodayCardType::Route => "Route window open", + TodayCardType::Proof => "Proof gap detected", + TodayCardType::Food => "Commitment window active", + TodayCardType::Task => "Assigned work ready", + TodayCardType::Provenance => "Candidate ready for review", + TodayCardType::Ask => "Network need available", + TodayCardType::Event => "Upcoming gathering", + TodayCardType::Place => "Place context updated", + TodayCardType::Update => "Community update ready", + TodayCardType::AccessMembership => "Membership state available", + } +} + +fn detail_lines_for(card_type: TodayCardType) -> Vec<String> { + match card_type { + TodayCardType::Exception => vec![ + "Resolve the blocker before related route work continues.".to_string(), + "Recovery path remains scoped to the active context.".to_string(), + ], + TodayCardType::SyncOutbox => { + vec!["Queued work will re-check context, visibility, and authority.".to_string()] + } + TodayCardType::Route => { + vec!["Review stops, timing, proof gaps, and assigned route partner state.".to_string()] + } + TodayCardType::Proof => { + vec!["Trace record needs proof completion before publication.".to_string()] + } + TodayCardType::Food => { + vec!["Food availability is connected to commitments and routes.".to_string()] + } + TodayCardType::Task => vec!["Complete the assigned task from this context.".to_string()], + TodayCardType::Provenance => { + vec!["Public provenance preview requires redaction review.".to_string()] + } + TodayCardType::Ask => vec!["Respond to a scoped network ask.".to_string()], + TodayCardType::Event => vec!["Gathering context is visible to the network.".to_string()], + TodayCardType::Place => { + vec!["Place details are ready for local network review.".to_string()] + } + TodayCardType::Update => vec!["Share a context-aware network update.".to_string()], + TodayCardType::AccessMembership => { + vec!["Review member access for this context.".to_string()] + } + } +} + +pub fn fixture_today_cards(context_id: Option<String>) -> Vec<TodayCard> { + let contexts = fixture_active_contexts(); + let filter_context = context_by_object_id(context_id); + TODAY_CARD_RANKING_PRIORITY + .into_iter() + .enumerate() + .map(|(index, card_type)| { + let context = filter_context + .clone() + .unwrap_or_else(|| contexts[index % contexts.len()].clone()); + let object_kind = object_kind_for_card(card_type); + let object_id = format!("phase1_{:?}_001", object_kind).to_lowercase(); + let object = object_ref(object_kind, object_id, format!("{:?} fixture", card_type)); + let action_type = card_action_for(card_type); + TodayCard { + id: format!("today_{:?}_001", card_type).to_lowercase(), + card_type, + source_object_refs: vec![object.clone()], + source_event_refs: Vec::new(), + primary_context: context.clone(), + actor: context.actor, + visibility: context.visibility_scope, + visibility_label: format!("{:?}", context.visibility_scope), + title: format!("{:?} fixture card", card_type), + status_line: status_line_for(card_type).to_string(), + detail_lines: detail_lines_for(card_type), + pills: vec![ + format!("{:?}", card_type), + ranking_reason_for(card_type).to_string(), + ], + primary_action: TodayCardAction { + id: format!("primary_{:?}", card_type).to_lowercase(), + label: action_type + .map(|action| format!("{:?}", action)) + .unwrap_or_else(|| "Review".to_string()), + action_type, + target_object: Some(object), + }, + secondary_action: None, + ranking_reason: ranking_reason_for(card_type).to_string(), + ranking_features: ranking_features_for(card_type), + sync_state: if matches!(card_type, TodayCardType::SyncOutbox) { + SyncState::Failed + } else { + SyncState::Online + }, + outbox_state: if matches!(card_type, TodayCardType::SyncOutbox) { + OutboxState::Failed + } else { + OutboxState::NotQueued + }, + is_stale: matches!(card_type, TodayCardType::Proof), + is_offline: matches!(card_type, TodayCardType::SyncOutbox), + } + }) + .collect() +} + +fn add_action_object_kind(action_type: AddActionType) -> ObjectKind { + match action_type { + AddActionType::Photo | AddActionType::Note | AddActionType::PublicUpdate => { + ObjectKind::Update + } + AddActionType::Ask | AddActionType::BuyerRequest | AddActionType::RouteNeed => { + ObjectKind::Ask + } + AddActionType::Scan | AddActionType::Proof => ObjectKind::Proof, + AddActionType::Food | AddActionType::Harvest | AddActionType::BuyerCommitment => { + ObjectKind::Food + } + AddActionType::RouteStop | AddActionType::PickupEvent => ObjectKind::RouteStop, + AddActionType::Place => ObjectKind::Place, + AddActionType::Exception => ObjectKind::Exception, + AddActionType::Provenance => ObjectKind::Provenance, + AddActionType::MemberInvite => ObjectKind::AccessMembership, + AddActionType::Correction => ObjectKind::Correction, + } +} + +fn add_action_authority(action_type: AddActionType) -> (AuthorityDomain, AuthorityAction) { + match action_type { + AddActionType::PublicUpdate | AddActionType::Provenance => { + (AuthorityDomain::PublicPublishing, AuthorityAction::Publish) + } + AddActionType::BuyerRequest | AddActionType::BuyerCommitment => { + (AuthorityDomain::BuyerWorkspace, AuthorityAction::Submit) + } + AddActionType::RouteNeed | AddActionType::RouteStop | AddActionType::PickupEvent => { + (AuthorityDomain::RouteCoordination, AuthorityAction::Submit) + } + AddActionType::Proof | AddActionType::Scan => { + (AuthorityDomain::TraceProof, AuthorityAction::Submit) + } + AddActionType::MemberInvite => (AuthorityDomain::RelayGroupAccess, AuthorityAction::Share), + AddActionType::Correction => (AuthorityDomain::TraceProof, AuthorityAction::Correct), + _ => ( + AuthorityDomain::FarmWorkspaceOperations, + AuthorityAction::Submit, + ), + } +} + +fn default_visibility_for_action(action_type: AddActionType) -> VisibilityClass { + match action_type { + AddActionType::PublicUpdate => VisibilityClass::PublicCommunity, + AddActionType::Provenance => VisibilityClass::PublicProvenance, + AddActionType::BuyerRequest | AddActionType::BuyerCommitment => { + VisibilityClass::BuyerScoped + } + AddActionType::RouteNeed | AddActionType::RouteStop | AddActionType::PickupEvent => { + VisibilityClass::RouteScoped + } + AddActionType::Photo | AddActionType::Note | AddActionType::Scan => { + VisibilityClass::LocalDraft + } + _ => VisibilityClass::FarmPrivate, + } +} + +pub fn fixture_add_actions(context_id: Option<String>) -> Vec<AddAction> { + let context = + context_by_object_id(context_id).unwrap_or_else(|| context_for_type(ContextType::Farm)); + CANONICAL_ADD_ACTION_TYPES + .into_iter() + .map(|action_type| { + let (domain, action) = add_action_authority(action_type); + AddAction { + action_type, + display_label: format!("{:?}", action_type), + allowed_context_types: vec![context.context_type], + required_authority: fixture_authority_gate( + context.actor, + context.clone(), + domain, + action, + ), + default_visibility: default_visibility_for_action(action_type), + allowed_visibility_options: vec![ + VisibilityClass::LocalDraft, + default_visibility_for_action(action_type), + ], + created_or_updated_object_type: add_action_object_kind(action_type), + related_object_requirements: vec![RelatedObjectRequirement { + object_type: context.context_ref.object_type, + relationship_label: "primary context".to_string(), + is_required: true, + }], + validation_requirements: vec![ValidationRequirement { + id: "fixture_required_fields".to_string(), + label: "Required fields are present".to_string(), + is_blocking: true, + }], + supports_offline: true, + supports_draft: true, + outbox_behavior: OutboxBehavior::QueueWhenOffline, + primary_submit_label: "Submit".to_string(), + completion_state: AddFlowState::ReadyToSubmit, + } + }) + .collect() +} + +fn object_kind_for_page(family: ObjectPageFamily) -> ObjectKind { + match family { + ObjectPageFamily::Network => ObjectKind::Network, + ObjectPageFamily::NetworkRoute => ObjectKind::Route, + ObjectPageFamily::FarmWorkspace | ObjectPageFamily::FarmPublicProfile => ObjectKind::Farm, + ObjectPageFamily::BuyerWorkspace => ObjectKind::BuyerWorkspace, + ObjectPageFamily::PickupPointPlace => ObjectKind::PickupPoint, + ObjectPageFamily::Food => ObjectKind::Food, + ObjectPageFamily::Event => ObjectKind::Event, + ObjectPageFamily::RouteStop => ObjectKind::RouteStop, + ObjectPageFamily::Proof => ObjectKind::Proof, + ObjectPageFamily::BuyerPacket => ObjectKind::BuyerPacket, + ObjectPageFamily::PublicProvenance => ObjectKind::Provenance, + ObjectPageFamily::Exception => ObjectKind::Exception, + } +} + +pub fn fixture_object_page_summaries(context_id: Option<String>) -> Vec<ObjectPageSummary> { + let context = + context_by_object_id(context_id).unwrap_or_else(|| context_for_type(ContextType::Network)); + CANONICAL_OBJECT_PAGE_FAMILIES + .into_iter() + .map(|family| { + let object_kind = object_kind_for_page(family); + ObjectPageSummary { + object_ref: object_ref( + object_kind, + format!("phase1_{:?}_page_001", family).to_lowercase(), + format!("{:?} fixture page", family), + ), + family, + primary_context: context.clone(), + title: format!("{:?} fixture page", family), + subtitle: Some("fixture-backed object summary".to_string()), + visibility: context.visibility_scope, + visibility_label: format!("{:?}", context.visibility_scope), + required_authority: fixture_authority_gate( + context.actor, + context.clone(), + AuthorityDomain::RelayGroupAccess, + AuthorityAction::NavigateRelatedObject, + ), + sync_state: SyncState::Online, + } + }) + .collect() +} + +fn visibility_allows_search_result(visibility: VisibilityClass) -> bool { + matches!( + visibility, + VisibilityClass::NetworkVisible + | VisibilityClass::PublicCommunity + | VisibilityClass::PublicProvenance + ) +} + +fn object_kind_allows_search_result(object_kind: ObjectKind, visibility: VisibilityClass) -> bool { + match object_kind { + ObjectKind::BuyerPacket | ObjectKind::RouteStop => false, + ObjectKind::Proof => visibility == VisibilityClass::PublicProvenance, + _ => true, + } +} + +pub fn fixture_search_results( + query: Option<String>, + context_id: Option<String>, +) -> Vec<SearchResultSummary> { + let normalized_query = query.unwrap_or_default().trim().to_lowercase(); + fixture_object_page_summaries(context_id) + .into_iter() + .filter(|page| page.required_authority.is_allowed) + .filter(|page| visibility_allows_search_result(page.visibility)) + .filter(|page| { + object_kind_allows_search_result(page.object_ref.object_type, page.visibility) + }) + .filter(|page| { + normalized_query.is_empty() + || page.title.to_lowercase().contains(&normalized_query) + || format!("{:?}", page.family) + .to_lowercase() + .contains(&normalized_query) + }) + .map(|page| SearchResultSummary { + id: format!("search_{}", page.object_ref.object_id), + object_ref: page.object_ref, + primary_context: page.primary_context, + title: page.title, + subtitle: page.subtitle, + visibility: page.visibility, + visibility_label: page.visibility_label, + required_authority: page.required_authority, + sync_state: page.sync_state, + }) + .collect() +} + +struct PrototypePathStepFixture { + id: &'static str, + label: &'static str, + context: ActiveContext, + action_type: Option<AddActionType>, + object_ref: Option<ObjectRef>, + domain: AuthorityDomain, + action: AuthorityAction, + visibility: VisibilityClass, + outbox_state: OutboxState, + sync_state: SyncState, +} + +fn prototype_path_step(fixture: PrototypePathStepFixture) -> PrototypePathStep { + let PrototypePathStepFixture { + id, + label, + context, + action_type, + object_ref, + domain, + action, + visibility, + outbox_state, + sync_state, + } = fixture; + PrototypePathStep { + id: id.to_string(), + label: label.to_string(), + context: context.clone(), + action_type, + object_ref, + authority_gate: fixture_authority_gate(context.actor, context, domain, action), + visibility, + outbox_state, + sync_state, + } +} + +pub fn fixture_prototype_paths() -> Vec<PrototypePath> { + let farm = context_for_type(ContextType::Farm); + let buyer = context_for_type(ContextType::Buyer); + let route = context_for_type(ContextType::Route); + let route_partner = context_for_type(ContextType::RoutePartner); + let food_ref = object_ref(ObjectKind::Food, "food_harvest_001", "Summer squash lot"); + let route_ref = object_ref( + ObjectKind::Route, + "route_thursday_001", + "Thursday network loop", + ); + let buyer_request_ref = object_ref( + ObjectKind::BuyerPacket, + "buyer_commitment_001", + "Kitchen commitment packet", + ); + let exception_ref = object_ref( + ObjectKind::Exception, + "route_blocker_001", + "Missing pickup confirmation", + ); + + vec![ + PrototypePath { + id: "producer_food_to_route".to_string(), + kind: PrototypePathKind::ProducerFoodToRoute, + title: "Producer food to route".to_string(), + actor: farm.actor, + context: farm.clone(), + steps: vec![ + prototype_path_step(PrototypePathStepFixture { + id: "producer_today", + label: "Farm Today", + context: farm.clone(), + action_type: None, + object_ref: Some(farm.context_ref.clone()), + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::Search, + visibility: farm.visibility_scope, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + prototype_path_step(PrototypePathStepFixture { + id: "producer_add_food", + label: "Add Food", + context: farm.clone(), + action_type: Some(AddActionType::Food), + object_ref: Some(food_ref.clone()), + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::Submit, + visibility: VisibilityClass::NetworkVisible, + outbox_state: OutboxState::Draft, + sync_state: SyncState::Offline, + }), + prototype_path_step(PrototypePathStepFixture { + id: "producer_add_to_route", + label: "Add to Route", + context: farm.clone(), + action_type: Some(AddActionType::RouteNeed), + object_ref: Some(route_ref.clone()), + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::Share, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Syncing, + }), + prototype_path_step(PrototypePathStepFixture { + id: "producer_food_page", + label: "Food page", + context: farm.clone(), + action_type: None, + object_ref: Some(food_ref.clone()), + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::NetworkVisible, + outbox_state: OutboxState::Shared, + sync_state: SyncState::Synced, + }), + prototype_path_step(PrototypePathStepFixture { + id: "producer_route_page", + label: "Route page", + context: route.clone(), + action_type: None, + object_ref: Some(route_ref.clone()), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + ], + }, + PrototypePath { + id: "buyer_commitment_to_route".to_string(), + kind: PrototypePathKind::BuyerCommitmentToRoute, + title: "Buyer commitment to route".to_string(), + actor: buyer.actor, + context: buyer.clone(), + steps: vec![ + prototype_path_step(PrototypePathStepFixture { + id: "buyer_today", + label: "Buyer Today", + context: buyer.clone(), + action_type: None, + object_ref: Some(buyer.context_ref.clone()), + domain: AuthorityDomain::BuyerWorkspace, + action: AuthorityAction::Search, + visibility: buyer.visibility_scope, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + prototype_path_step(PrototypePathStepFixture { + id: "buyer_request", + label: "Add Buyer Request", + context: buyer.clone(), + action_type: Some(AddActionType::BuyerRequest), + object_ref: Some(buyer_request_ref.clone()), + domain: AuthorityDomain::BuyerWorkspace, + action: AuthorityAction::Submit, + visibility: VisibilityClass::BuyerScoped, + outbox_state: OutboxState::Draft, + sync_state: SyncState::Offline, + }), + prototype_path_step(PrototypePathStepFixture { + id: "buyer_commitment", + label: "Confirm Commitment", + context: buyer.clone(), + action_type: Some(AddActionType::BuyerCommitment), + object_ref: Some(buyer_request_ref), + domain: AuthorityDomain::BuyerWorkspace, + action: AuthorityAction::Approve, + visibility: VisibilityClass::BuyerScoped, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Syncing, + }), + prototype_path_step(PrototypePathStepFixture { + id: "buyer_route", + label: "Route", + context: route.clone(), + action_type: None, + object_ref: Some(route_ref.clone()), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::Shared, + sync_state: SyncState::Synced, + }), + ], + }, + PrototypePath { + id: "route_coordinator_assignment".to_string(), + kind: PrototypePathKind::RouteCoordinatorAssignment, + title: "Route coordinator assignment".to_string(), + actor: route.actor, + context: route.clone(), + steps: vec![ + prototype_path_step(PrototypePathStepFixture { + id: "route_today", + label: "Route Today", + context: route.clone(), + action_type: None, + object_ref: Some(route_ref.clone()), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::Search, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + prototype_path_step(PrototypePathStepFixture { + id: "route_page", + label: "Route page", + context: route.clone(), + action_type: None, + object_ref: Some(route_ref), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + prototype_path_step(PrototypePathStepFixture { + id: "route_resolve_blocker", + label: "Resolve blocker", + context: route.clone(), + action_type: Some(AddActionType::Exception), + object_ref: Some(exception_ref), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::Close, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::Conflict, + sync_state: SyncState::Failed, + }), + prototype_path_step(PrototypePathStepFixture { + id: "route_assign_partner", + label: "Assign RoutePartner", + context: route, + action_type: Some(AddActionType::RouteNeed), + object_ref: Some(route_partner.context_ref.clone()), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::Assign, + visibility: VisibilityClass::RouteScoped, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Syncing, + }), + ], + }, + ] +} + +struct RouteExecutionStepFixture { + id: &'static str, + kind: RouteExecutionStepKind, + label: &'static str, + actor: WorkflowActor, + context: ActiveContext, + object_ref: Option<ObjectRef>, + domain: AuthorityDomain, + action: AuthorityAction, + visibility: VisibilityClass, + supports_offline: bool, + supports_partial_receipt: bool, + uses_receipt_token: bool, + outbox_state: OutboxState, + sync_state: SyncState, + detail_lines: Vec<&'static str>, +} + +fn route_execution_step( + route_ref: ObjectRef, + fixture: RouteExecutionStepFixture, +) -> RouteExecutionStep { + RouteExecutionStep { + id: fixture.id.to_string(), + kind: fixture.kind, + label: fixture.label.to_string(), + actor: fixture.actor, + context: fixture.context.clone(), + route_ref, + object_ref: fixture.object_ref, + required_authority: fixture_authority_gate( + fixture.actor, + fixture.context, + fixture.domain, + fixture.action, + ), + visibility: fixture.visibility, + supports_offline: fixture.supports_offline, + supports_partial_receipt: fixture.supports_partial_receipt, + uses_receipt_token: fixture.uses_receipt_token, + outbox_state: fixture.outbox_state, + sync_state: fixture.sync_state, + detail_lines: fixture + .detail_lines + .into_iter() + .map(str::to_string) + .collect(), + } +} + +fn all_route_execution_flows() -> Vec<RouteExecutionFlow> { + let route = context_for_type(ContextType::Route); + let route_partner = context_for_type(ContextType::RoutePartner); + let buyer_receiver = ActiveContext { + context_type: ContextType::Buyer, + context_ref: object_ref( + ObjectKind::BuyerWorkspace, + "buyer_receiver_workspace_001", + "Kitchen receiving workspace", + ), + actor: WorkflowActor::BuyerReceiver, + display_label: "Kitchen receiving workspace".to_string(), + visibility_scope: VisibilityClass::BuyerScoped, + }; + let route_ref = object_ref( + ObjectKind::Route, + "route_thursday_001", + "Thursday network loop", + ); + let stop_pickup_ref = object_ref( + ObjectKind::RouteStop, + "route_stop_pickup_001", + "Floripa Farm pickup", + ); + let stop_dropoff_ref = object_ref( + ObjectKind::RouteStop, + "route_stop_dropoff_001", + "Kitchen drop-off", + ); + let pickup_proof_ref = object_ref( + ObjectKind::Proof, + "proof_pickup_001", + "Pickup confirmation proof", + ); + let dropoff_proof_ref = object_ref( + ObjectKind::Proof, + "proof_dropoff_001", + "Drop-off confirmation proof", + ); + let receipt_ref = object_ref( + ObjectKind::Proof, + "receipt_kitchen_001", + "Kitchen receipt confirmation", + ); + let exception_ref = object_ref( + ObjectKind::Exception, + "exception_short_case_001", + "Short case divergence", + ); + + vec![ + RouteExecutionFlow { + id: "route_partner_assigned_stops".to_string(), + kind: RouteExecutionFlowKind::RoutePartnerAssignedStops, + title: "Assigned route stops".to_string(), + actor: WorkflowActor::RoutePartner, + context: route_partner.clone(), + route_ref: route_ref.clone(), + steps: vec![ + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "assigned_route", + kind: RouteExecutionStepKind::AssignedRoute, + label: "Assigned route", + actor: WorkflowActor::RoutePartner, + context: route_partner.clone(), + object_ref: Some(route_ref.clone()), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::Search, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + detail_lines: vec![ + "RoutePartner sees the assigned route and assigned stops only.", + "Buyer packet and private buyer workspace data are not exposed.", + ], + }, + ), + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "pickup_confirmation", + kind: RouteExecutionStepKind::PickupConfirmation, + label: "Confirm pickup", + actor: WorkflowActor::RoutePartner, + context: route_partner.clone(), + object_ref: Some(pickup_proof_ref), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::Submit, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Offline, + detail_lines: vec![ + "Photo, note, scan, or signature proof can queue offline.", + "The stop remains scoped to the assigned route.", + ], + }, + ), + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "dropoff_confirmation", + kind: RouteExecutionStepKind::DropoffConfirmation, + label: "Confirm drop-off", + actor: WorkflowActor::RoutePartner, + context: route_partner, + object_ref: Some(dropoff_proof_ref), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::Submit, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::Syncing, + sync_state: SyncState::Syncing, + detail_lines: vec![ + "Drop-off proof syncs when relay connectivity returns.", + "Receipt confirmation remains separate from route execution.", + ], + }, + ), + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "assigned_pickup_stop", + kind: RouteExecutionStepKind::AssignedRoute, + label: "Pickup stop", + actor: WorkflowActor::RoutePartner, + context: context_for_type(ContextType::RoutePartner), + object_ref: Some(stop_pickup_ref), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Synced, + detail_lines: vec!["Assigned stop detail is available offline."], + }, + ), + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "assigned_dropoff_stop", + kind: RouteExecutionStepKind::AssignedRoute, + label: "Drop-off stop", + actor: WorkflowActor::RoutePartner, + context: context_for_type(ContextType::RoutePartner), + object_ref: Some(stop_dropoff_ref), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::NavigateRelatedObject, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Synced, + detail_lines: vec!["Assigned stop detail is available offline."], + }, + ), + ], + }, + RouteExecutionFlow { + id: "buyer_receipt_confirmation".to_string(), + kind: RouteExecutionFlowKind::BuyerReceiptConfirmation, + title: "Buyer receipt confirmation".to_string(), + actor: WorkflowActor::BuyerReceiver, + context: buyer_receiver.clone(), + route_ref: route_ref.clone(), + steps: vec![route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "receiver_receipt", + kind: RouteExecutionStepKind::ReceiptConfirmation, + label: "Confirm full or partial receipt", + actor: WorkflowActor::BuyerReceiver, + context: buyer_receiver, + object_ref: Some(receipt_ref), + domain: AuthorityDomain::Receipt, + action: AuthorityAction::Submit, + visibility: VisibilityClass::BuyerScoped, + supports_offline: true, + supports_partial_receipt: true, + uses_receipt_token: true, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Offline, + detail_lines: vec![ + "BuyerReceiver can confirm full or partial receipt.", + "A scoped receipt token can be used without exposing buyer workspace data.", + ], + }, + )], + }, + RouteExecutionFlow { + id: "route_exception_recovery".to_string(), + kind: RouteExecutionFlowKind::ExceptionRecovery, + title: "Exception recovery".to_string(), + actor: WorkflowActor::RoutePartner, + context: context_for_type(ContextType::RoutePartner), + route_ref: route_ref.clone(), + steps: vec![ + route_execution_step( + route_ref.clone(), + RouteExecutionStepFixture { + id: "report_exception", + kind: RouteExecutionStepKind::ExceptionReport, + label: "Report divergence", + actor: WorkflowActor::RoutePartner, + context: context_for_type(ContextType::RoutePartner), + object_ref: Some(exception_ref.clone()), + domain: AuthorityDomain::RouteExecution, + action: AuthorityAction::Submit, + visibility: VisibilityClass::RouteScoped, + supports_offline: true, + supports_partial_receipt: false, + uses_receipt_token: false, + outbox_state: OutboxState::Conflict, + sync_state: SyncState::Failed, + detail_lines: vec![ + "Short, damaged, late, or missing-item divergence becomes an exception card.", + "The exception stays route-scoped until resolved or escalated.", + ], + }, + ), + route_execution_step( + route_ref, + RouteExecutionStepFixture { + id: "resolve_exception", + kind: RouteExecutionStepKind::RecoveryAction, + label: "Resolve recovery path", + actor: WorkflowActor::RouteCoordinator, + context: route, + object_ref: Some(exception_ref), + domain: AuthorityDomain::RouteCoordination, + action: AuthorityAction::Close, + visibility: VisibilityClass::RouteScoped, + supports_offline: false, + supports_partial_receipt: true, + uses_receipt_token: false, + outbox_state: OutboxState::AwaitingAuthority, + sync_state: SyncState::Online, + detail_lines: vec![ + "RouteCoordinator chooses correction, partial receipt, replacement, or closure.", + "Recovery keeps route execution, receipt, and buyer data boundaries separate.", + ], + }, + ), + ], + }, + ] +} + +pub fn fixture_route_execution_flows(context_id: Option<String>) -> Vec<RouteExecutionFlow> { + let Some(context_id) = context_id else { + return all_route_execution_flows(); + }; + let matching: Vec<RouteExecutionFlow> = all_route_execution_flows() + .into_iter() + .filter(|flow| { + flow.context.context_ref.object_id == context_id + || flow + .steps + .iter() + .any(|step| step.context.context_ref.object_id == context_id) + }) + .collect(); + if matching.is_empty() { + all_route_execution_flows() + } else { + matching + } +} + +struct ProofProvenanceArtifactFixture { + id: &'static str, + kind: ProofProvenanceArtifactKind, + review_state: ProofProvenanceReviewState, + title: &'static str, + actor: WorkflowActor, + context: ActiveContext, + object_ref: ObjectRef, + source_object_refs: Vec<ObjectRef>, + domain: AuthorityDomain, + action: AuthorityAction, + visibility: VisibilityClass, + is_public_preview: bool, + requires_redaction_review: bool, + can_publish: bool, + public_summary_lines: Vec<&'static str>, + redacted_field_labels: Vec<&'static str>, + outbox_state: OutboxState, + sync_state: SyncState, +} + +fn proof_provenance_artifact(fixture: ProofProvenanceArtifactFixture) -> ProofProvenanceArtifact { + ProofProvenanceArtifact { + id: fixture.id.to_string(), + kind: fixture.kind, + review_state: fixture.review_state, + title: fixture.title.to_string(), + actor: fixture.actor, + context: fixture.context.clone(), + object_ref: fixture.object_ref, + source_object_refs: fixture.source_object_refs, + required_authority: fixture_authority_gate( + fixture.actor, + fixture.context, + fixture.domain, + fixture.action, + ), + visibility: fixture.visibility, + is_public_preview: fixture.is_public_preview, + requires_redaction_review: fixture.requires_redaction_review, + can_publish: fixture.can_publish, + public_summary_lines: fixture + .public_summary_lines + .into_iter() + .map(str::to_string) + .collect(), + redacted_field_labels: fixture + .redacted_field_labels + .into_iter() + .map(str::to_string) + .collect(), + outbox_state: fixture.outbox_state, + sync_state: fixture.sync_state, + } +} + +fn private_provenance_redaction_labels() -> Vec<&'static str> { + vec![ + "private trace JSON", + "private buyer details", + "private evidence", + "private route stops", + "worker notes", + ] +} + +fn all_proof_provenance_artifacts() -> Vec<ProofProvenanceArtifact> { + let trace = context_for_type(ContextType::TraceRecords); + let farm = context_for_type(ContextType::Farm); + let buyer = context_for_type(ContextType::Buyer); + let proof_ref = object_ref( + ObjectKind::Proof, + "proof_route_loop_001", + "Route loop proof set", + ); + let producer_proof_ref = object_ref( + ObjectKind::Proof, + "proof_farm_lot_001", + "Farm lot proof set", + ); + let buyer_packet_ref = object_ref( + ObjectKind::BuyerPacket, + "buyer_packet_kitchen_001", + "Kitchen buyer packet", + ); + let public_provenance_ref = object_ref( + ObjectKind::Provenance, + "public_provenance_squash_001", + "Summer squash provenance preview", + ); + let food_ref = object_ref(ObjectKind::Food, "food_harvest_001", "Summer squash lot"); + let route_ref = object_ref( + ObjectKind::Route, + "route_thursday_001", + "Thursday network loop", + ); + let receipt_ref = object_ref( + ObjectKind::Proof, + "receipt_kitchen_001", + "Kitchen receipt confirmation", + ); + + vec![ + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "trace_proof_completeness", + kind: ProofProvenanceArtifactKind::ProofCompleteness, + review_state: ProofProvenanceReviewState::MissingProof, + title: "Trace proof completeness", + actor: WorkflowActor::TraceLead, + context: trace.clone(), + object_ref: proof_ref.clone(), + source_object_refs: vec![route_ref.clone(), receipt_ref.clone()], + domain: AuthorityDomain::TraceProof, + action: AuthorityAction::Approve, + visibility: VisibilityClass::WorkspacePrivate, + is_public_preview: false, + requires_redaction_review: false, + can_publish: false, + public_summary_lines: vec![ + "Internal proof set needs one receipt confirmation before publication review.", + ], + redacted_field_labels: Vec::new(), + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + }), + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "producer_proof_completeness", + kind: ProofProvenanceArtifactKind::ProofCompleteness, + review_state: ProofProvenanceReviewState::Complete, + title: "Producer proof completeness", + actor: WorkflowActor::ProducerAdmin, + context: farm.clone(), + object_ref: producer_proof_ref.clone(), + source_object_refs: vec![food_ref.clone(), route_ref.clone()], + domain: AuthorityDomain::TraceProof, + action: AuthorityAction::Approve, + visibility: VisibilityClass::FarmPrivate, + is_public_preview: false, + requires_redaction_review: false, + can_publish: false, + public_summary_lines: vec![ + "Authorized producer review confirms farm lot proof completeness.", + ], + redacted_field_labels: Vec::new(), + outbox_state: OutboxState::Shared, + sync_state: SyncState::Synced, + }), + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "buyer_packet_draft", + kind: ProofProvenanceArtifactKind::BuyerPacketDraft, + review_state: ProofProvenanceReviewState::Draft, + title: "Buyer packet draft", + actor: WorkflowActor::BuyerSourcingLead, + context: buyer.clone(), + object_ref: buyer_packet_ref.clone(), + source_object_refs: vec![food_ref.clone(), receipt_ref.clone()], + domain: AuthorityDomain::BuyerWorkspace, + action: AuthorityAction::Submit, + visibility: VisibilityClass::BuyerScoped, + is_public_preview: false, + requires_redaction_review: false, + can_publish: false, + public_summary_lines: vec!["Buyer packet draft is scoped to the buyer workspace."], + redacted_field_labels: Vec::new(), + outbox_state: OutboxState::Draft, + sync_state: SyncState::Offline, + }), + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "buyer_packet_shared", + kind: ProofProvenanceArtifactKind::BuyerPacketShared, + review_state: ProofProvenanceReviewState::Shared, + title: "Buyer packet shared", + actor: WorkflowActor::BuyerSourcingLead, + context: buyer, + object_ref: buyer_packet_ref, + source_object_refs: vec![producer_proof_ref.clone(), receipt_ref.clone()], + domain: AuthorityDomain::BuyerWorkspace, + action: AuthorityAction::Share, + visibility: VisibilityClass::BuyerScoped, + is_public_preview: false, + requires_redaction_review: false, + can_publish: false, + public_summary_lines: vec!["Buyer packet has been shared with authorized receivers."], + redacted_field_labels: Vec::new(), + outbox_state: OutboxState::Shared, + sync_state: SyncState::Synced, + }), + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "public_provenance_redaction_review", + kind: ProofProvenanceArtifactKind::PublicProvenancePreview, + review_state: ProofProvenanceReviewState::RedactionRequired, + title: "Public provenance redaction review", + actor: WorkflowActor::ProducerAdmin, + context: farm.clone(), + object_ref: public_provenance_ref.clone(), + source_object_refs: vec![food_ref.clone(), producer_proof_ref.clone()], + domain: AuthorityDomain::PublicPublishing, + action: AuthorityAction::Publish, + visibility: VisibilityClass::PublicProvenance, + is_public_preview: true, + requires_redaction_review: true, + can_publish: false, + public_summary_lines: vec![ + "Summer squash was grown by Floripa Farm for the Thursday network loop.", + "Public preview includes farm, food, harvest window, and network-level route summary.", + ], + redacted_field_labels: private_provenance_redaction_labels(), + outbox_state: OutboxState::AwaitingAuthority, + sync_state: SyncState::Online, + }), + proof_provenance_artifact(ProofProvenanceArtifactFixture { + id: "public_provenance_ready", + kind: ProofProvenanceArtifactKind::PublicProvenancePreview, + review_state: ProofProvenanceReviewState::ReadyToPublish, + title: "Public provenance ready", + actor: WorkflowActor::ProducerAdmin, + context: farm, + object_ref: public_provenance_ref, + source_object_refs: vec![food_ref, producer_proof_ref], + domain: AuthorityDomain::PublicPublishing, + action: AuthorityAction::Publish, + visibility: VisibilityClass::PublicProvenance, + is_public_preview: true, + requires_redaction_review: false, + can_publish: true, + public_summary_lines: vec![ + "Summer squash provenance is ready for public community publication.", + "Preview includes only redacted farm, food, harvest window, and network summary fields.", + ], + redacted_field_labels: private_provenance_redaction_labels(), + outbox_state: OutboxState::Queued, + sync_state: SyncState::Syncing, + }), + ] +} + +pub fn fixture_proof_provenance_artifacts( + context_id: Option<String>, +) -> Vec<ProofProvenanceArtifact> { + let Some(context_id) = context_id else { + return all_proof_provenance_artifacts(); + }; + let matching: Vec<ProofProvenanceArtifact> = all_proof_provenance_artifacts() + .into_iter() + .filter(|artifact| artifact.context.context_ref.object_id == context_id) + .collect(); + if matching.is_empty() { + all_proof_provenance_artifacts() + } else { + matching + } +} + +struct StewardshipAccessItemFixture { + id: &'static str, + kind: StewardshipAccessItemKind, + title: &'static str, + actor: WorkflowActor, + context: ActiveContext, + target_ref: ObjectRef, + domain: AuthorityDomain, + action: AuthorityAction, + visibility: VisibilityClass, + is_admin_lite: bool, + is_phase_2_deferred: bool, + grants_private_access: bool, + outbox_state: OutboxState, + sync_state: SyncState, + detail_lines: Vec<&'static str>, +} + +fn stewardship_access_item(fixture: StewardshipAccessItemFixture) -> StewardshipAccessItem { + StewardshipAccessItem { + id: fixture.id.to_string(), + kind: fixture.kind, + title: fixture.title.to_string(), + actor: fixture.actor, + context: fixture.context.clone(), + target_ref: fixture.target_ref, + required_authority: fixture_authority_gate( + fixture.actor, + fixture.context, + fixture.domain, + fixture.action, + ), + visibility: fixture.visibility, + is_admin_lite: fixture.is_admin_lite, + is_phase_2_deferred: fixture.is_phase_2_deferred, + grants_private_access: fixture.grants_private_access, + outbox_state: fixture.outbox_state, + sync_state: fixture.sync_state, + detail_lines: fixture + .detail_lines + .into_iter() + .map(str::to_string) + .collect(), + } +} + +fn all_stewardship_access_items() -> Vec<StewardshipAccessItem> { + let steward = context_for_type(ContextType::NetworkSteward); + let network = context_for_type(ContextType::Network); + let route = context_for_type(ContextType::Route); + let member = context_for_type(ContextType::Regional); + let access_request_ref = object_ref( + ObjectKind::AccessMembership, + "access_request_farm_team_001", + "Farm team access request", + ); + let role_ref = object_ref( + ObjectKind::AccessMembership, + "role_route_partner_candidate_001", + "Route partner candidate role", + ); + let route_partner_ref = object_ref( + ObjectKind::RoutePartner, + "route_partner_invite_001", + "Thursday route partner invite", + ); + let route_pool_ref = object_ref( + ObjectKind::Route, + "route_pool_metadata_001", + "Route pool metadata", + ); + let public_update_ref = object_ref( + ObjectKind::Update, + "community_update_review_001", + "Community update moderation", + ); + let invite_ref = object_ref( + ObjectKind::MemberInvite, + "member_invite_001", + "Network invite", + ); + let request_ref = object_ref( + ObjectKind::AccessMembership, + "access_request_self_001", + "Request network access", + ); + let denied_ref = object_ref( + ObjectKind::Farm, + "private_farm_denied_001", + "Private farm context", + ); + let group_ref = object_ref( + ObjectKind::AccessMembership, + "phase2_group_management_001", + "Group management", + ); + + vec![ + stewardship_access_item(StewardshipAccessItemFixture { + id: "steward_review_access_request", + kind: StewardshipAccessItemKind::AccessRequestReview, + title: "Review access request", + actor: WorkflowActor::NetworkSteward, + context: steward.clone(), + target_ref: access_request_ref, + domain: AuthorityDomain::RelayGroupAccess, + action: AuthorityAction::Approve, + visibility: VisibilityClass::WorkspacePrivate, + is_admin_lite: true, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Online, + detail_lines: vec![ + "NetworkSteward reviews scoped membership requests.", + "Approval grants role context, not private workspace access.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "steward_approve_role", + kind: StewardshipAccessItemKind::RoleApproval, + title: "Approve role", + actor: WorkflowActor::NetworkSteward, + context: steward.clone(), + target_ref: role_ref, + domain: AuthorityDomain::RelayGroupAccess, + action: AuthorityAction::Approve, + visibility: VisibilityClass::WorkspacePrivate, + is_admin_lite: true, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Shared, + sync_state: SyncState::Synced, + detail_lines: vec![ + "Role approval remains constrained to the requested context.", + "Private farm, buyer, route, proof, and trace data require their own authorities.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "steward_invite_route_partner", + kind: StewardshipAccessItemKind::RoutePartnerInvite, + title: "Invite RoutePartner", + actor: WorkflowActor::NetworkSteward, + context: steward.clone(), + target_ref: route_partner_ref, + domain: AuthorityDomain::RelayGroupAccess, + action: AuthorityAction::Share, + visibility: VisibilityClass::NetworkVisible, + is_admin_lite: true, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Syncing, + detail_lines: vec![ + "RoutePartner invite can be issued without route stop details.", + "Assignment still belongs to route coordination.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "steward_route_pool_metadata", + kind: StewardshipAccessItemKind::RoutePoolMetadata, + title: "Set route pool metadata", + actor: WorkflowActor::NetworkSteward, + context: steward.clone(), + target_ref: route_pool_ref, + domain: AuthorityDomain::NetworkStewardship, + action: AuthorityAction::Assign, + visibility: VisibilityClass::NetworkVisible, + is_admin_lite: true, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Draft, + sync_state: SyncState::Offline, + detail_lines: vec![ + "Stewardship metadata describes route pool availability.", + "Concrete route assignment remains route-coordinator authority.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "steward_public_moderation", + kind: StewardshipAccessItemKind::PublicModeration, + title: "Moderate public/community state", + actor: WorkflowActor::NetworkSteward, + context: steward.clone(), + target_ref: public_update_ref, + domain: AuthorityDomain::PublicPublishing, + action: AuthorityAction::Correct, + visibility: VisibilityClass::PublicCommunity, + is_admin_lite: true, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::AwaitingAuthority, + sync_state: SyncState::Online, + detail_lines: vec![ + "Public/community moderation is allowed where publishing authority permits it.", + "Moderation never exposes private proof, buyer, farm, or route-stop data.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "member_accept_invite", + kind: StewardshipAccessItemKind::InviteAcceptance, + title: "Accept invite", + actor: WorkflowActor::NetworkMember, + context: network.clone(), + target_ref: invite_ref, + domain: AuthorityDomain::RelayGroupAccess, + action: AuthorityAction::Submit, + visibility: VisibilityClass::NetworkVisible, + is_admin_lite: false, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Queued, + sync_state: SyncState::Online, + detail_lines: vec![ + "Invite acceptance connects membership without full group management.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "member_request_access", + kind: StewardshipAccessItemKind::RequestAccess, + title: "Request access", + actor: WorkflowActor::NetworkMember, + context: member, + target_ref: request_ref, + domain: AuthorityDomain::RelayGroupAccess, + action: AuthorityAction::Submit, + visibility: VisibilityClass::NetworkVisible, + is_admin_lite: false, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::Draft, + sync_state: SyncState::Offline, + detail_lines: vec!["Access requests are queued as explicit membership work."], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "member_access_denied", + kind: StewardshipAccessItemKind::AccessDenied, + title: "Access denied", + actor: WorkflowActor::NetworkMember, + context: network, + target_ref: denied_ref, + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::Search, + visibility: VisibilityClass::FarmPrivate, + is_admin_lite: false, + is_phase_2_deferred: false, + grants_private_access: false, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Online, + detail_lines: vec![ + "Denied state preserves the blocked context label without revealing private data.", + ], + }), + stewardship_access_item(StewardshipAccessItemFixture { + id: "phase2_group_management_deferred", + kind: StewardshipAccessItemKind::GroupManagementDeferred, + title: "Group management deferred", + actor: WorkflowActor::NetworkSteward, + context: route, + target_ref: group_ref, + domain: AuthorityDomain::NetworkStewardship, + action: AuthorityAction::Approve, + visibility: VisibilityClass::WorkspacePrivate, + is_admin_lite: true, + is_phase_2_deferred: true, + grants_private_access: false, + outbox_state: OutboxState::NotQueued, + sync_state: SyncState::Unknown, + detail_lines: vec![ + "Full group creation and management are explicitly deferred to Phase 2.", + ], + }), + ] +} + +pub fn fixture_stewardship_access_items(context_id: Option<String>) -> Vec<StewardshipAccessItem> { + let Some(context_id) = context_id else { + return all_stewardship_access_items(); + }; + let matching: Vec<StewardshipAccessItem> = all_stewardship_access_items() + .into_iter() + .filter(|item| item.context.context_ref.object_id == context_id) + .collect(); + if matching.is_empty() { + all_stewardship_access_items() + } else { + matching + } +} + +pub fn fixture_outbox_items() -> Vec<OutboxItem> { + let context = context_for_type(ContextType::Farm); + CANONICAL_OUTBOX_STATES + .into_iter() + .enumerate() + .map(|(index, outbox_state)| OutboxItem { + id: format!("outbox_fixture_{index:02}"), + action_type: AddActionType::PublicUpdate, + context: context.clone(), + object_refs: vec![object_ref( + ObjectKind::Update, + format!("draft_update_{index:02}"), + "Public update draft", + )], + event_refs: Vec::new(), + visibility: VisibilityClass::PublicCommunity, + authority_gate: fixture_authority_gate( + context.actor, + context.clone(), + AuthorityDomain::PublicPublishing, + AuthorityAction::Retry, + ), + flow_state: if matches!(outbox_state, OutboxState::Draft) { + AddFlowState::Draft + } else { + AddFlowState::Queued + }, + outbox_state, + sync_state: CANONICAL_SYNC_STATES[index % CANONICAL_SYNC_STATES.len()], + queued_at_unix: Some(1_799_971_200 + index as u64), + last_attempt_at_unix: None, + retry_count: index as u32, + last_error: if matches!(outbox_state, OutboxState::Failed) { + Some("fixture failure".to_string()) + } else { + None + }, + }) + .collect() +} + +fn outbox_state_allows_retry(state: OutboxState) -> bool { + matches!(state, OutboxState::Failed | OutboxState::Conflict) +} + +fn outbox_visibility_allows_retry(visibility: VisibilityClass) -> bool { + !matches!( + visibility, + VisibilityClass::LocalDraft | VisibilityClass::SecretNeverShared + ) +} + +pub fn fixture_outbox_retry_decision(item: OutboxItem) -> OutboxRetryDecision { + let authority_gate = fixture_authority_gate( + item.context.actor, + item.context.clone(), + item.authority_gate.domain, + AuthorityAction::Retry, + ); + let state_allows_retry = outbox_state_allows_retry(item.outbox_state); + let visibility_allows_retry = outbox_visibility_allows_retry(item.visibility); + let is_retryable = state_allows_retry && visibility_allows_retry && authority_gate.is_allowed; + let reason = if is_retryable { + None + } else if !state_allows_retry { + Some(format!( + "{:?} is not a retryable outbox state", + item.outbox_state + )) + } else if !visibility_allows_retry { + Some(format!( + "{:?} visibility cannot be retried", + item.visibility + )) + } else { + authority_gate.reason.clone() + }; + + OutboxRetryDecision { + item_id: item.id, + is_retryable, + authority_gate, + reason, + } +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +impl RadrootsRuntime { + pub fn phase1_active_contexts(&self) -> Vec<ActiveContext> { + let _ = self; + fixture_active_contexts() + } + + pub fn phase1_today_cards(&self, context_id: Option<String>) -> Vec<TodayCard> { + let _ = self; + fixture_today_cards(context_id) + } + + pub fn phase1_add_actions(&self, context_id: Option<String>) -> Vec<AddAction> { + let _ = self; + fixture_add_actions(context_id) + } + + pub fn phase1_object_page_summaries( + &self, + context_id: Option<String>, + ) -> Vec<ObjectPageSummary> { + let _ = self; + fixture_object_page_summaries(context_id) + } + + pub fn phase1_outbox_snapshot(&self) -> Vec<OutboxItem> { + let _ = self; + fixture_outbox_items() + } + + pub fn phase1_search_results( + &self, + query: Option<String>, + context_id: Option<String>, + ) -> Vec<SearchResultSummary> { + let _ = self; + fixture_search_results(query, context_id) + } + + pub fn phase1_prototype_paths(&self) -> Vec<PrototypePath> { + let _ = self; + fixture_prototype_paths() + } + + pub fn phase1_route_execution_flows( + &self, + context_id: Option<String>, + ) -> Vec<RouteExecutionFlow> { + let _ = self; + fixture_route_execution_flows(context_id) + } + + pub fn phase1_proof_provenance_artifacts( + &self, + context_id: Option<String>, + ) -> Vec<ProofProvenanceArtifact> { + let _ = self; + fixture_proof_provenance_artifacts(context_id) + } + + pub fn phase1_stewardship_access_items( + &self, + context_id: Option<String>, + ) -> Vec<StewardshipAccessItem> { + let _ = self; + fixture_stewardship_access_items(context_id) + } + + pub fn phase1_outbox_retry_decision(&self, item: OutboxItem) -> OutboxRetryDecision { + let _ = self; + fixture_outbox_retry_decision(item) + } + + pub fn phase1_check_authority( + &self, + actor: WorkflowActor, + context: ActiveContext, + domain: AuthorityDomain, + action: AuthorityAction, + ) -> AuthorityGate { + let _ = self; + fixture_authority_gate(actor, context, domain, action) + } +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::*; + + fn object_ref(object_type: ObjectKind, object_id: &str, display_label: &str) -> ObjectRef { + ObjectRef { + object_type, + object_id: object_id.to_string(), + display_label: display_label.to_string(), + } + } + + fn active_context() -> ActiveContext { + ActiveContext { + context_type: ContextType::Farm, + context_ref: object_ref(ObjectKind::Farm, "farm_123", "Root & Rad Farm"), + actor: WorkflowActor::ProducerAdmin, + display_label: "Root & Rad Farm".to_string(), + visibility_scope: VisibilityClass::FarmPrivate, + } + } + + fn authority_gate() -> AuthorityGate { + AuthorityGate { + domain: AuthorityDomain::FarmWorkspaceOperations, + action: AuthorityAction::Submit, + actor: WorkflowActor::ProducerAdmin, + context: active_context(), + is_required: true, + is_allowed: true, + reason: None, + } + } + + #[test] + fn runtime_wrappers_expose_the_complete_phase_1_surface() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let contexts = runtime.phase1_active_contexts(); + let context = contexts.first().expect("context").clone(); + let context_id = Some(context.context_ref.object_id.clone()); + + assert!(!runtime.phase1_today_cards(context_id.clone()).is_empty()); + assert!(!runtime.phase1_add_actions(context_id.clone()).is_empty()); + assert!( + !runtime + .phase1_object_page_summaries(context_id.clone()) + .is_empty() + ); + assert!(!runtime.phase1_outbox_snapshot().is_empty()); + assert!( + !runtime + .phase1_search_results(Some("farm".to_owned()), context_id.clone()) + .is_empty() + ); + assert!(!runtime.phase1_prototype_paths().is_empty()); + assert!( + !runtime + .phase1_route_execution_flows(context_id.clone()) + .is_empty() + ); + assert!( + !runtime + .phase1_proof_provenance_artifacts(context_id.clone()) + .is_empty() + ); + assert!( + !runtime + .phase1_stewardship_access_items(context_id) + .is_empty() + ); + + let item = runtime + .phase1_outbox_snapshot() + .into_iter() + .find(|item| item.outbox_state == OutboxState::Failed) + .expect("failed outbox fixture"); + let decision = runtime.phase1_outbox_retry_decision(item); + assert!(decision.is_retryable); + + let gate = runtime.phase1_check_authority( + context.actor, + context.clone(), + AuthorityDomain::RelayGroupAccess, + AuthorityAction::Search, + ); + assert_eq!(gate.context, context); + + assert!(!runtime.phase1_search_results(None, None).is_empty()); + + let flows = fixture_route_execution_flows(None); + let direct_context = flows[0].context.context_ref.object_id.clone(); + assert!(!fixture_route_execution_flows(Some(direct_context)).is_empty()); + let step_context = flows + .iter() + .flat_map(|flow| { + flow.steps + .iter() + .map(move |step| (&flow.context.context_ref.object_id, step)) + }) + .find(|(flow_context, step)| { + flow_context.as_str() != step.context.context_ref.object_id + }) + .map(|(_, step)| step.context.context_ref.object_id.clone()) + .expect("step-only context"); + assert!(!fixture_route_execution_flows(Some(step_context)).is_empty()); + assert_eq!( + fixture_route_execution_flows(Some("unknown_context".to_owned())).len(), + flows.len() + ); + + let proof_context = fixture_proof_provenance_artifacts(None)[0] + .context + .context_ref + .object_id + .clone(); + assert!(!fixture_proof_provenance_artifacts(Some(proof_context)).is_empty()); + let stewardship_context = fixture_stewardship_access_items(None)[0] + .context + .context_ref + .object_id + .clone(); + assert!(!fixture_stewardship_access_items(Some(stewardship_context)).is_empty()); + } + + #[test] + fn canonical_vocabularies_match_phase_1_spec_counts() { + assert_eq!(CANONICAL_CONTEXT_TYPES.len(), 10); + assert_eq!(CANONICAL_WORKFLOW_ACTORS.len(), 11); + assert_eq!(CANONICAL_VISIBILITY_CLASSES.len(), 9); + assert_eq!(CANONICAL_AUTHORITY_DOMAINS.len(), 9); + assert_eq!(CANONICAL_TODAY_CARD_TYPES.len(), 12); + assert_eq!(TODAY_CARD_RANKING_PRIORITY.len(), 12); + assert_eq!(CANONICAL_ADD_ACTION_TYPES.len(), 18); + assert_eq!(CANONICAL_ADD_FLOW_STATES.len(), 16); + assert_eq!(CANONICAL_OBJECT_PAGE_FAMILIES.len(), 13); + assert_eq!(CANONICAL_OUTBOX_STATES.len(), 10); + assert_eq!(CANONICAL_SYNC_STATES.len(), 7); + assert_eq!(CANONICAL_ROUTE_EXECUTION_FLOW_KINDS.len(), 3); + assert_eq!(CANONICAL_ROUTE_EXECUTION_STEP_KINDS.len(), 6); + assert_eq!(CANONICAL_PROOF_PROVENANCE_ARTIFACT_KINDS.len(), 4); + assert_eq!(CANONICAL_PROOF_PROVENANCE_REVIEW_STATES.len(), 8); + assert_eq!(CANONICAL_STEWARDSHIP_ACCESS_ITEM_KINDS.len(), 9); + } + + #[test] + fn today_card_ranking_priority_covers_every_card_type() { + for card_type in CANONICAL_TODAY_CARD_TYPES { + assert!(TODAY_CARD_RANKING_PRIORITY.contains(&card_type)); + } + assert_eq!(TODAY_CARD_RANKING_PRIORITY[0], TodayCardType::Exception); + assert_eq!(TODAY_CARD_RANKING_PRIORITY[1], TodayCardType::SyncOutbox); + assert_eq!(TODAY_CARD_RANKING_PRIORITY[2], TodayCardType::Route); + + let cards = fixture_today_cards(None); + assert_eq!(cards[0].card_type, TodayCardType::Exception); + assert_eq!(cards[0].ranking_reason, "blocking exception"); + assert_eq!(cards[1].card_type, TodayCardType::SyncOutbox); + assert_eq!(cards[1].outbox_state, OutboxState::Failed); + assert!(cards[1].is_offline); + } + + #[test] + fn fixture_backed_projection_apis_cover_required_surface() { + assert_eq!( + fixture_active_contexts().len(), + CANONICAL_CONTEXT_TYPES.len() + ); + assert_eq!( + fixture_today_cards(None).len(), + CANONICAL_TODAY_CARD_TYPES.len() + ); + assert_eq!( + fixture_add_actions(None).len(), + CANONICAL_ADD_ACTION_TYPES.len() + ); + assert_eq!( + fixture_object_page_summaries(None).len(), + CANONICAL_OBJECT_PAGE_FAMILIES.len() + ); + assert_eq!(fixture_outbox_items().len(), CANONICAL_OUTBOX_STATES.len()); + assert_eq!( + fixture_route_execution_flows(None).len(), + CANONICAL_ROUTE_EXECUTION_FLOW_KINDS.len() + ); + assert_eq!(fixture_proof_provenance_artifacts(None).len(), 6); + assert_eq!(fixture_stewardship_access_items(None).len(), 9); + } + + #[test] + fn object_page_fixtures_carry_routeable_refs_and_navigation_authority() { + let pages = fixture_object_page_summaries(None); + assert_eq!(pages.len(), CANONICAL_OBJECT_PAGE_FAMILIES.len()); + + for (page, family) in pages.iter().zip(CANONICAL_OBJECT_PAGE_FAMILIES) { + assert_eq!(page.family, family); + assert_eq!(page.object_ref.object_type, object_kind_for_page(family)); + assert_eq!( + page.required_authority.action, + AuthorityAction::NavigateRelatedObject + ); + assert_eq!( + page.required_authority.domain, + AuthorityDomain::RelayGroupAccess + ); + assert_eq!( + page.required_authority.context.context_ref.object_id, + page.primary_context.context_ref.object_id + ); + assert!(!page.object_ref.object_id.is_empty()); + assert!(!page.title.is_empty()); + } + } + + #[test] + fn authority_visibility_fixtures_cover_every_actor_and_visibility_class() { + let context = active_context(); + for actor in CANONICAL_WORKFLOW_ACTORS { + let gate = fixture_authority_gate( + actor, + context.clone(), + AuthorityDomain::RelayGroupAccess, + AuthorityAction::Search, + ); + assert_eq!(gate.actor, actor); + assert_eq!(gate.action, AuthorityAction::Search); + } + + for visibility in CANONICAL_VISIBILITY_CLASSES { + let result_allowed = visibility_allows_search_result(visibility); + if matches!( + visibility, + VisibilityClass::LocalDraft + | VisibilityClass::FarmPrivate + | VisibilityClass::WorkspacePrivate + | VisibilityClass::RouteScoped + | VisibilityClass::BuyerScoped + | VisibilityClass::SecretNeverShared + ) { + assert!(!result_allowed); + } + } + } + + #[test] + fn search_results_filter_private_and_unauthorized_surfaces() { + let network = context_for_type(ContextType::Network); + let results = fixture_search_results( + Some("fixture".to_string()), + Some(network.context_ref.object_id), + ); + assert!(!results.is_empty()); + assert!( + results + .iter() + .all(|result| result.required_authority.is_allowed) + ); + assert!( + results + .iter() + .all(|result| visibility_allows_search_result(result.visibility)) + ); + assert!( + results + .iter() + .all(|result| object_kind_allows_search_result( + result.object_ref.object_type, + result.visibility + )) + ); + assert!( + !results + .iter() + .any(|result| result.object_ref.object_type == ObjectKind::BuyerPacket) + ); + assert!( + !results + .iter() + .any(|result| result.object_ref.object_type == ObjectKind::RouteStop) + ); + + let farm = context_for_type(ContextType::Farm); + let denied = fixture_search_results( + Some("fixture".to_string()), + Some(farm.context_ref.object_id), + ); + assert!(denied.is_empty()); + } + + #[test] + fn prototype_paths_cover_required_phase_1_actor_routes() { + let paths = fixture_prototype_paths(); + assert_eq!(paths.len(), 3); + assert!( + paths + .iter() + .any(|path| path.kind == PrototypePathKind::ProducerFoodToRoute + && path.actor == WorkflowActor::ProducerAdmin + && path.steps.iter().any(|step| step.label == "Add Food") + && path.steps.iter().any(|step| step.label == "Add to Route")) + ); + assert!(paths.iter().any(|path| { + path.kind == PrototypePathKind::BuyerCommitmentToRoute + && path.actor == WorkflowActor::BuyerSourcingLead + && path + .steps + .iter() + .any(|step| step.label == "Confirm Commitment") + })); + assert!(paths.iter().any(|path| { + path.kind == PrototypePathKind::RouteCoordinatorAssignment + && path.actor == WorkflowActor::RouteCoordinator + && path + .steps + .iter() + .any(|step| step.label == "Assign RoutePartner") + })); + } + + #[test] + fn prototype_paths_connect_actions_objects_outbox_and_authority() { + let paths = fixture_prototype_paths(); + let steps: Vec<&PrototypePathStep> = + paths.iter().flat_map(|path| path.steps.iter()).collect(); + + assert!( + steps + .iter() + .any(|step| step.action_type == Some(AddActionType::Food)) + ); + assert!(steps.iter().any(|step| { + step.object_ref + .as_ref() + .is_some_and(|object_ref| object_ref.object_type == ObjectKind::Food) + })); + assert!(steps.iter().any(|step| { + step.object_ref + .as_ref() + .is_some_and(|object_ref| object_ref.object_type == ObjectKind::Route) + })); + assert!(steps.iter().any(|step| { + step.object_ref + .as_ref() + .is_some_and(|object_ref| object_ref.object_type == ObjectKind::RoutePartner) + })); + assert!( + steps + .iter() + .any(|step| step.outbox_state == OutboxState::Queued) + ); + assert!( + steps + .iter() + .any(|step| step.outbox_state == OutboxState::Conflict) + ); + assert!(steps.iter().all(|step| step.authority_gate.is_required)); + assert!( + steps + .iter() + .all(|step| step.visibility != VisibilityClass::SecretNeverShared) + ); + } + + #[test] + fn route_execution_flows_cover_partner_receipt_and_exception_paths() { + let flows = fixture_route_execution_flows(None); + assert_eq!(flows.len(), 3); + + for kind in CANONICAL_ROUTE_EXECUTION_FLOW_KINDS { + assert!( + flows.iter().any(|flow| flow.kind == kind), + "missing {kind:?}" + ); + } + + let steps: Vec<&RouteExecutionStep> = + flows.iter().flat_map(|flow| flow.steps.iter()).collect(); + for kind in CANONICAL_ROUTE_EXECUTION_STEP_KINDS { + assert!( + steps.iter().any(|step| step.kind == kind), + "missing {kind:?}" + ); + } + + assert!(steps.iter().any(|step| { + step.kind == RouteExecutionStepKind::PickupConfirmation + && step.supports_offline + && step + .object_ref + .as_ref() + .is_some_and(|object_ref| object_ref.object_type == ObjectKind::Proof) + })); + assert!(steps.iter().any(|step| { + step.kind == RouteExecutionStepKind::DropoffConfirmation + && step.supports_offline + && step + .object_ref + .as_ref() + .is_some_and(|object_ref| object_ref.object_type == ObjectKind::Proof) + })); + assert!( + steps + .iter() + .any(|step| step.kind == RouteExecutionStepKind::ExceptionReport + && step.outbox_state == OutboxState::Conflict) + ); + assert!( + fixture_today_cards(None) + .iter() + .any(|card| card.card_type == TodayCardType::Exception) + ); + } + + #[test] + fn route_partner_execution_flow_is_assigned_route_scoped_only() { + let flow = fixture_route_execution_flows(None) + .into_iter() + .find(|flow| flow.kind == RouteExecutionFlowKind::RoutePartnerAssignedStops) + .expect("route partner flow"); + assert_eq!(flow.actor, WorkflowActor::RoutePartner); + assert_eq!(flow.context.actor, WorkflowActor::RoutePartner); + + for step in &flow.steps { + assert_eq!(step.actor, WorkflowActor::RoutePartner); + assert_eq!(step.visibility, VisibilityClass::RouteScoped); + assert_eq!( + step.required_authority.domain, + AuthorityDomain::RouteExecution + ); + assert!(step.required_authority.is_allowed); + assert_ne!(step.required_authority.domain, AuthorityDomain::Receipt); + assert_ne!( + step.required_authority.domain, + AuthorityDomain::BuyerWorkspace + ); + assert!(matches!( + step.object_ref + .as_ref() + .map(|object_ref| object_ref.object_type), + Some(ObjectKind::Route | ObjectKind::RouteStop | ObjectKind::Proof) + )); + } + } + + #[test] + fn buyer_receipt_flow_supports_partial_receipt_token_without_route_execution() { + let flow = fixture_route_execution_flows(None) + .into_iter() + .find(|flow| flow.kind == RouteExecutionFlowKind::BuyerReceiptConfirmation) + .expect("buyer receipt flow"); + assert_eq!(flow.actor, WorkflowActor::BuyerReceiver); + assert_eq!(flow.context.actor, WorkflowActor::BuyerReceiver); + assert_eq!(flow.steps.len(), 1); + + let receipt = &flow.steps[0]; + assert_eq!(receipt.kind, RouteExecutionStepKind::ReceiptConfirmation); + assert_eq!(receipt.required_authority.domain, AuthorityDomain::Receipt); + assert_eq!(receipt.required_authority.action, AuthorityAction::Submit); + assert!(receipt.required_authority.is_allowed); + assert!(receipt.supports_partial_receipt); + assert!(receipt.uses_receipt_token); + assert_ne!( + receipt.required_authority.domain, + AuthorityDomain::RouteExecution + ); + assert_eq!(receipt.visibility, VisibilityClass::BuyerScoped); + } + + #[test] + fn route_exception_recovery_separates_reporting_from_coordination() { + let flow = fixture_route_execution_flows(None) + .into_iter() + .find(|flow| flow.kind == RouteExecutionFlowKind::ExceptionRecovery) + .expect("exception recovery flow"); + let report = flow + .steps + .iter() + .find(|step| step.kind == RouteExecutionStepKind::ExceptionReport) + .expect("report step"); + let recovery = flow + .steps + .iter() + .find(|step| step.kind == RouteExecutionStepKind::RecoveryAction) + .expect("recovery step"); + + assert_eq!(report.actor, WorkflowActor::RoutePartner); + assert_eq!( + report.required_authority.domain, + AuthorityDomain::RouteExecution + ); + assert_eq!(report.outbox_state, OutboxState::Conflict); + assert!(report.supports_offline); + assert_eq!(recovery.actor, WorkflowActor::RouteCoordinator); + assert_eq!( + recovery.required_authority.domain, + AuthorityDomain::RouteCoordination + ); + assert_eq!(recovery.required_authority.action, AuthorityAction::Close); + assert!(recovery.supports_partial_receipt); + assert!(recovery.required_authority.is_allowed); + } + + #[test] + fn proof_provenance_artifacts_cover_required_kinds_and_states() { + let artifacts = fixture_proof_provenance_artifacts(None); + for kind in CANONICAL_PROOF_PROVENANCE_ARTIFACT_KINDS { + assert!( + artifacts.iter().any(|artifact| artifact.kind == kind), + "missing {kind:?}" + ); + } + + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::ProofCompleteness + && artifact.review_state == ProofProvenanceReviewState::MissingProof + })); + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::ProofCompleteness + && artifact.review_state == ProofProvenanceReviewState::Complete + })); + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::BuyerPacketDraft + && artifact.review_state == ProofProvenanceReviewState::Draft + })); + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::BuyerPacketShared + && artifact.review_state == ProofProvenanceReviewState::Shared + })); + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::PublicProvenancePreview + && artifact.review_state == ProofProvenanceReviewState::RedactionRequired + })); + assert!(artifacts.iter().any(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::PublicProvenancePreview + && artifact.review_state == ProofProvenanceReviewState::ReadyToPublish + })); + } + + #[test] + fn trace_lead_and_authorized_producer_can_review_proof_completeness() { + let proof_artifacts: Vec<ProofProvenanceArtifact> = + fixture_proof_provenance_artifacts(None) + .into_iter() + .filter(|artifact| artifact.kind == ProofProvenanceArtifactKind::ProofCompleteness) + .collect(); + assert_eq!(proof_artifacts.len(), 2); + assert!(proof_artifacts.iter().any(|artifact| { + artifact.actor == WorkflowActor::TraceLead + && artifact.required_authority.domain == AuthorityDomain::TraceProof + && artifact.required_authority.action == AuthorityAction::Approve + && artifact.required_authority.is_allowed + })); + assert!(proof_artifacts.iter().any(|artifact| { + artifact.actor == WorkflowActor::ProducerAdmin + && artifact.required_authority.domain == AuthorityDomain::TraceProof + && artifact.required_authority.action == AuthorityAction::Approve + && artifact.required_authority.is_allowed + })); + } + + #[test] + fn buyer_packets_are_private_and_public_provenance_is_distinct() { + let artifacts = fixture_proof_provenance_artifacts(None); + let buyer_packets: Vec<&ProofProvenanceArtifact> = artifacts + .iter() + .filter(|artifact| { + matches!( + artifact.kind, + ProofProvenanceArtifactKind::BuyerPacketDraft + | ProofProvenanceArtifactKind::BuyerPacketShared + ) + }) + .collect(); + assert_eq!(buyer_packets.len(), 2); + assert!(buyer_packets.iter().all(|artifact| { + artifact.object_ref.object_type == ObjectKind::BuyerPacket + && artifact.visibility == VisibilityClass::BuyerScoped + && !artifact.is_public_preview + && !artifact.can_publish + })); + + let public_previews: Vec<&ProofProvenanceArtifact> = artifacts + .iter() + .filter(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::PublicProvenancePreview + }) + .collect(); + assert_eq!(public_previews.len(), 2); + assert!(public_previews.iter().all(|artifact| { + artifact.object_ref.object_type == ObjectKind::Provenance + && artifact.visibility == VisibilityClass::PublicProvenance + && artifact.is_public_preview + && artifact.required_authority.domain == AuthorityDomain::PublicPublishing + })); + } + + #[test] + fn public_provenance_publication_requires_authority_and_redaction_review() { + let artifacts = fixture_proof_provenance_artifacts(None); + let review = artifacts + .iter() + .find(|artifact| { + artifact.id == "public_provenance_redaction_review" + && artifact.kind == ProofProvenanceArtifactKind::PublicProvenancePreview + }) + .expect("redaction review artifact"); + assert!(review.required_authority.is_allowed); + assert_eq!(review.required_authority.action, AuthorityAction::Publish); + assert!(review.requires_redaction_review); + assert!(!review.can_publish); + assert_eq!(review.outbox_state, OutboxState::AwaitingAuthority); + + let ready = artifacts + .iter() + .find(|artifact| artifact.id == "public_provenance_ready") + .expect("ready artifact"); + assert!(ready.required_authority.is_allowed); + assert!(!ready.requires_redaction_review); + assert!(ready.can_publish); + assert_eq!( + ready.review_state, + ProofProvenanceReviewState::ReadyToPublish + ); + } + + #[test] + fn public_provenance_never_leaks_private_trace_or_buyer_fields() { + let public_previews: Vec<ProofProvenanceArtifact> = + fixture_proof_provenance_artifacts(None) + .into_iter() + .filter(|artifact| { + artifact.kind == ProofProvenanceArtifactKind::PublicProvenancePreview + }) + .collect(); + assert!(!public_previews.is_empty()); + + let blocked = private_provenance_redaction_labels(); + for artifact in public_previews { + for label in &blocked { + assert!( + artifact + .redacted_field_labels + .iter() + .any(|redacted| redacted == label) + ); + } + + let public_text = artifact.public_summary_lines.join(" ").to_lowercase(); + for label in &blocked { + assert!( + !public_text.contains(&label.to_lowercase()), + "{label} leaked into public summary" + ); + } + assert!( + !artifact + .source_object_refs + .iter() + .any(|object_ref| object_ref.object_type == ObjectKind::BuyerPacket) + ); + assert!( + !artifact + .source_object_refs + .iter() + .any(|object_ref| object_ref.object_type == ObjectKind::RouteStop) + ); + } + } + + #[test] + fn stewardship_access_items_cover_admin_lite_and_member_access_states() { + let items = fixture_stewardship_access_items(None); + for kind in CANONICAL_STEWARDSHIP_ACCESS_ITEM_KINDS { + assert!( + items.iter().any(|item| item.kind == kind), + "missing {kind:?}" + ); + } + + assert!(items.iter().any(|item| { + item.kind == StewardshipAccessItemKind::InviteAcceptance + && item.actor == WorkflowActor::NetworkMember + })); + assert!(items.iter().any(|item| { + item.kind == StewardshipAccessItemKind::RequestAccess + && item.actor == WorkflowActor::NetworkMember + })); + assert!(items.iter().any(|item| { + item.kind == StewardshipAccessItemKind::AccessDenied + && !item.required_authority.is_allowed + && item.visibility == VisibilityClass::FarmPrivate + })); + assert!(items.iter().any(|item| { + item.kind == StewardshipAccessItemKind::GroupManagementDeferred + && item.is_phase_2_deferred + })); + } + + #[test] + fn network_steward_can_perform_admin_lite_actions() { + let items: Vec<StewardshipAccessItem> = fixture_stewardship_access_items(None) + .into_iter() + .filter(|item| item.actor == WorkflowActor::NetworkSteward && item.is_admin_lite) + .collect(); + assert!(items.len() >= 6); + + for kind in [ + StewardshipAccessItemKind::AccessRequestReview, + StewardshipAccessItemKind::RoleApproval, + StewardshipAccessItemKind::RoutePartnerInvite, + StewardshipAccessItemKind::RoutePoolMetadata, + StewardshipAccessItemKind::PublicModeration, + ] { + let item = items + .iter() + .find(|item| item.kind == kind) + .unwrap_or_else(|| panic!("missing {kind:?}")); + assert!(item.required_authority.is_allowed); + assert!(!item.grants_private_access); + assert!(!item.is_phase_2_deferred); + } + + let route_pool = items + .iter() + .find(|item| item.kind == StewardshipAccessItemKind::RoutePoolMetadata) + .expect("route pool item"); + assert_eq!( + route_pool.required_authority.domain, + AuthorityDomain::NetworkStewardship + ); + assert_eq!( + route_pool.required_authority.action, + AuthorityAction::Assign + ); + + let moderation = items + .iter() + .find(|item| item.kind == StewardshipAccessItemKind::PublicModeration) + .expect("public moderation item"); + assert_eq!( + moderation.required_authority.domain, + AuthorityDomain::PublicPublishing + ); + } + + #[test] + fn phase_2_group_management_remains_deferred() { + let deferred = fixture_stewardship_access_items(None) + .into_iter() + .find(|item| item.kind == StewardshipAccessItemKind::GroupManagementDeferred) + .expect("deferred group management item"); + assert!(deferred.is_phase_2_deferred); + assert!(deferred.is_admin_lite); + assert!(!deferred.grants_private_access); + assert_eq!(deferred.outbox_state, OutboxState::NotQueued); + } + + #[test] + fn network_steward_does_not_automatically_gain_private_workspace_access() { + let steward = context_for_type(ContextType::NetworkSteward); + for (domain, context_type) in [ + (AuthorityDomain::FarmWorkspaceOperations, ContextType::Farm), + (AuthorityDomain::BuyerWorkspace, ContextType::Buyer), + (AuthorityDomain::RouteCoordination, ContextType::Route), + (AuthorityDomain::RouteExecution, ContextType::RoutePartner), + (AuthorityDomain::TraceProof, ContextType::TraceRecords), + (AuthorityDomain::Receipt, ContextType::PickupPoint), + ] { + let context = context_for_type(context_type); + let gate = fixture_authority_gate( + WorkflowActor::NetworkSteward, + context, + domain, + AuthorityAction::Search, + ); + assert!( + !gate.is_allowed, + "NetworkSteward unexpectedly gained {domain:?}" + ); + } + + assert!( + fixture_authority_gate( + WorkflowActor::NetworkSteward, + steward.clone(), + AuthorityDomain::RelayGroupAccess, + AuthorityAction::Approve, + ) + .is_allowed + ); + assert!( + fixture_authority_gate( + WorkflowActor::NetworkSteward, + steward, + AuthorityDomain::NetworkStewardship, + AuthorityAction::Assign, + ) + .is_allowed + ); + } + + #[test] + fn serde_names_preserve_product_vocabulary() { + assert_eq!( + serde_json::to_value(WorkflowActor::NetworkMember).expect("serialize actor"), + "NetworkMember" + ); + assert_eq!( + serde_json::to_value(VisibilityClass::PublicProvenance).expect("serialize visibility"), + "PublicProvenance" + ); + assert_eq!( + serde_json::to_value(AuthorityDomain::RelayGroupAccess).expect("serialize authority"), + "Relay/group access" + ); + assert_eq!( + serde_json::to_value(AddActionType::BuyerCommitment).expect("serialize action"), + "BuyerCommitment" + ); + } + + #[test] + fn product_surface_records_round_trip_through_json() { + let card = TodayCard { + id: "card_route_gap_001".to_string(), + card_type: TodayCardType::Proof, + source_object_refs: vec![object_ref(ObjectKind::Route, "route_123", "Thursday loop")], + source_event_refs: vec![EventRef { + event_id: "event_abc".to_string(), + relay_url: Some("wss://relay.example".to_string()), + kind: Some(1), + }], + primary_context: active_context(), + actor: WorkflowActor::ProducerAdmin, + visibility: VisibilityClass::RouteScoped, + visibility_label: "route crew".to_string(), + title: "Proof needed for Thursday loop".to_string(), + status_line: "missing pickup confirmation".to_string(), + detail_lines: vec!["2 stops need proof".to_string()], + pills: vec!["blocking".to_string(), "route".to_string()], + primary_action: TodayCardAction { + id: "add_proof".to_string(), + label: "Add proof".to_string(), + action_type: Some(AddActionType::Proof), + target_object: Some(object_ref(ObjectKind::Route, "route_123", "Thursday loop")), + }, + secondary_action: None, + ranking_reason: "blocking exception".to_string(), + ranking_features: vec!["proof_gap".to_string()], + sync_state: SyncState::Online, + outbox_state: OutboxState::NotQueued, + is_stale: false, + is_offline: false, + }; + + let json = serde_json::to_string(&card).expect("serialize card"); + let decoded: TodayCard = serde_json::from_str(&json).expect("decode card"); + assert_eq!(decoded, card); + assert!(json.contains("\"cardType\":\"Proof\"")); + assert!(json.contains("\"visibility\":\"RouteScoped\"")); + } + + #[test] + fn add_action_and_outbox_contract_carry_authority_and_visibility() { + let add_action = AddAction { + action_type: AddActionType::PublicUpdate, + display_label: "Public update".to_string(), + allowed_context_types: vec![ContextType::Network, ContextType::Farm], + required_authority: authority_gate(), + default_visibility: VisibilityClass::PublicCommunity, + allowed_visibility_options: vec![ + VisibilityClass::NetworkVisible, + VisibilityClass::PublicCommunity, + ], + created_or_updated_object_type: ObjectKind::Update, + related_object_requirements: vec![RelatedObjectRequirement { + object_type: ObjectKind::Farm, + relationship_label: "posted by".to_string(), + is_required: true, + }], + validation_requirements: vec![ValidationRequirement { + id: "non_empty_body".to_string(), + label: "Body is required".to_string(), + is_blocking: true, + }], + supports_offline: true, + supports_draft: true, + outbox_behavior: OutboxBehavior::PublishWhenAuthorized, + primary_submit_label: "Publish".to_string(), + completion_state: AddFlowState::ReadyToSubmit, + }; + let outbox_item = OutboxItem { + id: "outbox_001".to_string(), + action_type: add_action.action_type, + context: active_context(), + object_refs: vec![object_ref( + ObjectKind::Update, + "draft_001", + "Public update draft", + )], + event_refs: Vec::new(), + visibility: add_action.default_visibility, + authority_gate: add_action.required_authority.clone(), + flow_state: AddFlowState::Queued, + outbox_state: OutboxState::AwaitingAuthority, + sync_state: SyncState::Offline, + queued_at_unix: Some(1_799_971_200), + last_attempt_at_unix: None, + retry_count: 0, + last_error: None, + }; + + assert_eq!( + outbox_item.authority_gate.domain, + AuthorityDomain::FarmWorkspaceOperations + ); + assert_eq!(outbox_item.visibility, VisibilityClass::PublicCommunity); + assert_eq!(outbox_item.flow_state, AddFlowState::Queued); + assert_eq!(outbox_item.sync_state, SyncState::Offline); + } + + #[test] + fn outbox_retry_decision_rechecks_state_visibility_and_authority() { + let failed = fixture_outbox_items() + .into_iter() + .find(|item| item.outbox_state == OutboxState::Failed) + .expect("failed outbox fixture"); + + let retryable = fixture_outbox_retry_decision(failed.clone()); + assert!(retryable.is_retryable); + assert_eq!(retryable.item_id, failed.id); + assert_eq!(retryable.authority_gate.action, AuthorityAction::Retry); + assert!(retryable.reason.is_none()); + + let mut queued = failed.clone(); + queued.outbox_state = OutboxState::Queued; + let queued_decision = fixture_outbox_retry_decision(queued); + assert!(!queued_decision.is_retryable); + assert!( + queued_decision + .reason + .as_deref() + .expect("queued reason") + .contains("not a retryable outbox state") + ); + + let mut secret = failed.clone(); + secret.visibility = VisibilityClass::SecretNeverShared; + let secret_decision = fixture_outbox_retry_decision(secret); + assert!(!secret_decision.is_retryable); + assert!( + secret_decision + .reason + .as_deref() + .expect("secret reason") + .contains("visibility cannot be retried") + ); + + let mut denied = failed; + denied.authority_gate.domain = AuthorityDomain::BuyerWorkspace; + let denied_decision = fixture_outbox_retry_decision(denied); + assert!(!denied_decision.is_retryable); + assert!(!denied_decision.authority_gate.is_allowed); + assert!(denied_decision.reason.is_some()); + } + + #[test] + fn compatibility_note_quarantines_low_level_roles() { + assert!(WORKFLOW_ACTOR_COMPATIBILITY_NOTE.contains("Farmer")); + assert!(WORKFLOW_ACTOR_COMPATIBILITY_NOTE.contains("Buyer")); + assert!(WORKFLOW_ACTOR_COMPATIBILITY_NOTE.contains("not sufficient authority")); + } + + #[test] + fn authority_fixture_allows_and_denies_by_actor_domain_pair() { + let context = active_context(); + let allowed = fixture_authority_gate( + WorkflowActor::ProducerAdmin, + context.clone(), + AuthorityDomain::FarmWorkspaceOperations, + AuthorityAction::Submit, + ); + assert!(allowed.is_allowed); + assert_eq!(allowed.reason, None); + + let denied = fixture_authority_gate( + WorkflowActor::NetworkMember, + context, + AuthorityDomain::FarmWorkspaceOperations, + AuthorityAction::Submit, + ); + assert!(!denied.is_allowed); + assert!(denied.reason.is_some()); + } +} diff --git a/core/crates/tera_core/src/runtime/sdk.rs b/core/crates/tera_core/src/runtime/sdk.rs @@ -0,0 +1,98 @@ +use radroots_sdk::capability::{Availability, Maturity}; + +use super::RadrootsRuntime; +use crate::RadrootsAppError; + +#[derive(Clone, Debug, uniffi::Record)] +pub struct SdkCapabilityRecord { + pub id: String, + pub compiled: bool, + pub configured: bool, + pub availability: String, + pub maturity: String, +} + +#[derive(Clone, Debug, uniffi::Record)] +pub struct SdkStorageStatusRecord { + pub backend: String, + pub open_mode: String, + pub shutdown: String, + pub integrity: String, +} + +#[derive(Clone, Debug, Eq, PartialEq, uniffi::Record)] +pub struct SdkShutdownRecord { + pub state: String, + pub already_closed: bool, +} + +#[cfg_attr(not(coverage_nightly), uniffi::export)] +impl RadrootsRuntime { + pub fn sdk_capabilities(&self) -> Vec<SdkCapabilityRecord> { + self.client + .capabilities() + .iter() + .map(|status| SdkCapabilityRecord { + id: status.id().as_str().to_owned(), + compiled: status.is_compiled(), + configured: status.is_configured(), + availability: availability_label(status.availability()).to_owned(), + maturity: maturity_label(status.maturity()).to_owned(), + }) + .collect() + } + + pub async fn sdk_storage_status(&self) -> Result<SdkStorageStatusRecord, RadrootsAppError> { + let status = self + .client + .storage_status() + .await + .map_err(RadrootsAppError::from_sdk)?; + Ok(SdkStorageStatusRecord { + backend: format!("{:?}", status.backend()).to_ascii_lowercase(), + open_mode: format!("{:?}", status.open_mode()).to_ascii_lowercase(), + shutdown: format!("{:?}", status.shutdown()).to_ascii_lowercase(), + integrity: format!("{:?}", status.integrity().health()).to_ascii_lowercase(), + }) + } +} + +const fn availability_label(value: Availability) -> &'static str { + match value { + Availability::Available => "available", + Availability::Degraded => "degraded", + Availability::Unavailable => "unavailable", + Availability::Unsupported => "unsupported", + } +} + +const fn maturity_label(value: Maturity) -> &'static str { + match value { + Maturity::Stable => "stable", + Maturity::Preview => "preview", + Maturity::Experimental => "experimental", + } +} + +#[cfg(test)] +#[cfg_attr(coverage_nightly, coverage(off))] +mod tests { + use super::RadrootsRuntime; + + #[tokio::test] + async fn sdk_records_are_stable_and_storage_is_memory_backed() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let capabilities = runtime.sdk_capabilities(); + assert!(capabilities.iter().any(|capability| { + capability.id == "storage.canonical" + && capability.configured + && capability.availability == "available" + && capability.maturity == "stable" + })); + let status = runtime.sdk_storage_status().await.expect("storage status"); + assert_eq!(status.backend, "memory"); + assert_eq!(status.integrity, "healthy"); + runtime.shutdown().await.expect("shutdown"); + assert!(runtime.sdk_storage_status().await.is_err()); + } +} diff --git a/core/crates/tera_core/tests/logging_error.rs b/core/crates/tera_core/tests/logging_error.rs @@ -0,0 +1,9 @@ +use radroots_mobile_core::RadrootsAppError; +use radroots_mobile_core::logging; + +#[test] +fn init_logging_stdout_maps_global_subscriber_error() { + let _ = tracing_subscriber::fmt().try_init(); + let err = logging::init_logging_stdout(); + assert!(matches!(err, Err(RadrootsAppError::Initialization(_)))); +} diff --git a/core/crates/tera_core/tests/sdk_runtime.rs b/core/crates/tera_core/tests/sdk_runtime.rs @@ -0,0 +1,52 @@ +use std::sync::Arc; + +use radroots_mobile_core::{RadrootsAppError, RadrootsRuntime}; + +#[tokio::test] +async fn runtime_is_send_sync_and_shares_one_sdk_lifecycle() { + fn require_send_sync<T: Send + Sync>() {} + require_send_sync::<RadrootsRuntime>(); + + let runtime = Arc::new(RadrootsRuntime::new().expect("runtime")); + let worker = { + let runtime = Arc::clone(&runtime); + std::thread::spawn(move || runtime.sdk_capabilities()) + }; + let capabilities = worker.join().expect("worker"); + assert!( + capabilities + .iter() + .any(|capability| capability.id == "storage.canonical") + ); + let first = runtime.shutdown().await.expect("first shutdown"); + let second = runtime.shutdown().await.expect("second shutdown"); + assert!(!first.already_closed); + assert!(second.already_closed); + assert!(runtime.info().sdk_closed); +} + +#[tokio::test] +async fn operations_fail_safely_after_explicit_close() { + let runtime = RadrootsRuntime::new().expect("runtime"); + assert_eq!( + runtime.sdk_storage_status().await.expect("status").backend, + "memory" + ); + runtime.shutdown().await.expect("shutdown"); + assert!(matches!( + runtime.sdk_storage_status().await, + Err(RadrootsAppError::Sdk { .. }) + )); +} + +#[tokio::test] +async fn dropping_unpolled_shutdown_has_no_effect_and_retry_closes() { + let runtime = RadrootsRuntime::new().expect("runtime"); + drop(runtime.shutdown()); + assert!(!runtime.info().sdk_closed); + assert!(!runtime.info().app.shutting_down); + + runtime.shutdown().await.expect("retry shutdown"); + assert!(runtime.info().sdk_closed); + assert!(runtime.info().app.shutting_down); +} diff --git a/core/crates/tera_core/tests/uniffi_contract.rs b/core/crates/tera_core/tests/uniffi_contract.rs @@ -0,0 +1,33 @@ +use radroots_mobile_core::{RadrootsAppError, RadrootsRuntime, SdkErrorRecord}; + +#[tokio::test] +async fn final_mobile_abi_uses_async_sdk_dtos_and_versioned_errors() { + let runtime = RadrootsRuntime::new().expect("runtime"); + let storage = runtime.sdk_storage_status().await.expect("storage status"); + assert_eq!(storage.backend, "memory"); + + runtime.shutdown().await.expect("shutdown"); + let error = runtime + .sdk_storage_status() + .await + .expect_err("closed client must reject operations"); + let RadrootsAppError::Sdk { + report: + SdkErrorRecord { + schema_version, + code, + class, + retryable, + message, + .. + }, + } = error + else { + panic!("expected versioned SDK error record"); + }; + assert_eq!(schema_version, 1); + assert_eq!(code, "client_closed"); + assert_eq!(class, "runtime"); + assert!(!retryable); + assert_eq!(message, "SDK client is closed"); +} diff --git a/core/provenance/tera_core/LICENSE-GPL-3.0-or-later b/core/provenance/tera_core/LICENSE-GPL-3.0-or-later @@ -0,0 +1,674 @@ + GNU GENERAL PUBLIC LICENSE + Version 3, 29 June 2007 + + Copyright (C) 2007 Free Software Foundation, Inc. <https://fsf.org/> + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The GNU General Public License is a free, copyleft license for +software and other kinds of works. + + The licenses for most software and other practical works are designed +to take away your freedom to share and change the works. By contrast, +the GNU General Public License is intended to guarantee your freedom to +share and change all versions of a program--to make sure it remains free +software for all its users. We, the Free Software Foundation, use the +GNU General Public License for most of our software; it applies also to +any other work released this way by its authors. You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +them if you wish), that you receive source code or can get it if you +want it, that you can change the software or use pieces of it in new +free programs, and that you know you can do these things. + + To protect your rights, we need to prevent others from denying you +these rights or asking you to surrender the rights. Therefore, you have +certain responsibilities if you distribute copies of the software, or if +you modify it: responsibilities to respect the freedom of others. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must pass on to the recipients the same +freedoms that you received. You must make sure that they, too, receive +or can get the source code. And you must show them these terms so they +know their rights. + + Developers that use the GNU GPL protect your rights with two steps: +(1) assert copyright on the software, and (2) offer you this License +giving you legal permission to copy, distribute and/or modify it. + + For the developers' and authors' protection, the GPL clearly explains +that there is no warranty for this free software. For both users' and +authors' sake, the GPL requires that modified versions be marked as +changed, so that their problems will not be attributed erroneously to +authors of previous versions. + + Some devices are designed to deny users access to install or run +modified versions of the software inside them, although the manufacturer +can do so. This is fundamentally incompatible with the aim of +protecting users' freedom to change the software. The systematic +pattern of such abuse occurs in the area of products for individuals to +use, which is precisely where it is most unacceptable. Therefore, we +have designed this version of the GPL to prohibit the practice for those +products. If such problems arise substantially in other domains, we +stand ready to extend this provision to those domains in future versions +of the GPL, as needed to protect the freedom of users. + + Finally, every program is threatened constantly by software patents. +States should not allow patents to restrict development and use of +software on general-purpose computers, but in those that do, we wish to +avoid the special danger that patents applied to a free program could +make it effectively proprietary. To prevent this, the GPL assures that +patents cannot be used to render the program non-free. + + The precise terms and conditions for copying, distribution and +modification follow. + + TERMS AND CONDITIONS + + 0. Definitions. + + "This License" refers to version 3 of the GNU General Public License. + + "Copyright" also means copyright-like laws that apply to other kinds of +works, such as semiconductor masks. + + "The Program" refers to any copyrightable work licensed under this +License. Each licensee is addressed as "you". "Licensees" and +"recipients" may be individuals or organizations. + + To "modify" a work means to copy from or adapt all or part of the work +in a fashion requiring copyright permission, other than the making of an +exact copy. The resulting work is called a "modified version" of the +earlier work or a work "based on" the earlier work. + + A "covered work" means either the unmodified Program or a work based +on the Program. + + To "propagate" a work means to do anything with it that, without +permission, would make you directly or secondarily liable for +infringement under applicable copyright law, except executing it on a +computer or modifying a private copy. Propagation includes copying, +distribution (with or without modification), making available to the +public, and in some countries other activities as well. + + To "convey" a work means any kind of propagation that enables other +parties to make or receive copies. Mere interaction with a user through +a computer network, with no transfer of a copy, is not conveying. + + An interactive user interface displays "Appropriate Legal Notices" +to the extent that it includes a convenient and prominently visible +feature that (1) displays an appropriate copyright notice, and (2) +tells the user that there is no warranty for the work (except to the +extent that warranties are provided), that licensees may convey the +work under this License, and how to view a copy of this License. If +the interface presents a list of user commands or options, such as a +menu, a prominent item in the list meets this criterion. + + 1. Source Code. + + The "source code" for a work means the preferred form of the work +for making modifications to it. "Object code" means any non-source +form of a work. + + A "Standard Interface" means an interface that either is an official +standard defined by a recognized standards body, or, in the case of +interfaces specified for a particular programming language, one that +is widely used among developers working in that language. + + The "System Libraries" of an executable work include anything, other +than the work as a whole, that (a) is included in the normal form of +packaging a Major Component, but which is not part of that Major +Component, and (b) serves only to enable use of the work with that +Major Component, or to implement a Standard Interface for which an +implementation is available to the public in source code form. A +"Major Component", in this context, means a major essential component +(kernel, window system, and so on) of the specific operating system +(if any) on which the executable work runs, or a compiler used to +produce the work, or an object code interpreter used to run it. + + The "Corresponding Source" for a work in object code form means all +the source code needed to generate, install, and (for an executable +work) run the object code and to modify the work, including scripts to +control those activities. However, it does not include the work's +System Libraries, or general-purpose tools or generally available free +programs which are used unmodified in performing those activities but +which are not part of the work. For example, Corresponding Source +includes interface definition files associated with source files for +the work, and the source code for shared libraries and dynamically +linked subprograms that the work is specifically designed to require, +such as by intimate data communication or control flow between those +subprograms and other parts of the work. + + The Corresponding Source need not include anything that users +can regenerate automatically from other parts of the Corresponding +Source. + + The Corresponding Source for a work in source code form is that +same work. + + 2. Basic Permissions. + + All rights granted under this License are granted for the term of +copyright on the Program, and are irrevocable provided the stated +conditions are met. This License explicitly affirms your unlimited +permission to run the unmodified Program. The output from running a +covered work is covered by this License only if the output, given its +content, constitutes a covered work. This License acknowledges your +rights of fair use or other equivalent, as provided by copyright law. + + You may make, run and propagate covered works that you do not +convey, without conditions so long as your license otherwise remains +in force. You may convey covered works to others for the sole purpose +of having them make modifications exclusively for you, or provide you +with facilities for running those works, provided that you comply with +the terms of this License in conveying all material for which you do +not control copyright. Those thus making or running the covered works +for you must do so exclusively on your behalf, under your direction +and control, on terms that prohibit them from making any copies of +your copyrighted material outside their relationship with you. + + Conveying under any other circumstances is permitted solely under +the conditions stated below. Sublicensing is not allowed; section 10 +makes it unnecessary. + + 3. Protecting Users' Legal Rights From Anti-Circumvention Law. + + No covered work shall be deemed part of an effective technological +measure under any applicable law fulfilling obligations under article +11 of the WIPO copyright treaty adopted on 20 December 1996, or +similar laws prohibiting or restricting circumvention of such +measures. + + When you convey a covered work, you waive any legal power to forbid +circumvention of technological measures to the extent such circumvention +is effected by exercising rights under this License with respect to +the covered work, and you disclaim any intention to limit operation or +modification of the work as a means of enforcing, against the work's +users, your or third parties' legal rights to forbid circumvention of +technological measures. + + 4. Conveying Verbatim Copies. + + You may convey verbatim copies of the Program's source code as you +receive it, in any medium, provided that you conspicuously and +appropriately publish on each copy an appropriate copyright notice; +keep intact all notices stating that this License and any +non-permissive terms added in accord with section 7 apply to the code; +keep intact all notices of the absence of any warranty; and give all +recipients a copy of this License along with the Program. + + You may charge any price or no price for each copy that you convey, +and you may offer support or warranty protection for a fee. + + 5. Conveying Modified Source Versions. + + You may convey a work based on the Program, or the modifications to +produce it from the Program, in the form of source code under the +terms of section 4, provided that you also meet all of these conditions: + + a) The work must carry prominent notices stating that you modified + it, and giving a relevant date. + + b) The work must carry prominent notices stating that it is + released under this License and any conditions added under section + 7. This requirement modifies the requirement in section 4 to + "keep intact all notices". + + c) You must license the entire work, as a whole, under this + License to anyone who comes into possession of a copy. This + License will therefore apply, along with any applicable section 7 + additional terms, to the whole of the work, and all its parts, + regardless of how they are packaged. This License gives no + permission to license the work in any other way, but it does not + invalidate such permission if you have separately received it. + + d) If the work has interactive user interfaces, each must display + Appropriate Legal Notices; however, if the Program has interactive + interfaces that do not display Appropriate Legal Notices, your + work need not make them do so. + + A compilation of a covered work with other separate and independent +works, which are not by their nature extensions of the covered work, +and which are not combined with it such as to form a larger program, +in or on a volume of a storage or distribution medium, is called an +"aggregate" if the compilation and its resulting copyright are not +used to limit the access or legal rights of the compilation's users +beyond what the individual works permit. Inclusion of a covered work +in an aggregate does not cause this License to apply to the other +parts of the aggregate. + + 6. Conveying Non-Source Forms. + + You may convey a covered work in object code form under the terms +of sections 4 and 5, provided that you also convey the +machine-readable Corresponding Source under the terms of this License, +in one of these ways: + + a) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by the + Corresponding Source fixed on a durable physical medium + customarily used for software interchange. + + b) Convey the object code in, or embodied in, a physical product + (including a physical distribution medium), accompanied by a + written offer, valid for at least three years and valid for as + long as you offer spare parts or customer support for that product + model, to give anyone who possesses the object code either (1) a + copy of the Corresponding Source for all the software in the + product that is covered by this License, on a durable physical + medium customarily used for software interchange, for a price no + more than your reasonable cost of physically performing this + conveying of source, or (2) access to copy the + Corresponding Source from a network server at no charge. + + c) Convey individual copies of the object code with a copy of the + written offer to provide the Corresponding Source. This + alternative is allowed only occasionally and noncommercially, and + only if you received the object code with such an offer, in accord + with subsection 6b. + + d) Convey the object code by offering access from a designated + place (gratis or for a charge), and offer equivalent access to the + Corresponding Source in the same way through the same place at no + further charge. You need not require recipients to copy the + Corresponding Source along with the object code. If the place to + copy the object code is a network server, the Corresponding Source + may be on a different server (operated by you or a third party) + that supports equivalent copying facilities, provided you maintain + clear directions next to the object code saying where to find the + Corresponding Source. Regardless of what server hosts the + Corresponding Source, you remain obligated to ensure that it is + available for as long as needed to satisfy these requirements. + + e) Convey the object code using peer-to-peer transmission, provided + you inform other peers where the object code and Corresponding + Source of the work are being offered to the general public at no + charge under subsection 6d. + + A separable portion of the object code, whose source code is excluded +from the Corresponding Source as a System Library, need not be +included in conveying the object code work. + + A "User Product" is either (1) a "consumer product", which means any +tangible personal property which is normally used for personal, family, +or household purposes, or (2) anything designed or sold for incorporation +into a dwelling. In determining whether a product is a consumer product, +doubtful cases shall be resolved in favor of coverage. For a particular +product received by a particular user, "normally used" refers to a +typical or common use of that class of product, regardless of the status +of the particular user or of the way in which the particular user +actually uses, or expects or is expected to use, the product. A product +is a consumer product regardless of whether the product has substantial +commercial, industrial or non-consumer uses, unless such uses represent +the only significant mode of use of the product. + + "Installation Information" for a User Product means any methods, +procedures, authorization keys, or other information required to install +and execute modified versions of a covered work in that User Product from +a modified version of its Corresponding Source. The information must +suffice to ensure that the continued functioning of the modified object +code is in no case prevented or interfered with solely because +modification has been made. + + If you convey an object code work under this section in, or with, or +specifically for use in, a User Product, and the conveying occurs as +part of a transaction in which the right of possession and use of the +User Product is transferred to the recipient in perpetuity or for a +fixed term (regardless of how the transaction is characterized), the +Corresponding Source conveyed under this section must be accompanied +by the Installation Information. But this requirement does not apply +if neither you nor any third party retains the ability to install +modified object code on the User Product (for example, the work has +been installed in ROM). + + The requirement to provide Installation Information does not include a +requirement to continue to provide support service, warranty, or updates +for a work that has been modified or installed by the recipient, or for +the User Product in which it has been modified or installed. Access to a +network may be denied when the modification itself materially and +adversely affects the operation of the network or violates the rules and +protocols for communication across the network. + + Corresponding Source conveyed, and Installation Information provided, +in accord with this section must be in a format that is publicly +documented (and with an implementation available to the public in +source code form), and must require no special password or key for +unpacking, reading or copying. + + 7. Additional Terms. + + "Additional permissions" are terms that supplement the terms of this +License by making exceptions from one or more of its conditions. +Additional permissions that are applicable to the entire Program shall +be treated as though they were included in this License, to the extent +that they are valid under applicable law. If additional permissions +apply only to part of the Program, that part may be used separately +under those permissions, but the entire Program remains governed by +this License without regard to the additional permissions. + + When you convey a copy of a covered work, you may at your option +remove any additional permissions from that copy, or from any part of +it. (Additional permissions may be written to require their own +removal in certain cases when you modify the work.) You may place +additional permissions on material, added by you to a covered work, +for which you have or can give appropriate copyright permission. + + Notwithstanding any other provision of this License, for material you +add to a covered work, you may (if authorized by the copyright holders of +that material) supplement the terms of this License with terms: + + a) Disclaiming warranty or limiting liability differently from the + terms of sections 15 and 16 of this License; or + + b) Requiring preservation of specified reasonable legal notices or + author attributions in that material or in the Appropriate Legal + Notices displayed by works containing it; or + + c) Prohibiting misrepresentation of the origin of that material, or + requiring that modified versions of such material be marked in + reasonable ways as different from the original version; or + + d) Limiting the use for publicity purposes of names of licensors or + authors of the material; or + + e) Declining to grant rights under trademark law for use of some + trade names, trademarks, or service marks; or + + f) Requiring indemnification of licensors and authors of that + material by anyone who conveys the material (or modified versions of + it) with contractual assumptions of liability to the recipient, for + any liability that these contractual assumptions directly impose on + those licensors and authors. + + All other non-permissive additional terms are considered "further +restrictions" within the meaning of section 10. If the Program as you +received it, or any part of it, contains a notice stating that it is +governed by this License along with a term that is a further +restriction, you may remove that term. If a license document contains +a further restriction but permits relicensing or conveying under this +License, you may add to a covered work material governed by the terms +of that license document, provided that the further restriction does +not survive such relicensing or conveying. + + If you add terms to a covered work in accord with this section, you +must place, in the relevant source files, a statement of the +additional terms that apply to those files, or a notice indicating +where to find the applicable terms. + + Additional terms, permissive or non-permissive, may be stated in the +form of a separately written license, or stated as exceptions; +the above requirements apply either way. + + 8. Termination. + + You may not propagate or modify a covered work except as expressly +provided under this License. Any attempt otherwise to propagate or +modify it is void, and will automatically terminate your rights under +this License (including any patent licenses granted under the third +paragraph of section 11). + + However, if you cease all violation of this License, then your +license from a particular copyright holder is reinstated (a) +provisionally, unless and until the copyright holder explicitly and +finally terminates your license, and (b) permanently, if the copyright +holder fails to notify you of the violation by some reasonable means +prior to 60 days after the cessation. + + Moreover, your license from a particular copyright holder is +reinstated permanently if the copyright holder notifies you of the +violation by some reasonable means, this is the first time you have +received notice of violation of this License (for any work) from that +copyright holder, and you cure the violation prior to 30 days after +your receipt of the notice. + + Termination of your rights under this section does not terminate the +licenses of parties who have received copies or rights from you under +this License. If your rights have been terminated and not permanently +reinstated, you do not qualify to receive new licenses for the same +material under section 10. + + 9. Acceptance Not Required for Having Copies. + + You are not required to accept this License in order to receive or +run a copy of the Program. Ancillary propagation of a covered work +occurring solely as a consequence of using peer-to-peer transmission +to receive a copy likewise does not require acceptance. However, +nothing other than this License grants you permission to propagate or +modify any covered work. These actions infringe copyright if you do +not accept this License. Therefore, by modifying or propagating a +covered work, you indicate your acceptance of this License to do so. + + 10. Automatic Licensing of Downstream Recipients. + + Each time you convey a covered work, the recipient automatically +receives a license from the original licensors, to run, modify and +propagate that work, subject to this License. You are not responsible +for enforcing compliance by third parties with this License. + + An "entity transaction" is a transaction transferring control of an +organization, or substantially all assets of one, or subdividing an +organization, or merging organizations. If propagation of a covered +work results from an entity transaction, each party to that +transaction who receives a copy of the work also receives whatever +licenses to the work the party's predecessor in interest had or could +give under the previous paragraph, plus a right to possession of the +Corresponding Source of the work from the predecessor in interest, if +the predecessor has it or can get it with reasonable efforts. + + You may not impose any further restrictions on the exercise of the +rights granted or affirmed under this License. For example, you may +not impose a license fee, royalty, or other charge for exercise of +rights granted under this License, and you may not initiate litigation +(including a cross-claim or counterclaim in a lawsuit) alleging that +any patent claim is infringed by making, using, selling, offering for +sale, or importing the Program or any portion of it. + + 11. Patents. + + A "contributor" is a copyright holder who authorizes use under this +License of the Program or a work on which the Program is based. The +work thus licensed is called the contributor's "contributor version". + + A contributor's "essential patent claims" are all patent claims +owned or controlled by the contributor, whether already acquired or +hereafter acquired, that would be infringed by some manner, permitted +by this License, of making, using, or selling its contributor version, +but do not include claims that would be infringed only as a +consequence of further modification of the contributor version. For +purposes of this definition, "control" includes the right to grant +patent sublicenses in a manner consistent with the requirements of +this License. + + Each contributor grants you a non-exclusive, worldwide, royalty-free +patent license under the contributor's essential patent claims, to +make, use, sell, offer for sale, import and otherwise run, modify and +propagate the contents of its contributor version. + + In the following three paragraphs, a "patent license" is any express +agreement or commitment, however denominated, not to enforce a patent +(such as an express permission to practice a patent or covenant not to +sue for patent infringement). To "grant" such a patent license to a +party means to make such an agreement or commitment not to enforce a +patent against the party. + + If you convey a covered work, knowingly relying on a patent license, +and the Corresponding Source of the work is not available for anyone +to copy, free of charge and under the terms of this License, through a +publicly available network server or other readily accessible means, +then you must either (1) cause the Corresponding Source to be so +available, or (2) arrange to deprive yourself of the benefit of the +patent license for this particular work, or (3) arrange, in a manner +consistent with the requirements of this License, to extend the patent +license to downstream recipients. "Knowingly relying" means you have +actual knowledge that, but for the patent license, your conveying the +covered work in a country, or your recipient's use of the covered work +in a country, would infringe one or more identifiable patents in that +country that you have reason to believe are valid. + + If, pursuant to or in connection with a single transaction or +arrangement, you convey, or propagate by procuring conveyance of, a +covered work, and grant a patent license to some of the parties +receiving the covered work authorizing them to use, propagate, modify +or convey a specific copy of the covered work, then the patent license +you grant is automatically extended to all recipients of the covered +work and works based on it. + + A patent license is "discriminatory" if it does not include within +the scope of its coverage, prohibits the exercise of, or is +conditioned on the non-exercise of one or more of the rights that are +specifically granted under this License. You may not convey a covered +work if you are a party to an arrangement with a third party that is +in the business of distributing software, under which you make payment +to the third party based on the extent of your activity of conveying +the work, and under which the third party grants, to any of the +parties who would receive the covered work from you, a discriminatory +patent license (a) in connection with copies of the covered work +conveyed by you (or copies made from those copies), or (b) primarily +for and in connection with specific products or compilations that +contain the covered work, unless you entered into that arrangement, +or that patent license was granted, prior to 28 March 2007. + + Nothing in this License shall be construed as excluding or limiting +any implied license or other defenses to infringement that may +otherwise be available to you under applicable patent law. + + 12. No Surrender of Others' Freedom. + + If conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot convey a +covered work so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you may +not convey it at all. For example, if you agree to terms that obligate you +to collect a royalty for further conveying from those to whom you convey +the Program, the only way you could satisfy both those terms and this +License would be to refrain entirely from conveying the Program. + + 13. Use with the GNU Affero General Public License. + + Notwithstanding any other provision of this License, you have +permission to link or combine any covered work with a work licensed +under version 3 of the GNU Affero General Public License into a single +combined work, and to convey the resulting work. The terms of this +License will continue to apply to the part which is the covered work, +but the special requirements of the GNU Affero General Public License, +section 13, concerning interaction through a network will apply to the +combination as such. + + 14. Revised Versions of this License. + + The Free Software Foundation may publish revised and/or new versions of +the GNU General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + + Each version is given a distinguishing version number. If the +Program specifies that a certain numbered version of the GNU General +Public License "or any later version" applies to it, you have the +option of following the terms and conditions either of that numbered +version or of any later version published by the Free Software +Foundation. If the Program does not specify a version number of the +GNU General Public License, you may choose any version ever published +by the Free Software Foundation. + + If the Program specifies that a proxy can decide which future +versions of the GNU General Public License can be used, that proxy's +public statement of acceptance of a version permanently authorizes you +to choose that version for the Program. + + Later license versions may give you additional or different +permissions. However, no additional obligations are imposed on any +author or copyright holder as a result of your choosing to follow a +later version. + + 15. Disclaimer of Warranty. + + THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY +APPLICABLE LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT +HOLDERS AND/OR OTHER PARTIES PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY +OF ANY KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, +THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR +PURPOSE. THE ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM +IS WITH YOU. SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF +ALL NECESSARY SERVICING, REPAIR OR CORRECTION. + + 16. Limitation of Liability. + + IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MODIFIES AND/OR CONVEYS +THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, INCLUDING ANY +GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING OUT OF THE +USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED TO LOSS OF +DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY YOU OR THIRD +PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER PROGRAMS), +EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE POSSIBILITY OF +SUCH DAMAGES. + + 17. Interpretation of Sections 15 and 16. + + If the disclaimer of warranty and limitation of liability provided +above cannot be given local legal effect according to their terms, +reviewing courts shall apply local law that most closely approximates +an absolute waiver of all civil liability in connection with the +Program, unless a warranty or assumption of liability accompanies a +copy of the Program in return for a fee. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +state the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software: you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation, either version 3 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License + along with this program. If not, see <https://www.gnu.org/licenses/>. + +Also add information on how to contact you by electronic and paper mail. + + If the program does terminal interaction, make it output a short +notice like this when it starts in an interactive mode: + + <program> Copyright (C) <year> <name of author> + This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, your program's commands +might be different; for a GUI interface, you would use an "about box". + + You should also get your employer (if you work as a programmer) or school, +if any, to sign a "copyright disclaimer" for the program, if necessary. +For more information on this, and how to apply and follow the GNU GPL, see +<https://www.gnu.org/licenses/>. + + The GNU General Public License does not permit incorporating your program +into proprietary programs. If your program is a subroutine library, you +may consider it more useful to permit linking proprietary applications with +the library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. But first, please read +<https://www.gnu.org/licenses/why-not-lgpl.html>.