diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index cdab9e6..b04f426 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -6,17 +6,22 @@ on: push: branches: - main + pull_request: jobs: test: runs-on: ubuntu-latest steps: - name: Checkout code - uses: actions/checkout@v2 + uses: actions/checkout@v3 + - name: Set up Python + uses: actions/setup-python@v4 + with: + python-version: "3.11" - name: Install dependencies run: | python -m pip install --upgrade pip pip install -r requirements.txt - name: Run tests run: | - pytest \ No newline at end of file + pytest tests/ src/ \ No newline at end of file diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..9075a1b --- /dev/null +++ b/.gitignore @@ -0,0 +1,8 @@ +__pycache__/ +*.py[cod] +*.pyo +.pytest_cache/ +*.egg-info/ +dist/ +build/ +.env diff --git a/requirements.txt b/requirements.txt index 55b033e..3f22697 100644 --- a/requirements.txt +++ b/requirements.txt @@ -1 +1,3 @@ -pytest \ No newline at end of file +pytest +SpeechRecognition +anthropic \ No newline at end of file diff --git a/src/claude_api.py b/src/claude_api.py new file mode 100644 index 0000000..8c80f90 --- /dev/null +++ b/src/claude_api.py @@ -0,0 +1,68 @@ +import logging +import time + +logger = logging.getLogger(__name__) + + +class ClaudeAPIError(Exception): + """Raised when Claude API calls fail.""" + + +class ClaudeAPI: + """Sends prompts to Claude API and processes generated code.""" + + DEFAULT_MODEL = "claude-3-5-sonnet-20241022" + MAX_RETRIES = 3 + RETRY_DELAY = 2 # seconds + + def __init__(self, api_key=None, model=None, client=None): + self._model = model or self.DEFAULT_MODEL + if client is not None: + self._client = client + else: + try: + import anthropic + self._client = anthropic.Anthropic(api_key=api_key) + except ImportError as e: + raise ClaudeAPIError( + "anthropic library is not installed. Run: pip install anthropic" + ) from e + + def _build_messages(self, prompt): + """Build the messages list for the Claude API.""" + return [{"role": "user", "content": prompt}] + + def generate_code(self, prompt): + """Send a prompt to Claude and return the generated code.""" + logger.info("Working on implementing: %s...", prompt[:60]) + messages = self._build_messages(prompt) + last_error = None + for attempt in range(1, self.MAX_RETRIES + 1): + try: + response = self._client.messages.create( + model=self._model, + max_tokens=4096, + messages=messages, + ) + code = response.content[0].text + logger.info("Code generation complete.") + return code + except Exception as e: + last_error = e + logger.warning( + "API call failed (attempt %d/%d): %s", attempt, self.MAX_RETRIES, e + ) + if attempt < self.MAX_RETRIES: + time.sleep(self.RETRY_DELAY) + raise ClaudeAPIError( + f"API call failed after {self.MAX_RETRIES} attempts: {last_error}" + ) from last_error + + def explain_code(self, code): + """Request a natural-language explanation of the given code.""" + prompt = ( + "Explain the following code in natural language, describing its behavior " + "like an algorithm. Be concise and conversational.\n\n" + code + ) + logger.info("Requesting code explanation...") + return self.generate_code(prompt) diff --git a/src/testing_guardrails.py b/src/testing_guardrails.py new file mode 100644 index 0000000..9ee6844 --- /dev/null +++ b/src/testing_guardrails.py @@ -0,0 +1,84 @@ +import logging +import os +import subprocess +import sys +import tempfile + +logger = logging.getLogger(__name__) + + +class TestingGuardrails: + """Validates generated code by running pytest and summarizing results conversationally.""" + + def __init__(self, python_executable=None): + self._python = python_executable or sys.executable + + def run_tests(self, test_paths=None): + """Run pytest on the given paths and return a result dict.""" + paths = test_paths or ["tests/"] + cmd = [self._python, "-m", "pytest", "--tb=short", "-q"] + paths + logger.info("Running tests: %s", " ".join(cmd)) + result = subprocess.run(cmd, capture_output=True, text=True) + return { + "returncode": result.returncode, + "stdout": result.stdout, + "stderr": result.stderr, + } + + def parse_results(self, run_result): + """Parse pytest output to extract passed/failed counts.""" + stdout = run_result.get("stdout", "") + passed = 0 + failed = 0 + for line in stdout.splitlines(): + if "passed" in line or "failed" in line: + for part in line.split(","): + part = part.strip() + try: + if "passed" in part: + passed = int(part.split()[0]) + if "failed" in part: + failed = int(part.split()[0]) + except (ValueError, IndexError): + pass + return {"passed": passed, "failed": failed} + + def summarize(self, run_result): + """Return a conversational summary of test results.""" + counts = self.parse_results(run_result) + passed = counts["passed"] + failed = counts["failed"] + total = passed + failed + if total == 0: + return "No tests were collected. Please add tests to validate the generated code." + if failed == 0: + return f"Your code passed all {passed} tests. Everything looks good!" + return ( + f"Your code passed {passed} of {total} tests. " + f"Failures may be related to edge cases like invalid input handling. " + f"Would you like to refine?" + ) + + def validate_code(self, code, test_code=None, test_paths=None): + """ + Write code to a temp directory, optionally run provided test_code against it, + then run pytest and return a conversational summary. + """ + with tempfile.TemporaryDirectory() as tmpdir: + module_path = os.path.join(tmpdir, "generated_module.py") + with open(module_path, "w") as f: + f.write(code) + + if test_code: + test_path = os.path.join(tmpdir, "test_generated.py") + with open(test_path, "w") as f: + f.write(test_code) + run_result = self.run_tests([tmpdir]) + elif test_paths: + run_result = self.run_tests(test_paths) + else: + run_result = self.run_tests([tmpdir]) + + summary = self.summarize(run_result) + logger.info(summary) + return summary diff --git a/src/voice_parser.py b/src/voice_parser.py index 61638e5..93bf84b 100644 --- a/src/voice_parser.py +++ b/src/voice_parser.py @@ -1,13 +1,69 @@ +import logging +import re + +logger = logging.getLogger(__name__) + + +class VoiceParserError(Exception): + """Raised when voice parsing fails.""" + + class VoiceParser: - def __init__(self): - pass + """Converts voice input to text using the SpeechRecognition library.""" + + def __init__(self, recognizer=None): + try: + import speech_recognition as sr + self._sr = sr + self._recognizer = recognizer or sr.Recognizer() + except ImportError: + self._sr = None + self._recognizer = recognizer + logger.warning("speech_recognition library not available.") + + def listen(self): + """Capture audio from the microphone and return an AudioData object.""" + if self._sr is None: + raise VoiceParserError("speech_recognition library is not installed.") + logger.info("Listening...") + try: + with self._sr.Microphone() as source: + self._recognizer.adjust_for_ambient_noise(source, duration=0.5) + audio = self._recognizer.listen(source) + return audio + except self._sr.WaitTimeoutError as e: + raise VoiceParserError("No speech detected within the timeout period.") from e + except Exception as e: + raise VoiceParserError(f"Error capturing audio: {e}") from e + + def transcribe(self, audio): + """Convert AudioData to text using Google Speech Recognition.""" + if self._sr is None: + raise VoiceParserError("speech_recognition library is not installed.") + logger.info("Processing speech to text...") + try: + text = self._recognizer.recognize_google(audio) + logger.info("Transcribed: %s", text) + return text + except self._sr.UnknownValueError as e: + raise VoiceParserError("Speech was unintelligible.") from e + except self._sr.RequestError as e: + raise VoiceParserError(f"Speech recognition service error: {e}") from e + + def sanitize(self, text): + """Validate and sanitize transcribed text.""" + if not text or not text.strip(): + raise VoiceParserError("Transcribed text is empty.") + return re.sub(r"\s+", " ", text.strip()) def speech_to_text(self): - # Pseudo-code for speech-to-text using macOS APIs - converted_text = "" # Imagine this is where we process and get the speech input - print(converted_text) + """Full pipeline: listen -> transcribe -> sanitize -> return text.""" + audio = self.listen() + raw_text = self.transcribe(audio) + return self.sanitize(raw_text) + # Example usage -if __name__ == '__main__': +if __name__ == "__main__": parser = VoiceParser() - parser.speech_to_text() \ No newline at end of file + print(parser.speech_to_text()) \ No newline at end of file diff --git a/src/vscode_integration.py b/src/vscode_integration.py new file mode 100644 index 0000000..a4cbaa5 --- /dev/null +++ b/src/vscode_integration.py @@ -0,0 +1,35 @@ +import logging +import os +import subprocess + +logger = logging.getLogger(__name__) + + +class VSCodeIntegration: + """Hooks for opening files in VSCode and displaying Claude-generated code.""" + + def open_file(self, file_path): + """Open a file in VSCode for optional manual inspection.""" + abs_path = os.path.abspath(file_path) + if not os.path.exists(abs_path): + logger.error("File not found: %s", abs_path) + return False + logger.info("Opening %s in VSCode...", abs_path) + try: + subprocess.run(["code", abs_path], check=True) + return True + except FileNotFoundError: + logger.warning( + "VSCode 'code' command not found. Is VSCode installed and in PATH?" + ) + return False + except subprocess.CalledProcessError as e: + logger.error("Failed to open file in VSCode: %s", e) + return False + + def display_code(self, code, label="Generated Code"): + """Log code line-by-line for interactive inspection.""" + logger.info("--- %s ---", label) + for i, line in enumerate(code.splitlines(), start=1): + logger.info("%4d: %s", i, line) + logger.info("--- End of %s ---", label) diff --git a/tests/conftest.py b/tests/conftest.py new file mode 100644 index 0000000..d956842 --- /dev/null +++ b/tests/conftest.py @@ -0,0 +1,4 @@ +import os +import sys + +sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "src")) diff --git a/tests/test_claude_api.py b/tests/test_claude_api.py new file mode 100644 index 0000000..779599c --- /dev/null +++ b/tests/test_claude_api.py @@ -0,0 +1,58 @@ +import pytest +from unittest.mock import MagicMock, patch + +from claude_api import ClaudeAPI, ClaudeAPIError + + +def _make_api(response_text="def fib(n): pass"): + mock_client = MagicMock() + mock_response = MagicMock() + mock_response.content = [MagicMock(text=response_text)] + mock_client.messages.create.return_value = mock_response + return ClaudeAPI(client=mock_client), mock_client + + +class TestClaudeAPIGenerateCode: + def test_generate_code_returns_text(self): + api, _ = _make_api("def fib(n): return n") + assert api.generate_code("Write a fibonacci function") == "def fib(n): return n" + + def test_generate_code_builds_correct_messages(self): + api, mock_client = _make_api() + api.generate_code("Write a fibonacci function") + call_kwargs = mock_client.messages.create.call_args[1] + assert call_kwargs["messages"][0]["role"] == "user" + assert "fibonacci" in call_kwargs["messages"][0]["content"].lower() + + def test_generate_code_retries_on_transient_failure(self): + mock_client = MagicMock() + mock_response = MagicMock() + mock_response.content = [MagicMock(text="code")] + mock_client.messages.create.side_effect = [Exception("transient"), mock_response] + api = ClaudeAPI(client=mock_client) + with patch("claude_api.time.sleep"): + result = api.generate_code("prompt") + assert result == "code" + assert mock_client.messages.create.call_count == 2 + + def test_generate_code_raises_after_max_retries(self): + mock_client = MagicMock() + mock_client.messages.create.side_effect = Exception("persistent error") + api = ClaudeAPI(client=mock_client) + with patch("claude_api.time.sleep"): + with pytest.raises(ClaudeAPIError): + api.generate_code("prompt") + + +class TestClaudeAPIExplainCode: + def test_explain_code_returns_explanation(self): + api, _ = _make_api("This function calculates fibonacci.") + result = api.explain_code("def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2)") + assert result == "This function calculates fibonacci." + + def test_explain_code_includes_code_in_prompt(self): + api, mock_client = _make_api("explanation") + code = "def fib(n): return n if n <= 1 else fib(n-1) + fib(n-2)" + api.explain_code(code) + call_kwargs = mock_client.messages.create.call_args[1] + assert code in call_kwargs["messages"][0]["content"] diff --git a/tests/test_testing_guardrails.py b/tests/test_testing_guardrails.py new file mode 100644 index 0000000..86df0de --- /dev/null +++ b/tests/test_testing_guardrails.py @@ -0,0 +1,66 @@ +import pytest + +from testing_guardrails import TestingGuardrails + + +class TestParseResults: + def test_parse_all_passed(self): + guardrails = TestingGuardrails() + result = guardrails.parse_results({"stdout": "5 passed in 0.12s"}) + assert result == {"passed": 5, "failed": 0} + + def test_parse_mixed_results(self): + guardrails = TestingGuardrails() + result = guardrails.parse_results({"stdout": "3 passed, 2 failed in 0.5s"}) + assert result == {"passed": 3, "failed": 2} + + def test_parse_empty_output(self): + guardrails = TestingGuardrails() + result = guardrails.parse_results({"stdout": ""}) + assert result == {"passed": 0, "failed": 0} + + +class TestSummarize: + def test_summarize_all_passed(self): + guardrails = TestingGuardrails() + summary = guardrails.summarize({"stdout": "5 passed in 0.12s"}) + assert "passed all 5 tests" in summary + + def test_summarize_mixed_results(self): + guardrails = TestingGuardrails() + summary = guardrails.summarize({"stdout": "3 passed, 2 failed in 0.5s"}) + assert "3 of 5" in summary + assert "refine" in summary.lower() + + def test_summarize_no_tests(self): + guardrails = TestingGuardrails() + summary = guardrails.summarize({"stdout": ""}) + assert "No tests were collected" in summary + + +class TestValidateCode: + def test_validate_code_with_passing_test(self): + guardrails = TestingGuardrails() + code = "def add(a, b):\n return a + b\n" + test_code = ( + "import sys, os\n" + "sys.path.insert(0, os.path.dirname(__file__))\n" + "from generated_module import add\n" + "def test_add():\n" + " assert add(1, 2) == 3\n" + ) + summary = guardrails.validate_code(code, test_code=test_code) + assert "passed" in summary.lower() + + def test_validate_code_with_failing_test(self): + guardrails = TestingGuardrails() + code = "def add(a, b):\n return a - b\n" # intentionally wrong + test_code = ( + "import sys, os\n" + "sys.path.insert(0, os.path.dirname(__file__))\n" + "from generated_module import add\n" + "def test_add():\n" + " assert add(1, 2) == 3\n" + ) + summary = guardrails.validate_code(code, test_code=test_code) + assert "refine" in summary.lower() or "no tests were collected" in summary.lower() diff --git a/tests/test_voice_parser.py b/tests/test_voice_parser.py new file mode 100644 index 0000000..0b6c0c9 --- /dev/null +++ b/tests/test_voice_parser.py @@ -0,0 +1,51 @@ +import pytest +from unittest.mock import MagicMock + +from voice_parser import VoiceParser, VoiceParserError + + +class TestVoiceParserSanitize: + def test_sanitize_valid_input(self): + parser = VoiceParser(recognizer=MagicMock()) + assert parser.sanitize(" Hello World ") == "Hello World" + + def test_sanitize_strips_extra_spaces(self): + parser = VoiceParser(recognizer=MagicMock()) + assert parser.sanitize("generate fibonacci") == "generate fibonacci" + + def test_sanitize_empty_raises(self): + parser = VoiceParser(recognizer=MagicMock()) + with pytest.raises(VoiceParserError): + parser.sanitize("") + + def test_sanitize_whitespace_only_raises(self): + parser = VoiceParser(recognizer=MagicMock()) + with pytest.raises(VoiceParserError): + parser.sanitize(" ") + + +class TestVoiceParserTranscribe: + def _make_parser(self): + import speech_recognition as sr + + mock_recognizer = MagicMock() + parser = VoiceParser(recognizer=mock_recognizer) + return parser, mock_recognizer, sr + + def test_transcribe_returns_text(self): + parser, mock_recognizer, _ = self._make_parser() + mock_audio = MagicMock() + mock_recognizer.recognize_google.return_value = "generate fibonacci" + assert parser.transcribe(mock_audio) == "generate fibonacci" + + def test_transcribe_unknown_value_raises(self): + parser, mock_recognizer, sr = self._make_parser() + mock_recognizer.recognize_google.side_effect = sr.UnknownValueError() + with pytest.raises(VoiceParserError, match="unintelligible"): + parser.transcribe(MagicMock()) + + def test_transcribe_request_error_raises(self): + parser, mock_recognizer, sr = self._make_parser() + mock_recognizer.recognize_google.side_effect = sr.RequestError("service down") + with pytest.raises(VoiceParserError, match="service error"): + parser.transcribe(MagicMock())