# CLAUDE.md

This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.

## Project Overview

EQ2Go is a Go rewrite of the EverQuest II server emulator from C++ EQ2EMu. Implements core MMO server functionality with authentication, world simulation, and game mechanics using modern Go practices.

## Development Commands

### Building the Project
```bash
# Build login server
go build -o bin/login_server ./cmd/login_server

# Build world server  
go build -o bin/world_server ./cmd/world_server

# Build both servers
go build ./cmd/...
```

### Running the Servers
```bash
# Run login server (requires login_config.json)
./bin/login_server

# Run world server (creates world_config.json with defaults if missing)
./bin/world_server

# With custom configuration
./bin/world_server -listen-port 9001 -web-port 8081 -log-level debug
```

### Testing
```bash
# Run all tests
go test ./...

# Test specific packages
go test ./internal/udp
go test ./internal/packets/parser

# Run tests with verbose output
go test -v ./...

# Test with race detection
go test -race ./...
```

### Development Tools
```bash
# Format code
go fmt ./...

# Run linter (if golangci-lint is installed)
golangci-lint run

# Tidy modules
go mod tidy

# Check for vulnerabilities
go run golang.org/x/vuln/cmd/govulncheck@latest ./...
```

## Architecture Overview

### Core Components

**Login Server** - Client authentication, character management, world server coordination  
**World Server** - Game simulation engine, zones, NPCs, combat, quests, web admin interface

**Shared Libraries:**
- `common/` - EQ2-specific data types and constants  
- `database/` - SQLite wrapper with simplified query interface
- `udp/` - Custom UDP protocol with reliability layer
- `packets/` - XML-driven packet definition parser
- `achievements/` - Achievement system
- `spawn/` - Base game entity system (positioning, commands, scripting)
- `entity/` - Combat-capable entities with spell effects, stats, pet management
- `spells/` - Complete spell system with casting mechanics and processing  
- `titles/` - Character title system with achievement integration
- `trade/` - Player trading system with item/coin exchange and validation
- `object/` - Interactive objects extending spawn system (merchants, transporters, devices, collectors)
- `races/` - Race system with all EQ2 races, alignment classification, stat modifiers, and entity integration
- `classes/` - Class system with all EQ2 classes, progression paths, stat bonuses, and entity integration
- `widget/` - Interactive widget system for doors, lifts, and other usable objects with spawn integration
- `transmute/` - Item transmutation system for converting items into crafting materials with skill requirements
- `skills/` - Character skill system with master skill list, player skills, bonuses, and progression mechanics
- `sign/` - Interactive sign system extending spawn functionality with zone transport, entity commands, and text display
- `appearances/` - Appearance management system with client version compatibility and efficient ID-based lookups
- `factions/` - Faction reputation system with player standings, consideration levels, and inter-faction relationships
- `ground_spawn/` - Harvestable resource node system with skill-based harvesting, rare item generation, and multi-attempt mechanics
- `languages/` - Multilingual character communication system with master language registry and player-specific language knowledge

### Network Protocol
EverQuest II UDP protocol with reliability layer, RC4 encryption, CRC validation, connection management, packet combining.

### Database Layer  
SQLite with simplified query interface, transactions, connection pooling, parameter binding.

### Packet System
XML-driven packet definitions with version-specific formats, conditional fields, templates, dynamic arrays.

## Key Files and Locations

**Server Entry Points:**
- `cmd/login_server/main.go`: Login server startup and configuration
- `cmd/world_server/main.go`: World server startup with command-line options

**Core Data Structures:**
- `internal/common/types.go`: EQ2-specific types (EQ2Color, EQ2Equipment, AppearanceData, etc.)
- `internal/common/visual_states.go`: Visual states, emotes, and spell visuals with version management
- `internal/common/variables.go`: Configuration variable management with type conversion utilities

**Network Implementation:**
- `internal/udp/server.go`: Multi-connection UDP server
- `internal/udp/connection.go`: Individual client connection handling
- `internal/udp/protocol.go`: Protocol packet types and constants

**Database:**
- `internal/database/wrapper.go`: Simplified SQLite interface
- Database files: `login.db`, `world.db` (created automatically)

**Spawn System:**
- `internal/spawn/spawn.go`: Base spawn entity with position, stats, commands, and scripting
- `internal/spawn/spawn_lists.go`: Spawn location and entry management
- `internal/spawn/README.md`: Comprehensive spawn system documentation

