|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Turn one verified watcher task into one read-only AI diagnosis comment. |
| 3 | +
|
| 4 | +The watcher still owns issue creation and task construction. This dispatcher |
| 5 | +only consumes a task that is already cryptographically bound to P1/P2/P3 |
| 6 | +digests, asks the existing AI gateway for a text-only assessment, then adds one |
| 7 | +idempotency-marked comment to the existing issue. It cannot run an experiment |
| 8 | +or alter a strategy. |
| 9 | +""" |
| 10 | + |
| 11 | +from __future__ import annotations |
| 12 | + |
| 13 | +import argparse |
| 14 | +import json |
| 15 | +import os |
| 16 | +import subprocess |
| 17 | +import sys |
| 18 | +from collections.abc import Callable, Mapping |
| 19 | +from pathlib import Path |
| 20 | +from typing import Any |
| 21 | + |
| 22 | +ROOT = Path(__file__).resolve().parents[1] |
| 23 | +if str(ROOT) not in sys.path: |
| 24 | + sys.path.insert(0, str(ROOT)) |
| 25 | + |
| 26 | +from client.config import GatewayConfig # noqa: E402 |
| 27 | +from client.gateway_client import AiGatewayClient # noqa: E402 |
| 28 | +from service.research_diagnosis import ( # noqa: E402 |
| 29 | + MARKER, |
| 30 | + build_research_diagnosis_prompt, |
| 31 | + build_research_diagnosis_request, |
| 32 | + format_research_diagnosis_comment, |
| 33 | +) |
| 34 | + |
| 35 | + |
| 36 | +MAX_AUTOMATIC_DIAGNOSES = 1 |
| 37 | +_REPOSITORY = "QuantStrategyLab" |
| 38 | + |
| 39 | + |
| 40 | +def _clean_repo(value: object) -> str: |
| 41 | + repo = str(value or "").strip() |
| 42 | + if not repo.startswith(f"{_REPOSITORY}/") or "/" not in repo: |
| 43 | + return "" |
| 44 | + return repo |
| 45 | + |
| 46 | + |
| 47 | +def load_watcher_result(path: str | Path) -> dict[str, Any]: |
| 48 | + payload = json.loads(Path(path).read_text(encoding="utf-8")) |
| 49 | + if not isinstance(payload, dict): |
| 50 | + raise ValueError("watcher result must be a JSON object") |
| 51 | + return payload |
| 52 | + |
| 53 | + |
| 54 | +def diagnosis_candidates(result: Mapping[str, Any]) -> list[dict[str, Any]]: |
| 55 | + """Join watcher issue results to the exact current research-task IDs.""" |
| 56 | + snapshot = result.get("research_task_source_snapshot") |
| 57 | + if not isinstance(snapshot, Mapping) or snapshot.get("data_status") != "ready": |
| 58 | + return [] |
| 59 | + raw_tasks = snapshot.get("tasks") |
| 60 | + raw_issues = result.get("issues") |
| 61 | + if not isinstance(raw_tasks, list) or not isinstance(raw_issues, list): |
| 62 | + return [] |
| 63 | + tasks_by_id: dict[str, Mapping[str, Any]] = {} |
| 64 | + for task in raw_tasks: |
| 65 | + if isinstance(task, Mapping) and isinstance(task.get("task_id"), str): |
| 66 | + tasks_by_id[task["task_id"]] = task |
| 67 | + |
| 68 | + candidates: list[dict[str, Any]] = [] |
| 69 | + for issue in raw_issues: |
| 70 | + if not isinstance(issue, Mapping): |
| 71 | + continue |
| 72 | + summary = issue.get("task") |
| 73 | + if not isinstance(summary, Mapping): |
| 74 | + continue |
| 75 | + event_key = str(summary.get("event_key") or "") |
| 76 | + task = tasks_by_id.get(f"watcher-{event_key}") |
| 77 | + if task is None: |
| 78 | + continue |
| 79 | + repo = _clean_repo(issue.get("repo")) |
| 80 | + issue_url = str(issue.get("url") or issue.get("existing_url") or "").strip() |
| 81 | + trigger = summary.get("trigger") if isinstance(summary.get("trigger"), Mapping) else {} |
| 82 | + if repo and issue_url: |
| 83 | + candidates.append({"repository": repo, "issue_url": issue_url, "task": task, "trigger": trigger}) |
| 84 | + return sorted(candidates, key=lambda item: (str(item["repository"]), str(item["issue_url"]))) |
| 85 | + |
| 86 | + |
| 87 | +def issue_has_diagnosis_marker(repository: str, issue_url: str) -> bool: |
| 88 | + """Read comments only; any retrieval error means do not repeat an action.""" |
| 89 | + try: |
| 90 | + completed = subprocess.run( |
| 91 | + ["gh", "issue", "view", issue_url, "--repo", repository, "--json", "comments", "--jq", ".comments[].body"], |
| 92 | + check=True, |
| 93 | + capture_output=True, |
| 94 | + text=True, |
| 95 | + timeout=30, |
| 96 | + ) |
| 97 | + except (OSError, subprocess.CalledProcessError, subprocess.TimeoutExpired): |
| 98 | + return True |
| 99 | + return MARKER in completed.stdout |
| 100 | + |
| 101 | + |
| 102 | +def comment_issue(repository: str, issue_url: str, body: str) -> str: |
| 103 | + completed = subprocess.run( |
| 104 | + ["gh", "issue", "comment", issue_url, "--repo", repository, "--body", body], |
| 105 | + check=True, |
| 106 | + capture_output=True, |
| 107 | + text=True, |
| 108 | + timeout=30, |
| 109 | + ) |
| 110 | + return completed.stdout.strip() |
| 111 | + |
| 112 | + |
| 113 | +def _error_summary(value: object) -> str: |
| 114 | + return str(value or "").replace("\r", " ").replace("\n", " ").strip()[:300] |
| 115 | + |
| 116 | + |
| 117 | +def run_diagnosis( |
| 118 | + result: Mapping[str, Any], |
| 119 | + *, |
| 120 | + dry_run: bool = False, |
| 121 | + max_per_run: int = MAX_AUTOMATIC_DIAGNOSES, |
| 122 | + marker_present: Callable[[str, str], bool] = issue_has_diagnosis_marker, |
| 123 | + create_comment: Callable[[str, str, str], str] = comment_issue, |
| 124 | + client_factory: Callable[[GatewayConfig], AiGatewayClient] = AiGatewayClient, |
| 125 | +) -> dict[str, Any]: |
| 126 | + """Diagnose at most one not-yet-diagnosed issue; failures have no side effect.""" |
| 127 | + candidates = diagnosis_candidates(result) |
| 128 | + if max_per_run < 1: |
| 129 | + raise ValueError("max_per_run must be positive") |
| 130 | + pending = [ |
| 131 | + item |
| 132 | + for item in candidates |
| 133 | + if not marker_present(str(item["repository"]), str(item["issue_url"])) |
| 134 | + ] |
| 135 | + summary: dict[str, Any] = { |
| 136 | + "schema_version": "qsl.research_diagnosis_dispatch.v1", |
| 137 | + "status": "ok", |
| 138 | + "candidate_count": len(candidates), |
| 139 | + "pending_count": len(pending), |
| 140 | + "max_per_run": max_per_run, |
| 141 | + "dry_run": dry_run, |
| 142 | + "diagnoses": [], |
| 143 | + } |
| 144 | + if not pending: |
| 145 | + summary["status"] = "skipped" |
| 146 | + summary["reason"] = "no_pending_verified_research_task" |
| 147 | + return summary |
| 148 | + |
| 149 | + try: |
| 150 | + config = GatewayConfig.from_env() |
| 151 | + except ValueError: |
| 152 | + summary["status"] = "not_configured" |
| 153 | + summary["reason"] = "ai_gateway_not_configured" |
| 154 | + return summary |
| 155 | + client = client_factory(config) |
| 156 | + for candidate in pending[:max_per_run]: |
| 157 | + task = candidate["task"] |
| 158 | + try: |
| 159 | + request = build_research_diagnosis_request(task, trigger=candidate["trigger"]) |
| 160 | + prompt = build_research_diagnosis_prompt(request) |
| 161 | + except (TypeError, ValueError) as exc: |
| 162 | + summary["diagnoses"].append({"status": "rejected", "error": _error_summary(exc)}) |
| 163 | + continue |
| 164 | + if dry_run: |
| 165 | + summary["diagnoses"].append( |
| 166 | + { |
| 167 | + "status": "dry_run", |
| 168 | + "task_id": request["task_id"], |
| 169 | + "task_sha256": request["task_sha256"], |
| 170 | + "repository": candidate["repository"], |
| 171 | + "issue_url": candidate["issue_url"], |
| 172 | + "prompt": prompt, |
| 173 | + } |
| 174 | + ) |
| 175 | + continue |
| 176 | + ai_result = client.analyze( |
| 177 | + prompt, |
| 178 | + system="You provide bounded, read-only research diagnosis only.", |
| 179 | + max_tokens=1_600, |
| 180 | + timeout=120, |
| 181 | + source_repository=str(request["target"]["repository"]), |
| 182 | + ) |
| 183 | + if not ai_result.success: |
| 184 | + summary["diagnoses"].append( |
| 185 | + { |
| 186 | + "status": "unavailable", |
| 187 | + "task_id": request["task_id"], |
| 188 | + "error": _error_summary(ai_result.error), |
| 189 | + } |
| 190 | + ) |
| 191 | + continue |
| 192 | + try: |
| 193 | + body = format_research_diagnosis_comment( |
| 194 | + request, |
| 195 | + ai_result.output, |
| 196 | + provider=ai_result.provider, |
| 197 | + model=ai_result.model, |
| 198 | + ) |
| 199 | + comment_url = create_comment(str(candidate["repository"]), str(candidate["issue_url"]), body) |
| 200 | + except (OSError, RuntimeError, ValueError, subprocess.CalledProcessError, subprocess.TimeoutExpired) as exc: |
| 201 | + summary["diagnoses"].append( |
| 202 | + { |
| 203 | + "status": "comment_failed", |
| 204 | + "task_id": request["task_id"], |
| 205 | + "error": _error_summary(exc), |
| 206 | + } |
| 207 | + ) |
| 208 | + continue |
| 209 | + summary["diagnoses"].append( |
| 210 | + { |
| 211 | + "status": "diagnosed", |
| 212 | + "task_id": request["task_id"], |
| 213 | + "task_sha256": request["task_sha256"], |
| 214 | + "repository": candidate["repository"], |
| 215 | + "issue_url": candidate["issue_url"], |
| 216 | + "comment_url": comment_url, |
| 217 | + } |
| 218 | + ) |
| 219 | + if any(item.get("status") in {"unavailable", "comment_failed", "rejected"} for item in summary["diagnoses"]): |
| 220 | + summary["status"] = "partial_error" |
| 221 | + return summary |
| 222 | + |
| 223 | + |
| 224 | +def main(argv: list[str] | None = None) -> int: |
| 225 | + parser = argparse.ArgumentParser(description="Run bounded AI diagnosis for verified research tasks.") |
| 226 | + parser.add_argument("--input", required=True, help="Watcher result JSON path") |
| 227 | + parser.add_argument("--dry-run", action="store_true", help="Build the prompt but do not call AI or comment") |
| 228 | + parser.add_argument("--max-per-run", type=int, default=MAX_AUTOMATIC_DIAGNOSES) |
| 229 | + args = parser.parse_args(argv) |
| 230 | + try: |
| 231 | + result = run_diagnosis(load_watcher_result(args.input), dry_run=args.dry_run, max_per_run=args.max_per_run) |
| 232 | + except (OSError, ValueError, json.JSONDecodeError) as exc: |
| 233 | + print(json.dumps({"status": "error", "error": _error_summary(exc)}, sort_keys=True)) |
| 234 | + return 2 |
| 235 | + print(json.dumps(result, ensure_ascii=False, sort_keys=True)) |
| 236 | + # A missing service or failed text-only diagnosis must not turn into a |
| 237 | + # strategy action or break the primary watcher. Its durable issue remains |
| 238 | + # the retry point for the next scheduled run. |
| 239 | + return 0 |
| 240 | + |
| 241 | + |
| 242 | +if __name__ == "__main__": |
| 243 | + raise SystemExit(main()) |
0 commit comments