Skip to content
Merged
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: 8 additions & 1 deletion PROTO.md
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ write_tools.py # 12 write tools (create/edit issue+pr/merge/close/comm
release_tools.py # 3 release reads (run jobs, release, release asset) + 4 gated release writes (dispatch, tag, edit notes, upload asset)
review_tools.py # 3 verdict tools (comment/approve/request-changes, guarded) — gated
gh_issue.py # /issue chat command logic + repo resolution (resolve_repo, default_repo_error)
api.py # routers — public PAGES (view/workspace/new-issue) + gated data routes (config/status/issues/prs/issue)
api.py # routers — public PAGES (view/workspace/new-issue) + gated data routes (config/status/issues/prs/counts/issue)
view.py # PAGE = read-only board; NEW_ISSUE_PAGE = file-an-issue form; shared setup card. --pl-* themed
skills/github/SKILL.md # workflow manual (review / fix round / CI / issues / merge / release) — host auto-loads skills/
tests/ # host-free pytest (gating + version coherence + routes via TestClient + the no-raise sweep)
Expand Down Expand Up @@ -188,6 +188,13 @@ installed after boot is found by the next call.
getter and short-circuits when `default_repo` is set; the routes and `github_status`
run the resolution via `asyncio.to_thread`; checkout remotes are cached 10 min.

**Board totals**: gated `GET /api/plugins/github/counts?repo=owner/name&state=open&search=`
returns `{issues: N, prs: N}` using one GraphQL search request, independent of list
limits, or `{error: ...}` on failure. States are open/closed/merged/all; closed PRs
include merged PRs, matching `gh pr list --state closed`. Merged always returns zero
issues (issues cannot merge). Search is trimmed and capped at 256 characters, as on
the list routes, and passed as GraphQL variables.

## 6. Rules

- **Host-free.** NEVER import `graph.*` / `plugins.*` at module top — the suite runs
Expand Down
50 changes: 50 additions & 0 deletions api.py
Original file line number Diff line number Diff line change
Expand Up @@ -143,6 +143,52 @@ async def fetch_prs(
return {"items": items}


async def fetch_counts(repo: str, state: str = "open", search: str = "") -> dict:
"""Return issue/PR totals for the board filters in one GraphQL request.

Issues cannot be merged, so their count is always zero for ``state=merged``.
Search values are variables, never interpolated into the GraphQL document.
"""
if err := bad_repo(repo):
return {"error": err}
norm = _norm_state(state)
if norm is None:
return {"error": f"Error: state must be open|closed|merged|all (got {state!r})."}
q = _search_arg(search)
# is:closed for PRs includes merged, matching gh pr list --state closed.
qualifier = "" if norm == "all" else f"is:{norm}"
issue_qualifier = "" if norm == "merged" else qualifier
issues = " ".join(filter(None, [f"repo:{repo}", "is:issue", issue_qualifier, q]))
prs = " ".join(filter(None, [f"repo:{repo}", "is:pr", qualifier, q]))
query = (
"query($issues: String!, $prs: String!) { "
"issues: search(query: $issues, type: ISSUE, first: 0) { issueCount } "
"prs: search(query: $prs, type: ISSUE, first: 0) { issueCount } }"
)
rc, out, serr = await run_gh(
["api", "graphql", "-f", f"query={query}", "-f", f"issues={issues}", "-f", f"prs={prs}"]
)
if gh_err := check_gh_error(rc, serr, repo=repo):
return {"error": gh_err}
result, perr = parse_json(out, dict)
if perr:
return {"error": perr}
if result.get("errors"):
return {"error": "Error: GitHub GraphQL returned errors while fetching counts."}
data = result.get("data")
if not isinstance(data, dict):
return {"error": "Error: unexpected gh output (expected data object)."}
counts = {}
for name in ("issues", "prs"):
node = data.get(name)
if not isinstance(node, dict) or type(node.get("issueCount")) is not int or node["issueCount"] < 0:
return {"error": f"Error: unexpected gh output (expected non-negative integer data.{name}.issueCount)."}
counts[name] = node["issueCount"]
if norm == "merged":
counts["issues"] = 0
return counts


def _repos(cfg: dict) -> list[str]:
"""The picker list — the explicit ``github.repos`` entries (first, operator order)
UNION the host's ADR 0095 managed-projects registry (v0.115.0+) UNION the repos
Expand Down Expand Up @@ -253,6 +299,10 @@ async def _prs(repo: str, state: str = "open", limit: int = 30, search: str = ""
# with_checks=True adds the CI rollup the board renders as a per-row chip.
return await fetch_prs(repo, state, limit, with_checks=True, search=search)

@router.get("/counts")
async def _counts(repo: str, state: str = "open", search: str = "") -> dict:
return await fetch_counts(repo, state, search)

@router.get("/detail/pr")
async def _detail_pr(repo: str, number: int, fresh: int = 0) -> dict:
"""One PR's full detail object (``detail.fetch_pr_detail``) — read-only; memoised
Expand Down
115 changes: 115 additions & 0 deletions tests/test_counts_route.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,115 @@
"""Host-free coverage for the board's totals data route."""

import asyncio
import json
from unittest.mock import AsyncMock, patch

import pytest
from fastapi import FastAPI
from fastapi.testclient import TestClient
from ghplugin import api

QUERY = (
"query($issues: String!, $prs: String!) { "
"issues: search(query: $issues, type: ISSUE, first: 0) { issueCount } "
"prs: search(query: $prs, type: ISSUE, first: 0) { issueCount } }"
)
RESPONSE = {"data": {"issues": {"issueCount": 412}, "prs": {"issueCount": 107}}}


def client():
app = FastAPI()
app.include_router(api.build_data_router({}), prefix="/api/plugins/github")
return TestClient(app)


def argv(issues, prs):
return ["api", "graphql", "-f", f"query={QUERY}", "-f", f"issues={issues}", "-f", f"prs={prs}"]


def test_counts_route_exact_argv():
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(RESPONSE), ""))) as gh:
response = client().get("/api/plugins/github/counts", params={"repo": "o/n", "state": "open"})
assert response.status_code == 200
assert response.json() == {"issues": 412, "prs": 107}
gh.assert_awaited_once_with(argv("repo:o/n is:issue is:open", "repo:o/n is:pr is:open"))
assert "/counts" not in {route.path for route in api.build_view_router().routes}


