TunaCode Codebase Map
Generated: 2026-01-04
Project: TunaCode - TUI Code Agent
Source Directory: src/tunacode/
Version: 0.1.20
Python Version: 3.11-3.13
Statistics
| Metric |
Value |
| Total Python files analyzed |
134 |
| Documentation files generated |
28 |
| Documentation size |
~196 KB |
| SEAMS analysis dimensions |
Structure, Architecture, Modules, State |
| Analysis depth |
0 (root-level) |
| Analysis tool |
Gemini MCP (gemini-2.5-flash, gemini-2.5-pro) |
Structure Overview
src/tunacode/
├── ui/ # Presentation layer (Textual TUI)
│ ├── app.py # Main TextualReplApp
│ ├── screens/ # Modal dialogs (setup, picker, confirm)
│ ├── widgets/ # Custom widgets (Editor, ResourceBar)
│ ├── renderers/ # Output formatting (tools, panels)
│ ├── commands/ # UI command handlers (/help, /model)
│ ├── headless/ # Non-interactive mode
│ └── styles/ # CSS and theming
│
├── core/ # Agent orchestration & business logic
│ ├── agents/ # AI agent implementations
│ │ ├── main.py # Primary agent (process_request)
│ │ ├── research_agent.py
│ │ └── agent_components/
│ │ ├── agent_config.py # get_or_create_agent()
│ │ ├── node_processor.py # Response processing
│ │ ├── tool_executor.py # Parallel execution
│ │ └── state_transition.py # Agent state machine
│ ├── state.py # StateManager, SessionState
│ ├── prompting/ # Prompt construction
│ ├── setup/ # Setup wizard
│ ├── background/ # Async tasks
│ └── token_usage/ # Cost tracking
│
├── tools/ # Agent capabilities & system interactions
│ ├── bash.py # Shell execution
│ ├── grep.py # Content search (smart/ripgrep/python)
│ ├── glob.py # File pattern matching
│ ├── read_file.py # File reading
│ ├── write_file.py # File creation
│ ├── update_file.py # File editing (fuzzy matching)
│ ├── list_dir.py # Directory listing
│ ├── web_fetch.py # HTTP requests
│ ├── todo.py # TODO management
│ ├── decorators.py # @base_tool, @file_tool
│ ├── grep_components/ # Search implementation
│ └── tools_utils/ # Shared utilities
│
├── configuration/ # Settings, models, pricing
│ ├── settings.py # User preferences
│ ├── models.py # Model registry
│ ├── models_registry.json
│ ├── pricing.py # Cost tracking
│ └── defaults.py # Factory defaults
│
├── cli/ # Command-line interface
│ ├── commands/ # Slash commands
│ └── repl_components/ # REPL building blocks
│
├── lsp/ # Language Server Protocol client
│ └── client.py # LSPClient, diagnostics
│
├── services/ # External service integrations
│ └── (currently empty)
│
├── types/ # Type definitions
│ ├── base.py # ModelName, ToolName aliases
│ ├── dataclasses.py # UserConfig, AgentRun
│ ├── state.py # MessageHistory, ToolArgs
│ └── callbacks.py # Callback types
│
├── utils/ # Shared utilities
│ ├── config/ # User configuration loading
│ ├── messaging/ # Token counting, message utils
│ ├── parsing/ # JSON, command parsing
│ ├── system/ # Gitignore, paths
│ └── ui/ # File filtering
│
├── prompts/ # Modular prompt sections
│ ├── sections/ # agent_role.md, critical_rules.md
│ └── research/sections/ # Research-specific prompts
│
├── tutorial/ # Interactive tutorials
├── tools_utils/ # Shared tool utilities
├── exceptions.py # Custom exception hierarchy
├── constants.py # Global constants, UI themes
└── py.typed # PEP 561 compliance marker
Detailed Module Index
Core Modules
| Module |
Purpose |
Key Exports |
Seams |
| core/agents |
AI agent orchestration |
process_request, RequestOrchestrator, get_or_create_agent |
M, D |
| core/state |
Session state management |
StateManager, SessionState |
M |
| core/prompting |
System prompt composition |
PromptingEngine, SectionLoader |
M, D |
| ui/ |
Textual TUI interface |
TextualReplApp, screens, renderers |
M, D |
| tools/ |
Agent capabilities |
base_tool, file_tool, ToolHandler, bash, grep, read_file |
M, D |
Supporting Modules
| Module |
Purpose |
Key Exports |
Seams |
| configuration/ |
Settings & models |
load_user_config, ModelRegistry, get_pricing |
M |
| types/ |
Type definitions |
UserConfig, MessageHistory, ModelName, ToolCallback |
M |
| utils/ |
Shared utilities |
estimate_tokens, estimate_message_tokens, parse_json |
M |
| lsp/ |
Language Server Protocol |
LSPClient, get_diagnostics |
M |
| prompts/ |
Prompt templates |
agent_role.md, critical_rules.md |
M |
| cli/ |
Command-line interface |
REPL commands, slash commands |
M, D |
| exceptions.py |
Exception hierarchy |
TunaCodeError, ToolExecutionError |
M |
| constants.py |
Global constants |
UI_COLORS, TOOL_NAMES, themes |
M |
SEAMS Summary
Structure Analysis
The Structure Agent completed a comprehensive depth 0 analysis of the TunaCode source code:
Key Findings:
- Layered Architecture: Clean separation between Presentation (UI/CLI), Business Logic (Core), Capabilities (Tools), and Configuration
- Modular Organization: High cohesion, low coupling, single responsibility principle
- Type Safety: Full type annotation coverage with centralized type definitions
- Error Handling: Rich exception hierarchy with actionable recovery guidance
- NeXTSTEP Design: Consistent UI/UX following classic interface guidelines
Design Patterns Identified:
- Agent Pattern (Core) - Specialized agents with delegation
- Decorator Pattern (Tools) - Cross-cutting concerns via decorators
- Builder Pattern (Prompting) - Dynamic prompt construction
- Component Pattern (UI) - Reusable widgets and screens
- Strategy Pattern (Configuration) - Multiple configuration sources
- Observer Pattern (UI/Core) - Callback-based communication
- Composite Pattern (Delegation) - Agents as tools
Entry Points
Primary Entry Point: <repo_root>/src/tunacode/ui/main.py
- Instantiates global StateManager singleton
- Launches TextualReplApp
CLI Entry: <repo_root>/src/tunacode/cli/
- Command-line interface via Typer
- REPL mode with slash commands
Note: Entry analysis was not explicitly documented. Manual inspection reveals the above entry points.
Architecture Analysis
Architectural Pattern: Pragmatic layered architecture with strong component-based design
Key Architectural Decisions:
- UI/Core Decoupling: Callback-based communication enables headless execution
- Modular System Prompts: Composable prompt sections for maintainability
- Agent as Iterator: Pull-based model for consuming agent execution
- Centralized State Management: Single source of truth in StateManager
Data Flow:
USER INPUT → UI Capture → Request Queue → process_request()
→ Agent.iter() → LLM API → Tool Selection → Tool Dispatch
→ Tool Execution → Response Rendering → State Update
Circular Dependency Note: Core ↔ Tools have a circular dependency:
- Core imports tool functions for agent configuration
- Tools import from Core for state management and delegation
Modules Summary
Core Agent Orchestration:
process_request() in main.py creates RequestOrchestrator
- Agent components: agent_config, node_processor, tool_executor, tool_buffer
- Delegation system: research_agent with read-only tools
- State machine: AgentStateMachine with valid transitions
UI Module:
- TextualReplApp with screens, widgets, renderers
- Screen management: ModelPicker, SessionPicker, Setup, ThemePicker
- Renderer system: RichPanelRenderer with 4-zone NeXTSTEP layout
- Specialized tool renderers: bash, glob, grep, read_file, etc.
- Custom widgets: Editor, ResourceBar, StatusBar
Tools Module:
- Decorator system: @base_tool, @file_tool with XML prompt files
- Tool implementations: bash, grep (4 strategies), glob, read_file, write_file, update_file
- Fuzzy matching: line-trimmed, indentation-flexible, block-anchor
- Todo tools: todowrite, todoread, todoclear
State Summary
Multi-Layered State Management:
- Central Session Store: StateManager.session as single source of truth
- Layered Caching: Module-level caches for prompts, agents, models
- Explicit State Machines: AgentStateMachine for controlled lifecycle
- Persistent Sessions: JSON-based save/load with auto-save
- Flexible Configuration: Merged defaults + user config
- Component-Level State: Encapsulated UI widget state
- Environment-Aware: Dynamic API key and base URL resolution
State Stores:
- StateManager: Central session orchestrator
- SessionState: Conversation, config, tool, agent, UI, metadata, metrics
- Agent orchestration state: AgentConfig, RequestContext, IterationManager
- UI state containers: TextualReplApp, widget-specific state
Caching Strategies:
- Module-level in-memory caches (prompts, agents, tunacode content)
- Models registry cache
- Token counter memoization (lru_cache)
- Tool buffer for read-only batching
Design Philosophy
NeXTSTEP-Inspired UI Design
TunaCode's interface design is heavily inspired by the classic NeXTSTEP User Interface Guidelines (1993):
Core Principles
- Uniformity - Consistent, predictable experience across all interactions
- User Informed - Agent state and actions always visible (no magic background operations)
- Professional Aesthetic - Clean, retro-modern look with clarity
- Object-Oriented - Component-based architecture
Evidence in Codebase
- Two complete UI themes: "TunaCode" (default) and "NeXTSTEP"
- NeXTSTEP-style panel layouts (4-zone: header, context, viewport, status)
- Bevel and shadow effects in CSS styling
- High contrast for readability
- Clear information hierarchy
- Real-time feedback for all operations
Key Integration Points
Modification Seams (M)
Primary files where behavior can be modified:
| Module |
Key Files |
Purpose |
| Root |
constants.py, exceptions.py |
Foundation used everywhere |
| Core |
agents/main.py, state.py |
Agent orchestration |
| UI |
app.py, main.py, renderers/ |
Presentation layer |
| Tools |
decorators.py, individual tools |
Agent capabilities |
| Configuration |
settings.py, models.py |
Settings management |
| CLI |
commands/, repl_components/ |
Command-line interface |
Extension Seams (D)
Points where new functionality can be added:
| Module |
Extension Points |
| Core |
New agent types, custom agent factories, specialized tool executors |
| UI |
New screens, custom widgets, renderer strategies, REPL commands |
| Tools |
New tool implementations, custom authorizers, validation logic |
| Configuration |
New config options, model registry extensions |
Important Cross-Module Seams
- core ↔ tools: Circular dependency (shared interfaces)
- ui → core: Callback-based communication (streaming_callback, tool_callback)
- all → types: Centralized type definitions
- all → exceptions: Rich error handling hierarchy
Technical Debt & Anti-Patterns
Known Issues
Circular Dependency: Core ↔ Tools
- Impact: Difficult to test in isolation, complex initialization
- Potential solutions: Extract shared interfaces, use dependency injection
Entry Point Analysis Incomplete
- Manual inspection required for CLI entry documentation
Best Practices Followed
- Explicit over implicit
- Fail fast, fail loud
- DRY principle (Don't Repeat Yourself)
- Separation of concerns
- Dependency injection
- Async/await for non-blocking operations
Testing Strategy
Current Test Coverage
Located in <repo_root>/tests/:
- Tool decorator tests
- Tool conformance tests
- Compaction tests
- Tool retry logic tests
Testing Challenges
- Circular dependency makes unit testing difficult
- Async code requires pytest-asyncio
- UI code requires Textual framework testing
Recommended Approach
- Unit tests for tools in isolation
- Integration tests for core orchestration with mock tools
- E2E tests for full request flow
- UI tests using textual-dev
Extension Guide
Adding a New Tool
- Create tool function in
<repo_root>/src/tunacode/tools/
- Decorate with
@file_tool or @base_tool
- Add XML prompt file in
tools/prompts/
- Add to tools list in
agent_config.py
- Optionally create custom renderer in
ui/renderers/tools/
Adding a New Agent Type
- Create prompt sections in
<repo_root>/src/tunacode/prompts/sections/
- Compose prompt using
compose_prompt()
- Configure tools for agent type
- Add agent factory logic in
agent_config.py
Adding a New UI Screen
- Create screen class in
<repo_root>/src/tunacode/ui/screens/
- Integrate with
TextualReplApp
- Add navigation logic
Code Quality Metrics
Strengths
- Comprehensive type hints (PEP 484)
- Extensive documentation (docstrings, comments)
- Consistent naming conventions (snake_case, CamelCase, UPPER_SNAKE_CASE)
- Error handling with actionable guidance
- Modular architecture enabling testing
- Clear integration points (seams)
- Lazy loading for performance
- Theme consistency
External Dependencies
| Package |
Version |
Purpose |
| textual |
^4.0.0 |
TUI framework |
| pydantic-ai |
^1.18.0 |
AI agent framework |
| pydantic |
^2.12.4 |
Data validation |
| typer |
^0.15.0 |
CLI framework |
| rich |
^14.2.0 |
Terminal formatting |
| pathspec |
^0.12.1 |
Gitignore patterns |
| html2text |
^2024.2.26 |
HTML conversion |
Documentation Navigation
Structure Documents
- structure/ - Directory organization and file structure
Architecture Documents
Module Documents
- modules/ - Detailed module documentation
State Documents
Analysis Metadata
SEAMS Agents:
- Structure Agent - Directory organization and file structure
- Architecture Agent - System design and patterns
- Modules Agent - Detailed component documentation
- State Agent - State management and data flow
Analysis Tool: Gemini MCP (gemini-2.5-flash, gemini-2.5-pro)
Analysis Date: 2026-01-04
Output Location: <repo_root>/docs/codebase-map/
Conclusion
TunaCode demonstrates excellent software engineering practices:
- Well-organized with clear module boundaries
- Highly maintainable with consistent patterns
- Type-safe with comprehensive annotations
- User-focused with rich error messages
- Extensible with plugin-style tools and agents
- Documented with clear docstrings and comments
The depth 0 analysis provides a solid foundation for deeper codebase understanding and future development work. The primary technical debt (core ↔ tools circular dependency) should be addressed in future refactoring to improve testability and maintainability.
1---2name: tunacode-codebase-map3description: The depth 0 analysis provides a solid foundation for deeper codebase understanding and future development work.4---5# TunaCode Codebase Map67**Generated:** 2026-01-048**Project:** TunaCode - TUI Code Agent9**Source Directory:** src/tunacode/10**Version:** 0.1.2011**Python Version:** 3.11-3.131213---1415## Statistics1617| Metric | Value |18|--------|-------|19| Total Python files analyzed | 134 |20| Documentation files generated | 28 |21| Documentation size | ~196 KB |22| SEAMS analysis dimensions | Structure, Architecture, Modules, State |23| Analysis depth | 0 (root-level) |24| Analysis tool | Gemini MCP (gemini-2.5-flash, gemini-2.5-pro) |2526---2728## Structure Overview2930```31src/tunacode/32├── ui/ # Presentation layer (Textual TUI)33│ ├── app.py # Main TextualReplApp34│ ├── screens/ # Modal dialogs (setup, picker, confirm)35│ ├── widgets/ # Custom widgets (Editor, ResourceBar)36│ ├── renderers/ # Output formatting (tools, panels)37│ ├── commands/ # UI command handlers (/help, /model)38│ ├── headless/ # Non-interactive mode39│ └── styles/ # CSS and theming40│41├── core/ # Agent orchestration & business logic42│ ├── agents/ # AI agent implementations43│ │ ├── main.py # Primary agent (process_request)44│ │ ├── research_agent.py45│ │ └── agent_components/46│ │ ├── agent_config.py # get_or_create_agent()47│ │ ├── node_processor.py # Response processing48│ │ ├── tool_executor.py # Parallel execution49│ │ └── state_transition.py # Agent state machine50│ ├── state.py # StateManager, SessionState51│ ├── prompting/ # Prompt construction52│ ├── setup/ # Setup wizard53│ ├── background/ # Async tasks54│ └── token_usage/ # Cost tracking55│56├── tools/ # Agent capabilities & system interactions57│ ├── bash.py # Shell execution58│ ├── grep.py # Content search (smart/ripgrep/python)59│ ├── glob.py # File pattern matching60│ ├── read_file.py # File reading61│ ├── write_file.py # File creation62│ ├── update_file.py # File editing (fuzzy matching)63│ ├── list_dir.py # Directory listing64│ ├── web_fetch.py # HTTP requests65│ ├── todo.py # TODO management66│ ├── decorators.py # @base_tool, @file_tool67│ ├── grep_components/ # Search implementation68│ └── tools_utils/ # Shared utilities69│70├── configuration/ # Settings, models, pricing71│ ├── settings.py # User preferences72│ ├── models.py # Model registry73│ ├── models_registry.json74│ ├── pricing.py # Cost tracking75│ └── defaults.py # Factory defaults76│77├── cli/ # Command-line interface78│ ├── commands/ # Slash commands79│ └── repl_components/ # REPL building blocks80│81├── lsp/ # Language Server Protocol client82│ └── client.py # LSPClient, diagnostics83│84├── services/ # External service integrations85│ └── (currently empty)86│87├── types/ # Type definitions88│ ├── base.py # ModelName, ToolName aliases89│ ├── dataclasses.py # UserConfig, AgentRun90│ ├── state.py # MessageHistory, ToolArgs91│ └── callbacks.py # Callback types92│93├── utils/ # Shared utilities94│ ├── config/ # User configuration loading95│ ├── messaging/ # Token counting, message utils96│ ├── parsing/ # JSON, command parsing97│ ├── system/ # Gitignore, paths98│ └── ui/ # File filtering99│100├── prompts/ # Modular prompt sections101│ ├── sections/ # agent_role.md, critical_rules.md102│ └── research/sections/ # Research-specific prompts103│104├── tutorial/ # Interactive tutorials105├── tools_utils/ # Shared tool utilities106├── exceptions.py # Custom exception hierarchy107├── constants.py # Global constants, UI themes108└── py.typed # PEP 561 compliance marker109```110111---112113## Detailed Module Index114115### Core Modules116117| Module | Purpose | Key Exports | Seams |118|--------|---------|-------------|-------|119| **core/agents** | AI agent orchestration | process_request, RequestOrchestrator, get_or_create_agent | M, D |120| **core/state** | Session state management | StateManager, SessionState | M |121| **core/prompting** | System prompt composition | PromptingEngine, SectionLoader | M, D |122| **ui/** | Textual TUI interface | TextualReplApp, screens, renderers | M, D |123| **tools/** | Agent capabilities | base_tool, file_tool, ToolHandler, bash, grep, read_file | M, D |124125### Supporting Modules126127| Module | Purpose | Key Exports | Seams |128|--------|---------|-------------|-------|129| **configuration/** | Settings & models | load_user_config, ModelRegistry, get_pricing | M |130| **types/** | Type definitions | UserConfig, MessageHistory, ModelName, ToolCallback | M |131| **utils/** | Shared utilities | estimate_tokens, estimate_message_tokens, parse_json | M |132| **lsp/** | Language Server Protocol | LSPClient, get_diagnostics | M |133| **prompts/** | Prompt templates | agent_role.md, critical_rules.md | M |134| **cli/** | Command-line interface | REPL commands, slash commands | M, D |135| **exceptions.py** | Exception hierarchy | TunaCodeError, ToolExecutionError | M |136| **constants.py** | Global constants | UI_COLORS, TOOL_NAMES, themes | M |137138---139140## SEAMS Summary141142### Structure Analysis143144The Structure Agent completed a comprehensive **depth 0 analysis** of the TunaCode source code:145146**Key Findings:**147- **Layered Architecture**: Clean separation between Presentation (UI/CLI), Business Logic (Core), Capabilities (Tools), and Configuration148- **Modular Organization**: High cohesion, low coupling, single responsibility principle149- **Type Safety**: Full type annotation coverage with centralized type definitions150- **Error Handling**: Rich exception hierarchy with actionable recovery guidance151- **NeXTSTEP Design**: Consistent UI/UX following classic interface guidelines152153**Design Patterns Identified:**1541. Agent Pattern (Core) - Specialized agents with delegation1552. Decorator Pattern (Tools) - Cross-cutting concerns via decorators1563. Builder Pattern (Prompting) - Dynamic prompt construction1574. Component Pattern (UI) - Reusable widgets and screens1585. Strategy Pattern (Configuration) - Multiple configuration sources1596. Observer Pattern (UI/Core) - Callback-based communication1607. Composite Pattern (Delegation) - Agents as tools161162### Entry Points163164**Primary Entry Point:** `<repo_root>/src/tunacode/ui/main.py`165- Instantiates global StateManager singleton166- Launches TextualReplApp167168**CLI Entry:** `<repo_root>/src/tunacode/cli/`169- Command-line interface via Typer170- REPL mode with slash commands171172**Note:** Entry analysis was not explicitly documented. Manual inspection reveals the above entry points.173174### Architecture Analysis175176**Architectural Pattern:** Pragmatic layered architecture with strong component-based design177178**Key Architectural Decisions:**1791. **UI/Core Decoupling**: Callback-based communication enables headless execution1802. **Modular System Prompts**: Composable prompt sections for maintainability1813. **Agent as Iterator**: Pull-based model for consuming agent execution1824. **Centralized State Management**: Single source of truth in StateManager183184**Data Flow:**185```186USER INPUT → UI Capture → Request Queue → process_request()187 → Agent.iter() → LLM API → Tool Selection → Tool Dispatch188 → Tool Execution → Response Rendering → State Update189```190191**Circular Dependency Note:** Core ↔ Tools have a circular dependency:192- Core imports tool functions for agent configuration193- Tools import from Core for state management and delegation194195### Modules Summary196197**Core Agent Orchestration:**198- `process_request()` in main.py creates RequestOrchestrator199- Agent components: agent_config, node_processor, tool_executor, tool_buffer200- Delegation system: research_agent with read-only tools201- State machine: AgentStateMachine with valid transitions202203**UI Module:**204- TextualReplApp with screens, widgets, renderers205- Screen management: ModelPicker, SessionPicker, Setup, ThemePicker206- Renderer system: RichPanelRenderer with 4-zone NeXTSTEP layout207- Specialized tool renderers: bash, glob, grep, read_file, etc.208- Custom widgets: Editor, ResourceBar, StatusBar209210**Tools Module:**211- Decorator system: @base_tool, @file_tool with XML prompt files212- Tool implementations: bash, grep (4 strategies), glob, read_file, write_file, update_file213- Fuzzy matching: line-trimmed, indentation-flexible, block-anchor214- Todo tools: todowrite, todoread, todoclear215216### State Summary217218**Multi-Layered State Management:**2191. **Central Session Store:** StateManager.session as single source of truth2202. **Layered Caching:** Module-level caches for prompts, agents, models2213. **Explicit State Machines:** AgentStateMachine for controlled lifecycle2224. **Persistent Sessions:** JSON-based save/load with auto-save2235. **Flexible Configuration:** Merged defaults + user config2246. **Component-Level State:** Encapsulated UI widget state2257. **Environment-Aware:** Dynamic API key and base URL resolution226227**State Stores:**228- StateManager: Central session orchestrator229- SessionState: Conversation, config, tool, agent, UI, metadata, metrics230- Agent orchestration state: AgentConfig, RequestContext, IterationManager231- UI state containers: TextualReplApp, widget-specific state232233**Caching Strategies:**234- Module-level in-memory caches (prompts, agents, tunacode content)235- Models registry cache236- Token counter memoization (lru_cache)237- Tool buffer for read-only batching238239---240241## Design Philosophy242243**NeXTSTEP-Inspired UI Design**244245TunaCode's interface design is heavily inspired by the classic **NeXTSTEP User Interface Guidelines (1993)**:246247### Core Principles2481. **Uniformity** - Consistent, predictable experience across all interactions2492. **User Informed** - Agent state and actions always visible (no magic background operations)2503. **Professional Aesthetic** - Clean, retro-modern look with clarity2514. **Object-Oriented** - Component-based architecture252253### Evidence in Codebase254- Two complete UI themes: "TunaCode" (default) and "NeXTSTEP"255- NeXTSTEP-style panel layouts (4-zone: header, context, viewport, status)256- Bevel and shadow effects in CSS styling257- High contrast for readability258- Clear information hierarchy259- Real-time feedback for all operations260261---262263## Key Integration Points264265### Modification Seams (M)266Primary files where behavior can be modified:267268| Module | Key Files | Purpose |269|--------|-----------|---------|270| Root | `constants.py`, `exceptions.py` | Foundation used everywhere |271| Core | `agents/main.py`, `state.py` | Agent orchestration |272| UI | `app.py`, `main.py`, `renderers/` | Presentation layer |273| Tools | `decorators.py`, individual tools | Agent capabilities |274| Configuration | `settings.py`, `models.py` | Settings management |275| CLI | `commands/`, `repl_components/` | Command-line interface |276277### Extension Seams (D)278Points where new functionality can be added:279280| Module | Extension Points |281|--------|------------------|282| Core | New agent types, custom agent factories, specialized tool executors |283| UI | New screens, custom widgets, renderer strategies, REPL commands |284| Tools | New tool implementations, custom authorizers, validation logic |285| Configuration | New config options, model registry extensions |286287### Important Cross-Module Seams288- **core ↔ tools**: Circular dependency (shared interfaces)289- **ui → core**: Callback-based communication (streaming_callback, tool_callback)290- **all → types**: Centralized type definitions291- **all → exceptions**: Rich error handling hierarchy292293---294295## Technical Debt & Anti-Patterns296297### Known Issues2981. **Circular Dependency**: Core ↔ Tools299 - Impact: Difficult to test in isolation, complex initialization300 - Potential solutions: Extract shared interfaces, use dependency injection3013022. **Entry Point Analysis Incomplete**303 - Manual inspection required for CLI entry documentation304305### Best Practices Followed306- Explicit over implicit307- Fail fast, fail loud308- DRY principle (Don't Repeat Yourself)309- Separation of concerns310- Dependency injection311- Async/await for non-blocking operations312313---314315## Testing Strategy316317### Current Test Coverage318Located in `<repo_root>/tests/`:319- Tool decorator tests320- Tool conformance tests321- Compaction tests322- Tool retry logic tests323324### Testing Challenges3251. Circular dependency makes unit testing difficult3262. Async code requires pytest-asyncio3273. UI code requires Textual framework testing328329### Recommended Approach3301. Unit tests for tools in isolation3312. Integration tests for core orchestration with mock tools3323. E2E tests for full request flow3334. UI tests using textual-dev334335---336337## Extension Guide338339### Adding a New Tool3401. Create tool function in `<repo_root>/src/tunacode/tools/`3412. Decorate with `@file_tool` or `@base_tool`3423. Add XML prompt file in `tools/prompts/`3434. Add to tools list in `agent_config.py`3445. Optionally create custom renderer in `ui/renderers/tools/`345346### Adding a New Agent Type3471. Create prompt sections in `<repo_root>/src/tunacode/prompts/sections/`3482. Compose prompt using `compose_prompt()`3493. Configure tools for agent type3504. Add agent factory logic in `agent_config.py`351352### Adding a New UI Screen3531. Create screen class in `<repo_root>/src/tunacode/ui/screens/`3542. Integrate with `TextualReplApp`3553. Add navigation logic356357---358359## Code Quality Metrics360361### Strengths362- Comprehensive type hints (PEP 484)363- Extensive documentation (docstrings, comments)364- Consistent naming conventions (snake_case, CamelCase, UPPER_SNAKE_CASE)365- Error handling with actionable guidance366- Modular architecture enabling testing367- Clear integration points (seams)368- Lazy loading for performance369- Theme consistency370371### External Dependencies372| Package | Version | Purpose |373|---------|---------|---------|374| textual | ^4.0.0 | TUI framework |375| pydantic-ai | ^1.18.0 | AI agent framework |376| pydantic | ^2.12.4 | Data validation |377| typer | ^0.15.0 | CLI framework |378| rich | ^14.2.0 | Terminal formatting |379| pathspec | ^0.12.1 | Gitignore patterns |380| html2text | ^2024.2.26 | HTML conversion |381382---383384## Documentation Navigation385386### Structure Documents387- **[structure/](./structure/)** - Directory organization and file structure388 - [00-root-overview.md](./structure/00-root-overview.md) - Constants, exceptions389 - [01-ui-directory.md](./structure/01-ui-directory.md) - TUI components390 - [02-core-directory.md](./structure/02-core-directory.md) - Agent orchestration391 - [03-tools-directory.md](./structure/03-tools-directory.md) - Tool implementations392 - [04-configuration-directory.md](./structure/04-configuration-directory.md) - Settings393 - [05-cli-directory.md](./structure/05-cli-directory.md) - Command-line interface394 - [06-supporting-modules.md](./structure/06-supporting-modules.md) - Auxiliary modules395396### Architecture Documents397- **[architecture/architecture.md](./architecture/architecture.md)** - System design, patterns, data flow398- **[architecture/conversation-turns.md](./architecture/conversation-turns.md)** - Conversation turn flow from user input to response399400### Module Documents401- **[modules/](./modules/)** - Detailed module documentation402 - [00-overview.md](./modules/00-overview.md) - Package structure403 - [core-agents.md](./modules/core-agents.md) - Agent orchestration404 - [core-state.md](./modules/core-state.md) - State management405 - [core-prompting.md](./modules/core-prompting.md) - Prompt composition406 - [ui-overview.md](./modules/ui-overview.md) - UI components407 - [tools-overview.md](./modules/tools-overview.md) - Tool system408 - [configuration.md](./modules/configuration.md) - Configuration409 - [types.md](./modules/types.md) - Type definitions410 - [utils.md](./modules/utils.md) - Utilities411 - [lsp.md](./modules/lsp.md) - Language Server Protocol412 - [prompts.md](./modules/prompts.md) - Prompt sections413 - [exceptions.md](./modules/exceptions.md) - Exception hierarchy414 - [constants.md](./modules/constants.md) - Global constants415416### State Documents417- **[state/state.md](./state/state.md)** - State management, caching, persistence418419---420421## Analysis Metadata422423**SEAMS Agents:**424- Structure Agent - Directory organization and file structure425- Architecture Agent - System design and patterns426- Modules Agent - Detailed component documentation427- State Agent - State management and data flow428429**Analysis Tool:** Gemini MCP (gemini-2.5-flash, gemini-2.5-pro)430431**Analysis Date:** 2026-01-04432433**Output Location:** `<repo_root>/docs/codebase-map/`434435---436437## Conclusion438439TunaCode demonstrates **excellent software engineering practices**:440441- Well-organized with clear module boundaries442- Highly maintainable with consistent patterns443- Type-safe with comprehensive annotations444- User-focused with rich error messages445- Extensible with plugin-style tools and agents446- Documented with clear docstrings and comments447448The **depth 0 analysis** provides a solid foundation for deeper codebase understanding and future development work. The primary technical debt (core ↔ tools circular dependency) should be addressed in future refactoring to improve testability and maintainability.