Skip to content

Commit 939e711

Browse files
committed
I've analyzed the code changes and found several type annotation issues and potential bugs that need to be fixed. Here's my commit:
Fixed type annotations and potential bugs throughout codeflow_engine This commit addresses multiple type annotation issues and potential bugs: 1. Added proper type annotations for functions and variables 2. Fixed imports to use proper aliases for renamed classes 3. Fixed potential None reference issues with proper null checks 4. Improved error handling in several functions 5. Fixed comparison operations to check for compatible types 6. Made Redis storage more robust with better error handling 7. Fixed workflow condition evaluation to handle type mismatches safely 8. Added proper return types for functions that were missing them The changes maintain backward compatibility while improving type safety and reducing the potential for runtime errors.
1 parent 67c9828 commit 939e711

37 files changed

Lines changed: 806 additions & 557 deletions

engine/codeflow_engine/actions/__init__.py

Lines changed: 19 additions & 62 deletions
Original file line numberDiff line numberDiff line change
@@ -13,70 +13,31 @@
1313
- maintenance: Maintenance tasks
1414
"""
1515

16+
import importlib
17+
from types import ModuleType
1618
from typing import Any
1719

1820
from codeflow_engine.actions.registry import ActionRegistry
1921

20-
# Import category modules with error handling for optional dependencies
21-
ai_actions = None
22-
try:
23-
from codeflow_engine.actions import ai_actions
24-
except (ImportError, OSError):
25-
pass
26-
27-
analysis = None
28-
try:
29-
from codeflow_engine.actions import analysis
30-
except (ImportError, OSError):
31-
pass
32-
33-
base = None
34-
try:
35-
from codeflow_engine.actions import base
36-
except (ImportError, OSError):
37-
pass
38-
39-
generation = None
40-
try:
41-
from codeflow_engine.actions import generation
42-
except (ImportError, OSError):
43-
pass
4422

45-
git = None
46-
try:
47-
from codeflow_engine.actions import git
48-
except (ImportError, OSError):
49-
pass
23+
def _optional_module(module_name: str) -> ModuleType | None:
24+
try:
25+
return importlib.import_module(module_name)
26+
except (ImportError, OSError):
27+
return None
5028

51-
issues = None
52-
try:
53-
from codeflow_engine.actions import issues
54-
except (ImportError, OSError):
55-
pass
5629

57-
maintenance = None
58-
try:
59-
from codeflow_engine.actions import maintenance
60-
except (ImportError, OSError):
61-
pass
62-
63-
platform = None
64-
try:
65-
from codeflow_engine.actions import platform
66-
except (ImportError, OSError):
67-
pass
68-
69-
quality = None
70-
try:
71-
from codeflow_engine.actions import quality
72-
except (ImportError, OSError):
73-
pass
74-
75-
scripts = None
76-
try:
77-
from codeflow_engine.actions import scripts
78-
except (ImportError, OSError):
79-
pass
30+
# Import category modules with error handling for optional dependencies
31+
ai_actions: ModuleType | None = _optional_module("codeflow_engine.actions.ai_actions")
32+
analysis: ModuleType | None = _optional_module("codeflow_engine.actions.analysis")
33+
base: ModuleType | None = _optional_module("codeflow_engine.actions.base")
34+
generation: ModuleType | None = _optional_module("codeflow_engine.actions.generation")
35+
git: ModuleType | None = _optional_module("codeflow_engine.actions.git")
36+
issues: ModuleType | None = _optional_module("codeflow_engine.actions.issues")
37+
maintenance: ModuleType | None = _optional_module("codeflow_engine.actions.maintenance")
38+
platform: ModuleType | None = _optional_module("codeflow_engine.actions.platform")
39+
quality: ModuleType | None = _optional_module("codeflow_engine.actions.quality")
40+
scripts: ModuleType | None = _optional_module("codeflow_engine.actions.scripts")
8041

8142
# Re-export commonly used actions for backward compatibility
8243
# Analysis
@@ -187,11 +148,7 @@
187148
pass
188149

189150
# Create llm alias for backward compatibility (codeflow_engine.actions.llm)
190-
llm = None
191-
try:
192-
from codeflow_engine.actions.ai_actions import llm
193-
except ImportError:
194-
pass
151+
llm: ModuleType | None = _optional_module("codeflow_engine.actions.ai_actions.llm")
195152

196153
# Platform
197154
PlatformDetector: type[Any] | None = None

engine/codeflow_engine/actions/ai_actions/__init__.py

Lines changed: 7 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,14 @@
22

33
from codeflow_engine.actions.autogen_implementation import AutoGenImplementation
44
from codeflow_engine.actions.autogen_multi_agent import AutoGenAgentSystem
5-
from codeflow_engine.actions.configurable_llm_provider import ConfigurableLLMProvider
5+
from codeflow_engine.actions.configurable_llm_provider import (
6+
LLMProviderManager as ConfigurableLLMProvider,
7+
)
68
from codeflow_engine.actions.learning_memory_system import LearningMemorySystem
79
from codeflow_engine.actions.mem0_memory_integration import Mem0MemoryManager
8-
from codeflow_engine.actions.summarize_pr_with_ai import SummarizePRWithAI
10+
from codeflow_engine.actions.summarize_pr_with_ai import (
11+
SummarizePrWithAI as SummarizePRWithAI,
12+
)
913

1014
from . import autogen, llm
1115

@@ -18,4 +22,4 @@
1822
"SummarizePRWithAI",
1923
"autogen",
2024
"llm",
21-
]
25+
]

engine/codeflow_engine/actions/ai_linting_fixer/ai_fix_applier.py

Lines changed: 12 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -8,15 +8,17 @@
88
from typing import Any
99

1010
from codeflow_engine.actions.ai_linting_fixer.backup_manager import BackupManager
11-
from codeflow_engine.actions.ai_linting_fixer.file_persistence import \
12-
FilePersistenceManager
11+
from codeflow_engine.actions.ai_linting_fixer.file_persistence import (
12+
FilePersistenceManager,
13+
)
1314
from codeflow_engine.actions.ai_linting_fixer.fix_strategy import StrategySelector
1415
from codeflow_engine.actions.ai_linting_fixer.llm_client import LLMClient
15-
from codeflow_engine.actions.ai_linting_fixer.models import (LintingIssue)
16+
from codeflow_engine.actions.ai_linting_fixer.models import LintingIssue
1617
from codeflow_engine.actions.ai_linting_fixer.response_parser import ResponseParser
1718
from codeflow_engine.actions.ai_linting_fixer.validation_manager import (
18-
ValidationConfig, ValidationManager)
19-
from codeflow_engine.ai.core.providers.manager import LLMProviderManager
19+
ValidationConfig,
20+
ValidationManager,
21+
)
2022

2123
logger = logging.getLogger(__name__)
2224

@@ -26,7 +28,7 @@ class AIFixApplier:
2628

2729
def __init__(
2830
self,
29-
llm_manager: LLMProviderManager,
31+
llm_manager: Any,
3032
backup_manager: BackupManager | None = None,
3133
validation_config: ValidationConfig | None = None,
3234
):
@@ -51,7 +53,9 @@ def __init__(
5153
self.llm_client = LLMClient(llm_manager)
5254
self.response_parser = ResponseParser()
5355
self.persistence_manager = FilePersistenceManager(backup_manager)
54-
self.validation_manager = ValidationManager(validation_config or ValidationConfig())
56+
self.validation_manager = ValidationManager(
57+
validation_config or ValidationConfig()
58+
)
5559

5660
# Initialize strategy selector
5761
self.strategy_selector = StrategySelector(
@@ -61,7 +65,7 @@ def __init__(
6165
self.validation_manager,
6266
)
6367

64-
self.session_id = None
68+
self.session_id: str | None = None
6569

6670
async def apply_specialist_fix_with_validation(
6771
self,

engine/codeflow_engine/actions/ai_linting_fixer/code_analyzer.py

Lines changed: 9 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -6,6 +6,7 @@
66

77
import ast
88
import logging
9+
from typing import Any
910

1011

1112
try:
@@ -156,7 +157,7 @@ def count_lines_of_code(self, content: str) -> dict[str, int]:
156157
docstring_lines = 0
157158

158159
in_docstring = False
159-
docstring_quotes = None
160+
docstring_quotes: str | None = None
160161

161162
for line in lines:
162163
stripped = line.strip()
@@ -175,7 +176,7 @@ def count_lines_of_code(self, content: str) -> dict[str, int]:
175176
docstring_lines += 1
176177
else:
177178
# End of docstring
178-
if docstring_quotes in stripped:
179+
if docstring_quotes and docstring_quotes in stripped:
179180
in_docstring = False
180181
docstring_quotes = None
181182
docstring_lines += 1
@@ -223,7 +224,7 @@ def get_cpu_usage(self) -> float:
223224
logger.debug(f"Error getting CPU usage: {e}")
224225
return 0.0
225226

226-
def analyze_function_complexity(self, content: str) -> list[dict[str, any]]:
227+
def analyze_function_complexity(self, content: str) -> list[dict[str, Any]]:
227228
"""Analyze complexity of individual functions."""
228229
try:
229230
tree = ast.parse(content)
@@ -245,7 +246,9 @@ def analyze_function_complexity(self, content: str) -> list[dict[str, any]]:
245246
logger.debug(f"Error analyzing function complexity: {e}")
246247
return []
247248

248-
def _calculate_function_complexity(self, node: ast.FunctionDef) -> int:
249+
def _calculate_function_complexity(
250+
self, node: ast.FunctionDef | ast.AsyncFunctionDef
251+
) -> int:
249252
"""Calculate cyclomatic complexity of a function."""
250253
complexity = 1 # Base complexity
251254

@@ -266,7 +269,7 @@ def _calculate_function_complexity(self, node: ast.FunctionDef) -> int:
266269

267270
return complexity
268271

269-
def detect_code_smells(self, content: str) -> list[dict[str, any]]:
272+
def detect_code_smells(self, content: str) -> list[dict[str, Any]]:
270273
"""Detect common code smells and anti-patterns."""
271274
smells = []
272275

@@ -313,7 +316,7 @@ def detect_code_smells(self, content: str) -> list[dict[str, any]]:
313316

314317
return smells
315318

316-
def get_code_metrics(self, content: str) -> dict[str, any]:
319+
def get_code_metrics(self, content: str) -> dict[str, Any]:
317320
"""Get comprehensive code metrics."""
318321
return {
319322
"complexity": self.calculate_file_complexity(content),

engine/codeflow_engine/actions/ai_linting_fixer/core.py

Lines changed: 22 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,10 @@
1212
from codeflow_engine.actions.ai_linting_fixer.database import AIInteractionDB
1313
from codeflow_engine.actions.ai_linting_fixer.metrics import MetricsCollector
1414
from codeflow_engine.actions.ai_linting_fixer.queue_manager import IssueQueueManager
15-
from codeflow_engine.actions.ai_linting_fixer.workflow import (WorkflowContext,
16-
WorkflowIntegrationMixin)
17-
from codeflow_engine.ai.core.providers.manager import LLMProviderManager
15+
from codeflow_engine.actions.ai_linting_fixer.workflow import (
16+
WorkflowContext,
17+
WorkflowIntegrationMixin,
18+
)
1819

1920
logger = logging.getLogger(__name__)
2021

@@ -38,7 +39,7 @@ class AILintingFixer(WorkflowIntegrationMixin):
3839

3940
def __init__(
4041
self,
41-
llm_manager: LLMProviderManager | None = None,
42+
llm_manager: Any | None = None,
4243
max_workers: int = DEFAULT_MAX_WORKERS,
4344
workflow_context: WorkflowContext | None = None,
4445
):
@@ -82,8 +83,11 @@ def _generate_session_id(self) -> str:
8283
"""Generate a unique session identifier."""
8384
import random
8485
import string
86+
8587
timestamp = self.metrics.session_metrics.start_time.strftime("%Y%m%d_%H%M%S")
86-
random_suffix = "".join(random.choices(string.ascii_lowercase + string.digits, k=6))
88+
random_suffix = "".join(
89+
random.choices(string.ascii_lowercase + string.digits, k=6)
90+
)
8791
return f"ai_lint_{timestamp}_{random_suffix}"
8892

8993
def queue_detected_issues(self, issues: list, quiet: bool = False) -> int:
@@ -92,7 +96,7 @@ def queue_detected_issues(self, issues: list, quiet: bool = False) -> int:
9296
return 0
9397

9498
# Ensure session_id exists
95-
if not hasattr(self, 'session_id') or not self.session_id:
99+
if not hasattr(self, "session_id") or not self.session_id:
96100
msg = "Session ID is required but not available"
97101
raise ValueError(msg)
98102

@@ -126,9 +130,7 @@ async def process_queued_issues(
126130
# Get next batch of issues
127131
batch_size = min(max_fixes - processed_count, max_fixes)
128132
issues = self.queue_manager.get_next_issues(
129-
limit=batch_size,
130-
worker_id=self.session_id,
131-
filter_types=filter_types
133+
limit=batch_size, worker_id=self.session_id, filter_types=filter_types
132134
)
133135

134136
if not issues:
@@ -157,14 +159,16 @@ async def process_queued_issues(
157159
self.queue_manager.update_issue_status(
158160
issue_id=int(issue_id),
159161
status=status,
160-
fix_result=fix_result.get("details", {})
162+
fix_result=fix_result.get("details", {}),
161163
)
162164

163165
results["processed"] += 1
164166
processed_count += 1
165167
except Exception as e:
166168
if not quiet:
167-
logger.exception("Error processing issue %s", issue.get('id', 'unknown'))
169+
logger.exception(
170+
"Error processing issue %s", issue.get("id", "unknown")
171+
)
168172
results["failed"] += 1
169173
results["processed"] += 1
170174
processed_count += 1
@@ -175,7 +179,7 @@ async def process_queued_issues(
175179
self.queue_manager.update_issue_status(
176180
issue_id=int(issue_id),
177181
status="failed",
178-
fix_result={"error": str(e)}
182+
fix_result={"error": str(e)},
179183
)
180184

181185
# Update stats
@@ -204,15 +208,12 @@ async def _attempt_issue_fix(self, issue: dict[str, Any]) -> dict[str, Any]:
204208
"line_number": line_number,
205209
"error_code": error_code,
206210
"message": message,
207-
"fix_applied": f"Applied fix for {error_code}"
208-
}
211+
"fix_applied": f"Applied fix for {error_code}",
212+
},
209213
}
210214
except Exception as e:
211215
logger.exception("Error in _attempt_issue_fix")
212-
return {
213-
"success": False,
214-
"details": {"error": str(e)}
215-
}
216+
return {"success": False, "details": {"error": str(e)}}
216217
else:
217218
return fix_result
218219

@@ -223,7 +224,9 @@ def get_session_results(self) -> dict[str, Any]:
223224

224225
# Calculate success rate
225226
total_issues = self.stats["issues_processed"]
226-
success_rate = 0.0 if total_issues == 0 else self.stats["issues_fixed"] / total_issues
227+
success_rate = (
228+
0.0 if total_issues == 0 else self.stats["issues_fixed"] / total_issues
229+
)
227230

228231
return {
229232
"session_id": self.session_id,

0 commit comments

Comments
 (0)