crackerjack 0.39.1__py3-none-any.whl → 0.39.3__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of crackerjack might be problematic. Click here for more details.

@@ -10,9 +10,10 @@ type checking during pre-commit hooks.
10
10
  import sys
11
11
  from pathlib import Path
12
12
 
13
- from crackerjack.services.lsp_client import LSPClient
14
13
  from rich.console import Console
15
14
 
15
+ from crackerjack.services.lsp_client import LSPClient
16
+
16
17
 
17
18
  def main() -> int:
18
19
  """Main entry point for LSP hook."""
@@ -4,9 +4,8 @@ import subprocess
4
4
  import sys
5
5
  from pathlib import Path
6
6
 
7
- from rich.console import Console
8
-
9
7
  from mcp import stdio_client
8
+ from rich.console import Console
10
9
 
11
10
  from .progress_monitor import (
12
11
  run_crackerjack_with_enhanced_progress as run_crackerjack_with_progress,
@@ -4,7 +4,7 @@ import typing as t
4
4
  from datetime import datetime
5
5
  from pathlib import Path
6
6
 
7
- from pydantic import BaseModel, Field
7
+ from pydantic import BaseModel, ConfigDict, Field, field_serializer
8
8
 
9
9
 
10
10
  class EmbeddingVector(BaseModel):
@@ -26,13 +26,17 @@ class EmbeddingVector(BaseModel):
26
26
  end_line: int = Field(..., description="Ending line number in the source file")
27
27
  file_type: str = Field(..., description="File extension or type identifier")
28
28
 
29
- class Config:
30
- """Pydantic configuration."""
29
+ model_config = ConfigDict(ser_json_timedelta="iso8601")
31
30
 
32
- json_encoders = {
33
- Path: str,
34
- datetime: lambda v: v.isoformat(),
35
- }
31
+ @field_serializer("file_path")
32
+ def serialize_path(self, value: Path) -> str:
33
+ """Serialize Path to string."""
34
+ return str(value)
35
+
36
+ @field_serializer("created_at")
37
+ def serialize_datetime(self, value: datetime) -> str:
38
+ """Serialize datetime to ISO format."""
39
+ return value.isoformat()
36
40
 
37
41
 
38
42
  class SearchResult(BaseModel):
@@ -51,12 +55,10 @@ class SearchResult(BaseModel):
51
55
  default_factory=list, description="Surrounding context lines"
52
56
  )
53
57
 
54
- class Config:
55
- """Pydantic configuration."""
56
-
57
- json_encoders = {
58
- Path: str,
59
- }
58
+ @field_serializer("file_path")
59
+ def serialize_path(self, value: Path) -> str:
60
+ """Serialize Path to string."""
61
+ return str(value)
60
62
 
61
63
 
62
64
  class IndexStats(BaseModel):
@@ -72,12 +74,10 @@ class IndexStats(BaseModel):
72
74
  embedding_model: str = Field(..., description="Name of the embedding model used")
73
75
  avg_chunk_size: float = Field(..., description="Average chunk size in characters")
74
76
 
75
- class Config:
76
- """Pydantic configuration."""
77
-
78
- json_encoders = {
79
- datetime: lambda v: v.isoformat(),
80
- }
77
+ @field_serializer("last_updated")
78
+ def serialize_datetime(self, value: datetime) -> str:
79
+ """Serialize datetime to ISO format."""
80
+ return value.isoformat()
81
81
 
82
82
 
83
83
  class SearchQuery(BaseModel):
@@ -100,10 +100,7 @@ class SearchQuery(BaseModel):
100
100
  default=3, ge=0, le=10, description="Number of context lines"
101
101
  )
102
102
 
103
- class Config:
104
- """Pydantic configuration."""
105
-
106
- validate_assignment = True
103
+ model_config = ConfigDict(validate_assignment=True)
107
104
 
108
105
 
109
106
  class IndexingProgress(BaseModel):
@@ -125,12 +122,10 @@ class IndexingProgress(BaseModel):
125
122
  return 0.0
126
123
  return min(100.0, (self.files_processed / self.total_files) * 100.0)
127
124
 
128
- class Config:
129
- """Pydantic configuration."""
130
-
131
- json_encoders = {
132
- Path: str,
133
- }
125
+ @field_serializer("current_file")
126
+ def serialize_path(self, value: Path) -> str:
127
+ """Serialize Path to string."""
128
+ return str(value)
134
129
 
135
130
 
136
131
  class SemanticConfig(BaseModel):
@@ -195,10 +190,7 @@ class SemanticConfig(BaseModel):
195
190
  default=24, ge=1, le=168, description="Cache time-to-live in hours"
196
191
  )
197
192
 
198
- class Config:
199
- """Pydantic configuration."""
200
-
201
- validate_assignment = True
193
+ model_config = ConfigDict(validate_assignment=True)
202
194
 
203
195
 
204
196
  class FileChangeEvent(BaseModel):
@@ -215,13 +207,15 @@ class FileChangeEvent(BaseModel):
215
207
  default=None, description="New file hash if available"
216
208
  )
217
209
 
218
- class Config:
219
- """Pydantic configuration."""
210
+ @field_serializer("file_path")
211
+ def serialize_path(self, value: Path) -> str:
212
+ """Serialize Path to string."""
213
+ return str(value)
220
214
 
221
- json_encoders = {
222
- Path: str,
223
- datetime: lambda v: v.isoformat(),
224
- }
215
+ @field_serializer("timestamp")
216
+ def serialize_datetime(self, value: datetime) -> str:
217
+ """Serialize datetime to ISO format."""
218
+ return value.isoformat()
225
219
 
226
220
 
227
221
  class SemanticContext(BaseModel):
@@ -241,13 +235,6 @@ class SemanticContext(BaseModel):
241
235
  ..., ge=0.0, le=1.0, description="Confidence in the context relevance"
242
236
  )
243
237
 
244
- class Config:
245
- """Pydantic configuration."""
246
-
247
- json_encoders = {
248
- Path: str,
249
- }
250
-
251
238
 
252
239
  # Type aliases for better code readability
253
240
  EmbeddingMatrix = list[list[float]]
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: crackerjack
3
- Version: 0.39.1
3
+ Version: 0.39.3
4
4
  Summary: Crackerjack Python project management tool
5
5
  Project-URL: documentation, https://github.com/lesleslie/crackerjack
6
6
  Project-URL: homepage, https://github.com/lesleslie/crackerjack
@@ -1,4 +1,3 @@
1
- crackerjack/CLAUDE.md,sha256=FnF1XgcaCB59HEZxglEl4qEBTMyHQcqKoL0YjnAq24s,41230
2
1
  crackerjack/__init__.py,sha256=DajG9zHB8qBdgdiKMumrrssUbKeMXmtIQ3oOaSTb46Y,1426
3
2
  crackerjack/__main__.py,sha256=gS8PIp-98GUlZodL8vgOQNKUIo9qL-TY2FWQ2WXpqSk,58923
4
3
  crackerjack/api.py,sha256=PyCRaZHvKWdu62_2O4t_HcEfKNBdqyrfPdonS_PNn4c,21495
@@ -82,7 +81,7 @@ crackerjack/executors/hook_lock_manager.py,sha256=ft24q6VFEkW_QrifNnSlrQeHGx9GuJ
82
81
  crackerjack/executors/individual_hook_executor.py,sha256=t0W9vuqLGPx0HmbTo01N9MRFyqLfY0ZLG06ZIA5qfBY,24362
83
82
  crackerjack/executors/lsp_aware_hook_executor.py,sha256=aZxtTwpaDxfmN71II2MEAtfzEst-jPJp-GXmMLwnibA,10388
