import subprocess from afk_developer.scheduler.tools.command_policy import evaluate_command from afk_developer.scheduler.verification import ( VerificationOutcomeCode, parse_legacy_verification_command, run_verification_request, ) def run_command( command: str, project_dir: str, timeout: int = 60, *, disallow_unscoped_pytest: bool = False, ) -> str: policy = evaluate_command( command, disallow_unscoped_pytest=disallow_unscoped_pytest ) if not policy.allowed: prefix = ( "TASK_COMMAND_POLICY_REJECTED" if disallow_unscoped_pytest and policy.reason.startswith("this task prohibits") else "COMMAND_POLICY_REJECTED" ) return ( f"{prefix}: Refused to run this command ({policy.reason}). " "Choose a narrower, project-scoped command instead." ) try: result = subprocess.run( command, shell=True, cwd=str(project_dir), capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout, ) output = [] if result.stdout: output.append(result.stdout.strip()) if result.stderr: output.append(f"[stderr]\n{result.stderr.strip()}") if result.returncode != 0: output.append(f"[exit code: {result.returncode}]") return "\n".join(output) if output else f"Command completed (exit {result.returncode})" except subprocess.TimeoutExpired: return f"Error: Command timed out after {timeout}s" except Exception as e: return f"Error running command: {e}" def run_verification_command(command: str, project_dir: str, timeout: int = 60) -> str: """Compatibility shim for the retired string-based verification tool. New worker tools use ``run_verification_request`` directly. This parser is deliberately stricter than the old allowlist and never executes shell text. """ request = parse_legacy_verification_command(command) if request is None: return ( f"{VerificationOutcomeCode.POLICY_REJECTED.value.upper()}: " "Read-only verification requires a typed pytest, Ruff, or Git request." ) request = request.model_copy(update={"timeout_seconds": timeout}) return run_verification_request( request, project_dir, max_timeout_seconds=timeout, ).to_tool_text() def _is_allowed_verification_command(command: str) -> bool: """Return whether a legacy string can safely become a typed request.""" return parse_legacy_verification_command(command) is not None