Skip to main content

weftos/
lib.rs

1//! WeftOS: A portable AI kernel for any project.
2//!
3//! Add WeftOS to your project to get process management, mesh networking,
4//! capability-based security, an append-only audit chain, and a cognitive
5//! substrate that learns your codebase.
6//!
7//! # Quick Start
8//!
9//! ```rust,no_run
10//! use weftos::WeftOs;
11//!
12//! #[tokio::main]
13//! async fn main() {
14//!     let os = WeftOs::boot_default().await.unwrap();
15//!     println!("WeftOS running: {} services", os.service_count());
16//!     os.shutdown().await.unwrap();
17//! }
18//! ```
19//!
20//! # Feature Flags
21//!
22//! - `native` (default) -- Tokio runtime, native file I/O
23//! - `exochain` -- Append-only hash chain with Ed25519 + ML-DSA-65 signing
24//! - `cluster` -- Multi-node clustering via ruvector
25//! - `mesh` -- Encrypted peer-to-peer mesh networking
26//! - `ecc` -- Ephemeral Causal Cognition (causal DAG, HNSW, cognitive tick)
27//! - `wasm-sandbox` -- Wasmtime-based tool execution
28//! - `containers` -- Docker/Podman sidecar orchestration
29//! - `os-patterns` -- Self-healing, metrics, reliable IPC, timers
30//! - `full` -- Everything
31//!
32//! ## Crate Ecosystem
33//!
34//! WeftOS is built from these crates:
35//!
36//! | Crate | Role |
37//! |-------|------|
38//! | [`weftos`](https://crates.io/crates/weftos) | Product facade -- re-exports kernel, core, types |
39//! | [`clawft-kernel`](https://crates.io/crates/clawft-kernel) | Kernel: processes, services, governance, mesh, ExoChain |
40//! | [`clawft-core`](https://crates.io/crates/clawft-core) | Agent framework: pipeline, context, tools, skills |
41//! | [`clawft-types`](https://crates.io/crates/clawft-types) | Shared type definitions |
42//! | [`clawft-platform`](https://crates.io/crates/clawft-platform) | Platform abstraction (native/WASM/browser) |
43//! | [`clawft-plugin`](https://crates.io/crates/clawft-plugin) | Plugin SDK for tools, channels, and extensions |
44//! | [`clawft-llm`](https://crates.io/crates/clawft-llm) | LLM provider abstraction (11 providers + local) |
45//! | [`exo-resource-tree`](https://crates.io/crates/exo-resource-tree) | Hierarchical resource namespace with Merkle integrity |
46//!
47//! Source: <https://github.com/weave-logic-ai/weftos>
48
49pub mod init;
50
51// Re-export the kernel under the weftos namespace
52pub use clawft_kernel as kernel;
53
54// Re-export key types at the top level for ergonomic API
55pub use clawft_kernel::{
56    Kernel, KernelState,
57    // Process management
58    Pid, ProcessEntry, ProcessState, ProcessTable,
59    // Agent supervision
60    AgentSupervisor, SpawnBackend, SpawnRequest, SpawnResult,
61    // Capabilities
62    AgentCapabilities, CapabilityChecker, IpcScope, ResourceLimits,
63    // IPC
64    KernelIpc, KernelMessage, KernelSignal, MessagePayload, MessageTarget,
65    GlobalPid,
66    // Services
67    ServiceRegistry, ServiceEntry, SystemService,
68    // Health
69    HealthSystem, HealthStatus, OverallHealth,
70    // Governance
71    GovernanceEngine, GovernanceRule, GovernanceRequest, GovernanceDecision,
72    EffectVector,
73    // Topics
74    TopicRouter, Subscription,
75    // Cluster
76    ClusterConfig, ClusterMembership, NodeState, PeerNode,
77    // Config
78    KernelConfigExt,
79    // Console
80    BootEvent, BootPhase, BootLog,
81    // Error
82    KernelError, KernelResult,
83    // Cron
84    CronService,
85    // Apps
86    AppManager, AppManifest, InstalledApp, AppState,
87    // Containers
88    ContainerManager, ContainerConfig, ContainerState,
89};
90
91// Conditional re-exports
92#[cfg(feature = "exochain")]
93pub use clawft_kernel::{
94    ChainManager, ChainEvent, TreeManager, TreeStats,
95    GateBackend, GateDecision, GovernanceGate, CapabilityGate,
96};
97
98#[cfg(feature = "ecc")]
99pub use clawft_kernel::{
100    CausalGraph, CausalEdgeType, CognitiveTick, CognitiveTickConfig,
101    CrossRef, CrossRefStore, CrossRefType, UniversalNodeId,
102    HnswService, HnswServiceConfig, HnswSearchResult,
103    ImpulseQueue, ImpulseType,
104    EccCalibration,
105};
106
107#[cfg(feature = "mesh")]
108pub use clawft_kernel::{
109    MeshError, MeshPeer, MeshStream, MeshTransport, TransportListener,
110    WeftHandshake, MeshConnectionPool, TcpTransport,
111    DiscoveryCoordinator, BootstrapDiscovery,
112    MeshIpcEnvelope, DedupFilter,
113    HeartbeatTracker, HeartbeatConfig, HeartbeatState,
114    DistributedProcessTable, ClusterServiceRegistry,
115};
116
117#[cfg(feature = "os-patterns")]
118pub use clawft_kernel::{
119    MetricsRegistry, LogService, TimerService,
120    DeadLetterQueue, ReliableQueue, NamedPipeRegistry,
121    ReconciliationController,
122};
123
124use std::path::Path;
125
126#[cfg(feature = "native")]
127use std::sync::Arc;
128
129#[cfg(feature = "native")]
130use clawft_platform::NativePlatform;
131
132/// The main WeftOS instance -- boots and manages the kernel.
133#[cfg(feature = "native")]
134pub struct WeftOs {
135    kernel: clawft_kernel::Kernel<NativePlatform>,
136    project_root: std::path::PathBuf,
137}
138
139#[cfg(feature = "native")]
140impl WeftOs {
141    /// Boot WeftOS with default configuration.
142    pub async fn boot_default() -> Result<Self, KernelError> {
143        Self::boot_in(std::env::current_dir().unwrap_or_else(|_| ".".into())).await
144    }
145
146    /// Boot WeftOS in a specific project directory.
147    pub async fn boot_in(project_root: impl Into<std::path::PathBuf>) -> Result<Self, KernelError> {
148        let project_root = project_root.into();
149        let config = clawft_types::config::Config::default();
150        let kernel_config = clawft_types::config::KernelConfig::default();
151        let platform = Arc::new(NativePlatform::new());
152
153        let kernel = Kernel::boot(config, kernel_config, platform).await?;
154
155        Ok(Self { kernel, project_root })
156    }
157
158    /// Boot WeftOS with custom configuration.
159    pub async fn boot_with(
160        config: clawft_types::config::Config,
161        kernel_config: clawft_types::config::KernelConfig,
162        project_root: impl Into<std::path::PathBuf>,
163    ) -> Result<Self, KernelError> {
164        let project_root = project_root.into();
165        let platform = Arc::new(NativePlatform::new());
166        let kernel = Kernel::boot(config, kernel_config, platform).await?;
167        Ok(Self { kernel, project_root })
168    }
169
170    /// Get the project root directory.
171    pub fn project_root(&self) -> &Path {
172        &self.project_root
173    }
174
175    /// Get the kernel state.
176    pub fn state(&self) -> &KernelState {
177        self.kernel.state()
178    }
179
180    /// Get the number of registered services.
181    pub fn service_count(&self) -> usize {
182        self.kernel.services().len()
183    }
184
185    /// Get the number of active processes.
186    pub fn process_count(&self) -> usize {
187        self.kernel.process_table().len()
188    }
189
190    /// Get a reference to the underlying kernel.
191    pub fn kernel(&self) -> &Kernel<NativePlatform> {
192        &self.kernel
193    }
194
195    /// Get a mutable reference to the underlying kernel.
196    pub fn kernel_mut(&mut self) -> &mut Kernel<NativePlatform> {
197        &mut self.kernel
198    }
199
200    /// Shut down WeftOS gracefully.
201    pub async fn shutdown(mut self) -> KernelResult<()> {
202        tracing::info!("WeftOS shutting down");
203        self.kernel.shutdown().await
204    }
205}
206
207/// Version information.
208pub const VERSION: &str = env!("CARGO_PKG_VERSION");
209
210/// Check if WeftOS is initialized in the given directory.
211pub fn is_initialized(path: impl AsRef<Path>) -> bool {
212    path.as_ref().join(".weftos").exists()
213        || path.as_ref().join("weave.toml").exists()
214}
215
216#[cfg(test)]
217mod tests {
218    use super::*;
219
220    #[test]
221    fn is_not_initialized_in_random_dir() {
222        assert!(!is_initialized("/tmp/nonexistent-weftos-test"));
223    }
224
225    #[test]
226    fn init_creates_structure() {
227        let dir = std::env::temp_dir().join("weftos-test-init");
228        let _ = std::fs::remove_dir_all(&dir);
229        std::fs::create_dir_all(&dir).unwrap();
230
231        let result = init::init_project(&dir).unwrap();
232        assert!(result.weftos_dir_created);
233        assert!(result.weave_toml_created);
234        assert!(dir.join(".weftos").exists());
235        assert!(dir.join("weave.toml").exists());
236        assert!(dir.join(".weftos/chain").exists());
237        assert!(dir.join(".weftos/logs").exists());
238
239        // Cleanup
240        std::fs::remove_dir_all(&dir).ok();
241    }
242
243    #[test]
244    fn init_detects_rust_project() {
245        let dir = std::env::temp_dir().join("weftos-test-rust");
246        let _ = std::fs::remove_dir_all(&dir);
247        std::fs::create_dir_all(&dir).unwrap();
248        std::fs::write(dir.join("Cargo.toml"), "[package]\nname = \"test\"").unwrap();
249
250        let _result = init::init_project(&dir).unwrap();
251        let config = std::fs::read_to_string(dir.join("weave.toml")).unwrap();
252        assert!(config.contains("language = \"rust\""));
253        assert!(config.contains("*.rs"));
254
255        std::fs::remove_dir_all(&dir).ok();
256    }
257
258    #[tokio::test]
259    async fn weftos_boots_and_reports_state() {
260        let os = WeftOs::boot_default().await.unwrap();
261        assert!(matches!(os.state(), KernelState::Running));
262        assert!(os.service_count() > 0);
263        os.shutdown().await.unwrap();
264    }
265}