File size: 11,160 Bytes
2cfda00
33a4fd2
 
 
 
 
 
 
2cfda00
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
 
 
 
 
33a4fd2
 
 
 
 
d231444
33a4fd2
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
 
 
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
33a4fd2
 
d242052
d231444
33a4fd2
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
d231444
 
 
 
 
 
 
 
 
 
 
 
33a4fd2
 
 
d231444
 
 
 
33a4fd2
 
 
 
d231444
33a4fd2
 
 
 
 
 
 
 
d231444
33a4fd2
 
 
d231444
 
 
 
33a4fd2
 
 
 
 
 
 
 
 
 
d231444
33a4fd2
d231444
 
 
33a4fd2
 
 
 
 
d231444
33a4fd2
 
 
d231444
33a4fd2
 
d231444
 
 
 
33a4fd2
 
 
 
 
 
 
d242052
 
 
 
 
 
 
33a4fd2
d231444
33a4fd2
 
 
 
 
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
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
"""First-party CLI for ARIA (AI-Powered Repository Intelligence Agent) using Typer."""

import os
import json
import httpx
import typer
from typing import Optional

app = typer.Typer(help="ARIA CLI")


def get_api_url(url: Optional[str]) -> str:
    """Resolves the backend API server base URL."""
    if url:
        return url.rstrip("/")
    env_url = os.environ.get("API_SERVER_URL")
    if env_url:
        return env_url.rstrip("/")
    # Default fallback
    return "http://localhost:8001"