**Entity System:**
- `internal/entity/entity.go`: Combat-capable spawn extension with spell casting and pet management
- `internal/entity/info_struct.go`: Comprehensive character statistics and information management
- `internal/entity/spell_effects.go`: DEPRECATED - now imports from spells package
- `internal/entity/README.md`: Complete entity system documentation

**Spells System:**
- Core: `spell_data.go`, `spell.go`, `spell_effects.go`, `spell_manager.go`, `constants.go`
- Processing: `process_constants.go`, `spell_process.go`, `spell_targeting.go`, `spell_resources.go`  
- Docs: `README.md`, `SPELL_PROCESS.md`

**Titles System:**
- `internal/titles/title.go`: Core title data structures and player title management
- `internal/titles/constants.go`: Title system constants, categories, and rarity levels
- `internal/titles/master_list.go`: Global title registry and management with categorization
- `internal/titles/player_titles.go`: Individual player title collections and active title tracking
- `internal/titles/title_manager.go`: Central title system coordinator with background cleanup
- `internal/titles/integration.go`: Integration systems for earning titles through achievements, quests, PvP, events
- `internal/titles/README.md`: Complete title system documentation

**Trade System:**
- `internal/trade/trade.go`: Core trade mechanics with two-party item/coin exchange
- `internal/trade/types.go`: Trade data structures, participants, and validation
- `internal/trade/constants.go`: Trade constants, error codes, and configuration
- `internal/trade/utils.go`: Coin calculations, validation helpers, and formatting
- `internal/trade/manager.go`: Trade service with high-level management and placeholders

**Object System:**
- `internal/object/object.go`: Core object mechanics extending spawn functionality with interaction
- `internal/object/constants.go`: Object constants, spawn types, and interaction types
- `internal/object/manager.go`: Object manager with zone-based and type-based indexing
- `internal/object/integration.go`: Spawn system integration with ObjectSpawn wrapper
- `internal/object/interfaces.go`: Integration interfaces for trade/spell systems and entity adapters

**Race System:**
- `internal/races/races.go`: Core race management with all 21 EQ2 races and alignment mapping
- `internal/races/constants.go`: Race IDs, names, and display constants
- `internal/races/utils.go`: Race utilities with stat modifiers, descriptions, and parsing
- `internal/races/integration.go`: Entity system integration with RaceAware interface
- `internal/races/manager.go`: High-level race management with statistics and command processing

**Class System:**
- `internal/classes/classes.go`: Core class management with all EQ2 adventure and tradeskill classes
- `internal/classes/constants.go`: Class IDs, names, and display constants with progression hierarchy
- `internal/classes/utils.go`: Class utilities with progression paths, stat bonuses, and parsing
- `internal/classes/integration.go`: Entity system integration with ClassAware interface
- `internal/classes/manager.go`: High-level class management with statistics and command processing

**Widget System:**
- `internal/widget/widget.go`: Interactive spawn objects like doors and lifts with movement and state management
- `internal/widget/constants.go`: Widget type constants and display name mappings
- `internal/widget/actions.go`: Widget interaction logic with open/close mechanics and client handling
- `internal/widget/interfaces.go`: Integration interfaces for client and zone systems with spawn wrapper
- `internal/widget/manager.go`: Widget management with timer handling and linked spawn resolution

**Transmute System:**
- `internal/transmute/transmute.go`: Core transmutation logic with item validation and material generation
- `internal/transmute/types.go`: Transmute data structures and interface definitions for system integration
- `internal/transmute/constants.go`: Transmutation constants including probabilities and item flags
- `internal/transmute/manager.go`: High-level transmute management with statistics and command processing
- `internal/transmute/database.go`: Database operations for transmuting tier configuration
- `internal/transmute/packet_builder.go`: Client packet construction for transmutation UI and responses

**Skills System:**
- `internal/skills/types.go`: Core skill data structures with Skill, SkillBonus, and SkillBonusValue types
- `internal/skills/constants.go`: Skill type constants, special skill IDs, and skill increase parameters
- `internal/skills/master_skill_list.go`: Master skill registry with all available skills and packet building
- `internal/skills/player_skill_list.go`: Individual player skill management with values, caps, and updates
- `internal/skills/skill_bonuses.go`: Skill bonus system for spell-based skill modifications and calculations
- `internal/skills/manager.go`: High-level skill management with statistics, validation, and command processing
- `internal/skills/integration.go`: Integration interfaces including SkillAware and EntitySkillAdapter

