Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,15 @@ jobs:
- name: Install dependencies
run: python -m pip install -r requirements-dev.txt

- uses: actions/setup-node@v4
if: matrix.python-version == '3.13'
with:
node-version: '22'

- name: Test UI behavior without a browser
if: matrix.python-version == '3.13'
run: node --test tests/frontend/*.test.cjs

- name: Lint (errors only)
run: ruff check .

Expand Down
5 changes: 4 additions & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ A dashboard that analyzes pull request flow in public GitHub repositories and ma

## Try it

Enter a public repository such as `sveltejs/svelte` or `https://github.com/owner/repo`. Analysis runs on Cloudflare Workers; results are cached for six hours. Chat reads that cache on the server and sends Gemini a compact summary of cycle time, complete-week throughput, and aging work. Reanalyze the repository when the cache expires. Private repositories are rejected. Each visitor's IP is limited to six analyses and twelve AI questions per minute. Gemini chat is enabled when `GEMINI_API_KEY` is configured.
Enter a public repository such as `sveltejs/svelte` or `https://github.com/owner/repo`. Analysis runs on Cloudflare Workers; results are kept per repository in Cloudflare KV until explicitly refreshed. Chat reads that cache on the server and sends Gemini a compact summary of cycle time, complete-week throughput, and aging work. Opening a saved repository still checks that it is public, but does not repeat the full analysis scan. Private repositories are rejected. Each visitor's IP is limited to six analyses and twelve AI questions per minute. Gemini chat is enabled when `GEMINI_API_KEY` is configured.

## Local development

Expand All @@ -17,6 +17,8 @@ uv run uvicorn app:app --reload

Open `http://localhost:8000`. The local server uses the GitHub CLI and reads Gemini credentials from the environment or local setup.

The web UI remembers the last repository in the browser and displays when its data was captured. Use **Refresh data** to fetch the latest GitHub data. In local development, raw GitHub data is saved under `.cache/repositories/` and reused across page reloads and server restarts. Keep that directory on persistent storage if the local server is redeployed. The CLI's `raw_data.json` cache is separate.


## Testing

Expand All @@ -28,6 +30,7 @@ pip install -r requirements-dev.txt
ruff check .
pytest --cov # fails below the coverage floor in pyproject.toml
pytest -m unit # or -m integration / -m e2e
node --test tests/frontend/*.test.cjs # UI reload and refresh logic, no browser
```

Tests never touch the network, the `gh`/`bws` CLIs, or Gemini; `subprocess.run` is blocked by default and each test runs in a temp directory.
Expand Down
24 changes: 21 additions & 3 deletions analyze.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@
RAW_DATA_FILE = "raw_data.json"
DASHBOARD_FILE = "dashboard.html"

def run_graphql_query(search_query, count=100):
def run_graphql_query(search_query, count=100, strict=False):
import subprocess
query = """
query($searchQuery: String!, $first: Int!) {
Expand Down Expand Up @@ -90,17 +90,23 @@ def run_graphql_query(search_query, count=100):
try:
res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True)
data = json.loads(res.stdout)
if strict and data.get("errors"):
raise RuntimeError("GraphQL error in pull request search")
if "data" in data and "search" in data["data"]:
return data["data"]["search"]["nodes"]
else:
if strict:
raise RuntimeError("Invalid GraphQL response for pull request search")
print("GraphQL Error or empty response:", data)
return []
except subprocess.CalledProcessError as e:
if strict:
raise
print("Error executing query:", e)
print("Stderr:", e.stderr)
return []

def collect_data(repo="sveltejs/svelte"):
def collect_data(repo="sveltejs/svelte", strict=False):
import subprocess
print(f"Collecting data for {repo}...")

Expand All @@ -112,7 +118,7 @@ def collect_data(repo="sveltejs/svelte"):
# 1. Pre-AI Era (2021) baseline
print("Fetching Pre-AI Era (2021) sample...")
pre_ai_query = f"repo:{repo} is:pr is:merged merged:2021-06-01..2021-12-31"
pre_ai_nodes = run_graphql_query(pre_ai_query, 30)
pre_ai_nodes = run_graphql_query(pre_ai_query, 30, strict=strict) if strict else run_graphql_query(pre_ai_query, 30)
print(f"Retrieved {len(pre_ai_nodes)} Pre-AI PRs.")

# 2. Modern Era: Fetch 600 most recent merged PRs in pages of 100
Expand Down Expand Up @@ -204,6 +210,8 @@ def collect_data(repo="sveltejs/svelte"):
try:
res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True)
data = json.loads(res.stdout)
if strict and data.get("errors"):
raise RuntimeError("GraphQL error in merged pull request search")
if "data" in data and "search" in data["data"]:
page_nodes = data["data"]["search"]["nodes"]
recent_nodes.extend(page_nodes)
Expand All @@ -215,9 +223,13 @@ def collect_data(repo="sveltejs/svelte"):
else:
break
else:
if strict:
raise RuntimeError("Invalid GraphQL response for merged pull requests")
print("Error or empty response:", data)
break
except Exception as e:
if strict:
raise
print("Exception during merged PR fetch:", e)
break

Expand Down Expand Up @@ -296,10 +308,16 @@ def collect_data(repo="sveltejs/svelte"):
try:
res = subprocess.run(cmd, capture_output=True, text=True, encoding="utf-8", check=True)
data = json.loads(res.stdout)
if strict and data.get("errors"):
raise RuntimeError("GraphQL error in open pull request search")
if "data" in data and "search" in data["data"]:
open_nodes = data["data"]["search"]["nodes"]
print(f"Retrieved {len(open_nodes)} active open PRs.")
elif strict:
raise RuntimeError("Invalid GraphQL response for open pull requests")
except Exception as e:
if strict:
raise
print("Error fetching open PRs:", e)

# 4. Issues were fetched in parallel above, independent of PR linkage
Expand Down
21 changes: 19 additions & 2 deletions app.py
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,7 @@
import sys
sys.path.insert(0, str(Path(__file__).parent))
from analyze import collect_data, compute_flow_metrics
from repository_cache import RepositoryCache

# ---------------------------------------------------------------------------
# App Setup
Expand Down Expand Up @@ -76,20 +77,36 @@ def _parse_repo_slug(repo_url: str) -> str:
url = url[len("https://github.com/"):]
if url.startswith("http://github.com/"):
url = url[len("http://github.com/"):]
if url.startswith("github.com/"):
url = url[len("github.com/"):]
# Remove trailing .git if present
if url.endswith(".git"):
url = url[:-4]
# Remove any /tree/... or /blob/... path segments
parts = url.split("/")
if len(parts) >= 2:
return f"{parts[0]}/{parts[1]}"
repo = f"{parts[0].lower()}/{parts[1].lower()}"
RepositoryCache().path_for(repo)
return repo
raise ValueError(f"Cannot parse repo slug from: {repo_url!r}")


def _run_analysis(repo: str, force: bool) -> dict:
"""Blocking function that collects raw data and computes metrics."""
raw = collect_data(repo)
cache = RepositoryCache()
raw = None if force else cache.load(repo)
cache_hit = raw is not None
if raw is None:
raw = collect_data(repo, strict=True)
if raw.get("issues") is None:
raise RuntimeError(f"Incomplete GitHub collection for {repo}")
metrics = compute_flow_metrics(raw)
if not cache_hit:
try:
cache.save(repo, raw)
except OSError as exc:
print(f"Could not save repository cache for {repo}: {exc}")
metrics["cache_hit"] = cache_hit
return metrics


Expand Down
10 changes: 8 additions & 2 deletions cloudflare_app.py
Original file line number Diff line number Diff line change
Expand Up @@ -217,16 +217,20 @@ async def analyze_repo(req: AnalyzeRequest, request: Request):
if cache and not req.force_refresh:
saved = await cache.get(cache_key)
if saved:
return json.loads(saved)
metrics = json.loads(saved)
if metrics.get("repo", "").lower() == repo.lower():
metrics["cache_hit"] = True
return metrics
try:
raw = await collect_public_data(repo, token)
metrics = compute_flow_metrics(raw)
except (httpx.HTTPError, ValueError) as exc:
raise HTTPException(status_code=502, detail=str(exc)) from exc
if not metrics.get("recent_stats", {}).get("total"):
raise HTTPException(status_code=422, detail="No merged pull requests were found for this public repository.")
metrics["cache_hit"] = False
if cache:
await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")), expiration_ttl=21600)
await cache.put(cache_key, json.dumps(metrics, separators=(",", ":")))
return metrics


Expand Down Expand Up @@ -283,6 +287,8 @@ async def chat(req: ChatRequest, request: Request):
if not key:
raise HTTPException(status_code=503, detail="AI chat is not configured yet.")
repo = parse_repo(req.repo)
token = getattr(env, "GITHUB_TOKEN", None) if env else None
await public_repo_exists(repo, token)
cache = getattr(env, "ANALYTICS_CACHE", None) if env else None
if cache is None:
raise HTTPException(status_code=503, detail="Analysis cache is not configured yet.")
Expand Down
Loading
Loading