Filesystem Guide
Janus Standard Library: Filesystem Guide
Section titled “Janus Standard Library: Filesystem Guide”The Future of Programming: AI-First, Capability-Based Filesystem Operations
Section titled “The Future of Programming: AI-First, Capability-Based Filesystem Operations”Welcome to the Janus filesystem library! This guide introduces you to modern filesystem programming concepts that represent the future of software development. Janus combines AI-first design with capability-based security and atomic operations to create a filesystem API that’s safe, powerful, educational, and forward-thinking.
Why Traditional Filesystems Are Broken
Section titled “Why Traditional Filesystems Are Broken”Traditional filesystem APIs suffer from fundamental problems that make them unsafe and complex:
The Security Nightmare
Section titled “The Security Nightmare”// C/C++ - Race condition proneFILE* file = fopen("config.txt", "r");if (file) { // What if file is deleted here by another process? char buffer[1024]; fread(buffer, 1, sizeof(buffer), file); fclose(file);}The Complexity Trap
Section titled “The Complexity Trap”# Python - Manual resource managementtry: with open('data.txt', 'r') as f: data = f.read() # File automatically closed... sometimesexcept IOError as e: # Handle errors... hopefully passThe Reliability Gap
Section titled “The Reliability Gap”// Node.js - Fire and forgetfs.writeFile('important.dat', data, (err) => { if (err) { // Data might be corrupted console.error('Write failed!'); }});Janus: The Solution
Section titled “Janus: The Solution”Janus changes everything with modern programming principles:
Capability Security: No More TOCTOU Attacks
Section titled “Capability Security: No More TOCTOU Attacks”// Janus - Explicit permissions requiredvar cap = Capability.FileSystem.init("my-app", allocator);defer cap.deinit();try cap.allow_path("/safe/config");
// This is guaranteed safeconst content = try fs.read_with_capability("/safe/config/app.json", cap, allocator);Atomic Operations: Never Lose Data Again
Section titled “Atomic Operations: Never Lose Data Again”// Janus - Crash-safe writesconst result = try fs.atomicWrite("/database/users.db", userData, .{ .paranoid_mode = true, // Maximum durability}, allocator);
// Either old file exists OR complete new file exists// NEVER partial or corrupted dataAI-First Design: Code Documents Itself
Section titled “AI-First Design: Code Documents Itself”// Janus - Self-documenting with UTCP manualsconst result = try fs.walk_min("/project/src", myCallback, allocator);// Hover over any Janus function to see comprehensive docs// AI tools can understand and manipulate Janus code automaticallyProgressive Disclosure: Learn From Simple to Advanced
Section titled “Progressive Disclosure: Learn From Simple to Advanced”// Level 1: Just worksconst data = try fs.read("file.txt", allocator);
// Level 2: Add context awarenessvar ctx = Context.init(allocator);const data = try fs.read_with_context("file.txt", ctx, allocator);
// Level 3: Full security and auditingvar cap = Capability.FileSystem.init("secure-app", allocator);const data = try fs.read_with_capability("file.txt", cap, allocator);The Tri-Signature Pattern
Section titled “The Tri-Signature Pattern”Janus introduces the tri-signature pattern - the same function name with rising capability across profiles:
:core Profile - Simple and Safe
Section titled “:core Profile - Simple and Safe”// Basic file reading - just worksconst content = try fs.read("/my/file.txt", allocator);defer allocator.free(content);:service Profile - Context-Aware
Section titled “:service Profile - Context-Aware”// With cancellation and timeoutsvar ctx = Context.init(allocator);defer ctx.deinit();
const content = try fs.read_with_context("/my/file.txt", ctx, allocator);:sovereign Profile - Capability-Gated
Section titled “:sovereign Profile - Capability-Gated”// With security and audit trailsvar cap = Capability.FileSystem.init("my-app", allocator);defer cap.deinit();try cap.allow_path("/safe/data");
const content = try fs.read_with_capability("/safe/data/file.txt", cap, allocator);Data Integrity Above All
Section titled “Data Integrity Above All”Atomic Write Operations
Section titled “Atomic Write Operations”Janus ensures data integrity with atomic operations:
// Crash-safe database updatesconst result = try fs.atomicWrite("/database/users.db", userData, .{ .paranoid_mode = true, // Maximum durability}, allocator);defer result.deinit(allocator);
if (result.success) { std.debug.print("Data saved atomically: {} bytes\n", .{result.bytes_written});}Durability Guarantees
Section titled “Durability Guarantees”Before a crash: Either old file exists or no file exists During a crash: Temporary files are ignored After a crash: Either old file or complete new file exists Never: Partial or corrupted data
Modern Features for Future Programming
Section titled “Modern Features for Future Programming”Streaming for Large Files
Section titled “Streaming for Large Files”// Handle huge files efficientlyvar streamer = try fs.StreamingReader.init("/big/file.dat", 64*1024, allocator);defer streamer.deinit();
while (try streamer.readChunk(progressCallback)) |chunk| { defer allocator.free(chunk); // Process chunk...}File Watching (Hot Reload Ready)
Section titled “File Watching (Hot Reload Ready)”// Monitor files for changesvar watcher = fs.FileWatcher.init(allocator);defer watcher.deinit();
try watcher.watchFile("/config/app.json");
// Check for changesconst changed_files = try watcher.checkChanges();for (changed_files) |path| { std.debug.print("File changed: {s}\n", .{path}); // Trigger hot reload...}Async Operations (Future-Proofed)
Section titled “Async Operations (Future-Proofed)”// Ready for when Zig gets better async I/O// fs.AsyncFileOps.readAsync("/file.txt", allocator, myCallback);Learning the Future of Programming
Section titled “Learning the Future of Programming”Progressive Learning Path
Section titled “Progressive Learning Path”Level 1: Basic Operations
// Start simpleconst data = try fs.read("hello.txt", allocator);try fs.write("output.txt", "Hello World!", allocator);Level 2: Context Awareness
// Add timeouts and cancellationvar ctx = Context.init(allocator);defer ctx.deinit();ctx.setDeadline(std.time.ms_per_s * 5); // 5 second timeout
const data = try fs.read_with_context("slow/file.txt", ctx, allocator);Level 3: Security First
// Capability-based securityvar cap = Capability.FileSystem.init("student-app", allocator);defer cap.deinit();
// Only allow access to assignment directorytry cap.allow_path("/assignments/week3");
// Audit all operationsconst data = try fs.read_with_capability("/assignments/week3/data.txt", cap, allocator);Understanding Capability Security
Section titled “Understanding Capability Security”Capabilities are like keys to specific resources:
// Create a capability for file operationsvar fileCap = Capability.FileSystem.init("my-program", allocator);defer fileCap.deinit();
// Grant specific permissionstry fileCap.allow_path("/home/user/documents");try fileCap.allow_write(); // Can create/modify files
// This worksconst content = try fs.read_with_capability("/home/user/documents/notes.txt", fileCap, allocator);
// This fails - no permission// const secret = try fs.read_with_capability("/etc/passwd", fileCap, allocator);Educational Concepts
Section titled “Educational Concepts”Why Janus Represents the Future
Section titled “Why Janus Represents the Future”- AI-First Design: Code documents itself with UTCP manuals
- Memory Safety: No null pointer dereferences, no buffer overflows
- Capability Security: Fine-grained access control prevents exploits
- Atomic Operations: Data integrity guarantees
- Progressive Disclosure: Learn from simple to advanced
- Future-Proofed: Ready for async, distributed computing
Real-World Applications
Section titled “Real-World Applications”Database Systems:
// Atomic database updatesconst result = try fs.atomicWrite("/db/transactions.log", logData, .{ .paranoid_mode = true, // Never lose transaction data}, allocator);Configuration Management:
// Safe config updatesvar configCap = Capability.FileSystem.init("config-manager", allocator);try configCap.allow_path("/etc/myapp");
const result = try fs.atomicWrite("/etc/myapp/config.json", newConfig, .{ .paranoid_mode = true,}, configCap, allocator);File Processing Pipelines:
// Stream processing with progressvar streamer = try fs.StreamingReader.init("/large/dataset.csv", 1*1024*1024, allocator);defer streamer.deinit();
var processed: usize = 0;while (try streamer.readChunk(struct { fn callback(bytes: u64) void { processed += bytes; std.debug.print("Processed: {} MB\n", .{processed / (1024*1024)}); }}.callback)) |chunk| { defer allocator.free(chunk); // Process chunk...}Performance Characteristics
Section titled “Performance Characteristics”| Operation | NVMe SSD | SATA SSD | HDD | Network |
|---|---|---|---|---|
| Simple read | ~50us | ~200us | ~5ms | ~50ms |
| Atomic write (normal) | ~100us | ~500us | ~15ms | ~200ms |
| Atomic write (paranoid) | ~200us | ~1ms | ~30ms | ~1s+ |
Key Insights:
- Paranoid mode adds safety, not orders of magnitude slowdown
- Network storage needs careful consideration
- Modern SSDs make safety affordable
Best Practices
Section titled “Best Practices”For Students
Section titled “For Students”- Start with :core profile - learn basics first
- Add context awareness - prevent hanging operations
- Use capabilities - write secure code from day one
- Always handle errors - no silent failures
- Test atomic operations - verify durability guarantees
For Educators
Section titled “For Educators”- Teach progressive disclosure - from simple to complex
- Emphasize security - capabilities prevent real exploits
- Demonstrate atomicity - crash-safe operations
- Show AI integration - UTCP manuals for tooling
- Encourage experimentation - safe to explore
Module-by-Module Guide
Section titled “Module-by-Module Guide”std/path.zig: Cross-Platform Path Manipulation
Section titled “std/path.zig: Cross-Platform Path Manipulation”The foundation of safe filesystem operations:
// Path operations work on all platformsconst path = Path.init("/usr/local/bin/zig");const parent = path.parent().?; // "/usr/local/bin"const file_name = path.fileName().?; // "zig"const extension = path.extension(); // null (no extension)
// Cross-platform path buildingvar buf = try PathBuf.fromSlice("/tmp", allocator);defer buf.deinit();try buf.push("my-app");try buf.push("data.txt");// Result: "/tmp/my-app/data.txt" (Unix) or "C:\tmp\my-app\data.txt" (Windows)Teaching Moment: Paths are not strings! They have structure and platform-specific rules.
std/fs.zig: Core File Operations
Section titled “std/fs.zig: Core File Operations”The heart of filesystem programming with tri-signature safety:
// :core profile - Simple and safeconst content = try fs.read("config.json", allocator);defer allocator.free(content);
// :service profile - Context-awarevar ctx = Context.init(allocator);defer ctx.deinit();const content = try fs.read_with_context("config.json", ctx, allocator);
// :sovereign profile - Capability-securedvar cap = Capability.FileSystem.init("my-app", allocator);defer cap.deinit();try cap.allow_path("/etc/myapp");const content = try fs.read_with_capability("/etc/myapp/config.json", cap, allocator);std/fs_atomic.zig: Crash-Safe Data Integrity
Section titled “std/fs_atomic.zig: Crash-Safe Data Integrity”Never lose data again:
// Atomic rename with cross-device supportconst result = try fs.atomicRename("/old.db", "/new.db", allocator);if (result.success) { std.debug.print("Database migrated safely\n", .{});}
// Atomic write with durability guaranteesconst result = try fs.atomicWrite("/critical/data.bin", importantData, .{ .paranoid_mode = true, // Extra fsync operations}, allocator);Teaching Moment: Atomic operations prevent data corruption during crashes.
std/fs_write.zig: RAII Writing with Content Integrity
Section titled “std/fs_write.zig: RAII Writing with Content Integrity”Write safely with automatic cleanup and CID verification:
// RAII file writer - automatically cleans upvar writer = try fs.FileWriter.init("/output.txt", .{ .compute_cid = true,}, allocator);defer writer.deinit(); // Always called
try writer.write("Important data");const result = try writer.finish();
// result.cid contains BLAKE3 hash for integrity verificationstd/fs_temp.zig: Secure Temporary Files
Section titled “std/fs_temp.zig: Secure Temporary Files”Collision-resistant temporary file creation:
// Secure temp file with automatic cleanupvar temp = try fs.createTempFile(.{ .prefix = "myapp_", .suffix = ".tmp",}, allocator);defer temp.deinit(); // File automatically deleted
try temp.write("temporary data");try temp.persist("/permanent/location.txt"); // Make it permanentstd/fs_walker.zig: Advanced Directory Traversal
Section titled “std/fs_walker.zig: Advanced Directory Traversal”Powerful recursive directory walking with security:
// Walk with pruning and progressvar walker = try fs.Walker.init("/project/src", .{ .max_depth = 3, .prune_fn = myPruneFunction, .progress_callback = myProgressCallback,}, allocator);defer walker.deinit();
try walker.walk(struct { pub fn process(entry: fs.WalkEntry) fs.WalkAction { if (entry.isFile() and entry.extension() == ".zig") { std.debug.print("Found Zig file: {s}\n", .{entry.path}); } return .continue_traversal; }}.process);std/memory_fs.zig: Deterministic Testing
Section titled “std/memory_fs.zig: Deterministic Testing”In-memory filesystem for reliable testing:
// Perfect for testing - deterministic and fastvar memfs = try fs.MemoryFS.init(allocator);defer memfs.deinit();
try memfs.createFile("/test.txt", "test data");const content = try memfs.readFile("/test.txt");// Always returns "test data" - no disk I/O variabilityAdvanced Concepts for Students
Section titled “Advanced Concepts for Students”Understanding the Tri-Signature Pattern
Section titled “Understanding the Tri-Signature Pattern”The tri-signature pattern teaches progressive enhancement:
- :core Profile: “Just work” - Simple, safe defaults
- :service Profile: “Be aware” - Add context, timeouts, cancellation
- :sovereign Profile: “Be secure” - Full capabilities, auditing, verification
This pattern mirrors how real systems should be designed: start simple, add complexity as needed.
Capability-Based Security in Action
Section titled “Capability-Based Security in Action”// Create a "jail" for untrusted codevar sandbox = Capability.FileSystem.init("sandbox", allocator);defer sandbox.deinit();
// Only allow access to specific directoriestry sandbox.allow_path("/tmp/sandbox/input");try sandbox.allow_path("/tmp/sandbox/output");try sandbox.allow_write(); // But only to allowed paths
// Untrusted code can only touch allowed filesrunUntrustedCode(sandbox);Teaching Moment: Capabilities prevent supply chain attacks and sandbox escapes.
Atomic Operations and ACID Properties
Section titled “Atomic Operations and ACID Properties”Janus atomic operations provide ACID guarantees:
- Atomicity: All-or-nothing operations
- Consistency: System remains in valid state
- Isolation: Operations don’t interfere
- Durability: Changes survive crashes
// Database transaction with atomic file operationsconst result = try fs.atomicWrite("/db/transactions.log", newTransaction, .{ .paranoid_mode = true, // Durability}, allocator);
// Either transaction is fully logged or not at allResearch and Future Directions
Section titled “Research and Future Directions”AI Integration
Section titled “AI Integration”Janus is designed for AI tooling:
// AI can read UTCP manuals automaticallyconst manual = fs.utcpManual();// AI understands the API without human documentationDistributed Filesystems
Section titled “Distributed Filesystems”CID-based content addressing enables distributed systems:
// Same content, same CID across all machinesconst cid1 = ContentId.fromData(data);const cid2 = ContentId.fromFile("/distributed/file", allocator);// cid1 == cid2 - content-based addressingFormal Verification
Section titled “Formal Verification”Janus operations are designed to be formally verifiable:
// Pre/post conditions can be proven// @requires valid_path(path)// @ensures file_exists(path) || error_returnedconst result = try fs.atomicWrite(path, data, options, allocator);Educational Resources
Section titled “Educational Resources”For University Courses
Section titled “For University Courses”Course: Modern Systems Programming
- Week 1: Path manipulation and cross-platform concerns
- Week 2: Basic file I/O with error handling
- Week 3: Atomic operations and data integrity
- Week 4: Capability-based security
- Week 5: Advanced patterns (streaming, walking, compression)
Course: Secure Software Engineering
- Unit 1: TOCTOU attacks and capability solutions
- Unit 2: Race conditions and atomic operations
- Unit 3: Memory safety and RAII patterns
- Unit 4: Progressive disclosure in API design
Student Projects
Section titled “Student Projects”-
Build a Safe Configuration Manager
- Use atomic writes for config updates
- Implement capability-based access control
- Add CID verification for integrity
-
Create a File Backup System
- Use directory walking for source discovery
- Implement streaming for large files
- Add progress callbacks and cancellation
-
Design a Sandboxed Code Runner
- Use temporary directories for isolation
- Implement capability restrictions
- Add file watching for hot reload
Why This Matters for the Future
Section titled “Why This Matters for the Future”The Coming AI Revolution
Section titled “The Coming AI Revolution”As AI becomes central to programming:
- Self-Documenting Code: Janus UTCP manuals allow AI to understand and manipulate code
- Safety by Default: AI-generated code will be safer with capability controls
- Reliable Operations: AI can reason about atomic operations and crash safety
- Progressive Enhancement: AI can start simple and add complexity as needed
The Security Imperative
Section titled “The Security Imperative”With increasing cyber threats:
- Capability Security: Prevents exploits before they happen
- Atomic Operations: Guarantees data integrity under attack
- Memory Safety: Eliminates entire classes of vulnerabilities
- Audit Trails: Provides forensic evidence of breaches
The Reliability Requirement
Section titled “The Reliability Requirement”As systems grow more complex:
- Crash Safety: Systems stay running through failures
- Deterministic Testing: Reliable testing with MemoryFS
- Progressive Disclosure: APIs that grow with user needs
- Future-Proofing: Ready for async, distributed, and quantum computing
Conclusion
Section titled “Conclusion”The Janus filesystem library isn’t just a better way to handle files — it’s a blueprint for the future of programming. It demonstrates how modern software should be designed:
- AI-first: Code that documents and explains itself
- Security-first: Capabilities prevent exploits by default
- Reliability-first: Atomic operations ensure data integrity
- Education-first: Progressive disclosure teaches best practices
Welcome to the future of programming. The Janus filesystem library shows what’s possible when we design software with people, safety, and reliability in mind.
Ready to start coding? Check out /examples/ for working code samples, and explore the UTCP manuals in each module for comprehensive API documentation.