File size: 10,220 Bytes
d70e0e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
5246c92
d70e0e0
5246c92
 
d70e0e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
e83c312
74dd959
e83c312
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d70e0e0
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
#!/usr/bin/env python3
"""Alerting monitor for OpenCodeReview.

Runs a smoke-test review against a known reference PR and compares the
verdict/score against a last-known-good baseline.  Sends a webhook
notification (Discord or Slack) if the score deviates significantly or
the run errors out.

Usage
-----
    python scripts/alert.py \\
        --baseline-file alert_baseline.json \\
        --discord-webhook "$DISCORD_WEBHOOK_URL"

    # Or with Slack
    python scripts/alert.py \\
        --baseline-file alert_baseline.json \\
        --slack-webhook "$SLACK_WEBHOOK_URL"

Cron (GitHub Actions)
---------------------
    Runs via .github/workflows/alert.yml every 6 hours.
"""

from __future__ import annotations

import argparse
import json
import logging
import os
import sys
import uuid
from datetime import datetime, timezone
from pathlib import Path
from typing import Any, Optional

# Ensure project root is on sys.path
_project_root = Path(__file__).resolve().parent.parent
sys.path.insert(0, str(_project_root))

import urllib.request
import urllib.error

from backend.graph import build_graph
from langgraph.types import Command
from backend.main import SYNTHETIC_STATE
from backend.observability import TokenCostCallback, build_run_metadata, langfuse_trace

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(name)s β€” %(message)s",
)
logger = logging.getLogger(__name__)

DEFAULT_BASELINE = Path(__file__).resolve().parent / "alert_baseline.json"

# A score deviation beyond this threshold (points) triggers alert
SCORE_TOLERANCE = 2.5


# ─── Baseline management ────────────────────────────────────────────────────


def _load_baseline(path: Path) -> dict[str, Any]:
    """Load the last-known-good baseline from disk."""
    if path.exists():
        with open(path, encoding="utf-8") as f:
            return json.load(f)
    return {}


def _save_baseline(path: Path, data: dict[str, Any]) -> None:
    """Save the current run result as the new baseline."""
    with open(path, "w", encoding="utf-8") as f:
        json.dump(data, f, indent=2, ensure_ascii=False)
    logger.info("Baseline saved to %s", path)


# ─── Run smoke test ─────────────────────────────────────────────────────────


def _run_smoke_test() -> dict[str, Any]:
    """Execute one smoke-test review and return the results.

    Returns
    -------
    dict with keys: success, score, verdict, findings_count, cost, error
    """
    db_path = str(_project_root / "alert_checkpoints.db")
    graph = build_graph(db_path)
    thread_id = str(uuid.uuid4())
    cost_tracker = TokenCostCallback()
    metadata = build_run_metadata(
        source="cli", repo="demo-org/demo-repo",
        pr_number=1, session_id=thread_id,
    )
    config: dict = {
        "configurable": {"thread_id": f"alert-{thread_id}"},
        "metadata": metadata,
    }

    with langfuse_trace(
        trace_name="opencodereview/alert-check",
        tags=["cli", "alert", "demo-org/demo-repo"],
        session_id=thread_id,
    ) as handler:
        callbacks = [cost_tracker]
        if handler:
            callbacks.append(handler)
        config["callbacks"] = callbacks

        try:
            list(graph.stream(SYNTHETIC_STATE, config))
            state = graph.get_state(config)
            tasks = state.tasks
            values = state.values

            if not tasks:
                # Graph completed without findings
                verdict = values.get("verdict")
                score = verdict.overall_score if verdict else 0.0
                result = {
                    "success": True,
                    "score": score,
                    "verdict": verdict.recommendation if verdict else "none",
                    "findings_count": len(values.get("final_findings", [])),
                    "cost": cost_tracker.summary(),
                    "error": None,
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                }
            else:
                # Resume with reject to complete
                graph.invoke(Command(resume={"action": "reject"}), config)
                final_state = graph.get_state(config)
                verdict = final_state.values.get("verdict")
                findings = final_state.values.get("final_findings", [])
                score = verdict.overall_score if verdict else 0.0
                result = {
                    "success": True,
                    "score": score,
                    "verdict": verdict.recommendation if verdict else "none",
                    "findings_count": len(findings),
                    "cost": cost_tracker.summary(),
                    "error": None,
                    "timestamp": datetime.now(timezone.utc).isoformat(),
                }

            # Cleanup
            if os.path.exists(db_path):
                try:
                    os.remove(db_path)
                except PermissionError:
                    pass

            return result

        except Exception as exc:
            # Cleanup on error
            if os.path.exists(db_path):
                try:
                    os.remove(db_path)
                except PermissionError:
                    pass
            return {
                "success": False,
                "score": 0.0,
                "verdict": "error",
                "findings_count": 0,
                "cost": "N/A",
                "error": str(exc),
                "timestamp": datetime.now(timezone.utc).isoformat(),
            }