@pytest.mark.parametrize(
"state,issue_state,pr_state,issues",
[("closed", " is:closed", " is:closed", 412), ("merged", "", " is:merged", 0), ("all", "", "", 412)],
)
def test_states_and_search(state, issue_state, pr_state, issues):
search = '-label:bug "two words"'
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(RESPONSE), ""))) as gh:
result = client().get("/api/plugins/github/counts", params={"repo": "o/n", "state": state, "search": search})
assert result.json() == {"issues": issues, "prs": 107}
gh.assert_awaited_once_with(argv(f"repo:o/n is:issue{issue_state} {search}", f"repo:o/n is:pr{pr_state} {search}"))


def test_normalization_and_search_cap():
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(RESPONSE), ""))) as gh:
result = asyncio.run(api.fetch_counts("o/n", " OPEN ", " " + "x" * 300 + " "))
assert result == {"issues": 412, "prs": 107}
gh.assert_awaited_once_with(argv("repo:o/n is:issue is:open " + "x" * 256, "repo:o/n is:pr is:open " + "x" * 256))


@pytest.mark.parametrize("repo,state", [("bad", "open"), ("", "open"), ("o/n", "invalid")])
def test_invalid_input_skips_gh(repo, state):
with patch.object(api, "run_gh", AsyncMock()) as gh:
result = asyncio.run(api.fetch_counts(repo, state))
assert result["error"]
gh.assert_not_awaited()


def test_gh_error():
with patch.object(api, "run_gh", AsyncMock(return_value=(1, "", "failed"))):
assert "failed" in asyncio.run(api.fetch_counts("o/n"))["error"]


def test_non_json():
with patch.object(api, "run_gh", AsyncMock(return_value=(0, "not JSON", ""))):
assert "parse" in asyncio.run(api.fetch_counts("o/n"))["error"]


def test_missing_issue_count():
body = {"data": {"issues": {}, "prs": {"issueCount": 1}}}
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(body), ""))):
assert "data.issues.issueCount" in asyncio.run(api.fetch_counts("o/n"))["error"]


@pytest.mark.parametrize("value", [None, [], "bad", 1, True])
@pytest.mark.parametrize("level", ["root", "data", "issues", "prs"])
def test_malformed_response_levels(level, value):
body = json.loads(json.dumps(RESPONSE))
if level == "root":
body = value
elif level == "data":
body["data"] = value
else:
body["data"][level] = value
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(body), ""))):
assert asyncio.run(api.fetch_counts("o/n"))["error"]


@pytest.mark.parametrize("value", [None, [], {}, "12", 1.5, True, -1])
@pytest.mark.parametrize("name", ["issues", "prs"])
def test_invalid_count(name, value):
body = json.loads(json.dumps(RESPONSE))
body["data"][name]["issueCount"] = value
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(body), ""))):
assert asyncio.run(api.fetch_counts("o/n", "merged"))["error"]


def test_graphql_partial_error():
body = {**RESPONSE, "errors": [{"message": "query failed"}]}
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(body), ""))):
assert asyncio.run(api.fetch_counts("o/n"))["error"]


def test_zero_counts_and_defaults():
body = {"data": {"issues": {"issueCount": 0}, "prs": {"issueCount": 0}}}
with patch.object(api, "run_gh", AsyncMock(return_value=(0, json.dumps(body), ""))) as gh:
assert client().get("/api/plugins/github/counts", params={"repo": "o/n"}).json() == {"issues": 0, "prs": 0}
gh.assert_awaited_once_with(argv("repo:o/n is:issue is:open", "repo:o/n is:pr is:open"))
Loading