|
| 1 | +# SPDX-License-Identifier: MIT |
| 2 | +# Copyright (c) 2026 BitConcepts, LLC. All rights reserved. |
| 3 | +"""improve_specsmith workflow — self-improvement loop. |
| 4 | +
|
| 5 | +Executes: inspect repo → plan changes → edit code/docs → run tests → |
| 6 | +summarize → produce follow-up tasks. |
| 7 | +
|
| 8 | +Constraints: |
| 9 | +- No silent edits (all changes produce artifacts) |
| 10 | +- No skipping tests |
| 11 | +- No accepting unclear failures |
| 12 | +- Verifier must approve before changes are accepted |
| 13 | +""" |
| 14 | + |
| 15 | +from __future__ import annotations |
| 16 | + |
| 17 | +from datetime import datetime, timezone |
| 18 | +from typing import Any |
| 19 | + |
| 20 | +from specsmith.agents.config import AgentConfig, load_agent_config |
| 21 | +from specsmith.agents.reports import ChangeReport, save_report |
| 22 | + |
| 23 | + |
| 24 | +def run_improvement( |
| 25 | + task: str, |
| 26 | + project_dir: str, |
| 27 | + max_turns: int = 6, |
| 28 | + config: AgentConfig | None = None, |
| 29 | +) -> ChangeReport: |
| 30 | + """Run the full improvement workflow on the specsmith codebase. |
| 31 | +
|
| 32 | + Returns a ChangeReport with results and follow-up tasks. |
| 33 | + """ |
| 34 | + from specsmith.agents.roles import ( |
| 35 | + create_builder, |
| 36 | + create_planner, |
| 37 | + create_verifier, |
| 38 | + ) |
| 39 | + |
| 40 | + if config is None: |
| 41 | + config = load_agent_config(project_dir) |
| 42 | + |
| 43 | + report = ChangeReport( |
| 44 | + task_id=datetime.now(tz=timezone.utc).strftime("%Y%m%d_%H%M%S"), |
| 45 | + task_description=task, |
| 46 | + project_dir=project_dir, |
| 47 | + ) |
| 48 | + |
| 49 | + # ── Phase 1: Plan ────────────────────────────────────────────── |
| 50 | + planner = create_planner(config, project_dir) |
| 51 | + plan_result = planner.run( |
| 52 | + message=f"Plan this improvement task for the specsmith codebase:\n{task}", |
| 53 | + max_turns=max_turns, |
| 54 | + ) |
| 55 | + plan_result.process() |
| 56 | + |
| 57 | + plan_text = _extract_last_assistant_message(plan_result.messages) |
| 58 | + report.plan = plan_text |
| 59 | + |
| 60 | + if not plan_text: |
| 61 | + report.status = "failed" |
| 62 | + report.summary = "Planner produced no output." |
| 63 | + save_report(report) |
| 64 | + return report |
| 65 | + |
| 66 | + # ── Phase 2: Build ───────────────────────────────────────────── |
| 67 | + builder = create_builder(config, project_dir) |
| 68 | + build_result = builder.run( |
| 69 | + message=f"Execute this plan on the specsmith codebase:\n\n{plan_text}", |
| 70 | + max_turns=max_turns, |
| 71 | + ) |
| 72 | + build_result.process() |
| 73 | + |
| 74 | + build_text = _extract_last_assistant_message(build_result.messages) |
| 75 | + report.build_output = build_text |
| 76 | + |
| 77 | + # Extract files changed from build output |
| 78 | + report.files_changed = _extract_files_from_output(build_text) |
| 79 | + |
| 80 | + # ── Phase 3: Verify ──────────────────────────────────────────── |
| 81 | + verifier = create_verifier(config, project_dir) |
| 82 | + verify_result = verifier.run( |
| 83 | + message=( |
| 84 | + f"Verify these changes to the specsmith codebase:\n\n" |
| 85 | + f"{build_text}\n\n" |
| 86 | + "Run the relevant tests. Report ACCEPT or REJECT with reasoning." |
| 87 | + ), |
| 88 | + max_turns=max_turns, |
| 89 | + ) |
| 90 | + verify_result.process() |
| 91 | + |
| 92 | + verify_text = _extract_last_assistant_message(verify_result.messages) |
| 93 | + report.verify_output = verify_text |
| 94 | + |
| 95 | + # Parse verdict |
| 96 | + if "ACCEPT" in verify_text.upper(): |
| 97 | + report.status = "accepted" |
| 98 | + report.verdict = "ACCEPT" |
| 99 | + elif "REJECT" in verify_text.upper(): |
| 100 | + report.status = "rejected" |
| 101 | + report.verdict = "REJECT" |
| 102 | + else: |
| 103 | + report.status = "unclear" |
| 104 | + report.verdict = "UNCLEAR" |
| 105 | + |
| 106 | + # Extract test results |
| 107 | + report.tests_run, report.tests_passed, report.tests_failed = ( |
| 108 | + _extract_test_counts(verify_text) |
| 109 | + ) |
| 110 | + |
| 111 | + # Generate follow-up tasks |
| 112 | + report.follow_up_tasks = _extract_follow_ups(verify_text, build_text) |
| 113 | + report.summary = _generate_summary(report) |
| 114 | + |
| 115 | + save_report(report) |
| 116 | + return report |
| 117 | + |
| 118 | + |
| 119 | +def _extract_last_assistant_message(messages: list[dict[str, Any]]) -> str: |
| 120 | + """Get the last assistant message content from a conversation.""" |
| 121 | + for msg in reversed(messages): |
| 122 | + if msg.get("role") == "assistant" and msg.get("content"): |
| 123 | + return msg["content"] |
| 124 | + return "" |
| 125 | + |
| 126 | + |
| 127 | +def _extract_files_from_output(text: str) -> list[str]: |
| 128 | + """Heuristically extract file paths from builder output.""" |
| 129 | + import re |
| 130 | + |
| 131 | + files: list[str] = [] |
| 132 | + # Match patterns like "Wrote X chars to path" or "Patched path" |
| 133 | + pattern = r"(?:Wrote|Patched|Created|Modified)\s+.*?\s+(?:to\s+)?(\S+\.\w+)" |
| 134 | + for match in re.finditer(pattern, text): |
| 135 | + files.append(match.group(1)) |
| 136 | + # Match patterns like "- path/to/file.py" in lists |
| 137 | + for match in re.finditer(r"^-\s+`?([a-zA-Z0-9_/\\.]+\.\w+)`?", text, re.MULTILINE): |
| 138 | + if match.group(1) not in files: |
| 139 | + files.append(match.group(1)) |
| 140 | + return files |
| 141 | + |
| 142 | + |
| 143 | +def _extract_test_counts(text: str) -> tuple[int, int, int]: |
| 144 | + """Extract test run/pass/fail counts from verifier output.""" |
| 145 | + import re |
| 146 | + |
| 147 | + # Match "N passed" pattern |
| 148 | + passed_match = re.search(r"(\d+)\s+passed", text) |
| 149 | + failed_match = re.search(r"(\d+)\s+failed", text) |
| 150 | + passed = int(passed_match.group(1)) if passed_match else 0 |
| 151 | + failed = int(failed_match.group(1)) if failed_match else 0 |
| 152 | + return passed + failed, passed, failed |
| 153 | + |
| 154 | + |
| 155 | +def _extract_follow_ups(verify_text: str, build_text: str) -> list[str]: |
| 156 | + """Extract follow-up tasks from agent output.""" |
| 157 | + follow_ups: list[str] = [] |
| 158 | + for text in [verify_text, build_text]: |
| 159 | + for line in text.splitlines(): |
| 160 | + lower = line.lower().strip() |
| 161 | + if lower.startswith(("- todo:", "- follow-up:", "- next:")): |
| 162 | + follow_ups.append(line.strip().lstrip("- ")) |
| 163 | + elif "TODO" in line and ":" in line: |
| 164 | + follow_ups.append(line.strip()) |
| 165 | + return follow_ups |
| 166 | + |
| 167 | + |
| 168 | +def _generate_summary(report: ChangeReport) -> str: |
| 169 | + """Generate a human-readable summary of the improvement run.""" |
| 170 | + parts = [f"Task: {report.task_description}"] |
| 171 | + parts.append(f"Verdict: {report.verdict}") |
| 172 | + if report.files_changed: |
| 173 | + parts.append(f"Files changed: {', '.join(report.files_changed)}") |
| 174 | + if report.tests_run > 0: |
| 175 | + parts.append( |
| 176 | + f"Tests: {report.tests_passed}/{report.tests_run} passed" |
| 177 | + + (f", {report.tests_failed} failed" if report.tests_failed else "") |
| 178 | + ) |
| 179 | + if report.follow_up_tasks: |
| 180 | + parts.append(f"Follow-ups: {len(report.follow_up_tasks)}") |
| 181 | + return " | ".join(parts) |
0 commit comments