Grafting: Foreign Code Integration
Grafting Guide: Foreign Code Integration in Janus
Section titled “Grafting Guide: Foreign Code Integration in Janus”Injecting the world’s code into your AI-first applications
What is Grafting?
Section titled “What is Grafting?”Grafting is Janus’ approach to foreign code integration. Unlike traditional “bindings” or “wrappers”, grafting allows you to seamlessly inject foreign libraries and runtimes directly into your Janus code while maintaining:
- Zero-cost abstraction - No runtime overhead
- Cryptographic security - Capability-based access control
- AI tooling integration - Self-documenting code with UTCP manuals
- Namespace hygiene - Contained under
std.graft.*
Result: You can use any Zig library or Python module as if it were native Janus code.
Native Zig Integration: The Home Ground
Section titled “Native Zig Integration: The Home Ground”Janus is built on Zig. You are not just grafting; you are extending the compiler substrate.
Inline Zig Blocks
Section titled “Inline Zig Blocks”Write native Zig code directly inside Janus files. It is compiled alongside your Janus code with zero overhead.
foreign "zig" as substrate { const std = @import("std");
pub fn optimized_sort(ptr: [*]i32, len: usize) void { const slice = ptr[0..len]; std.sort.block(i32, slice, {}, std.sort.asc(i32)); }}
func sortData(data: []i32) do // Direct call into the Zig substrate substrate.optimized_sort(data.ptr, data.len);endLocal File Grafting
Section titled “Local File Grafting”Import any .zig file from your project structure.
// Graft a local Zig filegraft math = zig "./vendor/math_utils.zig";
func compute() f64 do return math.fast_inverse_sqrt(16.0);endQuick Start: Injecting Zig Libraries
Section titled “Quick Start: Injecting Zig Libraries”Step 1: The Graft Declaration
Section titled “Step 1: The Graft Declaration”// Inject the popular zig-clap CLI librarygraft clap = zig "https://github.com/Hejsil/zig-clap/archive/refs/tags/0.9.1.tar.gz";
// Now use it as native Janus code!func main(args: []string) do let parsed = clap.parse(args, clap.parsers(...)); processCommand(parsed);endThat’s it! The foreign Zig library is now available as clap in your scope.
Step 2: Capability-Based Security
Section titled “Step 2: Capability-Based Security”func secureProcess(path: string, ctx: Context) !Result do // Janus enforces capability checks automatically let data = std.fs.readFile(path, ctx.fs_read_capability); let result = my_zig_library.process(data); return result;endForeign code cannot access your filesystem without explicit capability grants.
Python Integration: Scripting Superpowers
Section titled “Python Integration: Scripting Superpowers”Foreign Blocks for Python
Section titled “Foreign Blocks for Python”// Create a Python runtime instanceforeign "python" as py do import numpy as np import matplotlib.pyplot as plt
def analyze_data(data): return { 'mean': np.mean(data), 'std': np.std(data), 'plot': plt.histogram(data) }end
// Use it seamlessly in Janusfunc processSensorData(raw_data: []f64, ctx: Context) !Analysis do using py := try std.graft.python.open(ctx, cap: ctx.foreign.python.ipc) do
// Convert Janus arrays to Python let py_array = py.call("numpy.array", [raw_data]);
// Call our custom Python function let analysis = try py.call("analyze_data", [py_array]);
// Extract results back to Janus types return Analysis{ mean: try analysis.get("mean").to_number(), std: try analysis.get("std").to_number(), histogram_data: try analysis.get("plot").to_array() }; endendYou just seamlessly called Python’s NumPy and Matplotlib from Janus code!
C Integration: The Universal Glue
Section titled “C Integration: The Universal Glue”Direct Shared Object Grafting
Section titled “Direct Shared Object Grafting”Janus treats C as the “lingua franca” of the system. You can graft shared objects (.so, .dll, .dylib) directly.
// Graft a standard C librarygraft libc = c "libc.so.6";
func getCurrentTime() i64 do // Call C functions directly with zero overhead return libc.time(null);endHeader Definitions
Section titled “Header Definitions”For complex C libraries, you can provide inline C definitions to help the Janus compiler understand types.
foreign "c" as raylib { #include "raylib.h" // Janus automatically parses the header AST}
func drawGame() do raylib.InitWindow(800, 600, "Janus Window"); while !raylib.WindowShouldClose() do raylib.BeginDrawing(); raylib.ClearBackground(raylib.RAYWHITE); raylib.DrawText("Hello C-Realms!", 190, 200, 20, raylib.LIGHTGRAY); raylib.EndDrawing(); end raylib.CloseWindow();endRust Integration: Oxidized Safety
Section titled “Rust Integration: Oxidized Safety”Cargo Crate Grafting
Section titled “Cargo Crate Grafting”Janus can drink directly from the Cargo stream. This requires cargo to be available in the build environment.
// Graft a Rust crate directly from a git repograft rocket = cargo "https://github.com/rwf2/Rocket";
// Or specify a crate version (uses crates.io)graft serde = cargo "serde:1.0";The Safety Bridge
Section titled “The Safety Bridge”Janus respects Rust’s safety guarantees.
// Using the grafted Rust libraryfunc handleRequest(req: Request) !Response do // Rust's Results are mapped to Janus error unions automatically let processed = try rocket.process(req); return processed;endNote: The first time you build, Janus will invoke Cargo to compile the grafted crate as a static library, then link it.
Julia Integration: Scientific Sovereignty
Section titled “Julia Integration: Scientific Sovereignty”For high-performance numerical computing, nothing beats Julia.
Foreign Blocks for Julia
Section titled “Foreign Blocks for Julia”foreign "julia" as flux do using Flux using LinearAlgebra
function train_model(x_data, y_data) model = Chain(Dense(10, 5, relu), Dense(5, 2)) loss(x, y) = Flux.mse(model(x), y) Flux.train!(loss, Flux.params(model), [(x_data, y_data)], ADAM()) return model endendTensor Bridging
Section titled “Tensor Bridging”Janus Arrays ([]f64) map directly to Julia Arrays with zero checking.
func runTraining() !Model do // Capability: Requires 'julia.embed' capability using jl := try std.graft.julia.open(ctx, cap: ctx.foreign.julia.embed) do let x = std.tensor.random([10, 100]); let y = std.tensor.random([2, 100]);
// Pass Janus tensors to Julia // Memory is shared, not copied! let model = jl.call("train_model", [x, y]);
return model; endendComplete Examples
Section titled “Complete Examples”Example 1: High-Performance Math
Section titled “Example 1: High-Performance Math”// Graft BLAS library for linear algebragraft blas = zig "https://github.com/kooparse/zig-blases/archive/main.tar.gz";
func matrixMultiply(a: Matrix, b: Matrix) Matrix do // Direct call to optimized BLAS return blas.gemm(a, b, 1.0, 0.0);endExample 2: Web Scraping with Python
Section titled “Example 2: Web Scraping with Python”foreign "python" as scraper do import requests from bs4 import BeautifulSoup
def extract_titles(url): response = requests.get(url) soup = BeautifulSoup(response.text, 'html.parser') return [h1.text for h1 in soup.find_all('h1')]end
func scrapeHeadlines(url: string, ctx: Context) ![]string do using scraper := try std.graft.python.open(ctx, cap: ctx.foreign.python.ipc) do let titles = try scraper.call("extract_titles", [url]); return titles.to_array(); // Automatic conversion endendExample 3: Cryptographic Operations
Section titled “Example 3: Cryptographic Operations”// Graft a crypto librarygraft crypto = zig "https://github.com/pornin/monocypher-zig/archive/main.tar.gz";
// Janus handles capability verification automaticallyfunc encryptData(data: []u8, key: Key) ![]u8 do return crypto.aead_encrypt(data, key, "JanusData");endThe Janus Advantage
Section titled “The Janus Advantage”Performance
Section titled “Performance”- Zero-copy data transfer where possible
- Native compilation of grafted Zig code
- Profile optimization (:core vs :sovereign performance modes)
Security
Section titled “Security”- Capability tokens required for sensitive operations
- Sandboxing prevents foreign code escape
- Audit trails track all foreign function calls
- Memory Safety: Rust grafts retain borrow checker guarantees at the boundary
Scientific Sovereignty
Section titled “Scientific Sovereignty”- Julia & Python: Direct memory mapping for tensors (Zero-Copy)
- Unified Logic: One language (Janus) to orchestrate C, Rust, Python, and Julia
AI Integration
Section titled “AI Integration”// UTCP manuals make foreign code discoverablefunc discoverCapabilities() ![]UTCPManual do // AI tools can explore all grafted capabilities return std.graft.enumerateAll();endGrafting Patterns
Section titled “Grafting Patterns”Pattern 1: Zig Library Integration
Section titled “Pattern 1: Zig Library Integration”// For algorithm-heavy codegraft algorithm = zig "path/to/zig-algorithm-lib";
func processLargeDataset(data: Dataset) Result do // Use optimized parallel algorithms return algorithm.parallel_process(data);endPattern 2: Python Ecosystem Access
Section titled “Pattern 2: Python Ecosystem Access”foreign "python" as ecosystem do import scikit-learn import pandas as pd # ... ML pipeline code ...end
func trainModel(training_data: Dataset) Model do using ecosystem := std.graft.python.open(...) do let df = ecosystem.call("pandas.DataFrame", [training_data]); return ecosystem.call("train_ml_model", [df]); endendPattern 3: Legacy System Integration
Section titled “Pattern 3: Legacy System Integration”// Connect to existing C librariesgraft legacy = c "legacy_system.so";
func migrateLegacyData() MigrationResult do let raw_data = legacy.fetch_records(); return transformToModernFormat(raw_data);endAdvanced Features
Section titled “Advanced Features”Resource Management
Section titled “Resource Management”// Automatic cleanupusing py := std.graft.python.open(ctx, cap: ctx.foreign.python.ipc) do let result = py.call("process_data", [data]); // py.close() called automatically hereendError Handling
Section titled “Error Handling”let result = py.call("risky_operation", [args]) or do |err| // Handle Python exceptions in Janus match err.kind { .ForeignError => log.warn("Foreign code error: {err.message}"); .CapabilityMissing => return Error.InsufficientPrivileges; .Timeout => return Error.OperationTimeout; }endForeign Data Types
Section titled “Foreign Data Types”// Automatic marshallinglet python_dict = py.eval("{'key': 'value'}");let janus_table = python_dict.to_table(); // Converts Python dict to Janus table
// Zero-copy for arrays (where supported)let numpy_array = py.call("numpy.linspace", [0, 100, 50]);let janus_array = numpy_array.to_ndarray("f64"); // Direct memory mappingConfiguration and Profiles
Section titled “Configuration and Profiles”Profile-Specific Grafting
Section titled “Profile-Specific Grafting”// :core profile - IPC onlyusing py := std.graft.python.open(ctx, cap: ctx.foreign.python.ipc);
// :sovereign profile - Embed Python VMusing py := std.graft.python.open(ctx, cap: ctx.foreign.python.embed);Policy-Based Governance
Section titled “Policy-Based Governance”foreign { python { deterministic = false // Allow non-deterministic ops in trusted contexts timeout_ms = 5000 allowed_modules = ["numpy", "scipy", "matplotlib"] }}Troubleshooting
Section titled “Troubleshooting”Common Issues
Section titled “Common Issues”-
Capability Missing
// Add to function parametersfunc myFunc(ctx: Context) do // Context provides capabilitieslet py = std.graft.python.open(ctx, cap: ctx.foreign.python.ipc);end -
Timeout Errors
let result = py.call("long_running", args, timeout_ms: 30000); -
Type Conversion Issues
// Explicit conversionslet py_obj = py.eval("some_python_expression");let janus_value = py_obj.to_number() or do return Error.ConversionFailed; end
What’s Next?
Section titled “What’s Next?”Grafting is just getting started:
- More Languages: Rust, Lua, JavaScript, R integration
- Performance: Direct memory mapping for tensor operations
- AI Integration: Automatic code generation from UTCP manuals
- Cloud: Distributed grafting across Janus clusters
With Janus grafting, your code can leverage the entire world’s software ecosystem while maintaining security, performance, and AI-first design principles.