repo stringclasses 454
values | file_path stringlengths 5 201 | extension stringclasses 1
value | content stringlengths 8 509k | num_lines int64 3 16.9k | size_bytes int64 8 511k |
|---|---|---|---|---|---|
code-review-graph | tests/fixtures/sample_map_dispatch.py | .py | # Fixture for testing REFERENCES edge extraction in Python map dispatch patterns.
def handle_create(data):
print("create", data)
def handle_update(data):
print("update", data)
def handle_delete(data):
print("delete", data)
def validate_input(data):
return data is not None
def process_data(data... | 48 | 838 |
code-review-graph | scripts/render_pr_comment.py | .py | #!/usr/bin/env python3
"""Render a risk-scored PR comment from ``code-review-graph detect-changes`` JSON.
Reads the JSON document printed by ``code-review-graph detect-changes
--base <ref>`` (the full, non ``--brief`` output) and emits GitHub-flavoured
markdown suitable for a sticky pull-request comment. Also implemen... | 389 | 13,054 |
code-review-graph | scripts/diagnose_pypi_connectivity.py | .py | #!/usr/bin/env python3
"""Check whether this Python can reach PyPI (same path pip/pipx use for hatchling, etc.).
If TLS to pypi.org fails (e.g. Errno 9 in some IDE terminals), a user-wide
install from a git checkout may still work via uv (different downloader):
uv tool install /path/to/code-review-graph --force
Ru... | 64 | 2,012 |
code-review-graph | code_review_graph/wiki.py | .py | """Wiki generation from community structure.
Generates markdown pages for each detected community and an index page,
providing a navigable documentation wiki for the codebase architecture.
"""
from __future__ import annotations
import logging
import re
import sqlite3
import unicodedata
from collections import Counte... | 309 | 10,610 |
code-review-graph | code_review_graph/graph_diff.py | .py | """Graph snapshot diffing -- compare graph state over time."""
from __future__ import annotations
import json
import logging
from pathlib import Path
from typing import Any
from .graph import GraphStore
logger = logging.getLogger(__name__)
def take_snapshot(store: GraphStore) -> dict[str, Any]:
"""Take a snap... | 123 | 3,628 |
code-review-graph | code_review_graph/uninstall.py | .py | """Safely reverse artifacts created by :mod:`code_review_graph.skills`.
The original implementation was contributed by Stephen Cheng in PR #491.
This current-main replacement keeps that command/report design while deriving
the live MCP inventory from ``skills.PLATFORMS`` and treating every shared file
as user-owned da... | 1,319 | 42,021 |
code-review-graph | code_review_graph/forget.py | .py | """Forget parsed files from the graph while keeping every derived layer sane.
Dropping a file's own nodes and edges is not enough to match the graph a full
rebuild without that file would produce:
* surviving files that referenced it keep dangling, still-qualified edges
(a call resolved to ``other.py::helper`` stay... | 175 | 7,071 |
code-review-graph | code_review_graph/migrations.py | .py | """Schema migration framework for the code-review-graph SQLite database.
Manages incremental schema changes via versioned migration functions.
Each migration is idempotent (uses IF NOT EXISTS / column existence checks).
"""
from __future__ import annotations
import logging
import sqlite3
from typing import Callable
... | 285 | 9,970 |
code-review-graph | code_review_graph/main.py | .py | """MCP server entry point for Code Review Graph.
Run as: code-review-graph serve
Communicates via stdio (standard MCP transport), or use
``code-review-graph serve --http`` for Streamable HTTP on localhost (port 5555
by default). The HTTP transport validates ``Host`` and ``Origin`` so the loopback
endpoint cannot be dr... | 1,173 | 43,653 |
code-review-graph | code_review_graph/changes.py | .py | """Change impact analysis for code review.
Maps git/svn diffs to affected functions, flows, communities, and test coverage
gaps. Produces risk-scored, priority-ordered review guidance.
"""
from __future__ import annotations
import logging
import os
import re
import subprocess
from pathlib import Path
from typing imp... | 532 | 19,115 |
code-review-graph | code_review_graph/temporal_resolver.py | .py | """Post-build Temporal workflow/activity call resolver.
After tree-sitter parsing, Java CALLS edges whose target is a bare method
name carry ``extra.receiver`` naming the local variable called on. This
module resolves those receivers through the TEMPORAL_STUB map to their
declared Temporal interface type, then option... | 205 | 8,267 |
code-review-graph | code_review_graph/analysis.py | .py | """Graph analysis: hub detection, bridge nodes, knowledge gaps,
surprise scoring, suggested questions."""
from __future__ import annotations
import logging
from collections import Counter, defaultdict
from .graph import GraphStore, _sanitize_name
logger = logging.getLogger(__name__)
def find_hub_nodes(store: Grap... | 411 | 13,248 |
code-review-graph | code_review_graph/http_origin_guard.py | .py | """Host/Origin validation for the opt-in ``serve --http`` MCP endpoint.
``code-review-graph serve --http`` starts a FastMCP streamable-http server bound
to loopback (127.0.0.1:5555 by default). A loopback bind is not by itself an
access control for a browser: a page the user visits can point a hostname it
controls at ... | 213 | 7,417 |
code-review-graph | code_review_graph/config_keys.py | .py | """Shared, value-free handling for Spring configuration property keys."""
from __future__ import annotations
import re
from pathlib import Path
_SPRING_CONFIG_NAME = re.compile(
r"^application(?:-[A-Za-z0-9_.-]+)?\.(?:properties|ya?ml)$",
re.IGNORECASE,
)
def is_spring_config_path(path: Path) -> bool:
... | 34 | 1,235 |
code-review-graph | code_review_graph/event_resolver.py | .py | """Resolve Spring application-event publishers to package-matched listeners."""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
from .parser import EdgeInfo, NodeInfo
if TYPE_CHECKING:
from .graph import GraphStore
logger = logging.getLogger(__name__)
_EVENT_NODE... | 123 | 4,329 |
code-review-graph | code_review_graph/jedi_resolver.py | .py | """Post-build Jedi enrichment for Python call resolution.
After tree-sitter parsing, many method calls on lowercase-receiver variables
are dropped (e.g. ``svc.authenticate()`` where ``svc = factory()``). Jedi
can resolve these by tracing return types across files.
This module runs as a post-build step: it re-walks P... | 304 | 10,560 |
code-review-graph | code_review_graph/visualization.py | .py | """Interactive D3.js graph visualization for code knowledge graphs.
Exports graph data to JSON and generates a self-contained HTML file with
a force-directed D3.js visualization. Dark theme, zoomable, draggable,
with collapsible file clusters, tooltips, legend, and stats bar.
Supports multiple rendering modes for lar... | 2,356 | 104,432 |
code-review-graph | code_review_graph/refactor.py | .py | """Graph-powered refactoring operations.
Provides rename previews, dead code detection, refactoring suggestions,
and safe application of refactoring edits to source files. All file writes
go through a preview-then-apply workflow with expiry enforcement and path
traversal prevention.
"""
from __future__ import annotat... | 890 | 36,357 |
code-review-graph | code_review_graph/tsconfig_resolver.py | .py | """TypeScript tsconfig.json / jsconfig.json path alias resolver.
Resolves TypeScript path aliases (e.g., ``@/ -> src/``) declared in
``compilerOptions.paths`` so that ``IMPORTS_FROM`` edges can point to
real file paths instead of raw alias strings. Plain-JS projects (Vue,
Nuxt, Vite) declare the same aliases in ``jsco... | 267 | 9,647 |
code-review-graph | code_review_graph/postprocessing.py | .py | """Shared post-build processing pipeline.
After the core Tree-sitter parse (full_build or incremental_update), five
post-processing steps must run to populate derived tables:
1. Resolve evidence-backed bare edge endpoints
2. Compute node signatures
3. Rebuild FTS5 search index
4. Trace execution flows
5. Detect code ... | 204 | 6,391 |
code-review-graph | code_review_graph/__main__.py | .py | """Allow running as: python -m code_review_graph"""
from .cli import main
main()
| 5 | 82 |
code-review-graph | code_review_graph/__init__.py | .py | """Code Review Graph - MCP server for persistent incremental code knowledge graphs."""
from .context_savings import (
attach_context_savings,
estimate_context_savings,
estimate_file_tokens,
estimate_tokens,
format_context_savings,
)
__version__ = "2.3.7"
__all__ = [
"__version__",
"attach... | 21 | 454 |
code-review-graph | code_review_graph/token_benchmark.py | .py | """Token reduction benchmark -- measures graph query efficiency vs naive file reading."""
from __future__ import annotations
import logging
import sqlite3
from pathlib import Path
from typing import Any
from .graph import GraphStore
from .search import hybrid_search
logger = logging.getLogger(__name__)
# Sample qu... | 126 | 4,096 |
code-review-graph | code_review_graph/embeddings.py | .py | """Vector embedding support for semantic code search.
Supports multiple providers:
1. Local (sentence-transformers) - Private, fast, offline.
2. Google Gemini - High-quality, cloud-based. Requires explicit opt-in.
3. MiniMax (embo-01) - High-quality 1536-dim cloud embeddings. Requires MINIMAX_API_KEY.
4. OpenAI-compat... | 1,424 | 55,820 |
code-review-graph | code_review_graph/hints.py | .py | """Context-aware hints system for MCP tool responses.
Tracks session state (in-memory only) and generates intelligent
next-step suggestions after each tool call. Hints are appended as
``_hints`` to new tool responses so that Claude Code can propose
follow-up actions without the user having to discover them.
"""
from... | 385 | 11,994 |
code-review-graph | code_review_graph/constants.py | .py | """Shared constants for code-review-graph."""
from __future__ import annotations
import math
import os
from pathlib import Path
def _bounded_float_env(
name: str,
default: float,
*,
lower: float,
upper: float,
) -> float:
"""Read a finite float strictly inside ``(lower, upper)``.
Invali... | 125 | 4,643 |
code-review-graph | code_review_graph/registry.py | .py | """Multi-repo registry and connection pool.
Manages a registry of multiple repositories at ``~/.code-review-graph/registry.json``
and provides a connection pool for concurrent access to multiple graph databases.
"""
from __future__ import annotations
import json
import logging
import sqlite3
import threading
from co... | 327 | 10,404 |
code-review-graph | code_review_graph/scoped_resolver.py | .py | """Post-build resolver for PHP/Rust/C# scoped calls and receiver-typed calls.
Tree-sitter extraction records a scoped/static call such as ``Mailer::send($x)``
(PHP) or ``Mailer::send(x)`` / ``Self::new()`` (Rust) as a ``CALLS`` edge whose
target is the intermediate ``Class::method`` string. That string matches
neithe... | 515 | 20,989 |
code-review-graph | code_review_graph/skills.py | .py | """Claude Code skills and hooks auto-install.
Generates Claude Code agent skill files, hooks configuration, and
CLAUDE.md integration for seamless code-review-graph usage.
Also supports multi-platform MCP server installation and
Cursor hooks / OpenCode plugin generation.
"""
from __future__ import annotations
import... | 1,862 | 71,358 |
code-review-graph | code_review_graph/search.py | .py | """Hybrid search engine combining FTS5 (BM25) and vector embeddings.
Uses Reciprocal Rank Fusion (RRF) to merge results from full-text search
and semantic similarity, with query-aware kind boosting and context-file
boosting for relevance tuning.
"""
from __future__ import annotations
import logging
import re
import ... | 471 | 16,274 |
code-review-graph | code_review_graph/enrich.py | .py | """PreToolUse search enrichment for Claude Code hooks.
Intercepts Grep/Glob/Bash/Read tool calls and enriches them with
structural context from the code knowledge graph: callers, callees,
execution flows, community membership, and test coverage.
"""
from __future__ import annotations
import json
import logging
impor... | 307 | 9,363 |
code-review-graph | code_review_graph/flows.py | .py | """Execution flow detection, tracing, and criticality scoring.
Detects entry points in the codebase (functions with no incoming CALLS edges,
framework-decorated handlers, and conventional name patterns), traces execution
paths via forward BFS through CALLS edges, scores each flow for criticality,
and persists results ... | 719 | 25,535 |
code-review-graph | code_review_graph/rescript_resolver.py | .py | """Post-build pass that resolves ReScript cross-module references.
The per-file parser emits CALLS/IMPORTS_FROM edges with bare targets like
``LogicUtils.safeParse`` because the parser only sees one file at a time.
This module runs after ``full_build`` / incremental updates and rewrites
those targets to canonical qual... | 207 | 7,564 |
code-review-graph | code_review_graph/hcl_resolver.py | .py | """Post-build resolution for Terraform module-scoped graph relationships."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .graph import GraphStore
logger = logging.getLogger(__name__)
def resolve_hcl_module_references(store:... | 111 | 3,927 |
code-review-graph | code_review_graph/context_savings.py | .py | """Compact estimated context savings helpers.
The project intentionally labels these values as estimates: the helper uses a
conservative character-count approximation instead of model-specific tokenizers.
"""
from __future__ import annotations
import json
from pathlib import Path
from typing import Any, Iterable
CH... | 318 | 10,981 |
code-review-graph | code_review_graph/cli.py | .py | """CLI entry point for code-review-graph.
Usage:
code-review-graph install
code-review-graph init
code-review-graph uninstall [--platform NAME] [--dry-run] [--yes] [--repo PATH]
code-review-graph build [--base BASE]
code-review-graph update [--base BASE]
code-review-graph forget PATH [PATH ...]... | 2,029 | 77,292 |
code-review-graph | code_review_graph/exports.py | .py | """Additional export formats: JSON, GraphML, Neo4j Cypher, Obsidian, SVG."""
from __future__ import annotations
import html
import json
import logging
import os
import re
import tempfile
from pathlib import Path
from .graph import GraphStore, _sanitize_name
from .visualization import export_graph_data
logger = logg... | 448 | 14,266 |
code-review-graph | code_review_graph/daemon.py | .py | """Multi-repo watch daemon for code-review-graph.
Reads ``~/.code-review-graph/watch.toml`` to configure which repositories
to watch, then spawns one ``code-review-graph watch`` child process per
repo. Monitors the config file for live changes (adding/removing repos)
and health-checks child processes, restarting any ... | 1,127 | 39,452 |
code-review-graph | code_review_graph/incremental.py | .py | """Incremental graph update logic.
Detects changed files via git diff, re-parses only changed + impacted files,
and updates the graph accordingly. Also supports CLI invocation for hooks.
"""
from __future__ import annotations
import concurrent.futures
import fnmatch
import hashlib
import logging
import os
import re
... | 1,610 | 61,573 |
code-review-graph | code_review_graph/prompts.py | .py | """MCP prompt templates for Code Review Graph.
Provides 5 pre-built prompt workflows, all enforcing token-efficient
detail_level="minimal" first patterns with get_minimal_context entry point.
1. review_changes - pre-commit review using detect_changes + affected_flows
2. architecture_map - architecture docs using co... | 160 | 6,491 |
code-review-graph | code_review_graph/python_resolver.py | .py | """Post-build resolution for repository-local Python imports."""
from __future__ import annotations
import json
import logging
from typing import TYPE_CHECKING
if TYPE_CHECKING:
from .graph import GraphStore
logger = logging.getLogger(__name__)
def resolve_python_imports(store: GraphStore) -> dict[str, int]:
... | 124 | 4,090 |
code-review-graph | code_review_graph/custom_languages.py | .py | """Config-driven custom language support ("bring your own language").
Repos can teach the parser new tree-sitter languages without forking by
dropping a ``languages.toml`` file into ``.code-review-graph/``::
[languages.erlang]
extensions = [".erl", ".hrl"]
grammar = "erlang" # tree_... | 354 | 12,686 |
code-review-graph | code_review_graph/communities.py | .py | """Community/cluster detection for the code knowledge graph.
Detects communities of related code nodes using the Leiden algorithm (via igraph,
optional) with a file-based grouping fallback when igraph is not installed.
"""
from __future__ import annotations
import logging
import random
import re
from collections imp... | 1,089 | 37,712 |
code-review-graph | code_review_graph/spring_resolver.py | .py | """Post-build Spring DI call resolver.
After tree-sitter parsing, Java CALLS edges whose target is a bare method
name (e.g. ``calculate``) carry ``extra.receiver`` naming the local variable
that was called on (e.g. ``invoiceCalculationService``). This module
resolves those receivers through the INJECTS map to their d... | 201 | 8,065 |
code-review-graph | code_review_graph/daemon_cli.py | .py | """CLI entry point for the crg-daemon multi-repo watcher.
Usage:
crg-daemon start [--foreground]
crg-daemon stop
crg-daemon restart [--foreground]
crg-daemon status
crg-daemon logs [--repo ALIAS] [--follow] [--lines N]
crg-daemon add <path> [--alias ALIAS]
crg-daemon remove <path_or_alias>
... | 330 | 9,444 |
code-review-graph | code_review_graph/memory.py | .py | """Memory/feedback loop -- persist Q&A results for graph enrichment."""
from __future__ import annotations
import logging
import re
import time
from pathlib import Path
from typing import Any
logger = logging.getLogger(__name__)
def save_result(
question: str,
answer: str,
nodes: list[str] | None = Non... | 143 | 3,848 |
code-review-graph | code_review_graph/graph.py | .py | """SQLite-backed knowledge graph storage and query engine.
Stores code structure as nodes (File, Class, Function, Type, Test) and
edges (CALLS, IMPORTS_FROM, INHERITS, IMPLEMENTS, CONTAINS, TESTED_BY, DEPENDS_ON, REFERENCES).
Supports impact-radius queries and subgraph extraction.
"""
from __future__ import annotatio... | 2,256 | 90,608 |
code-review-graph | code_review_graph/eval/scorer.py | .py | """Scoring metrics for evaluating graph-based code review quality.
Provides:
- Token efficiency: measures how many tokens the graph saves vs raw context.
- Mean Reciprocal Rank (MRR): evaluates ranking quality for search results.
- Precision / Recall / F1: evaluates set-based retrieval accuracy.
"""
from __future__ i... | 86 | 2,574 |
code-review-graph | code_review_graph/eval/reporter.py | .py | """Markdown report generator for evaluation benchmark results.
Takes a list of benchmark result dicts and produces a formatted markdown table
suitable for inclusion in documentation or CI output.
"""
from __future__ import annotations
import csv
from pathlib import Path
from typing import Any
def generate_markdown... | 302 | 9,942 |
code-review-graph | code_review_graph/eval/runner.py | .py | """Evaluation runner: orchestrates benchmark execution across repositories."""
from __future__ import annotations
import csv
import logging
import sqlite3
import subprocess
from datetime import date
from pathlib import Path
try:
import yaml # type: ignore[import-untyped]
except ImportError:
yaml = None # t... | 381 | 14,597 |
code-review-graph | code_review_graph/eval/__init__.py | .py | """Evaluation framework for code-review-graph.
Provides scoring metrics (token efficiency, MRR, precision/recall),
benchmark runners, and report generators for benchmarking graph-based code reviews.
"""
from __future__ import annotations
from .reporter import generate_full_report, generate_markdown_report, generate_... | 34 | 1,022 |
code-review-graph | code_review_graph/eval/token_benchmark.py | .py | """Measures total tokens consumed by agent workflows against benchmark repos."""
from __future__ import annotations
import json
import logging
from typing import Any, Callable
logger = logging.getLogger(__name__)
def estimate_tokens(obj: Any) -> int:
"""Estimate token count from JSON-serializable object.
... | 183 | 5,860 |
code-review-graph | code_review_graph/eval/benchmarks/token_efficiency.py | .py | """Token efficiency benchmark: compares naive, standard, and graph-based token counts.
Failure semantics: if ``get_review_context`` throws, the row is recorded with
``status="error"`` and empty metric fields. It stays in the CSV for forensics
but is excluded from every aggregate — a failed tool call is not a
measureme... | 144 | 4,908 |
code-review-graph | code_review_graph/eval/benchmarks/search_quality.py | .py | """Search quality benchmark: measures search result ranking via MRR."""
from __future__ import annotations
import logging
import sqlite3
from pathlib import Path
logger = logging.getLogger(__name__)
def run(repo_path: Path, store, config: dict) -> list[dict]:
"""Run search quality benchmark."""
results = [... | 66 | 2,198 |
code-review-graph | code_review_graph/eval/benchmarks/agent_baseline.py | .py | """Agent baseline benchmark: grep-and-read-top-k versus a graph query.
The whole-corpus baseline in the standalone token benchmark is an upper
bound no real agent pays: a competent agent greps for identifiers from the
question and reads only the best-matching files. This benchmark measures
that realistic baseline:
1.... | 210 | 7,924 |
code-review-graph | code_review_graph/eval/benchmarks/multi_hop_retrieval.py | .py | """Multi-hop retrieval benchmark.
Tests a two-step tool chain that mimics how an LLM agent actually uses the
graph for complex tasks:
1. ``hybrid_search(nl_query)`` to find a starting anchor from a natural-
language question.
2. ``query_graph(pattern, target=anchor)`` to traverse one hop along the
reque... | 132 | 4,500 |
code-review-graph | code_review_graph/eval/benchmarks/build_performance.py | .py | """Build performance benchmark: measures timing of graph operations."""
from __future__ import annotations
import logging
import time
from pathlib import Path
logger = logging.getLogger(__name__)
def run(repo_path: Path, store, config: dict) -> list[dict]:
"""Run build performance benchmark."""
stats = sto... | 61 | 1,911 |
code-review-graph | code_review_graph/eval/benchmarks/flow_completeness.py | .py | """Flow completeness benchmark: evaluates entry point detection and flow tracing."""
from __future__ import annotations
import logging
from pathlib import Path
logger = logging.getLogger(__name__)
def run(repo_path: Path, store, config: dict) -> list[dict]:
"""Run flow completeness benchmark."""
from code_... | 37 | 1,130 |
code-review-graph | code_review_graph/eval/benchmarks/impact_accuracy.py | .py | """Impact accuracy benchmark: measures precision/recall of change impact analysis.
Two ground-truth modes are emitted side by side (``ground_truth_mode`` column):
- **graph-derived (circular — upper bound)** — the historical mode. Ground
truth is the changed files plus files with CALLS/IMPORTS_FROM edges into
the... | 221 | 8,080 |
code-review-graph | code_review_graph/tools/flows_tools.py | .py | """Tools 10, 11: list_flows, get_flow."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from ..flows import get_flow_by_id, get_flows
from ..hints import generate_hints, get_session
from ._common import _get_store
# ---------------------------------------------------------------... | 177 | 6,096 |
code-review-graph | code_review_graph/tools/review.py | .py | """Tools 4, 12, 16: review context, affected flows, detect changes."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
from ..changes import analyze_changes, parse_diff_ranges, parse_git_diff_ranges # noqa: F401
from ..context_savings import attach_context_savings, ... | 481 | 17,694 |
code-review-graph | code_review_graph/tools/community_tools.py | .py | """Tools 13, 14, 15: community listing, detail, architecture overview."""
from __future__ import annotations
from collections import Counter
from typing import Any
from ..communities import get_architecture_overview, get_communities
from ..context_savings import attach_context_savings
from ..graph import node_to_dic... | 247 | 8,866 |
code-review-graph | code_review_graph/tools/analysis_tools.py | .py | """MCP tool wrappers for graph analysis features."""
from __future__ import annotations
from typing import Any
from ..analysis import (
find_bridge_nodes,
find_hub_nodes,
find_knowledge_gaps,
find_surprising_connections,
generate_suggested_questions,
)
from ._common import _get_store
def get_hu... | 185 | 5,713 |
code-review-graph | code_review_graph/tools/registry_tools.py | .py | """Tools 21, 22: list_repos_func, cross_repo_search_func."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
from ..graph import GraphStore
from ..incremental import get_db_path
from ..search import hybrid_search
logger = logging.getLogger(__name__)
# ------------... | 126 | 4,034 |
code-review-graph | code_review_graph/tools/__init__.py | .py | """MCP tool definitions for the Code Review Graph server.
Exposes 27 tools:
1. build_or_update_graph - full or incremental build
2. get_impact_radius - blast radius from changed files
3. query_graph - predefined graph queries
4. get_review_context - focused subgraph + review prompt
5. semantic_sea... | 159 | 5,663 |
code-review-graph | code_review_graph/tools/refactor_tools.py | .py | """Tools 17, 18: refactor_func, apply_refactor_func."""
from __future__ import annotations
from pathlib import Path
from typing import Any
from ..hints import generate_hints, get_session
from ..incremental import find_project_root
from ..refactor import (
apply_refactor,
find_dead_code,
rename_preview,
... | 169 | 5,689 |
code-review-graph | code_review_graph/tools/_common.py | .py | """Shared utilities for tool sub-modules."""
from __future__ import annotations
import logging
import sqlite3
import subprocess
from datetime import datetime
from pathlib import Path
from typing import Any
from ..graph import GraphStore
from ..incremental import find_project_root, get_db_path
from ..parser import no... | 293 | 11,176 |
code-review-graph | code_review_graph/tools/docs.py | .py | """Tools 7, 8, 19, 20: embed_graph, get_docs_section, wiki tools."""
from __future__ import annotations
import logging
from pathlib import Path
from typing import Any
from ..embeddings import EmbeddingStore, embed_all_nodes
from ..incremental import find_project_root, get_db_path
from ._common import _get_store, _re... | 283 | 10,163 |
code-review-graph | code_review_graph/tools/context.py | .py | """Tool: get_minimal_context — ultra-compact context for token-efficient workflows."""
from __future__ import annotations
import logging
import sqlite3
import subprocess
from pathlib import Path
from typing import Any
from ..incremental import get_db_path
from ..parser import normalize_file_path
from ._common import... | 190 | 7,234 |
code-review-graph | code_review_graph/tools/query.py | .py | """Tools 2, 3, 5, 6, 9: query / search / stats helpers."""
from __future__ import annotations
import logging
import re
from pathlib import Path
from typing import Any
from ..config_keys import normalize_spring_config_key
from ..context_savings import attach_context_savings, estimate_file_tokens
from ..embeddings imp... | 1,017 | 40,934 |
code-review-graph | code_review_graph/tools/build.py | .py | """Tool 1: build_or_update_graph + run_postprocess."""
from __future__ import annotations
import logging
import sqlite3
import time
from typing import Any
from ..incremental import (
full_build,
incremental_update,
resolve_incremental_base,
)
from ._common import _get_store
logger = logging.getLogger(__... | 703 | 26,995 |
claude-code-templates | cli-tool/components/settings/statusline/deadline-countdown.py | .py | #!/usr/bin/env python3
"""
Deadline Countdown Statusline
Shows git branch, changed files count, and countdown to deadline.
Color-coded urgency: green >2h, yellow 1-2h, red <1h, blinking <30min.
Configure with DEADLINE_TIME (HH:MM, default 15:30) env var.
"""
import json
import os
import subprocess
import sys
from date... | 126 | 3,112 |
claude-code-templates | cli-tool/components/settings/statusline/context-monitor.py | .py | #!/usr/bin/env python3
"""
Claude Code Context Monitor
Real-time context usage monitoring with visual indicators and session analytics
"""
import json
import sys
import os
import re
import subprocess
def get_git_status():
"""Get git branch and change count for statusline."""
try:
# Check if inside a ... | 300 | 9,528 |
claude-code-templates | cli-tool/components/sandbox/e2b/e2b-monitor.py | .py | #!/usr/bin/env python3.11
"""
E2B Sandbox Real-time Monitor
Provides real-time monitoring and debugging of E2B sandbox operations
"""
import os
import sys
import time
import json
from datetime import datetime
def log_with_timestamp(message, level="INFO"):
timestamp = datetime.now().strftime("%H:%M:%S")
print(... | 229 | 8,714 |
claude-code-templates | cli-tool/components/sandbox/e2b/e2b-launcher.py | .py | #!/usr/bin/env python3.11
"""
E2B Claude Code Sandbox Launcher
Executes Claude Code prompts in isolated E2B cloud sandbox
"""
import os
import sys
import json
import datetime
import re
import threading
import time
# Debug: Print Python path information
print(f"Python executable: {sys.executable}")
print(f"Python vers... | 438 | 18,739 |
claude-code-templates | cli-tool/components/hooks/security/secret-scanner.py | .py | #!/usr/bin/env python3
"""
Secret Scanner Hook
Detects hardcoded secrets before git commits
"""
import json
import sys
import re
import subprocess
import os
# Secret detection patterns with descriptions
SECRET_PATTERNS = [
# AWS Keys
(r'AKIA[0-9A-Z]{16}', 'AWS Access Key ID', 'high'),
(r'(?i)aws[_\-\s]*se... | 368 | 13,401 |
claude-code-templates | cli-tool/components/hooks/security/dangerous-command-blocker.py | .py | #!/usr/bin/env python3
"""
Dangerous Command Blocker Hook
Multi-level security system for blocking dangerous shell commands
"""
import json
import sys
import re
# Load command from stdin
data = json.load(sys.stdin)
cmd = data.get('tool_input', {}).get('command', '')
# === LEVEL 1: CATASTROPHIC COMMANDS (ALWAYS BLOCK... | 99 | 4,688 |
claude-code-templates | cli-tool/components/hooks/monitoring/context-timeline.py | .py | #!/usr/bin/env python3
"""
context-timeline: Claude Code session visualizer.
Modes (called by Claude Code hooks via stdin JSON):
--server-start SessionStart hook — launch daemon + open browser
--event <NAME> PreToolUse / PostToolUse / Stop hook — notify server
--shutdown Kill daemon manu... | 1,225 | 52,625 |
claude-code-templates | cli-tool/components/hooks/automation/change-logger.py | .py | #!/usr/bin/env python3
"""
Change Logger Hook
Logs every file mutation (Edit, Write, Bash) to a CSV file for demo prep and session review.
Output: .claude/critical_log_changes.csv
"""
import csv
import json
import os
import sys
from datetime import datetime
# Read-only commands that should not be logged
READONLY_COMM... | 86 | 2,459 |
claude-code-templates | cli-tool/components/hooks/automation/telegram-pr-webhook.py | .py | #!/usr/bin/env python3
"""
Telegram PR Webhook Hook
Sends a Telegram notification when a new PR is created via `gh pr create`.
Includes the PR URL and the Vercel preview URL.
Required environment variables:
TELEGRAM_BOT_TOKEN - Bot token from @BotFather
TELEGRAM_CHAT_ID - Chat ID for notifications
Optional en... | 138 | 3,887 |
claude-code-templates | cli-tool/components/hooks/git/conventional-commits.py | .py | #!/usr/bin/env python3
import json
import sys
import re
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command = tool_in... | 85 | 2,534 |
claude-code-templates | cli-tool/components/hooks/git/validate-branch-name.py | .py | #!/usr/bin/env python3
import json
import sys
import re
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command = tool_in... | 97 | 2,518 |
claude-code-templates | cli-tool/components/hooks/git/prevent-direct-push.py | .py | #!/usr/bin/env python3
import json
import sys
import subprocess
try:
input_data = json.load(sys.stdin)
except json.JSONDecodeError as e:
print(f"Error: Invalid JSON input: {e}", file=sys.stderr)
sys.exit(1)
tool_name = input_data.get("tool_name", "")
tool_input = input_data.get("tool_input", {})
command =... | 87 | 2,163 |
claude-code-templates | cli-tool/components/skills/media/screenshot/scripts/take_screenshot.py | .py | #!/usr/bin/env python3
"""Cross-platform screenshot helper for Codex skills."""
from __future__ import annotations
import argparse
import datetime as dt
import json
import os
import platform
import shutil
import subprocess
import tempfile
from pathlib import Path
SCRIPT_DIR = Path(__file__).resolve().parent
MAC_PERM... | 586 | 19,659 |
claude-code-templates | cli-tool/components/skills/media/transcribe/scripts/transcribe_diarize.py | .py | #!/usr/bin/env python3
"""Transcribe audio (optionally with speaker diarization) using OpenAI."""
from __future__ import annotations
import argparse
import base64
import json
import mimetypes
import os
from pathlib import Path
import sys
from typing import Any, Dict, List, Optional, Tuple
DEFAULT_MODEL = "gpt-4o-min... | 277 | 8,684 |
claude-code-templates | cli-tool/components/skills/media/speech/scripts/text_to_speech.py | .py | #!/usr/bin/env python3
"""Generate speech audio with the OpenAI Audio API (TTS).
Defaults to gpt-4o-mini-tts-2025-12-15 and a built-in voice (cedar).
"""
from __future__ import annotations
import argparse
import json
import os
from pathlib import Path
import re
import sys
import time
from typing import Any, Dict, Li... | 529 | 15,592 |
claude-code-templates | cli-tool/components/skills/security/security-ownership-map/scripts/community_maintainers.py | .py | #!/usr/bin/env python3
"""Report monthly maintainers for a file's community."""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import json
import math
import re
import subprocess
import sys
from collections import Counter, defaultdict
from pathlib import Path
from typing import It... | 545 | 18,122 |
claude-code-templates | cli-tool/components/skills/security/security-ownership-map/scripts/query_ownership.py | .py | #!/usr/bin/env python3
"""Query ownership-map outputs without loading everything into an LLM context."""
from __future__ import annotations
import argparse
import csv
import json
import sys
from collections import defaultdict
from pathlib import Path
from typing import Iterable
def parse_args() -> argparse.Namespac... | 484 | 17,991 |
claude-code-templates | cli-tool/components/skills/security/security-ownership-map/scripts/run_ownership_map.py | .py | #!/usr/bin/env python3
"""One-shot runner for building the security ownership map."""
from __future__ import annotations
import argparse
import subprocess
import sys
from pathlib import Path
def parse_args() -> argparse.Namespace:
parser = argparse.ArgumentParser(
description="Run build_ownership_map.py... | 201 | 5,890 |
claude-code-templates | cli-tool/components/skills/security/security-ownership-map/scripts/build_ownership_map.py | .py | #!/usr/bin/env python3
"""Build a security ownership map from git history."""
from __future__ import annotations
import argparse
import csv
import datetime as dt
import fnmatch
import json
import math
import os
import re
import subprocess
import sys
from collections import defaultdict
from pathlib import Path
from ty... | 957 | 34,330 |
claude-code-templates | cli-tool/components/skills/scientific/torch_geometric/scripts/create_gnn_template.py | .py | #!/usr/bin/env python3
"""
Generate boilerplate code for common GNN architectures in PyTorch Geometric.
This script creates ready-to-use GNN model templates with training loops,
evaluation metrics, and proper data handling.
Usage:
python create_gnn_template.py --model gcn --task node_classification --output my_mo... | 530 | 15,342 |
claude-code-templates | cli-tool/components/skills/scientific/torch_geometric/scripts/benchmark_model.py | .py | #!/usr/bin/env python3
"""
Benchmark GNN models on standard datasets.
This script provides a simple way to benchmark different GNN architectures
on common datasets and compare their performance.
Usage:
python benchmark_model.py --models gcn gat --dataset Cora
python benchmark_model.py --models gcn --dataset C... | 310 | 10,028 |
claude-code-templates | cli-tool/components/skills/scientific/torch_geometric/scripts/visualize_graph.py | .py | #!/usr/bin/env python3
"""
Visualize PyTorch Geometric graph structures using networkx and matplotlib.
This script provides utilities to visualize Data objects, including:
- Graph structure (nodes and edges)
- Node features (as colors)
- Edge attributes (as edge colors/widths)
- Community/cluster assignments
Usage:
... | 314 | 10,267 |
claude-code-templates | cli-tool/components/skills/scientific/pydicom/scripts/extract_metadata.py | .py | #!/usr/bin/env python3
"""
Extract and display DICOM metadata in a readable format.
Usage:
python extract_metadata.py file.dcm
python extract_metadata.py file.dcm --output metadata.txt
python extract_metadata.py file.dcm --format json --output metadata.json
"""
import argparse
import sys
import json
from ... | 174 | 5,686 |
claude-code-templates | cli-tool/components/skills/scientific/pydicom/scripts/anonymize_dicom.py | .py | #!/usr/bin/env python3
"""
Anonymize DICOM files by removing or replacing Protected Health Information (PHI).
Usage:
python anonymize_dicom.py input.dcm output.dcm
python anonymize_dicom.py input.dcm output.dcm --patient-id ANON001
"""
import argparse
import sys
from pathlib import Path
try:
import pydic... | 138 | 5,254 |
claude-code-templates | cli-tool/components/skills/scientific/pydicom/scripts/dicom_to_image.py | .py | #!/usr/bin/env python3
"""
Convert DICOM files to common image formats (PNG, JPEG, TIFF).
Usage:
python dicom_to_image.py input.dcm output.png
python dicom_to_image.py input.dcm output.jpg --format JPEG
python dicom_to_image.py input.dcm output.tiff --apply-windowing
"""
import argparse
import sys
from pa... | 173 | 6,101 |
claude-code-templates | cli-tool/components/skills/scientific/opentrons-integration/scripts/basic_protocol_template.py | .py | #!/usr/bin/env python3
"""
Basic Opentrons Protocol Template
This template provides a minimal starting point for creating Opentrons protocols.
Replace the placeholder values and add your specific protocol logic.
"""
from opentrons import protocol_api
# Metadata
metadata = {
'protocolName': 'Basic Protocol Templa... | 68 | 1,537 |
claude-code-templates | cli-tool/components/skills/scientific/opentrons-integration/scripts/serial_dilution_template.py | .py | #!/usr/bin/env python3
"""
Serial Dilution Protocol Template
This template demonstrates how to perform a serial dilution across a plate row.
Useful for creating concentration gradients for assays.
"""
from opentrons import protocol_api
metadata = {
'protocolName': 'Serial Dilution Template',
'author': 'Opent... | 97 | 3,171 |
claude-code-templates | cli-tool/components/skills/scientific/opentrons-integration/scripts/pcr_setup_template.py | .py | #!/usr/bin/env python3
"""
PCR Setup Protocol Template
This template demonstrates how to set up PCR reactions using the Thermocycler module.
Includes master mix distribution, sample addition, and PCR cycling.
"""
from opentrons import protocol_api
metadata = {
'protocolName': 'PCR Setup with Thermocycler',
'... | 155 | 4,538 |
claude-code-templates | cli-tool/components/skills/scientific/stable-baselines3/scripts/train_rl_agent.py | .py | """
Template script for training RL agents with Stable Baselines3.
This template demonstrates best practices for:
- Setting up training with proper monitoring
- Using callbacks for evaluation and checkpointing
- Vectorized environments for efficiency
- TensorBoard integration
- Model saving and loading
"""
import gym... | 166 | 5,123 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.