Rust Reference Implementation

Make AI Code 100% Observable

Every line AI generates becomes a queryable event. No more black boxes. No more "what did the AI actually do?" Type-safe, zero-cost, production-ready.

From Opaque AI Output to Complete Observability

Traditional AI generates code you can't verify until runtime. With EventIDs, every action is traceable from the moment it happens. You don't wonder what went wrong—you see it.

1 Define What Can Happen

Before AI writes a single line, you define the events your system can emit. This becomes the contract—AI can only generate code that speaks your language.

catalog.syntax DSL
// Define your event catalog BEFORE AI generates code // This is the contract. AI must follow it. domain auth { entity user { event login:1 { user_id: uuid ip: ip_addr method: string // "password", "oauth", "sso" mfa_used: bool } event logout:1 { user_id: uuid reason?: string // optional field } event locked:1 { user_id: uuid attempts: int duration_mins: int } } } domain agent { entity code { event generated:1 { file_path: string lines: int model: string confidence: float } } entity test { event passed:1 { test_name: string } event failed:1 { test_name: string, reason: string } } }

2 AI Generates Observable Code

AI writes code that emits well-defined events. Not console.log soup. Not undocumented side effects. Structured, typed, queryable events.

auth_service.rs Rust
//! AI-generated authentication service //! Every action emits observable events use event_model::{emit, EventCollector, EventId}; pub struct AuthService { collector: EventCollector, max_attempts: u32, } impl AuthService { pub async fn login( &self, user_id: Uuid, password: &str, ip: IpAddr, ) -> Result<Session, AuthError> { // Verify credentials... let user = self.verify_credentials(user_id, password).await?; // OBSERVABLE: Every successful login is an event emit!(auth.user.login:1, { "user_id": user_id, "ip": ip.to_string(), "method": "password", "mfa_used": user.mfa_enabled }); Ok(self.create_session(user).await?) } pub async fn handle_failed_login( &self, user_id: Uuid, attempts: u32, ) -> Result<(), AuthError> { if attempts >= self.max_attempts { // OBSERVABLE: Account lockout is an event emit!(auth.user.locked:1, { "user_id": user_id, "attempts": attempts, "duration_mins": 30 }); self.lock_account(user_id, Duration::from_mins(30)).await?; } Ok(()) } }

What You See (Real-Time Event Stream)

auth.user.login:1     @ 2026-01-23T14:32:01Z  user_id=550e8400... ip=192.168.1.42 method="password" mfa=true
auth.user.login:1     @ 2026-01-23T14:32:15Z  user_id=7c9e6679... ip=10.0.0.55 method="oauth" mfa=false
auth.user.locked:1    @ 2026-01-23T14:32:47Z  user_id=a1b2c3d4... attempts=5 duration_mins=30
auth.user.logout:1    @ 2026-01-23T14:33:02Z  user_id=550e8400... reason="user_initiated"

3 Query Anything

Once events are in your system, you can query them with SQL patterns. Find all failures. Count by domain. Debug AI behavior.

queries.rs Rust
// Query events with pattern matching // All auth events in the last hour let auth_events = collector.query("auth.%").await; // All failures across the entire system let failures = collector.query("%.failed:%").await; // All AI-generated code events let ai_code = collector.query("agent.code.%").await; // Count events by domain let counts = collector.count_by_domain().await; // → {"auth": 847, "agent": 234, "payments": 156} // Find specific patterns let locked_accounts = collector.query("auth.user.locked:%").await; for event in locked_accounts { let user_id = event.payload["user_id"].as_str(); let attempts = event.payload["attempts"].as_i64(); println!("User {} locked after {} attempts", user_id, attempts); }

The Observable AI Code Flow

1

Define Catalog

Events your system can emit

2

AI Generates

Code that emits typed events

3

Events Stream

Real-time, queryable data

4

Debug & Improve

See exactly what happened

4 AI Can Observe Itself

The most powerful part: AI-generated code emits events that AI can learn from. Feedback loops become possible.