84
83
  crackerjack/executors/tool_proxy.py,sha256=dJnrt72aFXEMuZLsgrLZrf51vfELDaXs5nBxzGHu7SQ,14881
85
- crackerjack/hooks/lsp_hook.py,sha256=MPP9EYmKdZMNBvAQSAwzI5L8TkwKTd0uVx3heaTHmM0,2877
84
+ crackerjack/hooks/lsp_hook.py,sha256=Rw52CFLfJj-eaW50_RFbAl7cCVyxHdup3YnJYTlN6pg,2878
86
85
  crackerjack/intelligence/__init__.py,sha256=3Sty6xFyxBEXTyy8W34dpAQk7S7m8SnxUz4wrb3xrZc,878
87
86
  crackerjack/intelligence/adaptive_learning.py,sha256=Q0pUyxzBBCtySTfp96zHObQVAUaN0c5kEFOFJKIG0j8,25610
88
87
  crackerjack/intelligence/agent_orchestrator.py,sha256=YOG2sQc0l5ddz7TzRZ_1YAugTNwuyY1brWrlj5tnMhk,16728
@@ -100,7 +99,7 @@ crackerjack/managers/test_manager_backup.py,sha256=CR8D7WZ68ZrTADFqYJtVDUWnlznJX
100
99
  crackerjack/managers/test_progress.py,sha256=B1013ygUk2nAo37whDXNA7n-FYdsEO4qj17fuDm_fdg,3058
101
100
  crackerjack/mcp/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
102
101
  crackerjack/mcp/cache.py,sha256=uq5XVeRjNyARfaAyN9DsaPURU_OHdBId5UfDvXbfSos,11974
103
- crackerjack/mcp/client_runner.py,sha256=Mrcsw7oTk1JgIno7OuNlVVM28UtmGjQYItpToTVOFzU,2993
102
+ crackerjack/mcp/client_runner.py,sha256=TAakDlrq6FYCc3tAj4m752GyzSpC5RTdJSXX34t8kqs,2992
104
103
  crackerjack/mcp/context.py,sha256=T1rhScFxbqi0Kaf6o8NusVUIwc8o7YGxcsLdmlWVsPI,28350
105
104
  crackerjack/mcp/dashboard.py,sha256=eApQekZe1DfKBrlDW5yobyqaN_gdh17ZQlqGmut5TCs,19602
106
105
  crackerjack/mcp/enhanced_progress_monitor.py,sha256=xhACaEjreDw1cLObJmhr5ttowl5mRqeohmMzQfRQj3w,16448
@@ -141,7 +140,7 @@ crackerjack/models/config.py,sha256=YBP3W_XhI94W_mcDZ_Tw5p0cOtVPMKZ4nsJs-GiXyYU,
141
140
  crackerjack/models/config_adapter.py,sha256=hlw2fwlgwSFjcgzRFG4NYsV5bO1Tud0PL-2WsJRSlvw,8821
142
141
  crackerjack/models/protocols.py,sha256=ZtyatubJxnmnnTKzXWCbl8CvREPt2pywSco5KYBJI2o,10970
143
142
  crackerjack/models/resource_protocols.py,sha256=oZiq0NEG2kWV0XQ871GIYRx_0v_oQulvEjTbidTbueM,7297
144
- crackerjack/models/semantic_models.py,sha256=ro0yHb7ctPV_w1_Fkgx9aNPK9PU3U3o976XmGpHkbgc,8666
143
+ crackerjack/models/semantic_models.py,sha256=I_F8K_se1NVklOIqr-PzKgWcgvhQ1CL6o89p1PJjLaI,9005
145
144
  crackerjack/models/task.py,sha256=Du5vwXj-P_aSIZsFt1Ek4jCTkXz_6DXfnflUxgXkecY,4542
146
145
  crackerjack/monitoring/__init__.py,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
147
146
  crackerjack/monitoring/ai_agent_watchdog.py,sha256=_Usni6d8A-1CKAx2d5LUMXYldMiQB5cdZPd-NrCe2p8,15138
@@ -236,8 +235,8 @@ crackerjack/tools/validate_input_validator_patterns.py,sha256=NN7smYlXWrHLQXTb-8
236
235
  crackerjack/tools/validate_regex_patterns.py,sha256=J7GG9EP1fASpRIsG8qRPeiCSkdCwmk0sdo29GgoJ6w8,5863
237
236
  crackerjack/ui/__init__.py,sha256=eMb1OeTU-dSLICAACn0YdYB4Amdr8wHckjKfn0wOIZE,37
238
237
  crackerjack/ui/server_panels.py,sha256=F5IH6SNN06BaZQMsFx_D-OA286aojmaFPJ5kvvSRv_c,4232
