Part 2 · Architecture

System Architecture

The core brain, an 18-stage cognitive pipeline, 26 conversational intelligence components, five mode agents, the AI operating system, knowledge ingestion, and the word identity system.

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+)

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))

FieldTypeDefaultDescription
system_namestr"Condrox AI"Human-readable system identifier.
versionstr"3.4.0"Semantic version string.
max_input_lengthint4096Maximum number of characters accepted in a single raw input.
enable_single_instance_lockboolTruePrevents two brain instances from booting concurrently.
persistence_pathOptional[str]NoneFilesystem path for the SQLite database. When None, persistence is disabled.
memory_decay_halflife_secondsfloat86400.0Half-life for memory decay, in seconds. Defaults to one day.

18-Stage Cognitive Pipeline

File: core/pipeline/pipeline_orchestrator.py

#StageFileDescription
1Stage01Preprocessorstage_01_preprocessor.pyNormalizes raw text and tokenizes input for downstream stages.
2Stage02Intentstage_02_intent.pyClassifies intent using the Word Identity Engine, falling back to keyword matching when no word identity hit is found.
3Stage02bIntentEnrichmentstage_02b_intent_enrichment.pyExpands the classified intent using semantic context from prior turns.
4Stage03ModeSelectorstage_03_mode_selector.pyMaps the resolved intent to one of the five agent modes.
5Stage04DomainRouterstage_04_domain_router.pyClassifies the input into a knowledge domain and routes accordingly.
6Stage05ContextBuilderstage_05_context_builder.pyConstructs a hierarchical context window from system, session, and turn-level sources.
7Stage05bContextEnrichmentstage_05b_context_enrichment.pyAdds temporal context and enriches the window with multi-turn history.
8Stage06KnowledgeFetchstage_06_knowledge_fetch.pyRuns BM25 retrieval against the knowledge base. Skipped for greet, clarify, and emotional intents.
9Stage07MemoryFetchstage_07_memory_fetch.pyPerforms semantic memory search and traverses the memory graph for related entries.
10Stage08ReasoningCorestage_08_reasoning_core.pyRuns symbolic reasoning over the assembled context and ranks resulting claims.
11Stage08bAgentExecutionstage_08b_agent_execution.pyDispatches to the mode-specific agent and collects its output.
12Stage09Synthesisstage_09_synthesis.pySynthesizes the final response along one of three paths: conversational, emotional, or knowledge-grounded.
13Stage09bResponseQualitystage_09b_response_quality.pyApplies semantic repair, checks internal consistency, and flags contradictions.
14Stage10Personalitystage_10_personality.pyApplies personality profile styling to the synthesized response.
15Stage11Ethicsstage_11_ethics.pyValidates the response against content ethics policy.
16Stage12Securitystage_12_security.pyRuns the output security check before delivery.
17Stage13OutputBuilderstage_13_output_builder.pyAssembles the final output payload from all prior stage outputs.
18Stage14Deliverystage_14_delivery.pyApplies latency compensation and delivers the response to the caller.

Core Subsystems

Memory System

Knowledge System

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

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)

ComponentTestsDescription
StateQueryHandler12Provides safe introspection into brain state without exposing mutable internals.
SingleInstanceLock6Prevents two brain instances from booting at the same time.
MemoryStabilizationLayer12Compresses stored memories and applies decay based on age and access frequency.
SearchAgentGuard13Validates arguments passed to search agents before execution.

Phase 2-B: Conversational Quality (5 components)

ComponentTestsDescription
ResponseStyleEngine13Controls formality level and caps preamble length in generated responses.
ClaimRankerV211Ranks claims by verification confidence before synthesis.
TemporalContextLayer16Expires context entries based on a per-entry time-to-live.
OutputStabilizer11Normalizes output formatting and removes stray artifacts.
LanguageEnforcerV213Enforces language consistency across the generated response.

Phase 2-C: Observability & Safety (3 components)

ComponentTestsDescription
SafetyLayer15Detects PII, leaked secrets, and injection attempts in both input and output.
PipelineMonitor12Records per-stage timing and reports pipeline health metrics.
ErrorRecoveryLayer13Recovers from stage failures where possible and re-raises unrecoverable errors.

