Files
optimclaw/src/error.rs
T
e843c18141 feat: add libSQL/Turso embedded database backend (#47)
* feat: add libSQL/Turso database backend with full feature parity

Introduce a Database trait abstraction (~60 async methods) enabling
compile-time backend selection between PostgreSQL and libSQL/Turso.
Convert all modules from concrete Store to Arc<dyn Database>, add
LibSqlSecretsStore and LibSqlWasmToolStore implementations, wire
libsql stores throughout CLI and main entry points, and make the
setup wizard backend-agnostic.

Key changes:
- src/db/: Database trait, PostgresDatabase adapter, LibSqlBackend
  with native SQLite-dialect SQL, and idempotent migration system
- src/secrets/store.rs: LibSqlSecretsStore (all 8 trait methods)
- src/tools/wasm/storage.rs: LibSqlWasmToolStore (all 7 trait methods)
- src/main.rs, cli/tool.rs, cli/mcp.rs: backend-conditional wiring
- src/setup/channels.rs: SecretsContext uses Arc<dyn SecretsStore>
- Feature-gate postgres-only tests and examples

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* feat: enable onboarding wizard for libSQL builds

Refactor the setup wizard to work with both postgres and libsql feature
flags. Previously the wizard was gated behind #[cfg(feature = "postgres")]
only, so libsql-only builds would print an error on `ironclaw onboard`.

- Add libsql fields to Settings (database_backend, libsql_path, libsql_url)
- Split wizard database/migration/secrets methods into feature-gated variants
- Add step_database_libsql() with local path and Turso remote replica prompts
- Update setup/mod.rs and main.rs feature gates to any(postgres, libsql)
- Extend check_onboard_needed() to detect libsql database presence

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: address PR review feedback for libSQL backend

- P0: Switch libsql_backend to connection-per-operation pattern to fix
  shared Connection concurrency issue across tokio tasks
- P0: Wrap secrets store INSERT+SELECT in transaction to fix TOCTOU race
- P0: Document encryption-at-rest limitations and json_patch divergence
- P1: Fix get_opt_text removing .filter(|s| !s.is_empty()) that conflated
  empty strings with NULL
- P1: Replace datetime('now') with fmt_ts(&Utc::now()) for consistent
  RFC 3339 timestamps across all queries
- P2: Use explicit _rowid column in FTS5 triggers and joins for stability
  across VACUUM operations
- P2: Add tracing::warn when embedding provided but vector search disabled
  in hybrid_search
- Extract shared connect_from_config() helper to deduplicate DB connection
  logic across main.rs, cli/config.rs, and cli/mcp.rs

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: add missing JobContext fields and resolve fmt/clippy warnings

Add total_tokens_used and max_tokens fields to JobContext in
libsql_backend.rs, apply cargo fmt, and fix clippy warnings.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: review fixes for libSQL backend (shared connections, panics, indexes)

- Replace .expect() with proper error propagation in 3 call sites
- Share Arc<Database> between backend and stores instead of single Connection
- Add connect-per-operation pattern to LibSqlSecretsStore and LibSqlWasmToolStore
- Wrap store() INSERT + SELECT-back in a transaction
- Add ~22 missing indexes for parity with PostgreSQL schema
- Add 18 leak_detection_patterns seed rows matching PostgreSQL V2 migration
- Fix super:: import to use crate:: style
- Gate mask_password_in_url behind #[cfg(feature = "postgres")]
- Rewrite secrets store init with or_else chain for runtime backend selection

Co-Authored-By: Claude Opus 4.6 <[email protected]>

* fix: Resolve clippy lints (collapsible_if, too_many_arguments)

Collapse nested if blocks into let_chains to satisfy clippy's
collapsible_if lint (CI uses -D warnings). Suppress too_many_arguments
on libsql_row_to_tool_at since refactoring the positional index
pattern would be a larger change.

Co-Authored-By: Claude Opus 4.6 <[email protected]>

---------

Co-authored-by: Claude Opus 4.6 <[email protected]>
Co-authored-by: Illia Polosukhin <[email protected]>
2026-02-14 02:05:05 +00:00

373 lines
10 KiB
Rust

//! Error types for IronClaw.
use std::time::Duration;
use uuid::Uuid;
/// Top-level error type for the agent.
#[derive(Debug, thiserror::Error)]
pub enum Error {
#[error("Configuration error: {0}")]
Config(#[from] ConfigError),
#[error("Database error: {0}")]
Database(#[from] DatabaseError),
#[error("Channel error: {0}")]
Channel(#[from] ChannelError),
#[error("LLM error: {0}")]
Llm(#[from] LlmError),
#[error("Tool error: {0}")]
Tool(#[from] ToolError),
#[error("Safety error: {0}")]
Safety(#[from] SafetyError),
#[error("Job error: {0}")]
Job(#[from] JobError),
#[error("Estimation error: {0}")]
Estimation(#[from] EstimationError),
#[error("Evaluation error: {0}")]
Evaluation(#[from] EvaluationError),
#[error("Repair error: {0}")]
Repair(#[from] RepairError),
#[error("Workspace error: {0}")]
Workspace(#[from] WorkspaceError),
#[error("Orchestrator error: {0}")]
Orchestrator(#[from] OrchestratorError),
#[error("Worker error: {0}")]
Worker(#[from] WorkerError),
}
/// Configuration-related errors.
#[derive(Debug, thiserror::Error)]
pub enum ConfigError {
#[error("Missing required environment variable: {0}")]
MissingEnvVar(String),
#[error("Missing required configuration: {key}. {hint}")]
MissingRequired { key: String, hint: String },
#[error("Invalid configuration value for {key}: {message}")]
InvalidValue { key: String, message: String },
#[error("Failed to parse configuration: {0}")]
ParseError(String),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
/// Database-related errors.
#[derive(Debug, thiserror::Error)]
pub enum DatabaseError {
#[error("Connection pool error: {0}")]
Pool(String),
#[error("Query failed: {0}")]
Query(String),
#[error("Entity not found: {entity} with id {id}")]
NotFound { entity: String, id: String },
#[error("Constraint violation: {0}")]
Constraint(String),
#[error("Migration failed: {0}")]
Migration(String),
#[error("Serialization error: {0}")]
Serialization(String),
#[cfg(feature = "postgres")]
#[error("PostgreSQL error: {0}")]
Postgres(#[from] tokio_postgres::Error),
#[cfg(feature = "postgres")]
#[error("Pool build error: {0}")]
PoolBuild(#[from] deadpool_postgres::BuildError),
#[cfg(feature = "postgres")]
#[error("Pool runtime error: {0}")]
PoolRuntime(#[from] deadpool_postgres::PoolError),
#[cfg(feature = "libsql")]
#[error("LibSQL error: {0}")]
LibSql(#[from] libsql::Error),
}
/// Channel-related errors.
#[derive(Debug, thiserror::Error)]
pub enum ChannelError {
#[error("Channel {name} failed to start: {reason}")]
StartupFailed { name: String, reason: String },
#[error("Channel {name} disconnected: {reason}")]
Disconnected { name: String, reason: String },
#[error("Failed to send response on channel {name}: {reason}")]
SendFailed { name: String, reason: String },
#[error("Invalid message format: {0}")]
InvalidMessage(String),
#[error("Authentication failed for channel {name}: {reason}")]
AuthFailed { name: String, reason: String },
#[error("Rate limited on channel {name}")]
RateLimited { name: String },
#[error("HTTP error: {0}")]
Http(String),
#[error("Channel health check failed: {name}")]
HealthCheckFailed { name: String },
}
/// LLM provider errors.
#[derive(Debug, thiserror::Error)]
pub enum LlmError {
#[error("Provider {provider} request failed: {reason}")]
RequestFailed { provider: String, reason: String },
#[error("Provider {provider} rate limited, retry after {retry_after:?}")]
RateLimited {
provider: String,
retry_after: Option<Duration>,
},
#[error("Invalid response from {provider}: {reason}")]
InvalidResponse { provider: String, reason: String },
#[error("Context length exceeded: {used} tokens used, {limit} allowed")]
ContextLengthExceeded { used: usize, limit: usize },
#[error("Model {model} not available on provider {provider}")]
ModelNotAvailable { provider: String, model: String },
#[error("Authentication failed for provider {provider}")]
AuthFailed { provider: String },
#[error("Session expired for provider {provider}")]
SessionExpired { provider: String },
#[error("Session renewal failed for provider {provider}: {reason}")]
SessionRenewalFailed { provider: String, reason: String },
#[error("HTTP error: {0}")]
Http(#[from] reqwest::Error),
#[error("JSON error: {0}")]
Json(#[from] serde_json::Error),
#[error("IO error: {0}")]
Io(#[from] std::io::Error),
}
/// Tool execution errors.
#[derive(Debug, thiserror::Error)]
pub enum ToolError {
#[error("Tool {name} not found")]
NotFound { name: String },
#[error("Tool {name} execution failed: {reason}")]
ExecutionFailed { name: String, reason: String },
#[error("Tool {name} timed out after {timeout:?}")]
Timeout { name: String, timeout: Duration },
#[error("Invalid parameters for tool {name}: {reason}")]
InvalidParameters { name: String, reason: String },
#[error("Tool {name} is disabled: {reason}")]
Disabled { name: String, reason: String },
#[error("Sandbox error for tool {name}: {reason}")]
Sandbox { name: String, reason: String },
#[error("Tool {name} requires authentication")]
AuthRequired { name: String },
#[error("Tool builder failed: {0}")]
BuilderFailed(String),
}
/// Safety/sanitization errors.
#[derive(Debug, thiserror::Error)]
pub enum SafetyError {
#[error("Potential prompt injection detected: {pattern}")]
InjectionDetected { pattern: String },
#[error("Output exceeded maximum length: {length} > {max}")]
OutputTooLarge { length: usize, max: usize },
#[error("Blocked content pattern detected: {pattern}")]
BlockedContent { pattern: String },
#[error("Validation failed: {reason}")]
ValidationFailed { reason: String },
#[error("Policy violation: {rule}")]
PolicyViolation { rule: String },
}
/// Job-related errors.
#[derive(Debug, thiserror::Error)]
pub enum JobError {
#[error("Job {id} not found")]
NotFound { id: Uuid },
#[error("Job {id} already in state {state}, cannot transition to {target}")]
InvalidTransition {
id: Uuid,
state: String,
target: String,
},
#[error("Job {id} failed: {reason}")]
Failed { id: Uuid, reason: String },
#[error("Job {id} stuck for {duration:?}")]
Stuck { id: Uuid, duration: Duration },
#[error("Maximum parallel jobs ({max}) exceeded")]
MaxJobsExceeded { max: usize },
#[error("Job {id} context error: {reason}")]
ContextError { id: Uuid, reason: String },
}
/// Estimation errors.
#[derive(Debug, thiserror::Error)]
pub enum EstimationError {
#[error("Insufficient data for estimation: need {needed} samples, have {have}")]
InsufficientData { needed: usize, have: usize },
#[error("Estimation calculation failed: {reason}")]
CalculationFailed { reason: String },
#[error("Invalid estimation parameters: {reason}")]
InvalidParameters { reason: String },
}
/// Evaluation errors.
#[derive(Debug, thiserror::Error)]
pub enum EvaluationError {
#[error("Evaluation failed for job {job_id}: {reason}")]
Failed { job_id: Uuid, reason: String },
#[error("Missing required evaluation data: {field}")]
MissingData { field: String },
#[error("Invalid evaluation criteria: {reason}")]
InvalidCriteria { reason: String },
}
/// Self-repair errors.
#[derive(Debug, thiserror::Error)]
pub enum RepairError {
#[error("Repair failed for {target_type} {target_id}: {reason}")]
Failed {
target_type: String,
target_id: Uuid,
reason: String,
},
#[error("Maximum repair attempts ({max}) exceeded for {target_type} {target_id}")]
MaxAttemptsExceeded {
target_type: String,
target_id: Uuid,
max: u32,
},
#[error("Cannot diagnose issue for {target_type} {target_id}: {reason}")]
DiagnosisFailed {
target_type: String,
target_id: Uuid,
reason: String,
},
}
/// Workspace/memory errors.
#[derive(Debug, thiserror::Error)]
pub enum WorkspaceError {
#[error("Document not found: {doc_type} for user {user_id}")]
DocumentNotFound { doc_type: String, user_id: String },
#[error("Search failed: {reason}")]
SearchFailed { reason: String },
#[error("Embedding generation failed: {reason}")]
EmbeddingFailed { reason: String },
#[error("Document chunking failed: {reason}")]
ChunkingFailed { reason: String },
#[error("Invalid document type: {doc_type}")]
InvalidDocType { doc_type: String },
#[error("Workspace not initialized for user {user_id}")]
NotInitialized { user_id: String },
#[error("Heartbeat error: {reason}")]
HeartbeatError { reason: String },
}
/// Orchestrator errors (internal API, container management).
#[derive(Debug, thiserror::Error)]
pub enum OrchestratorError {
#[error("Container creation failed for job {job_id}: {reason}")]
ContainerCreationFailed { job_id: Uuid, reason: String },
#[error("Container not found for job {job_id}")]
ContainerNotFound { job_id: Uuid },
#[error("Container for job {job_id} is in unexpected state: {state}")]
InvalidContainerState { job_id: Uuid, state: String },
#[error("Worker authentication failed: {reason}")]
AuthFailed { reason: String },
#[error("Internal API error: {reason}")]
ApiError { reason: String },
#[error("Docker error: {reason}")]
Docker { reason: String },
#[error("Job {job_id} timed out in container")]
ContainerTimeout { job_id: Uuid },
}
/// Worker errors (container-side execution).
#[derive(Debug, thiserror::Error)]
pub enum WorkerError {
#[error("Failed to connect to orchestrator at {url}: {reason}")]
ConnectionFailed { url: String, reason: String },
#[error("LLM proxy request failed: {reason}")]
LlmProxyFailed { reason: String },
#[error("Secret resolution failed for {secret_name}: {reason}")]
SecretResolveFailed { secret_name: String, reason: String },
#[error("Orchestrator returned error for job {job_id}: {reason}")]
OrchestratorRejected { job_id: Uuid, reason: String },
#[error("Worker execution failed: {reason}")]
ExecutionFailed { reason: String },
#[error("Missing worker token (IRONCLAW_WORKER_TOKEN not set)")]
MissingToken,
}
/// Result type alias for the agent.
pub type Result<T> = std::result::Result<T, Error>;