**Sign System:**
- `internal/sign/types.go`: Core Sign struct extending spawn functionality with widget and zone transport properties
- `internal/sign/constants.go`: Sign type constants, default values, and configuration parameters
- `internal/sign/sign.go`: Sign functionality including copy, serialization, usage handling, and validation
- `internal/sign/interfaces.go`: Integration interfaces with SignAware, SignAdapter, and system dependencies
- `internal/sign/manager.go`: Sign management with zone loading, statistics, validation, and command processing

**Appearances System:**
- `internal/appearances/types.go`: Core Appearance struct with ID, name, and client version compatibility
- `internal/appearances/constants.go`: Hash search constants and client version parameters
- `internal/appearances/appearances.go`: Appearance collection management with thread-safe operations
- `internal/appearances/manager.go`: High-level appearance management with database integration and statistics
- `internal/appearances/interfaces.go`: Integration interfaces with caching, entity adapters, and system dependencies

**Factions System:**
- `internal/factions/types.go`: Core Faction struct with reputation properties and validation methods
- `internal/factions/constants.go`: Faction value limits, consideration levels, and calculation constants
- `internal/factions/master_faction_list.go`: Master faction registry with hostile/friendly relationships
- `internal/factions/player_faction.go`: Individual player faction standings with consideration and percentage calculations
- `internal/factions/manager.go`: High-level faction management with statistics, validation, and command processing
- `internal/factions/interfaces.go`: Integration interfaces with entity adapters, player managers, and system dependencies

**Ground Spawn System:**
- `internal/ground_spawn/constants.go`: Harvest type constants, skill names, rarity flags, and configuration defaults
- `internal/ground_spawn/types.go`: Core GroundSpawn struct, harvest context data, result structures, and statistics tracking
- `internal/ground_spawn/ground_spawn.go`: Core ground spawn functionality with complex harvest processing and skill-based mechanics
- `internal/ground_spawn/interfaces.go`: Integration interfaces with database, players, items, skills, and event handling systems
- `internal/ground_spawn/manager.go`: High-level ground spawn management with respawn scheduling, statistics, and command processing

**Languages System:**
- `internal/languages/constants.go`: Language ID constants, validation limits, and system configuration values
- `internal/languages/types.go`: Core Language struct, master language list, player language list, and statistics tracking
- `internal/languages/manager.go`: High-level language management with database integration, statistics, and command processing
- `internal/languages/interfaces.go`: Integration interfaces with database, players, chat processing, and event handling systems

**Quests System:**
- `internal/quests/constants.go`: Quest step types, display status flags, sharing constants, and validation limits
- `internal/quests/types.go`: Core Quest and QuestStep structures with complete quest data management and thread-safe operations
- `internal/quests/quest.go`: Core quest functionality including step management, progress tracking, update checking, and validation
- `internal/quests/prerequisites.go`: Quest prerequisite management with class, race, level, faction, and quest requirements
- `internal/quests/rewards.go`: Quest reward system with coins, experience, status, faction rewards, and level-based calculations
- `internal/quests/actions.go`: Quest action system for Lua script execution on completion, progress, and failure events
- `internal/quests/manager.go`: MasterQuestList and QuestManager for system-wide quest management and player quest tracking
- `internal/quests/interfaces.go`: Integration interfaces with player, client, spawn, item systems and QuestSystemAdapter for complete quest lifecycle management

**NPC System:**
- `internal/npc/constants.go`: AI strategy constants, randomization flags, pet types, cast types, and system limits
- `internal/npc/types.go`: Core NPC struct extending Entity, NPCSpell configurations, skill bonuses, movement locations, brain system
- `internal/npc/npc.go`: Complete NPC functionality with AI, combat, spell casting, movement, appearance randomization, and validation
- `internal/npc/manager.go`: High-level NPC management with zone indexing, appearance tracking, combat processing, and statistics
- `internal/npc/interfaces.go`: Integration interfaces with database, spell/skill/appearance systems, combat, movement, and entity adapters

