Files
biz-bud/CLAUDE.md
Travis Vasceannie 32fcab7a79 Tests (#56)
* fix: resolve linting issues for clean test runs

- Fix flake8 PT011 errors by adding match parameters to pytest.raises
- Fix flake8 PT012 error by restructuring pytest.raises block
- Fix pyrefly type checking errors in cache_manager.py
- Address trailing whitespace issues

These fixes ensure pre-commit hooks pass cleanly, enabling successful
test commits and maintaining code quality standards.

* fix: correct config validation test expectations

* fix: adjust config reload test expectations for environment override behavior

* fix: correct LLM client test expectations and error handling

- Fix test_call_model_node_list_content to expect 'a b' instead of "['a', 'b']"
- Fix builtins import issue in provider exception tests
- Fix LLMExceptionHandler patch path from call module to core.errors.llm_exceptions
- Adjust provider exception tests to validate user-friendly error messages
- These fixes align tests with actual LLM content processing and error handling behavior

* fix: additional LLM test error categorization improvements

- Fix test_call_model_node_llm_error_categorization to match actual error message format
- Simplify error categorization assertions to focus on core functionality
- Remove overly specific assertions about logging call structure
- These changes improve test stability while maintaining error handling validation

* fix: resolve concurrency and race condition issues across codebase

- Remove threading.Lock from lazy_loader.py in favor of pure async patterns
- Simplify weak reference handling by removing complex callbacks
- Remove LazyProxy and ThreadSafeLazyLoader classes (no longer needed)
- Fix race condition in Redis backend by adding initialization lock
- Make cleanup_registry concurrency configurable via ServiceConfig
- Remove sync cache methods and fix CancelledError handling in decorators
- Add ServiceConfig with timeout and concurrency settings to AppConfig
- Remove complex cleanup tracking from ServiceFactory
- Fix cache decorator to use lazy initialization pattern
- Update all tests to use new async-only implementations

This refactoring improves code quality by:
- Eliminating mixed threading/async patterns that could cause deadlocks
- Simplifying cleanup logic to avoid nested timeouts
- Making system behavior configurable instead of hardcoded
- Removing backwards compatibility code for cleaner implementation

* docs: update documentation and audit script for async-only patterns

- Update audit_core_dependencies.py to check for deprecated patterns
  - Add threading.Lock to disallowed imports
  - Add ThreadSafeLazyLoader, LazyProxy, ThreadSafeFactoryManager to disallowed instantiations
  - Add ImportFrom check for threading.Lock
- Update core README.md with AsyncSafeLazyLoader and AsyncFactoryManager documentation
  - Add new section on async-safe lazy loading utilities
  - Add best practices for async patterns
- Fix references to old patterns in documentation files
  - Update CACHING_GUIDELINES.md to use cleanup_cache_singletons
  - Update AGENTS.md to reference AsyncSafeLazyLoader
  - Fix comment in graph.py referencing LazyProxy
- Note: Found remaining threading.Lock uses in logging and error modules for future cleanup

* fix: add missing ErrorNamespace constants and fix error type validation

- Add CFG_INVALID_CONFIG and UNK_GENERAL_ERROR to ErrorNamespace enum
- Add these constants to the error registry mappings
- Fix error type validation in create_error_dict_from_incomplete to ensure strings
- Remaining pyrefly errors are false positives about missing returns
- Fixed trailing whitespace

* refactor: improve control flow clarity for static analysis

- Add explicit None checks before awaiting tasks to help pyrefly understand control flow
- Initialize task variables with None to make assignment tracking clearer
- Add StateError raises when tasks are unexpectedly None
- Remaining pyrefly 'missing return' errors are false positives where all paths do return
- Fixed trailing whitespace

* docs: update services README to highlight async-only architecture

- Add key features section highlighting pure async patterns
- Note race-condition-free initialization in ServiceFactory description
- Document weak reference usage in global factory management
- Add async patterns section to best practices
- Emphasize no threading is needed with proper asyncio usage

* refactor: improve cache key generation and lock management in decorators.py

* refactor: optimize test performance with list comprehensions and parallel execution

* fix: add type hints and fix type errors in test files

* refactor: consolidate validation tests using pytest parametrize and helper functions

* refactor: replace SimpleNamespace with proper callable wrapper classes in test fixtures
2025-08-05 13:03:53 -04:00

8.4 KiB

Task Master AI - Claude Code Integration Guide

Essential Commands

Core Workflow Commands

# Project Setup
task-master init                                    # Initialize Task Master in current project
task-master parse-prd .taskmaster/docs/prd.txt      # Generate tasks from PRD document
task-master models --setup                        # Configure AI models interactively

# Daily Development Workflow
task-master list                                   # Show all tasks with status
task-master next                                   # Get next available task to work on
task-master show <id>                             # View detailed task information (e.g., task-master show 1.2)
task-master set-status --id=<id> --status=done    # Mark task complete

# Task Management
task-master add-task --prompt="description" --research        # Add new task with AI assistance
task-master expand --id=<id> --research --force              # Break task into subtasks
task-master update-task --id=<id> --prompt="changes"         # Update specific task
task-master update --from=<id> --prompt="changes"            # Update multiple tasks from ID onwards
task-master update-subtask --id=<id> --prompt="notes"        # Add implementation notes to subtask

# Analysis & Planning
task-master analyze-complexity --research          # Analyze task complexity
task-master complexity-report                      # View complexity analysis
task-master expand --all --research               # Expand all eligible tasks

# Dependencies & Organization
task-master add-dependency --id=<id> --depends-on=<id>       # Add task dependency
task-master move --from=<id> --to=<id>                       # Reorganize task hierarchy
task-master validate-dependencies                            # Check for dependency issues
task-master generate                                         # Update task markdown files (usually auto-called)

Key Files & Project Structure

Core Files

  • .taskmaster/tasks/tasks.json - Main task data file (auto-managed)
  • .taskmaster/config.json - AI model configuration (use task-master models to modify)
  • .taskmaster/docs/prd.txt - Product Requirements Document for parsing
  • .taskmaster/tasks/*.txt - Individual task files (auto-generated from tasks.json)
  • .env - API keys for CLI usage

Claude Code Integration Files

  • CLAUDE.md - Auto-loaded context for Claude Code (this file)
  • .claude/settings.json - Claude Code tool allowlist and preferences
  • .claude/commands/ - Custom slash commands for repeated workflows
  • .mcp.json - MCP server configuration (project-specific)

Directory Structure

project/
├── .taskmaster/
│   ├── tasks/              # Task files directory
│   │   ├── tasks.json      # Main task database
│   │   ├── task-1.md      # Individual task files
│   │   └── task-2.md
│   ├── docs/              # Documentation directory
│   │   ├── prd.txt        # Product requirements
│   ├── reports/           # Analysis reports directory
│   │   └── task-complexity-report.json
│   ├── templates/         # Template files
│   │   └── example_prd.txt  # Example PRD template
│   └── config.json        # AI models & settings
├── .claude/
│   ├── settings.json      # Claude Code configuration
│   └── commands/         # Custom slash commands
├── .env                  # API keys
├── .mcp.json            # MCP configuration
└── CLAUDE.md            # This file - auto-loaded by Claude Code

Development Tools & Recommendations

Linting and Type Checking

  • Caution: Do not run pyrefly check . as it will crash. Only use make pyrefly after activating the virtual environment.
  • Linting Recommendation: basedpyright & pyrefly are the best linters, only use ruff for fast formatting and syntax

Best Practices and Guidelines

Error Handling

  • Never use generic exceptions, always use custom exceptions from @src/biz_bud/core/errors/

Package Usage

  • Always utilize the projects core packages in @src/biz_bud/core/ and @src/biz_bud/logging/

Core Patterns and Code Quality Standards

Architecture Overview

Business Buddy follows a modular architecture with dependency injection, singleton service management, and typed state patterns:

Service Factory Pattern

  • Central orchestration: All services created through ServiceFactory with automatic dependency injection
  • Thread-safe singletons: Race-condition-free service creation with proper lifecycle management
  • Context managers: Always use async with ServiceFactory(config) for automatic cleanup
  • Global factory: Use get_global_factory() for application-wide services

Focused State Architecture

  • Scoped states: Each workflow uses focused TypedDict states instead of monolithic state
  • Type safety: All states inherit from BaseState with proper field typing
  • Reducer patterns: Use Annotated[list[T], add] for accumulating fields
  • Immutability: Return state updates, never mutate state directly

Provider-Based Tools

  • Unified interfaces: All tools follow consistent provider patterns for extensibility
  • Auto-fallback: Tools automatically select best available provider
  • Structured models: SearchResult, ScrapedContent, ExtractedData ensure interoperability
  • Service integration: Tools leverage service factory for consistent resource access

Code Quality Standards

Type Safety

  • Modern typing: Use typing_extensions for latest type annotations
  • No Any types: Find specific types instead of using Any
  • Pydantic models: Use for configuration and validation schemas
  • Field validation: Apply constraints with Field(ge=1, le=300)
  • Use the Annotated pattern with Pydantic Fields for constraints

Error Handling

  • Custom exceptions: Always use project-specific exceptions from @src/biz_bud/core/errors/
  • No generic exceptions: Never use bare Exception or ValueError
  • Retry patterns: Implement exponential backoff for external services
  • Circuit breakers: Use for external dependencies with failure thresholds

LangGraph Patterns

  • Standard decorators: Apply @standard_node, @handle_errors, @log_node_execution
  • Factory functions: Create graphs through factory functions, not direct construction
  • Command routing: Use Command pattern for intelligent state-based navigation
  • Reusable edge helpers: Leverage built-in routing functions to prevent duplication

Resource Management

  • Context managers: Use for automatic cleanup of services and connections
  • Connection pooling: Configure appropriate pool sizes (5-20 connections)
  • Batch processing: Process large datasets in chunks to avoid memory issues
  • Cache strategies: Implement multi-level caching (memory, Redis, disk)

Configuration Management

  • Single source of truth: Use AppConfig and RunnableConfig
  • Environment variables: Load sensitive data from environment
  • Node-specific configs: Use context-specific overrides when needed
  • Validation early: Validate configuration at startup

Testing Patterns

  • Service mocking: Mock services through factory for isolated testing
  • Fixture hierarchy: Use pytest fixtures for reusable test setup
  • Integration tests: Test full workflows with real backends
  • Error simulation: Test retry logic and error handling paths

Anti-Technical Debt Patterns

  • Centralized resource management: Use context managers and cleanup registries
  • Configuration consolidation: Single source through AppConfig
  • Standardized node patterns: Consistent structure across all nodes
  • Reusable components: DRY routing logic and common patterns

Performance Optimization

  • Concurrent initialization: Initialize multiple services concurrently
  • Critical services: Pre-initialize essential services for faster startup
  • Memory efficiency: Use weak references and proper cleanup
  • Caching layers: Redis with TTL management and batch operations

Code Design Recommendations

State Management

  • When interacting with State TypeDicts, prioritize .get() instead of isinstance checks

Git Best Practices

Version Control Guidelines

  • Do not ever git commit with --no-verify

Task Master AI Instructions

Import Task Master's development workflow commands and guidelines, treat as if import is in the main CLAUDE.md file. @./.taskmaster/CLAUDE.md