Phase 2-D: Agent Coordination (3 components)

ComponentTestsDescription
AgentArbiter13Resolves conflicts when multiple agents produce competing outputs.
KnowledgeRouterV215Routes knowledge queries to the correct domain index.
MultiAgentMemorySync19Synchronizes memory state across agents operating in the same session.

Phase 2-E: Advanced CI (7 components)

ComponentTestsDescription
SemanticIntentExpander13Expands the classified intent using surrounding conversational context.
MultiTurnReasoningEngine14Builds reasoning chains that span multiple conversation turns.
ConversationalMemoryGraph15Maintains a graph of relationships between stored memories.
DialogueGoalTracker14Tracks the active goal of a conversation and detects when it shifts.
ConsistencyEngine12Detects internal contradictions within a generated response.
SemanticRepair11Corrects semantic drift between the intended meaning and the produced text.
ContradictionDetector13Detects contradictions at the fact level across claims in the response.

Phase 2-F: System-Level Properties (4 components)

ComponentTestsDescription
LatencyCompensationLayer14Compensates for processing latency to keep response timing predictable.
TokenPressureRegulator15Budgets output length against the active token limit.
SemanticInterruptHandler12Handles user interruptions mid-conversation without losing context.
ConversationalPriorityEngine19Queues incoming requests by priority so urgent intents are served first.

2.3 Agent System (5 Modes)

Directory: core/agents/

AgentModeSub-intentsTestsDescription
CodeAgentcodegenerate, fix, review, refactor14Handles code generation, debugging, review, and refactoring tasks.
AnalyzeAgentanalyzeperformance, security, architecture, data9Runs performance analysis, security review, architecture assessment, and data analysis.
ArchitectAgentarchitectsystem, component, integration, migration8Produces system designs, component blueprints, integration plans, and migration strategies.
ExplainAgentexplainbrief, detailed, tutorial8Generates explanations, tutorials, and guides at three depth levels.
DefaultAgentdefaultfallback2Serves as the fallback when no mode matches the resolved intent.
Total5 modes63

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/

ComponentFileTestsDescription
EventBusevent_bus.py8Pub/sub message bus supporting 8 event types, backed by a 1000-entry ring buffer.
ServiceManagerservice_manager.py11Manages service lifecycle. Starts and stops services in topological order and auto-restarts failed services.
BootManagerboot_manager.py5Runs the 6 staged boot phases and tracks progress through each one.
MonitorLoopmonitor_loop.py3Daemon thread that polls every 5 seconds and collects health metrics from registered services.
StateManagerstate_manager.py6Checkpoints state to SQLite every 60 seconds and handles recovery on restart.
TaskQueuetask_queue.py7Priority task queue with a dedicated worker. Retries failed tasks using exponential backoff.
SelfRepairManagerself_repair.py8Runs circuit breakers, triggers auto-restart on failure, and probes services to verify recovery.
AIOSKernelaios_kernel.py3Central orchestrator that wires together the other seven OS subsystems.
Total8 files51

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

FileDomainWordsContent
social.jsonsocial~35Greetings, question words, and politeness markers.
emotion.jsonemotion~45Emotion vocabulary covering sad, angry, anxious, happy, grateful, confused, philosophical, and personal states.
programming.jsonprogramming~45Programming terms including code, algorithms, data structures, and debugging vocabulary.
architecture.jsonarchitecture~30Architecture terms covering design, analysis, trade-offs, and system architecture.
ai.jsonai~35AI and ML concepts, science terms, and explain-action verbs.
Total5 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

StageIntegration
Stage02IntentPrimary classifier. Runs the Word Identity Engine first, then falls back to keyword matching.
Stage02IntentEmotion detection. Checks Word Identity first, then falls back to EmotionDetector.
Stage03ModeSelectorMaps emotional intent to the default mode.
Stage06KnowledgeFetchSkips knowledge retrieval for emotional intent.
Stage09SynthesisRoutes emotional intent through the empathy response path.
Stage09bResponseQualitySkips semantic repair for emotional intent.
BrainControllerSkips the style engine and quality guardrail for emotional intent.