Files
Aperant/tests/test_critique_integration.py
53111dbb95 auto-claude: 147-remove-outdated-compatibility-shims (#1465)
* auto-claude: subtask-1-1 - Remove validation_strategy backward compatibility shim

- Delete apps/backend/validation_strategy.py shim file that re-exported from spec.validation_strategy
- Update docstring in spec/validation_strategy.py to show correct import path

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* auto-claude: subtask-1-2 - Remove service_orchestrator shim

- Deleted apps/backend/service_orchestrator.py backward compatibility shim file
- Updated docstring in services/orchestrator.py to use correct import path
  (from services.orchestrator import instead of from service_orchestrator import)
- Verified no external imports of the shim remain in the codebase
- Import from services.orchestrator works correctly

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* auto-claude: subtask-2-1 - Remove Chunk/ChunkStatus aliases from implementation_plan

Removed backwards compatibility aliases as part of cleaning up outdated
compatibility shims:

- Removed ChunkStatus = SubtaskStatus from enums.py
- Removed Chunk = Subtask from subtask.py
- Removed Chunk/ChunkStatus exports from __init__.py
- Updated all test files to use canonical names (Subtask, SubtaskStatus)

This completes subtasks 2-1, 2-2, and 2-3 together since the test files
depend on all three changes being made atomically.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* auto-claude: subtask-2-4 - Remove deprecated use_orchestrator_review field from GitHub runner models

* auto-claude: subtask-3-1 - Update apps/frontend/src/main/index.ts to use platform imports

* auto-claude: subtask-3-2 - Update python-detector.ts to use platform imports

- Import isWindows from ./platform module
- Replace all process.platform === 'win32' checks with isWindows() calls
- Remove redundant local isWindows variable declarations

* auto-claude: subtask-3-3 - Update apps/frontend/src/main/claude-cli-utils.ts to use platform imports

* auto-claude: subtask-3-4 - Update apps/frontend/src/main/config-paths.ts to use platform imports

* auto-claude: subtask-3-5 - Update apps/frontend/src/main/memory-service.ts to use platform imports

* auto-claude: subtask-4-1 - Update claude-code-handlers.ts to use platform imports

Replace all direct process.platform checks with centralized platform
abstraction functions from ../platform module:
- isWindows() for Windows platform checks
- isMacOS() for macOS/Darwin platform checks
- isLinux() for Linux platform checks

This removes 6 instances of process.platform === '...' comparisons and
1 local isWindows variable assignment, replacing them with the platform
abstraction layer for better cross-platform consistency.

* auto-claude: subtask-4-2 - Update apps/frontend/src/main/ipc-handlers/mcp-handlers.ts to use platform imports

* auto-claude: subtask-4-3 - Update apps/frontend/src/main/ipc-handlers/memory-handlers.ts to use platform imports

- Replace process.platform checks with platform module functions
- Add getOllamaExecutablePaths(), getOllamaInstallCommand(), and getWhichCommand() to platform/paths.ts
- Export new functions from platform/index.ts
- Migrate checkOllamaInstalled() to use platform module for path resolution
- Migrate getOllamaInstallCommand() to delegate to platform module
- Update debug log to use getCurrentOS() instead of process.platform

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* auto-claude: subtask-4-4 - Update apps/frontend/src/main/ipc-handlers/termina

* auto-claude: subtask-4-5 - Update apps/frontend/src/main/ipc-handlers/github/

- Replace direct process.platform check with getWhichCommand() from platform abstraction
- Import getWhichCommand from ../../platform for cross-platform which/where command

* auto-claude: subtask-4-6 - Update apps/frontend/src/main/ipc-handlers/github/utils/subprocess-runner.ts to use platform imports

* auto-claude: subtask-5-1 - Update apps/frontend/src/main/agent/agent-process.ts

Replace direct process.platform checks with platform abstraction:
- Import isWindows from ../platform module
- Replace `process.platform !== 'win32'` with `!isWindows()`
- Replace `process.platform === 'win32'` with `isWindows()`

This ensures consistent platform detection using the centralized
platform abstraction layer.

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* auto-claude: subtask-5-2 - Update apps/frontend/src/main/agent/agent-queue.ts

* auto-claude: subtask-5-3 - Update apps/frontend/src/main/terminal/pty-daemon.ts to use platform imports

* auto-claude: subtask-5-4 - Update pty-daemon-client.ts to use platform imports

Replace direct process.platform === 'win32' check with isWindows()
from the platform abstraction layer for consistent cross-platform
handling of socket paths.

* auto-claude: subtask-5-5 - Update apps/frontend/src/main/insights/config.ts to use platform imports

- Import isWindows() from '../platform'
- Replace process.platform === 'win32' checks with isWindows()
- Maintains case-insensitive path comparison on Windows

* auto-claude: subtask-5-6 - Update apps/frontend/src/main/changelog/version-suggester.ts to use platform imports

* auto-claude: subtask-5-7 - Update apps/frontend/src/main/changelog/generator.

* fix: Remove unused import and fix test import paths

- Remove unused `isWindows` import from memory-handlers.ts
- Fix test_service_orchestrator.py to import from services.orchestrator
  instead of the removed service_orchestrator shim
- Fix case sensitivity in path ("Apps" -> "apps")

Co-Authored-By: Claude Opus 4.5 <[email protected]>

* fix: Fix test import paths for case sensitivity and removed shims

- Fix path case sensitivity: "Apps" -> "apps" in 21 test files
- Update test_validation_strategy.py to import from spec.validation_strategy

Co-Authored-By: Claude Opus 4.5 <[email protected]>

---------

Co-authored-by: Claude Opus 4.5 <[email protected]>
2026-01-25 12:31:06 +01:00

305 lines
8.2 KiB
Python

#!/usr/bin/env python3
"""
Test script for Self-Critique System Integration
Verifies that:
1. Critique module works correctly
2. Implementation plan supports critique_result field
3. Complete workflow integration functions properly
"""
import json
import sys
from pathlib import Path
# Add auto-claude directory to path for imports
sys.path.insert(0, str(Path(__file__).parent.parent / "apps" / "backend"))
from critique import (
generate_critique_prompt,
parse_critique_response,
should_proceed,
format_critique_summary,
CritiqueResult,
)
from implementation_plan import Subtask, SubtaskStatus, Verification, VerificationType
def test_critique_data_structures():
"""Test CritiqueResult data structure."""
print("Testing CritiqueResult data structure...")
result = CritiqueResult(
passes=True,
issues=["Issue 1", "Issue 2"],
improvements_made=["Fixed issue 1", "Fixed issue 2"],
recommendations=["Consider adding tests"],
)
# Test to_dict
data = result.to_dict()
assert data["passes"] == True
assert len(data["issues"]) == 2
assert len(data["improvements_made"]) == 2
# Test from_dict
result2 = CritiqueResult.from_dict(data)
assert result2.passes == result.passes
assert result2.issues == result.issues
print("✓ CritiqueResult data structure works correctly")
def test_critique_prompt_generation():
"""Test critique prompt generation."""
print("\nTesting critique prompt generation...")
chunk = {
"id": "test-chunk",
"description": "Add authentication middleware",
"service": "backend",
"files_to_modify": ["app/middleware/auth.py"],
"files_to_create": ["app/tests/test_auth.py"],
"patterns_from": ["app/middleware/cors.py"],
}
files_modified = ["app/middleware/auth.py", "app/tests/test_auth.py"]
prompt = generate_critique_prompt(chunk, files_modified, chunk["patterns_from"])
# Verify prompt contains key elements
assert "test-chunk" in prompt
assert "Add authentication middleware" in prompt
assert "app/middleware/auth.py" in prompt
assert "STEP 1: Code Quality Checklist" in prompt
assert "STEP 5: Final Verdict" in prompt
print("✓ Critique prompt generation works correctly")
def test_critique_response_parsing():
"""Test parsing of critique responses."""
print("\nTesting critique response parsing...")
# Test successful critique
response_pass = """
### STEP 3: Potential Issues Analysis
1. None identified
### STEP 4: Improvements Made
1. Added error handling for edge cases
2. Improved code documentation
### STEP 5: Final Verdict
**PROCEED:** YES
**REASON:** All checks passed, ready for verification
**CONFIDENCE:** High
"""
result = parse_critique_response(response_pass)
assert result.passes == True
assert len(result.improvements_made) == 2
# Test failed critique
response_fail = """
### STEP 3: Potential Issues Analysis
1. Missing error handling in auth flow
2. No input validation for tokens
### STEP 4: Improvements Made
1. No fixes needed
### STEP 5: Final Verdict
**PROCEED:** NO
**REASON:** Critical issues need to be addressed
**CONFIDENCE:** Medium
"""
result2 = parse_critique_response(response_fail)
assert result2.passes == False
assert len(result2.issues) == 2
assert not should_proceed(result2)
print("✓ Critique response parsing works correctly")
def test_implementation_plan_integration():
"""Test integration with implementation_plan.py Subtask class."""
print("\nTesting implementation plan integration...")
# Create a chunk with critique result
chunk = Subtask(
id="test-chunk",
description="Test chunk with critique",
status=SubtaskStatus.PENDING,
service="backend",
files_to_modify=["app/test.py"],
)
# Add critique result
critique_data = {
"passes": True,
"issues": [],
"improvements_made": ["Fixed error handling"],
"recommendations": [],
}
chunk.critique_result = critique_data
# Test serialization
chunk_dict = chunk.to_dict()
assert "critique_result" in chunk_dict
assert chunk_dict["critique_result"]["passes"] == True
# Test deserialization
chunk2 = Subtask.from_dict(chunk_dict)
assert chunk2.critique_result is not None
assert chunk2.critique_result["passes"] == True
assert len(chunk2.critique_result["improvements_made"]) == 1
print("✓ Implementation plan integration works correctly")
def test_complete_workflow():
"""Test complete critique workflow."""
print("\nTesting complete workflow...")
# 1. Create chunk
chunk = {
"id": "workflow-test",
"description": "Test complete workflow",
"service": "backend",
"files_to_modify": ["app/workflow.py"],
"patterns_from": ["app/example.py"],
}
# 2. Generate critique prompt
prompt = generate_critique_prompt(chunk, ["app/workflow.py"], chunk["patterns_from"])
assert len(prompt) > 0
# 3. Simulate agent response
agent_response = """
### STEP 3: Potential Issues Analysis
1. None identified
### STEP 4: Improvements Made
1. Added comprehensive error handling
2. Updated imports to match pattern files
3. Added documentation comments
### STEP 5: Final Verdict
**PROCEED:** YES
**REASON:** All quality checks passed
**CONFIDENCE:** High
"""
# 4. Parse response
result = parse_critique_response(agent_response)
# 5. Check if should proceed
can_proceed = should_proceed(result)
assert can_proceed == True
# 6. Format summary
summary = format_critique_summary(result)
assert "PASSED ✓" in summary
assert "Subtask is ready to be marked complete" in summary
# 7. Store in chunk
chunk_obj = Subtask(
id=chunk["id"],
description=chunk["description"],
service=chunk["service"],
files_to_modify=chunk["files_to_modify"],
critique_result=result.to_dict(),
)
# 8. Verify storage
assert chunk_obj.critique_result is not None
assert chunk_obj.critique_result["passes"] == True
print("✓ Complete workflow works correctly")
def test_summary_formatting():
"""Test critique summary formatting."""
print("\nTesting summary formatting...")
result = CritiqueResult(
passes=True,
issues=[],
improvements_made=["Fixed error handling", "Updated tests"],
recommendations=["Consider adding more edge case tests"],
)
summary = format_critique_summary(result)
assert "PASSED ✓" in summary
assert "Fixed error handling" in summary
assert "Subtask is ready to be marked complete" in summary
# Test failed critique summary
result_fail = CritiqueResult(
passes=False,
issues=["Missing validation", "No error handling"],
improvements_made=[],
recommendations=["Add input validation first"],
)
summary_fail = format_critique_summary(result_fail)
assert "FAILED ✗" in summary_fail
assert "Missing validation" in summary_fail
assert "Subtask needs more work" in summary_fail
print("✓ Summary formatting works correctly")
def main():
"""Run all tests."""
print("="*70)
print("Self-Critique System Integration Tests")
print("="*70)
try:
test_critique_data_structures()
test_critique_prompt_generation()
test_critique_response_parsing()
test_implementation_plan_integration()
test_complete_workflow()
test_summary_formatting()
print("\n" + "="*70)
print("All tests passed! ✓")
print("="*70)
print("\nSelf-Critique System is ready for use.")
print("\nKey components:")
print(" - critique.py: Core critique logic")
print(" - prompts/coder.md: Updated with STEP 6.5 (mandatory critique)")
print(" - implementation_plan.py: Subtask.critique_result field added")
except AssertionError as e:
print(f"\n✗ Test failed: {e}")
return 1
except Exception as e:
print(f"\n✗ Unexpected error: {e}")
import traceback
traceback.print_exc()
return 1
return 0
if __name__ == "__main__":
exit(main())