@app.command()
def analyze(
    repo_url: str = typer.Argument(..., help="GitHub repository URL"),
    branch: str = typer.Option("main", "--branch", "-b", help="Git branch or ref"),
    model: str = typer.Option(
        "deepseek-ai/deepseek-v4-flash",
        "--model",
        "-m",
        help="LLM model variant to use",
    ),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Initiates repository analysis and streams progress."""
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/analyze"

    typer.echo(f"Submitting analysis request to {api_endpoint}...")

    try:
        with httpx.stream(
            "POST",
            api_endpoint,
            json={"url": repo_url, "branch": branch, "model": model},
            timeout=None,
        ) as response:
            if response.status_code != 200:
                # Read response body for error detail
                err_content = response.read().decode("utf-8", errors="ignore")
                typer.echo(f"Error {response.status_code}: {err_content}", err=True)
                raise typer.Exit(code=1)

            for line in response.iter_lines():
                if not line.strip():
                    continue
                if line.startswith("data:"):
                    data_str = line[5:].strip()
                    if data_str == "[DONE]":
                        typer.echo("Analysis complete.")
                        break
                    try:
                        data = json.loads(data_str)
                        event = data.get("event") or data.get("status")
                        message = data.get("message") or data.get("step") or ""
                        if event:
                            typer.echo(f"[{event}] {message}")
                        else:
                            typer.echo(data_str)
                    except json.JSONDecodeError:
                        typer.echo(data_str)
    except Exception as exc:
        typer.echo(f"Connection failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command()
def graph(
    owner: str = typer.Argument(..., help="Repository owner/organization"),
    repo: str = typer.Argument(..., help="Repository name"),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Retrieves the React-Flow compatible dependency graph data."""
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/architecture/{owner}/{repo}/graph"

    try:
        response = httpx.get(api_endpoint, timeout=30.0)
        if response.status_code == 200:
            typer.echo(json.dumps(response.json(), indent=2))
        else:
            typer.echo(f"Error {response.status_code}: {response.text}", err=True)
            raise typer.Exit(code=1)
    except Exception as exc:
        typer.echo(f"Request failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command(name="call-graph")
def call_graph(
    owner: str = typer.Argument(..., help="Repository owner/organization"),
    repo: str = typer.Argument(..., help="Repository name"),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Retrieves call graph summary details for the repository."""
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/call-graph/{owner}/{repo}"

    try:
        response = httpx.get(api_endpoint, timeout=30.0)
        if response.status_code == 200:
            typer.echo(json.dumps(response.json(), indent=2))
        else:
            typer.echo(f"Error {response.status_code}: {response.text}", err=True)
            raise typer.Exit(code=1)
    except Exception as exc:
        typer.echo(f"Request failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command(name="api-surface")
def api_surface(
    owner: str = typer.Argument(..., help="Repository owner/organization"),
    repo: str = typer.Argument(..., help="Repository name"),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Retrieves the API surface data for a repository."""
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/api-surface/{owner}/{repo}"

    try:
        response = httpx.get(api_endpoint, timeout=30.0)
        if response.status_code == 200:
            typer.echo(json.dumps(response.json(), indent=2))
        else:
            typer.echo(f"Error {response.status_code}: {response.text}", err=True)
            raise typer.Exit(code=1)
    except Exception as exc:
        typer.echo(f"Request failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command()
def stability(
    owner: str = typer.Argument(..., help="Repository owner/organization"),
    repo: str = typer.Argument(..., help="Repository name"),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Retrieves module stability scores.

    Note: The module stability router is not yet implemented. This command
    will return a 404 until the stability endpoints are added in a future release.
    """
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/stability/{owner}/{repo}"
    try:
        response = httpx.get(api_endpoint, timeout=30.0)
        if response.status_code == 200:
            typer.echo(json.dumps(response.json(), indent=2))
        elif response.status_code == 404:
            typer.echo(
                "Module stability endpoints are not yet implemented. Check back in a future release."
            )
        else:
            typer.echo(f"Error {response.status_code}: {response.text}", err=True)
            raise typer.Exit(code=1)
    except Exception as exc:
        typer.echo(f"Request failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command()
def health(
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Verifies connection and checks health status of backend systems."""
    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/health"

    try:
        response = httpx.get(api_endpoint, timeout=10.0)
        if response.status_code == 200:
            typer.echo(json.dumps(response.json(), indent=2))
        else:
            typer.echo(f"Error {response.status_code}: {response.text}", err=True)
            raise typer.Exit(code=1)
    except Exception as exc:
        typer.echo(f"Health check failed: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command()
def version(
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Prints the CLI version and backend version."""
    typer.echo("Client Version: 1.5.0")

    base_url = get_api_url(url)
    api_endpoint = f"{base_url}/api/v1/health"
    try:
        response = httpx.get(api_endpoint, timeout=5.0)
        if response.status_code == 200:
            status = response.json().get("status", "unknown")
            typer.echo(f"Backend Status: {status}")
        else:
            typer.echo("Backend: Offline")
    except Exception:
        typer.echo("Backend: Offline")


@app.command()
def report(
    repo_name: str = typer.Argument(..., help="Repository identifier (owner/repo)"),
    html: bool = typer.Option(False, "--html", help="Generate HTML report"),
    pdf: bool = typer.Option(
        False, "--pdf", help="Generate print-ready PDF-friendly HTML report"
    ),
    markdown: bool = typer.Option(
        False, "--markdown", "--md", help="Generate Markdown report"
    ),
    output_path: Optional[str] = typer.Option(
        None, "--output-path", "-o", help="Path to write the report file"
    ),
    url: Optional[str] = typer.Option(
        None, "--url", "-u", help="Base URL of the API server"
    ),
) -> None:
    """Generates and downloads the Repository Intelligence Report."""
    if "/" not in repo_name:
        typer.echo(
            "Error: Repository identifier must be in the format 'owner/repo_name'",
            err=True,
        )
        raise typer.Exit(code=1)

    base_url = get_api_url(url)
    owner, repo = repo_name.split("/", 1)

    # 1. Trigger report build
    build_endpoint = f"{base_url}/api/v1/report/{owner}/{repo}/build"
    try:
        typer.echo(f"Building health report for {repo_name}...")
        resp = httpx.post(build_endpoint, timeout=60.0)
        if resp.status_code != 200:
            typer.echo(f"Error building report: {resp.text}", err=True)
            raise typer.Exit(code=1)

        report_data = resp.json()
        overall = report_data["scores"]["overall"]
        grade = report_data["scores"]["grade"]
        typer.echo(
            f"Report composed successfully. Health Score: {overall} (Grade: {grade})"
        )

        # Determine the format
        if markdown:
            fmt = "markdown"
            ext = "md"
        elif pdf:
            fmt = "pdf"
            ext = "html"
        else:
            fmt = "html"
            ext = "html"

        # 2. Download report
        download_endpoint = (
            f"{base_url}/api/v1/report/{owner}/{repo}/download?format={fmt}"
        )
        typer.echo(f"Downloading {fmt.upper()} report...")
        down_resp = httpx.get(download_endpoint, timeout=30.0)
        if down_resp.status_code != 200:
            typer.echo(f"Error downloading report: {down_resp.text}", err=True)
            raise typer.Exit(code=1)

        # Determine output file path
        if not output_path:
            output_path = f"{owner}_{repo}_report.{ext}"

        with open(output_path, "wb") as fh:
            fh.write(down_resp.content)

        typer.echo(
            f"{fmt.upper()} report successfully saved to {os.path.abspath(output_path)}"
        )
    except Exception as exc:
        typer.echo(f"Failed to generate report: {exc}", err=True)
        raise typer.Exit(code=1)


@app.command()
def mcp() -> None:
    """Launches the stdio JSON-RPC Model Context Protocol (MCP) server.

    Speaks JSON-RPC on stdin/stdout and logs to stderr, so it can be launched
    directly by any MCP client. The FastMCP implementation under ``mcp/`` stays
    importable for direct integrations but is deliberately not constructed here,
    to keep this entry point free of SDK-version-specific behaviour.
    """
    from backend.mcp_server import run_mcp_server

    run_mcp_server()


if __name__ == "__main__":
    app()