# ─── Webhook notification ────────────────────────────────────────────────────


def _send_discord(webhook: str, message: str) -> None:
    """Send a message to a Discord channel via webhook."""
    payload = json.dumps({"content": message}).encode("utf-8")
    req = urllib.request.Request(
        webhook,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        urllib.request.urlopen(req, timeout=15)
        logger.info("Discord notification sent")
    except urllib.error.URLError as exc:
        logger.warning("Failed to send Discord webhook: %s", exc)


def _send_slack(webhook: str, message: str) -> None:
    """Send a message to a Slack channel via webhook."""
    payload = json.dumps({"text": message}).encode("utf-8")
    req = urllib.request.Request(
        webhook,
        data=payload,
        headers={"Content-Type": "application/json"},
        method="POST",
    )
    try:
        urllib.request.urlopen(req, timeout=15)
        logger.info("Slack notification sent")
    except urllib.error.URLError as exc:
        logger.warning("Failed to send Slack webhook: %s", exc)


# ─── Main ────────────────────────────────────────────────────────────────────


def main() -> None:
    parser = argparse.ArgumentParser(
        description="Run smoke-test alert check for OpenCodeReview",
    )
    parser.add_argument(
        "--baseline-file", type=Path, default=DEFAULT_BASELINE,
        help="Path to baseline JSON file (default: %(default)s)",
    )
    parser.add_argument(
        "--discord-webhook", default=os.environ.get("DISCORD_WEBHOOK", ""),
        help="Discord webhook URL (or DISCORD_WEBHOOK env var)",
    )
    parser.add_argument(
        "--slack-webhook", default=os.environ.get("SLACK_WEBHOOK", ""),
        help="Slack webhook URL (or SLACK_WEBHOOK env var)",
    )
    parser.add_argument(
        "--update-baseline", action="store_true",
        help="Update the baseline file with this run's result (no alert on deviation)",
    )
    args = parser.parse_args()

    if not args.discord_webhook and not args.slack_webhook:
        logger.info("No webhook configured β€” running in dry-run mode (no notification)")

    # --- Run smoke test ---
    logger.info("Running smoke test alert check…")
    result = _run_smoke_test()

    if not result["success"]:
        msg = (
            f"🚨 **OpenCodeReview Alert β€” Smoke test FAILED**\n"
            f"Error: {result['error']}\n"
            f"Time: {result['timestamp']}"
        )
        logger.error(msg)
        if args.discord_webhook:
            _send_discord(args.discord_webhook, msg)
        if args.slack_webhook:
            _send_slack(args.slack_webhook, msg)
        sys.exit(1)

    logger.info(
        "Smoke test OK β€” score=%.1f, findings=%d, verdict=%s, %s",
        result["score"], result["findings_count"],
        result["verdict"], result["cost"],
    )

    # --- Compare with baseline ---
    baseline = _load_baseline(args.baseline_file)

    if args.update_baseline or not baseline:
        _save_baseline(args.baseline_file, result)
        logger.info("Baseline set β€” no comparison performed")
        return

    baseline_score = baseline.get("score", 0.0)
    deviation = abs(result["score"] - baseline_score)

    if deviation > SCORE_TOLERANCE:
        msg = (
            f"⚠️ **OpenCodeReview Alert β€” Score deviation detected**\n"
            f"Current score: {result['score']:.1f}/10 (baseline: {baseline_score:.1f}/10)\n"
            f"Deviation: {deviation:.1f} points (tolerance: {SCORE_TOLERANCE})\n"
            f"Verdict: {result['verdict']}\n"
            f"Findings: {result['findings_count']}\n"
            f"Cost: {result['cost']}\n"
            f"Time: {result['timestamp']}"
        )
        logger.warning(msg)
        if args.discord_webhook:
            _send_discord(args.discord_webhook, msg)
        if args.slack_webhook:
            _send_slack(args.slack_webhook, msg)
    else:
        logger.info(
            "Score within tolerance (deviation=%.1f) β€” no alert needed",
            deviation,
        )


if __name__ == "__main__":
    main()