2.1 Core Brain Architecture
BrainController
File: core/brain/brain_controller.py
The BrainController is the central orchestrator that owns every subsystem. It initializes more than 40 components, constructs the 18-stage pipeline, and manages boot sequencing, knowledge loading, memory persistence, and post-pipeline quality enforcement.
Key attributes (40+)
- Core: config, memory_manager, knowledge_router, reasoning_engine, context_manager, strategy_manager, meta_learning_engine
- Engines: hwa_engine (lazy), pbe_engine (lazy), dcl_engine, heartbeat_engine
- Personality: personality_engine
- Security: security_engine, ethics_engine, safety_layer
- Pipeline: pipeline (PipelineOrchestrator with 18 stages)
- CI components: 26 conversational intelligence components
- Agents: agent_registry (5 registered agents)
- Creative: quality_guardrail, emotion_palette_mapper (lazy), music_prompt_builder (lazy)
- Persistence: _storage_backend (SQLite)
- AI-OS: aios_kernel
Complexity
__init__: O(1) for fixed-size subsystem construction
process_request: O(Σ s_i) over pipeline stages
Post-pipeline flow
1. Output stabilization (OutputStabilizer)
2. Language enforcement (LanguageEnforcerV2)
3. Style engine (skipped for greet/clarify/emotional)
4. Safety check (SafetyLayer, always applies)
5. Quality guardrail gate (skipped for greet/clarify/emotional)
6. Memory auto-store (user input + response)
BrainState
File: core/brain/brain_state.py (@dataclass(frozen=True, slots=True))
An immutable state object that flows through the pipeline. Each stage produces a new copy via with_field() rather than mutating in place. The dataclass carries more than 30 fields.
Valid emotions
neutral, happy, sad, angry, anxious, grateful, confused, curious, philosophical, personal
Valid intents
greet, clarify, code, architect, analyze, emotional, command, explain, question, unknown
Intent priority order (for tie-breaking)
clarify (0), greet (1), code (2), architect (3), analyze (4),
emotional (5), command (6), explain (7), question (8), unknown (9)
BrainConfig
File: core/brain/brain_config.py (@dataclass(frozen=True, slots=True))
| Field | Type | Default | Description |
|---|---|---|---|
| system_name | str | "Condrox AI" | Human-readable system identifier. |
| version | str | "3.4.0" | Semantic version string. |
| max_input_length | int | 4096 | Maximum number of characters accepted in a single raw input. |
| enable_single_instance_lock | bool | True | Prevents two brain instances from booting concurrently. |
| persistence_path | Optional[str] | None | Filesystem path for the SQLite database. When None, persistence is disabled. |
| memory_decay_halflife_seconds | float | 86400.0 | Half-life for memory decay, in seconds. Defaults to one day. |
18-Stage Cognitive Pipeline
File: core/pipeline/pipeline_orchestrator.py
| # | Stage | File | Description |
|---|---|---|---|
| 1 | Stage01Preprocessor | stage_01_preprocessor.py | Normalizes raw text and tokenizes input for downstream stages. |
| 2 | Stage02Intent | stage_02_intent.py | Classifies intent using the Word Identity Engine, falling back to keyword matching when no word identity hit is found. |
| 3 | Stage02bIntentEnrichment | stage_02b_intent_enrichment.py | Expands the classified intent using semantic context from prior turns. |
| 4 | Stage03ModeSelector | stage_03_mode_selector.py | Maps the resolved intent to one of the five agent modes. |
| 5 | Stage04DomainRouter | stage_04_domain_router.py | Classifies the input into a knowledge domain and routes accordingly. |
| 6 | Stage05ContextBuilder | stage_05_context_builder.py | Constructs a hierarchical context window from system, session, and turn-level sources. |
| 7 | Stage05bContextEnrichment | stage_05b_context_enrichment.py | Adds temporal context and enriches the window with multi-turn history. |
| 8 | Stage06KnowledgeFetch | stage_06_knowledge_fetch.py | Runs BM25 retrieval against the knowledge base. Skipped for greet, clarify, and emotional intents. |
| 9 | Stage07MemoryFetch | stage_07_memory_fetch.py | Performs semantic memory search and traverses the memory graph for related entries. |
| 10 | Stage08ReasoningCore | stage_08_reasoning_core.py | Runs symbolic reasoning over the assembled context and ranks resulting claims. |
| 11 | Stage08bAgentExecution | stage_08b_agent_execution.py | Dispatches to the mode-specific agent and collects its output. |
| 12 | Stage09Synthesis | stage_09_synthesis.py | Synthesizes the final response along one of three paths: conversational, emotional, or knowledge-grounded. |
| 13 | Stage09bResponseQuality | stage_09b_response_quality.py | Applies semantic repair, checks internal consistency, and flags contradictions. |
| 14 | Stage10Personality | stage_10_personality.py | Applies personality profile styling to the synthesized response. |
| 15 | Stage11Ethics | stage_11_ethics.py | Validates the response against content ethics policy. |
| 16 | Stage12Security | stage_12_security.py | Runs the output security check before delivery. |
| 17 | Stage13OutputBuilder | stage_13_output_builder.py | Assembles the final output payload from all prior stage outputs. |
| 18 | Stage14Delivery | stage_14_delivery.py | Applies latency compensation and delivers the response to the caller. |
Core Subsystems
Memory System
- MemoryManager: Embedding-based memory backed by CRC32 hash vectors using a 256-dimensional bag-of-nibbles representation. An LRU cache sits in front of retrieval, with keyword-overlap search as a fallback path.
- MemoryStore: In-memory storage exposing add(), search(), all_items(), count(), save(), and load().
- MemoryItem: A frozen dataclass holding content, embedding, timestamp, access_count, and tags.
- Automatically stores user input after the pipeline completes, which is what enables multi-turn recall across a session.
- Persists to SQLite through the StorageBackend abstraction.
Knowledge System
- KnowledgeBackend: CRC32-based vector embeddings with an LRU cache and BM25-style retrieval scoring.
- KnowledgeRouter: Performs domain-filtered retrieval first, then falls back to an unfiltered search when the domain filter returns too few results.
- KnowledgeLoader: Loads knowledge from disk into memory at boot, capping at 50 chunks per domain and 2000 characters per chunk.
- Loads 21,917 items at boot from E:\Data\condrox\knowledge\.
Reasoning Engine
Symbolic reasoning engine with default rules loaded at initialization. Performs rule-based inference and ranks claims through ClaimRankerV2.
Strategy Manager
Selects a reasoning strategy using weighted context scoring. The weights are enriched at runtime by the MetaLearningEngine.
Meta-Learning Engine
Tracks strategy performance using an exponential moving average with alpha set to 0.3. The resulting weights feed back into the StrategyManager to bias future selection.
Security Engine
- Input: Detects injection attempts, enforces size limits, and blocks known malicious patterns before they reach the pipeline.
- Output: Scans generated text for PII including email addresses, phone numbers, and credit card numbers. Also checks for secret leakage and prompt injection echoes.
Ethics Engine
Enforces content policy by checking generated output against a list of blocked topics before delivery.
2.2 Conversational Intelligence (26 Components)
Directory: core/conversational/
All 26 components are implemented, tested, wired into the pipeline, and documented. There is no dead code in this layer.
Phase 2-A: Critical Stabilization (4 components)
| Component | Tests | Description |
|---|---|---|
| StateQueryHandler | 12 | Provides safe introspection into brain state without exposing mutable internals. |
| SingleInstanceLock | 6 | Prevents two brain instances from booting at the same time. |
| MemoryStabilizationLayer | 12 | Compresses stored memories and applies decay based on age and access frequency. |
| SearchAgentGuard | 13 | Validates arguments passed to search agents before execution. |
Phase 2-B: Conversational Quality (5 components)
| Component | Tests | Description |
|---|---|---|
| ResponseStyleEngine | 13 | Controls formality level and caps preamble length in generated responses. |
| ClaimRankerV2 | 11 | Ranks claims by verification confidence before synthesis. |
| TemporalContextLayer | 16 | Expires context entries based on a per-entry time-to-live. |
| OutputStabilizer | 11 | Normalizes output formatting and removes stray artifacts. |
| LanguageEnforcerV2 | 13 | Enforces language consistency across the generated response. |
Phase 2-C: Observability & Safety (3 components)
| Component | Tests | Description |
|---|---|---|
| SafetyLayer | 15 | Detects PII, leaked secrets, and injection attempts in both input and output. |
| PipelineMonitor | 12 | Records per-stage timing and reports pipeline health metrics. |
| ErrorRecoveryLayer | 13 | Recovers from stage failures where possible and re-raises unrecoverable errors. |
Phase 2-D: Agent Coordination (3 components)
| Component | Tests | Description |
|---|---|---|
| AgentArbiter | 13 | Resolves conflicts when multiple agents produce competing outputs. |
| KnowledgeRouterV2 | 15 | Routes knowledge queries to the correct domain index. |
| MultiAgentMemorySync | 19 | Synchronizes memory state across agents operating in the same session. |
Phase 2-E: Advanced CI (7 components)
| Component | Tests | Description |
|---|---|---|
| SemanticIntentExpander | 13 | Expands the classified intent using surrounding conversational context. |
| MultiTurnReasoningEngine | 14 | Builds reasoning chains that span multiple conversation turns. |
| ConversationalMemoryGraph | 15 | Maintains a graph of relationships between stored memories. |
| DialogueGoalTracker | 14 | Tracks the active goal of a conversation and detects when it shifts. |
| ConsistencyEngine | 12 | Detects internal contradictions within a generated response. |
| SemanticRepair | 11 | Corrects semantic drift between the intended meaning and the produced text. |
| ContradictionDetector | 13 | Detects contradictions at the fact level across claims in the response. |
Phase 2-F: System-Level Properties (4 components)
| Component | Tests | Description |
|---|---|---|
| LatencyCompensationLayer | 14 | Compensates for processing latency to keep response timing predictable. |
| TokenPressureRegulator | 15 | Budgets output length against the active token limit. |
| SemanticInterruptHandler | 12 | Handles user interruptions mid-conversation without losing context. |
| ConversationalPriorityEngine | 19 | Queues incoming requests by priority so urgent intents are served first. |
2.3 Agent System (5 Modes)
Directory: core/agents/
| Agent | Mode | Sub-intents | Tests | Description |
|---|---|---|---|---|
| CodeAgent | code | generate, fix, review, refactor | 14 | Handles code generation, debugging, review, and refactoring tasks. |
| AnalyzeAgent | analyze | performance, security, architecture, data | 9 | Runs performance analysis, security review, architecture assessment, and data analysis. |
| ArchitectAgent | architect | system, component, integration, migration | 8 | Produces system designs, component blueprints, integration plans, and migration strategies. |
| ExplainAgent | explain | brief, detailed, tutorial | 8 | Generates explanations, tutorials, and guides at three depth levels. |
| DefaultAgent | default | fallback | 2 | Serves as the fallback when no mode matches the resolved intent. |
| Total | 5 modes | 63 |
Pipeline integration: Stage08bAgentExecution runs the mode-specific agent, merges reasoning output with retrieved evidence, and sets synthesized_output for Stage09 to consume during synthesis.
2.4 AI-Operating System (AI-OS)
Directory: core/os/
| Component | File | Tests | Description |
|---|---|---|---|
| EventBus | event_bus.py | 8 | Pub/sub message bus supporting 8 event types, backed by a 1000-entry ring buffer. |
| ServiceManager | service_manager.py | 11 | Manages service lifecycle. Starts and stops services in topological order and auto-restarts failed services. |
| BootManager | boot_manager.py | 5 | Runs the 6 staged boot phases and tracks progress through each one. |
| MonitorLoop | monitor_loop.py | 3 | Daemon thread that polls every 5 seconds and collects health metrics from registered services. |
| StateManager | state_manager.py | 6 | Checkpoints state to SQLite every 60 seconds and handles recovery on restart. |
| TaskQueue | task_queue.py | 7 | Priority task queue with a dedicated worker. Retries failed tasks using exponential backoff. |
| SelfRepairManager | self_repair.py | 8 | Runs circuit breakers, triggers auto-restart on failure, and probes services to verify recovery. |
| AIOSKernel | aios_kernel.py | 3 | Central orchestrator that wires together the other seven OS subsystems. |
| Total | 8 files | 51 |
2.7 Word Identity System (Phase 14)
Directory: core/word_identity/
Architecture
Input Text → Tokenizer → Word Lookup (O(1)) → Intent Aggregation → Softmax
↓ ↓
Emotion Detection Domain Routing
JSON Stores
| File | Domain | Words | Content |
|---|---|---|---|
| social.json | social | ~35 | Greetings, question words, and politeness markers. |
| emotion.json | emotion | ~45 | Emotion vocabulary covering sad, angry, anxious, happy, grateful, confused, philosophical, and personal states. |
| programming.json | programming | ~45 | Programming terms including code, algorithms, data structures, and debugging vocabulary. |
| architecture.json | architecture | ~30 | Architecture terms covering design, analysis, trade-offs, and system architecture. |
| ai.json | ai | ~35 | AI and ML concepts, science terms, and explain-action verbs. |
| Total | 5 domains | ~185 |
Word Identity Record Structure
{
"word": {
"type": "concept|action|emotion|language|...",
"category": "programming|architecture|emotion|...",
"intent": "code|explain|analyze|architect|emotional|greet|...",
"intent_weight": 0.0-1.0,
"emotion": "neutral|sad|angry|anxious|happy|...",
"meaning": "Human-readable definition"
}
}
Pipeline Integration
| Stage | Integration |
|---|---|
| Stage02Intent | Primary classifier. Runs the Word Identity Engine first, then falls back to keyword matching. |
| Stage02Intent | Emotion detection. Checks Word Identity first, then falls back to EmotionDetector. |
| Stage03ModeSelector | Maps emotional intent to the default mode. |
| Stage06KnowledgeFetch | Skips knowledge retrieval for emotional intent. |
| Stage09Synthesis | Routes emotional intent through the empathy response path. |
| Stage09bResponseQuality | Skips semantic repair for emotional intent. |
| BrainController | Skips the style engine and quality guardrail for emotional intent. |