LEO
Open-Architecture Cognitive Operating System
Agent cognition run as an operating-system workload, and the audit that found 281 ways the architecture was being bypassed.
- commits
- 152
- lines of backend Python
- 130,098
- test functions
- 370
- violations found by audit
- 281
- first commit
- 18 Jun 2026
- subsystems specified
- 43
Measured from the repository on 7 Oct 2026 (git rev-list, git ls-files over backend/; audit and subsystem counts from Lab notes L004 and L017).
Abstract
Leo was an early, ambitious exploration into treating artificial intelligence as an operating system workload. It introduced a centralized cognitive kernel, a Cognitive Memory Management Unit (CMMU), and 43 granular subsystems, but a forensic Phase 28 audit uncovered 281 direct database violations that permanently reshaped my approach to engineering enforcement.
An ambitious cognitive operating system mapping 43 subsystems that exposed the critical reality gap between architecture and implementation.
- Type
- Cognitive Operating System Prototype
- Started
- 16 June 2026
- Status
- Archived & Superseded by Vani / ÆON
- Language
- Python 3.11 / React 18
- Domain
- Cognitive OS Kernel / Multi-Database Memory / Agent Scheduling
- Architecture
- OS Kernel Metaphor · Centralized CMMU Gateway · DAG Scheduler
- Scale
- 43 Subsystems · 3 Database Engines · 281 Audit Violations Documented
- Verification
- 281 Architectural Invariant Bypasses Discovered in Phase 28
- Materials
- Python 3.11FastAPIPostgreSQL (pgvector)Neo4jRedisThree.jsDocker
Background
Treating Agent Cognition as an Operating System Workload
“Can we manage complex, long-running AI agent processes by applying proven operating system primitives—clocks, process schedulers, and memory management units—instead of linear while-loops?”
Conventional AI agents were built as linear scripting loops (`while True: response = llm.chat(...)`). When background tasks ran concurrently with user conversations, systems suffered from priority inversion, state corruption, and runaway token expenses. There was no concept of process priority, temporal synchronization, or memory access arbitration.
Leo represented the foundational exploration phase of my systems thinking. It proved the power of OS-level scheduling for AI, but also provided my most valuable lesson in technical debt and architectural enforcement.
Where earlier approaches fall short
- 01No mechanism for fast interactive queries to preempt long-running background reasoning.
- 02Fragmented state split across disparate caching, vector, and relational databases without transactional consistency.
- 03Lack of architectural governance allowed modules to bypass memory gatekeepers and directly query databases.
- 04Unit test suites heavily relied on mocks, creating a false impression of health while integration points rotted.
Working hypothesis
By placing a Cognitive Kernel at the center of the system—featuring a temporal clock, a DAG scheduler, and a hardware-inspired Cognitive Memory Management Unit (CMMU)—an agent could coordinate 40+ specialized capabilities without deadlocks or priority inversion.
Summary
The Operating System Metaphor for AI
Cognitive actions are treated as OS processes scheduled across priority queues, synchronized by a temporal heartbeat, and restricted to accessing memory solely through a memory management gateway.
- 10
Ingestion via UCI
Events from WebSockets, Telegram, or REST arrive at the Unified Communication Interface and are normalized into system interrupts.
- 20
Kernel Synchronization
The Cognitive Clock emits synchronization ticks, driving the DAG execution engine to resolve dependencies and allocate compute.
- 30
Priority DAG Scheduling
Interactive user requests (Priority 1) pre-empt long-running background cognitive reflections (Priority 4).
- 40
CMMU Memory Mediation
Subsystems request data via the CMMU, which translates virtual cognitive addresses to Redis (working), Postgres (episodic), or Neo4j (associative).
- 50
Cognitive Engine Execution
Belief engines, conflict resolvers, and domain skills process state and yield outputs back through the UCI.
Description
Leo was designed with a centralized kernel coordinating 43 granular subsystems across four primary divisions: Kernel, CMMU, Cognition, and Interfaces.
- Implemented
- Partial
- Experimental
Cognitive Clock
102 · in 100 Cognitive Kernel
Emits discrete temporal pulses to synchronize cognitive ticks across subsystems.
- How it works
- Async timer driving periodic maintenance and scheduling cycles.
- Trade-off
- Fixed tick rates introduce slight latency overhead for ad-hoc user events.
- Source
- backend/app/kernel/clock/
Reference numerals
100Cognitive Kernel
120Cognitive Memory Management Unit (CMMU)
140Cognition Engines
160Unified Communication & Presentation
In operation
Execution Flow: Preemptive Cognitive Scheduling
How Leo scheduled concurrent background thinking tasks and prioritized an incoming interactive user message.
Input · illustrative, not a captured log
Interactive user message arrives via WebSocket while background graph indexing is executing.
- 10
Intake
UCI Gateway
Catches WebSocket payload, tags as Priority 1 (Interactive), and signals Kernel Interconnect.
StateInterrupt queued in Scheduler mailbox.
- 20
Preemption
DAG Scheduler
Pauses active Priority 4 (Associative Graph Indexing) task and saves execution checkpoint.
StateCompute resources reallocated to P1 task.
- 30
Memory Lookup
CMMU Gateway
Fetches active session state from Redis working memory and recent episodic vectors from PostgreSQL.
StateContext assembled for reasoning pipeline.
- 40
Reasoning
Cognition Engine
Executes LLM provider inference with automatic failover (Gemini -> Groq).
StateResponse synthesized in 1.8s.
- 50
Dispatch & Resume
DAG Scheduler & UCI
Emits response to user via WebSocket, then resumes the paused P4 background indexing task.
StateBackground graph indexing resumes from checkpoint.
Output
Instant user response delivered without interference from intensive background graph indexing.
Claims
Forensic Audit Findings & Reality Gap Analysis
- 1.
Subsystems Defined: 43
Granular separation across Kernel, Memory, Cognition, and Presentation layers.
Evidence: Lab note L017
Open findings, on the record
- 2.
Database Engines Managed: 3Under audit
Redis (Working) + PostgreSQL pgvector (Episodic) + Neo4j (Associative).
Evidence: Lab note L009 - 3.
Architectural Violations: 281Failed
Documented instances where application code bypassed the CMMU gatekeeper.
Evidence: Lab note L004 - 4.
Direct SQLAlchemy Sessions: 100%Failed
Essentially every repository module directly accessed SQLAlchemy rather than CMMU.
Evidence: Lab note L004
Test suite
Method
Decisions
Decision
DAG Execution Engine vs Linear Event Loop
Standard Python agents run synchronous `while True` loops that freeze the application whenever an external API or long-running tool is invoked.
| Option | For | Against |
|---|---|---|
| Simple asyncio event loop | Standard Python library, simple syntax. | No native priority queuing or dependency resolution across multi-step agent plans. |
| Priority-aware DAG Scheduler | Explicit dependency graphs, priority preemption (P1 user chat over P4 memory consolidation). | Significant architectural complexity and scheduling overhead. |
Chosen
Custom Priority DAG Scheduler
Why
Cost accepted
Decision
Three-Database Memory Architecture (Redis + Postgres + Neo4j)
Different cognitive memories have different access patterns: working memory is fast key-value, episodic is chronological vector, and associative is a network graph.
| Option | For | Against |
|---|---|---|
| Single relational database (PostgreSQL alone) | Single connection pool, transactional ACID guarantees. | Complex recursive Cypher-like queries required for associative relationship traversal. |
| Polyglot Persistence: Redis + Postgres + Neo4j mediated by CMMU | Optimal engine for each access pattern (sub-millisecond Redis cache, pgvector for history, Neo4j for graphs). | Enormous operational footprint, zero cross-database transaction guarantees, immense failure surface. |
Chosen
Polyglot Persistence (Redis + Postgres + Neo4j)
Why
Cost accepted
Deficiencies
What broke, why, and what changed because of it. These stay on the record next to everything that worked.
The Phase 28 Audit: 281 Direct Database Violations
CATASTROPHIC ARCHITECTURAL DRIFTFailure
A Phase 28 automated audit of the entire codebase revealed 281 direct database calls that completely bypassed the central CMMU gateway.
Root cause
The CMMU constraint was formalized after much of the application layer had already been written using direct SQLAlchemy `Session` queries. Because there was no CI linting rule preventing direct database imports, developers continued using direct connections for speed.
First attempt
Documenting the violations in a 286-line markdown table (`phase_28_x_2_violation_report.md`) and requesting manual refactoring.
Fix that held
The violation count was so vast across all 43 subsystems that retroactive migration proved impractical. The project was archived, and its lessons were codified into Vani's 'Phase 0 Architecture Before Features' and AST static analysis guardian.
Lesson
An architectural rule that is not enforced by a compiler or CI linter does not exist. Retroactive architectural enforcement on a large codebase is a massive, often fatal engineering undertaking.
Evidence: lab-content/Leo/004-281-violation-debt-architecture-enforcement.md
The Mock Testing Trap: Green CI While Live Systems Rotted
TESTING METHODOLOGY FAILUREFailure
Leo's test suite reported 95%+ pass rates, but the system repeatedly crashed when deployed against live databases and APIs.
Root cause
Developers mocked out database connections and external LLM endpoints so heavily that tests were only verifying that Python functions could call mocked return values. Invariant violations and schema mismatches in live PostgreSQL and Neo4j queries were completely hidden.
First attempt
Add more unit test cases with complex mock return structures.
Fix that held
Abandoned pure mock testing for cognitive architectures. Mandated live integration testing against disposable local container databases.
Lesson
Mocks verify your assumptions, not reality. Over-mocked test suites provide a dangerous illusion of security while live integrations decay.
Evidence: lab-content/Leo/008-TESTING_AND_VERIFICATION.md
Hard problems
01Cross-Database Distributed Consistency
Why it is hard
First approach
What failed
Final approach
Where it stands
02The Reality Gap: Architecture on Paper vs Code in Production
Why it is hard
First approach
What failed
Final approach
Where it stands
History
Late 2025
Phase 1–10 · completed
Kernel Foundations & DAG Scheduling
Implemented cognitive clock and priority-aware task execution engine.
Why
Solve agent priority inversion and enable concurrent background tasks.How
Python asyncio engine with custom graph resolution logic.Result
Demonstrated preemptive scheduling of interactive user turns over background workers.Early 2026
Phase 11–25 · completed
CMMU & Subsystem Explosion (43 Packages)
Added Redis, PostgreSQL, and Neo4j; expanded architecture to 43 subsystems.
Why
Attempt to provide specialized memory tiers for different cognitive tasks.How
Constructed multi-database adapters and Three.js 3D visual workspace.Result
Explosion in architectural complexity; rapid divergence between documentation and code.Mid 2026
Phase 28 · pivot
The Forensic Audit & Architectural Reckoning
Ran automated audit against CMMU gateway rules.
Why
Verify codebase conformance to the Architecture Constitution.How
Scripted codebase scanner cataloging direct database access.Result
Discovered 281 violations across all modules. Project superseded by Vani.
Measurements
281 VIOLATIONS DOCUMENTED (FAILED CONFORMANCE)
Phase 28.X.2 Architectural Conformance Audit
Audit revealed that the CMMU had become a decorative facade. Application code from API routers to anomaly managers established direct database connections.
- 281 direct database calls bypassing CMMU.
- Over-reliance on mock test suites masking live query syntax errors.
- High maintenance overhead of polyglot persistence (Redis + Postgres + Neo4j).
Status
Leo is permanently archived. Its architectural successes (DAG scheduler, temporal clock) and forensic audit lessons (281 violations) served as the direct conceptual foundation for Vani and ÆON.
Leo is archived. Its active evolution continues in ÆON.
Works today
- DAG Scheduler with priority task preemption.
- Unified Communication Interface handling multi-channel transports.
- Comprehensive forensic documentation of architectural debt.
Incomplete
- The CMMU migration was never completed due to 281 pervasive violations.
- Neo4j graph synchronization remained prone to split-brain states.
Remaining
- Archived repository serving as an open reference and engineering case study.
I would change today
- I would use a single database engine (PostgreSQL or SQLite) instead of three.
- I would enforce import boundaries with a CI AST linter from commit number one.
- I would build 5 core subsystems instead of 43 before writing application code.
Next
Lineage Continuation in ÆON
planned
The priority scheduling and cognitive clock primitives from Leo were redesigned into ÆON's 28-package acyclic monorepo.
Key Explorations & Architectural Precedents
Engineered an OS-style cognitive kernel with temporal clock synchronization and priority task preemption.
Directions under study
- Hardware-inspired MMU semantics (virtual addressing, paging, DMA) applied to AI cognitive memory.
- Real-time 3D WebGL memory topology visualization for inspecting agent knowledge clusters.
Possible contributions
- Case study documenting the failure of retroactive architectural governance in solo/small-team AI codebases.
“Leo was not a failure of vision, but a masterclass in engineering reality: an unenforced rule is a wish, polyglot databases create operational misery, and mock tests lie.”
Rules Must Be Enforced at Compile Time
You cannot document your way to architectural purity. If an import is illegal, a linter or test must break the build the moment it is written.
Reject Polyglot Persistence in Early Systems
Running Redis, PostgreSQL, and Neo4j simultaneously for a single agent introduces massive synchronization overhead. SQLite or PostgreSQL alone can handle 99% of early memory needs.
Beware the Lure of Over-Granular Subsystems
Defining 43 subsystems before having a hardened core runtime creates immense maintenance friction and encourages developers to take shortcuts.
Prior art
SHEET 12 / 12The foundational prototype that proved the validity of operating system metaphors for AI while providing the definitive lesson in architectural debt.
- Cited by Vani
- Direct successor born from Leo's lessons; instituted the AST Guardian to make the 281 violations impossible.