**NPC AI System:**
- `internal/npc/ai/constants.go`: AI timing constants, combat ranges, hate limits, brain types, and decision parameters
- `internal/npc/ai/types.go`: HateList and EncounterList management, BrainState tracking, performance statistics, and thread-safe operations
- `internal/npc/ai/brain.go`: BaseBrain with complete AI logic including hate management, encounter tracking, spell/melee processing, and combat decisions
- `internal/npc/ai/variants.go`: Specialized brain types (CombatPet, NonCombatPet, Blank, Lua, DumbFire) with unique behaviors and factory functions
- `internal/npc/ai/interfaces.go`: Integration interfaces with NPC/Entity systems, AIManager for brain lifecycle, adapters, and debugging utilities

**Packet Definitions:**
- `internal/packets/xml/`: XML packet structure definitions
- `internal/packets/PARSER.md`: Packet definition language documentation
- `internal/packets/parser/`: Parser implementation for XML packet definitions

## Configuration

**Login Server**: Requires `login_config.json` with database and server settings

**World Server**: Creates `world_config.json` with defaults:
```json
{
    "listen_addr": "0.0.0.0",
    "listen_port": 9000,
    "max_clients": 1000,
    "web_port": 8080,
    "database_path": "world.db",
    "log_level": "info"
}
```

Command-line flags override JSON configuration.

## Important Dependencies

**Core Dependencies:**
- `zombiezen.com/go/sqlite`: Modern SQLite driver
- `golang.org/x/crypto`: Cryptographic functions

**Module Information:**
- Go version: 1.24.5
- Module name: `eq2emu`

## Development Notes

**Architecture Transition**: This Go implementation is based on the extensive C++ EQ2EMu codebase documented in `EQ2EMU_Architecture_White_Paper.md`. The Go version maintains compatibility with the original protocol while modernizing the implementation.

**Packet Handling**: The XML packet definition system allows for easy addition of new packet types without code changes. See `internal/packets/PARSER.md` for syntax reference.

**Database Schema**: Currently uses SQLite for development/testing. Production deployments may require migration to PostgreSQL or MySQL for better concurrent access.

**Spawn System**: The spawn system (`internal/spawn/`) provides the foundation for all game entities. It's converted from the C++ EQ2EMu codebase with modern Go concurrency patterns.

**Entity System**: The entity system (`internal/entity/`) extends spawns with combat capabilities, implementing the complete EverQuest II character statistics system, spell effect management, and pet systems. Key features include:
- **InfoStruct**: Complete character statistics (attributes, resistances, experience, currency, equipment data)
- **Entity**: Combat-capable spawn with spell casting, pet management, and bonus calculations
- **Thread Safety**: All systems use proper Go concurrency patterns with mutexes and atomic operations
- **Stat Calculations**: Dynamic stat calculations with bonuses from equipment, spells, and other sources
- **Pet Management**: Support for multiple pet types (summon, charm, deity, cosmetic) with proper ownership tracking

**Spells System**: Complete spell management with spell definitions, effect system, and real-time casting engine. Features spell processing (50ms intervals), comprehensive targeting (self/single/group/AOE), resource management (power/health/concentration), cast/recast timers, interrupt handling, heroic opportunities, and thread-safe operations.

**Titles System**: Character title management with prefix/suffix positioning, categories, rarity levels, achievement integration, and thread-safe operations.

**Trade System**: Player-to-player trading with item/coin exchange, validation (no-trade, heirloom restrictions), slot management, acceptance workflow, bot trading support, and client version compatibility (6/12 slots).

**Object System**: Interactive world objects extending spawn system with merchants, transporters, devices, and collectors. Features clickable interaction, command handling, device IDs, size randomization, transport/teleport support, and complete spawn integration with entity/item adapters for trade/spell system compatibility.

**Race System**: Complete EverQuest II race management with all 21 races (Human through Aerakyn), alignment classification (good/evil/neutral), racial stat modifiers, starting locations, lore descriptions, and full entity system integration. Features randomization by alignment, compatibility checking, usage statistics, and RaceAware interface for seamless integration with existing systems.

**Class System**: Complete EverQuest II class management with all 58 classes (adventure and tradeskill), hierarchical progression paths (Commoner → Base → Secondary → Final), stat bonuses, starting stat calculations, and full entity system integration. Features class transition validation, progression tracking, usage statistics, and ClassAware interface for seamless integration with existing systems. Includes all 4 base classes (Fighter, Priest, Mage, Scout) with their complete specialization trees.

