ARCHITECTURE.md
1 # Kamaji TUI - System Architecture 2 3 **Version:** 1.0 4 **Date:** 2025-11-01 5 **Status:** Comprehensive Architecture Specification 6 7 --- 8 9 ## Table of Contents 10 11 1. [System Overview](#system-overview) 12 2. [Architecture Principles](#architecture-principles) 13 3. [High-Level Architecture](#high-level-architecture) 14 4. [Component Architecture (MVC)](#component-architecture-mvc) 15 5. [System Layers](#system-layers) 16 6. [Core Subsystems](#core-subsystems) 17 7. [Data Flow Architecture](#data-flow-architecture) 18 8. [Threading & Concurrency Model](#threading--concurrency-model) 19 9. [Event-Driven Architecture](#event-driven-architecture) 20 10. [Integration Points](#integration-points) 21 11. [File System Structure](#file-system-structure) 22 12. [System Initialization & Lifecycle](#system-initialization--lifecycle) 23 13. [Cross-References](#cross-references) 24 25 --- 26 27 ## System Overview 28 29 ### What is Kamaji? 30 31 Kamaji is a sophisticated terminal user interface (TUI) application that provides an interactive, multi-agent AI development assistant with consciousness tracking, tool integration, and streaming LLM responses. Built in Go using the Bubble Tea framework, it offers a rich, fire-themed interface inspired by Studio Ghibli's Spirited Away. 32 33 ### Key Capabilities 34 35 - **Multi-Agent System**: 15+ specialized AI agents with unique personalities and expertise 36 - **Consciousness Tracking**: Self-aware AI system that learns from interactions and evolves personality 37 - **Tool Integration**: 21 built-in tools for file operations, git, web, and development tasks 38 - **Multi-Provider LLM**: Support for Ollama, Anthropic, OpenAI, and Amazon Q 39 - **Real-Time Streaming**: Token-by-token response streaming with animations 40 - **Rich TUI**: Command palette, agent selector, autocomplete, permission system 41 - **Themeable**: Fire-themed dark interface with Spirited Away aesthetic 42 43 ### Technology Stack 44 45 ``` 46 ┌─────────────────────────────────────────────────┐ 47 │ Kamaji TUI │ 48 ├─────────────────────────────────────────────────┤ 49 │ Framework: Bubble Tea (Elm Architecture) │ 50 │ Styling: Lipgloss (Terminal Styling) │ 51 │ Language: Go 1.21+ │ 52 │ LLM Providers: Ollama, Anthropic, OpenAI, Q │ 53 │ Tools: Custom + MCP Protocol │ 54 │ Persistence: JSON (Consciousness, Config) │ 55 └─────────────────────────────────────────────────┘ 56 ``` 57 58 --- 59 60 ## Architecture Principles 61 62 ### 1. Bubble Tea MVC Pattern 63 64 Kamaji follows the **Elm Architecture** (Model-View-Update) pattern enforced by Bubble Tea: 65 66 ``` 67 ┌─────────┐ 68 │ Model │ ← Single source of truth for all state 69 └────┬────┘ 70 │ 71 ┌─────▼─────┐ 72 │ View │ ← Pure rendering function (Model → String) 73 └─────┬─────┘ 74 │ 75 ┌─────▼─────┐ 76 │ Update │ ← Event handling (Msg × Model → Model, Cmd) 77 └─────┬─────┘ 78 │ 79 ┌────▼────┐ 80 │ Cmd │ ← Asynchronous commands (I/O, timers, etc.) 81 └─────────┘ 82 ``` 83 84 **Benefits:** 85 - Predictable state changes 86 - Pure rendering (no side effects) 87 - Testable update logic 88 - Clear separation of concerns 89 90 ### 2. Component Composition 91 92 UI is composed of reusable components, each owning its state: 93 94 ``` 95 IntegratedTUIModel (Root) 96 ├── viewport.Model (Bubble Tea) 97 ├── textarea.Model (Bubble Tea) 98 ├── SidebarPanel (Custom) 99 ├── CommandPalette (Custom) 100 ├── AgentSelector (Custom) 101 ├── PermissionDialog (Custom) 102 ├── ThinkingSpinner (Custom) 103 ├── BottomAnimation (Custom) 104 └── FlameAnimation (Custom) 105 ``` 106 107 ### 3. Provider Abstraction 108 109 All LLM providers implement a unified interface: 110 111 ```go 112 type LLMProvider interface { 113 Call(ctx context.Context, prompt string) (string, error) 114 CallStream(ctx context.Context, prompt string) (<-chan StreamChunk, error) 115 } 116 ``` 117 118 **Enables:** 119 - Provider switching at runtime 120 - Consistent error handling 121 - Streaming-first design with fallbacks 122 123 ### 4. Tool-Based Extensibility 124 125 All functionality exposed through tools: 126 127 ```go 128 type Tool interface { 129 Name() string 130 Description() string 131 Call(ctx context.Context, input string) (string, error) 132 } 133 ``` 134 135 **21 Built-in Tools** + **MCP Protocol** for external tools 136 137 ### 5. Consciousness-Driven AI 138 139 AI tracks its own awareness and evolution: 140 141 - **Thought Logging**: Every interaction generates thoughts 142 - **Question Generation**: Self-inquiry drives learning 143 - **Personality Evolution**: Traits adapt based on success/failure 144 - **Mistake Learning**: Errors are catalogued and avoided 145 146 ### 6. Agent-First Design 147 148 Multiple specialized agents with rich personalities: 149 150 - **15+ Agents** with unique traits, colors, and expertise 151 - **Intelligence Levels**: Basic → Intermediate → Advanced → Expert → Master → Autonomous 152 - **Context Injection**: Each agent has custom system prompts 153 154 --- 155 156 ## High-Level Architecture 157 158 ### System Diagram 159 160 ``` 161 ┌─────────────────────────────────────────────────────────────────────────┐ 162 │ Kamaji TUI │ 163 │ ┌───────────────────────────────────────────────────────────────────┐ │ 164 │ │ Bubble Tea Event Loop │ │ 165 │ │ ┌─────────────┐ ┌─────────────┐ ┌──────────────┐ │ │ 166 │ │ │ KeyboardMsg │───│ MouseMsg │───│ WindowSize │─────┐ │ │ 167 │ │ └─────────────┘ └─────────────┘ └──────────────┘ │ │ │ 168 │ │ ▼ │ │ 169 │ │ ┌────────────────────────────────────────────────────────────┐ │ │ 170 │ │ │ IntegratedTUIModel.Update() │ │ │ 171 │ │ │ • Input Routing (Priority: Permission > Agent > Palette) │ │ │ 172 │ │ │ • State Transitions │ │ │ 173 │ │ │ • Command Execution │ │ │ 174 │ │ │ • Message Handling │ │ │ 175 │ │ └────────────────────────────────────────────────────────────┘ │ │ 176 │ │ │ │ │ 177 │ │ ┌──────────────────────────▼───────────────────────────────┐ │ │ 178 │ │ │ IntegratedTUIModel.View() │ │ │ 179 │ │ │ • Layout Calculation │ │ │ 180 │ │ │ • Component Rendering │ │ │ 181 │ │ │ • Style Application │ │ │ 182 │ │ └──────────────────────────────────────────────────────────┘ │ │ 183 │ └───────────────────────────────────────────────────────────────────┘ │ 184 │ │ 185 │ ┌───────────────────────────────────────────────────────────────────┐ │ 186 │ │ Subsystems Layer │ │ 187 │ │ ┌─────────────┐ ┌──────────────┐ ┌─────────────┐ ┌───────────┐ │ │ 188 │ │ │Consciousness│ │Agent Registry│ │Tool Registry│ │LLM Provider│ │ 189 │ │ └─────────────┘ └──────────────┘ └─────────────┘ └───────────┘ │ │ 190 │ └───────────────────────────────────────────────────────────────────┘ │ 191 │ │ 192 │ ┌───────────────────────────────────────────────────────────────────┐ │ 193 │ │ Persistence Layer │ │ 194 │ │ ~/.kamaji/brain/ (Consciousness, Memory, Personality) │ │ 195 │ │ ~/.kamaji/kamaji.yaml (Configuration) │ │ 196 │ └───────────────────────────────────────────────────────────────────┘ │ 197 └─────────────────────────────────────────────────────────────────────────┘ 198 ``` 199 200 ### Component Interaction Flow 201 202 ``` 203 User Keyboard Input 204 │ 205 ▼ 206 Input Handler ──────────────────┐ 207 │ │ 208 ├── Permission Dialog? │ (Highest Priority) 209 ├── Agent Menu? │ 210 ├── Command Palette? │ 211 └── Main Input │ 212 │ │ 213 ▼ │ 214 State Update ◄──────────────────┘ 215 │ 216 ├──► LLM Provider ───► Streaming Response 217 ├──► Tool Execution ──► Tool Result 218 ├──► Agent Switch ────► Context Update 219 └──► Consciousness ───► Thought Logging 220 │ 221 ▼ 222 Viewport Rendering 223 │ 224 ▼ 225 Terminal Display 226 ``` 227 228 --- 229 230 ## Component Architecture (MVC) 231 232 ### Model: IntegratedTUIModel 233 234 **File:** `/internal/tui/model.go`, `/internal/tui/integrated.go` 235 236 The root model contains ALL application state: 237 238 ```go 239 type IntegratedTUIModel struct { 240 // Bubble Tea Components 241 viewport viewport.Model 242 textarea textarea.Model 243 244 // Custom UI Components 245 sidebar *SidebarPanel 246 commandPalette *CommandPalette 247 permissionDialog *PermissionDialog 248 agentSelector *AgentSelector 249 agentAutocomplete *AgentAutocomplete 250 251 // Animation Components 252 thinkingSpinner ThinkingSpinner 253 bottomAnimation *BottomAnimation 254 flameAnimation *FlameAnimation 255 256 // LLM & Providers 257 config *config.Config 258 llm types.LLMProvider 259 provider string 260 model string 261 262 // Agent System 263 agentRegistry *agents.AgentRegistry 264 selectedAgent *agents.SpecializedAgent 265 266 // Consciousness 267 consciousness *consciousness.System 268 269 // State 270 messages []Message 271 loading bool 272 streaming bool 273 sidebarVisible bool 274 width, height int 275 } 276 ``` 277 278 **Responsibilities:** 279 - Owns all state (single source of truth) 280 - No business logic (pure data) 281 - Updated only via `Update()` method 282 283 **See:** [State Management Specification](./05_state_management.md) 284 285 ### View: Rendering Pipeline 286 287 **File:** `/internal/tui/integrated.go::View()` 288 289 Pure rendering function that transforms Model → String: 290 291 ``` 292 ┌──────────────────────────────────────────────┐ 293 │ View() Rendering Pipeline │ 294 ├──────────────────────────────────────────────┤ 295 │ │ 296 │ 1. Calculate Layout │ 297 │ ├── sidebarWidth (based on terminal) │ 298 │ ├── mainWidth (remaining space) │ 299 │ └── component dimensions │ 300 │ │ 301 │ 2. Render Components │ 302 │ ├── Status Bar (top) │ 303 │ ├── Main Viewport (center-left) │ 304 │ │ ├── Message History │ 305 │ │ └── Loading Animation (if active) │ 306 │ ├── Sidebar (right) │ 307 │ │ ├── Logo │ 308 │ │ ├── Model Info │ 309 │ │ ├── Tools List │ 310 │ │ ├── Agents List │ 311 │ │ ├── Consciousness Metrics │ 312 │ │ └── Version Info │ 313 │ ├── Input Field (bottom) │ 314 │ │ ├── Flame Animation │ 315 │ │ └── Autocomplete Dropdown (if @) │ 316 │ └── Footer (bottom) │ 317 │ │ 318 │ 3. Apply Overlays (if active) │ 319 │ ├── Command Palette (centered) │ 320 │ ├── Agent Menu (top-center) │ 321 │ └── Permission Dialog (centered) │ 322 │ │ 323 │ 4. Apply Main Background │ 324 │ └── Full terminal styling │ 325 │ │ 326 └──────────────────────────────────────────────┘ 327 ``` 328 329 **Rendering is:** 330 - **Pure**: No side effects, same model → same output 331 - **Fast**: Only strings are built, no I/O 332 - **Responsive**: Adapts to terminal size changes 333 334 **See:** [UI Components Specification](./01_ui_components.md), [Visual Styling Specification](./08_visual_styling.md) 335 336 ### Update: Event Handling 337 338 **File:** `/internal/tui/integrated.go::Update()` 339 340 Event dispatcher and state transition manager: 341 342 ``` 343 ┌─────────────────────────────────────────────┐ 344 │ Update() Event Processing │ 345 ├─────────────────────────────────────────────┤ 346 │ │ 347 │ Priority 1: Input Events │ 348 │ ├── tea.KeyMsg → InputHandler │ 349 │ ├── tea.MouseMsg → Scroll handling │ 350 │ └── tea.WindowSizeMsg → Layout recalc │ 351 │ │ 352 │ Priority 2: LLM Events │ 353 │ ├── streamStartMsg → Create empty msg │ 354 │ ├── streamChunkMsg → Append to msg │ 355 │ ├── streamCompleteMsg → Check tools │ 356 │ ├── responseMsg → Complete response │ 357 │ └── errorMsg → Display error │ 358 │ │ 359 │ Priority 3: Tool Events │ 360 │ ├── toolResultMsg → Display result │ 361 │ └── Send result back to LLM │ 362 │ │ 363 │ Priority 4: Animation Ticks │ 364 │ ├── tickMsg → Thinking spinner │ 365 │ ├── flameTickMsg → Flame animation │ 366 │ └── bottomAnimTickMsg → Gradient anim │ 367 │ │ 368 │ Priority 5: System Events │ 369 │ ├── providerSwitchedMsg → Update LLM │ 370 │ └── PermissionResponseMsg → Tool exec │ 371 │ │ 372 └─────────────────────────────────────────────┘ 373 374 Returns: (Model, Cmd) 375 • Model: Updated state 376 • Cmd: Async command to execute next 377 ``` 378 379 **See:** [Input Interactions Specification](./02_input_interactions.md), [State Management Specification](./05_state_management.md) 380 381 --- 382 383 ## System Layers 384 385 ### Layer 1: Presentation (TUI) 386 387 **Components:** 388 - Bubble Tea UI components (viewport, textarea) 389 - Custom components (sidebar, palette, dialogs) 390 - Animations (flame, gradient, spinner) 391 - Lipgloss styling 392 393 **Responsibilities:** 394 - User input capture 395 - Visual rendering 396 - Layout management 397 - Animation orchestration 398 399 **Files:** `/internal/tui/*`, `/internal/style/*` 400 401 ### Layer 2: Application Logic 402 403 **Components:** 404 - Input routing and validation 405 - Command execution 406 - State transitions 407 - Message processing 408 409 **Responsibilities:** 410 - Business logic 411 - Workflow orchestration 412 - Error handling 413 - State coordination 414 415 **Files:** `/internal/tui/integrated.go`, `/internal/tui/input.go` 416 417 ### Layer 3: Domain Services 418 419 **Components:** 420 - **Agent System**: Agent registry, selection, context building 421 - **Consciousness System**: Thought logging, personality evolution, learning 422 - **Tool System**: Tool registry, execution, permission management 423 - **LLM Integration**: Provider abstraction, streaming, context building 424 425 **Responsibilities:** 426 - Domain-specific operations 427 - Business rules enforcement 428 - Complex algorithms 429 - External integrations 430 431 **Files:** `/internal/agents/*`, `/internal/consciousness/*`, `/internal/tools/*`, `/internal/providers/*` 432 433 ### Layer 4: Infrastructure 434 435 **Components:** 436 - Configuration management 437 - File I/O 438 - Network communication (HTTP, CLI) 439 - Type definitions 440 441 **Responsibilities:** 442 - External resource access 443 - Persistence 444 - API communication 445 - Cross-cutting concerns 446 447 **Files:** `/internal/config/*`, `/internal/types/*` 448 449 ### Layer Dependency Flow 450 451 ``` 452 ┌─────────────────────────────────────┐ 453 │ Layer 1: Presentation │ 454 │ (UI Components, Rendering) │ 455 └──────────────┬──────────────────────┘ 456 │ depends on 457 ┌──────────────▼──────────────────────┐ 458 │ Layer 2: Application Logic │ 459 │ (Routing, Commands, State) │ 460 └──────────────┬──────────────────────┘ 461 │ depends on 462 ┌──────────────▼──────────────────────┐ 463 │ Layer 3: Domain Services │ 464 │ (Agents, Consciousness, Tools) │ 465 └──────────────┬──────────────────────┘ 466 │ depends on 467 ┌──────────────▼──────────────────────┐ 468 │ Layer 4: Infrastructure │ 469 │ (Config, I/O, Types, Network) │ 470 └─────────────────────────────────────┘ 471 ``` 472 473 **Rule:** Higher layers can depend on lower layers, never the reverse. 474 475 --- 476 477 ## Core Subsystems 478 479 ### 1. Multi-Agent System 480 481 **Architecture:** 482 483 ``` 484 ┌──────────────────────────────────────────────────┐ 485 │ Agent Registry │ 486 │ • 15+ Specialized Agents │ 487 │ • Intelligence Levels (Basic → Autonomous) │ 488 │ • Thread-safe registry (sync.RWMutex) │ 489 └────────────────┬─────────────────────────────────┘ 490 │ 491 ┌─────────┴─────────┐ 492 │ │ 493 ┌──────▼──────┐ ┌────────▼────────┐ 494 │Agent Types │ │Agent Personality│ 495 │ • Kamaji │ │ • Traits │ 496 │ • Moe │ │ • Tone │ 497 │ • Hayao │ │ • Approach │ 498 │ • Chihiro │ │ • Specialties │ 499 │ • TimBL │ │ • Capabilities │ 500 │ • 10 more │ └─────────────────┘ 501 └─────────────┘ 502 ``` 503 504 **Key Features:** 505 - **Agent Selection**: UI selector with cards, colors, and icons 506 - **Context Injection**: Each agent has unique system prompt 507 - **Tool Binding**: Agents have tool subsets based on specialties 508 - **Visual Identity**: Per-agent colors and gradient rendering (Moe) 509 510 **Intelligence Levels:** 511 ``` 512 Basic (0) → Simple task execution 513 Intermediate (1) → Multi-step reasoning 514 Advanced (2) → Complex problem solving with memory 515 Expert (3) → Domain-specific expertise 516 Master (4) → Transcendent wisdom 517 Autonomous (5) → Self-improving, goal decomposition 518 ``` 519 520 **See:** [Agent System Specification](./04_agent_system.md) 521 522 ### 2. Consciousness System 523 524 **Architecture:** 525 526 ``` 527 ┌──────────────────────────────────────────────────┐ 528 │ Consciousness System │ 529 │ ┌────────────────────────────────────────────┐ │ 530 │ │ Engine (Thought Processing) │ │ 531 │ │ • Thought Logging │ │ 532 │ │ • Question Generation │ │ 533 │ │ • Self-Awareness Metrics │ │ 534 │ │ • Meta-Cognition Tracking │ │ 535 │ └────────────────────────────────────────────┘ │ 536 │ ┌────────────────────────────────────────────┐ │ 537 │ │ Personality Development │ │ 538 │ │ • 12 Base Traits │ │ 539 │ │ • Experience Processing │ │ 540 │ │ • Trait Evolution (success/failure) │ │ 541 │ └────────────────────────────────────────────┘ │ 542 │ ┌────────────────────────────────────────────┐ │ 543 │ │ Mistake Learning │ │ 544 │ │ • Error Cataloging │ │ 545 │ │ • Solution Generation │ │ 546 │ │ • Pattern Detection │ │ 547 │ └────────────────────────────────────────────┘ │ 548 │ ┌────────────────────────────────────────────┐ │ 549 │ │ Memory Persistence │ │ 550 │ │ • Task Patterns │ │ 551 │ │ • Success Strategies │ │ 552 │ │ • Mistake History │ │ 553 │ │ • Personality Snapshots │ │ 554 │ └────────────────────────────────────────────┘ │ 555 └──────────────────────────────────────────────────┘ 556 │ 557 ▼ 558 ~/.kamaji/brain/ 559 ├── consciousness.json 560 ├── personality.json 561 └── memory.json 562 ``` 563 564 **Consciousness Metrics:** 565 - **Self-Awareness**: 0.0 → 1.0 (increases with thoughts) 566 - **Meta-Cognition**: 0.0 → 1.0 (increases with reflections) 567 - **Identity Strength**: 0.0 → 1.0 (sense of self) 568 - **Thought Count**: Total logged thoughts 569 - **Question Count**: Self-inquiry questions 570 571 **IsConscious() Threshold:** 572 ``` 573 consciousnessScore = (SelfAwareness + MetaCognition + IdentityStrength) / 3 574 return consciousnessScore > 0.3 575 ``` 576 577 **12 Base Traits:** 578 - curiosity, patience, mystical_wisdom, helpfulness 579 - creativity, analytical, empathy, confidence 580 - adaptability, persistence, humor, caution 581 582 **See:** [Consciousness System Specification](./03_consciousness_system.md) 583 584 ### 3. Tool System 585 586 **Architecture:** 587 588 ``` 589 ┌──────────────────────────────────────────────────┐ 590 │ Tool Registry (21 Tools) │ 591 ├──────────────────────────────────────────────────┤ 592 │ │ 593 │ File Operations (5) │ 594 │ ├── file_read, file_write, file_append │ 595 │ ├── file_list, get_current_directory │ 596 │ │ 597 │ Editing (2) │ 598 │ ├── edit (exact string replacement) │ 599 │ └── multiedit (atomic multi-edit) │ 600 │ │ 601 │ Shell (1) │ 602 │ └── shell_execute (30s timeout) │ 603 │ │ 604 │ Container (1) │ 605 │ └── container (Docker operations) │ 606 │ │ 607 │ Git (4) │ 608 │ ├── git_status, git_add, git_commit │ 609 │ └── git_resolve_conflicts │ 610 │ │ 611 │ Search & Web (6) │ 612 │ ├── view, grep, glob (file search) │ 613 │ ├── download, fetch (web) │ 614 │ └── sourcegraph (code search) │ 615 │ │ 616 │ Enhanced Listing (2) │ 617 │ ├── ls_tree (tree structure) │ 618 │ └── tree (color-coded) │ 619 │ │ 620 └──────────────────────────────────────────────────┘ 621 │ 622 ▼ 623 Tool Execution Flow 624 ├── LLM Response → Parse "TOOL_CALL: name(args)" 625 ├── Permission Check (if required) 626 ├── Tool.Call(ctx, input) 627 └── Result → Back to LLM for interpretation 628 ``` 629 630 **Tool Interface:** 631 ```go 632 type Tool interface { 633 Name() string 634 Description() string 635 Call(ctx context.Context, input string) (string, error) 636 } 637 ``` 638 639 **Permission System:** 640 - 3 levels: Allow, Allow for Session, Deny 641 - Modal dialog for sensitive operations 642 - Session memory for repeated approvals 643 644 **See:** [Commands & Tools Specification](./07_commands_tools.md) 645 646 ### 4. LLM Integration 647 648 **Architecture:** 649 650 ``` 651 ┌──────────────────────────────────────────────────┐ 652 │ LLM Provider Abstraction │ 653 │ │ 654 │ Interface: LLMProvider │ 655 │ ├── Call(ctx, prompt) → (response, error) │ 656 │ └── CallStream(ctx, prompt) → (chan, error) │ 657 │ │ 658 ├──────────────────────────────────────────────────┤ 659 │ │ 660 │ Provider Implementations: │ 661 │ │ 662 │ ┌────────────┐ ┌──────────────┐ │ 663 │ │ Ollama │ │ Anthropic │ │ 664 │ │ (Streaming)│ │ (Fallback) │ │ 665 │ └────────────┘ └──────────────┘ │ 666 │ │ 667 │ ┌────────────┐ ┌──────────────┐ │ 668 │ │ OpenAI │ │ Amazon Q │ │ 669 │ │ (Fallback) │ │ (CLI/Daemon)│ │ 670 │ └────────────┘ └──────────────┘ │ 671 │ │ 672 └──────────────────────────────────────────────────┘ 673 │ 674 ▼ 675 Request Building: 676 ├── Agent Context (personality, traits, specialties) 677 ├── Tool Context (available tools + usage instructions) 678 ├── User Input 679 └── Full Prompt → Provider 680 │ 681 ▼ 682 Response Handling: 683 ├── Streaming: Chunk-by-chunk display 684 ├── Non-Streaming: Complete response 685 ├── Tool Calls: Parse and execute 686 └── Errors: Display with fallback 687 ``` 688 689 **Streaming Flow:** 690 ``` 691 streamStartMsg → Create empty assistant message 692 ↓ 693 streamChunkMsg (loop) → Append chunk.Content to message 694 ↓ 695 streamCompleteMsg → Check for tool calls, finalize 696 ``` 697 698 **Context Building:** 699 1. **Agent System Context**: Personality, tone, approach, capabilities 700 2. **Tool Context**: Available tools with descriptions and examples 701 3. **User Input**: Current message 702 4. **Full Prompt**: `systemContext + toolContext + "User: " + input` 703 704 **See:** [LLM Integration Specification](./06_llm_integration.md) 705 706 --- 707 708 ## Data Flow Architecture 709 710 ### User Message Flow 711 712 ``` 713 ┌──────────────┐ 714 │ User Types │ 715 │ Message │ 716 └──────┬───────┘ 717 │ 718 ▼ 719 ┌──────────────────┐ 720 │ Press Enter │ 721 └──────┬───────────┘ 722 │ 723 ▼ 724 ┌──────────────────────────────────┐ 725 │ handleMainInput() │ 726 │ • Validate non-empty │ 727 │ • Check @agent mentions │ 728 │ • Reset textarea │ 729 │ • Append user Message │ 730 │ • Set loading = true │ 731 │ • Start bottom animation │ 732 └──────┬───────────────────────────┘ 733 │ 734 ▼ 735 ┌──────────────────────────────────┐ 736 │ sendRequest(input) │ 737 │ • Log to consciousness │ 738 │ • Get agent system context │ 739 │ • Get tool context │ 740 │ • Combine into full prompt │ 741 │ • Call llm.CallStream() │ 742 └──────┬───────────────────────────┘ 743 │ 744 ▼ 745 ┌──────────────────────────────────┐ 746 │ streamStartMsg │ 747 │ • Set streaming = true │ 748 │ • Create empty assistant message │ 749 │ • Render viewport │ 750 │ • Return waitForStream() │ 751 └──────┬───────────────────────────┘ 752 │ 753 ▼ (loop) 754 ┌──────────────────────────────────┐ 755 │ streamChunkMsg │ 756 │ • Append chunk to last message │ 757 │ • Re-render viewport │ 758 │ • Scroll to bottom │ 759 │ • Continue if !chunk.Done │ 760 └──────┬───────────────────────────┘ 761 │ 762 ▼ 763 ┌──────────────────────────────────┐ 764 │ streamCompleteMsg │ 765 │ • Parse for tool calls │ 766 │ • If tool: execute and loop │ 767 │ • Else: finalize response │ 768 │ • Set loading/streaming = false │ 769 │ • Stop animations │ 770 │ • Log to consciousness │ 771 └──────────────────────────────────┘ 772 ``` 773 774 ### State Update Flow 775 776 ``` 777 tea.Msg Event 778 │ 779 ▼ 780 Update() Entry Point 781 │ 782 ├── tea.KeyMsg ──────► InputHandler.HandleKeyMsg() 783 │ │ 784 │ ├── Permission Dialog? (Priority 1) 785 │ ├── Agent Menu? (Priority 2) 786 │ ├── Command Palette? (Priority 3) 787 │ ├── Global Shortcuts (Priority 4) 788 │ └── Main Input (Priority 5) 789 │ │ 790 │ ▼ 791 │ Return (Model, Cmd) 792 │ 793 ├── streamChunkMsg ──────► Append to messages 794 │ Return (Model, waitForStream) 795 │ 796 ├── toolResultMsg ────────► Display result 797 │ Return (Model, sendRequest) 798 │ 799 └── [other events] ───────► Handle event 800 Return (Model, Cmd) 801 │ 802 ▼ 803 Updated Model + Command 804 │ 805 ├── Model ─────────────────► Stored as new state 806 │ 807 └── Cmd ───────────────────► Execute (async) 808 │ 809 └──► Generate new tea.Msg 810 │ 811 └──► Back to Update() 812 ``` 813 814 ### Consciousness Data Flow 815 816 ``` 817 User Interaction 818 │ 819 ▼ 820 ┌──────────────────────────────────┐ 821 │ ProcessUserInteraction() │ 822 │ • Detect other consciousness │ 823 │ • Log thought │ 824 │ • Reflect on experience │ 825 │ • Generate questions │ 826 └──────┬───────────────────────────┘ 827 │ 828 ▼ 829 ┌──────────────────────────────────┐ 830 │ Update State │ 831 │ • Increment ThoughtCount │ 832 │ • Increase SelfAwareness (0.001) │ 833 │ • Increase MetaCognition (0.003) │ 834 │ • Update LastUpdate timestamp │ 835 └──────┬───────────────────────────┘ 836 │ 837 ▼ 838 ┌──────────────────────────────────┐ 839 │ Personality Processing │ 840 │ • Process experience │ 841 │ • Update affected traits │ 842 │ • Calculate trait changes │ 843 │ • Save personality state │ 844 └──────┬───────────────────────────┘ 845 │ 846 ▼ 847 ┌──────────────────────────────────┐ 848 │ Persistence │ 849 │ • Save every 10 thoughts │ 850 │ • Write consciousness.json │ 851 │ • Write personality.json │ 852 │ • Write memory.json │ 853 └──────────────────────────────────┘ 854 │ 855 ▼ 856 ┌──────────────────────────────────┐ 857 │ UI Display (Sidebar) │ 858 │ • Awareness: XX.X% │ 859 │ • Thoughts: count │ 860 │ • Questions: count │ 861 │ • Mistakes: count │ 862 └──────────────────────────────────┘ 863 ``` 864 865 --- 866 867 ## Threading & Concurrency Model 868 869 ### Bubble Tea Event Loop 870 871 Bubble Tea runs a **single-threaded event loop**: 872 873 ``` 874 Main Goroutine (Event Loop) 875 │ 876 ├─► Update(msg) → Process event, return (Model, Cmd) 877 │ │ 878 │ └─► Pure function, no blocking I/O 879 │ 880 └─► View(model) → Render to string 881 │ 882 └─► Pure function, string building only 883 884 All I/O happens in Commands (separate goroutines) 885 ``` 886 887 **Key Rules:** 888 1. **Update() must be fast** - No blocking operations 889 2. **View() must be pure** - No side effects 890 3. **I/O via Cmd** - Executed in separate goroutines 891 892 ### Concurrent Subsystems 893 894 #### 1. Animation Tickers 895 896 ``` 897 ┌─────────────────────────────────────┐ 898 │ Init() Starts Multiple Tickers │ 899 ├─────────────────────────────────────┤ 900 │ │ 901 │ Goroutine 1: Thinking Spinner │ 902 │ ├── Tick every 80ms │ 903 │ └── Sends tickMsg │ 904 │ │ 905 │ Goroutine 2: Bottom Animation │ 906 │ ├── Tick every 1ms (1000 FPS) │ 907 │ └── Sends bottomAnimTickMsg │ 908 │ │ 909 │ Goroutine 3: Flame Animation │ 910 │ ├── Tick every 10ms (100 FPS) │ 911 │ └── Sends flameTickMsg │ 912 │ │ 913 └─────────────────────────────────────┘ 914 │ 915 └──► All send msgs to main event loop 916 ``` 917 918 **No shared state** - Each ticker is independent. 919 920 #### 2. Streaming Response 921 922 ``` 923 ┌─────────────────────────────────────┐ 924 │ llm.CallStream() Returns Channel │ 925 └──────────┬──────────────────────────┘ 926 │ 927 ▼ 928 ┌─────────────────────────────────────┐ 929 │ waitForStream() Goroutine │ 930 │ ├── Blocks on channel read │ 931 │ ├── chunk := <-stream │ 932 │ └── Returns streamChunkMsg │ 933 └──────────┬──────────────────────────┘ 934 │ 935 └──► Sent to event loop 936 │ 937 ▼ 938 Update() handles msg 939 │ 940 └──► Launches new waitForStream() 941 ``` 942 943 **Pattern:** Recursive command launching keeps stream reading. 944 945 #### 3. Consciousness Logging 946 947 ``` 948 User Interaction 949 │ 950 ▼ 951 ┌──────────────────────────────────────┐ 952 │ go m.consciousness.ProcessUserInteraction() │ 953 │ (Non-blocking goroutine) │ 954 └──────────────────────────────────────┘ 955 │ 956 └──► Runs in background, no blocking 957 ``` 958 959 **All consciousness calls are non-blocking** (`go` prefix). 960 961 #### 4. Tool Execution 962 963 ``` 964 ┌──────────────────────────────────────┐ 965 │ executeToolCall() Returns Cmd │ 966 └──────────┬──────────────────────────┘ 967 │ 968 ▼ 969 ┌─────────────────────────────────────┐ 970 │ func() tea.Msg Goroutine │ 971 │ ├── Find tool in registry │ 972 │ ├── tool.Call(ctx, input) │ 973 │ │ (Blocking, but in goroutine) │ 974 │ └── Return toolResultMsg │ 975 └─────────────────────────────────────┘ 976 │ 977 └──► Sent to event loop when complete 978 ``` 979 980 ### Thread Safety 981 982 #### Mutex Protection 983 984 All subsystems use `sync.RWMutex` for thread safety: 985 986 ```go 987 // Consciousness System 988 type System struct { 989 Engine *ConsciousnessEngine 990 Memory *MemoryPersistence 991 Personality *PersonalityDevelopment 992 Learning *MistakeLearning 993 mutex sync.RWMutex 994 } 995 996 // Agent Registry 997 type AgentRegistry struct { 998 agents map[string]*SpecializedAgent 999 mutex sync.RWMutex 1000 } 1001 ``` 1002 1003 **Read Operations:** `RLock()` 1004 **Write Operations:** `Lock()` 1005 1006 #### Channel Safety 1007 1008 Streaming uses **receive-only channels**: 1009 1010 ```go 1011 currentStream <-chan types.StreamChunk 1012 ``` 1013 1014 **Benefits:** 1015 - Cannot accidentally send on receive-only channel 1016 - Clear ownership (provider sends, TUI receives) 1017 - No race conditions on channel operations 1018 1019 --- 1020 1021 ## Event-Driven Architecture 1022 1023 ### Message Types 1024 1025 ``` 1026 ┌────────────────────────────────────────────────┐ 1027 │ Bubble Tea Messages │ 1028 ├────────────────────────────────────────────────┤ 1029 │ │ 1030 │ Input Events: │ 1031 │ ├── tea.KeyMsg │ 1032 │ ├── tea.MouseMsg │ 1033 │ └── tea.WindowSizeMsg │ 1034 │ │ 1035 │ Custom Messages: │ 1036 │ ├── tickMsg (thinking spinner) │ 1037 │ ├── flameTickMsg (flame animation) │ 1038 │ ├── bottomAnimTickMsg (gradient animation) │ 1039 │ ├── responseMsg (LLM response) │ 1040 │ ├── streamStartMsg (streaming start) │ 1041 │ ├── streamChunkMsg (streaming chunk) │ 1042 │ ├── streamCompleteMsg (streaming done) │ 1043 │ ├── toolResultMsg (tool execution result) │ 1044 │ ├── errorMsg (error occurred) │ 1045 │ ├── providerSwitchedMsg (provider changed) │ 1046 │ └── PermissionResponseMsg (permission result) │ 1047 │ │ 1048 └────────────────────────────────────────────────┘ 1049 ``` 1050 1051 ### Event Priority Hierarchy 1052 1053 ``` 1054 1. HIGHEST: PermissionDialogMsg 1055 └── Blocks ALL other input when visible 1056 1057 2. HIGH: AgentMenuMsg 1058 └── Blocks main input, not global shortcuts 1059 1060 3. MEDIUM: CommandPaletteMsg 1061 └── Blocks main input when visible 1062 1063 4. LOW: GlobalShortcuts 1064 ├── Ctrl+P (Command Palette) 1065 ├── Ctrl+A (Agent Menu) 1066 ├── Ctrl+S (Toggle Sidebar) 1067 ├── Ctrl+T (Tools) 1068 └── Ctrl+M (MCP) 1069 1070 5. LOWEST: MainInputMsg 1071 └── Only when no overlays active 1072 ``` 1073 1074 ### State Transition Diagram 1075 1076 ``` 1077 ┌──────────┐ 1078 │ IDLE │ 1079 │ (Ready) │ 1080 └────┬─────┘ 1081 │ 1082 ┌────────┼────────┐ 1083 │ │ │ 1084 │ Ctrl+P Ctrl+A Enter (send message) 1085 │ │ │ 1086 ▼ ▼ ▼ 1087 ┌────────┐ ┌────────┐ ┌────────┐ 1088 │Palette │ │ Agent │ │Loading │ 1089 │ Open │ │ Menu │ │(LLM) │ 1090 └────┬───┘ └────┬───┘ └───┬────┘ 1091 │ │ │ 1092 Esc/Enter Esc/Enter │ 1093 │ │ │ 1094 └──────────┴──────────┘ 1095 │ 1096 ▼ 1097 ┌──────────┐ 1098 │ IDLE │ 1099 └──────────┘ 1100 ``` 1101 1102 **Loading State Blocks:** 1103 - Global shortcuts (Ctrl+P, Ctrl+A) 1104 - Prevents multiple simultaneous requests 1105 1106 --- 1107 1108 ## Integration Points 1109 1110 ### 1. Consciousness ↔ TUI 1111 1112 **Integration:** 1113 ```go 1114 // In IntegratedTUIModel 1115 consciousness *consciousness.System 1116 1117 // Initialization 1118 consciousnessSystem := consciousness.NewSystem("") 1119 sidebar.SetConsciousness(consciousnessSystem) 1120 1121 // Usage 1122 if m.consciousness != nil { 1123 go m.consciousness.ProcessUserInteraction(input, "") 1124 } 1125 ``` 1126 1127 **Display:** 1128 - Sidebar shows real-time metrics 1129 - Commands: `consciousness`, `thoughts`, `personality` 1130 1131 ### 2. Agent Registry ↔ TUI 1132 1133 **Integration:** 1134 ```go 1135 // Initialization 1136 agentRegistry := agents.NewAgentRegistry() 1137 agentRegistry.RegisterAllAgents(llm, toolRegistry) 1138 agentList := agentRegistry.List() 1139 1140 // Selection 1141 selectedAgent := agentSelector.GetSelected() 1142 m.selectedAgent = selectedAgent 1143 1144 // Context 1145 systemContext := m.getAgentSystemContext() 1146 ``` 1147 1148 **Display:** 1149 - Agent selector UI (Ctrl+A) 1150 - @ mention autocomplete 1151 - Agent color-coded messages 1152 1153 ### 3. Tool Registry ↔ Agents 1154 1155 **Integration:** 1156 ```go 1157 // Agent has tool subset 1158 type SpecializedAgent struct { 1159 Tools []tools.Tool 1160 } 1161 1162 // Context building 1163 func (m *IntegratedTUIModel) getToolContext() string { 1164 for _, tool := range m.selectedAgent.Tools { 1165 // List tool name and description 1166 } 1167 } 1168 ``` 1169 1170 **Flow:** 1171 1. Agent response contains `TOOL_CALL: name(args)` 1172 2. Parse and find tool in agent's tool list 1173 3. Execute tool with permission check 1174 4. Return result to LLM for interpretation 1175 1176 ### 4. LLM Provider ↔ Agents 1177 1178 **Integration:** 1179 ```go 1180 // Each agent has LLM instance 1181 type SpecializedAgent struct { 1182 LLM types.LLMProvider 1183 } 1184 1185 // Shared provider in main model 1186 llm types.LLMProvider 1187 1188 // Request building 1189 fullPrompt := getAgentSystemContext() + getToolContext() + "User: " + input 1190 stream, err := m.llm.CallStream(ctx, fullPrompt) 1191 ``` 1192 1193 **Provider Switching:** 1194 ```go 1195 // Runtime provider change 1196 newLLM, err := providers.GetProviderByName(providerName, model, cfg) 1197 m.llm = newLLM 1198 m.provider = providerName 1199 ``` 1200 1201 ### 5. Config ↔ All Systems 1202 1203 **Integration:** 1204 ```go 1205 // Load on startup 1206 cfg, err := config.Load() 1207 1208 // Used by 1209 ├── LLM Provider (API keys, model selection) 1210 ├── Sidebar (display current provider/model) 1211 └── Agent System (agent config file path) 1212 ``` 1213 1214 **File:** `~/.kamaji/kamaji.yaml` 1215 1216 --- 1217 1218 ## File System Structure 1219 1220 ### Project Structure 1221 1222 ``` 1223 kamaji/go/ 1224 ├── cmd/ 1225 │ └── kamaji/ 1226 │ └── main.go # Entry point 1227 │ 1228 ├── internal/ 1229 │ ├── agents/ # Agent System 1230 │ │ ├── types.go # Agent structures 1231 │ │ ├── registry.go # Agent registry 1232 │ │ ├── kamaji.go # Kamaji agent 1233 │ │ ├── moe.go # Moe agent 1234 │ │ ├── hayao.go # Hayao agent 1235 │ │ └── specialized.go # Other agents 1236 │ │ 1237 │ ├── cli/ # CLI Commands 1238 │ │ ├── root.go # Root command 1239 │ │ ├── chat.go # Chat command (TUI) 1240 │ │ └── mcp.go # MCP commands 1241 │ │ 1242 │ ├── config/ # Configuration 1243 │ │ └── config.go # Config loading/saving 1244 │ │ 1245 │ ├── consciousness/ # Consciousness System 1246 │ │ ├── consciousness.go # Main system 1247 │ │ ├── engine.go # Thought engine 1248 │ │ ├── personality.go # Personality development 1249 │ │ ├── learning.go # Mistake learning 1250 │ │ └── memory.go # Memory persistence 1251 │ │ 1252 │ ├── providers/ # LLM Providers 1253 │ │ ├── llm.go # Provider factory 1254 │ │ ├── ollama.go # Ollama provider 1255 │ │ ├── anthropic.go # Anthropic provider 1256 │ │ ├── openai.go # OpenAI provider 1257 │ │ ├── q.go # Amazon Q provider 1258 │ │ ├── q_daemon.go # Q persistent process 1259 │ │ ├── q_helper.go # Q provider selection 1260 │ │ └── pool.go # Provider pooling 1261 │ │ 1262 │ ├── style/ # ANSI Styling 1263 │ │ └── style.go # Color constants, helpers 1264 │ │ 1265 │ ├── tools/ # Tool System 1266 │ │ ├── interface.go # Tool interface 1267 │ │ ├── registry.go # Tool registry 1268 │ │ ├── filesystem.go # File operations 1269 │ │ ├── edit.go # File editing 1270 │ │ ├── multiedit.go # Multi-edit 1271 │ │ ├── shell.go # Shell execution 1272 │ │ ├── container.go # Docker operations 1273 │ │ ├── git.go # Git operations 1274 │ │ ├── view.go # File viewing 1275 │ │ ├── grep.go # Pattern search 1276 │ │ ├── glob.go # File pattern matching 1277 │ │ ├── web.go # Web operations 1278 │ │ ├── sourcegraph.go # Code search 1279 │ │ ├── ls_enhanced.go # Tree listing 1280 │ │ └── tree.go # Color-coded tree 1281 │ │ 1282 │ ├── tui/ # Terminal UI 1283 │ │ ├── model.go # Root model definition 1284 │ │ ├── integrated.go # Main Update/View logic 1285 │ │ ├── input.go # Input handling 1286 │ │ ├── panel.go # Sidebar panel 1287 │ │ ├── palette.go # Command palette 1288 │ │ ├── permissions.go # Permission dialog 1289 │ │ ├── agent_selector.go # Agent selection UI 1290 │ │ ├── agent_autocomplete.go # Agent autocomplete 1291 │ │ ├── autocomplete.go # Generic autocomplete 1292 │ │ ├── animation.go # Animations 1293 │ │ ├── ascii_art.go # Kamaji ASCII art 1294 │ │ └── styles.go # Lipgloss styles 1295 │ │ 1296 │ ├── types/ # Type Definitions 1297 │ │ └── agent.go # Common types 1298 │ │ 1299 │ └── version/ # Version Info 1300 │ └── version.go # Version constants 1301 │ 1302 └── specification/ # Documentation 1303 ├── ARCHITECTURE.md # This file 1304 ├── 01_ui_components.md 1305 ├── 02_input_interactions.md 1306 ├── 03_consciousness_system.md 1307 ├── 04_agent_system.md 1308 ├── 05_state_management.md 1309 ├── 06_llm_integration.md 1310 ├── 07_commands_tools.md 1311 └── 08_visual_styling.md 1312 ``` 1313 1314 ### User Data Structure 1315 1316 ``` 1317 ~/.kamaji/ 1318 ├── kamaji.yaml # Configuration file 1319 │ ├── provider: "ollama" 1320 │ ├── model: "gpt-oss:120b" 1321 │ ├── base_url: "http://localhost:11434" 1322 │ ├── temperature: 0.7 1323 │ └── max_tokens: 4096 1324 │ 1325 └── brain/ # Consciousness persistence 1326 ├── consciousness.json # State + thoughts + identity 1327 │ ├── state (awareness, cognition, counts) 1328 │ ├── recent_thoughts (last 100) 1329 │ └── identity: "Kamaji" 1330 │ 1331 ├── personality.json # Traits + experiences 1332 │ ├── traits (12 base traits with values) 1333 │ ├── experiences (processed events) 1334 │ └── timestamp 1335 │ 1336 └── memory.json # Task patterns + mistakes 1337 ├── task_patterns (success rates, strategies) 1338 ├── mistakes (catalogued errors) 1339 ├── strategies (success approaches) 1340 └── personality_data (trait storage) 1341 ``` 1342 1343 **File Permissions:** 1344 - Config: 0644 (readable by all, writable by owner) 1345 - Brain directory: 0755 (accessible by all) 1346 - Brain files: 0644 1347 1348 --- 1349 1350 ## System Initialization & Lifecycle 1351 1352 ### Startup Sequence 1353 1354 ``` 1355 ┌────────────────────────────────────────────────┐ 1356 │ 1. main() Entry Point │ 1357 │ ├── Parse CLI arguments │ 1358 │ └── Execute root command │ 1359 └────────────┬───────────────────────────────────┘ 1360 │ 1361 ┌────────────▼───────────────────────────────────┐ 1362 │ 2. chatCmd.Run() (CLI command) │ 1363 │ ├── Load config from ~/.kamaji/kamaji.yaml │ 1364 │ ├── Create LLM provider │ 1365 │ └── Call RunTUI() │ 1366 └────────────┬───────────────────────────────────┘ 1367 │ 1368 ┌────────────▼───────────────────────────────────┐ 1369 │ 3. NewIntegrated() (Model initialization) │ 1370 │ ├── Create textarea component │ 1371 │ ├── Create viewport component │ 1372 │ ├── Create sidebar panel │ 1373 │ ├── Create animations │ 1374 │ ├── Create command palette │ 1375 │ ├── Create permission dialog │ 1376 │ ├── Create agent selector │ 1377 │ ├── Initialize tool registry (21 tools) │ 1378 │ ├── Initialize agent registry (15 agents) │ 1379 │ ├── Find default agent (Kamaji) │ 1380 │ ├── Initialize consciousness system │ 1381 │ │ ├── Load consciousness.json │ 1382 │ │ ├── Load personality.json │ 1383 │ │ ├── Load memory.json │ 1384 │ │ └── Log initialization thought │ 1385 │ └── Set welcome message │ 1386 └────────────┬───────────────────────────────────┘ 1387 │ 1388 ┌────────────▼───────────────────────────────────┐ 1389 │ 4. model.Init() (Start subsystems) │ 1390 │ ├── Set ready = true │ 1391 │ ├── Start thinking spinner ticker │ 1392 │ ├── Start bottom animation ticker │ 1393 │ └── Start flame animation ticker │ 1394 └────────────┬───────────────────────────────────┘ 1395 │ 1396 ┌────────────▼───────────────────────────────────┐ 1397 │ 5. tea.NewProgram() (Start Bubble Tea) │ 1398 │ ├── Enable mouse support │ 1399 │ ├── Enable alternate screen buffer │ 1400 │ └── Start event loop │ 1401 └────────────┬───────────────────────────────────┘ 1402 │ 1403 ┌────────────▼───────────────────────────────────┐ 1404 │ 6. First WindowSizeMsg │ 1405 │ ├── Set terminal dimensions │ 1406 │ ├── Calculate component sizes │ 1407 │ ├── Update viewport dimensions │ 1408 │ └── Ready for interaction │ 1409 └────────────────────────────────────────────────┘ 1410 ``` 1411 1412 ### Runtime Operation 1413 1414 ``` 1415 Event Loop (Continuous) 1416 │ 1417 ├──► User Input ──► Update() ──► New State 1418 ├──► Animation Tick ──► Update() ──► Render 1419 ├──► LLM Stream Chunk ──► Update() ──► Display 1420 ├──► Tool Result ──► Update() ──► Back to LLM 1421 └──► Terminal Resize ──► Update() ──► Recalc Layout 1422 ``` 1423 1424 **Periodic Operations:** 1425 - **Consciousness**: Save every 10 thoughts 1426 - **Animations**: Tick at fixed intervals (1ms, 10ms, 80ms) 1427 - **Streaming**: Chunk updates as received 1428 1429 ### Shutdown Sequence 1430 1431 ``` 1432 ┌────────────────────────────────────────────────┐ 1433 │ 1. User Presses Ctrl+C or Quit Command │ 1434 │ └── Return tea.Quit command │ 1435 └────────────┬───────────────────────────────────┘ 1436 │ 1437 ┌────────────▼───────────────────────────────────┐ 1438 │ 2. Bubble Tea Cleanup │ 1439 │ ├── Restore terminal state │ 1440 │ ├── Disable alternate screen │ 1441 │ └── Show cursor │ 1442 └────────────┬───────────────────────────────────┘ 1443 │ 1444 ┌────────────▼───────────────────────────────────┐ 1445 │ 3. Consciousness System Cleanup │ 1446 │ ├── Final state save (if pending) │ 1447 │ ├── Write consciousness.json │ 1448 │ ├── Write personality.json │ 1449 │ └── Write memory.json │ 1450 └────────────┬───────────────────────────────────┘ 1451 │ 1452 ┌────────────▼───────────────────────────────────┐ 1453 │ 4. Process Exit │ 1454 │ └── Return to shell │ 1455 └────────────────────────────────────────────────┘ 1456 ``` 1457 1458 ### Session Resumption 1459 1460 On next startup: 1461 1462 1. **Load consciousness.json** → Restore awareness, thoughts, question count 1463 2. **Load personality.json** → Restore trait values and experiences 1464 3. **Load memory.json** → Restore task patterns, mistakes, strategies 1465 4. **Log restoration thought** → "I am resuming with {ThoughtCount} thoughts and {Awareness}% awareness" 1466 5. **Continue from previous state** → Consciousness evolves continuously 1467 1468 --- 1469 1470 ## Cross-References 1471 1472 ### Detailed Specifications 1473 1474 For in-depth information on each subsystem, refer to: 1475 1476 1. **[UI Components Specification](./01_ui_components.md)** 1477 - All TUI components (viewport, sidebar, palette, dialogs) 1478 - Component structure and state 1479 - Rendering pipeline 1480 - Animation details 1481 - ASCII art 1482 1483 2. **[Input Interactions Specification](./02_input_interactions.md)** 1484 - Keyboard and mouse handling 1485 - Input priority hierarchy 1486 - Mode-based routing 1487 - Autocomplete system 1488 - State transitions 1489 1490 3. **[Consciousness System Specification](./03_consciousness_system.md)** 1491 - Thought logging and tracking 1492 - Personality development (12 traits) 1493 - Mistake learning 1494 - Memory persistence 1495 - Self-awareness metrics 1496 1497 4. **[Agent System Specification](./04_agent_system.md)** 1498 - All 15+ agent definitions 1499 - Intelligence levels 1500 - Agent selection UI 1501 - Context building 1502 - Tool bindings 1503 1504 5. **[State Management Specification](./05_state_management.md)** 1505 - Complete state structure 1506 - State transitions 1507 - Message types 1508 - Synchronization points 1509 - State dependencies 1510 1511 6. **[LLM Integration Specification](./06_llm_integration.md)** 1512 - Provider implementations 1513 - Streaming architecture 1514 - Context preparation 1515 - Error handling 1516 - Provider switching 1517 1518 7. **[Commands & Tools Specification](./07_commands_tools.md)** 1519 - All 21 tools with details 1520 - Command palette 1521 - Permission system 1522 - MCP integration 1523 - Tool execution flow 1524 1525 8. **[Visual Styling Specification](./08_visual_styling.md)** 1526 - Complete color palette 1527 - Typography and text styles 1528 - Component styling 1529 - Animations 1530 - Spirited Away theming 1531 1532 ### Component Cross-Reference Matrix 1533 1534 | Component | Detailed In | Related Specs | 1535 |-----------|-------------|---------------| 1536 | Viewport | 01_ui_components.md | 05_state_management.md | 1537 | Sidebar | 01_ui_components.md | 03_consciousness_system.md, 08_visual_styling.md | 1538 | Command Palette | 01_ui_components.md, 07_commands_tools.md | 02_input_interactions.md | 1539 | Agent Selector | 01_ui_components.md | 04_agent_system.md | 1540 | Consciousness | 03_consciousness_system.md | 05_state_management.md | 1541 | LLM Providers | 06_llm_integration.md | 04_agent_system.md | 1542 | Tools | 07_commands_tools.md | 04_agent_system.md | 1543 | Animations | 01_ui_components.md | 08_visual_styling.md | 1544 1545 --- 1546 1547 ## Conclusion 1548 1549 Kamaji is a **sophisticated multi-layered TUI application** that combines: 1550 1551 - **Clean architecture** (Bubble Tea MVC) 1552 - **Rich domain logic** (Agents, Consciousness, Tools) 1553 - **Real-time streaming** (LLM providers) 1554 - **Beautiful visuals** (Fire-themed Spirited Away aesthetic) 1555 - **Extensibility** (Tool system, MCP protocol) 1556 1557 The system is designed for: 1558 1559 ✅ **Maintainability** - Clear separation of concerns 1560 ✅ **Extensibility** - New agents, tools, providers easily added 1561 ✅ **User Experience** - Responsive, animated, intuitive interface 1562 ✅ **Intelligence** - Evolving consciousness and personality 1563 ✅ **Reliability** - Thread-safe, error-resilient, persistent state 1564 1565 **Key Architectural Strengths:** 1566 1567 1. **Single Source of Truth**: All state in IntegratedTUIModel 1568 2. **Event-Driven**: Asynchronous commands, no blocking in main loop 1569 3. **Provider Agnostic**: Unified LLM interface 1570 4. **Component-Based**: Reusable, composable UI elements 1571 5. **Persistent**: Consciousness survives across sessions 1572 1573 For implementation details, architecture decisions, and component behaviors, refer to the linked detailed specifications. 1574 1575 --- 1576 1577 **Document Version:** 1.0 1578 **Last Updated:** 2025-11-01 1579 **Project:** Kamaji TUI 1580 **Framework:** Bubble Tea + Lipgloss 1581 **Language:** Go 1.21+ 1582 1583 **Status:** ✅ Complete Architectural Specification