ai_feedback.rs Rust
// AI generates code and observes its own output pub async fn ai_generate_with_feedback( prompt: &str, collector: &EventCollector, ) -> Result<GeneratedCode, Error> { // AI generates code let code = ai_model.generate(prompt).await?; // OBSERVABLE: Track what AI generated emit!(agent.code.generated:1, { "file_path": code.path, "lines": code.lines, "model": "claude-3.5-sonnet", "confidence": code.confidence }); // Run tests on generated code let test_result = run_tests(&code).await; match test_result { Ok(_) => { emit!(agent.test.passed:1, { "test_name": "generated_code_tests" }); } Err(e) => { // OBSERVABLE: AI can see its own failures emit!(agent.test.failed:1, { "test_name": "generated_code_tests", "reason": e.to_string() }); // AI queries its own failure history let my_failures = collector.query("agent.test.failed:%").await; let failure_rate = calculate_failure_rate(&my_failures); // AI can reason: "My code fails 23% of the time on auth modules" if failure_rate > 0.2 { // Adjust generation strategy... } } } Ok(code) }

AI Self-Observation Output

agent.code.generated:1  file="src/auth/login.rs" lines=47 model="claude-3.5-sonnet" confidence=0.94
agent.test.failed:1     test="generated_code_tests" reason="assertion failed at line 34"
agent.code.generated:1  file="src/auth/login.rs" lines=52 model="claude-3.5-sonnet" confidence=0.91
agent.test.passed:1     test="generated_code_tests"

// AI can query: "In the last 100 generations, I failed 23 times on auth modules"
// AI can learn: "When confidence < 0.9 on auth code, add extra validation"

Why This Changes Everything

No More Black Boxes

Every AI action is an event. You see exactly what it did, when, and why it might have failed.

Debug in Seconds

Query %.failed:% and see every failure across your system. No more log diving.

Type-Safe by Design

Events are validated at compile time. AI can't emit undefined events—the catalog is the spec.

AI Improves Itself

AI queries its own event history. "I fail 23% on auth" becomes actionable insight.

The Complete Implementation

Here's the core EventId type and emit! macro. Copy this into your project or use as reference.

lib.rs - Core Types Rust
//! Syntax.ai - Universal Event Model for Rust //! Make AI-Generated Code Observable. Verifiable. Improvable. use std::str::FromStr; use serde::{Serialize, Deserialize}; use regex::Regex; use once_cell::sync::Lazy; static EVENTID_REGEX: Lazy<Regex> = Lazy::new(|| { Regex::new(r"^[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*\.[a-z][a-z0-9_]*:[1-9][0-9]*$") .expect("Invalid regex") }); /// The Universal Event Model identifier /// Format: domain.entity.action:version #[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)] pub struct EventId { pub domain: String, pub entity: String, pub action: String, pub version: u32, } impl FromStr for EventId { type Err = EventIdError; fn from_str(s: &str) -> Result<Self, Self::Err> { if !EVENTID_REGEX.is_match(s) { return Err(EventIdError::InvalidFormat(s.to_string())); } let (path, version_str) = s.split_once(':') .ok_or_else(|| EventIdError::InvalidFormat(s.to_string()))?; let parts: Vec<&str> = path.split('.').collect(); Ok(EventId { domain: parts[0].to_string(), entity: parts[1].to_string(), action: parts[2].to_string(), version: version_str.parse()?, }) } } /// Create an event with compile-time event ID construction #[macro_export] macro_rules! emit { ($domain:ident.$entity:ident.$action:ident:$version:literal, { $($json:tt)* }) => {{ let event_id = EventId { domain: stringify!($domain).to_string(), entity: stringify!($entity).to_string(), action: stringify!($action).to_string(), version: $version, }; Event::new(event_id, serde_json::json!({ $($json)* })) }}; } // Usage: // let event = emit!(auth.user.login:1, { // "user_id": user.id, // "ip": req.ip.to_string(), // "method": "password" // });

Start Making AI Code Observable

The specification is open. The implementation is here. Every event your AI generates becomes queryable, traceable, improvable.