**Visual States System**: Manages visual animations, emotes, and spell visuals with client version support. Features version-based emote/visual selection, animation ID mapping, message formatting (targeted/untargeted), and thread-safe concurrent access. Supports both named lookups and ID-based lookups for efficient client communication.

**Variables System**: Configuration variable management for runtime settings and game parameters. Features type-safe value conversion (int, float, bool), partial name matching, variable cloning and merging, comment support for documentation, and thread-safe operations. Used for game rules, server settings, and dynamic configuration.

**Widget System**: Interactive spawn objects like doors, lifts, and other usable world elements. Features open/close state management, position-based movement with timers, sound integration, linked widget chains (action/linked spawns), house integration for player housing, multi-floor lift support, and complete spawn system integration. Supports complex interactions like transporter integration and custom scripted behaviors.

**Transmute System**: Item transmutation system allowing players to convert items into crafting materials. Features tier-based material generation, skill requirement validation, probabilistic loot rolls (15% both materials, 75%/25% split), automatic skill progression, request state management, and comprehensive validation. Supports level-based transmuting tiers with four material types (fragments, powder, infusions, mana) and integrates with item, spell, and skill systems.

**Skills System**: Complete character skill system with master skill registry and individual player skill management. Features all EQ2 skill types (weaponry, spellcasting, avoidance, armor, harvesting, artisan, etc.), skill bonuses from spells, skill progression with automatic increases, disarm skill checks for chests, and comprehensive skill value calculations. Supports skill caps, type-based operations, packet building for client updates, and full integration with entity system through SkillAware interface. Includes special handling for weapon skills, crafting skills, and language skills with version-specific client compatibility.

**Sign System**: Interactive sign system extending spawn functionality for in-world text displays and zone transport. Features two sign types (generic and zone transport), zone teleportation with coordinate validation, entity command processing, sign marking system, transporter integration, distance-based interaction, and comprehensive text display with location/heading options. Supports quest requirement checking, instance zone handling, size randomization on copy, validation system, and full spawn system integration. Includes SignAware interface and SignAdapter for seamless integration with existing entity systems.

**Appearances System**: Comprehensive appearance management system handling visual character and entity representations with client version compatibility. Features efficient hash-based ID lookups, client version compatibility checking, name-based searching, statistics tracking, and thread-safe operations. Supports caching with SimpleAppearanceCache and CachedAppearanceManager, database integration for persistence, entity appearance adapters for seamless integration, and comprehensive validation. Includes AppearanceAware interface and EntityAppearanceAdapter for entity system integration. Designed to handle large appearance collections with sparse ID ranges efficiently using hash tables as noted in C++ comments.

**Factions System**: Complete faction reputation system managing player standings and inter-faction relationships. Features master faction list with hostile/friendly relationships, individual player faction standings with consideration levels (-4 to 4), percentage calculations within consideration ranges, attack determination based on faction standing, and comprehensive faction value management (-50000 to 50000 range). Supports special faction handling (IDs <= 10), faction increase/decrease with configurable amounts, packet building for client updates, statistics tracking, and thread-safe operations. Includes EntityFactionAdapter and PlayerFactionManager for seamless integration with entity and player systems. Maintains exact C++ calculation formulas for consideration levels and percentage values.

**Ground Spawn System**: Harvestable resource node system extending spawn functionality for gathering, mining, fishing, trapping, and foresting. Features skill-based table selection, probabilistic harvest outcomes (1/3/5/10 items + rare/imbue types), multi-attempt harvesting sessions, skill progression mechanics, and automatic respawn scheduling. Implements complex C++ harvest logic with table filtering by skill/level requirements, random item selection from filtered pools, grid-based location restrictions, and comprehensive item reward processing. Supports collection vs. harvesting skill differentiation, harvest message generation, spell integration for casting animations, and statistics tracking. Includes PlayerGroundSpawnAdapter and HarvestEventAdapter for seamless integration with player and event systems. Thread-safe operations with separate mutexes for harvest processing and usage handling.

