File size: 21,511 Bytes
1269259 | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496 497 498 499 500 501 502 503 504 505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558 559 560 561 562 563 564 565 566 567 568 569 570 571 572 573 574 575 576 577 578 579 580 581 582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616 617 618 619 620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656 657 658 659 660 661 662 663 664 665 666 667 | // SPF Smart Gateway - LMDB Filesystem
// Copyright 2026 Joseph Stone - All Rights Reserved
//
// Real filesystem backed by LMDB using heed.
// Provides: read, write, mkdir, ls, rm, stat, rename
// Hybrid storage: small files in LMDB, large files on disk.
// All operations gated through SPF complexity formula.
use anyhow::{anyhow, Result};
use heed::types::{SerdeBincode, Str, Bytes};
use heed::{Database, Env, EnvOpenOptions};
use serde::{Deserialize, Serialize};
use sha2::{Digest, Sha256};
use std::collections::HashSet;
use std::path::{Path, PathBuf};
use std::time::{SystemTime, UNIX_EPOCH};
// ============================================================================
// CONSTANTS
// ============================================================================
const MAX_INLINE_SIZE: usize = 1_048_576; // 1MB - files larger go to disk
const MAP_SIZE: usize = 4 * 1024 * 1024 * 1024; // 4GB
const MAX_DBS: u32 = 8;
// ============================================================================
// TYPES
// ============================================================================
#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
pub enum FileType {
File,
Directory,
Symlink,
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct FileMetadata {
pub file_type: FileType,
pub size: u64,
pub mode: u32,
pub created_at: i64,
pub modified_at: i64,
pub checksum: Option<String>,
pub version: u64,
pub vector_id: Option<String>,
pub real_path: Option<String>,
}
impl FileMetadata {
pub fn new_file(size: u64) -> Self {
let now = unix_now();
Self {
file_type: FileType::File,
size,
mode: 0o644,
created_at: now,
modified_at: now,
checksum: None,
version: 1,
vector_id: None,
real_path: None,
}
}
pub fn new_dir() -> Self {
let now = unix_now();
Self {
file_type: FileType::Directory,
size: 0,
mode: 0o755,
created_at: now,
modified_at: now,
checksum: None,
version: 1,
vector_id: None,
real_path: None,
}
}
}
// ============================================================================
// SPF FILESYSTEM
// ============================================================================
pub struct SpfFs {
env: Env,
metadata: Database<Str, SerdeBincode<FileMetadata>>,
content: Database<Str, Bytes>,
index: Database<Str, Str>,
blob_dir: PathBuf,
}
impl SpfFs {
/// Open or create the LMDB filesystem at the given path
pub fn open(storage_path: &Path) -> Result<Self> {
let fs_path = storage_path.join("SPF_FS.DB");
let blob_dir = storage_path.join("blobs");
std::fs::create_dir_all(&fs_path)?;
std::fs::create_dir_all(&blob_dir)?;
let env = unsafe {
EnvOpenOptions::new()
.map_size(MAP_SIZE)
.max_dbs(MAX_DBS)
.open(&fs_path)?
};
let mut wtxn = env.write_txn()?;
let metadata = env.create_database(&mut wtxn, Some("fs_metadata"))?;
let content = env.create_database(&mut wtxn, Some("fs_content"))?;
let index = env.create_database(&mut wtxn, Some("fs_index"))?;
wtxn.commit()?;
let fs = Self { env, metadata, content, index, blob_dir };
// Initialize root structure if empty
if !fs.exists("/")? {
fs.init_structure()?;
}
log::info!("SPF FS opened at {:?}", fs_path);
Ok(fs)
}
/// Initialize the virtual filesystem structure
fn init_structure(&self) -> Result<()> {
log::info!("Initializing SPF FS structure...");
// Create root directories — mount point stubs per build spec
self.mkdir_internal("/")?;
self.mkdir_internal("/system")?; // LMDB 1 — read-only system
self.mkdir_internal("/config")?; // mount → LMDB 2
self.mkdir_internal("/tools")?; // legacy — no active mount
self.mkdir_internal("/tmp")?; // mount → LMDB 4 (writable TMP)
self.mkdir_internal("/home")?;
self.mkdir_internal("/home/agent")?; // mount → LMDB 5
// /home/agent/ full tree (build spec lines 1230-1249 + containment spec)
self.mkdir_internal("/home/agent/.claude")?;
self.mkdir_internal("/home/agent/.claude/projects")?;
self.mkdir_internal("/home/agent/.claude/file-history")?;
self.mkdir_internal("/home/agent/.claude/paste-cache")?;
self.mkdir_internal("/home/agent/.claude/session-env")?;
self.mkdir_internal("/home/agent/.claude/todos")?;
self.mkdir_internal("/home/agent/.claude/plans")?;
self.mkdir_internal("/home/agent/.claude/tasks")?;
self.mkdir_internal("/home/agent/.claude/shell-snapshots")?;
self.mkdir_internal("/home/agent/.claude/statsig")?;
self.mkdir_internal("/home/agent/.claude/telemetry")?;
self.mkdir_internal("/home/agent/bin")?;
self.mkdir_internal("/home/agent/bin/claude-code")?;
self.mkdir_internal("/home/agent/tmp")?; // routes to /tmp (LMDB 4)
self.mkdir_internal("/home/agent/.config")?;
self.mkdir_internal("/home/agent/.config/settings")?;
self.mkdir_internal("/home/agent/.local")?;
self.mkdir_internal("/home/agent/.local/bin")?;
self.mkdir_internal("/home/agent/.local/share")?;
self.mkdir_internal("/home/agent/.local/share/history")?;
self.mkdir_internal("/home/agent/.local/share/data")?;
self.mkdir_internal("/home/agent/.local/state")?;
self.mkdir_internal("/home/agent/.local/state/sessions")?;
self.mkdir_internal("/home/agent/.cache")?;
self.mkdir_internal("/home/agent/.cache/context")?;
self.mkdir_internal("/home/agent/.cache/tmp")?;
self.mkdir_internal("/home/agent/.memory")?;
self.mkdir_internal("/home/agent/.memory/facts")?;
self.mkdir_internal("/home/agent/.memory/instructions")?;
self.mkdir_internal("/home/agent/.memory/preferences")?;
self.mkdir_internal("/home/agent/.memory/pinned")?;
self.mkdir_internal("/home/agent/.ssh")?;
self.mkdir_internal("/home/agent/Documents")?;
self.mkdir_internal("/home/agent/Documents/notes")?;
self.mkdir_internal("/home/agent/Documents/templates")?;
self.mkdir_internal("/home/agent/Projects")?; // future: PROJECTS LMDB gateway
self.mkdir_internal("/home/agent/workspace")?;
self.mkdir_internal("/home/agent/workspace/current")?;
log::info!("SPF FS structure initialized");
Ok(())
}
/// Internal mkdir without parent creation
fn mkdir_internal(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
let mut wtxn = self.env.write_txn()?;
self.metadata.put(&mut wtxn, &path, &FileMetadata::new_dir())?;
wtxn.commit()?;
Ok(())
}
// ========================================================================
// CORE OPERATIONS
// ========================================================================
/// Check if path exists
pub fn exists(&self, path: &str) -> Result<bool> {
let path = normalize_path(path);
let rtxn = self.env.read_txn()?;
Ok(self.metadata.get(&rtxn, &path)?.is_some())
}
/// Get file/directory metadata
pub fn stat(&self, path: &str) -> Result<Option<FileMetadata>> {
let path = normalize_path(path);
let rtxn = self.env.read_txn()?;
Ok(self.metadata.get(&rtxn, &path)?)
}
/// Read file content
pub fn read(&self, path: &str) -> Result<Vec<u8>> {
let path = normalize_path(path);
let rtxn = self.env.read_txn()?;
let meta = self.metadata.get(&rtxn, &path)?
.ok_or_else(|| anyhow!("File not found: {}", path))?;
if meta.file_type != FileType::File {
return Err(anyhow!("Not a file: {}", path));
}
// Hybrid: check if content is on disk
if let Some(ref real_path) = meta.real_path {
return Ok(std::fs::read(real_path)?);
}
// Content is in LMDB
let content = self.content.get(&rtxn, &path)?
.ok_or_else(|| anyhow!("Content missing for: {}", path))?;
Ok(content.to_vec())
}
/// Write file content (creates parent directories if needed)
pub fn write(&self, path: &str, data: &[u8]) -> Result<()> {
let path = normalize_path(path);
// Ensure parent directories exist
if let Some(parent) = parent_path(&path) {
self.mkdir_p(&parent)?;
}
let checksum = sha256_hex(data);
let size = data.len() as u64;
let mut meta = self.stat(&path)?.unwrap_or_else(|| FileMetadata::new_file(size));
meta.size = size;
meta.modified_at = unix_now();
meta.checksum = Some(checksum.clone());
meta.version += 1;
meta.file_type = FileType::File;
let mut wtxn = self.env.write_txn()?;
// Hybrid storage: large files go to disk
if data.len() > MAX_INLINE_SIZE {
let blob_path = self.blob_dir.join(&checksum);
// Write blob with cleanup on failure (handles disk full)
if let Err(e) = std::fs::write(&blob_path, data) {
let _ = std::fs::remove_file(&blob_path);
return Err(anyhow!("Failed to write blob (disk full?): {}", e));
}
meta.real_path = Some(blob_path.to_string_lossy().to_string());
// Don't store content in LMDB
let _ = self.content.delete(&mut wtxn, &path);
} else {
meta.real_path = None;
self.content.put(&mut wtxn, &path, data)?;
}
self.metadata.put(&mut wtxn, &path, &meta)?;
wtxn.commit()?;
Ok(())
}
/// Create directory (single level)
pub fn mkdir(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
if self.exists(&path)? {
return Err(anyhow!("Already exists: {}", path));
}
// Ensure parent exists
if let Some(parent) = parent_path(&path) {
if !self.exists(&parent)? {
return Err(anyhow!("Parent directory does not exist: {}", parent));
}
}
self.mkdir_internal(&path)
}
/// Create directory and all parents (mkdir -p)
pub fn mkdir_p(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
if self.exists(&path)? {
return Ok(());
}
// Build path components and create each
let mut current = String::new();
for component in path.split('/').filter(|s| !s.is_empty()) {
current.push('/');
current.push_str(component);
if !self.exists(¤t)? {
self.mkdir_internal(¤t)?;
}
}
Ok(())
}
/// List directory contents
pub fn ls(&self, path: &str) -> Result<Vec<(String, FileMetadata)>> {
let path = normalize_path(path);
let rtxn = self.env.read_txn()?;
// Verify it's a directory
let meta = self.metadata.get(&rtxn, &path)?
.ok_or_else(|| anyhow!("Directory not found: {}", path))?;
if meta.file_type != FileType::Directory {
return Err(anyhow!("Not a directory: {}", path));
}
// Prefix scan for children
let prefix = if path == "/" { "/".to_string() } else { format!("{}/", path) };
let depth = prefix.matches('/').count();
let mut results = Vec::new();
let mut seen = HashSet::new();
let iter = self.metadata.iter(&rtxn)?;
for item in iter {
let (key, value) = item?;
// Check if this is a direct child
if key.starts_with(&prefix) && key != path {
let child_depth = key.matches('/').count();
// Only direct children (one level deeper)
if child_depth == depth {
let name = key.rsplit('/').next().unwrap_or(key);
if seen.insert(name.to_string()) {
results.push((name.to_string(), value.clone()));
}
}
}
}
Ok(results)
}
/// Remove file or empty directory
pub fn rm(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
if path == "/" {
return Err(anyhow!("Cannot remove root directory"));
}
let rtxn = self.env.read_txn()?;
let meta = self.metadata.get(&rtxn, &path)?
.ok_or_else(|| anyhow!("Not found: {}", path))?;
// If directory, check if empty
if meta.file_type == FileType::Directory {
let children = self.ls(&path)?;
if !children.is_empty() {
return Err(anyhow!("Directory not empty: {}", path));
}
}
// Remove blob file if exists
if let Some(ref real_path) = meta.real_path {
let _ = std::fs::remove_file(real_path);
}
drop(rtxn);
let mut wtxn = self.env.write_txn()?;
self.metadata.delete(&mut wtxn, &path)?;
let _ = self.content.delete(&mut wtxn, &path);
wtxn.commit()?;
Ok(())
}
/// Remove directory recursively
pub fn rm_rf(&self, path: &str) -> Result<()> {
let path = normalize_path(path);
if path == "/" {
return Err(anyhow!("Cannot remove root directory"));
}
// Collect all paths to delete
let rtxn = self.env.read_txn()?;
let prefix = format!("{}/", path);
let mut to_delete = vec![path.clone()];
let iter = self.metadata.iter(&rtxn)?;
for item in iter {
let (key, _) = item?;
if key.starts_with(&prefix) {
to_delete.push(key.to_string());
}
}
drop(rtxn);
// Delete all collected paths
let mut wtxn = self.env.write_txn()?;
for p in &to_delete {
// Check for blob files to clean up
if let Ok(Some(meta)) = self.stat(p) {
if let Some(ref real_path) = meta.real_path {
let _ = std::fs::remove_file(real_path);
}
}
self.metadata.delete(&mut wtxn, p)?;
let _ = self.content.delete(&mut wtxn, p);
}
wtxn.commit()?;
Ok(())
}
/// Rename/move file or directory
pub fn rename(&self, old_path: &str, new_path: &str) -> Result<()> {
let old_path = normalize_path(old_path);
let new_path = normalize_path(new_path);
if !self.exists(&old_path)? {
return Err(anyhow!("Source not found: {}", old_path));
}
if self.exists(&new_path)? {
return Err(anyhow!("Destination already exists: {}", new_path));
}
// Ensure parent of destination exists
if let Some(parent) = parent_path(&new_path) {
self.mkdir_p(&parent)?;
}
let rtxn = self.env.read_txn()?;
let meta = self.metadata.get(&rtxn, &old_path)?
.ok_or_else(|| anyhow!("Source not found: {}", old_path))?
.clone();
let content = self.content.get(&rtxn, &old_path)?.map(|b| b.to_vec());
drop(rtxn);
let mut wtxn = self.env.write_txn()?;
// Copy to new location
self.metadata.put(&mut wtxn, &new_path, &meta)?;
if let Some(data) = content {
self.content.put(&mut wtxn, &new_path, &data)?;
}
// Delete old
self.metadata.delete(&mut wtxn, &old_path)?;
let _ = self.content.delete(&mut wtxn, &old_path);
wtxn.commit()?;
Ok(())
}
// ========================================================================
// VECTOR INDEX (Reverse RAG Lookup)
// ========================================================================
/// Index a file with a vector ID for reverse lookup
pub fn index_vector(&self, path: &str, vector_id: &str) -> Result<()> {
let path = normalize_path(path);
let mut wtxn = self.env.write_txn()?;
// Update metadata
if let Some(mut meta) = self.stat(&path)? {
meta.vector_id = Some(vector_id.to_string());
self.metadata.put(&mut wtxn, &path, &meta)?;
}
// Add to index
self.index.put(&mut wtxn, vector_id, &path)?;
wtxn.commit()?;
Ok(())
}
/// Reverse lookup: vector_id → path
pub fn vector_to_path(&self, vector_id: &str) -> Result<Option<String>> {
let rtxn = self.env.read_txn()?;
Ok(self.index.get(&rtxn, vector_id)?.map(|s| s.to_string()))
}
// ========================================================================
// UTILITIES
// ========================================================================
/// Get total size of all files
pub fn total_size(&self) -> Result<u64> {
let rtxn = self.env.read_txn()?;
let mut total = 0u64;
let iter = self.metadata.iter(&rtxn)?;
for item in iter {
let (_, meta) = item?;
total += meta.size;
}
Ok(total)
}
/// Get file count
pub fn file_count(&self) -> Result<u64> {
let rtxn = self.env.read_txn()?;
let mut count = 0u64;
let iter = self.metadata.iter(&rtxn)?;
for item in iter {
let (_, meta) = item?;
if meta.file_type == FileType::File {
count += 1;
}
}
Ok(count)
}
/// Get directory count
pub fn dir_count(&self) -> Result<u64> {
let rtxn = self.env.read_txn()?;
let mut count = 0u64;
let iter = self.metadata.iter(&rtxn)?;
for item in iter {
let (_, meta) = item?;
if meta.file_type == FileType::Directory {
count += 1;
}
}
Ok(count)
}
}
// ============================================================================
// HELPER FUNCTIONS
// ============================================================================
/// Normalize a path: resolve . and .., ensure leading /, no trailing /
fn normalize_path(path: &str) -> String {
let mut components: Vec<&str> = Vec::new();
for part in path.split('/') {
match part {
"" | "." => continue,
".." => { components.pop(); }
_ => components.push(part),
}
}
if components.is_empty() {
"/".to_string()
} else {
format!("/{}", components.join("/"))
}
}
/// Get parent path
fn parent_path(path: &str) -> Option<String> {
let path = normalize_path(path);
if path == "/" {
return None;
}
let idx = path.rfind('/')?;
if idx == 0 {
Some("/".to_string())
} else {
Some(path[..idx].to_string())
}
}
/// Current Unix timestamp
fn unix_now() -> i64 {
SystemTime::now()
.duration_since(UNIX_EPOCH)
.map(|d| d.as_secs() as i64)
.unwrap_or(0)
}
/// SHA256 hash as hex string
fn sha256_hex(data: &[u8]) -> String {
let mut hasher = Sha256::new();
hasher.update(data);
let result = hasher.finalize();
hex::encode(result)
}
// ============================================================================
// TESTS
// ============================================================================
#[cfg(test)]
mod tests {
use super::*;
use tempfile::tempdir;
#[test]
fn test_normalize_path() {
assert_eq!(normalize_path("/"), "/");
assert_eq!(normalize_path("/home/user"), "/home/user");
assert_eq!(normalize_path("/home/user/"), "/home/user");
assert_eq!(normalize_path("/home/../home/user"), "/home/user");
assert_eq!(normalize_path("/home/./user"), "/home/user");
assert_eq!(normalize_path("relative"), "/relative");
}
#[test]
fn test_parent_path() {
assert_eq!(parent_path("/"), None);
assert_eq!(parent_path("/home"), Some("/".to_string()));
assert_eq!(parent_path("/home/user"), Some("/home".to_string()));
}
#[test]
fn test_basic_operations() -> Result<()> {
let dir = tempdir()?;
let fs = SpfFs::open(dir.path())?;
// Test exists
assert!(fs.exists("/")?);
assert!(fs.exists("/home/agent")?);
assert!(!fs.exists("/nonexistent")?);
// Test write and read
fs.write("/home/user/test.txt", b"Hello, SPF!")?;
let content = fs.read("/home/user/test.txt")?;
assert_eq!(content, b"Hello, SPF!");
// Test stat
let meta = fs.stat("/home/user/test.txt")?.unwrap();
assert_eq!(meta.file_type, FileType::File);
assert_eq!(meta.size, 11);
// Test ls
let entries = fs.ls("/home/user")?;
assert!(entries.iter().any(|(name, _)| name == "test.txt"));
// Test rm
fs.rm("/home/user/test.txt")?;
assert!(!fs.exists("/home/user/test.txt")?);
Ok(())
}
}
|