Compare commits
19
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
762b85d7ca | ||
|
|
267c392a96 | ||
|
|
832dc537b3 | ||
|
|
6c82f81d13 | ||
|
|
6c9b5ef63c | ||
|
|
3145ca2e52 | ||
|
|
fd0ebb5957 | ||
|
|
b9871d7019 | ||
|
|
ac72cd3aaa | ||
|
|
48c9f024fb | ||
|
|
e1636a0e88 | ||
|
|
8b41440ad1 | ||
|
|
e1947826fc | ||
|
|
441e3b6574 | ||
|
|
18d697aac9 | ||
|
|
e97379e551 | ||
|
|
7683df1cd5 | ||
|
|
ffc5427351 | ||
|
|
5f4f557034 |
No files matched your search
@@ -2,16 +2,25 @@ name: CI
|
||||
|
||||
on:
|
||||
push:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
|
||||
pull_request:
|
||||
branches: ["v1", "v2", "v3", "v4", "main"]
|
||||
branches: ["v1", "v2", "v3", "v4", "v5", "main"]
|
||||
workflow_dispatch:
|
||||
|
||||
concurrency:
|
||||
group: ci-${{ github.ref }}
|
||||
cancel-in-progress: true
|
||||
|
||||
permissions:
|
||||
contents: read
|
||||
|
||||
jobs:
|
||||
test:
|
||||
runs-on: ubuntu-latest
|
||||
strategy:
|
||||
fail-fast: false
|
||||
matrix:
|
||||
python-version: ["3.10", "3.12"]
|
||||
python-version: ["3.10", "3.11", "3.12", "3.13"]
|
||||
|
||||
steps:
|
||||
- uses: actions/checkout@v4
|
||||
@@ -20,11 +29,12 @@ jobs:
|
||||
uses: actions/setup-python@v5
|
||||
with:
|
||||
python-version: ${{ matrix.python-version }}
|
||||
cache: 'pip'
|
||||
cache-dependency-path: 'pyproject.toml'
|
||||
|
||||
- name: Install dependencies
|
||||
run: |
|
||||
pip install -e ".[mcp,pdf,watch]"
|
||||
pip install pytest
|
||||
pip install -e ".[all,test]"
|
||||
|
||||
- name: Run tests
|
||||
run: |
|
||||
|
||||
@@ -97,7 +97,7 @@ pip install graphifyy && graphify install
|
||||
| Cursor | `graphify cursor install` |
|
||||
| Google Antigravity | `graphify antigravity install` |
|
||||
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports PreToolUse hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
|
||||
Codex users also need `multi_agent = true` under `[features]` in `~/.codex/config.toml` for parallel extraction. Factory Droid uses the `Task` tool for parallel subagent dispatch. OpenClaw and Aider use sequential extraction (parallel agent support is still early on those platforms). Trae uses the Agent tool for parallel subagent dispatch and does **not** support PreToolUse hooks — AGENTS.md is the always-on mechanism. Codex supports UserPromptSubmit hooks — `graphify codex install` installs one in `.codex/hooks.json` in addition to writing AGENTS.md.
|
||||
|
||||
Then open your AI coding assistant and type:
|
||||
|
||||
@@ -131,7 +131,7 @@ After building a graph, run this once in your project:
|
||||
|
||||
**Claude Code** does two things: writes a `CLAUDE.md` section telling Claude to read `graphify-out/GRAPH_REPORT.md` before answering architecture questions, and installs a **PreToolUse hook** (`settings.json`) that fires before every Glob and Grep call. If a knowledge graph exists, Claude sees: _"graphify: Knowledge graph exists. Read GRAPH_REPORT.md for god nodes and community structure before searching raw files."_ — so Claude navigates via the graph instead of grepping through every file.
|
||||
|
||||
**Codex** writes to `AGENTS.md` and also installs a **PreToolUse hook** in `.codex/hooks.json` that fires before every Bash tool call — same always-on mechanism as Claude Code.
|
||||
**Codex** writes to `AGENTS.md` and also installs a **UserPromptSubmit hook** in `.codex/hooks.json` that fires when the user submits a prompt. This reminds Codex about `GRAPH_REPORT.md` before it decides whether to search files.
|
||||
|
||||
**OpenCode** writes to `AGENTS.md` and also installs a **`tool.execute.before` plugin** (`.opencode/plugins/graphify.js` + `opencode.json` registration) that fires before bash tool calls and injects the graph reminder into tool output when the graph exists.
|
||||
|
||||
@@ -299,7 +299,7 @@ graphify hook status
|
||||
# always-on assistant instructions - platform-specific
|
||||
graphify claude install # CLAUDE.md + PreToolUse hook (Claude Code)
|
||||
graphify claude uninstall
|
||||
graphify codex install # AGENTS.md + PreToolUse hook in .codex/hooks.json (Codex)
|
||||
graphify codex install # AGENTS.md + UserPromptSubmit hook in .codex/hooks.json (Codex)
|
||||
graphify opencode install # AGENTS.md + tool.execute.before plugin (OpenCode)
|
||||
graphify cursor install # .cursor/rules/graphify.mdc (Cursor)
|
||||
graphify cursor uninstall
|
||||
@@ -426,6 +426,14 @@ Token reduction scales with corpus size. 6 files fits in a context window anyway
|
||||
|
||||
graphify sends file contents to your AI coding assistant's underlying model API for semantic extraction of docs, papers, and images — Anthropic (Claude Code), OpenAI (Codex), or whichever provider your platform uses. Code files are processed locally via tree-sitter AST — no file contents leave your machine for code. Video and audio files are transcribed locally with faster-whisper — audio never leaves your machine. No telemetry, usage tracking, or analytics of any kind. The only network calls are to your platform's model API during extraction, using your own API key.
|
||||
|
||||
## Optional integrations
|
||||
|
||||
Runbooks for setting up extra tooling alongside graphify. None of these are required.
|
||||
|
||||
| Integration | Doc |
|
||||
|---|---|
|
||||
| LocalColabFold (ColabFold + AlphaFold2) on macOS Apple Silicon | [`docs/colabfold-macos-install.md`](docs/colabfold-macos-install.md) |
|
||||
|
||||
## Tech stack
|
||||
|
||||
NetworkX + Leiden (graspologic) + tree-sitter + vis.js. Semantic extraction via Claude (Claude Code), GPT-4 (Codex), or whichever model your platform runs. Video transcription via faster-whisper + yt-dlp (optional, `pip install graphifyy[video]`). No Neo4j required, no server, runs entirely locally.
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
# Installing LocalColabFold on macOS Apple Silicon
|
||||
A reproducible runbook for installing
|
||||
[LocalColabFold](https://github.com/YoshitakaMo/localcolabfold)
|
||||
(ColabFold + AlphaFold2 weights) on Apple Silicon (arm64) Macs, so you can
|
||||
predict protein structures locally and feed the resulting PDBs / confidence
|
||||
scores into a graphify corpus.
|
||||
|
||||
This document is **optional** and unrelated to graphify's pipeline. It is
|
||||
included as a known-good recipe for users who want a CPU-capable local
|
||||
ColabFold install alongside graphify on the same machine.
|
||||
|
||||
## Why a separate runbook
|
||||
LocalColabFold's current top-level installer (`install_colabbatch_linux.sh`)
|
||||
hardcodes `Miniforge3-Linux-x86_64.sh` and later runs
|
||||
`pip install jax[cuda12]==0.5.3`. Both fail on Apple Silicon: there are no
|
||||
macOS CUDA wheels, and Apple GPUs are unreachable from JAX's CUDA backend.
|
||||
Upstream stopped shipping a current macOS installer after v1.5.5. The
|
||||
**v1.5.5 M1 installer** (bundled in the LocalColabFold repo at
|
||||
`v1.5.5_old_installers/install_colabbatch_M1mac.sh`) is the working Apple
|
||||
Silicon path — ColabFold 1.6.1, JAX 0.4.23 CPU build.
|
||||
|
||||
## Verified configuration
|
||||
- Hardware: Apple Silicon (arm64)
|
||||
- OS: macOS (Darwin)
|
||||
- ColabFold installed: 1.6.1 (commit `de5ab5f`)
|
||||
- JAX: 0.4.23 (CPU build)
|
||||
- 62-residue smoke test (1 model, 1 recycle, single-sequence MSA): ~60 s wall
|
||||
|
||||
## Prerequisites (Homebrew)
|
||||
The M1 installer fail-fasts on these. Install once before running:
|
||||
|
||||
```bash
|
||||
brew tap brewsci/bio # custom tap for hh-suite
|
||||
brew install brewsci/bio/hh-suite \
|
||||
kalign \
|
||||
mmseqs2
|
||||
|
||||
# verify
|
||||
for c in wget hhsearch kalign mmseqs; do
|
||||
printf "%-10s " "$c" && command -v "$c" || echo MISSING
|
||||
done
|
||||
```
|
||||
|
||||
Roughly ~600 MB of brew downloads (gcc, open-mpi, hh-suite are the heavy
|
||||
items); 5–10 minutes on a modern internet link.
|
||||
|
||||
## Install
|
||||
Clone LocalColabFold (or use an existing clone), then from the repo root:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/YoshitakaMo/localcolabfold.git
|
||||
cd localcolabfold
|
||||
bash v1.5.5_old_installers/install_colabbatch_M1mac.sh
|
||||
```
|
||||
|
||||
What the installer does, in order:
|
||||
1. Downloads `Miniforge3-MacOSX-arm64.sh` and installs into
|
||||
`localcolabfold/conda/`
|
||||
2. `conda update -n base conda -y`
|
||||
3. Creates env at `localcolabfold/colabfold-conda` with
|
||||
`python=3.10 openmm==8.0.0 pdbfixer==1.9` from conda-forge
|
||||
4. `pip install "colabfold[alphafold] @ git+https://github.com/sokrypton/ColabFold"`
|
||||
5. `pip install jax==0.4.23 jaxlib==0.4.23` (CPU build)
|
||||
6. `pip install silence_tensorflow`
|
||||
7. Downloads `update_M1mac.sh`
|
||||
8. `python -m colabfold.download` — pulls AlphaFold2 weights into
|
||||
`~/Library/Caches/colabfold` (~5.3 GB total: 3.82 GB multimer_v3 +
|
||||
3.47 GB AlphaFold2-ptm)
|
||||
|
||||
Total install time: ~10–30 min depending on network and AlphaFold weight
|
||||
download speed.
|
||||
|
||||
## Add to PATH
|
||||
The installer's last step prints the line for your shell. Adapt the prefix
|
||||
to wherever you cloned LocalColabFold:
|
||||
|
||||
```bash
|
||||
export PATH="$(pwd)/localcolabfold/colabfold-conda/bin:$PATH"
|
||||
```
|
||||
|
||||
Add the line to `~/.zshrc` to persist across shell sessions.
|
||||
|
||||
## Smoke test
|
||||
A minimal CPU-only inference exercising the JAX path (no MMseqs2 server,
|
||||
no templates, single model, single recycle). Use any short FASTA — the
|
||||
LocalColabFold repo ships `1BJP_1.fasta` (62 residues).
|
||||
|
||||
```bash
|
||||
colabfold_batch \
|
||||
--num-models 1 --num-recycle 1 \
|
||||
--msa-mode single_sequence \
|
||||
--random-seed 0 \
|
||||
1BJP_1.fasta out_smoketest/
|
||||
```
|
||||
|
||||
Expected output in `out_smoketest/`:
|
||||
- `*.pdb` — predicted structure
|
||||
- `*_scores_*.json` — per-residue confidence
|
||||
- `*_pae.png`, `*_plddt.png`, `*_coverage.png` — diagnostic plots
|
||||
- `1BJP_1.done.txt` — sentinel marker
|
||||
|
||||
Sample log lines on success:
|
||||
```
|
||||
Running colabfold 1.6.1 (de5ab5f795ed95c70a7a9b6a9dc6bb5625016142)
|
||||
WARNING: no GPU detected, will be using CPU
|
||||
Query 1/1: 1BJP_1 (length 62)
|
||||
alphafold2_ptm_model_1_seed_000 recycle=0 pLDDT=56.7 pTM=0.363
|
||||
alphafold2_ptm_model_1_seed_000 took 18.1s (1 recycles)
|
||||
```
|
||||
|
||||
The low pLDDT (~57) is **expected** — single-sequence MSA, 1 model, and
|
||||
1 recycle is the cheapest config that still exercises the JAX inference
|
||||
path. It is **not** representative of structure quality. Use the
|
||||
production config below for real predictions.
|
||||
|
||||
## Production run (CPU-friendly defaults)
|
||||
LocalColabFold's bundled `run_colabfoldbatch_sample.sh` uses
|
||||
`--use-gpu-relax`, `--templates`, and `--amber` — all of which require
|
||||
either GPU or extra setup that doesn't apply on macOS. Use this
|
||||
CPU-friendly variant instead:
|
||||
|
||||
```bash
|
||||
colabfold_batch \
|
||||
--num-recycle 3 \
|
||||
--num-models 5 \
|
||||
--model-order 1,2,3,4,5 \
|
||||
--random-seed 0 \
|
||||
YOUR_INPUT.fasta out_dir/
|
||||
# Dropped from the sample script:
|
||||
# --use-gpu-relax (no GPU)
|
||||
# --amber (slow on CPU; pdbfixer-only is fine for many use cases)
|
||||
# --templates (requires hhsearch + a PDB templates DB)
|
||||
```
|
||||
|
||||
MSA defaults to MMseqs2 server-side queries — needs network, ~30–90 s
|
||||
roundtrip per sequence.
|
||||
|
||||
Expect 5–15 min per ~100-residue monomer on this hardware. Multimers and
|
||||
longer chains scale much worse on CPU.
|
||||
|
||||
## Honest caveats
|
||||
- **CPU-only.** No CUDA wheels for macOS exist; JAX has experimental
|
||||
Metal support but LocalColabFold's pinned `jax==0.4.23` is the CPU
|
||||
build. Inference can be 30–100× slower than a recent NVIDIA GPU.
|
||||
- **ColabFold version is 1.6.1**, pinned by the v1.5.5 installer track.
|
||||
Newer features in ColabFold `main` aren't available here. For latest
|
||||
features either use Google Colab or a Linux + NVIDIA box.
|
||||
- **Weights cache is ~5.3 GB** at `~/Library/Caches/colabfold`. Move with
|
||||
`XDG_CACHE_HOME` if disk is tight.
|
||||
- **Apple Silicon Metal** is not used by this JAX. There's no
|
||||
straightforward way to enable it without changing the pinned versions
|
||||
in the installer script.
|
||||
|
||||
## Update
|
||||
```bash
|
||||
bash localcolabfold/update_M1mac.sh
|
||||
```
|
||||
|
||||
## Uninstall / reset
|
||||
```bash
|
||||
# Remove the conda env + Miniforge (keeps weights cache)
|
||||
rm -rf localcolabfold/
|
||||
|
||||
# Optionally drop weights cache
|
||||
rm -rf ~/Library/Caches/colabfold
|
||||
|
||||
# Optionally remove brew prereqs
|
||||
brew uninstall brewsci/bio/hh-suite kalign mmseqs2
|
||||
brew untap brewsci/bio
|
||||
```
|
||||
+102
-21
@@ -712,15 +712,14 @@ def _uninstall_opencode_plugin(project_dir: Path) -> None:
|
||||
|
||||
_CODEX_HOOK = {
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
"UserPromptSubmit": [
|
||||
{
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"UserPromptSubmit","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
),
|
||||
}
|
||||
@@ -731,40 +730,103 @@ _CODEX_HOOK = {
|
||||
}
|
||||
|
||||
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK = {
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": (
|
||||
"[ -f graphify-out/graph.json ] && "
|
||||
r"""echo '{"hookSpecificOutput":{"hookEventName":"PreToolUse","additionalContext":"graphify: Knowledge graph exists. Read graphify-out/GRAPH_REPORT.md for god nodes and community structure before searching raw files."}}' """
|
||||
"|| true"
|
||||
),
|
||||
}
|
||||
],
|
||||
}
|
||||
|
||||
|
||||
def _is_graphify_codex_hook(hook: object) -> bool:
|
||||
"""Return True for Codex hooks generated by graphify."""
|
||||
return hook in (
|
||||
_CODEX_HOOK["hooks"]["UserPromptSubmit"][0],
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK,
|
||||
)
|
||||
|
||||
|
||||
def _remove_graphify_codex_hooks(existing: dict) -> None:
|
||||
"""Remove graphify Codex hooks while preserving unrelated hooks."""
|
||||
hooks = existing.get("hooks")
|
||||
if not isinstance(hooks, dict):
|
||||
return
|
||||
|
||||
for event in ("UserPromptSubmit", "PreToolUse"):
|
||||
event_hooks = hooks.get(event)
|
||||
if not isinstance(event_hooks, list):
|
||||
continue
|
||||
filtered = [h for h in event_hooks if not _is_graphify_codex_hook(h)]
|
||||
if filtered:
|
||||
hooks[event] = filtered
|
||||
else:
|
||||
hooks.pop(event, None)
|
||||
|
||||
if not hooks:
|
||||
existing.pop("hooks", None)
|
||||
|
||||
|
||||
def _install_codex_hook(project_dir: Path) -> None:
|
||||
"""Add graphify PreToolUse hook to .codex/hooks.json."""
|
||||
"""Add graphify UserPromptSubmit hook to .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
if hooks_path.exists():
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
existing = {}
|
||||
print(" .codex/hooks.json -> invalid JSON; left unchanged")
|
||||
return
|
||||
if not isinstance(loaded, dict):
|
||||
print(" .codex/hooks.json -> top-level value is not an object; left unchanged")
|
||||
return
|
||||
existing = loaded
|
||||
else:
|
||||
existing = {}
|
||||
|
||||
pre_tool = existing.setdefault("hooks", {}).setdefault("PreToolUse", [])
|
||||
existing["hooks"]["PreToolUse"] = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"].extend(_CODEX_HOOK["hooks"]["PreToolUse"])
|
||||
_remove_graphify_codex_hooks(existing)
|
||||
hooks = existing.get("hooks")
|
||||
if hooks is None:
|
||||
hooks = existing["hooks"] = {}
|
||||
elif not isinstance(hooks, dict):
|
||||
print(" .codex/hooks.json -> existing hooks value is not an object; left unchanged")
|
||||
return
|
||||
|
||||
user_prompt = hooks.get("UserPromptSubmit")
|
||||
if user_prompt is None:
|
||||
user_prompt = hooks["UserPromptSubmit"] = []
|
||||
elif not isinstance(user_prompt, list):
|
||||
print(" .codex/hooks.json -> UserPromptSubmit hooks are not a list; left unchanged")
|
||||
return
|
||||
|
||||
user_prompt.extend(_CODEX_HOOK["hooks"]["UserPromptSubmit"])
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook registered")
|
||||
print(f" .codex/hooks.json -> UserPromptSubmit hook registered")
|
||||
|
||||
|
||||
def _uninstall_codex_hook(project_dir: Path) -> None:
|
||||
"""Remove graphify PreToolUse hook from .codex/hooks.json."""
|
||||
"""Remove graphify Codex hooks from .codex/hooks.json."""
|
||||
hooks_path = project_dir / ".codex" / "hooks.json"
|
||||
if not hooks_path.exists():
|
||||
return
|
||||
try:
|
||||
existing = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
loaded = json.loads(hooks_path.read_text(encoding="utf-8"))
|
||||
except json.JSONDecodeError:
|
||||
return
|
||||
pre_tool = existing.get("hooks", {}).get("PreToolUse", [])
|
||||
filtered = [h for h in pre_tool if "graphify" not in str(h)]
|
||||
existing["hooks"]["PreToolUse"] = filtered
|
||||
hooks_path.write_text(json.dumps(existing, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> PreToolUse hook removed")
|
||||
if not isinstance(loaded, dict):
|
||||
return
|
||||
before = json.dumps(loaded, sort_keys=True)
|
||||
_remove_graphify_codex_hooks(loaded)
|
||||
if json.dumps(loaded, sort_keys=True) != before:
|
||||
hooks_path.write_text(json.dumps(loaded, indent=2), encoding="utf-8")
|
||||
print(f" .codex/hooks.json -> graphify hooks removed")
|
||||
|
||||
|
||||
def _agents_install(project_dir: Path, platform: str) -> None:
|
||||
@@ -1002,6 +1064,7 @@ def main() -> None:
|
||||
print(" watch <path> watch a folder and rebuild the graph on code changes")
|
||||
print(" update <path> re-extract code files and update the graph (no LLM needed)")
|
||||
print(" cluster-only <path> rerun clustering on an existing graph.json and regenerate report")
|
||||
print(" --no-viz skip graph.html generation (useful for >5000 node graphs / CI)")
|
||||
print(" query \"<question>\" BFS traversal of graph.json for a question")
|
||||
print(" --dfs use depth-first instead of breadth-first")
|
||||
print(" --budget N cap output at N tokens (default 2000)")
|
||||
@@ -1023,8 +1086,8 @@ def main() -> None:
|
||||
print(" cursor uninstall remove .cursor/rules/graphify.mdc")
|
||||
print(" claude install write graphify section to CLAUDE.md + PreToolUse hook (Claude Code)")
|
||||
print(" claude uninstall remove graphify section from CLAUDE.md + PreToolUse hook")
|
||||
print(" codex install write graphify section to AGENTS.md (Codex)")
|
||||
print(" codex uninstall remove graphify section from AGENTS.md")
|
||||
print(" codex install write AGENTS.md section + UserPromptSubmit hook (Codex)")
|
||||
print(" codex uninstall remove AGENTS.md section + graphify Codex hook")
|
||||
print(" opencode install write graphify section to AGENTS.md + tool.execute.before plugin (OpenCode)")
|
||||
print(" opencode uninstall remove graphify section from AGENTS.md + plugin")
|
||||
print(" aider install write graphify section to AGENTS.md (Aider)")
|
||||
@@ -1379,6 +1442,7 @@ def main() -> None:
|
||||
|
||||
elif cmd == "cluster-only":
|
||||
watch_path = Path(sys.argv[2]) if len(sys.argv) > 2 else Path(".")
|
||||
no_viz = "--no-viz" in sys.argv
|
||||
graph_json = watch_path / "graphify-out" / "graph.json"
|
||||
if not graph_json.exists():
|
||||
print(f"error: no graph found at {graph_json} — run /graphify first", file=sys.stderr)
|
||||
@@ -1407,8 +1471,25 @@ def main() -> None:
|
||||
out = watch_path / "graphify-out"
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, str(out / "graph.json"))
|
||||
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
|
||||
|
||||
# Mirror watch.py pattern: gate to_html so core outputs (graph.json +
|
||||
# GRAPH_REPORT.md) always land. Honor --no-viz explicitly; otherwise
|
||||
# fall back to ValueError handling so an oversized graph doesn't crash
|
||||
# the CLI mid-write and leave a stale graph.html on disk.
|
||||
html_target = out / "graph.html"
|
||||
if no_viz:
|
||||
if html_target.exists():
|
||||
html_target.unlink()
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated (--no-viz; graph.html removed).")
|
||||
else:
|
||||
try:
|
||||
to_html(G, communities, str(html_target), community_labels=labels or None)
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md, graph.json and graph.html updated.")
|
||||
except ValueError as viz_err:
|
||||
if html_target.exists():
|
||||
html_target.unlink()
|
||||
print(f"Skipped graph.html: {viz_err}")
|
||||
print(f"Done — {len(communities)} communities. GRAPH_REPORT.md and graph.json updated.")
|
||||
|
||||
elif cmd == "update":
|
||||
if len(sys.argv) > 2:
|
||||
|
||||
+94
-23
@@ -263,13 +263,13 @@ def _is_noise_dir(part: str) -> bool:
|
||||
return False
|
||||
|
||||
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore from root **and ancestor directories**.
|
||||
def _load_pattern_file(root: Path, filename: str) -> list[tuple[Path, str]]:
|
||||
"""Read a Graphify pattern file from root **and ancestor directories**.
|
||||
|
||||
Returns a list of (anchor_dir, pattern) pairs. Each pattern is matched
|
||||
against paths relative to both the scan root and the anchor_dir where
|
||||
the .graphifyignore file was found — so patterns written relative to a
|
||||
parent directory still work when graphify is run on a subfolder.
|
||||
the pattern file was found — so patterns written relative to a parent
|
||||
directory still work when graphify is run on a subfolder.
|
||||
|
||||
Walks upward from *root* towards the filesystem root, stopping at a
|
||||
``.git`` boundary. Lines starting with # are comments; blank lines ignored.
|
||||
@@ -277,9 +277,9 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
patterns: list[tuple[Path, str]] = []
|
||||
current = root.resolve()
|
||||
while True:
|
||||
ignore_file = current / ".graphifyignore"
|
||||
if ignore_file.exists():
|
||||
for line in ignore_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
pattern_file = current / filename
|
||||
if pattern_file.exists():
|
||||
for line in pattern_file.read_text(encoding="utf-8", errors="ignore").splitlines():
|
||||
line = line.strip()
|
||||
if line and not line.startswith("#"):
|
||||
patterns.append((current, line))
|
||||
@@ -293,13 +293,29 @@ def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
return patterns
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
if not patterns:
|
||||
return False
|
||||
def _load_graphifyignore(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyignore patterns from root and ancestor directories."""
|
||||
return _load_pattern_file(root, ".graphifyignore")
|
||||
|
||||
def _matches(rel: str, p: str) -> bool:
|
||||
parts = rel.split("/")
|
||||
|
||||
def _load_graphifyinclude(root: Path) -> list[tuple[Path, str]]:
|
||||
"""Read .graphifyinclude allowlist patterns from root and ancestors.
|
||||
|
||||
Include patterns are intentionally narrow: they only opt matching files and
|
||||
the directories needed to reach them into hidden-path traversal. Sensitive
|
||||
files and hard-skipped noise directories are still excluded later.
|
||||
"""
|
||||
return _load_pattern_file(root, ".graphifyinclude")
|
||||
|
||||
|
||||
def _pattern_matches(path: Path, rel: str, pattern: str) -> bool:
|
||||
"""Return True if *rel* or path.name matches a Graphify glob pattern."""
|
||||
parts = rel.split("/")
|
||||
candidates = [pattern]
|
||||
if "/**/" in pattern:
|
||||
# Treat foo/**/*.md as matching both foo/bar.md and foo/a/bar.md.
|
||||
candidates.append(pattern.replace("/**/", "/"))
|
||||
for p in candidates:
|
||||
if fnmatch.fnmatch(rel, p):
|
||||
return True
|
||||
if fnmatch.fnmatch(path.name, p):
|
||||
@@ -309,6 +325,12 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
return True
|
||||
if fnmatch.fnmatch("/".join(parts[:i + 1]), p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _matches_patterns(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any pattern loaded for root/ancestors."""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
for anchor, pattern in patterns:
|
||||
@@ -318,22 +340,64 @@ def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> boo
|
||||
# Try path relative to the scan root
|
||||
try:
|
||||
rel = str(path.relative_to(root)).replace(os.sep, "/")
|
||||
if _matches(rel, p):
|
||||
if _pattern_matches(path, rel, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
# Also try relative to the anchor dir (the .graphifyignore's location),
|
||||
# so patterns written at a parent level still fire when running on a subfolder
|
||||
# Also try relative to the anchor dir (the pattern file's location),
|
||||
# so parent-level patterns still fire when running on a subfolder.
|
||||
if anchor != root:
|
||||
try:
|
||||
rel_anchor = str(path.relative_to(anchor)).replace(os.sep, "/")
|
||||
if _matches(rel_anchor, p):
|
||||
if _pattern_matches(path, rel_anchor, p):
|
||||
return True
|
||||
except ValueError:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _is_ignored(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyignore pattern."""
|
||||
return _matches_patterns(path, root, patterns)
|
||||
|
||||
|
||||
def _is_included(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if path matches any .graphifyinclude allowlist pattern."""
|
||||
return _matches_patterns(path, root, patterns)
|
||||
|
||||
|
||||
def _could_contain_included_path(path: Path, root: Path, patterns: list[tuple[Path, str]]) -> bool:
|
||||
"""Return True if a directory may contain files matched by .graphifyinclude."""
|
||||
if not patterns:
|
||||
return False
|
||||
|
||||
rels: list[str] = []
|
||||
try:
|
||||
rels.append(str(path.relative_to(root)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
for anchor, _ in patterns:
|
||||
if anchor != root:
|
||||
try:
|
||||
rels.append(str(path.relative_to(anchor)).replace(os.sep, "/"))
|
||||
except ValueError:
|
||||
pass
|
||||
|
||||
for rel in rels:
|
||||
rel = rel.strip("/")
|
||||
if not rel:
|
||||
return True
|
||||
for _, pattern in patterns:
|
||||
p = pattern.strip("/")
|
||||
if not p:
|
||||
continue
|
||||
if p == rel or p.startswith(rel + "/"):
|
||||
return True
|
||||
if _pattern_matches(path, rel, p):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
root = root.resolve()
|
||||
files: dict[FileType, list[str]] = {
|
||||
@@ -347,6 +411,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
|
||||
skipped_sensitive: list[str] = []
|
||||
ignore_patterns = _load_graphifyignore(root)
|
||||
include_patterns = _load_graphifyinclude(root)
|
||||
|
||||
# Always include graphify-out/memory/ - query results filed back into the graph
|
||||
memory_dir = root / "graphify-out" / "memory"
|
||||
@@ -368,11 +433,13 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
dirnames.clear()
|
||||
continue
|
||||
if not in_memory_tree:
|
||||
# Prune noise dirs in-place so os.walk never descends into them
|
||||
# Prune noise dirs in-place so os.walk never descends into them.
|
||||
# Hidden dirs remain skipped by default, but .graphifyinclude can
|
||||
# opt in the exact hidden subtrees needed to reach allowlisted files.
|
||||
dirnames[:] = [
|
||||
d for d in dirnames
|
||||
if not d.startswith(".")
|
||||
and not _is_noise_dir(d)
|
||||
if not _is_noise_dir(d)
|
||||
and (not d.startswith(".") or _could_contain_included_path(dp / d, root, include_patterns))
|
||||
and not _is_ignored(dp / d, root, ignore_patterns)
|
||||
]
|
||||
for fname in filenames:
|
||||
@@ -389,9 +456,12 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
# For memory dir files, skip hidden/noise filtering
|
||||
in_memory = memory_dir.exists() and str(p).startswith(str(memory_dir))
|
||||
if not in_memory:
|
||||
# Hidden files are already excluded via dir pruning above,
|
||||
# but catch hidden files at the root level
|
||||
if p.name.startswith("."):
|
||||
try:
|
||||
rel_parts = p.relative_to(root).parts
|
||||
except ValueError:
|
||||
rel_parts = p.parts
|
||||
# Hidden files/directories are excluded unless this exact file is allowlisted.
|
||||
if any(part.startswith(".") for part in rel_parts) and not _is_included(p, root, include_patterns):
|
||||
continue
|
||||
# Skip files inside our own converted/ dir (avoid re-processing sidecars)
|
||||
if str(p).startswith(str(converted_dir)):
|
||||
@@ -442,6 +512,7 @@ def detect(root: Path, *, follow_symlinks: bool = False) -> dict:
|
||||
"warning": warning,
|
||||
"skipped_sensitive": skipped_sensitive,
|
||||
"graphifyignore_patterns": len(ignore_patterns),
|
||||
"graphifyinclude_patterns": len(include_patterns),
|
||||
}
|
||||
|
||||
|
||||
|
||||
+40
-7
@@ -25,6 +25,22 @@ COMMUNITY_COLORS = [
|
||||
MAX_NODES_FOR_VIZ = 5_000
|
||||
|
||||
|
||||
def _viz_node_limit() -> int:
|
||||
"""Return the effective viz node limit, honoring GRAPHIFY_VIZ_NODE_LIMIT env var.
|
||||
|
||||
Falls back to MAX_NODES_FOR_VIZ when the env var is unset, empty, or non-integer.
|
||||
Set to 0 to disable HTML viz unconditionally (useful for CI runners).
|
||||
"""
|
||||
import os
|
||||
raw = os.environ.get("GRAPHIFY_VIZ_NODE_LIMIT")
|
||||
if raw is None or not raw.strip():
|
||||
return MAX_NODES_FOR_VIZ
|
||||
try:
|
||||
return int(raw)
|
||||
except ValueError:
|
||||
return MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def _html_styles() -> str:
|
||||
return """<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
@@ -327,6 +343,15 @@ def to_json(G: nx.Graph, communities: dict[int, list[str]], output_path: str, *,
|
||||
if "confidence_score" not in link:
|
||||
conf = link.get("confidence", "EXTRACTED")
|
||||
link["confidence_score"] = _CONFIDENCE_SCORE_DEFAULTS.get(conf, 1.0)
|
||||
# Restore original edge direction. Undirected NetworkX storage may
|
||||
# canonicalize endpoint order, flipping `calls` and other directional
|
||||
# edges in graph.json. The build path stashes the true endpoints in
|
||||
# _src/_tgt for exactly this purpose (#563).
|
||||
true_src = link.pop("_src", None)
|
||||
true_tgt = link.pop("_tgt", None)
|
||||
if true_src is not None and true_tgt is not None:
|
||||
link["source"] = true_src
|
||||
link["target"] = true_tgt
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
with open(output_path, "w", encoding="utf-8") as f: # nosec
|
||||
json.dump(data, f, indent=2)
|
||||
@@ -386,15 +411,18 @@ def to_html(
|
||||
|
||||
Features: node size by degree, click-to-inspect panel, search box,
|
||||
community filter, physics clustering by community, confidence-styled edges.
|
||||
Raises ValueError if graph exceeds MAX_NODES_FOR_VIZ.
|
||||
Raises ValueError if graph exceeds the effective viz node limit
|
||||
(MAX_NODES_FOR_VIZ by default; overridable via GRAPHIFY_VIZ_NODE_LIMIT env var).
|
||||
|
||||
If member_counts is provided (aggregated community view), node sizes are
|
||||
based on community member counts rather than graph degree.
|
||||
"""
|
||||
if G.number_of_nodes() > MAX_NODES_FOR_VIZ:
|
||||
limit = _viz_node_limit()
|
||||
if G.number_of_nodes() > limit:
|
||||
raise ValueError(
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz. "
|
||||
f"Use --no-viz or reduce input size."
|
||||
f"Graph has {G.number_of_nodes()} nodes - too large for HTML viz "
|
||||
f"(limit: {limit}). Use --no-viz, raise GRAPHIFY_VIZ_NODE_LIMIT, "
|
||||
f"or reduce input size."
|
||||
)
|
||||
|
||||
node_community = _node_community_map(communities)
|
||||
@@ -431,14 +459,19 @@ def to_html(
|
||||
"degree": deg,
|
||||
})
|
||||
|
||||
# Build edges list
|
||||
# Build edges list. Restore original edge direction from _src/_tgt
|
||||
# (stashed by build.py for exactly this reason): undirected NetworkX
|
||||
# canonicalizes endpoint order, which would otherwise flip the arrow
|
||||
# for `calls` and `rationale_for` in the rendered graph (#563).
|
||||
vis_edges = []
|
||||
for u, v, data in G.edges(data=True):
|
||||
confidence = data.get("confidence", "EXTRACTED")
|
||||
relation = data.get("relation", "")
|
||||
true_src = data.get("_src", u)
|
||||
true_tgt = data.get("_tgt", v)
|
||||
vis_edges.append({
|
||||
"from": u,
|
||||
"to": v,
|
||||
"from": true_src,
|
||||
"to": true_tgt,
|
||||
"label": relation,
|
||||
"title": _html.escape(f"{relation} [{confidence}]"),
|
||||
"dashes": confidence != "EXTRACTED",
|
||||
|
||||
+68
-4
@@ -11,6 +11,29 @@ from typing import Callable, Any
|
||||
from .cache import load_cached, save_cached
|
||||
|
||||
|
||||
# AST node types that represent a member-expression callee
|
||||
# (`x.foo()`, `obj.bar()`, `Pkg::baz()`). Cross-file name-only resolution of
|
||||
# these is unsafe — without receiver type info we routinely link them to the
|
||||
# wrong target, producing phantom god nodes (e.g. every `Logger.log(...)` call
|
||||
# in a NestJS codebase collapsing onto a one-off `function log(...)` defined
|
||||
# in a smoke-test script). The cross-file resolver in `extract()` skips
|
||||
# entries whose `callee_node_type` falls in this set.
|
||||
_MEMBER_CALL_NODE_TYPES = frozenset({
|
||||
"member_expression", # JS / TS / Python attribute calls
|
||||
"selector_expression", # Go
|
||||
"field_expression", # Rust, C++, Scala
|
||||
"navigation_expression", # Swift, Kotlin
|
||||
"qualified_identifier", # C++ (Foo::bar())
|
||||
"scoped_identifier", # Rust (foo::bar())
|
||||
"scoped_call_expression", # PHP (Foo::bar())
|
||||
"member_call_expression", # PHP ($obj->method())
|
||||
"field_access", # Java
|
||||
"method_invocation", # Java (when receiver-qualified)
|
||||
"dot", # Elixir
|
||||
"_zig_dotted_callee", # synthetic marker for Zig (callee text contains ".")
|
||||
})
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
"""Build a stable node ID from one or more name parts."""
|
||||
combined = "_".join(p.strip("_.") for p in parts if p)
|
||||
@@ -1172,13 +1195,16 @@ def _extract_generic(path: Path, config: LanguageConfig) -> dict:
|
||||
"weight": 1.0,
|
||||
})
|
||||
elif callee_name and not tgt_nid:
|
||||
# Callee not in this file — save for cross-file resolution in extract()
|
||||
# Callee not in this file — save for cross-file resolution in extract().
|
||||
# Track the AST node type so the cross-file resolver can refuse to
|
||||
# name-match member-expression callees (`x.foo()`).
|
||||
raw_calls.append({
|
||||
"caller_nid": caller_nid,
|
||||
"callee": callee_name,
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
|
||||
# Helper function calls: config('foo.bar') → uses_config edge to "foo"
|
||||
@@ -2131,6 +2157,7 @@ def extract_go(path: Path) -> dict:
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2311,6 +2338,7 @@ def extract_rust(path: Path) -> dict:
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": func_node.type if func_node is not None else None,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2482,6 +2510,13 @@ def extract_zig(path: Path) -> dict:
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
# Zig: callee is `_read_text(fn, source).split(".")[-1]`,
|
||||
# so a "." in the original text means it was a member call.
|
||||
"callee_node_type": (
|
||||
"_zig_dotted_callee"
|
||||
if "." in _read_text(fn, source)
|
||||
else fn.type
|
||||
),
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2647,6 +2682,7 @@ def extract_powershell(path: Path) -> dict:
|
||||
"is_member_call": False,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
"callee_node_type": "command_name",
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -2699,8 +2735,17 @@ def _resolve_cross_file_imports(
|
||||
stem = Path(src).stem
|
||||
label = node.get("label", "")
|
||||
nid = node.get("id", "")
|
||||
# Only index real classes/functions (not file nodes, not method stubs)
|
||||
if label and not label.endswith((")", ".py")) and "_" not in label[:1]:
|
||||
# Index class-level entities only. Function/method labels end in "()"
|
||||
# so are excluded by the `endswith(")")` filter; file nodes end in ".py";
|
||||
# private/internal labels start with "_"; rationale nodes carry
|
||||
# file_type=="rationale" and must never participate in cross-file
|
||||
# import resolution (#563).
|
||||
if (
|
||||
label
|
||||
and not label.endswith((")", ".py"))
|
||||
and "_" not in label[:1]
|
||||
and node.get("file_type") != "rationale"
|
||||
):
|
||||
stem_to_entities.setdefault(stem, {})[label] = nid
|
||||
|
||||
# Pass 2: for each file, find `from .X import A, B, C` and resolve
|
||||
@@ -2711,12 +2756,15 @@ def _resolve_cross_file_imports(
|
||||
stem = _file_stem(path)
|
||||
str_path = str(path)
|
||||
|
||||
# Find all classes defined in this file (the importers)
|
||||
# Find all classes defined in this file (the importers).
|
||||
# Excludes rationale nodes whose labels happen not to end in ")" or ".py"
|
||||
# but which must never be treated as importing entities (#563).
|
||||
local_classes = [
|
||||
n["id"] for n in file_result.get("nodes", [])
|
||||
if n.get("source_file") == str_path
|
||||
and not n["label"].endswith((")", ".py"))
|
||||
and n["id"] != _make_id(stem) # exclude file-level node
|
||||
and n.get("file_type") != "rationale"
|
||||
]
|
||||
if not local_classes:
|
||||
continue
|
||||
@@ -3253,6 +3301,9 @@ def extract_elixir(path: Path) -> dict:
|
||||
"is_member_call": is_member_call,
|
||||
"source_file": str_path,
|
||||
"source_location": f"L{node.start_point[0] + 1}",
|
||||
# Elixir: `child` is the node we just inspected — `dot` for
|
||||
# `Mod.fn(...)`, `identifier` for a bare local call.
|
||||
"callee_node_type": child.type,
|
||||
})
|
||||
for child in node.children:
|
||||
walk_calls(child, caller_nid)
|
||||
@@ -3435,8 +3486,13 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
# Cross-file call resolution for all languages
|
||||
# Each extractor saved unresolved calls in raw_calls. Now that we have all
|
||||
# nodes from all files, resolve any callee that exists in another file.
|
||||
# Build label -> node_id index for cross-file call resolution.
|
||||
# Skip rationale nodes (their labels are docstring text, not callable
|
||||
# identifiers, and they were polluting matches for short names — #563).
|
||||
global_label_to_nid: dict[str, str] = {}
|
||||
for n in all_nodes:
|
||||
if n.get("file_type") == "rationale":
|
||||
continue
|
||||
raw = n.get("label", "")
|
||||
normalised = raw.strip("()").lstrip(".")
|
||||
if normalised:
|
||||
@@ -3445,6 +3501,14 @@ def extract(paths: list[Path], cache_root: Path | None = None) -> dict:
|
||||
existing_pairs = {(e["source"], e["target"]) for e in all_edges}
|
||||
for result in per_file:
|
||||
for rc in result.get("raw_calls", []):
|
||||
# Member-expression callees (`x.foo()`, `obj.bar()`, `Pkg::baz()`)
|
||||
# cannot be safely resolved by bare property name across files —
|
||||
# without receiver-type analysis we routinely link them to the
|
||||
# wrong target, producing phantom god nodes (e.g. every
|
||||
# `Logger.log(...)` call collapsing onto a one-off
|
||||
# `function log(...)` defined in a smoke-test script).
|
||||
if rc.get("callee_node_type") in _MEMBER_CALL_NODE_TYPES:
|
||||
continue
|
||||
callee = rc.get("callee", "")
|
||||
if not callee:
|
||||
continue
|
||||
|
||||
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
@@ -240,7 +240,7 @@ Process each file one at a time. For each file:
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
+10
-4
@@ -293,10 +293,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -289,10 +289,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
@@ -819,11 +825,22 @@ deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
+10
-4
@@ -290,10 +290,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -239,7 +239,7 @@ Process each file one at a time. For each file:
|
||||
- DEEP_MODE (if --mode deep): be aggressive with INFERRED edges
|
||||
- Semantic similarity: if two concepts solve the same problem without a structural link, add `semantically_similar_to` INFERRED edge (confidence 0.6-0.95). Non-obvious cross-file links only.
|
||||
- Hyperedges: if 3+ nodes share a concept/flow not captured by pairwise edges, add a hyperedge. Max 3 per file.
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0, INFERRED=0.6-0.9 (reason individually), AMBIGUOUS=0.1-0.3
|
||||
- confidence_score REQUIRED on every edge: EXTRACTED=1.0; INFERRED ∈ {0.55, 0.65, 0.75, 0.85, 0.95} forced-rank (NEVER 0.5 — pick the closest discrete value or mark AMBIGUOUS); AMBIGUOUS=0.1-0.3
|
||||
3. Accumulate results across all files
|
||||
|
||||
Schema for each file's output:
|
||||
|
||||
@@ -291,10 +291,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
+10
-4
@@ -280,10 +280,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
@@ -279,10 +279,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
|
||||
+22
-5
@@ -337,10 +337,16 @@ If a file has YAML frontmatter (--- ... ---), copy source_url, captured_at, auth
|
||||
|
||||
confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a default:
|
||||
- EXTRACTED edges: confidence_score = 1.0 always
|
||||
- INFERRED edges: reason about each edge individually.
|
||||
Direct structural evidence (shared data structure, clear dependency): 0.8-0.9.
|
||||
Reasonable inference with some uncertainty: 0.6-0.7.
|
||||
Weak or speculative: 0.4-0.5. Most edges should be 0.6-0.9, not 0.5.
|
||||
- INFERRED edges: pick exactly ONE value from this set — never 0.5:
|
||||
0.95 direct structural evidence (shared data structure, named cross-file reference).
|
||||
0.85 strong inference (clear functional alignment, no direct symbol link).
|
||||
0.75 reasonable inference (shared problem domain + similar shape, requires interpretation).
|
||||
0.65 weak inference (thematically related, no shape evidence).
|
||||
0.55 speculative but plausible (surface-level co-occurrence only).
|
||||
Models follow discrete rubrics better than continuous ranges; the bimodal
|
||||
distribution observed in production (>50% at 0.5, >40% at 0.85+) shows the
|
||||
range guidance is being collapsed to a binary. If no value above fits, mark
|
||||
the edge AMBIGUOUS rather than picking 0.4 or below.
|
||||
- AMBIGUOUS edges: 0.1-0.3
|
||||
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is the filename without extension and entity is the symbol name, both normalized (lowercase, non-alphanumeric chars replaced with `_`). Example: `src/auth/session.py` + `ValidateToken` → `session_validatetoken`. This must match the ID the AST extractor generates so cross-references between code and semantic nodes connect correctly. CRITICAL: never append chunk numbers, sequence numbers, or any suffix to an ID (no `_c1`, `_c2`, `_chunk2`, etc.). IDs must be deterministic from the label alone — the same entity must always produce the same ID regardless of which chunk processes it.
|
||||
@@ -923,7 +929,10 @@ deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
print(f'Pruned {len(to_remove)} ghost nodes from {len(deleted)} deleted file(s)')
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
@@ -939,6 +948,14 @@ merged_out = {
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
|
||||
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
```
|
||||
|
||||
|
||||
+21
-1
@@ -7,7 +7,18 @@ import networkx as nx
|
||||
|
||||
|
||||
def _safe_filename(name: str) -> str:
|
||||
return name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
"""Make a label safe for use as a filename across platforms.
|
||||
|
||||
Substitutes characters that Windows reserves in filenames
|
||||
(< > : " / \\ | ? *) and strips trailing dots/spaces, also reserved.
|
||||
Falls back to 'unnamed' for empty results and caps length at 200
|
||||
chars to stay well under common filesystem limits.
|
||||
"""
|
||||
import re
|
||||
s = name.replace("/", "-").replace(" ", "_").replace(":", "-")
|
||||
s = re.sub(r'[<>:"/\\|?*]', '_', s)
|
||||
s = s.strip('. ')
|
||||
return s[:200] if s else 'unnamed'
|
||||
|
||||
|
||||
def _cross_community_links(G: nx.Graph, nodes: list[str], own_cid: int, labels: dict[int, str]) -> list[tuple[str, int]]:
|
||||
@@ -185,6 +196,15 @@ def to_wiki(
|
||||
out = Path(output_dir)
|
||||
out.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
# Clear stale .md files from previous runs to prevent orphan accumulation.
|
||||
# Community labels are LLM-generated (per skill.md Step 5) and non-deterministic
|
||||
# across runs — the same conceptual community may be named differently each time
|
||||
# (e.g. "AutoAgent Skills" → "AutoAgent Methodology"), leaving the previous file
|
||||
# as an orphan. Since to_wiki() owns wiki/ entirely (always writes the full set),
|
||||
# it can safely clear .md files at the start of each call.
|
||||
for old_article in out.glob("*.md"):
|
||||
old_article.unlink()
|
||||
|
||||
labels = community_labels or {cid: f"Community {cid}" for cid in communities}
|
||||
cohesion = cohesion or {}
|
||||
god_nodes_data = god_nodes_data or []
|
||||
|
||||
@@ -51,6 +51,7 @@ leiden = ["graspologic; python_version < '3.13'"]
|
||||
office = ["python-docx", "openpyxl"]
|
||||
video = ["faster-whisper", "yt-dlp"]
|
||||
kimi = ["openai"]
|
||||
test = ["pytest>=7", "pytest-cov"]
|
||||
all = ["mcp", "neo4j", "pypdf", "html2text", "watchdog", "graspologic; python_version < '3.13'", "python-docx", "openpyxl", "faster-whisper", "yt-dlp", "matplotlib", "openai"]
|
||||
|
||||
[project.scripts]
|
||||
|
||||
@@ -104,6 +104,42 @@ def test_graphifyignore_missing_is_fine(tmp_path):
|
||||
assert result["graphifyignore_patterns"] == 0
|
||||
|
||||
|
||||
def test_graphifyinclude_allows_curated_files_inside_hidden_dirs(tmp_path):
|
||||
"""A .graphifyinclude allowlist can opt curated hidden markdown paths into detect()."""
|
||||
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
|
||||
plans = tmp_path / ".hermes" / "plans"
|
||||
plans.mkdir(parents=True)
|
||||
(plans / "knowledge-plan.md").write_text("# Knowledge Plan\nThis is the searchable plan.")
|
||||
context = tmp_path / ".hermes" / "context"
|
||||
context.mkdir(parents=True)
|
||||
(context / "scratch.md").write_text("# Scratch\nThis should stay out.")
|
||||
(tmp_path / "README.md").write_text("# Visible\nVisible docs still work.")
|
||||
|
||||
result = detect(tmp_path)
|
||||
docs = result["files"]["document"]
|
||||
|
||||
assert any(".hermes/plans/knowledge-plan.md" in f for f in docs)
|
||||
assert not any(".hermes/context/scratch.md" in f for f in docs)
|
||||
assert any("README.md" in f for f in docs)
|
||||
assert result["graphifyinclude_patterns"] == 1
|
||||
|
||||
|
||||
def test_graphifyinclude_does_not_override_sensitive_file_skips(tmp_path):
|
||||
"""Even allowlisted hidden paths must not index secret-looking files."""
|
||||
(tmp_path / ".graphifyinclude").write_text(".hermes/plans/**/*.md\n")
|
||||
plans = tmp_path / ".hermes" / "plans"
|
||||
plans.mkdir(parents=True)
|
||||
(plans / "api_token.md").write_text("token: should not be indexed")
|
||||
(plans / "public-plan.md").write_text("# Public Plan\nSafe searchable material.")
|
||||
|
||||
result = detect(tmp_path)
|
||||
docs = result["files"]["document"]
|
||||
|
||||
assert any(".hermes/plans/public-plan.md" in f for f in docs)
|
||||
assert not any("api_token.md" in f for f in docs)
|
||||
assert len(result["skipped_sensitive"]) == 1
|
||||
|
||||
|
||||
def test_graphifyignore_comments_ignored(tmp_path):
|
||||
"""Comment lines in .graphifyignore are not treated as patterns."""
|
||||
(tmp_path / ".graphifyignore").write_text("# this is a comment\n\nmain.py\n")
|
||||
|
||||
+67
-1
@@ -1,9 +1,19 @@
|
||||
import json
|
||||
import os
|
||||
import tempfile
|
||||
import pytest
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster
|
||||
from graphify.export import to_json, to_cypher, to_graphml, to_html, to_canvas
|
||||
from graphify.export import (
|
||||
to_json,
|
||||
to_cypher,
|
||||
to_graphml,
|
||||
to_html,
|
||||
to_canvas,
|
||||
_viz_node_limit,
|
||||
MAX_NODES_FOR_VIZ,
|
||||
)
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -127,6 +137,62 @@ def test_to_html_contains_nodes_and_edges():
|
||||
assert "RAW_EDGES" in content
|
||||
|
||||
|
||||
# --- GRAPHIFY_VIZ_NODE_LIMIT env var --------------------------------------------
|
||||
|
||||
@pytest.fixture
|
||||
def restore_viz_env(monkeypatch):
|
||||
"""Ensure each test runs without GRAPHIFY_VIZ_NODE_LIMIT bleeding across cases."""
|
||||
monkeypatch.delenv("GRAPHIFY_VIZ_NODE_LIMIT", raising=False)
|
||||
yield
|
||||
|
||||
|
||||
def test_viz_node_limit_default(restore_viz_env):
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_viz_node_limit_env_override_higher(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "20000")
|
||||
assert _viz_node_limit() == 20000
|
||||
|
||||
|
||||
def test_viz_node_limit_env_override_zero_disables(restore_viz_env, monkeypatch):
|
||||
"""Setting to 0 lets users disable HTML viz unconditionally (CI runners)."""
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "0")
|
||||
assert _viz_node_limit() == 0
|
||||
|
||||
|
||||
def test_viz_node_limit_invalid_falls_back_to_default(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "not-an-int")
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_viz_node_limit_empty_falls_back_to_default(restore_viz_env, monkeypatch):
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", " ")
|
||||
assert _viz_node_limit() == MAX_NODES_FOR_VIZ
|
||||
|
||||
|
||||
def test_to_html_raises_with_lowered_limit(restore_viz_env, monkeypatch):
|
||||
"""Lowering the limit below the test graph's size triggers ValueError."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "1")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
with pytest.raises(ValueError, match="too large for HTML viz"):
|
||||
to_html(G, communities, str(out))
|
||||
|
||||
|
||||
def test_to_html_writes_with_raised_limit(restore_viz_env, monkeypatch):
|
||||
"""Raising the limit above the graph's size lets to_html proceed normally."""
|
||||
G = make_graph()
|
||||
communities = cluster(G)
|
||||
monkeypatch.setenv("GRAPHIFY_VIZ_NODE_LIMIT", "100000")
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
out = Path(tmp) / "graph.html"
|
||||
to_html(G, communities, str(out))
|
||||
assert out.exists()
|
||||
|
||||
|
||||
def test_to_html_member_counts_accepted():
|
||||
"""to_html accepts member_counts without raising."""
|
||||
G = make_graph()
|
||||
|
||||
@@ -123,3 +123,30 @@ def test_hook_skips_head_on_exe():
|
||||
"""Hook script must skip shebang extraction for .exe binaries (Windows)."""
|
||||
from graphify.hooks import _PYTHON_DETECT
|
||||
assert "*.exe) _SHEBANG=" in _PYTHON_DETECT or '*.exe)' in _PYTHON_DETECT
|
||||
|
||||
|
||||
def test_hooks_dir_expands_tilde(tmp_path, monkeypatch):
|
||||
"""_hooks_dir must call expanduser() so ~/... paths in core.hooksPath resolve correctly."""
|
||||
from graphify.hooks import _hooks_dir
|
||||
import types
|
||||
|
||||
repo = _make_git_repo(tmp_path)
|
||||
custom_hooks = tmp_path / "custom_hooks"
|
||||
custom_hooks.mkdir()
|
||||
|
||||
# expanduser() reads $HOME, so override it to make ~/custom_hooks predictable
|
||||
monkeypatch.setenv("HOME", str(tmp_path))
|
||||
|
||||
real_run = subprocess.run
|
||||
|
||||
def fake_run(cmd, **kwargs):
|
||||
if isinstance(cmd, list) and "config" in cmd and "core.hooksPath" in cmd:
|
||||
return types.SimpleNamespace(returncode=0, stdout="~/custom_hooks")
|
||||
return real_run(cmd, **kwargs)
|
||||
|
||||
monkeypatch.setattr(subprocess, "run", fake_run)
|
||||
|
||||
resolved = _hooks_dir(repo)
|
||||
assert resolved == custom_hooks, (
|
||||
f"expected {custom_hooks}, got {resolved} — tilde was not expanded"
|
||||
)
|
||||
@@ -1,4 +1,5 @@
|
||||
"""Tests for graphify install --platform routing."""
|
||||
import json
|
||||
from pathlib import Path
|
||||
from unittest.mock import patch
|
||||
import pytest
|
||||
@@ -129,6 +130,69 @@ def test_codex_agents_install_writes_agents_md(tmp_path):
|
||||
assert "GRAPH_REPORT.md" in agents_md.read_text()
|
||||
|
||||
|
||||
def test_codex_agents_install_writes_user_prompt_submit_hook(tmp_path):
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
command = hooks["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"]
|
||||
|
||||
assert "UserPromptSubmit" in hooks["hooks"]
|
||||
assert "PreToolUse" not in hooks["hooks"]
|
||||
assert "UserPromptSubmit" in command
|
||||
assert "additionalContext" in command
|
||||
assert "graphify-out/GRAPH_REPORT.md" in command
|
||||
|
||||
|
||||
def test_codex_agents_install_removes_only_graphify_generated_hooks(tmp_path):
|
||||
from graphify.__main__ import _LEGACY_CODEX_PRE_TOOL_HOOK
|
||||
|
||||
unrelated_hook = {
|
||||
"matcher": "Bash",
|
||||
"hooks": [
|
||||
{
|
||||
"type": "command",
|
||||
"command": "echo graphify for my own plugin",
|
||||
}
|
||||
],
|
||||
}
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True)
|
||||
hooks_path.write_text(json.dumps({
|
||||
"hooks": {
|
||||
"PreToolUse": [
|
||||
_LEGACY_CODEX_PRE_TOOL_HOOK,
|
||||
unrelated_hook,
|
||||
]
|
||||
}
|
||||
}))
|
||||
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
pre_tool = hooks["hooks"].get("PreToolUse", [])
|
||||
user_prompt = hooks["hooks"].get("UserPromptSubmit", [])
|
||||
|
||||
assert pre_tool == [unrelated_hook]
|
||||
assert len(user_prompt) == 1
|
||||
assert "graphify-out/GRAPH_REPORT.md" in user_prompt[0]["hooks"][0]["command"]
|
||||
|
||||
|
||||
def test_codex_agents_install_preserves_non_object_hooks_value(tmp_path):
|
||||
hooks_path = tmp_path / ".codex" / "hooks.json"
|
||||
hooks_path.parent.mkdir(parents=True)
|
||||
hooks_path.write_text(json.dumps({
|
||||
"hooks": ["recoverable user config"],
|
||||
"other": {"keep": True},
|
||||
}))
|
||||
|
||||
_agents_install(tmp_path, "codex")
|
||||
|
||||
hooks = json.loads(hooks_path.read_text())
|
||||
assert hooks["hooks"] == ["recoverable user config"]
|
||||
assert hooks["other"] == {"keep": True}
|
||||
|
||||
|
||||
def test_opencode_agents_install_writes_agents_md(tmp_path):
|
||||
_agents_install(tmp_path, "opencode")
|
||||
assert (tmp_path / "AGENTS.md").exists()
|
||||
|
||||
@@ -0,0 +1,326 @@
|
||||
"""Regression tests for issue #563.
|
||||
|
||||
Two extractor bugs were inflating god-node centrality:
|
||||
|
||||
1. `_resolve_cross_file_imports` accepted rationale nodes as "importing
|
||||
classes", causing a phantom `<file>_rationale_N --uses--> ImportedThing`
|
||||
edge for every imported entity in every file with docstrings. Cross-file
|
||||
call resolution had the same leak via `global_label_to_nid`.
|
||||
|
||||
2. The `to_json` exporter serialized a NetworkX undirected graph and lost
|
||||
edge direction; `_src` / `_tgt` were stashed by `build` precisely to
|
||||
restore direction at export time, but were not consulted.
|
||||
|
||||
Both bugs are observable in the AST-only path (no LLM required).
|
||||
|
||||
Note: the fixture uses module name ``jobq`` rather than ``queue`` to avoid
|
||||
colliding with the Python stdlib ``queue`` module that graphify's update
|
||||
path imports.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import textwrap
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def _write_repro(root: Path) -> None:
|
||||
(root / "jobq.py").write_text(textwrap.dedent('''
|
||||
"""Job-queue module — provides SQLiteQueue for idempotent job tracking."""
|
||||
|
||||
|
||||
class SQLiteQueue:
|
||||
"""Lightweight SQLite-backed queue.
|
||||
|
||||
Used by middleware routers and CLI commands to enqueue work and
|
||||
deduplicate via idempotency keys.
|
||||
"""
|
||||
|
||||
def check_idempotency(self, key):
|
||||
"""Return existing lead for key, or None."""
|
||||
return None
|
||||
|
||||
def enqueue(self, payload):
|
||||
"""Persist payload to the queue."""
|
||||
return True
|
||||
''').lstrip())
|
||||
|
||||
(root / "contact_form.py").write_text(textwrap.dedent('''
|
||||
"""HTTP router for the contact form endpoint."""
|
||||
from jobq import SQLiteQueue
|
||||
|
||||
q = SQLiteQueue()
|
||||
|
||||
|
||||
def contact_form(payload_obj):
|
||||
"""Handle a contact form submission.
|
||||
|
||||
Idempotency is keyed on payload_obj.idempotency_key.
|
||||
"""
|
||||
existing_lead = q.check_idempotency(payload_obj.idempotency_key)
|
||||
if existing_lead:
|
||||
return existing_lead
|
||||
q.enqueue(payload_obj)
|
||||
return {"ok": True}
|
||||
''').lstrip())
|
||||
|
||||
(root / "test_customer_dedup.py").write_text(textwrap.dedent('''
|
||||
"""Tests for customer dedup — exercises phone normalization and Odoo tagging."""
|
||||
from jobq import SQLiteQueue
|
||||
from contact_form import contact_form
|
||||
|
||||
|
||||
def test_us_phone_no_country_code():
|
||||
"""US phone without country code uses default region US -> +1 prefix."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_uk_phone_with_prefix():
|
||||
"""UK phone with +44 prefix parses regardless of default region."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_invalid_phone_returns_none():
|
||||
"""Phone that parses but isn't a valid number -> None."""
|
||||
assert True
|
||||
|
||||
|
||||
def test_odoo_tag_missing_still_chatter():
|
||||
"""If the tag isn't seeded, still post the chatter note."""
|
||||
queue = SQLiteQueue()
|
||||
queue.enqueue({})
|
||||
contact_form(None)
|
||||
''').lstrip())
|
||||
|
||||
|
||||
def _run_graphify_update(root: Path) -> dict:
|
||||
result = subprocess.run(
|
||||
[sys.executable, "-m", "graphify", "update", str(root)],
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=str(root),
|
||||
)
|
||||
assert result.returncode == 0, (
|
||||
f"graphify update failed: {result.stderr}\nstdout: {result.stdout}"
|
||||
)
|
||||
graph_path = root / "graphify-out" / "graph.json"
|
||||
assert graph_path.exists(), f"graph.json not produced. stderr: {result.stderr}"
|
||||
return json.loads(graph_path.read_text())
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def repro_graph(tmp_path: Path) -> dict:
|
||||
_write_repro(tmp_path)
|
||||
return _run_graphify_update(tmp_path)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 1: rationale node leakage into cross-file resolvers
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _file_type_map(graph: dict) -> dict[str, str]:
|
||||
"""Map node id -> file_type from the serialized graph.
|
||||
|
||||
Identifying rationale nodes via node metadata (file_type == "rationale")
|
||||
is more durable than substring-matching on the id, which couples to the
|
||||
current `<stem>_rationale_<line>` naming scheme.
|
||||
"""
|
||||
return {n["id"]: n.get("file_type", "") for n in graph["nodes"]}
|
||||
|
||||
|
||||
def test_no_rationale_nodes_in_uses_or_calls_edges(repro_graph):
|
||||
"""Rationale nodes describe code; they cannot `use`, `call`, or `reference`
|
||||
anything. The only relation a rationale node may participate in is
|
||||
`rationale_for` (extractor emits `rationale --rationale_for--> parent`)."""
|
||||
ftype = _file_type_map(repro_graph)
|
||||
bad = [
|
||||
e for e in repro_graph["links"]
|
||||
if (ftype.get(e["source"]) == "rationale"
|
||||
or ftype.get(e["target"]) == "rationale")
|
||||
and e["relation"] != "rationale_for"
|
||||
]
|
||||
assert bad == [], (
|
||||
f"Rationale nodes must only appear in rationale_for edges. "
|
||||
f"Found {len(bad)} bad edges with relations "
|
||||
f"{sorted({e['relation'] for e in bad})}: {bad[:3]}"
|
||||
)
|
||||
|
||||
|
||||
def test_rationale_for_direction_is_rationale_to_parent(repro_graph):
|
||||
"""Rationale_for edges encode "this docstring fragment is the rationale
|
||||
for this code entity": source is the rationale node, target is the parent.
|
||||
The export-side direction restore (#563) was the only thing that made
|
||||
this hold under undirected NetworkX storage."""
|
||||
ftype = _file_type_map(repro_graph)
|
||||
rats = [e for e in repro_graph["links"] if e["relation"] == "rationale_for"]
|
||||
assert rats, "expected some rationale_for edges in the repro"
|
||||
bad = [e for e in rats if ftype.get(e["source"]) != "rationale"]
|
||||
assert bad == [], (
|
||||
f"rationale_for edges must have a rationale node as source. "
|
||||
f"Found {len(bad)} flipped: {bad[:3]}"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 2: `calls` direction must be caller -> callee
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _calls(graph: dict) -> list[tuple[str, str]]:
|
||||
return [
|
||||
(e["source"], e["target"])
|
||||
for e in graph["links"]
|
||||
if e.get("relation") == "calls"
|
||||
]
|
||||
|
||||
|
||||
def test_calls_direction_is_caller_to_callee(repro_graph):
|
||||
"""The exact directions reported as inverted in #563 must hold."""
|
||||
calls = _calls(repro_graph)
|
||||
|
||||
# contact_form() calls SQLiteQueue.check_idempotency() and SQLiteQueue.enqueue()
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_check_idempotency",
|
||||
) in calls, f"expected caller->callee edge missing. got: {calls}"
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_enqueue",
|
||||
) in calls, f"contact_form->enqueue edge missing. got: {calls}"
|
||||
|
||||
# The test function calls contact_form()
|
||||
assert (
|
||||
"test_customer_dedup_test_odoo_tag_missing_still_chatter",
|
||||
"contact_form_contact_form",
|
||||
) in calls, f"test->contact_form edge missing. got: {calls}"
|
||||
|
||||
# And critically, none of the inversions exist:
|
||||
inversions = {
|
||||
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
|
||||
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
|
||||
("contact_form_contact_form",
|
||||
"test_customer_dedup_test_odoo_tag_missing_still_chatter"),
|
||||
}
|
||||
leaked = set(calls) & inversions
|
||||
assert not leaked, f"Found inverted calls edges: {leaked}"
|
||||
|
||||
|
||||
def test_calls_direction_on_existing_sample_calls_fixture():
|
||||
"""Pin the direction on the in-tree fixture too — adds direction
|
||||
coverage to the existing AST extractor tests."""
|
||||
from graphify.extract import extract_python
|
||||
|
||||
fixture = REPO_ROOT / "tests" / "fixtures" / "sample_calls.py"
|
||||
result = extract_python(fixture)
|
||||
|
||||
calls = [
|
||||
(e["source"], e["target"])
|
||||
for e in result["edges"]
|
||||
if e.get("relation") == "calls"
|
||||
]
|
||||
assert calls, "sample_calls.py must produce some calls edges"
|
||||
|
||||
# In sample_calls.py:
|
||||
# compute_score and normalize are LEAF functions — they call nothing.
|
||||
# They must appear as callees, never as callers.
|
||||
leaf_callers = [
|
||||
src for src, _ in calls
|
||||
if src.endswith("compute_score") or src.endswith("normalize")
|
||||
]
|
||||
assert leaf_callers == [], (
|
||||
f"Leaf functions appearing as callers means direction is inverted: "
|
||||
f"{leaf_callers}"
|
||||
)
|
||||
|
||||
# And they should appear at least once as callees.
|
||||
leaf_callees = [
|
||||
tgt for _, tgt in calls
|
||||
if "compute_score" in tgt or "normalize" in tgt
|
||||
]
|
||||
assert leaf_callees, f"leaf functions should appear as callees. got: {calls}"
|
||||
|
||||
|
||||
def test_src_tgt_metadata_not_leaked_into_graph_json(repro_graph):
|
||||
"""The _src/_tgt direction-preservation fields are an internal detail
|
||||
of the build path; they must be consumed by the exporter and stripped
|
||||
from graph.json."""
|
||||
leaks = [e for e in repro_graph["links"] if "_src" in e or "_tgt" in e]
|
||||
assert leaks == [], (
|
||||
f"_src/_tgt are internal; must not appear in graph.json. Leaks: {leaks[:3]}"
|
||||
)
|
||||
|
||||
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
# Bug 2 (HTML export): graph.html arrows must respect direction too
|
||||
# ─────────────────────────────────────────────────────────────────────────────
|
||||
|
||||
|
||||
def _vis_edges_from_html(html: str) -> list[dict]:
|
||||
"""Extract the vis.js edges array embedded in graph.html.
|
||||
|
||||
`_html_script` emits `const RAW_EDGES = <json>;` — pull that JSON out
|
||||
directly rather than parsing the surrounding script.
|
||||
"""
|
||||
import re
|
||||
m = re.search(r"const RAW_EDGES = (\[.*?\]);", html, re.DOTALL)
|
||||
assert m, "could not locate RAW_EDGES in graph.html"
|
||||
return json.loads(m.group(1))
|
||||
|
||||
|
||||
def test_to_html_preserves_calls_and_rationale_for_direction(tmp_path: Path):
|
||||
"""to_html must read _src/_tgt before assigning vis.js `from`/`to`,
|
||||
otherwise undirected NetworkX storage flips arrows on render (#563)."""
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
|
||||
_write_repro(tmp_path)
|
||||
repro_graph = _run_graphify_update(tmp_path)
|
||||
|
||||
G = build_from_json(repro_graph)
|
||||
out_html = tmp_path / "graph.html"
|
||||
to_html(G, communities={0: list(G.nodes())}, output_path=str(out_html))
|
||||
|
||||
vis_edges = _vis_edges_from_html(out_html.read_text(encoding="utf-8"))
|
||||
pairs = {(e["from"], e["to"]): e.get("label") for e in vis_edges}
|
||||
|
||||
# rationale_for: source must be the rationale node (file_type metadata
|
||||
# isn't on vis_edges, so we check via the json graph's node map).
|
||||
ftype = _file_type_map(repro_graph)
|
||||
rats_html = [
|
||||
(frm, to) for (frm, to), rel in pairs.items() if rel == "rationale_for"
|
||||
]
|
||||
assert rats_html, "expected rationale_for edges in graph.html"
|
||||
flipped_rats = [
|
||||
(frm, to) for (frm, to) in rats_html if ftype.get(frm) != "rationale"
|
||||
]
|
||||
assert flipped_rats == [], (
|
||||
f"rationale_for arrows in graph.html must point rationale->parent. "
|
||||
f"Flipped: {flipped_rats[:3]}"
|
||||
)
|
||||
|
||||
# calls: pin the same caller->callee directions asserted on graph.json.
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_check_idempotency",
|
||||
) in pairs, "contact_form->check_idempotency arrow missing in graph.html"
|
||||
assert (
|
||||
"contact_form_contact_form",
|
||||
"jobq_sqlitequeue_enqueue",
|
||||
) in pairs, "contact_form->enqueue arrow missing in graph.html"
|
||||
|
||||
# And the inversions must not be present.
|
||||
inversions = {
|
||||
("jobq_sqlitequeue_check_idempotency", "contact_form_contact_form"),
|
||||
("jobq_sqlitequeue_enqueue", "contact_form_contact_form"),
|
||||
}
|
||||
leaked = inversions & {
|
||||
(frm, to) for (frm, to), rel in pairs.items() if rel == "calls"
|
||||
}
|
||||
assert not leaked, f"Inverted calls arrows in graph.html: {leaked}"
|
||||
@@ -0,0 +1,177 @@
|
||||
"""
|
||||
Regression test for the cross-file member-call name-collision bug fixed by
|
||||
the `_MEMBER_CALL_NODE_TYPES` resolver guard.
|
||||
|
||||
Bug summary
|
||||
-----------
|
||||
graphify's per-language AST extractors strip member-expression callees
|
||||
(`this.logger.log(...)`, `obj.find(...)`, `Pkg::baz(...)`) down to the
|
||||
trailing identifier (`log`, `find`, `baz`) and queue them in `raw_calls`
|
||||
for cross-file resolution. The cross-file resolver then matches that bare
|
||||
identifier against a global lowercase name → id map. If any other file in
|
||||
the corpus defines a top-level helper with the same name (e.g. a
|
||||
`function log(id, name, pass) { ... }` in a smoke-test script), every
|
||||
unrelated `Logger.log` / `this.logger.log` / `logger.log` call across the
|
||||
codebase resolves to that single helper, producing a phantom god node with
|
||||
hundreds of bogus INFERRED edges.
|
||||
|
||||
Fix
|
||||
---
|
||||
Each `raw_calls.append(...)` now records `callee_node_type` (the AST node
|
||||
type of the callee). The cross-file resolver in `extract()` skips entries
|
||||
whose `callee_node_type` is in `_MEMBER_CALL_NODE_TYPES`.
|
||||
|
||||
Run with:
|
||||
pytest tests/test_member_call_resolution.py -v
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify.extract import extract
|
||||
|
||||
try:
|
||||
from graphify.extract import _MEMBER_CALL_NODE_TYPES
|
||||
except ImportError:
|
||||
_MEMBER_CALL_NODE_TYPES = None # patched constant absent on unpatched code
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Source fixtures — written verbatim to a tmp dir so tree-sitter sees real files
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
_SMOKE_TEST_JS = """\
|
||||
const results = [];
|
||||
|
||||
function log(id, name, pass, detail = '') {
|
||||
const status = pass ? 'PASS' : 'FAIL';
|
||||
console.log(`${id} ${status} ${name}`);
|
||||
results.push({ id, name, pass });
|
||||
}
|
||||
|
||||
function testAuth() {
|
||||
log('A1', 'auth-login', true);
|
||||
log('A2', 'auth-refresh', true);
|
||||
}
|
||||
|
||||
testAuth();
|
||||
"""
|
||||
|
||||
_NESTJS_SERVICE_TS = """\
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
export class AppointmentsService {
|
||||
private readonly logger = new Logger('AppointmentsService');
|
||||
|
||||
async create(payload: unknown): Promise<void> {
|
||||
this.logger.log('Creating appointment');
|
||||
Logger.log('static-style log call');
|
||||
}
|
||||
|
||||
async cancel(id: string): Promise<void> {
|
||||
this.logger.log(`Cancelled ${id}`);
|
||||
}
|
||||
}
|
||||
"""
|
||||
|
||||
_NESTJS_OTHER_SERVICE_TS = """\
|
||||
import { Logger } from '@nestjs/common';
|
||||
|
||||
const logger = new Logger('eprescribing-metrics');
|
||||
|
||||
export function logTransmissionAttempt(rxId: string): void {
|
||||
logger.log({ event: 'tx-attempt', rxId });
|
||||
}
|
||||
|
||||
export function logWebhookReceived(payload: unknown): void {
|
||||
logger.log({ event: 'webhook', payload });
|
||||
}
|
||||
"""
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def project(tmp_path: Path) -> Path:
|
||||
(tmp_path / "validation").mkdir()
|
||||
(tmp_path / "src").mkdir()
|
||||
(tmp_path / "validation" / "smoke-test.mjs").write_text(_SMOKE_TEST_JS)
|
||||
(tmp_path / "src" / "appointments.service.ts").write_text(_NESTJS_SERVICE_TS)
|
||||
(tmp_path / "src" / "eprescribing-metrics.ts").write_text(_NESTJS_OTHER_SERVICE_TS)
|
||||
return tmp_path
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Tests
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def test_member_call_node_types_constant_present() -> None:
|
||||
"""The constant must exist and cover every language extractor."""
|
||||
assert _MEMBER_CALL_NODE_TYPES is not None, (
|
||||
"_MEMBER_CALL_NODE_TYPES is missing from graphify.extract — patch not applied"
|
||||
)
|
||||
assert isinstance(_MEMBER_CALL_NODE_TYPES, frozenset)
|
||||
# Spot-check that the most important node types are tracked.
|
||||
for required in (
|
||||
"member_expression", # JS/TS
|
||||
"selector_expression", # Go
|
||||
"field_expression", # Rust / C++
|
||||
"navigation_expression", # Swift / Kotlin
|
||||
"dot", # Elixir
|
||||
):
|
||||
assert required in _MEMBER_CALL_NODE_TYPES, f"missing: {required}"
|
||||
|
||||
|
||||
def test_smoke_test_log_does_not_steal_nestjs_logger_calls(project: Path) -> None:
|
||||
"""
|
||||
Regression: with a corpus containing both `validation/smoke-test.mjs`
|
||||
(which defines `function log(...)`) AND NestJS service files (which
|
||||
call `this.logger.log(...)` / `Logger.log(...)` / `logger.log(...)`),
|
||||
NONE of the NestJS calls should resolve to the smoke-test `log` node.
|
||||
"""
|
||||
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
|
||||
result = extract(files, cache_root=project)
|
||||
|
||||
log_nodes = [n for n in result["nodes"]
|
||||
if n.get("label", "").strip().rstrip("()") == "log"]
|
||||
assert len(log_nodes) == 1, "expected exactly one top-level log() symbol"
|
||||
|
||||
log_id = log_nodes[0]["id"]
|
||||
log_source_file = log_nodes[0]["source_file"]
|
||||
|
||||
# Every inbound edge to log() must come from the same file (validation/smoke-test.mjs).
|
||||
inbound = [e for e in result["edges"] if e.get("target") == log_id]
|
||||
cross_file = [e for e in inbound if e.get("source_file") != log_source_file]
|
||||
|
||||
assert not cross_file, (
|
||||
f"phantom edges leaked to log() from other files: "
|
||||
f"{[(e['source_file'], e['source_location']) for e in cross_file]}"
|
||||
)
|
||||
|
||||
# And we should still capture the legitimate intra-file calls
|
||||
# (testAuth → log in the smoke-test file).
|
||||
assert any(e for e in inbound if e.get("source_file") == log_source_file), (
|
||||
"lost legitimate intra-file call edges to log()"
|
||||
)
|
||||
|
||||
|
||||
def test_raw_calls_emit_callee_node_type_for_member_expressions(project: Path) -> None:
|
||||
"""
|
||||
Direct check on the raw-calls payload: any unresolved member-expression
|
||||
callee should carry a `callee_node_type` that's in _MEMBER_CALL_NODE_TYPES.
|
||||
|
||||
We can't easily inspect raw_calls after extract() returns (they get
|
||||
consumed by the resolver), so we test indirectly: the absence of phantom
|
||||
edges (above test) is the observable proof.
|
||||
"""
|
||||
# Sanity: just exercise extract() with something that triggers raw_calls
|
||||
# so we know our test corpus is meaningful.
|
||||
files = sorted(project.rglob("*.mjs")) + sorted(project.rglob("*.ts"))
|
||||
result = extract(files, cache_root=project)
|
||||
# We expect nodes from all three files.
|
||||
source_files = {n.get("source_file") for n in result["nodes"]}
|
||||
assert any("smoke-test" in (s or "") for s in source_files)
|
||||
assert any("appointments.service" in (s or "") for s in source_files)
|
||||
assert any("eprescribing-metrics" in (s or "") for s in source_files)
|
||||
@@ -137,3 +137,50 @@ def test_community_article_truncation_notice(tmp_path):
|
||||
to_wiki(G, communities, tmp_path, community_labels={0: "Big Community"})
|
||||
article = (tmp_path / "Big_Community.md").read_text()
|
||||
assert "and 5 more nodes" in article
|
||||
|
||||
|
||||
def test_to_wiki_clears_stale_articles(tmp_path):
|
||||
"""Regression: previous-run articles must be removed when labels change.
|
||||
|
||||
Real-world impact: community labels are LLM-generated (per skill.md Step 5)
|
||||
and non-deterministic across runs, so the same conceptual community gets a
|
||||
different 2-5 word name each rebuild. Without cleanup, every rebuild leaves
|
||||
the previous run's files as orphans, growing wiki/ unboundedly.
|
||||
"""
|
||||
G = _make_graph()
|
||||
|
||||
# First run with one set of labels
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "Old Name A", 1: "Old Name B"})
|
||||
assert (tmp_path / "Old_Name_A.md").exists()
|
||||
assert (tmp_path / "Old_Name_B.md").exists()
|
||||
|
||||
# Second run simulates LLM picking different names for the same communities
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels={0: "New Name A", 1: "New Name B"})
|
||||
|
||||
# Old files should be gone; new files should exist
|
||||
assert not (tmp_path / "Old_Name_A.md").exists(), "stale article from previous run not cleared"
|
||||
assert not (tmp_path / "Old_Name_B.md").exists(), "stale article from previous run not cleared"
|
||||
assert (tmp_path / "New_Name_A.md").exists()
|
||||
assert (tmp_path / "New_Name_B.md").exists()
|
||||
# index.md is always rewritten
|
||||
assert (tmp_path / "index.md").exists()
|
||||
|
||||
|
||||
def test_to_wiki_preserves_non_md_files(tmp_path):
|
||||
"""Cleanup only touches top-level .md files; subdirectories and other files survive.
|
||||
|
||||
Some users may keep auxiliary assets (images, .json sidecars) in wiki/ —
|
||||
cleanup must not be destructive beyond its own .md output domain.
|
||||
"""
|
||||
G = _make_graph()
|
||||
tmp_path.mkdir(parents=True, exist_ok=True)
|
||||
(tmp_path / "user_image.png").write_bytes(b"\x89PNG fake")
|
||||
(tmp_path / "user_data.json").write_text('{"key": "value"}')
|
||||
(tmp_path / "subdir").mkdir()
|
||||
(tmp_path / "subdir" / "nested.md").write_text("# user content")
|
||||
|
||||
to_wiki(G, COMMUNITIES, tmp_path, community_labels=LABELS)
|
||||
|
||||
assert (tmp_path / "user_image.png").exists(), "non-.md file deleted"
|
||||
assert (tmp_path / "user_data.json").exists(), "non-.md file deleted"
|
||||
assert (tmp_path / "subdir" / "nested.md").exists(), "subdirectory .md deleted"
|
||||
Reference in new issue
Block a user