239
- crackerjack-0.39.1.dist-info/METADATA,sha256=5lW_THu86owYxpYnBifg6vQ0kh3CiRVkp-FAPizho2Y,38239
240
- crackerjack-0.39.1.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
241
- crackerjack-0.39.1.dist-info/entry_points.txt,sha256=AJKNft0WXm9xoGUJ3Trl-iXHOWxRAYbagQiza3AILr4,57
242
- crackerjack-0.39.1.dist-info/licenses/LICENSE,sha256=fDt371P6_6sCu7RyqiZH_AhT1LdN3sN1zjBtqEhDYCk,1531
243
- crackerjack-0.39.1.dist-info/RECORD,,
238
+ crackerjack-0.39.3.dist-info/METADATA,sha256=yApUCaBS7T4QJ6sTyVSc1gKWnr9VlpPCr26MWnaM1zM,38239
239
+ crackerjack-0.39.3.dist-info/WHEEL,sha256=qtCwoSJWgHk21S1Kb4ihdzI2rlJ1ZKaIurTj_ngOhyQ,87
240
+ crackerjack-0.39.3.dist-info/entry_points.txt,sha256=AJKNft0WXm9xoGUJ3Trl-iXHOWxRAYbagQiza3AILr4,57
241
+ crackerjack-0.39.3.dist-info/licenses/LICENSE,sha256=fDt371P6_6sCu7RyqiZH_AhT1LdN3sN1zjBtqEhDYCk,1531
242
+ crackerjack-0.39.3.dist-info/RECORD,,
crackerjack/CLAUDE.md DELETED
@@ -1,1011 +0,0 @@
1
- # CLAUDE.md
2
-
3
- This file provides guidance to Claude Code (claude.ai/code) when working with code in this repository.
4
-
5
- ## Clean Code Philosophy (READ FIRST)
6
-
7
- **EVERY LINE OF CODE IS A LIABILITY. The best code is no code.**
8
-
9
- - **DRY (Don't Repeat Yourself)**: If you write it twice, you're doing it wrong
10
- - **YAGNI (You Ain't Gonna Need It)**: Build only what's needed NOW
11
- - **KISS (Keep It Simple, Stupid)**: Complexity is the enemy of maintainability
12
- - **Less is More**: Prefer 10 lines that are clear over 100 that are clever
13
- - **Code is Read 10x More Than Written**: Optimize for readability
14
- - **Self-Documenting Code**: Code should explain itself; comments only for "why", not "what". Variable names should **ALWAYS** be clear and descriptive, even in inline map/filter functions.
15
-
16
- ## Project Overview
17
-
18
- Crackerjack is an opinionated Python project management tool that unifies UV, Ruff, pytest, and pre-commit into a single workflow. It enforces consistent code quality from setup to deployment and includes AI agent integration via MCP (Model Context Protocol).
19
-
20
- **Key Dependencies**: Python 3.13+, UV package manager, pre-commit hooks, pytest
21
-
22
- ## Core Development Commands
23
-
24
- ### Primary Workflows
25
-
26
- ```bash
27
- # Quality checks only (most common during development)
28
- python -m crackerjack
29
-
30
- # With testing
31
- python -m crackerjack -t
32
-
33
- # Code cleaning with TODO detection (blocks if TODOs found)
34
- # Note: Automatically creates backups in temp directory for safety
35
- python -m crackerjack -x
36
-
37
- # Full release workflow with version bump and publishing
38
- python -m crackerjack -a patch
39
-
40
- # Interactive mode with rich UI
41
- python -m crackerjack -i
42
-
43
- # Skip hooks during development iterations
44
- python -m crackerjack --skip-hooks
45
-
46
- # AI Agent mode with autonomous auto-fixing (STANDARD PROCESS)
47
- python -m crackerjack --ai-agent -t
48
-
49
- # AI Agent mode with full debugging and verbose output
50
- python -m crackerjack --ai-debug -t
51
-
52
- # Start MCP server for AI agent integration
53
- python -m crackerjack --start-mcp-server
54
-
55
- # Stop all running MCP servers
56
- python -m crackerjack --stop-mcp-server
57
-
58
- # Restart MCP server (stop and start again)
59
- python -m crackerjack --restart-mcp-server
60
-
61
- # Start dedicated WebSocket progress server (runs on localhost:8675)
62
- python -m crackerjack --start-websocket-server
63
-
64
- # Start multi-project progress monitor with Textual TUI
65
- python -m crackerjack --monitor
66
-
67
- # Start enhanced progress monitor with advanced MetricCard widgets (recommended)
68
- python -m crackerjack --enhanced-monitor
69
-
70
- # Start MCP server with custom WebSocket port
71
- python -m crackerjack --start-mcp-server --websocket-port 8675
72
-
73
- # Restart MCP server with custom WebSocket port
74
- python -m crackerjack --restart-mcp-server --websocket-port 8675
75
-
76
- # Start service watchdog to monitor and auto-restart MCP and WebSocket servers
77
- python -m crackerjack --watchdog
78
- ```
79
-
80
- ### Terminal Recovery
81
-
82
- **If your terminal gets stuck after quitting the monitor (no history, character input issues):**
83
-
84
- ```bash
85
- # Option 1: Use the recovery script
86
- ./fix_terminal.sh
87
-
88
- # Option 2: Manual recovery commands
89
- stty sane; reset; exec $SHELL -l
90
-
91
- # Option 3: Simple reset
92
- reset
93
- ```
94
-
95
- **The enhanced terminal restoration automatically handles:**
96
-
97
- - Mouse tracking disabling
98
- - Alternate screen buffer exit
99
- - Focus events restoration
100
- - Bracketed paste mode cleanup
101
- - Full terminal input/output restoration
102
-
103
- ### AI Agent Auto-Fixing Process
104
-
105
- **The AI agent provides intelligent, autonomous code fixing that goes far beyond basic tool auto-fixes:**
106
-
107
- #### Two Types of Auto-Fixing
108
-
109
- **1. Hook Auto-Fix Modes (Limited Scope)**
110
-
111
- - Basic formatting tools like `ruff --fix`, `trailing-whitespace --fix`
112
- - Only handle simple style issues (whitespace, import order, basic formatting)
113
- - Cannot fix logic errors, type issues, security problems, or test failures
114
-
115
- **2. AI Agent Auto-Fixing (Comprehensive Intelligence)**
116
-
117
- - Analyzes ALL error types: hooks, tests, type checking, security, complexity
118
- - Reads source code, understands context, and makes intelligent modifications
119
- - Fixes actual bugs, adds missing type annotations, resolves test failures
120
- - Handles complex issues that require code understanding and logic changes
121
-
122
- #### Standard AI Agent Iterative Process
123
-
124
- **This is the recommended standard process for achieving code quality compliance:**
125
-
126
- ```bash
127
- # AI Agent mode with automatic fixing between iterations
128
- python -m crackerjack --ai-agent -t
129
-
130
- # The AI agent follows this optimal workflow order in each iteration:
131
- # 1. Fast Hooks (formatting) → Retry once if any fail (fixes often cascade)
132
- # 2. Full Test Suite → Collect ALL test failures (don't stop on first)
133
- # 3. Comprehensive Hooks → Collect ALL quality issues (don't stop on first)
134
- # 4. AI Analysis & Batch Fixing → Fix ALL collected issues in one pass
135
- # 5. Repeat entire cycle until all checks pass (up to 10 iterations)
136
-
137
- # CRITICAL: The AI agent only moves to the next iteration AFTER applying fixes
138
- # This ensures that each iteration validates the fixes from the previous iteration
139
- ```
140
-
141
- **What the AI Agent Auto-Fixes:**
142
-
143
- - **Type Errors**: Adds missing type annotations, fixes type mismatches
144
- - **Security Issues**: Removes hardcoded paths, fixes subprocess vulnerabilities
145
- - **Dead Code**: Removes unused imports, variables, and functions
146
- - **Test Failures**: Fixes missing fixtures, import errors, assertion issues
147
- - **Code Quality**: Applies refactoring suggestions, reduces complexity
148
- - **Dependency Issues**: Removes unused dependencies from pyproject.toml
149
- - **Hook Failures**: All formatting, linting, and style issues
150
-
151
- **Benefits of AI Agent Auto-Fixing:**
152
-
153
- - **Autonomous Operation**: Requires no manual intervention
154
- - **Intelligent Analysis**: Understands code context and intent
155
- - **Comprehensive Coverage**: Fixes all error types, not just formatting
156
- - **Iterative Improvement**: Continues until perfect code quality achieved
157
- - **Learning Capability**: Adapts fixing strategies based on codebase patterns
158
-
159
- #### Sub-Agent Architecture
160
-
161
- **Crackerjack uses specialized sub-agents for domain-specific code quality issues:**
162
-
163
- **Available Sub-Agents:**
164
-
165
- - **DocumentationAgent**: Documentation consistency and changelog management
166
-
167
- - **Primary Expertise**: `IssueType.DOCUMENTATION` (documentation consistency, changelog updates)
168
- - **Capabilities**:
169
- - Auto-generates changelog entries from git commits during version bumps
170
- - Maintains consistency across all .md files (agent counts, references)
171
- - Updates README examples when APIs change
172
- - Adds newly discovered error patterns to CLAUDE.md
173
- - Cross-validates documentation references
174
- - Integrates with publish workflow for automatic changelog updates
175
- - **Philosophy Alignment**: Reduces manual documentation maintenance (YAGNI principle)
176
- - **Confidence**: 0.8 for documentation issues
177
-
178
- - **RefactoringAgent**: Structural code improvements and complexity reduction
179
-
180
- - **Primary Expertise**: `IssueType.COMPLEXITY` (cognitive complexity ≤13)
181
- - **Secondary Expertise**: `IssueType.DEAD_CODE` (unused imports, variables, functions)
182
- - **Capabilities**:
183
- - Breaks down complex functions into helper methods
184
- - Removes unused imports, variables, and functions using AST analysis
185
- - Extracts common patterns into reusable utilities
186
- - Applies dependency injection and Protocol patterns
187
- - **Philosophy Alignment**: Perfect fit with DRY, YAGNI, KISS principles
188
-
189
- - **PerformanceAgent**: Performance optimization and algorithmic improvements
190
-
191
- - **Primary Expertise**: `IssueType.PERFORMANCE` (performance anti-patterns and bottlenecks)
192
- - **Capabilities**:
193
- - Detects and fixes nested loops with O(n²) complexity
194
- - Transforms inefficient list concatenation (`list += [item]` → `list.append(item)`)
195
- - Optimizes string building (concatenation → list.append + join pattern)
196
- - Identifies repeated expensive operations in loops (file I/O, function calls)
197
- - Applies AST-based pattern recognition for accurate detection
198
- - **Real Code Transformation**: Actually modifies code, not just comments
199
- - **Philosophy Alignment**: KISS principle through algorithmic efficiency
200
-
201
- - **DRYAgent**: Don't Repeat Yourself violation detection and fixing
202
-
203
- - **Primary Expertise**: `IssueType.DRY_VIOLATION` (code duplication and repetition)
204
- - **Capabilities**:
205
- - Detects duplicate code patterns and repeated functionality
206
- - Suggests extracting common patterns to utility functions
207
- - Recommends creating base classes or mixins for repeated functionality
208
- - Identifies opportunities for code consolidation and refactoring
209
- - **Philosophy Alignment**: Core DRY principle enforcement
210
-
211
- - **FormattingAgent**: Code style and formatting issues
212
-
213
- - **Primary Expertise**: `IssueType.FORMATTING`, `IssueType.IMPORT_ERROR`
214
- - **Capabilities**:
215
- - Handles code style and formatting violations
216
- - Fixes import-related formatting issues
217
- - Ensures consistent code formatting standards
218
-
219
- - **SecurityAgent**: Security vulnerabilities and best practices
220
-
221
- - **Primary Expertise**: `IssueType.SECURITY`
222
- - **Capabilities**:
223
- - Detects and fixes security vulnerabilities (hardcoded paths, unsafe operations)
224
- - Applies security best practices
225
- - Identifies potential security risks in code patterns
226
-
227
- - **ImportOptimizationAgent**: Import statement optimization and cleanup
228
-
229
- - **Primary Expertise**: `IssueType.IMPORT_ERROR`, `IssueType.DEAD_CODE`
230
- - **Capabilities**:
231
- - Optimizes import statements and organization
232
- - Removes unused imports and dead code
233
- - Consolidates and reorganizes import patterns
234
- - **Real Code Transformation**: Restructures import statements
235
-
236
- - **TestCreationAgent**: Test coverage and quality improvements
237
-
238
- - **Primary Expertise**: `IssueType.TEST_FAILURE`, `IssueType.DEPENDENCY`
239
- - **Capabilities**:
240
- - Fixes test failures and missing test dependencies
241
- - Improves test coverage and quality
242
- - Handles dependency-related testing issues
243
-
244
- - **TestSpecialistAgent**: Advanced testing scenarios and fixtures
245
-
246
- - **Primary Expertise**: `IssueType.IMPORT_ERROR`, `IssueType.TEST_FAILURE`
247
- - **Capabilities**:
248
- - Handles complex testing scenarios and fixture management
249
- - Fixes advanced test failures and import issues in test files
250
- - Specializes in testing framework integration
251
-
252
- **Agent Coordination:**
253
-
254
- - **AgentCoordinator** routes issues to appropriate agents based on confidence scoring
255
- - **Single-agent mode**: High confidence (≥0.7) issues handled by best-match agent
256
- - **Collaborative mode**: Lower confidence issues processed by multiple agents
257
- - **Batch processing**: Issues grouped by type for efficient parallel processing
258
-
259
- **Agent Integration:**
260
-
261
- ```python
262
- # Automatic integration - all agents are registered and coordinated
263
- # 9 total agents: DocumentationAgent, RefactoringAgent, PerformanceAgent, FormattingAgent,
264
- # SecurityAgent, TestCreationAgent, TestSpecialistAgent, ImportOptimizationAgent, DRYAgent
265
-
266
- # Agent confidence scoring examples:
267
- # DocumentationAgent:
268
- # - 0.8 confidence for documentation issues (primary expertise)
269
- # RefactoringAgent:
270
- # - 0.9 confidence for complexity issues (primary expertise)
271
- # - 0.8 confidence for dead code issues (secondary expertise)
272
- # PerformanceAgent:
273
- # - 0.85 confidence for performance issues (primary expertise)
274
- # - Real code transformations with AST-based detection
275
-
276
- # Works with all agents for comprehensive code quality fixes
277
- ```
278
-
279
- ### Temporary File Management
280
-
281
- **Crackerjack automatically manages temporary files created during execution:**
282
-
283
- ```bash
284
- # Default behavior (recommended)
285
- python -m crackerjack # Auto-cleanup: keeps 5 debug logs, 10 coverage files
286
-
287
- # Customize cleanup behavior
288
- python -m crackerjack --no-cleanup # Disable automatic cleanup
289
- python -m crackerjack --keep-debug-logs 10 # Keep more debug files
290
- python -m crackerjack --keep-coverage-files 20 # Keep more coverage files
291
- ```
292
-
293
- **Files managed:**
294
-
295
- - `crackerjack-debug-*.log` - Debug logs from each run (default: keep 5 most recent)
296
- - `.coverage.*` - Coverage data files from pytest-cov (default: keep 10 most recent)
297
-
298
- **Configuration**: Cleanup behavior can be controlled via CLI options or disabled entirely for debugging purposes.
299
-
300
- ### Testing & Development
301
-
302
- ```bash
303
- # Run specific test
304
- python -m pytest tests/test_specific.py::TestClass::test_method -v
305
-
306
- # Run with coverage
307
- python -m pytest --cov=crackerjack --cov-report=html
308
-
309
- # Run tests with specific worker count
310
- python -m crackerjack -t --test-workers 4
311
-
312
- # Benchmark mode
313
- python -m crackerjack --benchmark
314
-
315
- # Progress monitoring for WebSocket MCP jobs
316
- python -m crackerjack.mcp.progress_monitor <job_id> ws://localhost:8675
317
-
318
- # Run with experimental hooks (pyrefly, ty)
319
- python -m crackerjack --experimental-hooks
320
-
321
- # Debug AI agent workflows with detailed logging
322
- python -m crackerjack --ai-debug -t
323
-
324
- # Enable verbose output for troubleshooting
325
- python -m crackerjack --verbose -t
326
-
327
- ```
328
-
329
- ### Version Management
330
-
331
- ```bash
332
- # Bump version without publishing
333
- python -m crackerjack --bump patch # 0.30.3 -> 0.30.4
334
- python -m crackerjack --bump minor # 0.30.3 -> 0.31.0
335
- python -m crackerjack --bump major # 0.30.3 -> 1.0.0
336
-
337
- # Bump version without git tags
338
- python -m crackerjack --bump patch --no-git-tags
339
-
340
- # Skip version consistency verification
341
- python -m crackerjack --bump patch --skip-version-check
342
-
343
- # Publish to PyPI (requires UV_PUBLISH_TOKEN or keyring)
344
- python -m crackerjack -p patch
345
- ```
346
-
347
- ### UVX Integration
348
-
349
- **Crackerjack can be executed via uvx for isolated environments:**
350
-
351
- ```bash
352
- # For installed crackerjack (from PyPI)
353
- uvx crackerjack --help
354
- uvx crackerjack -t
355
- uvx crackerjack --start-mcp-server
356
-
357
- # For local development version
358
- uvx --from /Users/les/Projects/crackerjack crackerjack --help
359
- uvx --from /Users/les/Projects/crackerjack crackerjack -t
360
- uvx --from /Users/les/Projects/crackerjack crackerjack --start-mcp-server
361
- ```
362
-
363
- **Benefits**: Isolated execution, no dependency conflicts, consistent environment across systems.
364
-
365
- ## Architecture Overview
366
-
367
- **Recently refactored from monolithic `crackerjack.py` to modular architecture:**
368
-
369
- ### Core Orchestration Layer
370
-
371
- - **`core/workflow_orchestrator.py`**: Main entry point with `WorkflowOrchestrator` and `WorkflowPipeline` classes
372
- - **`core/container.py`**: Basic dependency injection container using protocols for loose coupling
373
- - **`core/enhanced_container.py`**: Advanced DI container with lifecycle management
374
- - **ServiceLifetime** enum: `SINGLETON`, `TRANSIENT`, `SCOPED` service lifetimes
375
- - **ServiceDescriptor** dataclass: Comprehensive service registration with factory support
376
- - **Thread-safe**: Singleton instances with thread-local scoping
377
- - **Dependency resolution**: Automatic dependency injection with circular dependency detection
378
- - **`__main__.py`**: Simplified CLI entry point (reduced from 601 to 122 lines via modularization)
379
-
380
- ### Coordinator Layer (Workflow Management)
381
-
382
- - **`core/session_coordinator.py`**: Session tracking, cleanup handlers, progress management
383
- - **`core/phase_coordinator.py`**: Individual workflow phases (cleaning, config, hooks, testing, publishing, commit)
384
- - **`core/async_workflow_orchestrator.py`**: Async workflow coordination with parallel execution
385
- - **Async/await patterns**: Non-blocking workflow execution
386
- - **Parallel hook execution**: Concurrent pre-commit hook processing
387
- - **Progress streaming**: Real-time progress updates via WebSocket
388
- - **Error aggregation**: Collects all errors before batch processing by AI agents
389
-
390
- ### Domain Managers (Business Logic)
391
-
392
- - **`managers/hook_manager.py`**: Pre-commit hook execution with fast→comprehensive two-stage system
393
- - **`managers/test_manager.py`**: Test execution, coverage analysis, environment validation
394
- - **`managers/publish_manager.py`**: Version bumping, git tagging, PyPI publishing with authentication
395
-
396
- ### Component Interaction Patterns
397
-
398
- **Dependency Flow:**
399
-
400
- ```
401
- WorkflowOrchestrator → SessionCoordinator → PhaseCoordinator → Managers
402
-
403
- Container (DI) → Protocols → Concrete Implementations
404
- ```
405
-
406
- **Critical Interfaces in `models/protocols.py`:**
407
-
408
- - `HookManagerProtocol`, `TestManagerProtocol`, `PublishManagerProtocol`
409
- - Always import protocols, never concrete classes for dependency injection
410
- - **Common Error**: `from ..managers.test_manager import TestManager` ❌
411
- - **Correct**: `from ..models.protocols import TestManagerProtocol` ✅
412
-
413
- **Enhanced Dependency Injection Patterns** (using `EnhancedContainer`):
414
-
415
- ```python
416
- from crackerjack.core.enhanced_container import EnhancedContainer, ServiceLifetime
417
-
418
- # Service registration with lifecycle management
419
- container.register_service(
420
- interface=HookManagerProtocol,
421
- implementation=AsyncHookManager,
422
- lifetime=ServiceLifetime.SINGLETON, # Shared instance
423
- )
424
-
425
- # Factory-based registration for complex initialization
426
- container.register_factory(
427
- interface=TestManagerProtocol,
428
- factory=lambda: create_test_manager_with_config(),
429
- lifetime=ServiceLifetime.SCOPED, # Per-session instance
430
- )
431
-
432
- # Automatic dependency resolution
433
- hook_manager = container.resolve(HookManagerProtocol) # Returns singleton
434
- test_manager = container.resolve(TestManagerProtocol) # Creates scoped instance
435
- ```
436
-
437
- ### Infrastructure Services
438
-
439
- - **`services/filesystem.py`**: Basic file operations with caching, batching, and security validation
440
- - **`services/enhanced_filesystem.py`**: Advanced filesystem operations
441
- - **Atomic Operations**: Ensures file consistency during concurrent operations
442
- - **XDG Compliance**: Follows XDG Base Directory Specification for config/cache/data
443
- - **Backup Management**: Automatic backup creation with rotation policies
444
- - **Performance Monitoring**: File operation timing and performance metrics
445
- - **Security Validation**: Path traversal prevention and secure temp file handling
446
- - **`services/git.py`**: Git operations (commit, push, file tracking) with intelligent commit messages
447
- - **`services/config.py`**: Configuration management for pyproject.toml and .pre-commit-config.yaml
448
- - **`services/unified_config.py`**: Centralized configuration management across all components
449
- - **`services/security.py`**: Token handling, command validation, secure temp file creation
450
- - **`services/health_metrics.py`**: System health monitoring and performance benchmarking
451
- - **`services/contextual_ai_assistant.py`**: AI-powered code analysis and suggestions
452
-
453
- ### MCP Integration (AI Agent Support)
454
-
455
- **Refactored from monolithic 3,116-line server to modular architecture (70% line reduction):**
456
-
457
- - **`mcp/server.py`**: Backward compatibility wrapper (32 lines, imports from modular implementation)
458
- - **`mcp/server_core.py`**: Core MCP server configuration and setup (194 lines)
459
- - **`mcp/tools/`**: Modular tool implementations:
460
- - `core_tools.py`: Basic execution and stage tools
461
- - `monitoring_tools.py`: Status monitoring and health checks
462
- - `progress_tools.py`: Progress tracking and job management
463
- - `execution_tools.py`: Auto-fixing and workflow execution
464
- - **`mcp/context.py`**: Context manager for dependency injection and state management
465
- - **`mcp/state.py`**: Thread-safe session state management with async locks
466
- - **`mcp/cache.py`**: Thread-safe error pattern caching and fix result tracking
467
- - **`mcp/rate_limiter.py`**: Rate limiting, resource management, and DoS protection
468
- - **`mcp/file_monitor.py`**: Event-based file monitoring with watchdog
469
- - **Entry point**: `python -m crackerjack --start-mcp-server`
470
-
471
- **WebSocket Server (refactored from 1,479 lines to modular architecture - 35% reduction):**
472
-
473
- - **`mcp/websocket_server.py`**: Backward compatibility wrapper (imports from modular implementation)
474
- - **`mcp/websocket/server.py`**: Main WebSocket server class (101 lines)
475
- - **`mcp/websocket/app.py`**: FastAPI application setup (26 lines)
476
- - **`mcp/websocket/jobs.py`**: Job lifecycle and progress management (197 lines)
477
- - **`mcp/websocket/endpoints.py`**: HTTP endpoint definitions (545 lines)
478
- - **`mcp/websocket/websocket_handler.py`**: WebSocket connection handling (75 lines)
479
- - **Entry point**: `python -m crackerjack --start-websocket-server`
480
-
481
- ### CLI Interface (Modular Command Handling)
482
-
483
- - **`cli/options.py`**: CLI option definitions and models (213 lines)
484
- - **`cli/handlers.py`**: Mode handlers for different execution types (124 lines)
485
- - **`cli/utils.py`**: CLI utility functions (17 lines)
486
-
487
- ### Advanced Orchestration
488
-
489
- - **`orchestration/advanced_orchestrator.py`**: Advanced workflow orchestration with parallel execution strategies
490
- - **`orchestration/execution_strategies.py`**: Pluggable execution strategies for different workflow types
491
- - **`orchestration/test_progress_streamer.py`**: Real-time test progress streaming with Rich UI
492
-
493
- ### Plugin System
494
-
495
- - **`plugins/base.py`**: Base plugin interface and lifecycle management
496
- - **`plugins/loader.py`**: Dynamic plugin loading with dependency resolution
497
- - **`plugins/hooks.py`**: Pre-commit hook plugins with custom validation rules
498
- - **`plugins/managers.py`**: Plugin-specific manager implementations
499
-
500
- ### Legacy Components (Stable, Integrated)
501
-
502
- - **`code_cleaner.py`**: Modernized code cleaning with AST parsing and protocol-based architecture
503
- - **`dynamic_config.py`**: Configuration generation and management
504
- - **`interactive.py`**: Rich UI interactive mode with clean architecture
505
- - **`api.py`**: Public API with TODO detection for code cleaning operations
506
-
507
- ## Quality Process
508
-
509
- ### Optimal AI Agent Workflow Order
510
-
511
- **Proper execution order for maximum efficiency (used by `/crackerjack:run`):**
512
-
513
- 1. **Fast Hooks First** (~5 seconds): `trailing-whitespace`, `end-of-file-fixer`, `ruff-format`, `ruff-check`, `gitleaks`
514
-
515
- - **Package-focused**: `ruff-check` now runs only on `crackerjack/` package code, excludes `tests/`
516
- - **Repository-wide**: Other fast hooks (formatting) still run on entire repository
517
- - If any formatting hooks fail → **Retry fast hooks once** (formatting fixes often resolve downstream issues)
518
- - Only proceed when fast hooks pass or have been retried
519
-
520
- 1. **Full Test Suite** (~variable): Run ALL tests, collect ALL failures
521
-
522
- - **Don't stop on first failure** - gather complete list of test issues
523
- - Tests are more critical than lint issues, so run before comprehensive hooks
524
-
525
- 1. **Comprehensive Hooks** (~30 seconds): `pyright`, `bandit`, `vulture`, `refurb`, `creosote`, `complexipy`
526
-
527
- - **Package-focused by default**: Only run on `crackerjack/` package code, excludes `tests/`, `examples/`
528
- - **Don't stop on first failure** - gather complete list of quality issues
529
- - Use `--with-tests` flag (future) to include tests in comprehensive quality checks
530
-
531
- 1. **AI Analysis & Batch Fixing**: Process ALL collected failures together
532
-
533
- - More efficient than fixing one issue at a time
534
- - AI can consider dependencies between fixes
535
-
536
- ### Testing Configuration
537
-
538
- - **Framework**: pytest with asyncio auto mode
539
- - **Coverage**: Incremental ratchet system targeting 100% coverage
540
- - **Timeout**: 300 seconds per test (configurable with --test-timeout)
541
- - **Workers**: Auto-detected based on CPU count (override with --test-workers)
542
- - **Config file**: `pyproject.toml` contains pytest configuration
543
-
544
- ## Code Standards
545
-
546
- ### Clean Code Principles (Applied)
547
-
548
- Following our philosophy that **EVERY LINE OF CODE IS A LIABILITY**:
549
-
550
- - **DRY**: Extract common patterns into reusable functions/classes
551
- - **YAGNI**: Implement only current requirements, not future "what-ifs"
552
- - **KISS**: Choose simple solutions over clever ones
553
- - **Readability First**: Code should be self-explanatory
554
- - **Descriptive Names**: `user_count` not `uc`, even in map/filter functions
555
-
556
- ### Python 3.13+ Requirements
557
-
558
- - Modern type hints with `|` unions instead of `Union`
559
- - Protocol-based interfaces in `models/protocols.py`
560
- - Pathlib over os.path
561
- - `import typing as t` convention
562
- - Pydantic BaseModel for configuration with validation
563
-
564
- ### Quality Rules (Enforced by Tools)
565
-
566
- - **Cognitive complexity ≤15** per function (Complexipy) - KISS principle in action
567
- - **No hardcoded temp paths** (Security: Bandit B108) - use `tempfile` module
568
- - **UV tool execution**: Always use `uv run` for external tools
569
- - **No shell=True** in subprocess calls
570
- - **Type annotations required**: All functions must have return type hints
571
- - **Protocol compliance**: Use protocols for dependency injection interfaces
572
- - **TODO detection**: Code cleaning (`-x`) requires resolving all TODO comments first
573
-
574
- ### Refactoring Patterns for Complexity Reduction
575
-
576
- ```python
577
- # GOOD: Break complex methods into smaller helper methods
578
- def complex_method(self, data: dict) -> bool:
579
- if not self._validate_input(data):
580
- return self._handle_invalid_input()
581
-
582
- processed = self._process_data(data)
583
- return self._save_results(processed)
584
-
585
-
586
- def _validate_input(self, data: dict) -> bool:
587
- # Single responsibility validation logic
588
- pass
589
-
590
-
591
- def _handle_invalid_input(self) -> bool:
592
- # Focused error handling
593
- pass
594
- ```
595
-
596
- ### Error Prevention Patterns
597
-
598
- ```python
599
- # AVOID: Hardcoded temp paths (Security issue)
600
- config_path = "/tmp/test-config.yaml" # BAD
601
-
602
- # USE: Proper temp file handling
603
- import tempfile
604
-
605
- with tempfile.NamedTemporaryFile(suffix=".yaml") as f:
606
- config_path = f.name
607
-
608
- # AVOID: try/except pass (Refurb FURB107)
609
- try:
610
- risky_operation()
611
- except Exception:
612
- pass # BAD
613
-
614
- # USE: contextlib.suppress
615
- from contextlib import suppress
616
-
617
- with suppress(Exception):
618
- risky_operation()
619
-
620
- # AVOID: Lists in membership tests (Refurb FURB109)
621
- if status in ["error", "failed", "timeout"]: # BAD
622
- handle_error()
623
-
624
- # USE: Tuples for immutable membership tests
625
- if status in ("error", "failed", "timeout"): # GOOD
626
- handle_error()
627
-
628
- # AVOID: Manual list building (FURB138)
629
- issues = []
630
- for item in data:
631
- if condition(item):
632
- issues.append(process(item))
633
-
634
- # USE: List comprehensions
635
- issues = [process(item) for item in data if condition(item)]
636
-
637
- # AVOID: Dictionary get with if/else (FURB184)
638
- emoji = AGENT_EMOJIS.get(agent_type)
639
- if emoji:
640
- return emoji
641
- return "🤖"
642
-
643
- # USE: Dictionary get with default
644
- return AGENT_EMOJIS.get(agent_type, "🤖")
645
-
646
- # AVOID: Lambda for simple attribute access (FURB118)
647
- sorted_items = sorted(items, key=lambda x: x["priority"])
648
-
649
- # USE: operator.itemgetter
650
- from operator import itemgetter
651
-
652
- sorted_items = sorted(items, key=itemgetter("priority"))
653
- ```
654
-
655
- ## Development Workflow
656
-
657
- ### Making Changes
658
-
659
- 1. **Run quality checks**: `python -m crackerjack`
660
- 1. **Run with tests**: `python -m crackerjack -t` (for comprehensive validation)
661
- 1. **Address remaining issues**: Manual fixes for any issues that tools cannot resolve
662
- 1. **Get AI code review**: When gemini-cli MCP server is connected, have Gemini review your completed work with `mcp__gemini-cli__ask-gemini` for a second opinion on code quality
663
- 1. **Commit changes**: Use `python -m crackerjack -c` for auto-commit with intelligent messages
664
-
665
- ### Testing Individual Components
666
-
667
- ```bash
668
- # Test specific manager
669
- python -m pytest tests/test_managers.py -v
670
-
671
- # Test core orchestration
672
- python -m pytest tests/test_coordinator_integration.py -v
673
-
674
- # Test MCP integration
675
- python -m pytest tests/test_mcp_server.py -v
676
-
677
- # Run failing test in isolation
678
- python -m pytest tests/test_crackerjack.py::TestClass::test_method -v -s
679
- ```
680
-
681
- ### Common Development Issues
682
-
683
- - **Import errors**: Check `models/protocols.py` for interface definitions
684
- - **Type errors**: Use `t.cast()` for complex type scenarios, ensure proper type annotations
685
- - **Complexity violations**: Break large methods into focused helper methods
686
- - **Test failures**: Check mock paths for new architecture
687
-
688
- ## MCP Server Integration
689
-
690
- **WebSocket-based MCP server with real-time progress streaming:**
691
-
692
- ### Server Features
693
-
694
- - **🌐 Dual Protocol Support**: MCP protocol tools + WebSocket server on localhost:8675
695
- - **🎨 Real-time Progress**: Live progress updates with Rich formatting
696
- - **🔄 Auto-Fallback**: Graceful fallback from WebSocket to polling
697
- - **📊 Job Tracking**: Comprehensive job progress and iteration monitoring
698
- - **🛑 Signal Handling**: Graceful shutdown with Ctrl+C support
699
-
700
- ### MCP Server Usage
701
-
702
- **For live progress monitoring with `/crackerjack:run`:**
703
-
704
- ```bash
705
- # Step 1: Start the dedicated WebSocket server (in a separate terminal)
706
- python -m crackerjack --start-websocket-server
707
-
708
- # Step 2: Use /crackerjack:run in Claude - progress will be available at:
709
- # - WebSocket: ws://localhost:8675/ws/progress/{job_id}
710
- # - Test page: http://localhost:8675/test
711
- # - Status: http://localhost:8675/
712
- ```
713
-
714
- **Alternative - Start MCP server with WebSocket support:**
715
-
716
- ```bash
717
- # Starts server on localhost:8675 with WebSocket + MCP protocol support
718
- python -m crackerjack --start-mcp-server --websocket-port 8675
719
- ```
720
-
721
- **Progress monitoring:**
722
-
723
- ```bash
724
- # Monitor specific job by ID via WebSocket
725
- python -m crackerjack.mcp.progress_monitor abc123-def456
726
-
727
- # Monitor with custom WebSocket URL
728
- python -m crackerjack.mcp.progress_monitor abc123-def456 ws://localhost:8675
729
- ```
730
-
731
- **Enhanced API integration:**
732
-
733
- ```python
734
- from crackerjack.mcp.progress_monitor import (
735
- run_crackerjack_with_enhanced_progress,
736
- )
737
-
738
- # Uses WebSocket monitoring with Rich display
739
- await run_crackerjack_with_enhanced_progress(client, "/crackerjack:run")
740
- ```
741
-
742
- ### Server Architecture
743
-
744
- - **WebSocket Server**: Runs on localhost:8675 for progress streaming
745
- - **MCP Protocol**: FastMCP-based tools for AI agent integration
746
- - **Progress Queue**: `asyncio.Queue` for real-time job updates
747
- - **Rich Components**: Formatted progress panels and status displays
748
- - **Job Management**: Background task execution with progress tracking
749
-
750
- ### Available MCP Tools
751
-
752
- - `execute_crackerjack`: Start iterative auto-fixing workflow
753
- - `get_job_progress`: Get current progress for running jobs
754
- - `get_comprehensive_status`: Get complete system status (servers, jobs, health)
755
- - `run_crackerjack_stage`: Execute specific workflow stages
756
- - `analyze_errors`: Intelligent error pattern analysis
757
- - `session_management`: Track iteration state and checkpoints
758
- - `get_stage_status`: Get workflow stage completion status
759
- - `get_server_stats`: Get MCP server resource usage and statistics
760
-
761
- ### Dependencies
762
-
763
- - `fastmcp>=2.10.6`: MCP server framework
764
- - `uvicorn>=0.32.1`: WebSocket server support
765
- - `websockets>=15.0.1`: WebSocket client connections
766
- - `fastapi>=0.116.1`: HTTP/WebSocket endpoint framework
767
- - `rich>=14`: Terminal formatting and progress displays
768
-
769
- ### Slash Commands
770
-
771
- **Location**: Available in `crackerjack.slash_commands` module for other packages to use
772
-
773
- **`/crackerjack:run`**: Run full iterative auto-fixing with AI agent, tests, progress tracking, and verbose output
774
-
775
- **`/crackerjack:status`**: Get comprehensive system status including MCP server health, WebSocket server status, active jobs, progress tracking, and resource usage
776
-
777
- **`/crackerjack:init`**: Initialize or update project configuration with intelligent smart merge (preserves existing configurations, never overwrites project identity)
778
-
779
- **Programmatic Access**:
780
-
781
- ```python
782
- from crackerjack.slash_commands import list_available_commands, get_slash_command_path
783
-
784
- # List all available commands
785
- commands = list_available_commands() # ['run', 'init']
786
-
787
- # Get path to specific command
788
- command_path = get_slash_command_path("run")
789
- command_content = command_path.read_text()
790
- ```
791
-
792
- ## Configuration Details
793
-
794
- **Tool Configuration** (from `pyproject.toml`):
795
-
796
- - **Coverage requirement**: Ratchet system - never decrease, always improve toward 100%
797
- - **Cognitive complexity**: ≤13 per function (complexipy)
798
- - **Python version**: 3.13+ required
799
- - **Test timeout**: 300 seconds per test
800
- - **Type checking**: Strict mode with Pyright
801
- - **Security scanning**: Bandit with custom exclusions
802
-
803
- ## Service Watchdog
804
-
805
- **Automatic monitoring and restart system for MCP and WebSocket servers.**
806
-
807
- ### Overview
808
-
809
- The Service Watchdog provides enterprise-grade monitoring and automatic recovery for Crackerjack's server components. It ensures continuous availability by detecting failures and restarting services automatically.
810
-
811
- ### Usage
812
-
813
- ```bash
814
- # Start watchdog to monitor both MCP and WebSocket servers
815
- python -m crackerjack --watchdog
816
- ```
817
-
818
- ### Monitored Services
819
-
820
- 1. **MCP Server** (`--start-mcp-server`)
821
-
822
- - Process monitoring (detects crashes)
823
- - No HTTP health checks (stdio-based protocol)
824
- - Auto-restart on process termination
825
-
826
- 1. **WebSocket Server** (`--start-websocket-server`)
827
-
828
- - Process monitoring (detects crashes)
829
- - HTTP health checks (`http://localhost:8675/`)
830
- - Auto-restart on process or health check failures
831
-
832
- ### Features
833
-
834
- - **Real-time Monitoring**: Continuous process and health monitoring
835
- - **Intelligent Restart**: Rate-limited restarts with exponential backoff
836
- - **Rich Dashboard**: Live status display with service health, restart counts, and errors
837
- - **Rate Limiting**: Maximum 10 restarts per 5-minute window to prevent restart loops
838
- - **Health Checks**: HTTP endpoint monitoring for WebSocket server
839
- - **Error Tracking**: Logs and displays last error for each service
840
- - **Graceful Shutdown**: Proper cleanup on Ctrl+C
841
-
842
- ### Dashboard Display
843
-
844
- The watchdog shows a real-time table with:
845
-
846
- - **Service**: Service name (MCP Server, WebSocket Server)
847
- - **Status**: ✅ Running / ❌ Stopped
848
- - **Health**: 🟢 Healthy / 🔴 Unhealthy / N/A
849
- - **Restarts**: Total restart count for the session
850
- - **Last Error**: Most recent error message (truncated)
851
-
852
- ### Configuration
853
-
854
- Default configuration monitors:
855
-
856
- - **Health Check Interval**: 30 seconds
857
- - **Restart Delay**: 5 seconds between restart attempts
858
- - **Max Restarts**: 10 per 5-minute window
859
- - **Health Timeout**: 10 seconds for HTTP checks
860
-
861
- ### Use Cases
862
-
863
- - **Development**: Automatic recovery during active development sessions
864
- - **CI/CD**: Ensure services stay running during automated testing
865
- - **Production**: High-availability deployment with automatic failover
866
- - **Debugging**: Monitor service stability and identify recurring issues
867
-
868
- ### Dependencies
869
-
870
- - `aiohttp`: HTTP health check client
871
- - `rich`: Dashboard display and formatting
872
- - `asyncio`: Concurrent monitoring and restart management
873
-
874
- ## Architecture Migration Notes
875
-
876
- **Key changes from monolithic to modular:**
877
-
878
- - `Crackerjack` class methods → `WorkflowOrchestrator` + coordinator delegation
879
- - Direct tool execution → Manager pattern with dependency injection
880
- - Hardcoded workflows → Configurable phase execution with retry logic
881
- - Manual error handling → Automatic fixing with intelligent retry
882
-
883
- **Modular Architecture Notes:**
884
-
885
- - **Clean Architecture**: Direct use of modern class names (`InteractiveCLI`, `WorkflowManager`, `CodeCleaner`)
886
- - **Modular CLI**: Options and handlers moved to dedicated modules (`cli/options.py`, `cli/handlers.py`)
887
- - **Protocol-based Design**: Dependency injection through protocols for better testability
888
-
889
- **Refactoring Achievements (January 2025):**
890
-
891
- - **70% line reduction** in MCP server (3,116 lines → 921 lines across 6 focused modules)
892
- - **35% line reduction** in WebSocket server (1,479 lines → 944 lines across 5 modules)
893
- - **80% line reduction** in CLI entry point (601 lines → 122 lines via delegation)
894
- - **Code Quality Improvements**:
895
- - Fixed all 31+ refurb violations in agents directory (FURB107, FURB109, FURB118, FURB135, FURB138, FURB184)
896
- - Reduced complex functions from 32 to 29 total, with major reductions:
897
- - `_execute_crackerjack_sync`: complexity 34 → 3 (91% reduction)
898
- - `TestManagementImpl::run_tests`: complexity 33 → 2 (94% reduction)
899
- - All 5 fast hooks now passing consistently
900
- - **Improved maintainability** through single responsibility principle
901
- - **Better testability** with focused, isolated modules
902
- - **Enhanced security** with modular validation and error handling
903
- - **Protocol-based interfaces** for better dependency injection and testing
904
- - **Performance Improvements**: Enhanced async/await patterns, parallel execution, and caching strategies
905
- - **Plugin Architecture**: Extensible plugin system for custom hooks and workflow extensions
906
- - **Health Monitoring**: Comprehensive system health metrics and performance benchmarking
907
-
908
- ## Test Coverage Requirements
909
-
910
- **CRITICAL**: The coverage ratchet system prevents regression and targets 100% coverage.
911
-
912
- - **2% Tolerance Margin**: Coverage within 2% of baseline passes to prevent test flakiness
913
- - **Never reduce coverage below baseline - 2%** - allows small fluctuations but prevents regression
914
- - **Add tests to increase coverage** incrementally toward 100%
915
- - **Current Status**: Test coverage at 10.11% baseline, targeting 100%
916
- - Existing test files cover various modules including core components, managers, and async workflows
917
- - Focus testing on modules with 0% coverage: plugins, MCP server, enhanced filesystem, unified config
918
-
919
- ## Current Quality Status (January 2025)
920
-
921
- **✅ COMPLETED:**
922
-
923
- - All 31+ refurb violations fixed in agents directory
924
- - Fast hooks: All 5 passing consistently
925
- - Major complexity reductions (34→3, 33→2)
926
- - Import errors and protocol compliance fixed
927
- - Documentation reorganization: Security reports moved to `docs/security/`, implementation docs to `docs/`
928
-
929
- **🔄 IN PROGRESS:**
930
-
931
- - Complexipy violations: Some functions still > 15 complexity
932
- - Test coverage: Working toward 100% via incremental improvements
933
-
934
- **⚠️ CRITICAL PRIORITIES:**
935
-
936
- 1. **Fix existing test failures first** (before adding new tests)
937
- 1. Add tests strategically to reach next milestone toward 100% coverage
938
- 1. Complete remaining complexity reductions
939
- 1. Final integration and release preparation
940
-
941
- **Key User Directive**: Always prioritize fixing failures of existing tests over creating new tests, especially when coverage issues are being addressed.
942
-
943
- ### Current Test Strategy (Post-Architectural Refactoring)
944
-
945
- **Strategic Testing Approach**:
946
-
947
- - **Import-only tests**: Fast, reliable coverage for basic module loading and interface compliance
948
- - **Protocol compliance tests**: Ensure all implementations properly follow interface contracts
949
- - **Async pattern testing**: Comprehensive validation of async/await workflows without hanging tests
950
- - **Integration testing**: End-to-end validation of dependency injection and workflow orchestration
951
- - **Performance regression testing**: Automated detection of performance degradation in async workflows
952
-
953
- ## Important Instruction Reminders
954
-
955
- - Do what has been asked; nothing more, nothing less
956
- - NEVER create files unless absolutely necessary for achieving your goal
957
- - ALWAYS prefer editing an existing file to creating a new one
958
- - NEVER proactively create documentation files (\*.md) or README files unless explicitly requested
959
- - MAINTAIN coverage ratchet - never decrease coverage, always improve toward 100%
960
-
961
- ## Coding Standards Memories
962
-
963
- - Do not reduce coverage below current baseline. Instead add tests to increase coverage toward 100% target.
964
- - **Debugging Approach Memory**: Focus on test errors first then move on to failures when debugging tests
965
-
966
- ## Critical Quality Standards
967
-
968
- - **Test Quality**: Never create async tests that hang indefinitely. When testing async components like `BatchedStateSaver`, prefer simple synchronous tests that verify configuration and basic state rather than complex async workflows that can cause test suite timeouts.
969
- - **Honest Progress Reporting**: Always report actual coverage percentages and test results accurately. If coverage is 10.17%, report it as 10.17%, not "approaching 15%" or other optimistic estimates.
970
- - **Import Error Prevention**: Common import error pattern: `TestManager` vs `TestManagerProtocol` in `async_workflow_orchestrator.py`. Always use protocol interfaces from `models/protocols.py`.
971
-
972
- ## Development Standards
973
-
974
- - be honest when describing the things you have accomplished. if tasks have not been completed to their full extent we need to know so sugarcoating your accomplishments for your, and especially our, benefit helps nobody.
975
-
976
- - be very critical and comprehensive when performing code or documentation reviews/audits. pride ourselves on our attention to detail and take the time to do things right the first time. always still assume failure on the first try, when making edits, so our work is double checked and bulletproof.
977
-
978
- ## Common Failure Patterns to Avoid
979
-
980
- ### Async Test Hangs
981
-
982
- ```python
983
- # AVOID: Complex async tests that can hang
984
- @pytest.mark.asyncio
985
- async def test_batch_processing(self, batched_saver):
986
- await batched_saver.start()
987
- # Complex async workflow that might hang
988
-
989
-
990
- # PREFER: Simple synchronous config tests
991
- def test_batch_configuration(self, batched_saver):
992
- assert batched_saver.max_batch_size == expected_size
993
- assert not batched_saver._running
994
- ```
995
-
996
- ### Import Error Prevention
997
-
998
- ```python
999
- # WRONG: Importing concrete classes instead of protocols
1000
- from ..managers.test_manager import TestManager
1001
-
1002
- # CORRECT: Use protocol interfaces for dependency injection
1003
- from ..models.protocols import TestManagerProtocol
1004
- ```
1005
-
1006
- - DO NOT CREATE ANY NEW TESTS UNTIL CURRENTLY FAILING OR ERRORING TESTS HAVE EITHER BEEN FIXED OR REMOVED!
1007
- - always be honest with your answers. do not embelish on progress.
1008
- - always clean up after yourself
1009
- - Always use IDE diagnostics to validate code after implementation if available
1010
- - Always use IDE diagnostics to validate code after implementation if available
1011
- - Always use IDE diagnostics to validate code after implementation if available