**Languages System**: Multilingual character communication system managing language learning and chat processing. Features master language registry with ID-based and name-based lookups, individual player language collections with thread-safe operations, language validation and persistence, and comprehensive multilingual chat processing. Supports all EverQuest II racial languages (Common, Elvish, Dwarven, Halfling, Gnomish, Iksar, Trollish, Ogrish, Fae, Arasai, Sarnak, Froglok), language learning/forgetting mechanics, primary language selection, and message scrambling for unknown languages. Includes PlayerLanguageAdapter for seamless player integration, ChatLanguageProcessor for multilingual communication, and statistics tracking for language usage patterns. Thread-safe operations with efficient hash-based lookups and comprehensive validation systems.

**Quests System**: Complete quest management with quest definitions, step system, and real-time progress tracking. Features quest system with multiple step types (kill, chat, obtain item, location, spell, normal, craft, harvest, kill race requirements), comprehensive prerequisite system (level, class, race, faction, quest dependencies), flexible reward system (coins, experience, status points, faction reputation, items), step-based progress tracking with percentage-based success chances, task group organization for complex quests, Lua action system for completion/progress/failure events, quest sharing system with configurable sharing rules, repeatable quest support, player quest management with active quest tracking, master quest list with categorization and search, validation system for quest integrity, and thread-safe operations with proper mutex usage. Includes QuestSystemAdapter for complete quest lifecycle management and integration with player, client, spawn, and item systems.

**NPC System**: Non-player character system extending Entity with complete AI, combat, and spell casting capabilities. Features NPC struct with brain system, spell management (cast-on-spawn/aggro triggers), skill bonuses, movement with runback mechanics, appearance randomization (33+ flags for race/gender/colors/features), AI strategies (balanced/offensive/defensive), and combat state management. Includes NPCSpell configurations with HP ratio requirements, skill bonus system with spell-based modifications, movement locations with navigation pathfinding, timer system for pause/movement control, and comprehensive appearance randomization covering all EQ2 races and visual elements. Manager provides zone-based indexing, appearance tracking, combat processing, AI processing, statistics collection, and command interface. Integration interfaces support database persistence, spell/skill/appearance systems, combat management, movement control, and entity adapters for seamless system integration. Thread-safe operations with proper mutex usage and atomic flags for state management.

**NPC AI System**: Comprehensive artificial intelligence system for NPCs with hate management, encounter tracking, and specialized brain types. Features BaseBrain with complete AI logic including target selection, spell/melee processing, combat decisions, movement control, and runback mechanics. HateList provides thread-safe hate value tracking with percentage calculations and most-hated selection. EncounterList manages player/group participation for loot rights and rewards with character ID mapping. Specialized brain variants include CombatPetBrain (follows owner, assists in combat), NonCombatPetBrain (cosmetic pet following), BlankBrain (minimal processing), LuaBrain (script-controlled AI), and DumbFirePetBrain (temporary combat pets with expiration). BrainState tracks timing, spell recovery, active status, and debug levels. AIManager provides centralized brain lifecycle management with type-based creation, active brain processing, and performance statistics. Integration interfaces support NPC/Entity systems, Lua scripting, zone operations, and debugging utilities. Thread-safe operations with proper mutex usage and performance tracking for all AI operations.

All systems are converted from C++ with TODO comments marking areas for future implementation (LUA integration, advanced mechanics, etc.).

**Testing**: Focus testing on the UDP protocol layer and packet parsing, as these are critical for client compatibility.

## Code Documentation Standards

**Function Documentation**: All functions must have thorough documentation explaining their purpose, parameters, return values, and any important behavior. Do NOT follow the standard Go convention of starting comments with the function name - instead, write clear explanations of what the function does.

**Examples:**

Good:
```go
// Creates a new UDP server instance with the specified address and packet handler.
// The server will listen on the given address and route incoming packets to the handler.
// Returns an error if the address is invalid or the socket cannot be bound.
func NewServer(addr string, handler PacketHandler, config ...Config) (*Server, error) {
```

Poor (standard Go convention - avoid this):
```go
// NewServer creates a new UDP server instance with the specified address and packet handler.
func NewServer(addr string, handler PacketHandler, config ...Config) (*Server, error) {
```

**Additional Documentation Requirements:**
- Document all public types, constants, and variables
- Include examples in documentation for complex functions
- Explain any non-obvious algorithms or business logic
- Document error conditions and edge cases
- For packet-related code, reference the relevant XML definitions or protocol specifications