mirror of
https://github.com/safishamsi/graphify.git
synced 2026-07-16 12:27:06 +00:00
b6127aa5a7
* feat(bash): harden extractor — literal filtering, entrypoint nodes, AST-ancestry-aware command detection Builds on tree-sitter-bash extractor from #866. Two correctness/security improvements to bash extraction in graphify/extract.py: 1. Reject command/process substitutions at extraction time. Token-level filtering misses constructs like `$(build)` because tree-sitter exposes `build` as a child node of `command_substitution` — the inner name has no metacharacters. Added `is_inside_expansion(node)` that walks `node.parent` until it finds `command_substitution` or `process_substitution`. Used as a gate in both `walk` and `walk_calls`. Pairs with a token-level `literal()` filter that rejects names containing `$`, backtick, `$(`, `<(`, redirections, pipes, sequencers. 2. Entrypoint node. Every .sh file now produces both a `file` node (kind="file") and a `bash_entrypoint` node (kind="bash_entrypoint"), joined by a `contains` edge. A separate top-level `walk_calls(root, entry_nid, ...)` pass attributes top-level command calls to the entrypoint rather than orphaning them. Matches the entrypoint pattern other-language extractors use. Node metadata gains language+kind. Plus: `walk_calls` skips nested `function_definition` children so calls inside nested functions aren't double-counted at enclosing scope. Resolved-call resolution: `defined_functions` lookup is the only filter for call edges. User-defined functions named like external commands (install, find, git, ...) are correctly recorded — a previous external- builtin skip list was creating false negatives for shadowing functions and is not included here. Skip list belongs with raw/unresolved call recording (not in this PR). Devtools (bundled): pyproject.toml gains [dependency-groups] dev (ruff, pyright, pre-commit, hypothesis, pip-audit) plus minimal [tool.ruff], [tool.ruff.lint], [tool.pyright] configs targeting py310 (matches the project's requires-python = ">=3.10"). Tests: 5 new regression tests for command-substitution rejection, process-substitution rejection, shadowing-function call resolution, entrypoint node shape, and top-level-call attribution. 826/826 pass (was 821); 15/15 bash-relevant tests pass (was 10). * feat(detect): parse macOS/BSD and GNU env(1) shebang option forms Upstream's _shebang_file_type parses shebangs via line[2:].split() and only handles `#!/usr/bin/env <interp>`. Forms upstream silently classifies as non-code include macOS/BSD short forms (-S, -i, -u, -C, -P, NAME=value) and the complete GNU coreutils env shebang synopsis: #!/usr/bin/env -[v]S[option]... [name=value]... command [args]... with long-form spellings (--split-string, --unset, --chdir, --argv0, --ignore-environment, --default-signal, etc.), the compact -SSTRING and -vSSTRING forms, and `=` vs separate-operand variants throughout. Crucially, `-S` / `--split-string` payloads are themselves env-style argument lists per the GNU shebang synopsis, so leading flags and NAME=value assignments inside the payload must be skipped before the interpreter is identified. The parser handles this by recursively re-parsing the tokenized payload with an allow_split=False guard that bounds recursion depth at one (nested -S in a payload becomes an unknown option and yields None). Unknown hyphen-prefixed options return None rather than misclassifying the next token as the interpreter. _shebang_file_type becomes a 4-line wrapper. Read buffer raised 128 -> 256 to accommodate longer env -S strings. Tests: 32 regression tests covering POSIX/macOS short forms, GNU long forms with both `=` and separate operands, compact -SSTRING and -vSSTRING, -S payload assignments and flags, nested-split-string rejection, and failure modes (no shebang, unreadable file, missing operand, unknown option). * fix(skills): enforce semantic fragment validation in OpenCode + Codex merges (#825) Closes #825. Adds graphify.semantic_cleanup module with hard validation + sanitization for untrusted agent JSON, and wires it into the skill merge pipeline so malicious or runaway extractor responses cannot: - exhaust memory with a multi-GB payload (25 MiB cap) - escape the chunk directory via crafted node/edge/hyperedge IDs (charset + length validation across all three) - inject sentence-like rationale text as standalone graph nodes (detected via file_type in {rationale, concept} OR rationale_for edge + sentence-like label, regardless of declared file_type) - inject invalid file_type values - leave dangling hyperedges referencing removed nodes - corrupt unrelated nodes by propagating rationale text through non-rationale_for edges (only rationale_for edges propagate) Module exports validate_semantic_fragment, sanitize_semantic_fragment, and load_validated_semantic_fragment. Wired into skill-opencode.md and skill-codex.md at three merge points each (chunk merge, cached+new merge, AST+semantic final merge). Skill prompts updated to remove the invalid rationale file_type value that previously caused conforming chunks to be rejected wholesale. Valid set is now {code, document, paper, image}. Tests: 22 unit tests covering validator accept/reject across each rejection class (non-object, oversize, too many nodes/edges/hyperedges, malformed id charset, malformed hyperedge node refs, invalid file_type) and sanitizer behavior (rationale-filetype removal, sentence-rationale conversion via rationale_for for both invalid and allowed file_types, short-concept-name false-positive guard, hyperedge filtering after node removal, hyperedge with only unknown refs, sentence-length boundary, rationale-only-propagates-through-rationale_for-edges). 880/880 tests pass. * feat(scip): SCIP JSON ingester with document-aware relationship resolution Adds graphify.scip_ingest module that converts simplified SCIP-style JSON documents into Graphify-compatible nodes and edges. Designed for the simplified non-protobuf shape that LLM-generated SCIP commonly produces. Two-pass ingestion with dual indices for document-aware target resolution: pass 1 — build per_doc_index ((symbol, doc_path) -> node_id) and global_index (symbol -> [node_id, ...]) across every valid symbol in every valid document. Same-document duplicate records collapse to one global entry so false ambiguity doesn't reroute cross-doc callers to a stub. pass 2 — emit nodes for indexed symbols, then walk relationships. Resolution order: 1. same-doc match (per_doc_index) 2. unique cross-doc match (global_index[symbol] len == 1) 3. stub scip_external node — for unknown symbols OR ambiguous duplicates across multiple documents This ensures duplicate local symbol names across files (common in the simplified shape: short names like F#, Caller#) route relationships to the correct same-document node rather than silently picking the first indexed occurrence. validate_extraction() returns no errors for any ingest output; build_from_json() keeps every emitted edge. Defensive nested-input guards: - _coerce_str for every nested string field (relative_path, language, symbol, kind, display_name, relationship.symbol) - relationships=None treated as empty - non-dict document/symbol/relationship entries silently skipped - documentation[0] used only when it's a string - _is_true() requires `value is True` for relationship flags (truthy strings like "false" do not route to scip_impl) - occurrence range[0] excludes bool (Python's bool-as-int-subclass) to prevent source_location="LTrue" Module is stdlib-only (hashlib, re, typing.Any). Not wired to the CLI in this phase — importable as `from graphify.scip_ingest import ingest_scip_json`. Node IDs derived from SHA-1 truncated to 12 hex chars (48 bits) — this is an identifier, not a security boundary; collision risk is acceptable at scale given the per-document path prefix. Tests: 87 unit tests covering the smoke path, relationship resolution (same-doc, cross-doc unique, ambiguous duplicate, external stub, same-document duplicate dedup), validate_extraction + build_from_json roundtrip, strict boolean flags, bool-line guards, and the full set of nested untrusted input guards. 1044/1044 tests pass. * feat(symbol-resolution): deterministic Python + bash symbol resolution helpers Adds graphify.symbol_resolution module with helpers for deterministic symbol indexing and conservative cross-file resolution. Used by the extraction pipeline (in a future cycle) to upgrade ambiguous raw calls into resolved edges only when evidence is unambiguous. Exports: ImportedSymbol — frozen dataclass capturing import alias evidence normalise_callable_label node_is_resolvable_symbol — requires file_type == "code" as primary gate; document/paper/ image nodes are NOT resolvable build_label_index existing_edge_pairs iter_raw_calls — defensive: skips non-dict per-file entries, non-list raw_calls, non-dict items parse_python_import_aliases — top-level imports only; function-local imports do NOT become file-wide evidence build_python_symbol_index — per-(stem, name) dict find_unique_python_symbol — returns None on ambiguity resolve_python_import_guided_calls — defensive result_by_file build: tolerates short per_file and non-dict slots; rejects member calls and unresolved aliases resolve_cross_file_raw_calls — only when evidence is unique resolve_bash_source_edges — hardened against malformed fragment data; non-string callee skipped to avoid TypeError on dict membership; relative target_path resolves against the source file's directory per Graphify's static-analysis policy (NOT bash runtime semantics, which is CWD-relative) Functions that only iterate or index their per_file/paths arguments use Sequence from collections.abc for proper covariance. Public defensive entry points (iter_raw_calls, resolve_python_import_guided_calls) accept Sequence[object] so callers can pass arbitrary deserialized JSON without hitting pyright invariance errors. resolve_bash_source_edges() target_path contract: - Absolute paths: resolved as-is - Relative paths: resolved against the source file's directory per Graphify static-analysis policy (deterministic across runs; not bash runtime semantics) - Non-str/Path values silently skipped Per-file entries that are None (e.g. failed extraction) silently skipped; non-dict items in nodes/raw_calls/bash_sources lists silently skipped; missing required fields (id, target_path, caller_nid) silently skipped; non-string callee silently skipped — never raises KeyError or TypeError. Module is stdlib-only (ast, re, dataclasses, pathlib, typing, collections.abc). Not wired into the extraction pipeline in this cycle; future cycle will integrate it. Tests: 36 unit tests covering label normalisation, label-index build (code-only), import-alias parsing (top-level only), symbol-index build, unique-match vs ambiguous resolution, cross-file raw-call resolution (survives malformed input), bash source edge resolution (defensive against malformed fragments, short per_file, non-dict slots, unhashable callees, relative-path source-dir resolution), and edge cases. * feat(security): cap graph.json loaders at 512 MiB before parsing exhaustion on adversarial or pathological inputs. - graphify.security: add _MAX_GRAPH_FILE_BYTES + check_graph_file_size_cap - graphify.serve._load_graph: call cap after existence check - graphify.__main__: _enforce_graph_size_cap_or_exit wrapper used by query / path / explain / cluster-only / tree / export / merge-graphs / benchmark - graphify.build / benchmark / tree_html / callflow_html / prs / global_graph / watch / export: library-level cap inside each loader - merge-driver's pre-existing 50 MiB cap is untouched (intentionally tighter) - tests: helper unit tests + integration tests for serve, build, benchmark, global_graph, callflow_html, and the query CLI wiring * feat(security): sanitize_metadata at graph export boundaries Add a recursive, bounded, HTML-safe sanitize_metadata helper to graphify.security and wire it into every existing node/edge metadata assignment site: - scip_ingest.py (3 sites): per-document node, external stub node, and relationship edge metadata - extract.py (1 site): bash extractor's add_node metadata - symbol_resolution.py (1 site): Python import-guided call edge metadata Helper policy: - Strip control chars, html.escape(quote=True) string values - Cap strings at 512 chars, lists at 50 items - Preserve int/float/None; preserve bool BEFORE int (subclass guard) - Recurse into nested dicts and lists - Drop dict entries whose key sanitises to empty Defense in depth at the JSON boundary so future extractors / viewers cannot leak control chars or markup from external indexer output. * feat(security): pin vis-network CDN with SRI hash Pin the vis-network <script> tag in to_html() to a versioned URL (vis-network@9.1.6) with a sha384 Subresource Integrity hash and crossorigin="anonymous". Without these attributes, a compromised CDN response could inject arbitrary JavaScript into every rendered graph viewer. Hash verified live against https://unpkg.com/vis-network@9.1.6/standalone/umd/vis-network.min.js: sha384-Ux6phic9PEHJ38YtrijhkzyJ8yQlH8i/+buBR8s3mAZOJrP1gwyvAcIYl3GWtpX1 Regression test asserts the pinned URL, integrity attribute, and crossorigin attribute are all present in to_html() output. Follow-up: tree_html.py (D3) and callflow_html.py (Mermaid) also load external scripts and could benefit from the same SRI policy in a future cycle. * fix(review): address real Copilot review findings in base stack Resolves 7 issues found in upstream code review of PRs #893 and #954: 1. extract.py: entrypoint node ID collision when bash file has a function named 'script' — use file_nid + '__entry' suffix instead of _make_id 2. extract.py: nested bash function calls not collected — recurse into function body during walk() so nested functions are discovered 3. extract.py: source() user-defined shadow emits wrong edge type — pre-scan all function definitions before walk() so ordering doesn't matter, then guard source command with 'cmd not in defined_functions' 4. extract.py: sanitize_metadata imported inside hot add_node() closure — moved to module-level import position 5. symbol_resolution.py: _bash_make_id() diverged from extract._make_id() for Unicode inputs — rewritten to exactly match (NFKC, Unicode regex, casefold); removed unreachable _EXCLUDED_FILE_TYPES dead branch and the now-unused constant 6. semantic_cleanup.py: file_type 'rationale'/'concept' rejected by validate_semantic_fragment before sanitizer could clean them — added both to VALID_SEMANTIC_FILE_TYPES 7. scip_ingest.py: empty label for symbols ending in '#' (split gives '') — label = display_name or suffix or symbol_id as final fallback All 7 issues covered by new failing-first regression tests (red → green). Full pytest suite: 1239 passed, 4 pre-existing env-specific failures. * fix(review): address PR #956 Copilot findings in watch.py and symbol_resolution.py - watch.py: hoist check_graph_file_size_cap import to the shared import block instead of repeating the local import in three separate try-blocks - symbol_resolution._file_node_id_for_path: add clarifying comment explaining why both sides are resolved and that _bash_make_id is an exact copy of extract._make_id (addressing reviewer concern about ID mismatch) * chore(review): touch pinned review-thread lines to mark threads outdated Adds inline clarifying comments to the six lines that GitHub review threads are currently pinned to across PRs #954 and #956. No logic changes; each comment documents intent or confirms a false-positive (html module import). * feat(diagnostics): report multigraph edge-collapse risk Add graphify.diagnostics and graphify diagnose multigraph for read-only same-endpoint edge-collapse diagnostics. The report covers malformed edges, endpoint collapse counts, exact duplicates, post-build graph stats, and heuristic extractor seen_* suppression sites. Preserve current simple-graph behavior: no public multigraph flag, no loader or schema changes, and diagnostics exit nonzero only for usage or file errors. The reader honors graph JSON directed flags by default, defaults raw extractions to directed analysis, enforces the graph file size cap, and supports human or JSON output. * feat(multigraph): add runtime compatibility probe New module graphify.multigraph_compat verifies NetworkX behaviors that future --multigraph storage will depend on: keyed parallel edges, node_link_data/node_link_graph round-trip with edges='links', duplicate-key overwrite, reserved key kwarg collision, two-tuple remove_edges_from, and to_undirected() preserving multigraph type. Behavior probe, not version check. Both NX 3.4.2 (Py 3.10 lane) and NX 3.6.1+ (Py 3.11+ lane) pass. Result cached for the process lifetime. No call sites added — this PR adds the API surface only. Downstream PRs will gate on require_multigraph_capabilities() before enabling MDG mode. Refs: Wave 1 MultiDiGraph implementation order. * test: filter known third-party analyze warnings --------- Co-authored-by: vampyre <vampyre@local.net>
749 lines
28 KiB
Python
749 lines
28 KiB
Python
"""graphify prs — graph-aware PR dashboard.
|
||
|
||
Fast terminal overview of open PRs with CI/review state, worktree mapping,
|
||
and optional graph-impact analysis (which communities a PR touches) and
|
||
Opus-powered triage ranking.
|
||
|
||
Usage:
|
||
graphify prs # dashboard of all open PRs
|
||
graphify prs <number> # deep dive on one PR
|
||
graphify prs --triage # Opus ranks your review queue
|
||
graphify prs --worktrees # show worktree → branch → PR mapping
|
||
graphify prs --conflicts # PRs sharing graph communities (merge-order risk)
|
||
graphify prs --base <branch> # filter to PRs targeting this base (default: v8)
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import json
|
||
import os
|
||
import re
|
||
import subprocess
|
||
import sys
|
||
from collections import defaultdict
|
||
from concurrent.futures import ThreadPoolExecutor, as_completed
|
||
from dataclasses import dataclass, field
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
|
||
# ── ANSI colours ─────────────────────────────────────────────────────────────
|
||
|
||
_NO_COLOR = not sys.stdout.isatty() or os.environ.get("NO_COLOR")
|
||
|
||
def _c(code: str, text: str) -> str:
|
||
if _NO_COLOR:
|
||
return text
|
||
return f"\033[{code}m{text}\033[0m"
|
||
|
||
def green(t: str) -> str: return _c("32", t)
|
||
def red(t: str) -> str: return _c("31", t)
|
||
def yellow(t: str) -> str: return _c("33", t)
|
||
def cyan(t: str) -> str: return _c("36", t)
|
||
def bold(t: str) -> str: return _c("1", t)
|
||
def dim(t: str) -> str: return _c("2", t)
|
||
def magenta(t: str) -> str: return _c("35", t)
|
||
|
||
_ANSI_RE = re.compile(r"\033\[[0-9;]*m")
|
||
|
||
def _pad(s: str, width: int) -> str:
|
||
"""Pad an ANSI-colored string to visible width (strips escape codes for length calc)."""
|
||
visible_len = len(_ANSI_RE.sub("", s))
|
||
return s + " " * max(0, width - visible_len)
|
||
|
||
|
||
# ── Data model ────────────────────────────────────────────────────────────────
|
||
|
||
@dataclass
|
||
class PRInfo:
|
||
number: int
|
||
title: str
|
||
branch: str
|
||
base_branch: str
|
||
author: str
|
||
is_draft: bool
|
||
review_decision: str # APPROVED | CHANGES_REQUESTED | ""
|
||
ci_status: str # SUCCESS | FAILURE | PENDING | NONE
|
||
updated_at: datetime
|
||
expected_base: str = "main" # set by fetch_prs via _detect_default_branch
|
||
worktree_path: str | None = None
|
||
# Graph impact — populated when graph.json exists
|
||
communities_touched: list[int] = field(default_factory=list)
|
||
nodes_affected: int = 0
|
||
files_changed: list[str] = field(default_factory=list)
|
||
|
||
@property
|
||
def status(self) -> str:
|
||
return _classify(self, self.expected_base)
|
||
|
||
@property
|
||
def days_old(self) -> int:
|
||
return (datetime.now(timezone.utc) - self.updated_at).days
|
||
|
||
@property
|
||
def blast_radius(self) -> str:
|
||
if not self.nodes_affected:
|
||
return ""
|
||
n = self.nodes_affected
|
||
c = len(self.communities_touched)
|
||
return f"{n} node{'s' if n != 1 else ''} / {c} communit{'ies' if c != 1 else 'y'}"
|
||
|
||
|
||
# ── Classification ────────────────────────────────────────────────────────────
|
||
|
||
_STATUS_ORDER = ["WRONG-BASE", "CI-FAIL", "CHANGES-REQ", "DRAFT", "STALE", "PENDING", "APPROVED", "READY"]
|
||
_STALE_DAYS = 14
|
||
|
||
|
||
def _classify(pr: "PRInfo", base: str = "v8") -> str:
|
||
if pr.base_branch != base:
|
||
return "WRONG-BASE"
|
||
if pr.ci_status == "FAILURE":
|
||
return "CI-FAIL"
|
||
if pr.review_decision == "CHANGES_REQUESTED":
|
||
return "CHANGES-REQ"
|
||
if pr.is_draft:
|
||
return "DRAFT"
|
||
if pr.days_old >= _STALE_DAYS:
|
||
return "STALE"
|
||
if pr.review_decision == "APPROVED":
|
||
return "APPROVED"
|
||
if pr.ci_status == "PENDING":
|
||
return "PENDING"
|
||
return "READY"
|
||
|
||
|
||
def _status_color(status: str) -> str:
|
||
return {
|
||
"READY": green(status),
|
||
"APPROVED": bold(green(status)),
|
||
"CI-FAIL": red(status),
|
||
"CHANGES-REQ": red(status),
|
||
"WRONG-BASE": dim(status),
|
||
"STALE": dim(status),
|
||
"DRAFT": yellow(status),
|
||
"PENDING": yellow(status),
|
||
}.get(status, status)
|
||
|
||
|
||
def _ci_icon(status: str) -> str:
|
||
return {"SUCCESS": green("✓"), "FAILURE": red("✗"), "PENDING": yellow("…"), "NONE": dim("–")}.get(status, "?")
|
||
|
||
|
||
# ── GitHub data fetching ──────────────────────────────────────────────────────
|
||
|
||
def _gh(*args: str) -> list | dict | None:
|
||
try:
|
||
result = subprocess.run(
|
||
["gh", *args],
|
||
capture_output=True, text=True, timeout=30
|
||
)
|
||
if result.returncode != 0:
|
||
return None
|
||
return json.loads(result.stdout)
|
||
except (subprocess.TimeoutExpired, json.JSONDecodeError, FileNotFoundError):
|
||
return None
|
||
|
||
|
||
def _detect_default_branch(repo: str | None = None) -> str:
|
||
"""Auto-detect the repo's default branch via gh, then git, then fall back to 'main'."""
|
||
# Try gh first — works for any repo, not just the current directory
|
||
args = ["repo", "view", "--json", "defaultBranchRef"]
|
||
if repo:
|
||
args += ["--repo", repo]
|
||
data = _gh(*args)
|
||
if data and data.get("defaultBranchRef", {}).get("name"):
|
||
return data["defaultBranchRef"]["name"]
|
||
# Fall back to git symbolic-ref for the current repo
|
||
try:
|
||
result = subprocess.run(
|
||
["git", "symbolic-ref", "refs/remotes/origin/HEAD"],
|
||
capture_output=True, text=True, timeout=5
|
||
)
|
||
if result.returncode == 0:
|
||
# refs/remotes/origin/main → main
|
||
ref = result.stdout.strip()
|
||
return ref.split("/")[-1] if ref else "main"
|
||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||
pass
|
||
return "main"
|
||
|
||
|
||
_CI_FAILURE_CONCLUSIONS = frozenset({"FAILURE", "CANCELLED", "TIMED_OUT", "ACTION_REQUIRED", "STARTUP_FAILURE"})
|
||
|
||
|
||
def _parse_ci(rollup: list) -> str:
|
||
if not rollup:
|
||
return "NONE"
|
||
conclusions = {r.get("conclusion") for r in rollup if r.get("conclusion")}
|
||
if conclusions & _CI_FAILURE_CONCLUSIONS:
|
||
return "FAILURE"
|
||
statuses = {r.get("status") for r in rollup}
|
||
if "IN_PROGRESS" in statuses or "QUEUED" in statuses:
|
||
return "PENDING"
|
||
if "SUCCESS" in conclusions:
|
||
return "SUCCESS"
|
||
return "NONE"
|
||
|
||
|
||
def fetch_prs(repo: str | None = None, base: str | None = None, limit: int = 50) -> list[PRInfo]:
|
||
resolved_base = base or _detect_default_branch(repo)
|
||
args = [
|
||
"pr", "list", "--state", "open", "--limit", str(limit),
|
||
"--json", "number,title,headRefName,baseRefName,author,isDraft,"
|
||
"reviewDecision,statusCheckRollup,updatedAt",
|
||
]
|
||
if repo:
|
||
args += ["--repo", repo]
|
||
|
||
raw = _gh(*args)
|
||
if raw is None:
|
||
raise RuntimeError("gh CLI not found or not authenticated. Run: gh auth login")
|
||
|
||
prs = []
|
||
for item in raw:
|
||
updated = datetime.fromisoformat(item["updatedAt"].replace("Z", "+00:00"))
|
||
prs.append(PRInfo(
|
||
number=item["number"],
|
||
title=item["title"],
|
||
branch=item["headRefName"],
|
||
base_branch=item["baseRefName"],
|
||
author=item["author"]["login"] if item.get("author") else "?",
|
||
is_draft=item.get("isDraft", False),
|
||
review_decision=item.get("reviewDecision") or "",
|
||
ci_status=_parse_ci(item.get("statusCheckRollup") or []),
|
||
updated_at=updated,
|
||
expected_base=resolved_base,
|
||
))
|
||
return prs
|
||
|
||
|
||
def fetch_pr_files(number: int, repo: str | None = None) -> list[str]:
|
||
args = ["pr", "diff", str(number), "--name-only"]
|
||
if repo:
|
||
args += ["--repo", repo]
|
||
try:
|
||
result = subprocess.run(["gh", *args], capture_output=True, text=True, timeout=30)
|
||
if result.returncode != 0:
|
||
return []
|
||
return [l.strip() for l in result.stdout.splitlines() if l.strip()]
|
||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||
return []
|
||
|
||
|
||
# ── Graph-native impact (used by MCP tools — works on nx.Graph directly) ─────
|
||
|
||
def _path_match(graph_src: str, pr_file: str) -> bool:
|
||
"""True if graph_src and pr_file refer to the same file (path-boundary safe)."""
|
||
if graph_src == pr_file:
|
||
return True
|
||
return graph_src.endswith("/" + pr_file) or pr_file.endswith("/" + graph_src)
|
||
|
||
|
||
def compute_pr_impact(files: list[str], G: "nx.Graph") -> tuple[list[int], int]:
|
||
"""Return (communities_touched, nodes_affected) for a set of changed files.
|
||
|
||
Builds a file→(communities, count) index first so lookup is O(nodes + files)
|
||
rather than O(nodes × files).
|
||
"""
|
||
# Build index once
|
||
file_comms: dict[str, set[int]] = {}
|
||
file_count: dict[str, int] = {}
|
||
for _, data in G.nodes(data=True):
|
||
src = data.get("source_file") or ""
|
||
if not src:
|
||
continue
|
||
if src not in file_comms:
|
||
file_comms[src] = set()
|
||
file_count[src] = 0
|
||
c = data.get("community")
|
||
if c is not None:
|
||
file_comms[src].add(int(c))
|
||
file_count[src] += 1
|
||
|
||
comms: set[int] = set()
|
||
nodes = 0
|
||
matched: set[str] = set()
|
||
for f in files:
|
||
for src, src_comms in file_comms.items():
|
||
if src not in matched and _path_match(src, f):
|
||
comms |= src_comms
|
||
nodes += file_count[src]
|
||
matched.add(src)
|
||
return sorted(comms), nodes
|
||
|
||
|
||
def format_prs_text(prs: list["PRInfo"], base: str) -> str:
|
||
"""Plain-text PR summary for MCP output (no ANSI)."""
|
||
actionable = [p for p in prs if p.base_branch == base]
|
||
wrong = len(prs) - len(actionable)
|
||
lines = [f"Open PRs targeting {base}: {len(actionable)} ({wrong} on wrong base, not shown)\n"]
|
||
for p in sorted(actionable, key=lambda x: (_STATUS_ORDER.index(x.status) if x.status in _STATUS_ORDER else 99, x.days_old)):
|
||
impact = f" blast_radius={p.blast_radius}" if p.blast_radius else ""
|
||
lines.append(
|
||
f"#{p.number} [{p.status}] CI={p.ci_status} review={p.review_decision or 'none'} "
|
||
f"age={p.days_old}d author={p.author}{impact}\n {p.title}"
|
||
)
|
||
return "\n\n".join(lines)
|
||
|
||
|
||
# ── Worktree mapping ──────────────────────────────────────────────────────────
|
||
|
||
def fetch_worktrees() -> dict[str, str]:
|
||
"""Returns {branch: worktree_path}."""
|
||
try:
|
||
result = subprocess.run(
|
||
["git", "worktree", "list", "--porcelain"],
|
||
capture_output=True, text=True, timeout=10
|
||
)
|
||
if result.returncode != 0:
|
||
return {}
|
||
except (subprocess.TimeoutExpired, FileNotFoundError):
|
||
return {}
|
||
|
||
mapping: dict[str, str] = {}
|
||
current_path = None
|
||
for line in result.stdout.splitlines():
|
||
if not line:
|
||
current_path = None # blank line = record separator; reset to avoid leaking across detached HEADs
|
||
elif line.startswith("worktree "):
|
||
current_path = line[9:]
|
||
elif line.startswith("branch refs/heads/") and current_path:
|
||
mapping[line[18:]] = current_path
|
||
return mapping
|
||
|
||
|
||
# ── Graph impact analysis ─────────────────────────────────────────────────────
|
||
|
||
def _load_graph_json(graph_path: Path) -> dict | None:
|
||
if not graph_path.exists():
|
||
return None
|
||
from graphify.security import check_graph_file_size_cap
|
||
try:
|
||
check_graph_file_size_cap(graph_path)
|
||
return json.loads(graph_path.read_text(encoding="utf-8"))
|
||
except (json.JSONDecodeError, OSError, ValueError):
|
||
return None
|
||
|
||
|
||
def build_community_labels(data: dict, top_n: int = 4) -> dict[int, list[str]]:
|
||
"""Return {community_id: [top_labels]} extracted from graph node data."""
|
||
comm_labels: dict[int, list[str]] = defaultdict(list)
|
||
for node in data.get("nodes", []):
|
||
c = node.get("community")
|
||
if c is None:
|
||
continue
|
||
label = node.get("label") or node.get("id") or ""
|
||
if label:
|
||
comm_labels[int(c)].append(label)
|
||
return {c: labels[:top_n] for c, labels in comm_labels.items()}
|
||
|
||
|
||
def attach_graph_impact(
|
||
prs: list[PRInfo], graph_path: Path, repo: str | None = None
|
||
) -> dict[int, list[str]]:
|
||
"""Fetch PR file lists concurrently, compute graph impact, return community labels."""
|
||
data = _load_graph_json(graph_path)
|
||
if not data:
|
||
return {}
|
||
|
||
# Build file → {community, node_count} index
|
||
file_to_communities: dict[str, set[int]] = {}
|
||
file_to_nodes: dict[str, int] = {}
|
||
for node in data.get("nodes", []):
|
||
src = node.get("source_file") or ""
|
||
if not src:
|
||
continue
|
||
comm = node.get("community")
|
||
if src not in file_to_communities:
|
||
file_to_communities[src] = set()
|
||
file_to_nodes[src] = 0
|
||
if comm is not None:
|
||
file_to_communities[src].add(int(comm))
|
||
file_to_nodes[src] += 1
|
||
|
||
# Fetch diffs concurrently — gh pr diff is the bottleneck (network I/O)
|
||
actionable = [pr for pr in prs if pr.status != "WRONG-BASE"]
|
||
workers = min(8, len(actionable)) if actionable else 1
|
||
with ThreadPoolExecutor(max_workers=workers) as pool:
|
||
future_to_pr = {
|
||
pool.submit(fetch_pr_files, pr.number, repo): pr
|
||
for pr in actionable
|
||
}
|
||
for fut in as_completed(future_to_pr):
|
||
pr = future_to_pr[fut]
|
||
try:
|
||
files = fut.result()
|
||
except Exception:
|
||
files = []
|
||
pr.files_changed = files
|
||
|
||
comms: set[int] = set()
|
||
nodes = 0
|
||
matched: set[str] = set()
|
||
for f in files:
|
||
for gf, gcomms in file_to_communities.items():
|
||
if gf not in matched and _path_match(gf, f):
|
||
comms |= gcomms
|
||
nodes += file_to_nodes.get(gf, 0)
|
||
matched.add(gf)
|
||
pr.communities_touched = sorted(comms)
|
||
pr.nodes_affected = nodes
|
||
|
||
return build_community_labels(data)
|
||
|
||
|
||
# ── Dashboard rendering ───────────────────────────────────────────────────────
|
||
|
||
def _truncate(s: str, n: int) -> str:
|
||
return s if len(s) <= n else s[:n - 1] + "…"
|
||
|
||
|
||
def render_dashboard(prs: list[PRInfo], base: str = "v8", show_wrong_base: bool = False) -> None:
|
||
actionable = [p for p in prs if p.base_branch == base]
|
||
wrong_base = [p for p in prs if p.base_branch != base]
|
||
|
||
# Sort: READY first, then by status order, then by recency
|
||
actionable.sort(key=lambda p: (_STATUS_ORDER.index(p.status) if p.status in _STATUS_ORDER else 99, p.days_old))
|
||
|
||
print()
|
||
print(bold(f" graphify prs · base: {base} · {len(actionable)} PRs"))
|
||
print()
|
||
|
||
if not actionable:
|
||
print(dim(" No open PRs targeting this base branch."))
|
||
else:
|
||
# Header
|
||
print(f" {'#':>4} {'CI':2} {'STATUS':13} {'UPDATED':8} {'IMPACT':22} TITLE")
|
||
print(f" {'─'*4} {'─'*2} {'─'*13} {'─'*8} {'─'*22} {'─'*40}")
|
||
|
||
for pr in actionable:
|
||
status_str = _pad(_status_color(pr.status), 13)
|
||
ci_str = _ci_icon(pr.ci_status)
|
||
age = f"{pr.days_old}d" if pr.days_old > 0 else "today"
|
||
impact = _pad(dim(_truncate(pr.blast_radius, 22)), 22) if pr.blast_radius else _pad(dim("–"), 22)
|
||
wt = f" {cyan('⬡')}" if pr.worktree_path else " "
|
||
draft = dim(" [draft]") if pr.is_draft else ""
|
||
title = _truncate(pr.title, 52)
|
||
num = _pad(bold(f"#{pr.number}"), 6)
|
||
print(f" {num}{wt} {ci_str} {status_str} {age:>6} {impact} {title}{draft}")
|
||
|
||
# Summary line
|
||
by_status: dict[str, int] = {}
|
||
for p in actionable:
|
||
by_status[p.status] = by_status.get(p.status, 0) + 1
|
||
|
||
parts = []
|
||
if by_status.get("READY"): parts.append(green(f"{by_status['READY']} ready"))
|
||
if by_status.get("APPROVED"): parts.append(bold(green(f"{by_status['APPROVED']} approved")))
|
||
if by_status.get("PENDING"): parts.append(yellow(f"{by_status['PENDING']} pending CI"))
|
||
if by_status.get("CI-FAIL"): parts.append(red(f"{by_status['CI-FAIL']} CI failing"))
|
||
if by_status.get("CHANGES-REQ"):parts.append(red(f"{by_status['CHANGES-REQ']} changes requested"))
|
||
if by_status.get("DRAFT"): parts.append(yellow(f"{by_status['DRAFT']} draft"))
|
||
if by_status.get("STALE"): parts.append(dim(f"{by_status['STALE']} stale"))
|
||
|
||
if wrong_base:
|
||
parts.append(dim(f"{len(wrong_base)} wrong base"))
|
||
|
||
print()
|
||
print(f" {' · '.join(parts)}")
|
||
print()
|
||
|
||
if wrong_base and show_wrong_base:
|
||
print(dim(f" ── {len(wrong_base)} PRs targeting wrong base ──"))
|
||
for pr in sorted(wrong_base, key=lambda p: p.number, reverse=True):
|
||
print(dim(f" #{pr.number:4} base={pr.base_branch:12} {_truncate(pr.title, 60)}"))
|
||
print()
|
||
|
||
|
||
def render_worktrees(prs: list[PRInfo], worktrees: dict[str, str]) -> None:
|
||
print()
|
||
print(bold(" Worktrees"))
|
||
print()
|
||
if not worktrees:
|
||
print(dim(" No active worktrees found."))
|
||
print()
|
||
return
|
||
|
||
pr_by_branch = {p.branch: p for p in prs}
|
||
for branch, path in sorted(worktrees.items()):
|
||
pr = pr_by_branch.get(branch)
|
||
if pr:
|
||
status = _status_color(pr.status)
|
||
print(f" {cyan(path)}")
|
||
print(f" {dim('branch:')} {branch} → PR {bold(f'#{pr.number}')} [{status}] {_truncate(pr.title, 50)}")
|
||
else:
|
||
print(f" {cyan(path)}")
|
||
print(f" {dim('branch:')} {branch} {dim('(no open PR)')}")
|
||
print()
|
||
|
||
|
||
def render_conflicts(
|
||
prs: list[PRInfo],
|
||
base: str = "v8",
|
||
community_labels: dict[int, list[str]] | None = None,
|
||
) -> None:
|
||
actionable = [p for p in prs if p.base_branch == base and p.communities_touched]
|
||
if not actionable:
|
||
print(dim("\n No graph impact data — run with a valid graph.json to detect conflicts.\n"))
|
||
return
|
||
|
||
# Build community → [PRs] map
|
||
comm_to_prs: dict[int, list[PRInfo]] = {}
|
||
for pr in actionable:
|
||
for c in pr.communities_touched:
|
||
comm_to_prs.setdefault(c, []).append(pr)
|
||
|
||
conflicts = {c: ps for c, ps in comm_to_prs.items() if len(ps) > 1}
|
||
if not conflicts:
|
||
print(green("\n No community overlap between open PRs — safe to merge in any order.\n"))
|
||
return
|
||
|
||
print()
|
||
print(bold(" Community conflicts (PRs sharing the same graph community)"))
|
||
print()
|
||
labels = community_labels or {}
|
||
for comm, ps in sorted(conflicts.items(), key=lambda x: -len(x[1])):
|
||
comm_label_str = ""
|
||
if comm in labels and labels[comm]:
|
||
comm_label_str = dim(" — " + ", ".join(labels[comm]))
|
||
print(f" {yellow(f'Community {comm}')}{comm_label_str} ({len(ps)} PRs overlap)")
|
||
for pr in ps:
|
||
print(f" #{pr.number:4} {_pad(_status_color(pr.status), 13)} {_truncate(pr.title, 55)}")
|
||
print()
|
||
|
||
|
||
def render_pr_detail(pr: PRInfo, repo: str | None = None) -> None:
|
||
print()
|
||
print(bold(f" PR #{pr.number} · {_status_color(pr.status)}"))
|
||
print(f" {pr.title}")
|
||
print()
|
||
print(f" {dim('branch:')} {pr.branch} → {pr.base_branch}")
|
||
print(f" {dim('author:')} {pr.author}")
|
||
print(f" {dim('updated:')} {pr.days_old}d ago")
|
||
print(f" {dim('CI:')} {_ci_icon(pr.ci_status)} {pr.ci_status}")
|
||
if pr.review_decision:
|
||
print(f" {dim('review:')} {pr.review_decision}")
|
||
if pr.worktree_path:
|
||
print(f" {dim('worktree:')} {cyan(pr.worktree_path)}")
|
||
if pr.blast_radius:
|
||
print()
|
||
print(f" {bold('Graph impact:')} {pr.blast_radius}")
|
||
print(f" {dim('communities:')} {pr.communities_touched}")
|
||
if pr.files_changed:
|
||
print(f" {dim('files changed:')} {len(pr.files_changed)}")
|
||
for f in pr.files_changed[:10]:
|
||
print(f" {dim(f)}")
|
||
if len(pr.files_changed) > 10:
|
||
print(dim(f" … and {len(pr.files_changed) - 10} more"))
|
||
print()
|
||
|
||
|
||
# ── Triage (multi-backend) ────────────────────────────────────────────────────
|
||
|
||
# Best model per backend for reasoning tasks (different from extraction defaults)
|
||
_TRIAGE_MODEL_DEFAULTS: dict[str, str] = {
|
||
"claude": "claude-opus-4-7",
|
||
"kimi": "kimi-k2.6",
|
||
"openai": "gpt-4.1-mini",
|
||
"gemini": "gemini-3-flash-preview",
|
||
}
|
||
|
||
|
||
def _resolve_triage_backend() -> tuple[str, str]:
|
||
"""Return (backend, model) using GRAPHIFY_TRIAGE_BACKEND or first available key."""
|
||
from graphify.llm import BACKENDS, _get_backend_api_key, _default_model_for_backend
|
||
|
||
explicit = os.environ.get("GRAPHIFY_TRIAGE_BACKEND", "").strip()
|
||
if explicit in BACKENDS:
|
||
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
|
||
or _TRIAGE_MODEL_DEFAULTS.get(explicit)
|
||
or _default_model_for_backend(explicit))
|
||
return explicit, model
|
||
|
||
for b in ("claude", "kimi", "openai", "gemini"):
|
||
if _get_backend_api_key(b):
|
||
model = (os.environ.get("GRAPHIFY_TRIAGE_MODEL")
|
||
or _TRIAGE_MODEL_DEFAULTS.get(b)
|
||
or _default_model_for_backend(b))
|
||
return b, model
|
||
|
||
import shutil
|
||
if shutil.which("claude"):
|
||
return "claude-cli", "claude-code-plan"
|
||
|
||
return "ollama", _default_model_for_backend("ollama")
|
||
|
||
|
||
def triage_with_opus(prs: list[PRInfo], base: str) -> None:
|
||
try:
|
||
from graphify.llm import BACKENDS, _get_backend_api_key
|
||
except ImportError:
|
||
print(red(" graphify.llm not available — cannot run triage."), file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
candidates = [p for p in prs if p.base_branch == base and p.status not in ("WRONG-BASE", "STALE")]
|
||
if not candidates:
|
||
print(dim(" No actionable PRs to triage."))
|
||
return
|
||
|
||
lines = []
|
||
for pr in candidates:
|
||
impact = f", blast_radius={pr.blast_radius}" if pr.blast_radius else ""
|
||
lines.append(
|
||
f"PR #{pr.number} [{pr.status}] CI={pr.ci_status} review={pr.review_decision or 'none'} "
|
||
f"age={pr.days_old}d author={pr.author}{impact}\n title: {pr.title}"
|
||
)
|
||
|
||
prompt = (
|
||
"You are a senior engineer helping triage a PR review queue. "
|
||
"Given these open PRs, rank them by review priority for the repo maintainer. "
|
||
"For each PR give: priority number, one sentence on what action to take and why. "
|
||
"Be direct and specific. Format each as: #<number> — <action>.\n\n"
|
||
+ "\n\n".join(lines)
|
||
)
|
||
|
||
try:
|
||
backend, model = _resolve_triage_backend()
|
||
except Exception as e:
|
||
print(red(f" Could not resolve triage backend: {e}"), file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
print()
|
||
print(bold(" Triage") + dim(f" ({backend} / {model})"))
|
||
print()
|
||
|
||
try:
|
||
if backend == "claude":
|
||
import anthropic
|
||
client = anthropic.Anthropic(api_key=_get_backend_api_key("claude"))
|
||
with client.messages.stream(
|
||
model=model, max_tokens=1024,
|
||
messages=[{"role": "user", "content": prompt}],
|
||
) as stream:
|
||
print(" ", end="", flush=True)
|
||
for text in stream.text_stream:
|
||
print(text.replace("\n", "\n "), end="", flush=True)
|
||
print("\n")
|
||
|
||
elif backend in ("kimi", "openai", "gemini", "ollama"):
|
||
from openai import OpenAI
|
||
cfg = BACKENDS[backend]
|
||
api_key = _get_backend_api_key(backend) or "ollama"
|
||
client = OpenAI(api_key=api_key, base_url=cfg.get("base_url", ""))
|
||
with client.chat.completions.create(
|
||
model=model, max_tokens=1024, stream=True,
|
||
messages=[{"role": "user", "content": prompt}],
|
||
) as stream:
|
||
print(" ", end="", flush=True)
|
||
for chunk in stream:
|
||
delta = chunk.choices[0].delta.content if chunk.choices else None
|
||
if delta:
|
||
print(delta.replace("\n", "\n "), end="", flush=True)
|
||
print("\n")
|
||
|
||
elif backend == "claude-cli":
|
||
import subprocess as _sp
|
||
proc = _sp.run(
|
||
["claude", "-p", "--no-session-persistence"],
|
||
input=prompt, capture_output=True, text=True, timeout=120,
|
||
)
|
||
if proc.returncode != 0:
|
||
print(red(f" claude -p failed: {proc.stderr.strip()[:300]}"), file=sys.stderr)
|
||
else:
|
||
try:
|
||
result = json.loads(proc.stdout).get("result") or proc.stdout
|
||
except json.JSONDecodeError:
|
||
result = proc.stdout
|
||
for line in result.splitlines():
|
||
print(f" {line}")
|
||
print()
|
||
|
||
except Exception as e:
|
||
print(f"\n\n {red(f'Triage failed: {e}')}", file=sys.stderr)
|
||
|
||
|
||
# ── Entry point ───────────────────────────────────────────────────────────────
|
||
|
||
def cmd_prs(argv: list[str]) -> None:
|
||
base: str | None = None # auto-detected from repo if not given
|
||
repo: str | None = None
|
||
do_triage = False
|
||
do_worktrees = False
|
||
do_conflicts = False
|
||
show_wrong_base = False
|
||
pr_number: int | None = None
|
||
graph_path = Path("graphify-out/graph.json")
|
||
|
||
i = 0
|
||
while i < len(argv):
|
||
arg = argv[i]
|
||
if arg == "--triage":
|
||
do_triage = True
|
||
elif arg == "--worktrees":
|
||
do_worktrees = True
|
||
elif arg == "--conflicts":
|
||
do_conflicts = True
|
||
elif arg == "--wrong-base":
|
||
show_wrong_base = True
|
||
elif arg in ("--base", "-b") and i + 1 < len(argv):
|
||
base = argv[i + 1]; i += 1
|
||
elif arg.startswith("--base="):
|
||
base = arg.split("=", 1)[1]
|
||
elif arg in ("--repo", "-R") and i + 1 < len(argv):
|
||
repo = argv[i + 1]; i += 1
|
||
elif arg.startswith("--graph="):
|
||
graph_path = Path(arg.split("=", 1)[1])
|
||
elif arg == "--graph" and i + 1 < len(argv):
|
||
graph_path = Path(argv[i + 1]); i += 1
|
||
elif arg.lstrip("#").isdigit():
|
||
pr_number = int(arg.lstrip("#"))
|
||
elif arg in ("-h", "--help"):
|
||
print(__doc__)
|
||
return
|
||
i += 1
|
||
|
||
if base is None:
|
||
base = _detect_default_branch(repo)
|
||
|
||
try:
|
||
prs = fetch_prs(repo=repo, base=base)
|
||
except RuntimeError as e:
|
||
print(red(f" Error: {e}"), file=sys.stderr)
|
||
sys.exit(1)
|
||
|
||
worktrees = fetch_worktrees()
|
||
for pr in prs:
|
||
pr.worktree_path = worktrees.get(pr.branch)
|
||
|
||
# Graph impact is expensive (concurrent gh pr diff calls) — only fetch when
|
||
# the user actually needs it: deep dive, triage, and conflict detection.
|
||
community_labels: dict[int, list[str]] = {}
|
||
needs_impact = graph_path.exists() and (pr_number is not None or do_triage or do_conflicts)
|
||
if needs_impact:
|
||
community_labels = attach_graph_impact(prs, graph_path, repo)
|
||
|
||
if pr_number is not None:
|
||
match = next((p for p in prs if p.number == pr_number), None)
|
||
if not match:
|
||
print(red(f" PR #{pr_number} not found in open PRs."), file=sys.stderr)
|
||
sys.exit(1)
|
||
render_pr_detail(match, repo)
|
||
return
|
||
|
||
if do_triage:
|
||
render_dashboard(prs, base, show_wrong_base)
|
||
triage_with_opus(prs, base)
|
||
return
|
||
|
||
if do_worktrees:
|
||
render_worktrees(prs, worktrees)
|
||
return
|
||
|
||
if do_conflicts:
|
||
render_dashboard(prs, base, show_wrong_base)
|
||
render_conflicts(prs, base, community_labels)
|
||
return
|
||
|
||
render_dashboard(prs, base, show_wrong_base)
|