Compare commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
43baaf1950 | ||
|
|
230a75c4f6 | ||
|
|
3d99603e8d | ||
|
|
5685984110 | ||
|
|
7c561e6f82 | ||
|
|
4e7648b4e2 | ||
|
|
972fdc1b87 | ||
|
|
a9b0ddbb86 | ||
|
|
3baedc5bdb | ||
|
|
cfe18ea947 | ||
|
|
fcafec7081 | ||
|
|
6c78a74776 | ||
|
|
a08f0de53b | ||
|
|
2c975ee9fb | ||
|
|
77bb10c682 | ||
|
|
b7e7ae5ad6 | ||
|
|
7c68c84fac | ||
|
|
f7c9a9ad82 | ||
|
|
7d1c1096bc | ||
|
|
1b8b76816e | ||
|
|
ddb98226df | ||
|
|
76833f0281 | ||
|
|
c0048d0a61 | ||
|
|
2db5d966f2 | ||
|
|
28fc71eddc | ||
|
|
ef0e6ee681 | ||
|
|
8e4c803f31 |
No files matched your search
@@ -2,6 +2,24 @@
|
||||
|
||||
Full release notes with details on each version: [GitHub Releases](https://github.com/safishamsi/graphify/releases)
|
||||
|
||||
## 0.7.19 (2026-05-14)
|
||||
|
||||
- Feat: `.astro` files now extracted as code — frontmatter static imports, dynamic imports, and `<script>` block imports all produce edges; tsconfig path aliases resolved (#850, PR #852)
|
||||
- Fix: `.rebuild.lock` no longer accumulates PIDs across rebuilds — now contains a single owning PID while running and is unlinked on release so downstream tooling polling for its absence unblocks promptly (#858, PR #859)
|
||||
- Docs: skill.md now clarifies that graphify does not read `ANTHROPIC_API_KEY` or other provider keys during `/graphify` skill runs — the host IDE session provides the LLM (PR #864)
|
||||
|
||||
## 0.7.18 (2026-05-14)
|
||||
|
||||
- Fix: `graphify update` is now idempotent — graph.json and GRAPH_REPORT.md are only rewritten when content actually changes; topology comparison short-circuits clustering entirely on unchanged graphs, eliminating residual community-count drift (#824)
|
||||
- Fix: community IDs are now stable across rebuilds — Leiden/Louvain receive deterministically sorted input and a fixed random seed; greedy overlap remapper preserves existing IDs so hand-edited `.graphify_labels.json` labels don't drift onto wrong communities (#824)
|
||||
- Fix: `--no-cluster` flag added to `graphify update` — writes raw AST graph without clustering, consistent with `graphify extract --no-cluster` (#824)
|
||||
- Fix: `graphify update --no-cluster` now writes `"links"` key matching the schema of the full clustered path; previously wrote `"edges"`, causing schema toggle on every mode switch
|
||||
- Fix: `.graphify_labels.json` was rewritten on every rebuild even when nothing changed; now only written when outputs actually change
|
||||
- Fix: shrink-check (refuse overwrite when new graph has fewer nodes) was duplicated across two code paths; unified into a single `_check_shrink()` helper
|
||||
- Fix: node ID format in skill.md corrected to `{parent_dir}_{filename_stem}_{entity}` — the old filename-only format caused ghost-duplicate nodes when AST and semantic extractors disagreed on the stem; top-level files use just the filename stem; existing graphs with ghost duplicates can be cleaned up with `graphify extract --force`
|
||||
- Fix: safer JSON serialization in clustering sort keys (`default=str`) prevents crashes when edge attributes contain non-serializable values
|
||||
- Docs: added Prerequisites, optional extras table, environment variables reference, troubleshooting, and dev setup to README (#833)
|
||||
|
||||
## 0.7.17 (2026-05-13)
|
||||
|
||||
- Fix: `graphify path` and `graphify explain` now render arrow direction correctly — `-->` for caller→callee, `<--` for callee←caller; previously the graph was loaded undirected so every hop printed `-->` regardless of stored direction (#849, #853)
|
||||
|
||||
@@ -47,19 +47,57 @@ graphify export callflow-html
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
## Prerequisites
|
||||
|
||||
**Requires Python 3.10+**
|
||||
| Requirement | Minimum | Check | Install |
|
||||
|---|---|---|---|
|
||||
| Python | 3.10+ | `python --version` | [python.org](https://www.python.org/downloads/) |
|
||||
| uv *(recommended)* | any | `uv --version` | `curl -LsSf https://astral.sh/uv/install.sh \| sh` |
|
||||
| pipx *(alternative)* | any | `pipx --version` | `pip install pipx` |
|
||||
|
||||
**macOS quick install (Homebrew):**
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# or: pipx install graphifyy && graphify install
|
||||
# or: pip install graphifyy && graphify install
|
||||
brew install python@3.12 uv
|
||||
```
|
||||
|
||||
**Windows quick install:**
|
||||
```powershell
|
||||
winget install astral-sh.uv
|
||||
```
|
||||
|
||||
**Ubuntu/Debian:**
|
||||
```bash
|
||||
sudo apt install python3.12 python3-pip pipx
|
||||
# or install uv:
|
||||
curl -LsSf https://astral.sh/uv/install.sh | sh
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Install
|
||||
|
||||
> **Official package:** The PyPI package is `graphifyy` (double-y). Other `graphify*` packages on PyPI are not affiliated. The CLI command is still `graphify`.
|
||||
|
||||
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell and will cause a "not recognized" error.
|
||||
**Step 1 — install the package:**
|
||||
|
||||
```bash
|
||||
# Recommended (uv puts graphify on PATH automatically):
|
||||
uv tool install graphifyy
|
||||
|
||||
# Alternatives:
|
||||
pipx install graphifyy
|
||||
pip install graphifyy
|
||||
```
|
||||
|
||||
**Step 2 — register the skill with your AI assistant:**
|
||||
|
||||
```bash
|
||||
graphify install
|
||||
```
|
||||
|
||||
That's it. Open your AI assistant and type `/graphify .`
|
||||
|
||||
> **PowerShell note:** Use `graphify .` not `/graphify .` — the leading slash is a path separator in PowerShell.
|
||||
|
||||
> **`graphify: command not found`?** Use `uv tool install graphifyy` or `pipx install graphifyy` — both put the CLI on PATH automatically. With plain `pip`, add `~/.local/bin` (Linux) or `~/Library/Python/3.x/bin` (Mac) to your PATH, or run `python -m graphify`.
|
||||
|
||||
@@ -89,6 +127,27 @@ uv tool install graphifyy && graphify install
|
||||
> Codex users: also add `multi_agent = true` under `[features]` in `~/.codex/config.toml`.
|
||||
> Codex uses `$graphify` instead of `/graphify`.
|
||||
|
||||
### Optional extras
|
||||
|
||||
Install only what you need:
|
||||
|
||||
| Extra | What it adds | Install |
|
||||
|---|---|---|
|
||||
| `pdf` | PDF extraction | `pip install "graphifyy[pdf]"` |
|
||||
| `office` | `.docx` and `.xlsx` support | `pip install "graphifyy[office]"` |
|
||||
| `google` | Google Sheets rendering | `pip install "graphifyy[google]"` |
|
||||
| `video` | Video/audio transcription (faster-whisper + yt-dlp) | `pip install "graphifyy[video]"` |
|
||||
| `mcp` | MCP stdio server | `pip install "graphifyy[mcp]"` |
|
||||
| `neo4j` | Neo4j push support | `pip install "graphifyy[neo4j]"` |
|
||||
| `svg` | SVG graph export | `pip install "graphifyy[svg]"` |
|
||||
| `leiden` | Leiden community detection (Python < 3.13 only) | `pip install "graphifyy[leiden]"` |
|
||||
| `ollama` | Ollama local inference | `pip install "graphifyy[ollama]"` |
|
||||
| `openai` | OpenAI / OpenAI-compatible APIs | `pip install "graphifyy[openai]"` |
|
||||
| `gemini` | Google Gemini API | `pip install "graphifyy[gemini]"` |
|
||||
| `bedrock` | AWS Bedrock (uses IAM, no API key) | `pip install "graphifyy[bedrock]"` |
|
||||
| `sql` | SQL schema extraction | `pip install "graphifyy[sql]"` |
|
||||
| `all` | Everything above | `pip install "graphifyy[all]"` |
|
||||
|
||||
---
|
||||
|
||||
## Make your assistant always use the graph
|
||||
@@ -135,7 +194,7 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
|
||||
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
|
||||
| Code (29 languages) | `.py .ts .js .jsx .tsx .mjs .go .rs .java .c .cpp .h .hpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .mm .jl .vue .svelte .astro .groovy .gradle .dart .v .sv .sql .f .f90 .f95 .f03 .f08 .pas .pp .dpr .dpk .lpr .inc .dfm .lfm .lpk` |
|
||||
| Docs | `.md .mdx .qmd .html .txt .rst .yaml .yml` |
|
||||
| Office | `.docx .xlsx` (requires `pip install graphifyy[office]`) |
|
||||
| Google Workspace | `.gdoc .gsheet .gslides` (opt-in; requires `gws` auth and `--google-workspace`; Sheets need `pip install graphifyy[google]`) |
|
||||
@@ -247,15 +306,92 @@ The MCP server gives your assistant structured access: `query_graph`, `get_node`
|
||||
|
||||
---
|
||||
|
||||
## Environment variables
|
||||
|
||||
These are only needed for **headless / CI extraction** (`graphify extract`). When running via the `/graphify` skill inside your IDE, the model API is provided by your IDE session — no extra keys needed.
|
||||
|
||||
| Variable | Used for | When required |
|
||||
|---|---|---|
|
||||
| `ANTHROPIC_API_KEY` | Claude (Anthropic) backend | `--backend claude` |
|
||||
| `GEMINI_API_KEY` or `GOOGLE_API_KEY` | Google Gemini backend | `--backend gemini` |
|
||||
| `OPENAI_API_KEY` | OpenAI or OpenAI-compatible APIs | `--backend openai` |
|
||||
| `MOONSHOT_API_KEY` | Kimi Code backend | `--backend kimi` |
|
||||
| `OLLAMA_BASE_URL` | Ollama local inference URL | `--backend ollama` (default: `http://localhost:11434`) |
|
||||
| `OLLAMA_MODEL` | Ollama model name | `--backend ollama` (default: auto-detect) |
|
||||
| `GRAPHIFY_OLLAMA_NUM_CTX` | Override Ollama KV-cache window size | optional — auto-sized by default |
|
||||
| `GRAPHIFY_OLLAMA_KEEP_ALIVE` | Minutes to keep Ollama model loaded | optional — set `0` to unload after each chunk |
|
||||
| `AWS_*` / `~/.aws/credentials` | AWS Bedrock — standard credential chain | `--backend bedrock` (no API key, uses IAM) |
|
||||
| `GRAPHIFY_MAX_WORKERS` | AST parallelism thread count | optional — also `--max-workers` flag |
|
||||
| `GRAPHIFY_MAX_OUTPUT_TOKENS` | Raise output cap for dense corpora | optional — e.g. `32768` for large files |
|
||||
| `GRAPHIFY_API_TIMEOUT` | HTTP timeout in seconds (default: 600) | optional — also `--api-timeout` flag |
|
||||
| `GRAPHIFY_FORCE` | Force graph rebuild even with fewer nodes | optional — also `--force` flag |
|
||||
| `GRAPHIFY_GOOGLE_WORKSPACE` | Auto-enable Google Workspace export | optional — set to `1` |
|
||||
|
||||
---
|
||||
|
||||
## Privacy
|
||||
|
||||
- **Code files** — processed locally via tree-sitter. Nothing leaves your machine.
|
||||
- **Video / audio** — transcribed locally with faster-whisper. Nothing leaves your machine.
|
||||
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), a running Ollama instance (`OLLAMA_BASE_URL`), or AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM). The `--dedup-llm` flag uses the same key.
|
||||
- **Docs, PDFs, images** — sent to your AI assistant for semantic extraction (via the `/graphify` skill, using whatever model your IDE session runs). Headless `graphify extract` requires `GEMINI_API_KEY` / `GOOGLE_API_KEY` (Gemini), `MOONSHOT_API_KEY` (Kimi), `ANTHROPIC_API_KEY` (Claude), `OPENAI_API_KEY` (OpenAI), a running Ollama instance (`OLLAMA_BASE_URL`), AWS credentials via the standard provider chain (Bedrock - no API key needed, uses IAM), or the `claude` CLI binary (Claude Code - no API key needed, uses your Claude subscription). The `--dedup-llm` flag uses the same key.
|
||||
- No telemetry, no usage tracking, no analytics.
|
||||
|
||||
---
|
||||
|
||||
## Troubleshooting
|
||||
|
||||
**`graphify: command not found` after `pip install graphifyy`**
|
||||
pip installs scripts to a user bin directory that may not be on your PATH. Fix:
|
||||
- macOS: add `~/Library/Python/3.x/bin` to your PATH in `~/.zshrc`
|
||||
- Linux: add `~/.local/bin` to your PATH in `~/.bashrc`
|
||||
- Or use `uv tool install graphifyy` / `pipx install graphifyy` — both manage PATH automatically.
|
||||
|
||||
**`python -m graphify` works but `graphify` command doesn't**
|
||||
Your shell's PATH doesn't include the Python scripts directory. Use `uv` or `pipx` instead of plain `pip`.
|
||||
|
||||
**`/graphify .` causes "path not recognized" in PowerShell**
|
||||
PowerShell treats a leading `/` as a path separator. Use `graphify .` (no slash) on Windows.
|
||||
|
||||
**Graph has fewer nodes after `--update` or rebuild**
|
||||
If a refactor deleted files, the old nodes linger. Pass `--force` (or set `GRAPHIFY_FORCE=1`) to overwrite even when the rebuild has fewer nodes.
|
||||
|
||||
**Graph has duplicate nodes for the same entity (ghost duplicates)**
|
||||
This happens when semantic and AST extraction disagreed on the node ID format. Run a full re-extract to clean up:
|
||||
```bash
|
||||
graphify extract . --force
|
||||
```
|
||||
|
||||
**Ollama runs out of VRAM / context window exceeded**
|
||||
The KV-cache window is auto-sized but may be too large for your GPU. Reduce it:
|
||||
```bash
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=8192 graphify extract ./docs --backend ollama --token-budget 4000
|
||||
```
|
||||
|
||||
**Graph HTML is too large to open in a browser (>5000 nodes)**
|
||||
Skip HTML generation and use the JSON directly:
|
||||
```bash
|
||||
graphify cluster-only ./my-project --no-viz
|
||||
graphify query "..."
|
||||
```
|
||||
|
||||
**`graph.json` has conflict markers after two devs commit at once**
|
||||
Run `graphify hook install` — it sets up a git merge driver that union-merges `graph.json` automatically so conflicts never happen.
|
||||
|
||||
**Extraction returns empty nodes/edges for docs or PDFs**
|
||||
Docs and PDFs require an LLM call. Check that your API key is set and the backend is correct:
|
||||
```bash
|
||||
ANTHROPIC_API_KEY=sk-... graphify extract ./docs --backend claude
|
||||
```
|
||||
|
||||
**Skill version mismatch warning in your IDE**
|
||||
Your installed graphify version is different from the skill file. Update:
|
||||
```bash
|
||||
uv tool upgrade graphifyy
|
||||
graphify install # overwrites the skill file
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Full command reference
|
||||
|
||||
```
|
||||
@@ -307,18 +443,20 @@ graphify kiro install / uninstall
|
||||
graphify antigravity install / uninstall
|
||||
|
||||
graphify extract ./docs # headless LLM extraction for CI (no IDE needed)
|
||||
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, ollama, or bedrock
|
||||
graphify extract ./docs --backend gemini # explicit backend: gemini, kimi, claude, openai, ollama, bedrock, or claude-cli
|
||||
graphify extract ./docs --backend gemini --model gemini-3.1-pro-preview
|
||||
graphify extract ./docs --backend ollama # local Ollama (set OLLAMA_BASE_URL / OLLAMA_MODEL) - no API key needed for loopback
|
||||
GRAPHIFY_OLLAMA_NUM_CTX=32768 graphify extract ./docs --backend ollama # override KV-cache window (auto-sized by default)
|
||||
GRAPHIFY_OLLAMA_KEEP_ALIVE=0 graphify extract ./docs --backend ollama # unload model after each chunk (saves VRAM on small GPUs)
|
||||
graphify extract ./docs --backend bedrock # AWS Bedrock via IAM - no API key, uses AWS credential chain
|
||||
graphify extract ./docs --backend claude-cli # route through Claude Code CLI - no API key, uses your Claude subscription
|
||||
graphify extract ./docs --max-workers 16 # AST parallelism (also GRAPHIFY_MAX_WORKERS)
|
||||
graphify extract ./docs --token-budget 30000 # smaller semantic chunks for local/small models
|
||||
graphify extract ./docs --max-concurrency 2 # fewer parallel LLM calls (useful for local inference)
|
||||
graphify extract ./docs --api-timeout 900 # longer HTTP timeout for slow local models (default 600s)
|
||||
graphify extract ./docs --google-workspace # export .gdoc/.gsheet/.gslides via gws before extraction
|
||||
graphify extract ./docs --no-cluster # raw extraction only, skip clustering
|
||||
graphify extract ./docs --force # overwrite graph.json even if new graph has fewer nodes (use after refactors or to clear ghost duplicates)
|
||||
graphify extract ./docs --dedup-llm # LLM tiebreaker for ambiguous entity pairs (uses same API key)
|
||||
graphify extract ./docs --global --as myrepo # extract and register into the cross-project global graph
|
||||
GRAPHIFY_MAX_OUTPUT_TOKENS=32768 graphify extract ./docs --backend claude # raise output cap for dense corpora
|
||||
@@ -339,6 +477,8 @@ graphify --version # print installed version
|
||||
graphify watch ./src
|
||||
graphify check-update ./src
|
||||
graphify update ./src
|
||||
graphify update ./src --no-cluster # skip reclustering, write raw AST graph only
|
||||
graphify update ./src --force # overwrite even if new graph has fewer nodes
|
||||
graphify cluster-only ./my-project
|
||||
graphify cluster-only ./my-project --graph path/to/graph.json # custom graph location
|
||||
```
|
||||
@@ -366,6 +506,49 @@ Built for people whose work lives across hundreds of conversations and documents
|
||||
<details>
|
||||
<summary>Contributing</summary>
|
||||
|
||||
### Development setup
|
||||
|
||||
Clone the repo and install in editable mode:
|
||||
|
||||
```bash
|
||||
git clone https://github.com/safishamsi/graphify.git
|
||||
cd graphify
|
||||
git checkout v7 # active development branch
|
||||
|
||||
# Create a virtual environment (Python 3.10+ required):
|
||||
python3 -m venv .venv
|
||||
source .venv/bin/activate # Windows: .venv\Scripts\activate
|
||||
|
||||
# Install in editable mode with all optional extras:
|
||||
pip install -e ".[all]"
|
||||
```
|
||||
|
||||
Verify the editable install:
|
||||
```bash
|
||||
graphify --version
|
||||
python -c "import graphify; print(graphify.__file__)"
|
||||
```
|
||||
|
||||
### Running tests
|
||||
|
||||
```bash
|
||||
pip install pytest
|
||||
pytest tests/ -q # run the full suite
|
||||
pytest tests/test_extract.py -q # one module
|
||||
pytest tests/ -q -k "python" # filter by name
|
||||
```
|
||||
|
||||
> macOS note: the test suite includes both `sample.f90` and `sample.F90` fixtures. These collide on case-insensitive HFS+ / APFS file systems. Run on Linux or in a Docker container if you need to test both Fortran variants simultaneously.
|
||||
|
||||
### Git workflow
|
||||
|
||||
- Active development happens on the `v7` branch.
|
||||
- Commit style: `fix: <description>` / `feat: <description>` / `docs: <description>`
|
||||
- Before opening a PR, run `pytest tests/ -q` and confirm it passes.
|
||||
- Add a fixture file to `tests/fixtures/` and tests to `tests/test_languages.py` for any new language extractor.
|
||||
|
||||
### What to contribute
|
||||
|
||||
**Worked examples** are the most useful contribution. Run `/graphify` on a real corpus, save the output to `worked/{slug}/`, write an honest `review.md` covering what the graph got right and wrong, and open a PR.
|
||||
|
||||
**Extraction bugs** — open an issue with the input file, the cache entry (`graphify-out/cache/`), and what was missed or wrong.
|
||||
|
||||
+24
-9
@@ -1153,6 +1153,7 @@ def main() -> None:
|
||||
print(" update <path> re-extract code files and update the graph (no LLM needed)")
|
||||
print(" --force overwrite graph.json even if the rebuild has fewer nodes")
|
||||
print(" (also: GRAPHIFY_FORCE=1 env var; use after refactors that delete code)")
|
||||
print(" --no-cluster skip clustering, write raw extraction only")
|
||||
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(" --graph <path> path to graph.json (default <path>/graphify-out/graph.json)")
|
||||
@@ -1756,12 +1757,26 @@ def main() -> None:
|
||||
|
||||
elif cmd == "update":
|
||||
force = os.environ.get("GRAPHIFY_FORCE", "").lower() in ("1", "true", "yes")
|
||||
argv = list(sys.argv)
|
||||
if "--force" in argv[2:]:
|
||||
force = True
|
||||
argv = [a for a in argv if a != "--force"]
|
||||
if len(argv) > 2:
|
||||
watch_path = Path(argv[2])
|
||||
no_cluster = False
|
||||
args = sys.argv[2:]
|
||||
watch_arg: str | None = None
|
||||
for a in args:
|
||||
if a == "--force":
|
||||
force = True
|
||||
continue
|
||||
if a == "--no-cluster":
|
||||
no_cluster = True
|
||||
continue
|
||||
if a.startswith("-"):
|
||||
print(f"error: unknown update option: {a}", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
if watch_arg is not None:
|
||||
print("error: update accepts at most one path argument", file=sys.stderr)
|
||||
sys.exit(2)
|
||||
watch_arg = a
|
||||
|
||||
if watch_arg is not None:
|
||||
watch_path = Path(watch_arg)
|
||||
else:
|
||||
# Try to recover the scan root saved by the last full build
|
||||
saved = Path(_GRAPHIFY_OUT) / ".graphify_root"
|
||||
@@ -1777,7 +1792,7 @@ def main() -> None:
|
||||
# Interactive CLI: block on the per-repo lock rather than skip, so the
|
||||
# user sees their explicit `graphify update` complete instead of
|
||||
# exiting silently when a hook-driven rebuild happens to be running.
|
||||
ok = _rebuild_code(watch_path, force=force, block_on_lock=True)
|
||||
ok = _rebuild_code(watch_path, force=force, no_cluster=no_cluster, block_on_lock=True)
|
||||
if ok:
|
||||
print("Code graph updated. For doc/paper/image changes run /graphify --update in your AI assistant.")
|
||||
if not (
|
||||
@@ -2650,7 +2665,7 @@ def main() -> None:
|
||||
f"est. cost: ${cost:.4f}"
|
||||
)
|
||||
try:
|
||||
_save_manifest(files_by_type, manifest_path=str(manifest_path))
|
||||
_save_manifest(files_by_type, manifest_path=str(manifest_path), kind="both")
|
||||
except Exception as exc:
|
||||
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
|
||||
if global_merge:
|
||||
@@ -2732,7 +2747,7 @@ def main() -> None:
|
||||
}
|
||||
analysis_path.write_text(json.dumps(analysis, indent=2), encoding="utf-8")
|
||||
try:
|
||||
_save_manifest(files_by_type, manifest_path=str(manifest_path))
|
||||
_save_manifest(files_by_type, manifest_path=str(manifest_path), kind="both")
|
||||
except Exception as exc:
|
||||
print(f"[graphify extract] warning: could not write manifest: {exc}", file=sys.stderr)
|
||||
|
||||
|
||||
+73
-2
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import inspect
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import networkx as nx
|
||||
|
||||
@@ -27,15 +28,34 @@ def _partition(G: nx.Graph) -> dict[str, int]:
|
||||
Output from graspologic is suppressed to prevent ANSI escape codes
|
||||
from corrupting terminal scroll buffers on Windows PowerShell 5.1.
|
||||
"""
|
||||
stable = nx.Graph()
|
||||
stable.add_nodes_from(sorted(G.nodes(), key=str))
|
||||
edge_rows = sorted(
|
||||
G.edges(data=True),
|
||||
key=lambda row: (
|
||||
str(row[0]),
|
||||
str(row[1]),
|
||||
json.dumps(row[2], sort_keys=True, ensure_ascii=False, default=str),
|
||||
),
|
||||
)
|
||||
for src, tgt, attrs in edge_rows:
|
||||
stable.add_edge(src, tgt, **attrs)
|
||||
|
||||
try:
|
||||
from graspologic.partition import leiden
|
||||
lsig = inspect.signature(leiden).parameters
|
||||
kwargs: dict = {}
|
||||
if "random_seed" in lsig:
|
||||
kwargs["random_seed"] = 42
|
||||
if "trials" in lsig:
|
||||
kwargs["trials"] = 1
|
||||
# Suppress graspologic output to prevent ANSI escape codes from
|
||||
# corrupting PowerShell 5.1 scroll buffer (issue #19)
|
||||
old_stderr = sys.stderr
|
||||
try:
|
||||
sys.stderr = io.StringIO()
|
||||
with _suppress_output():
|
||||
result = leiden(G)
|
||||
result = leiden(stable, **kwargs)
|
||||
finally:
|
||||
sys.stderr = old_stderr
|
||||
return result
|
||||
@@ -48,7 +68,7 @@ def _partition(G: nx.Graph) -> dict[str, int]:
|
||||
kwargs: dict = {"seed": 42, "threshold": 1e-4}
|
||||
if "max_level" in inspect.signature(nx.community.louvain_communities).parameters:
|
||||
kwargs["max_level"] = 10
|
||||
communities = nx.community.louvain_communities(G, **kwargs)
|
||||
communities = nx.community.louvain_communities(stable, **kwargs)
|
||||
return {node: cid for cid, nodes in enumerate(communities) for node in nodes}
|
||||
|
||||
|
||||
@@ -148,3 +168,54 @@ def cohesion_score(G: nx.Graph, community_nodes: list[str]) -> float:
|
||||
|
||||
def score_all(G: nx.Graph, communities: dict[int, list[str]]) -> dict[int, float]:
|
||||
return {cid: cohesion_score(G, nodes) for cid, nodes in communities.items()}
|
||||
|
||||
|
||||
def remap_communities_to_previous(
|
||||
communities: dict[int, list[str]],
|
||||
previous_node_community: dict[str, int],
|
||||
) -> dict[int, list[str]]:
|
||||
"""Remap community IDs to maximize overlap with a previous assignment.
|
||||
|
||||
Uses greedy one-to-one matching by intersection size, then assigns fresh IDs
|
||||
to unmatched communities in deterministic order (size desc, lexical tie-break).
|
||||
"""
|
||||
if not communities:
|
||||
return {}
|
||||
|
||||
new_sets = {cid: set(nodes) for cid, nodes in communities.items()}
|
||||
old_sets: dict[int, set[str]] = {}
|
||||
for node, old_cid in previous_node_community.items():
|
||||
old_sets.setdefault(old_cid, set()).add(node)
|
||||
|
||||
overlaps: list[tuple[int, int, int]] = []
|
||||
for old_cid, old_nodes in old_sets.items():
|
||||
for new_cid, new_nodes in new_sets.items():
|
||||
overlap = len(old_nodes & new_nodes)
|
||||
if overlap > 0:
|
||||
overlaps.append((overlap, old_cid, new_cid))
|
||||
overlaps.sort(key=lambda x: (-x[0], x[1], x[2]))
|
||||
|
||||
new_to_final: dict[int, int] = {}
|
||||
used_old_ids: set[int] = set()
|
||||
matched_new_ids: set[int] = set()
|
||||
for _overlap, old_cid, new_cid in overlaps:
|
||||
if old_cid in used_old_ids or new_cid in matched_new_ids:
|
||||
continue
|
||||
new_to_final[new_cid] = old_cid
|
||||
used_old_ids.add(old_cid)
|
||||
matched_new_ids.add(new_cid)
|
||||
|
||||
unmatched = [cid for cid in communities if cid not in matched_new_ids]
|
||||
unmatched.sort(key=lambda cid: (-len(communities[cid]), tuple(sorted(communities[cid]))))
|
||||
next_id = 0
|
||||
for new_cid in unmatched:
|
||||
while next_id in used_old_ids:
|
||||
next_id += 1
|
||||
new_to_final[new_cid] = next_id
|
||||
used_old_ids.add(next_id)
|
||||
next_id += 1
|
||||
|
||||
remapped: dict[int, list[str]] = {}
|
||||
for new_cid, nodes in communities.items():
|
||||
remapped[new_to_final[new_cid]] = sorted(nodes)
|
||||
return dict(sorted(remapped.items(), key=lambda kv: kv[0]))
|
||||
+76
-15
@@ -24,7 +24,7 @@ class FileType(str, Enum):
|
||||
|
||||
_MANIFEST_PATH = "graphify-out/manifest.json"
|
||||
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
|
||||
CODE_EXTENSIONS = {'.py', '.ts', '.js', '.jsx', '.tsx', '.mjs', '.ejs', '.go', '.rs', '.java', '.groovy', '.gradle', '.cpp', '.cc', '.cxx', '.c', '.h', '.hpp', '.rb', '.swift', '.kt', '.kts', '.cs', '.scala', '.php', '.lua', '.luau', '.toc', '.zig', '.ps1', '.ex', '.exs', '.m', '.mm', '.jl', '.vue', '.svelte', '.astro', '.dart', '.v', '.sv', '.sql', '.r', '.f', '.F', '.f90', '.F90', '.f95', '.F95', '.f03', '.F03', '.f08', '.F08', '.pas', '.pp', '.dpr', '.dpk', '.lpr', '.inc', '.dfm', '.lfm', '.lpk'}
|
||||
DOC_EXTENSIONS = {'.md', '.mdx', '.qmd', '.txt', '.rst', '.html', '.yaml', '.yml'}
|
||||
PAPER_EXTENSIONS = {'.pdf'}
|
||||
IMAGE_EXTENSIONS = {'.png', '.jpg', '.jpeg', '.gif', '.webp', '.svg'}
|
||||
@@ -370,6 +370,12 @@ _SKIP_DIRS = {
|
||||
".pytest_cache", ".mypy_cache", ".ruff_cache",
|
||||
".tox", ".eggs", "*.egg-info",
|
||||
"graphify-out", # never treat own output as source input (#524)
|
||||
# Coverage/test-artefact dirs — generated, never architecturally meaningful
|
||||
"coverage", "lcov-report", # Vitest/Istanbul/nyc HTML reports (#870)
|
||||
"visual-tests", "visual-test", # Playwright/visual-regression bundles (#869)
|
||||
"__snapshots__", "snapshots", # Jest/Vitest snapshot dirs
|
||||
"storybook-static", # Storybook production build output
|
||||
"dist-protected", # Protected dist variants (same noise as dist)
|
||||
}
|
||||
|
||||
# Large generated files that are never useful to extract
|
||||
@@ -722,6 +728,8 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
|
||||
skipped_sensitive.append(str(p) + f" [Google Workspace export failed: {exc}]")
|
||||
continue
|
||||
if md_path:
|
||||
if _is_ignored(md_path, root, ignore_patterns):
|
||||
continue
|
||||
files[ftype].append(str(md_path))
|
||||
total_words += count_words(md_path)
|
||||
else:
|
||||
@@ -731,6 +739,8 @@ def detect(root: Path, *, follow_symlinks: bool = False, google_workspace: bool
|
||||
if p.suffix.lower() in OFFICE_EXTENSIONS:
|
||||
md_path = convert_office_file(p, converted_dir)
|
||||
if md_path:
|
||||
if _is_ignored(md_path, root, ignore_patterns):
|
||||
continue
|
||||
files[ftype].append(str(md_path))
|
||||
total_words += count_words(md_path)
|
||||
else:
|
||||
@@ -790,16 +800,48 @@ def load_manifest(manifest_path: str = _MANIFEST_PATH) -> dict:
|
||||
return {}
|
||||
|
||||
|
||||
def save_manifest(files: dict[str, list[str]], manifest_path: str = _MANIFEST_PATH) -> None:
|
||||
"""Save current file mtimes + content hashes for change detection on --update."""
|
||||
def save_manifest(
|
||||
files: dict[str, list[str]],
|
||||
manifest_path: str = _MANIFEST_PATH,
|
||||
*,
|
||||
kind: str = "both",
|
||||
) -> None:
|
||||
"""Save current file mtimes + content hashes for change detection.
|
||||
|
||||
kind="ast" — written by `graphify update` (AST-only rebuild). Stamps
|
||||
ast_hash; preserves an existing semantic_hash only when
|
||||
the file content is unchanged (mtime + hash match).
|
||||
kind="semantic" — written by `graphify extract` after semantic extraction.
|
||||
Stamps semantic_hash; preserves existing ast_hash.
|
||||
kind="both" — full pipeline: stamps both hashes (default).
|
||||
"""
|
||||
existing = load_manifest(manifest_path)
|
||||
manifest: dict[str, dict] = {}
|
||||
for file_list in files.values():
|
||||
for f in file_list:
|
||||
try:
|
||||
p = Path(f)
|
||||
manifest[f] = {"mtime": p.stat().st_mtime, "hash": _md5_file(p)}
|
||||
mtime = p.stat().st_mtime
|
||||
h = _md5_file(p)
|
||||
except OSError:
|
||||
pass # file deleted between detect() and manifest write - skip it
|
||||
continue # file deleted between detect() and manifest write
|
||||
prev = existing.get(f, {})
|
||||
# Normalise legacy {mtime, hash} entries to new schema
|
||||
if isinstance(prev, (int, float)):
|
||||
prev = {"mtime": prev, "ast_hash": "", "semantic_hash": ""}
|
||||
elif isinstance(prev, dict) and "hash" in prev and "ast_hash" not in prev:
|
||||
prev = {"mtime": prev.get("mtime", 0), "ast_hash": prev["hash"], "semantic_hash": ""}
|
||||
entry: dict = {"mtime": mtime}
|
||||
if kind in ("ast", "both"):
|
||||
entry["ast_hash"] = h
|
||||
else:
|
||||
entry["ast_hash"] = prev.get("ast_hash", "")
|
||||
if kind in ("semantic", "both"):
|
||||
entry["semantic_hash"] = h
|
||||
else:
|
||||
# Preserve semantic_hash only when content is unchanged
|
||||
entry["semantic_hash"] = prev.get("semantic_hash", "") if h == prev.get("ast_hash", "") else ""
|
||||
manifest[f] = entry
|
||||
Path(manifest_path).parent.mkdir(parents=True, exist_ok=True)
|
||||
Path(manifest_path).write_text(json.dumps(manifest, indent=2), encoding="utf-8")
|
||||
|
||||
@@ -810,14 +852,24 @@ def detect_incremental(
|
||||
*,
|
||||
follow_symlinks: bool = False,
|
||||
google_workspace: bool | None = None,
|
||||
kind: str = "semantic",
|
||||
) -> dict:
|
||||
"""Like detect(), but returns only new or modified files since the last run.
|
||||
|
||||
Fast path: mtime unchanged → unchanged (free, no hash).
|
||||
Slow path: mtime bumped → compare MD5. Same hash = sync tool touched mtime,
|
||||
treat as unchanged. Different hash = actually changed, re-extract.
|
||||
kind="semantic" (default for extract): a file is "changed" when its
|
||||
semantic_hash is missing or its content has changed since the last
|
||||
semantic extraction pass. Use this for `graphify extract` so that
|
||||
files touched by `graphify update` (AST-only) are re-extracted
|
||||
semantically.
|
||||
kind="ast": a file is "changed" when its ast_hash is missing or its
|
||||
content has changed. Use this for `graphify update`.
|
||||
|
||||
Backwards compatible with legacy manifests storing plain float mtime values.
|
||||
Fast path: mtime unchanged + hash matches → unchanged (free, no disk IO
|
||||
beyond stat). Slow path: mtime bumped → compare MD5 against the relevant
|
||||
hash field before re-extracting.
|
||||
|
||||
Backwards compatible with legacy manifests storing plain float mtime values
|
||||
or {mtime, hash} dicts (treated as ast_hash only; semantic_hash = miss).
|
||||
|
||||
The ``follow_symlinks`` flag is forwarded to :func:`detect` so corpora that
|
||||
rely on symlinked sub-trees (e.g. a ``state_of_truth/`` symlink pointing to a
|
||||
@@ -846,16 +898,25 @@ def detect_incremental(
|
||||
except Exception:
|
||||
current_mtime = 0
|
||||
|
||||
# Legacy manifest: plain float value
|
||||
# Legacy manifest: plain float value — treat as ast_hash only
|
||||
if isinstance(stored, (int, float)):
|
||||
changed = stored is None or current_mtime > stored
|
||||
elif isinstance(stored, dict):
|
||||
stored_mtime = stored.get("mtime")
|
||||
if stored_mtime is None or current_mtime != stored_mtime:
|
||||
# mtime bumped — verify with content hash before re-extracting
|
||||
changed = _md5_file(Path(f)) != stored.get("hash", "")
|
||||
# Normalise legacy {mtime, hash} to new schema
|
||||
if "hash" in stored and "ast_hash" not in stored:
|
||||
stored = {"mtime": stored.get("mtime", 0), "ast_hash": stored["hash"], "semantic_hash": ""}
|
||||
hash_key = "semantic_hash" if kind == "semantic" else "ast_hash"
|
||||
stored_hash = stored.get(hash_key, "")
|
||||
# Missing semantic_hash means update ran but extract hasn't — always re-extract
|
||||
if not stored_hash:
|
||||
changed = True
|
||||
else:
|
||||
changed = False
|
||||
stored_mtime = stored.get("mtime")
|
||||
if stored_mtime is None or current_mtime != stored_mtime:
|
||||
# mtime bumped — verify with content hash before re-extracting
|
||||
changed = _md5_file(Path(f)) != stored_hash
|
||||
else:
|
||||
changed = False
|
||||
else:
|
||||
changed = True # unknown format, re-extract to be safe
|
||||
|
||||
|
||||
@@ -2123,6 +2123,142 @@ def extract_svelte(path: Path) -> dict:
|
||||
return result
|
||||
|
||||
|
||||
def extract_astro(path: Path) -> dict:
|
||||
"""Extract imports from .astro files: frontmatter (TS) + template regex fallback.
|
||||
|
||||
Astro files start with a ``---\\n...\\n---`` frontmatter block of TypeScript
|
||||
setup code (where almost all imports live), followed by an HTML-with-expressions
|
||||
template body, and optionally ``<script>`` blocks for client-side JS. Tree-sitter
|
||||
only sees the file usefully through the frontmatter — feeding the whole file to
|
||||
the JS parser produces a top-level ERROR node because the template is not valid
|
||||
JS, so ``import_statement`` nodes are never reached and static imports are
|
||||
silently dropped (#850). Mirrors :func:`extract_svelte` — same regex-rescue
|
||||
approach, scanning the frontmatter block and any client-side ``<script>`` blocks
|
||||
for static and dynamic imports.
|
||||
"""
|
||||
result = _extract_generic(path, _JS_CONFIG)
|
||||
try:
|
||||
import re as _re
|
||||
src = path.read_text(encoding="utf-8", errors="replace")
|
||||
existing_ids = {n["id"] for n in result.get("nodes", [])}
|
||||
file_node_id = _make_id(str(path))
|
||||
aliases = _load_tsconfig_aliases(path.parent)
|
||||
# Dynamic imports anywhere in the file: `import('./X.astro')` is legal in
|
||||
# frontmatter setup code and inside expression slots.
|
||||
for m in _re.finditer(r"""import\(\s*['"]([^'"]+)['"]\s*\)""", src):
|
||||
raw = m.group(1)
|
||||
if not raw:
|
||||
continue
|
||||
if raw.startswith("."):
|
||||
resolved = Path(os.path.normpath(path.parent / raw))
|
||||
resolved = _resolve_js_module_path(resolved)
|
||||
node_id = _make_id(str(resolved))
|
||||
stub_source_file = str(resolved)
|
||||
else:
|
||||
resolved_alias = None
|
||||
for alias_prefix, alias_base in aliases.items():
|
||||
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
|
||||
rest = raw[len(alias_prefix):].lstrip("/")
|
||||
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
|
||||
break
|
||||
if resolved_alias is not None:
|
||||
resolved_alias = _resolve_js_module_path(resolved_alias)
|
||||
node_id = _make_id(str(resolved_alias))
|
||||
stub_source_file = str(resolved_alias)
|
||||
else:
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
continue
|
||||
node_id = _make_id(module_name)
|
||||
stub_source_file = raw
|
||||
if node_id in existing_ids:
|
||||
result.setdefault("edges", []).append({
|
||||
"source": file_node_id, "target": node_id,
|
||||
"relation": "dynamic_import", "confidence": "EXTRACTED",
|
||||
"source_file": str(path),
|
||||
})
|
||||
continue
|
||||
result.setdefault("nodes", []).append({
|
||||
"id": node_id, "label": raw,
|
||||
"file_type": "code", "source_file": stub_source_file,
|
||||
"confidence": "EXTRACTED",
|
||||
})
|
||||
result.setdefault("edges", []).append({
|
||||
"source": file_node_id, "target": node_id,
|
||||
"relation": "dynamic_import", "confidence": "EXTRACTED",
|
||||
"source_file": str(path),
|
||||
})
|
||||
existing_ids.add(node_id)
|
||||
# Static imports: scan the `---...---` frontmatter at the file head plus any
|
||||
# client-side <script> blocks. Both are TS/JS regions but live inside a file
|
||||
# the JS tree-sitter parser cannot validate as a whole.
|
||||
frontmatter_re = _re.compile(
|
||||
r"\A\s*---\s*\r?\n([\s\S]*?)\r?\n---\s*(?:\r?\n|\Z)"
|
||||
)
|
||||
script_re = _re.compile(
|
||||
r"<script\b[^>]*>([\s\S]*?)</script\s*>", _re.IGNORECASE
|
||||
)
|
||||
static_import_re = _re.compile(
|
||||
r"""import\s+(?:[^'"`;]+?\s+from\s+)?['"]([^'"]+)['"]"""
|
||||
)
|
||||
regions: list[str] = []
|
||||
fm = frontmatter_re.search(src)
|
||||
if fm:
|
||||
regions.append(fm.group(1))
|
||||
for script_match in script_re.finditer(src):
|
||||
regions.append(script_match.group(1))
|
||||
for region in regions:
|
||||
for m in static_import_re.finditer(region):
|
||||
raw = m.group(1)
|
||||
if not raw:
|
||||
continue
|
||||
if raw.startswith("."):
|
||||
resolved = Path(os.path.normpath(path.parent / raw))
|
||||
if resolved.suffix == ".js":
|
||||
resolved = resolved.with_suffix(".ts")
|
||||
elif resolved.suffix == ".jsx":
|
||||
resolved = resolved.with_suffix(".tsx")
|
||||
node_id = _make_id(str(resolved))
|
||||
stub_source_file = str(resolved)
|
||||
else:
|
||||
resolved_alias = None
|
||||
for alias_prefix, alias_base in aliases.items():
|
||||
if raw == alias_prefix or raw.startswith(alias_prefix + "/"):
|
||||
rest = raw[len(alias_prefix):].lstrip("/")
|
||||
resolved_alias = Path(os.path.normpath(Path(alias_base) / rest))
|
||||
break
|
||||
if resolved_alias is not None:
|
||||
node_id = _make_id(str(resolved_alias))
|
||||
stub_source_file = str(resolved_alias)
|
||||
else:
|
||||
module_name = raw.split("/")[-1]
|
||||
if not module_name:
|
||||
continue
|
||||
node_id = _make_id(module_name)
|
||||
stub_source_file = raw
|
||||
if node_id in existing_ids:
|
||||
result.setdefault("edges", []).append({
|
||||
"source": file_node_id, "target": node_id,
|
||||
"relation": "imports_from", "confidence": "EXTRACTED",
|
||||
"source_file": str(path),
|
||||
})
|
||||
continue
|
||||
result.setdefault("nodes", []).append({
|
||||
"id": node_id, "label": raw,
|
||||
"file_type": "code", "source_file": stub_source_file,
|
||||
"confidence": "EXTRACTED",
|
||||
})
|
||||
result.setdefault("edges", []).append({
|
||||
"source": file_node_id, "target": node_id,
|
||||
"relation": "imports_from", "confidence": "EXTRACTED",
|
||||
"source_file": str(path),
|
||||
})
|
||||
existing_ids.add(node_id)
|
||||
except Exception:
|
||||
pass
|
||||
return result
|
||||
|
||||
|
||||
def extract_java(path: Path) -> dict:
|
||||
"""Extract classes, interfaces, methods, constructors, and imports from a .java file."""
|
||||
return _extract_generic(path, _JAVA_CONFIG)
|
||||
@@ -5490,6 +5626,7 @@ _DISPATCH: dict[str, Any] = {
|
||||
".F08": extract_fortran,
|
||||
".vue": extract_js,
|
||||
".svelte": extract_svelte,
|
||||
".astro": extract_astro,
|
||||
".dart": extract_dart,
|
||||
".v": extract_verilog,
|
||||
".sv": extract_verilog,
|
||||
|
||||
+15
-1
@@ -197,8 +197,22 @@ def _hooks_dir(root: Path) -> Path:
|
||||
f"{root / '.git' / 'config'}: {exc}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
# In a linked worktree .git is a file not a directory, so constructing
|
||||
# root/.git/hooks directly fails. Ask git for the real hooks path instead.
|
||||
import subprocess as _sp
|
||||
try:
|
||||
res = _sp.run(
|
||||
["git", "-C", str(root), "rev-parse", "--path-format=absolute", "--git-path", "hooks"],
|
||||
capture_output=True, text=True,
|
||||
)
|
||||
if res.returncode == 0:
|
||||
d = Path(res.stdout.strip())
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
except (OSError, FileNotFoundError):
|
||||
pass
|
||||
d = root / ".git" / "hooks"
|
||||
d.mkdir(exist_ok=True)
|
||||
d.mkdir(parents=True, exist_ok=True)
|
||||
return d
|
||||
|
||||
|
||||
|
||||
@@ -241,8 +241,8 @@ all_files = [f for files in detect['files'].values() for f in files]
|
||||
cached_nodes, cached_edges, cached_hyperedges, uncached = check_semantic_cache(all_files)
|
||||
|
||||
if cached_nodes or cached_edges or cached_hyperedges:
|
||||
Path('.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
|
||||
Path('graphify-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}, ensure_ascii=False), encoding="utf-8")
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached), encoding="utf-8")
|
||||
print(f'Cache: {len(all_files)-len(uncached)} files hit, {len(uncached)} files need extraction')
|
||||
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_5.py -Encoding utf8
|
||||
python .graphify_step_3_extract_entities_and_relations_5.py
|
||||
@@ -370,7 +370,7 @@ import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
saved = save_semantic_cache(new.get('nodes', []), new.get('edges', []), new.get('hyperedges', []))
|
||||
print(f'Cached {saved} files')
|
||||
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_6.py -Encoding utf8
|
||||
@@ -384,8 +384,8 @@ Merge cached + new results into `.graphify_semantic.json`:
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('.graphify_cached.json').read_text(encoding="utf-8")) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text(encoding="utf-8")) if Path('graphify-out/.graphify_semantic_new.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
|
||||
all_nodes = cached['nodes'] + new.get('nodes', [])
|
||||
all_edges = cached['edges'] + new.get('edges', [])
|
||||
@@ -404,13 +404,13 @@ merged = {
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Extraction complete - {len(deduped)} nodes, {len(all_edges)} edges ({len(cached["nodes"])} from cache, {len(new.get("nodes",[]))} new)')
|
||||
'@ | Out-File -FilePath .graphify_step_3_extract_entities_and_relations_7.py -Encoding utf8
|
||||
python .graphify_step_3_extract_entities_and_relations_7.py
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_step_3_extract_entities_and_relations_7.py
|
||||
```
|
||||
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue .graphify_cached.json, .graphify_uncached.txt, .graphify_semantic_new.json`
|
||||
Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue graphify-out\.graphify_cached.json, graphify-out\.graphify_uncached.txt, graphify-out\.graphify_semantic_new.json`
|
||||
|
||||
#### Part C - Merge AST + semantic into final extraction
|
||||
|
||||
|
||||
+3
-1
@@ -207,6 +207,8 @@ This step has two parts: **structural extraction** (deterministic, free) and **s
|
||||
|
||||
Print it once, then continue. If `GEMINI_API_KEY` or `GOOGLE_API_KEY` IS set, use `graphify.llm.extract_corpus_parallel(files, backend="gemini")` for semantic extraction instead of dispatching Claude subagents. The default Gemini model is `gemini-3-flash-preview`; set `GRAPHIFY_GEMINI_MODEL` or pass `--model` in headless CLI flows to override it.
|
||||
|
||||
> **No other API keys are read.** If `GEMINI_API_KEY`/`GOOGLE_API_KEY` are unset, fall straight through to Claude Code subagent dispatch (Part B below) — the host session itself is the LLM. graphify does **not** read `ANTHROPIC_API_KEY`, `OPENAI_API_KEY`, or any other provider key from the environment. If a host agent prompts the user for `ANTHROPIC_API_KEY` to run extraction, that prompt is a misread of this skill — ignore it and dispatch subagents as written.
|
||||
|
||||
**Run Part A (AST) and Part B (semantic) in parallel. Dispatch all semantic subagents AND start AST extraction in the same message. Both can run simultaneously since they operate on different file types. Merge results in Part C as before.**
|
||||
|
||||
Note: Parallelizing AST + semantic saves 5-15s on large corpora. AST is deterministic and fast; start it while subagents are processing docs/papers.
|
||||
@@ -357,7 +359,7 @@ confidence_score is REQUIRED on every edge - never omit it, never use 0.5 as a d
|
||||
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.
|
||||
Node ID format: lowercase, only `[a-z0-9_]`, no dots or slashes. Format: `{stem}_{entity}` where stem is `{parent_dir}_{filename_without_ext}` (the **immediate** parent directory name + the filename stem, both lowercased with non-alphanumeric chars replaced by `_`) and entity is the symbol name similarly normalized. Only one level of parent is used — not the full path. Examples: `src/auth/session.py` + `ValidateToken` → `auth_session_validatetoken`; `lib/utils/helpers.py` + `parse_url` → `utils_helpers_parse_url`; `tests/test_foo.py` + `_helper` → `tests_test_foo_helper`. Top-level files (no parent dir, e.g. `setup.py`) use just the filename stem: `setup_my_func`. This must match the ID the AST extractor generates — using just the filename (e.g., `session_validatetoken`) or the full path (e.g., `src_auth_session_validatetoken`) will create orphan ghost-duplicate nodes. If you are re-extracting a project that had ghost duplicates under the old format, the user should run `graphify extract --force` to rebuild cleanly. 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.
|
||||
|
||||
Generate the extraction JSON matching this schema exactly:
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale|concept","source_file":"relative/path","source_location":null,"source_url":null,"captured_at":null,"author":null,"contributor":null}],"edges":[{"source":"node_id","target":"node_id","relation":"calls|implements|references|cites|conceptually_related_to|shares_data_with|semantically_similar_to|rationale_for","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[{"id":"snake_case_id","label":"Human Readable Label","nodes":["node_id1","node_id2","node_id3"],"relation":"participate_in|implement|form","confidence":"EXTRACTED|INFERRED","confidence_score":0.75,"source_file":"relative/path"}],"input_tokens":0,"output_tokens":0}
|
||||
|
||||
+287
-38
@@ -3,6 +3,7 @@ from __future__ import annotations
|
||||
import contextlib
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
@@ -18,6 +19,11 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
``blocking`` is False. Uses fcntl.flock so the lock is released
|
||||
automatically if the process is killed (no stale-lock cleanup needed).
|
||||
|
||||
While the lock is held, ``.rebuild.lock`` contains the owning PID followed
|
||||
by a newline so external pollers (publish scripts, etc.) can read it.
|
||||
On successful release the file is unlinked so downstream tooling that
|
||||
waits for the lock to clear by polling for its absence unblocks promptly.
|
||||
|
||||
Falls back to a no-op yield(True) on platforms without fcntl (Windows).
|
||||
"""
|
||||
try:
|
||||
@@ -28,7 +34,11 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
|
||||
out_dir.mkdir(parents=True, exist_ok=True)
|
||||
lock_path = out_dir / ".rebuild.lock"
|
||||
fh = open(lock_path, "a", encoding="utf-8")
|
||||
# "a+" creates the file if missing without truncating an existing holder's
|
||||
# PID payload — important because another process may have already written
|
||||
# its PID before we attempt the flock.
|
||||
fh = open(lock_path, "a+", encoding="utf-8")
|
||||
acquired = False
|
||||
try:
|
||||
flags = fcntl.LOCK_EX if blocking else (fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
try:
|
||||
@@ -36,18 +46,29 @@ def _rebuild_lock(out_dir: Path, *, blocking: bool = False):
|
||||
except BlockingIOError:
|
||||
yield False
|
||||
return
|
||||
acquired = True
|
||||
# Replace any prior owner's PID with ours so external readers see a
|
||||
# single parseable line, not a digit-concatenation across rebuilds.
|
||||
try:
|
||||
fh.write(str(os.getpid()))
|
||||
fh.seek(0)
|
||||
fh.truncate()
|
||||
fh.write(f"{os.getpid()}\n")
|
||||
fh.flush()
|
||||
except OSError:
|
||||
pass
|
||||
yield True
|
||||
finally:
|
||||
try:
|
||||
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
||||
except OSError:
|
||||
pass
|
||||
if acquired:
|
||||
try:
|
||||
fcntl.flock(fh.fileno(), fcntl.LOCK_UN)
|
||||
except OSError:
|
||||
pass
|
||||
fh.close()
|
||||
# Signal "rebuild done" by removing the lock file. Only the holder
|
||||
# unlinks; a non-acquiring caller leaves the existing lock in place.
|
||||
if acquired:
|
||||
with contextlib.suppress(OSError):
|
||||
lock_path.unlink()
|
||||
|
||||
|
||||
def _apply_resource_limits() -> None:
|
||||
@@ -115,16 +136,145 @@ def _relativize_source_files(payload: dict, root: Path) -> None:
|
||||
continue
|
||||
|
||||
|
||||
def _node_community_map(graph_data: dict) -> dict[str, int]:
|
||||
out: dict[str, int] = {}
|
||||
for node in graph_data.get("nodes", []):
|
||||
node_id = node.get("id")
|
||||
cid = node.get("community")
|
||||
if node_id is None or cid is None:
|
||||
continue
|
||||
try:
|
||||
out[str(node_id)] = int(cid)
|
||||
except (TypeError, ValueError):
|
||||
print(
|
||||
f"[graphify watch] Skipping node with invalid community id: "
|
||||
f"node_id={node_id!r} community={cid!r}",
|
||||
file=sys.stderr,
|
||||
)
|
||||
continue
|
||||
return out
|
||||
|
||||
|
||||
def _canonical_graph_for_compare(graph_data: dict) -> dict:
|
||||
canonical = dict(graph_data)
|
||||
canonical.pop("built_at_commit", None)
|
||||
for key in ("nodes", "links", "edges", "hyperedges"):
|
||||
if key in canonical and isinstance(canonical[key], list):
|
||||
canonical[key] = sorted(
|
||||
canonical[key],
|
||||
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
|
||||
)
|
||||
return canonical
|
||||
|
||||
|
||||
def _canonical_topology_for_compare(graph_data: dict) -> dict:
|
||||
canonical = dict(graph_data)
|
||||
canonical.pop("built_at_commit", None)
|
||||
|
||||
nodes = canonical.get("nodes")
|
||||
if isinstance(nodes, list):
|
||||
norm_nodes = []
|
||||
for node in nodes:
|
||||
if not isinstance(node, dict):
|
||||
continue
|
||||
n = dict(node)
|
||||
n.pop("community", None)
|
||||
n.pop("norm_label", None)
|
||||
norm_nodes.append(n)
|
||||
canonical["nodes"] = sorted(
|
||||
norm_nodes,
|
||||
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
for key in ("links", "edges"):
|
||||
items = canonical.get(key)
|
||||
if not isinstance(items, list):
|
||||
continue
|
||||
norm_edges = []
|
||||
for edge in items:
|
||||
if not isinstance(edge, dict):
|
||||
continue
|
||||
e = dict(edge)
|
||||
# to_json writes _src/_tgt as the canonical directed endpoints and
|
||||
# overwrites source/target with them before serialising, so the
|
||||
# on-disk graph has no _src/_tgt. The candidate topology (fresh from
|
||||
# node_link_data) still has them. Popping and reassigning here makes
|
||||
# both sides comparable: existing gets no-op pops (None), candidate
|
||||
# gets source/target overwritten from _src/_tgt — same result.
|
||||
true_src = e.pop("_src", None)
|
||||
true_tgt = e.pop("_tgt", None)
|
||||
if true_src is not None and true_tgt is not None:
|
||||
e["source"] = true_src
|
||||
e["target"] = true_tgt
|
||||
e.pop("confidence_score", None)
|
||||
norm_edges.append(e)
|
||||
canonical[key] = sorted(
|
||||
norm_edges,
|
||||
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
hyperedges = canonical.get("hyperedges")
|
||||
if isinstance(hyperedges, list):
|
||||
canonical["hyperedges"] = sorted(
|
||||
hyperedges,
|
||||
key=lambda item: json.dumps(item, sort_keys=True, ensure_ascii=False, default=str),
|
||||
)
|
||||
|
||||
return canonical
|
||||
|
||||
|
||||
def _topology_from_graph(G) -> dict:
|
||||
from networkx.readwrite import json_graph
|
||||
try:
|
||||
data = json_graph.node_link_data(G, edges="links")
|
||||
except TypeError:
|
||||
data = json_graph.node_link_data(G)
|
||||
data["hyperedges"] = getattr(G, "graph", {}).get("hyperedges", [])
|
||||
return data
|
||||
|
||||
|
||||
def _check_shrink(force: bool, existing_data: dict, new_data: dict, tmp: "Path | None" = None) -> bool:
|
||||
"""Return True (ok to proceed) or False (shrink refused).
|
||||
|
||||
When False, cleans up *tmp* if provided and prints a warning to stderr.
|
||||
"""
|
||||
if force or not existing_data:
|
||||
return True
|
||||
existing_n = len(existing_data.get("nodes", []))
|
||||
new_n = len(new_data.get("nodes", []))
|
||||
if new_n < existing_n:
|
||||
if tmp is not None:
|
||||
tmp.unlink(missing_ok=True)
|
||||
print(
|
||||
f"[graphify] WARNING: new graph has {new_n} nodes but existing "
|
||||
f"graph.json has {existing_n}. Refusing to overwrite — you may be "
|
||||
f"missing chunk files from a previous session. "
|
||||
f"Pass --force to override.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
def _report_for_compare(report_text: str) -> str:
|
||||
return re.sub(r"^- Built from commit: `[^`]+`\n?", "", report_text, flags=re.MULTILINE)
|
||||
|
||||
|
||||
def _json_text(data: dict) -> str:
|
||||
return json.dumps(data, indent=2, ensure_ascii=False) + "\n"
|
||||
|
||||
|
||||
def _rebuild_code(
|
||||
watch_path: Path,
|
||||
*,
|
||||
changed_paths: list[Path] | None = None,
|
||||
follow_symlinks: bool = False,
|
||||
force: bool = False,
|
||||
no_cluster: bool = False,
|
||||
acquire_lock: bool = True,
|
||||
block_on_lock: bool = False,
|
||||
) -> bool:
|
||||
"""Re-run AST extraction + build + cluster + report for code files. No LLM needed.
|
||||
"""Re-run AST extraction + build + optional cluster + report for code files. No LLM needed.
|
||||
|
||||
When ``force`` is True the node-count safety check in ``to_json`` is bypassed
|
||||
so the rebuilt graph overwrites graph.json even if it has fewer nodes.
|
||||
@@ -142,6 +292,9 @@ def _rebuild_code(
|
||||
``block_on_lock=True`` to wait instead of skip (used by the interactive
|
||||
``graphify update`` CLI).
|
||||
|
||||
``no_cluster`` skips community detection and writes raw merged extraction
|
||||
JSON to graphify-out/graph.json (mirrors ``extract --no-cluster``).
|
||||
|
||||
Returns True on success, False on error or skipped-due-to-lock.
|
||||
"""
|
||||
out = watch_path / _GRAPHIFY_OUT
|
||||
@@ -156,6 +309,7 @@ def _rebuild_code(
|
||||
changed_paths=changed_paths,
|
||||
follow_symlinks=follow_symlinks,
|
||||
force=force,
|
||||
no_cluster=no_cluster,
|
||||
acquire_lock=False,
|
||||
)
|
||||
|
||||
@@ -166,7 +320,7 @@ def _rebuild_code(
|
||||
from graphify.extract import extract, _get_extractor
|
||||
from graphify.detect import detect
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, score_all
|
||||
from graphify.cluster import cluster, remap_communities_to_previous, score_all
|
||||
from graphify.analyze import god_nodes, surprising_connections, suggest_questions
|
||||
from graphify.report import generate
|
||||
from graphify.export import to_json, to_html
|
||||
@@ -225,9 +379,11 @@ def _rebuild_code(
|
||||
# source_file matches a path that was changed (re-extracted) or deleted —
|
||||
# otherwise the old nodes for those files would survive forever.
|
||||
existing_graph = out / "graph.json"
|
||||
existing_graph_data: dict = {}
|
||||
if existing_graph.exists():
|
||||
try:
|
||||
existing = json.loads(existing_graph.read_text(encoding="utf-8"))
|
||||
existing_graph_data = existing
|
||||
new_ast_ids = {n["id"] for n in result["nodes"]}
|
||||
evict_sources: set[str] = set(deleted_paths)
|
||||
if changed_paths is not None:
|
||||
@@ -257,6 +413,51 @@ def _rebuild_code(
|
||||
pass # corrupt graph.json - proceed with AST-only
|
||||
|
||||
_relativize_source_files(result, project_root)
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
if no_cluster:
|
||||
# Normalise to "links" key so schema is consistent with the full clustered path.
|
||||
candidate_graph_data = {
|
||||
**{k: v for k, v in result.items() if k != "edges"},
|
||||
"links": result.get("edges", []),
|
||||
}
|
||||
candidate_graph_text = _json_text(candidate_graph_data)
|
||||
same_graph = False
|
||||
if existing_graph.exists():
|
||||
try:
|
||||
existing_payload = json.loads(existing_graph.read_text(encoding="utf-8"))
|
||||
same_graph = (
|
||||
json.dumps(_canonical_graph_for_compare(existing_payload), sort_keys=True, ensure_ascii=False)
|
||||
== json.dumps(_canonical_graph_for_compare(candidate_graph_data), sort_keys=True, ensure_ascii=False)
|
||||
)
|
||||
except Exception:
|
||||
same_graph = False
|
||||
if not same_graph:
|
||||
if not _check_shrink(force, existing_graph_data, candidate_graph_data):
|
||||
return False
|
||||
existing_graph.write_text(candidate_graph_text, encoding="utf-8")
|
||||
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"], kind="ast")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# clear stale needs_update flag if present
|
||||
flag = out / "needs_update"
|
||||
if flag.exists():
|
||||
flag.unlink()
|
||||
|
||||
if same_graph:
|
||||
print("[graphify watch] No code-graph changes detected (--no-cluster); outputs left untouched.")
|
||||
else:
|
||||
print(
|
||||
"[graphify watch] Rebuilt (no clustering): "
|
||||
f"{len(result.get('nodes', []))} nodes, {len(result.get('edges', []))} edges"
|
||||
)
|
||||
print(f"[graphify watch] graph.json updated in {out}")
|
||||
return True
|
||||
|
||||
detection = {
|
||||
"files": {"code": [str(f) for f in code_files], "document": [], "paper": [], "image": []},
|
||||
@@ -265,7 +466,31 @@ def _rebuild_code(
|
||||
}
|
||||
|
||||
G = build_from_json(result)
|
||||
candidate_topology = _topology_from_graph(G)
|
||||
if existing_graph_data:
|
||||
try:
|
||||
same_topology = (
|
||||
json.dumps(_canonical_topology_for_compare(existing_graph_data), sort_keys=True, ensure_ascii=False)
|
||||
== json.dumps(_canonical_topology_for_compare(candidate_topology), sort_keys=True, ensure_ascii=False)
|
||||
)
|
||||
except Exception:
|
||||
same_topology = False
|
||||
if same_topology:
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"], kind="ast")
|
||||
except Exception:
|
||||
pass
|
||||
flag = out / "needs_update"
|
||||
if flag.exists():
|
||||
flag.unlink()
|
||||
print("[graphify watch] No code-graph topology changes detected; outputs left untouched.")
|
||||
return True
|
||||
|
||||
communities = cluster(G)
|
||||
previous_node_community = _node_community_map(existing_graph_data)
|
||||
if previous_node_community:
|
||||
communities = remap_communities_to_previous(communities, previous_node_community)
|
||||
cohesion = score_all(G, communities)
|
||||
gods = god_nodes(G)
|
||||
surprises = surprising_connections(G, communities)
|
||||
@@ -280,41 +505,64 @@ def _rebuild_code(
|
||||
if cid not in labels:
|
||||
labels[cid] = "Community " + str(cid)
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
out.mkdir(exist_ok=True)
|
||||
(out / ".graphify_root").write_text(str(watch_root), encoding="utf-8")
|
||||
|
||||
json_written = to_json(G, communities, str(out / "graph.json"), force=force, built_at_commit=commit)
|
||||
if not json_written:
|
||||
return False
|
||||
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"])
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection,
|
||||
{"input": 0, "output": 0}, report_root, suggested_questions=questions,
|
||||
built_at_commit=commit)
|
||||
(out / "GRAPH_REPORT.md").write_text(report, encoding="utf-8")
|
||||
report_path = out / "GRAPH_REPORT.md"
|
||||
labels_json = json.dumps({str(k): v for k, v in sorted(labels.items())}, ensure_ascii=False, indent=2) + "\n"
|
||||
graph_tmp = out / ".graph.tmp.json"
|
||||
json_written = to_json(G, communities, str(graph_tmp), force=True, built_at_commit=commit)
|
||||
if not json_written:
|
||||
return False
|
||||
candidate_graph_data = json.loads(graph_tmp.read_text(encoding="utf-8"))
|
||||
same_graph = False
|
||||
same_report = False
|
||||
if existing_graph.exists():
|
||||
try:
|
||||
existing_payload = json.loads(existing_graph.read_text(encoding="utf-8"))
|
||||
same_graph = (
|
||||
json.dumps(_canonical_graph_for_compare(existing_payload), sort_keys=True, ensure_ascii=False)
|
||||
== json.dumps(_canonical_graph_for_compare(candidate_graph_data), sort_keys=True, ensure_ascii=False)
|
||||
)
|
||||
except Exception:
|
||||
same_graph = False
|
||||
if report_path.exists():
|
||||
old_report = report_path.read_text(encoding="utf-8")
|
||||
same_report = _report_for_compare(old_report) == _report_for_compare(report)
|
||||
no_change = same_graph and same_report
|
||||
if no_change:
|
||||
graph_tmp.unlink(missing_ok=True)
|
||||
print("[graphify watch] No code-graph changes detected; graph.json/GRAPH_REPORT.md left untouched.")
|
||||
else:
|
||||
if not _check_shrink(force, existing_graph_data, candidate_graph_data, tmp=graph_tmp):
|
||||
return False
|
||||
graph_tmp.replace(existing_graph)
|
||||
report_path.write_text(report, encoding="utf-8")
|
||||
labels_file.write_text(labels_json, encoding="utf-8")
|
||||
|
||||
try:
|
||||
from graphify.detect import save_manifest
|
||||
save_manifest(detected["files"], kind="ast")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# to_html raises ValueError for graphs > MAX_NODES_FOR_VIZ (5000).
|
||||
# Wrap so core outputs (graph.json + GRAPH_REPORT.md) always land.
|
||||
html_written = False
|
||||
try:
|
||||
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
|
||||
html_written = True
|
||||
except ValueError as viz_err:
|
||||
print(f"[graphify watch] Skipped graph.html: {viz_err}")
|
||||
stale = out / "graph.html"
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
if not no_change:
|
||||
try:
|
||||
to_html(G, communities, str(out / "graph.html"), community_labels=labels or None)
|
||||
html_written = True
|
||||
except ValueError as viz_err:
|
||||
print(f"[graphify watch] Skipped graph.html: {viz_err}")
|
||||
stale = out / "graph.html"
|
||||
if stale.exists():
|
||||
stale.unlink()
|
||||
|
||||
# Regenerate callflow HTML if the user previously generated one —
|
||||
# opt-in by existence so users who never ran callflow-html aren't affected.
|
||||
callflow_files = list(out.glob("*-callflow.html"))
|
||||
if callflow_files:
|
||||
if callflow_files and not no_change:
|
||||
try:
|
||||
from graphify.callflow_html import write_callflow_html
|
||||
for cf in callflow_files:
|
||||
@@ -333,12 +581,13 @@ def _rebuild_code(
|
||||
if flag.exists():
|
||||
flag.unlink()
|
||||
|
||||
print(f"[graphify watch] Rebuilt: {G.number_of_nodes()} nodes, "
|
||||
f"{G.number_of_edges()} edges, {len(communities)} communities")
|
||||
products = "graph.json" + (", graph.html" if html_written else "") + " and GRAPH_REPORT.md"
|
||||
if callflow_files:
|
||||
products += f", {len(callflow_files)} callflow HTML"
|
||||
print(f"[graphify watch] {products} updated in {out}")
|
||||
if not no_change:
|
||||
print(f"[graphify watch] Rebuilt: {G.number_of_nodes()} nodes, "
|
||||
f"{G.number_of_edges()} edges, {len(communities)} communities")
|
||||
products = "graph.json" + (", graph.html" if html_written else "") + " and GRAPH_REPORT.md"
|
||||
if callflow_files:
|
||||
products += f", {len(callflow_files)} callflow HTML"
|
||||
print(f"[graphify watch] {products} updated in {out}")
|
||||
return True
|
||||
|
||||
except Exception as exc:
|
||||
|
||||
+1
-1
@@ -4,7 +4,7 @@ build-backend = "setuptools.build_meta"
|
||||
|
||||
[project]
|
||||
name = "graphifyy"
|
||||
version = "0.7.17"
|
||||
version = "0.7.19"
|
||||
description = "AI coding assistant skill (Claude Code, Codex, OpenCode, Cursor, Gemini CLI, Aider, OpenClaw, Factory Droid, Trae, Hermes, Kiro, Pi, Google Antigravity) - turn any folder of code, docs, papers, images, or videos into a queryable knowledge graph"
|
||||
readme = "README.md"
|
||||
license = { file = "LICENSE" }
|
||||
|
||||
@@ -0,0 +1,143 @@
|
||||
"""Tests for `.astro` extraction (#850).
|
||||
|
||||
Astro files have a TypeScript frontmatter block (`---...---`) at the top where
|
||||
nearly all imports live, followed by an HTML-with-expressions template and
|
||||
optionally `<script>` blocks. Tree-sitter-javascript fed the whole file produces
|
||||
a top-level ERROR node because the template is not valid JS, so the JS AST pass
|
||||
recovers nothing. The :func:`extract_astro` regex pass salvages imports from the
|
||||
frontmatter and any `<script>` blocks — same strategy as :func:`extract_svelte`.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.detect import CODE_EXTENSIONS
|
||||
from graphify.extract import (
|
||||
_make_id,
|
||||
extract_astro,
|
||||
)
|
||||
|
||||
|
||||
def _write(path: Path, body: str) -> Path:
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
path.write_text(body, encoding="utf-8")
|
||||
return path
|
||||
|
||||
|
||||
def _import_targets(result: dict, *, relation: str | None = None) -> set[str]:
|
||||
return {
|
||||
str(e.get("target") or "")
|
||||
for e in result.get("edges", [])
|
||||
if relation is None or e.get("relation") == relation
|
||||
}
|
||||
|
||||
|
||||
def test_astro_is_in_code_extensions():
|
||||
"""Without this, detect.py silently drops `.astro` from the AST pass (#850)."""
|
||||
assert ".astro" in CODE_EXTENSIONS
|
||||
|
||||
|
||||
def test_extract_astro_picks_up_frontmatter_static_imports(tmp_path):
|
||||
page = _write(
|
||||
tmp_path / "src/pages/index.astro",
|
||||
"""---
|
||||
import Layout from '../layouts/Layout.astro';
|
||||
import Hero from '../components/Hero.astro';
|
||||
const { title } = Astro.props;
|
||||
---
|
||||
|
||||
<Layout title={title}>
|
||||
<Hero />
|
||||
</Layout>
|
||||
""",
|
||||
)
|
||||
# Sibling files so the resolver lands on real node ids, not phantoms.
|
||||
layout = _write(tmp_path / "src/layouts/Layout.astro", "---\n---\n<slot />\n")
|
||||
hero = _write(tmp_path / "src/components/Hero.astro", "---\n---\n<h1>hi</h1>\n")
|
||||
|
||||
result = extract_astro(page)
|
||||
targets = _import_targets(result, relation="imports_from")
|
||||
assert _make_id(str(layout)) in targets
|
||||
assert _make_id(str(hero)) in targets
|
||||
|
||||
|
||||
def test_extract_astro_handles_dynamic_import_in_frontmatter(tmp_path):
|
||||
page = _write(
|
||||
tmp_path / "src/pages/lazy.astro",
|
||||
"""---
|
||||
const Mod = await import('./Other.astro');
|
||||
---
|
||||
|
||||
<div>{Mod.default}</div>
|
||||
""",
|
||||
)
|
||||
other = _write(tmp_path / "src/pages/Other.astro", "---\n---\n<p>o</p>\n")
|
||||
|
||||
result = extract_astro(page)
|
||||
targets = _import_targets(result, relation="dynamic_import")
|
||||
assert _make_id(str(other)) in targets
|
||||
|
||||
|
||||
def test_extract_astro_picks_up_client_side_script_imports(tmp_path):
|
||||
page = _write(
|
||||
tmp_path / "src/pages/with-script.astro",
|
||||
"""---
|
||||
import Layout from '../layouts/Layout.astro';
|
||||
---
|
||||
|
||||
<Layout>
|
||||
<button id="b">click</button>
|
||||
</Layout>
|
||||
|
||||
<script>
|
||||
import { hydrate } from '../client/hydrate.ts';
|
||||
hydrate(document.getElementById('b'));
|
||||
</script>
|
||||
""",
|
||||
)
|
||||
layout = _write(tmp_path / "src/layouts/Layout.astro", "---\n---\n<slot />\n")
|
||||
hydrate = _write(tmp_path / "src/client/hydrate.ts", "export function hydrate(){}\n")
|
||||
|
||||
result = extract_astro(page)
|
||||
targets = _import_targets(result, relation="imports_from")
|
||||
assert _make_id(str(layout)) in targets
|
||||
assert _make_id(str(hydrate)) in targets
|
||||
|
||||
|
||||
def test_extract_astro_no_frontmatter_does_not_crash(tmp_path):
|
||||
"""Astro permits frontmatter-less files (pure-HTML pages). Must not raise."""
|
||||
page = _write(
|
||||
tmp_path / "src/pages/plain.astro",
|
||||
"<h1>no frontmatter here</h1>\n",
|
||||
)
|
||||
result = extract_astro(page)
|
||||
# Empty/no-imports result is acceptable; the extractor must just not crash.
|
||||
assert isinstance(result, dict)
|
||||
assert _import_targets(result, relation="imports_from") == set()
|
||||
|
||||
|
||||
def test_extract_astro_handles_tsconfig_path_alias(tmp_path):
|
||||
_write(
|
||||
tmp_path / "tsconfig.json",
|
||||
"""{
|
||||
"compilerOptions": {
|
||||
"baseUrl": ".",
|
||||
"paths": { "@components/*": ["src/components/*"] }
|
||||
}
|
||||
}
|
||||
""",
|
||||
)
|
||||
page = _write(
|
||||
tmp_path / "src/pages/alias.astro",
|
||||
"""---
|
||||
import Hero from '@components/Hero.astro';
|
||||
---
|
||||
|
||||
<Hero />
|
||||
""",
|
||||
)
|
||||
hero = _write(tmp_path / "src/components/Hero.astro", "---\n---\n<h1>h</h1>\n")
|
||||
|
||||
result = extract_astro(page)
|
||||
targets = _import_targets(result, relation="imports_from")
|
||||
assert _make_id(str(hero)) in targets
|
||||
@@ -236,3 +236,17 @@ def test_explain_uses_graphify_out_env(tmp_path):
|
||||
def test_export_unknown_format_fails(tmp_path):
|
||||
r = _run(["export", "pdf"], tmp_path)
|
||||
assert r.returncode != 0
|
||||
|
||||
|
||||
def test_update_no_cluster_writes_raw_graph(tmp_path):
|
||||
src = tmp_path / "sample.py"
|
||||
src.write_text("def f():\n return 1\n", encoding="utf-8")
|
||||
|
||||
r = _run(["update", ".", "--no-cluster"], tmp_path)
|
||||
assert r.returncode == 0, r.stderr
|
||||
|
||||
graph_path = tmp_path / "graphify-out" / "graph.json"
|
||||
assert graph_path.exists()
|
||||
data = json.loads(graph_path.read_text(encoding="utf-8"))
|
||||
assert "nodes" in data and "links" in data
|
||||
assert all("community" not in node for node in data["nodes"])
|
||||
+25
-1
@@ -3,7 +3,7 @@ import sys
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
from graphify.build import build_from_json
|
||||
from graphify.cluster import cluster, cohesion_score, score_all
|
||||
from graphify.cluster import cluster, cohesion_score, remap_communities_to_previous, score_all
|
||||
|
||||
FIXTURES = Path(__file__).parent / "fixtures"
|
||||
|
||||
@@ -74,3 +74,27 @@ def test_cluster_does_not_write_to_stderr(capsys):
|
||||
# Allow logging output (starts with [graphify]) but no raw ANSI codes
|
||||
for line in captured.err.splitlines():
|
||||
assert "\x1b" not in line, f"cluster() wrote ANSI to stderr: {line!r}"
|
||||
|
||||
|
||||
def test_remap_communities_to_previous_reuses_old_ids():
|
||||
communities = {
|
||||
10: ["a", "b", "c"],
|
||||
11: ["d", "e"],
|
||||
}
|
||||
previous = {"a": 5, "b": 5, "c": 5, "d": 1, "e": 1}
|
||||
remapped = remap_communities_to_previous(communities, previous)
|
||||
assert set(remapped.keys()) == {1, 5}
|
||||
assert remapped[5] == ["a", "b", "c"]
|
||||
assert remapped[1] == ["d", "e"]
|
||||
|
||||
|
||||
def test_remap_communities_to_previous_assigns_deterministic_new_ids():
|
||||
communities = {
|
||||
7: ["x", "y", "z"],
|
||||
8: ["m"],
|
||||
}
|
||||
previous = {"a": 3}
|
||||
remapped = remap_communities_to_previous(communities, previous)
|
||||
assert list(remapped.keys()) == [0, 1]
|
||||
assert remapped[0] == ["x", "y", "z"]
|
||||
assert remapped[1] == ["m"]
|
||||
@@ -316,3 +316,54 @@ def test_detect_video_not_in_words(tmp_path):
|
||||
result = detect(tmp_path)
|
||||
# Only video file present — total_words should be 0
|
||||
assert result["total_words"] == 0
|
||||
|
||||
|
||||
def test_detect_skips_coverage_dir(tmp_path):
|
||||
"""coverage/ and lcov-report/ are noise dirs — HTML reports inside must be excluded (#870)."""
|
||||
cov = tmp_path / "coverage" / "lcov-report"
|
||||
cov.mkdir(parents=True)
|
||||
(cov / "index.html").write_text("<html>coverage report</html>")
|
||||
(cov / "src.ts.html").write_text("<html>file coverage</html>")
|
||||
(tmp_path / "main.py").write_text("def hello(): pass")
|
||||
result = detect(tmp_path)
|
||||
all_files = [f for files in result["files"].values() for f in files]
|
||||
cov_prefix = str(tmp_path / "coverage")
|
||||
assert not any(f.startswith(cov_prefix) for f in all_files)
|
||||
assert any("main.py" in f for f in all_files)
|
||||
|
||||
|
||||
def test_detect_skips_visual_tests_dir(tmp_path):
|
||||
"""visual-tests/ bundles and snapshots are noise — must be excluded (#869)."""
|
||||
vt = tmp_path / "visual-tests"
|
||||
vt.mkdir()
|
||||
(vt / "bundle.js").write_text("var u3=function(){};var d2=function(){}")
|
||||
(vt / "screens.tsx").write_text("export const Screen = () => <div/>")
|
||||
(tmp_path / "app.py").write_text("def main(): pass")
|
||||
result = detect(tmp_path)
|
||||
all_files = [f for files in result["files"].values() for f in files]
|
||||
assert not any("visual-tests" in f for f in all_files)
|
||||
assert any("app.py" in f for f in all_files)
|
||||
|
||||
|
||||
def test_detect_skips_snapshots_dir(tmp_path):
|
||||
"""__snapshots__/ and snapshots/ are jest/vitest artefacts — must be excluded."""
|
||||
(tmp_path / "__snapshots__").mkdir()
|
||||
(tmp_path / "__snapshots__" / "app.test.ts.snap").write_text("// Jest Snapshot\nexports[`test 1`] = `<div/>`")
|
||||
(tmp_path / "app.ts").write_text("export function greet() { return 'hi'; }")
|
||||
result = detect(tmp_path)
|
||||
all_files = [f for files in result["files"].values() for f in files]
|
||||
assert not any("__snapshots__" in f for f in all_files)
|
||||
assert any("app.ts" in f for f in all_files)
|
||||
|
||||
|
||||
def test_detect_skips_storybook_static_dir(tmp_path):
|
||||
"""storybook-static/ is a build artefact — must be excluded."""
|
||||
sb = tmp_path / "storybook-static"
|
||||
sb.mkdir()
|
||||
(sb / "index.html").write_text("<html>storybook</html>")
|
||||
(sb / "main.js").write_text("(function(){var s=1;})()")
|
||||
(tmp_path / "Button.tsx").write_text("export const Button = () => <button/>")
|
||||
result = detect(tmp_path)
|
||||
all_files = [f for files in result["files"].values() for f in files]
|
||||
assert not any("storybook-static" in f for f in all_files)
|
||||
assert any("Button.tsx" in f for f in all_files)
|
||||
+113
-1
@@ -1,9 +1,11 @@
|
||||
"""Tests for watch.py - file watcher helpers (no watchdog required)."""
|
||||
import os
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
import pytest
|
||||
|
||||
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS
|
||||
from graphify.watch import _notify_only, _WATCHED_EXTENSIONS, _rebuild_lock
|
||||
|
||||
|
||||
# --- _notify_only ---
|
||||
@@ -94,3 +96,113 @@ def test_watch_raises_without_watchdog(tmp_path, monkeypatch):
|
||||
from graphify.watch import watch
|
||||
with pytest.raises(ImportError, match="watchdog not installed"):
|
||||
watch(tmp_path)
|
||||
|
||||
|
||||
# --- _rebuild_lock (GH-858) ---
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
|
||||
def test_rebuild_lock_writes_pid_with_newline(tmp_path):
|
||||
out = tmp_path / "graphify-out"
|
||||
lock_path = out / ".rebuild.lock"
|
||||
with _rebuild_lock(out) as got:
|
||||
assert got is True
|
||||
assert lock_path.exists()
|
||||
contents = lock_path.read_text(encoding="utf-8")
|
||||
assert contents == f"{os.getpid()}\n", contents
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
|
||||
def test_rebuild_lock_removed_after_release(tmp_path):
|
||||
"""GH-858: lock file must be unlinked once the rebuild completes so
|
||||
downstream waiters that poll for its absence unblock promptly."""
|
||||
out = tmp_path / "graphify-out"
|
||||
lock_path = out / ".rebuild.lock"
|
||||
with _rebuild_lock(out) as got:
|
||||
assert got is True
|
||||
assert not lock_path.exists(), "lock file should be unlinked after release"
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
|
||||
def test_rebuild_lock_does_not_accumulate_pids_across_runs(tmp_path):
|
||||
"""GH-858: each acquisition truncates and rewrites the PID line rather
|
||||
than appending, so the file never grows into a digit-concatenation."""
|
||||
out = tmp_path / "graphify-out"
|
||||
lock_path = out / ".rebuild.lock"
|
||||
expected = f"{os.getpid()}\n"
|
||||
for _ in range(5):
|
||||
with _rebuild_lock(out) as got:
|
||||
assert got is True
|
||||
assert lock_path.read_text(encoding="utf-8") == expected
|
||||
assert not lock_path.exists()
|
||||
|
||||
|
||||
@pytest.mark.skipif(sys.platform == "win32", reason="fcntl-only (POSIX)")
|
||||
def test_rebuild_lock_non_blocking_does_not_clobber_holder(tmp_path):
|
||||
"""GH-858: a non-blocking caller that fails to acquire the lock must not
|
||||
truncate the holder's PID payload."""
|
||||
out = tmp_path / "graphify-out"
|
||||
lock_path = out / ".rebuild.lock"
|
||||
with _rebuild_lock(out) as outer:
|
||||
assert outer is True
|
||||
held_contents = lock_path.read_text(encoding="utf-8")
|
||||
with _rebuild_lock(out, blocking=False) as inner:
|
||||
assert inner is False
|
||||
# Holder's PID line must still be intact.
|
||||
assert lock_path.read_text(encoding="utf-8") == held_contents
|
||||
|
||||
|
||||
def test_rebuild_code_is_idempotent_when_cluster_ids_flap(tmp_path, monkeypatch):
|
||||
from graphify import cluster as cluster_mod
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
src = tmp_path / "app.py"
|
||||
src.write_text("def alpha():\n return 1\n\ndef beta():\n return alpha()\n", encoding="utf-8")
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
def flaky_cluster(G):
|
||||
calls["n"] += 1
|
||||
nodes = sorted(G.nodes())
|
||||
if calls["n"] % 2 == 1:
|
||||
return {100: nodes}
|
||||
return {7: nodes}
|
||||
|
||||
monkeypatch.setattr(cluster_mod, "cluster", flaky_cluster)
|
||||
monkeypatch.setattr(cluster_mod, "score_all", lambda _G, comm: {cid: 1.0 for cid in comm})
|
||||
|
||||
assert _rebuild_code(tmp_path)
|
||||
graph_path = tmp_path / "graphify-out" / "graph.json"
|
||||
report_path = tmp_path / "graphify-out" / "GRAPH_REPORT.md"
|
||||
first_graph = graph_path.read_text(encoding="utf-8")
|
||||
first_report = report_path.read_text(encoding="utf-8")
|
||||
|
||||
assert _rebuild_code(tmp_path)
|
||||
second_graph = graph_path.read_text(encoding="utf-8")
|
||||
second_report = report_path.read_text(encoding="utf-8")
|
||||
|
||||
assert first_graph == second_graph
|
||||
assert first_report == second_report
|
||||
|
||||
|
||||
def test_rebuild_code_skips_cluster_when_topology_unchanged(tmp_path, monkeypatch):
|
||||
from graphify import cluster as cluster_mod
|
||||
from graphify.watch import _rebuild_code
|
||||
|
||||
src = tmp_path / "app.py"
|
||||
src.write_text("def alpha():\n return 1\n\ndef beta():\n return alpha()\n", encoding="utf-8")
|
||||
|
||||
calls = {"n": 0}
|
||||
|
||||
def cluster_once(G):
|
||||
calls["n"] += 1
|
||||
if calls["n"] > 1:
|
||||
raise AssertionError("cluster() should be skipped when topology is unchanged")
|
||||
return {0: sorted(G.nodes())}
|
||||
|
||||
monkeypatch.setattr(cluster_mod, "cluster", cluster_once)
|
||||
monkeypatch.setattr(cluster_mod, "score_all", lambda _G, comm: {cid: 1.0 for cid in comm})
|
||||
|
||||
assert _rebuild_code(tmp_path)
|
||||
assert _rebuild_code(tmp_path)
|
||||
assert calls["n"] == 1
|
||||
@@ -0,0 +1,467 @@
|
||||
# Graph Report - . (2026-05-13)
|
||||
|
||||
## Corpus Check
|
||||
- cluster-only mode — file stats not available
|
||||
|
||||
## Summary
|
||||
- 1886 nodes · 3876 edges · 141 communities (89 shown, 52 thin omitted)
|
||||
- Extraction: 90% EXTRACTED · 10% INFERRED · 0% AMBIGUOUS · INFERRED: 393 edges (avg confidence: 0.62)
|
||||
- Token cost: 0 input · 0 output
|
||||
|
||||
## Graph Freshness
|
||||
- Built from commit: `6085fd66`
|
||||
- Run `git rev-parse HEAD` and compare to check if the graph is stale.
|
||||
- Run `graphify update .` after code changes (no API cost).
|
||||
|
||||
## Community Hubs (Navigation)
|
||||
- [[_COMMUNITY_Community 0|Community 0]]
|
||||
- [[_COMMUNITY_Community 1|Community 1]]
|
||||
- [[_COMMUNITY_Community 2|Community 2]]
|
||||
- [[_COMMUNITY_Community 3|Community 3]]
|
||||
- [[_COMMUNITY_Community 4|Community 4]]
|
||||
- [[_COMMUNITY_Community 5|Community 5]]
|
||||
- [[_COMMUNITY_Community 6|Community 6]]
|
||||
- [[_COMMUNITY_Community 7|Community 7]]
|
||||
- [[_COMMUNITY_Community 8|Community 8]]
|
||||
- [[_COMMUNITY_Community 9|Community 9]]
|
||||
- [[_COMMUNITY_Community 10|Community 10]]
|
||||
- [[_COMMUNITY_Community 11|Community 11]]
|
||||
- [[_COMMUNITY_Community 12|Community 12]]
|
||||
- [[_COMMUNITY_Community 13|Community 13]]
|
||||
- [[_COMMUNITY_Community 14|Community 14]]
|
||||
- [[_COMMUNITY_Community 15|Community 15]]
|
||||
- [[_COMMUNITY_Community 16|Community 16]]
|
||||
- [[_COMMUNITY_Community 17|Community 17]]
|
||||
- [[_COMMUNITY_Community 18|Community 18]]
|
||||
- [[_COMMUNITY_Community 19|Community 19]]
|
||||
- [[_COMMUNITY_Community 20|Community 20]]
|
||||
- [[_COMMUNITY_Community 21|Community 21]]
|
||||
- [[_COMMUNITY_Community 22|Community 22]]
|
||||
- [[_COMMUNITY_Community 23|Community 23]]
|
||||
- [[_COMMUNITY_Community 24|Community 24]]
|
||||
- [[_COMMUNITY_Community 25|Community 25]]
|
||||
- [[_COMMUNITY_Community 26|Community 26]]
|
||||
- [[_COMMUNITY_Community 27|Community 27]]
|
||||
- [[_COMMUNITY_Community 28|Community 28]]
|
||||
- [[_COMMUNITY_Community 29|Community 29]]
|
||||
- [[_COMMUNITY_Community 30|Community 30]]
|
||||
- [[_COMMUNITY_Community 31|Community 31]]
|
||||
- [[_COMMUNITY_Community 32|Community 32]]
|
||||
- [[_COMMUNITY_Community 33|Community 33]]
|
||||
- [[_COMMUNITY_Community 34|Community 34]]
|
||||
- [[_COMMUNITY_Community 35|Community 35]]
|
||||
- [[_COMMUNITY_Community 36|Community 36]]
|
||||
- [[_COMMUNITY_Community 37|Community 37]]
|
||||
- [[_COMMUNITY_Community 38|Community 38]]
|
||||
- [[_COMMUNITY_Community 39|Community 39]]
|
||||
- [[_COMMUNITY_Community 40|Community 40]]
|
||||
- [[_COMMUNITY_Community 41|Community 41]]
|
||||
- [[_COMMUNITY_Community 42|Community 42]]
|
||||
- [[_COMMUNITY_Community 43|Community 43]]
|
||||
- [[_COMMUNITY_Community 44|Community 44]]
|
||||
- [[_COMMUNITY_Community 45|Community 45]]
|
||||
- [[_COMMUNITY_Community 46|Community 46]]
|
||||
- [[_COMMUNITY_Community 47|Community 47]]
|
||||
- [[_COMMUNITY_Community 48|Community 48]]
|
||||
- [[_COMMUNITY_Community 49|Community 49]]
|
||||
- [[_COMMUNITY_Community 50|Community 50]]
|
||||
- [[_COMMUNITY_Community 51|Community 51]]
|
||||
- [[_COMMUNITY_Community 52|Community 52]]
|
||||
- [[_COMMUNITY_Community 53|Community 53]]
|
||||
- [[_COMMUNITY_Community 54|Community 54]]
|
||||
- [[_COMMUNITY_Community 55|Community 55]]
|
||||
- [[_COMMUNITY_Community 56|Community 56]]
|
||||
- [[_COMMUNITY_Community 57|Community 57]]
|
||||
- [[_COMMUNITY_Community 58|Community 58]]
|
||||
- [[_COMMUNITY_Community 59|Community 59]]
|
||||
- [[_COMMUNITY_Community 60|Community 60]]
|
||||
- [[_COMMUNITY_Community 61|Community 61]]
|
||||
- [[_COMMUNITY_Community 62|Community 62]]
|
||||
- [[_COMMUNITY_Community 63|Community 63]]
|
||||
- [[_COMMUNITY_Community 64|Community 64]]
|
||||
- [[_COMMUNITY_Community 65|Community 65]]
|
||||
- [[_COMMUNITY_Community 66|Community 66]]
|
||||
- [[_COMMUNITY_Community 67|Community 67]]
|
||||
- [[_COMMUNITY_Community 68|Community 68]]
|
||||
- [[_COMMUNITY_Community 69|Community 69]]
|
||||
- [[_COMMUNITY_Community 70|Community 70]]
|
||||
- [[_COMMUNITY_Community 71|Community 71]]
|
||||
- [[_COMMUNITY_Community 72|Community 72]]
|
||||
- [[_COMMUNITY_Community 73|Community 73]]
|
||||
- [[_COMMUNITY_Community 76|Community 76]]
|
||||
- [[_COMMUNITY_Community 77|Community 77]]
|
||||
- [[_COMMUNITY_Community 78|Community 78]]
|
||||
- [[_COMMUNITY_Community 79|Community 79]]
|
||||
- [[_COMMUNITY_Community 80|Community 80]]
|
||||
- [[_COMMUNITY_Community 81|Community 81]]
|
||||
- [[_COMMUNITY_Community 82|Community 82]]
|
||||
- [[_COMMUNITY_Community 83|Community 83]]
|
||||
- [[_COMMUNITY_Community 84|Community 84]]
|
||||
- [[_COMMUNITY_Community 85|Community 85]]
|
||||
- [[_COMMUNITY_Community 86|Community 86]]
|
||||
- [[_COMMUNITY_Community 87|Community 87]]
|
||||
- [[_COMMUNITY_Community 88|Community 88]]
|
||||
- [[_COMMUNITY_Community 89|Community 89]]
|
||||
- [[_COMMUNITY_Community 90|Community 90]]
|
||||
- [[_COMMUNITY_Community 91|Community 91]]
|
||||
- [[_COMMUNITY_Community 92|Community 92]]
|
||||
- [[_COMMUNITY_Community 93|Community 93]]
|
||||
- [[_COMMUNITY_Community 94|Community 94]]
|
||||
- [[_COMMUNITY_Community 95|Community 95]]
|
||||
- [[_COMMUNITY_Community 96|Community 96]]
|
||||
- [[_COMMUNITY_Community 97|Community 97]]
|
||||
- [[_COMMUNITY_Community 98|Community 98]]
|
||||
- [[_COMMUNITY_Community 101|Community 101]]
|
||||
- [[_COMMUNITY_Community 102|Community 102]]
|
||||
- [[_COMMUNITY_Community 103|Community 103]]
|
||||
- [[_COMMUNITY_Community 104|Community 104]]
|
||||
- [[_COMMUNITY_Community 105|Community 105]]
|
||||
- [[_COMMUNITY_Community 106|Community 106]]
|
||||
- [[_COMMUNITY_Community 107|Community 107]]
|
||||
- [[_COMMUNITY_Community 108|Community 108]]
|
||||
- [[_COMMUNITY_Community 109|Community 109]]
|
||||
- [[_COMMUNITY_Community 110|Community 110]]
|
||||
- [[_COMMUNITY_Community 111|Community 111]]
|
||||
- [[_COMMUNITY_Community 112|Community 112]]
|
||||
- [[_COMMUNITY_Community 113|Community 113]]
|
||||
- [[_COMMUNITY_Community 114|Community 114]]
|
||||
- [[_COMMUNITY_Community 115|Community 115]]
|
||||
- [[_COMMUNITY_Community 116|Community 116]]
|
||||
- [[_COMMUNITY_Community 117|Community 117]]
|
||||
- [[_COMMUNITY_Community 118|Community 118]]
|
||||
- [[_COMMUNITY_Community 119|Community 119]]
|
||||
- [[_COMMUNITY_Community 120|Community 120]]
|
||||
- [[_COMMUNITY_Community 121|Community 121]]
|
||||
- [[_COMMUNITY_Community 122|Community 122]]
|
||||
- [[_COMMUNITY_Community 123|Community 123]]
|
||||
- [[_COMMUNITY_Community 124|Community 124]]
|
||||
- [[_COMMUNITY_Community 125|Community 125]]
|
||||
|
||||
## God Nodes (most connected - your core abstractions)
|
||||
1. `_make_siege()` - 124 edges
|
||||
2. `_make_member()` - 92 edges
|
||||
3. `_make_position()` - 85 edges
|
||||
4. `SiegeMember` - 78 edges
|
||||
5. `_make_building()` - 64 edges
|
||||
6. `_make_group()` - 60 edges
|
||||
7. `BoardPage()` - 55 edges
|
||||
8. `makeSiegeMember()` - 55 edges
|
||||
9. `PostsPage()` - 37 edges
|
||||
10. `_session_with_siege_and_configs()` - 35 edges
|
||||
|
||||
## Surprising Connections (you probably didn't know these)
|
||||
- `PostPriorityResponse` --uses--> `PostPriorityConfig` [INFERRED]
|
||||
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
|
||||
- `PostPriorityUpdate` --uses--> `PostPriorityConfig` [INFERRED]
|
||||
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
|
||||
- `TestStartupValidation` --uses--> `MemberRole` [INFERRED]
|
||||
backend/tests/test_auth.py → frontend/src/api/types.ts
|
||||
- `AuthError` --uses--> `Member` [INFERRED]
|
||||
backend/app/api/auth.py → frontend/src/api/types.ts
|
||||
- `import_file()` --calls--> `seed_post_priority_config()` [INFERRED]
|
||||
scripts/excel-import/import_excel.py → backend/app/db/seeds.py
|
||||
|
||||
## Communities (141 total, 52 thin omitted)
|
||||
|
||||
### Community 0 - "Community 0"
|
||||
Cohesion: 0.05
|
||||
Nodes (84): BuildingUpdate, _make_group(), _make_config(), Service-layer tests for update_building — focus on unbreak restoration., A Mana Shrine at level 5 has 13 teams = 4 full groups + 1 slot last group (4, Stronghold level 6: 10 groups × 3 slots. Break → reduces to base config (4 g, Adding a post-type building must use PostPriorityConfig to set the Post prio, Return a MagicMock shaped like scalars().all() → items. (+76 more)
|
||||
|
||||
### Community 1 - "Community 1"
|
||||
Cohesion: 0.05
|
||||
Nodes (45): Carousel(), CarouselProps, CarouselSlide, dot0, renderCarousel(), track, viewport, renderDropdown() (+37 more)
|
||||
|
||||
### Community 2 - "Community 2"
|
||||
Cohesion: 0.07
|
||||
Nodes (61): makeBoard(), _build_assignments_html(), _build_reserves_html(), generate_assignments_image(), generate_reserves_image(), Image generation service — renders HTML/CSS to PNG via Playwright., Build the reserves/members list HTML string. Args: members: Siege m, Render an HTML string to PNG bytes using headless Chromium. (+53 more)
|
||||
|
||||
### Community 3 - "Community 3"
|
||||
Cohesion: 0.05
|
||||
Nodes (41): activateSiege(), applyAttackDay(), cloneSiege(), completeSiege(), deleteSiege(), getSiege(), getSiegeMembers(), reopenSiege() (+33 more)
|
||||
|
||||
### Community 4 - "Community 4"
|
||||
Cohesion: 0.06
|
||||
Nodes (60): build_member_notification_message(), _build_section(), _position_label(), _position_sort_key(), PositionInfo, _positions_from_keys(), _positions_to_key_set(), Build rich per-member Discord DM messages for siege assignment notifications. (+52 more)
|
||||
|
||||
### Community 5 - "Community 5"
|
||||
Cohesion: 0.05
|
||||
Nodes (54): lifespan(), main(), FastAPI application factory and middleware wiring., Run the FastAPI/uvicorn HTTP sidecar on port 8001., Connect and run the Discord client., Start both the Discord client and HTTP server concurrently., Application lifespan — runs startup guards before serving requests., run_discord_client() (+46 more)
|
||||
|
||||
### Community 6 - "Community 6"
|
||||
Cohesion: 0.08
|
||||
Nodes (53): _make_member(), Return a minimal Member-like namespace., _preview(), Regression for #381. Setup: one member matches a condition that is active o, Invoke preview_post_suggestions with a mocked session., AC: single post with one matching member → suggestion targets that member., AC #6: post with no matching member → skip_reason='no_match'., Charge #1: is_reserve=True on the position → skip_reason='reserve'. (+45 more)
|
||||
|
||||
### Community 7 - "Community 7"
|
||||
Cohesion: 0.09
|
||||
Nodes (40): compareSiegesSpecific(), createSiege(), getSieges(), CONFIDENCE_LABEL, ConfidenceVariant, ComparisonPage(), formatPosition(), PositionTag() (+32 more)
|
||||
|
||||
### Community 8 - "Community 8"
|
||||
Cohesion: 0.07
|
||||
Nodes (40): getBoard(), PostPriorityResponse, PostPriorityUpdate, SiegeMemberCreate, AutofillApplyResult, AutofillAssignment, AutofillPreviewResult, BuildingGroupResponse (+32 more)
|
||||
|
||||
### Community 9 - "Community 9"
|
||||
Cohesion: 0.05
|
||||
Nodes (43): _make_mock_bot_with_guild(), _make_mock_member(), patch_guild_id(), Tests for GET /api/members/{discord_user_id} — guild member lookup endpoint., The @everyone role must never appear in the roles list., When Discord returns NotFound, respond 200 with is_member=false., When Discord raises an unexpected HTTPException, respond 503., When get_guild() returns None (bot not in guild), respond 503. (+35 more)
|
||||
|
||||
### Community 10 - "Community 10"
|
||||
Cohesion: 0.05
|
||||
Nodes (20): get_config(), Public config endpoint — exposes non-sensitive runtime flags to the frontend., Return public runtime configuration flags. This endpoint is intentionally u, Settings, BaseSettings, Tests for the /api/config public endpoint and startup guards. Covers: - /api/, Backend must refuse to start when SESSION_SECRET is missing and auth is enabled., GET /api/config returns the current auth_disabled flag. (+12 more)
|
||||
|
||||
### Community 11 - "Community 11"
|
||||
Cohesion: 0.06
|
||||
Nodes (42): Tests for the attack day auto-assign algorithm., Heavy hitters and advanced always get Day 2 regardless of threshold., Medium members are promoted to Day 2 (by power desc) when count < 10., Novice promoted by power desc after medium if still < 10., Overridden Day 2 members count toward the 10-threshold., attack_day_override=True members keep their existing attack_day., Exactly 10 HH/ADV → all remaining go to Day 1., Apply reads stored preview and updates siege_member attack_day values. (+34 more)
|
||||
|
||||
### Community 12 - "Community 12"
|
||||
Cohesion: 0.08
|
||||
Nodes (42): makeSiegeMember(), _make_batch(), _make_batch_result(), _make_db_session(), Endpoint tests for notification and post-to-channel routes., POST /notify must return 400 with a clear message when siege.date is None., POST /post-to-channel must return 400 with a clear message when siege.date is No, Build a mock DB session that returns the given objects. (+34 more)
|
||||
|
||||
### Community 13 - "Community 13"
|
||||
Cohesion: 0.05
|
||||
Nodes (43): Endpoints for Discord guild member ↔ clan member sync., Return proposed Discord ↔ clan member matches without writing to the DB., Apply accepted sync matches, updating discord_username and discord_id., applyDiscordSync(), previewDiscordSync(), SyncApply, SyncApplyResponse, Service logic for Discord guild member → clan member matching. (+35 more)
|
||||
|
||||
### Community 14 - "Community 14"
|
||||
Cohesion: 0.06
|
||||
Nodes (31): PostSuggestionStaleEntry, ChangeCell(), Classification, classify(), ExpiryCountdown, OutcomeFilter, Pill(), PRIORITY_META (+23 more)
|
||||
|
||||
### Community 15 - "Community 15"
|
||||
Cohesion: 0.08
|
||||
Nodes (30): createMember(), getMember(), getMemberRoles(), getPostConditions(), updateMember(), updateMemberPreferences(), MemberRoleInfo, SyncApplyItem (+22 more)
|
||||
|
||||
### Community 16 - "Community 16"
|
||||
Cohesion: 0.17
|
||||
Nodes (35): PostPriorityConfig, Building, Member, Post, PostCondition, Siege, SiegeStatus, Base (+27 more)
|
||||
|
||||
### Community 17 - "Community 17"
|
||||
Cohesion: 0.09
|
||||
Nodes (23): _cors_headers(), _make_app(), Integration tests for the CORS middleware wired in app/main.py. The middleware, Entries that are only whitespace after stripping must be dropped., A request from an explicitly allowed origin must get CORS response headers., The echoed origin must match the request, not be a wildcard., allow_credentials=True means the vary/credentials header is set., The default value from Settings must allow the dev frontend. (+15 more)
|
||||
|
||||
### Community 18 - "Community 18"
|
||||
Cohesion: 0.05
|
||||
Nodes (24): Tests for backend/app/telemetry.py. Verifies: - configure_telemetry() is a no-o, If configure_azure_monitor raises, the exception is swallowed., Regression tests: FastAPIInstrumentor.instrument_app() must be called. Issu, FastAPIInstrumentor.instrument_app() is called with the FastAPI app. Wh, When APPLICATIONINSIGHTS_CONNECTION_STRING is absent, nothing should happen., configure_azure_monitor() is called when both env vars are present. Reg, No exception and configure_azure_monitor is never imported or called., FastAPIInstrumentor.instrument_app() is NOT called when app argument is None. (+16 more)
|
||||
|
||||
### Community 19 - "Community 19"
|
||||
Cohesion: 0.08
|
||||
Nodes (36): _get(), Tests for rate limiting on the Discord OAuth2 auth endpoints. Covers: - /api/au, 3rd rapid request to /api/auth/login returns 429 when limit is 2/minute. Th, Two different X-Forwarded-For IPs have independent rate-limit buckets., 3rd rapid request to /api/auth/callback returns 429 when limit is 2/minute., When AUTH_DISABLED=true, 50 rapid requests to /login never return 429., Pathologically long X-Forwarded-For header is handled without error. Constr, Garbage XFF value falls back to the ASGI remote-address bucket. Sending ``X (+28 more)
|
||||
|
||||
### Community 20 - "Community 20"
|
||||
Cohesion: 0.12
|
||||
Nodes (34): _make_position(), _apply(), _entry_dict(), _preview_data(), Unit tests for the Suggest Post Assignments service. All tests use SimpleNamesp, Null suggested_member_id entries are skipped; no error raised., Position disabled since preview → 409 with reason position_disabled., Position set to reserve since preview → 409 with reason position_reserve. (+26 more)
|
||||
|
||||
### Community 21 - "Community 21"
|
||||
Cohesion: 0.09
|
||||
Nodes (31): build_group_structure(), compute_building_group_structure(), create_building_with_groups_and_positions(), import_file(), infer_building_level(), map_building_alias(), map_role(), parse_assignments_sheet() (+23 more)
|
||||
|
||||
### Community 22 - "Community 22"
|
||||
Cohesion: 0.1
|
||||
Nodes (17): apiClient, AppConfig, fetchConfig(), Layout(), navLinkClass(), renderLayout(), RequireAuth(), postsLink (+9 more)
|
||||
|
||||
### Community 23 - "Community 23"
|
||||
Cohesion: 0.1
|
||||
Nodes (17): downgrade(), initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16, upgrade(), add autofill and attack day preview columns to siege Revision ID: 0002 Revises:, make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1, Add post_priority_config table, Add description to post_priority_config, Replace power with power_level, drop sort_value (+9 more)
|
||||
|
||||
### Community 24 - "Community 24"
|
||||
Cohesion: 0.1
|
||||
Nodes (24): API router for the Suggest Post Assignments feature. Routes: POST /sieges/{, Generate a greedy post-assignment suggestion preview. Args: siege_i, Apply a caller-filtered subset of the stored preview atomically. Uses SELEC, applyAutofill(), applyPostSuggestions(), previewAttackDay(), previewPostSuggestions(), AttackDayApplyResult (+16 more)
|
||||
|
||||
### Community 25 - "Community 25"
|
||||
Cohesion: 0.1
|
||||
Nodes (24): compareSieges(), get_most_recent_completed(), _load_assignments(), _load_member_names(), Return {member_id: [PositionKey, ...]} for non-reserve, non-disabled assigned po, _build_siege_assignments(), Tests for siege comparison service and endpoints., Build (Position, BuildingGroup, Building) rows for mock execute results. (+16 more)
|
||||
|
||||
### Community 26 - "Community 26"
|
||||
Cohesion: 0.1
|
||||
Nodes (24): AuthError, callback(), _check_guild_membership(), _error_redirect(), _exchange_code_for_token(), _get_discord_user(), login(), logout() (+16 more)
|
||||
|
||||
### Community 27 - "Community 27"
|
||||
Cohesion: 0.13
|
||||
Nodes (22): _async_client_that_raises(), _async_client_that_returns(), _make_ok_response(), Tests for bot HTTP client graceful degradation., get_member() returns the member dict when sidecar responds 200., get_member() returns the dict as-is when sidecar responds with is_member=False., get_member() raises httpx.HTTPError when the sidecar is unreachable., get_member() raises httpx.HTTPStatusError when sidecar returns 503. (+14 more)
|
||||
|
||||
### Community 28 - "Community 28"
|
||||
Cohesion: 0.09
|
||||
Nodes (9): Tests for scripts/import_excel.py parsing logic. All tests are pure-function te, Stronghold: 4 groups all with 3 slots., Only assignments for the specified (type, number) pair are counted., Returns None when the extracted date components don't form a valid date., 1 total position in a post -> level 1., test_build_group_structure_stronghold(), test_compute_building_group_structure_filters_by_building_number(), test_infer_building_level_post() (+1 more)
|
||||
|
||||
### Community 29 - "Community 29"
|
||||
Cohesion: 0.09
|
||||
Nodes (22): Tests for GET /api/version endpoint and _read_backend_version helper., GET /api/version responds 200 with all required fields., backend_version includes build metadata when env vars are present., backend_version is bare semver when BUILD_NUMBER/GIT_SHA are absent., git_sha top-level field is still returned for backward compatibility., Force re-import of version module so env-var reads pick up monkeypatches., bot_version is null when the bot sidecar is unreachable., When BUILD_NUMBER / GIT_SHA are absent, return bare semver. (+14 more)
|
||||
|
||||
### Community 30 - "Community 30"
|
||||
Cohesion: 0.1
|
||||
Nodes (16): get_team_count(), Return the theoretical total team slots for a building type at a given level., compute_scroll_count(), Compute total scroll count from the theoretical capacity of every building., Enable SQLite foreign key enforcement (no-op on PostgreSQL)., _enable_sqlite_fk(), Enable SQLite foreign key enforcement., compute_scroll_count returns the sum of _LEVEL_TEAMS capacities for all building (+8 more)
|
||||
|
||||
### Community 31 - "Community 31"
|
||||
Cohesion: 0.11
|
||||
Nodes (21): _make_mock_db(), A correct Bearer token grants access as the bot-service principal., Full valid callback flow issues a session cookie and redirects to /., Guild member WITH the required role passes the role check and proceeds normally., Return an AsyncMock session whose db.get() returns `member`., test_callback_happy_path(), test_callback_with_required_role_proceeds_to_member_lookup(), test_valid_service_token_allows_access() (+13 more)
|
||||
|
||||
### Community 32 - "Community 32"
|
||||
Cohesion: 0.15
|
||||
Nodes (20): PostSuggestionApplyRequest, Request body for POST /post-suggestions/apply. Attributes: apply_po, engine(), Integration tests for the Suggest Post Assignments feature. These tests use a r, Charge #12: selectinload chain works against real DB. Verifies that no Miss, Second preview within TTL overwrites first in the DB JSON column. Asserts b, Charge #17: apply → re-read position from DB → matched_condition_id set. Wi, Charge #22: member_changed reason fires when position written between preview an (+12 more)
|
||||
|
||||
### Community 33 - "Community 33"
|
||||
Cohesion: 0.1
|
||||
Nodes (17): _make_expired_jwt(), Tests for Discord OAuth2 auth middleware and endpoints., A wrong Bearer token is rejected with 401., An expired JWT cookie is rejected with 401., /api/version is accessible without any credentials., Mismatched OAuth state redirects to /login?error=invalid_state., Guild member response without role_names key is treated as no roles (rejected)., Bot sidecar connection error redirects to /login?error=service_unavailable. (+9 more)
|
||||
|
||||
### Community 34 - "Community 34"
|
||||
Cohesion: 0.22
|
||||
Nodes (17): generate_images(), Image generation endpoints., Generate PNG images for siege assignments and members list., getNotificationBatch(), notifySiegeMembers(), postToChannel(), Notification endpoints — send DMs and post images to Discord., Send DM notifications to all siege members asynchronously. (+9 more)
|
||||
|
||||
### Community 35 - "Community 35"
|
||||
Cohesion: 0.12
|
||||
Nodes (17): apiAddBuilding(), apiCreateMember(), apiCreateSiege(), autofillBtn, buildingsTab, chevron, firstPositionSpan, positionCell (+9 more)
|
||||
|
||||
### Community 36 - "Community 36"
|
||||
Cohesion: 0.11
|
||||
Nodes (13): PostSuggestionPreviewResult, applyBtn, board, btn, chip, labels, makePostBoard(), makeTwoPostBoard() (+5 more)
|
||||
|
||||
### Community 37 - "Community 37"
|
||||
Cohesion: 0.15
|
||||
Nodes (14): Send DMs for each member and record results in a fresh DB session., _send_dms(), Find member by username in the guild, open DM, send message., Find text channel by name, post message., Find text channel by name, post image as Discord file attachment. Retur, Discord client for the Siege Assignment System., SiegeBot, _get_bot() (+6 more)
|
||||
|
||||
### Community 38 - "Community 38"
|
||||
Cohesion: 0.14
|
||||
Nodes (13): getPostPriorities(), getPosts(), updatePostPriority(), getSiegeMemberPreferences(), DuplicateConditionMap, MemberWithMatches, postsTab, priorityBadgeColor() (+5 more)
|
||||
|
||||
### Community 39 - "Community 39"
|
||||
Cohesion: 0.19
|
||||
Nodes (15): bulk_update_positions(), list_posts(), Build a PostResponse-compatible dict, denormalizing building_number from the rel, _serialize_post(), setPostConditions(), updatePost(), Update a single position's assignment. Raises: 404 if position not, Apply multiple position updates in a single transaction. Each update dict m (+7 more)
|
||||
|
||||
### Community 40 - "Community 40"
|
||||
Cohesion: 0.17
|
||||
Nodes (14): VersionInfo, _fetch_bot_version(), getVersion(), Return a version string for the backend. When both BUILD_NUMBER and GIT_SHA, Call the bot sidecar's /version endpoint. Returns None if unreachable., Return version information for all components., _read_backend_version(), useVersion() (+6 more)
|
||||
|
||||
### Community 41 - "Community 41"
|
||||
Cohesion: 0.15
|
||||
Nodes (11): ChangelogStatus, fetchChangelogStatus(), DropdownMenuCheckboxItem, DropdownMenuContent, DropdownMenuItem, DropdownMenuLabel, DropdownMenuRadioItem, DropdownMenuSeparator (+3 more)
|
||||
|
||||
### Community 42 - "Community 42"
|
||||
Cohesion: 0.16
|
||||
Nodes (14): list_buildings(), list_members(), list_post_priorities(), list_siege_members(), delete_siege(), get_siege(), list_sieges(), previewAutofill() (+6 more)
|
||||
|
||||
### Community 43 - "Community 43"
|
||||
Cohesion: 0.13
|
||||
Nodes (14): db_session(), Schema constraint and seed data tests using in-memory SQLite., seed_building_type_config populates exactly 5 rows., Inserting a duplicate (siege_id, member_id) pair raises IntegrityError., Inserting two members with the same name must raise IntegrityError., The check constraint preventing is_reserve=True with a member_id is defined., slot_count check constraints (1–3) are declared on the table., seed_post_conditions populates exactly 36 rows. (+6 more)
|
||||
|
||||
### Community 44 - "Community 44"
|
||||
Cohesion: 0.14
|
||||
Nodes (13): Schema-aware tests for Member.last_seen_changelog_at (issue #295, AC 1). These, Mapped type annotation allows a datetime value. Assigning a real datetime m, Member mapper exposes last_seen_changelog_at as a mapped attribute., last_seen_changelog_at column is defined nullable=True. Null is the sentine, last_seen_changelog_at has no server-side default. Null is the intentional, last_seen_changelog_at uses SQLAlchemy DateTime (no timezone). Matches the, Mapped type annotation allows None (datetime | None). Constructing a Member, test_last_seen_changelog_at_accepts_datetime_at_python_level() (+5 more)
|
||||
|
||||
### Community 45 - "Community 45"
|
||||
Cohesion: 0.23
|
||||
Nodes (13): add_building(), add_group(), delete_group(), deleteBuilding(), getBuildings(), updateBuilding(), _create_groups_and_positions(), _get_building_type_config() (+5 more)
|
||||
|
||||
### Community 46 - "Community 46"
|
||||
Cohesion: 0.2
|
||||
Nodes (11): _make_post_priority_config(), _make_post_ns(), _make_src_building_ns(), _make_src_group_ns(), _make_src_position_ns(), Endpoint tests for siege lifecycle transitions: activate, complete, clone., Cloning a siege with stale priority=0 posts must use PostPriorityConfig.priority, test_activate_planning_siege() (+3 more)
|
||||
|
||||
### Community 47 - "Community 47"
|
||||
Cohesion: 0.36
|
||||
Nodes (12): _make_bot(), _make_guild(), _make_text_channel(), Unit tests for SiegeBot Discord client methods using mock guild/member objects., Create a SiegeBot instance with a pre-loaded guild (bypasses Discord connect)., test_get_members_returns_correct_dict_format(), test_post_image_returns_cdn_url(), test_post_message_finds_channel_and_sends() (+4 more)
|
||||
|
||||
### Community 48 - "Community 48"
|
||||
Cohesion: 0.15
|
||||
Nodes (13): _make_worksheet(), Create a mock openpyxl worksheet that yields the given rows., Parses name, power_level bucket, and role from correct column positions., Column E is parsed as a slash-separated list of keyword strings., Empty or None column E results in an empty list., test_parse_members_sheet_basic(), test_parse_members_sheet_post_preferences(), test_parse_members_sheet_skips_empty_rows() (+5 more)
|
||||
|
||||
### Community 49 - "Community 49"
|
||||
Cohesion: 0.25
|
||||
Nodes (10): get_changelog_status(), markChangelogSeen(), Changelog status and mark-seen endpoints. These endpoints let the frontend trac, Raise HTTP 400 if the caller is a service principal. Args: current_, Return the authenticated user's last-seen changelog timestamp. Args:, Set the authenticated user's last-seen changelog timestamp to now. Idempote, _require_member_session(), ChangelogStatusResponse (+2 more)
|
||||
|
||||
### Community 50 - "Community 50"
|
||||
Cohesion: 0.18
|
||||
Nodes (9): health(), get_guild_member(), NotifyRequest, PostMessageRequest, Look up a single guild member by Discord user ID. Returns ``{"is_member": f, Validate the Bearer token against the configured bot API key., Health check — no authentication required., set_bot() (+1 more)
|
||||
|
||||
### Community 51 - "Community 51"
|
||||
Cohesion: 0.2
|
||||
Nodes (8): Exception, disable_auth_for_tests(), _FakeClient, _FakeHTTPException, _FakeNotFound, _FakeTextChannel, Shared pytest configuration for backend tests. Sets required environment variab, Bypass auth middleware for all tests by default. Individual tests that exer
|
||||
|
||||
### Community 52 - "Community 52"
|
||||
Cohesion: 0.33
|
||||
Nodes (9): MemberRole, SyncMatch, SyncPreviewResponse, PowerLevel, MemberBase, MemberCreate, MemberPreferencesUpdate, MemberResponse (+1 more)
|
||||
|
||||
### Community 53 - "Community 53"
|
||||
Cohesion: 0.24
|
||||
Nodes (9): _get_client_ip(), _parse_retry_after_seconds(), rate_limit_exceeded_handler(), _rate_limit_key(), Rate-limiting utilities shared across the application. This module owns the sin, Composite key function that honours the AUTH_DISABLED bypass. When ``AUTH_D, Parse a slowapi rate-limit detail string into a window size in seconds. slo, Return a JSON 429 response with a ``Retry-After`` header. Replaces slowapi' (+1 more)
|
||||
|
||||
### Community 54 - "Community 54"
|
||||
Cohesion: 0.24
|
||||
Nodes (9): _build_valid_siege_graph(), Integration test: full siege lifecycle — create → validate → assign → activate →, Build a siege with exactly the right building counts and assigned active members, Return a mock async session that serves the siege + configs across multiple exec, Happy-path: validate (errors) → assign → validate (0 errors) → activate → comple, test_full_siege_lifecycle(), _make_session(), Return a minimal AsyncSession mock that scalar_one_or_none returns siege. (+1 more)
|
||||
|
||||
### Community 55 - "Community 55"
|
||||
Cohesion: 0.2
|
||||
Nodes (10): _make_jwt(), A valid JWT session cookie with an existing member grants access., A JWT signed with a different secret is rejected with 401., A valid JWT whose member no longer exists in the DB returns 401., GET /api/auth/me returns member info when authenticated via session cookie., test_jwt_with_deleted_member_returns_401(), test_jwt_with_wrong_secret_returns_401(), test_me_with_valid_session() (+2 more)
|
||||
|
||||
### Community 56 - "Community 56"
|
||||
Cohesion: 0.22
|
||||
Nodes (10): _make_empty_worksheet(), _make_session_mock(), _make_workbook_mock(), Worksheet that yields no rows., Minimal openpyxl workbook mock. Members / Assignments / Reserves are empty, AsyncMock session whose execute() returns a result whose scalars().all() is []., When is_most_recent=False, section 3c must not run even if the Posts sheet p, When is_most_recent=True and the DB has no PostPriorityConfig rows yet, sect (+2 more)
|
||||
|
||||
### Community 57 - "Community 57"
|
||||
Cohesion: 0.32
|
||||
Nodes (6): get_member(), getMemberPreferences(), Return list of guild members as dicts with id, username, and display_name., Retrieve guild member list., Check guild membership via bot sidecar. Returns the member dict (includi, deactivate_member()
|
||||
|
||||
### Community 58 - "Community 58"
|
||||
Cohesion: 0.25
|
||||
Nodes (8): _make_assignments_worksheet(), Build a mock assignments worksheet with the proper two header rows prepended., Rows with a None group cell are skipped., Whitespace-only cell values normalise to None., test_parse_assignments_sheet_empty_value_is_none(), test_parse_assignments_sheet_member_assignment(), test_parse_assignments_sheet_skips_incomplete_rows(), test_parse_assignments_sheet_skips_unknown_building_type()
|
||||
|
||||
### Community 59 - "Community 59"
|
||||
Cohesion: 0.25
|
||||
Nodes (8): _make_posts_config_worksheet(), Create a mock worksheet for parse_posts_sheet_config. The function calls ws, One high-priority section with two posts: both get priority=3 and correct descri, Rows before any priority header default to priority=1 (Low)., Posts fall into the correct priority section based on their position., test_parse_posts_sheet_config_basic(), test_parse_posts_sheet_config_default_priority(), test_parse_posts_sheet_config_multiple_sections()
|
||||
|
||||
### Community 60 - "Community 60"
|
||||
Cohesion: 0.29
|
||||
Nodes (3): test_create_member_returns_201(), test_delete_member_returns_204(), Endpoint tests for /api/sieges — mocks the service layer directly.
|
||||
|
||||
### Community 61 - "Community 61"
|
||||
Cohesion: 0.4
|
||||
Nodes (5): notify(), Send a DM notification to a guild member., BotClient, HTTP client for the Discord bot sidecar API., Send DM via bot. Returns True on success, False on error.
|
||||
|
||||
### Community 63 - "Community 63"
|
||||
Cohesion: 0.33
|
||||
Nodes (5): Tests for enum definitions and associated constants in app.models.enums., BUILDING_TYPE_LABELS values must be non-empty title-cased display strings., Every BuildingType member must have an entry in BUILDING_TYPE_LABELS. This, test_building_type_labels_are_friendly_strings(), test_building_type_labels_covers_all_values()
|
||||
|
||||
### Community 64 - "Community 64"
|
||||
Cohesion: 0.33
|
||||
Nodes (6): _make_posts_conditions_worksheet(), Create a mock worksheet for parse_posts_sheet_conditions. The function enum, Three post rows with 1–3 keywords each are parsed correctly., A row with all-None cells is not included in the result., test_parse_posts_sheet_conditions_basic(), test_parse_posts_sheet_conditions_skips_empty()
|
||||
|
||||
### Community 65 - "Community 65"
|
||||
Cohesion: 0.4
|
||||
Nodes (3): _make_post_condition(), Endpoint tests for /api reference data endpoints., test_get_post_conditions_returns_list()
|
||||
|
||||
### Community 67 - "Community 67"
|
||||
Cohesion: 0.4
|
||||
Nodes (5): Mana shrine with 2 groups: position 3 is an empty trailing sheet column for grou, Stronghold level 2 = 16 total slots = 5 full groups (3 slots each) + 1 last grou, Stronghold level 4 = 22 total slots = 7 full groups + 1 last group with 1 slot., Defense Tower level 4 = 6 total slots = 2 full groups × 3 slots each. At lev, test_compute_building_group_structure_basic()
|
||||
|
||||
### Community 69 - "Community 69"
|
||||
Cohesion: 0.5
|
||||
Nodes (3): configure_telemetry(), Application Insights / OpenTelemetry initialisation for the backend. Call ``con, Initialise Azure Monitor OpenTelemetry and instrument the app. The ``azure-
|
||||
|
||||
### Community 71 - "Community 71"
|
||||
Cohesion: 0.5
|
||||
Nodes (4): Magic tower (base_last_slots=2): position 3 is a trailing empty sheet column and, Magic tower at a higher level where position 3 is genuinely filled: slot_cou, Magic Tower level 3 = 4 total slots = 1 full group (3 slots) + 1 last group with, test_compute_building_group_structure_magic_tower_level3()
|
||||
|
||||
### Community 72 - "Community 72"
|
||||
Cohesion: 0.67
|
||||
Nodes (3): Mana Shrine level 2 = 7 total slots = 2 full groups + 1 last group with 1 slot., Mana Shrine level 4 = 11 total slots = 3 full groups + 1 last group with 2 slots, test_compute_building_group_structure_mana_shrine_level2()
|
||||
|
||||
### Community 73 - "Community 73"
|
||||
Cohesion: 0.67
|
||||
Nodes (3): Returns None for a filename that does not match the pattern., Returns None for a completely unrelated filename., test_parse_filename_invalid_random()
|
||||
|
||||
## Knowledge Gaps
|
||||
- **752 isolated node(s):** `initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`, `add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`, `make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1`, `Add post_priority_config table`, `Add description to post_priority_config` (+747 more)
|
||||
These have ≤1 connection - possible missing edges or undocumented components.
|
||||
- **52 thin communities (<3 nodes) omitted from report** — run `graphify query` to explore isolated nodes.
|
||||
|
||||
## Suggested Questions
|
||||
_Questions this graph is uniquely positioned to answer:_
|
||||
|
||||
- **Why does `_make_siege()` connect `Community 12` to `Community 0`, `Community 1`, `Community 3`, `Community 36`, `Community 6`, `Community 11`, `Community 46`, `Community 20`, `Community 54`, `Community 22`, `Community 25`, `Community 30`?**
|
||||
_High betweenness centrality (0.183) - this node is a cross-community bridge._
|
||||
- **Why does `SiegeMember` connect `Community 3` to `Community 1`, `Community 34`, `Community 35`, `Community 36`, `Community 6`, `Community 38`, `Community 8`, `Community 7`, `Community 42`, `Community 12`, `Community 14`, `Community 15`, `Community 16`, `Community 22`, `Community 24`, `Community 57`?**
|
||||
_High betweenness centrality (0.167) - this node is a cross-community bridge._
|
||||
- **Why does `list` connect `Community 42` to `Community 0`, `Community 1`, `Community 56`, `Community 5`, `Community 6`, `Community 39`, `Community 38`, `Community 45`, `Community 13`, `Community 15`, `Community 21`, `Community 24`, `Community 57`, `Community 58`?**
|
||||
_High betweenness centrality (0.089) - this node is a cross-community bridge._
|
||||
- **Are the 17 inferred relationships involving `SiegeMember` (e.g. with `Base` and `TestSeedDemoMembers`) actually correct?**
|
||||
_`SiegeMember` has 17 INFERRED edges - model-reasoned connections that need verification._
|
||||
- **What connects `initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`, `add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`, `make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1` to the rest of the system?**
|
||||
_752 weakly-connected nodes found - possible documentation gaps or missing edges._
|
||||
- **Should `Community 0` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.05 - nodes in this community are weakly interconnected._
|
||||
- **Should `Community 1` be split into smaller, more focused modules?**
|
||||
_Cohesion score 0.05 - nodes in this community are weakly interconnected._
|
||||
@@ -0,0 +1,88 @@
|
||||
# Case Study: rsl-siege-manager (Python + TypeScript monorepo)
|
||||
|
||||
A graphify dry-run against [`glitchwerks/rsl-siege-manager`](https://github.com/glitchwerks/rsl-siege-manager) — a real-world web app with a Python (FastAPI) backend, a TypeScript (React + Vite) frontend, and a Python Discord bot, all in one repo. Captured here as a worked example of running graphify on a mixed-language full-stack codebase that includes a substantial test suite.
|
||||
|
||||
**Corpus:** `glitchwerks/rsl-siege-manager` @ commit `6085fd66`
|
||||
**Date:** 2026-05-15
|
||||
**Findings:** [`review.md`](./review.md)
|
||||
**Raw artifacts:** [`GRAPH_REPORT.md`](./GRAPH_REPORT.md), [`graph.html`](./graph.html), [`graph.json`](./graph.json), [`manifest.json`](./manifest.json)
|
||||
|
||||
## How to reproduce
|
||||
|
||||
### 1. Clone the corpus
|
||||
|
||||
```bash
|
||||
git clone https://github.com/glitchwerks/rsl-siege-manager
|
||||
cd rsl-siege-manager
|
||||
git checkout 6085fd66
|
||||
```
|
||||
|
||||
### 2. Install the CLI
|
||||
|
||||
```powershell
|
||||
uv tool install graphifyy
|
||||
```
|
||||
|
||||
> The PyPI package is `graphifyy` (double-y). The CLI command is `graphify`.
|
||||
|
||||
Verify it's on PATH:
|
||||
|
||||
```powershell
|
||||
graphify --version
|
||||
```
|
||||
|
||||
If "not recognized" on Windows, open a new shell — `uv tool` updates PATH but the current session won't see it.
|
||||
|
||||
### 3. Run extraction
|
||||
|
||||
This case study ran extraction with no `.graphifyignore` (the run included tests). To reproduce a tests-included run:
|
||||
|
||||
```powershell
|
||||
graphify extract .
|
||||
```
|
||||
|
||||
Watch terminal output. graphify uses tree-sitter for code (free, fast) and LLM API calls only for non-code files (markdown, PDFs, images). On a code-heavy repo like rsl-siege-manager, the cost is dominated by docs.
|
||||
|
||||
Check the cost summary when it finishes:
|
||||
|
||||
```powershell
|
||||
Get-Content .\graphify-out\cost.json
|
||||
```
|
||||
|
||||
### 4. Inspect
|
||||
|
||||
```powershell
|
||||
# The headline summary an assistant would read
|
||||
code .\graphify-out\GRAPH_REPORT.md
|
||||
|
||||
# The interactive graph
|
||||
Start-Process .\graphify-out\graph.html
|
||||
```
|
||||
|
||||
## What's in this directory
|
||||
|
||||
| File | What it is |
|
||||
|---|---|
|
||||
| `README.md` | This file — corpus description + reproduction steps |
|
||||
| `review.md` | Findings against the headline outputs in `GRAPH_REPORT.md` |
|
||||
| `GRAPH_REPORT.md` | Raw graphify report (god nodes, communities, surprising connections, suggested questions) |
|
||||
| `graph.html` | Interactive force-directed visualization |
|
||||
| `graph.json` | Underlying graph data used by `graphify query` |
|
||||
| `manifest.json` | Per-file extraction record |
|
||||
|
||||
The AST cache (`graphify-out/cache/`) is regenerable and not committed.
|
||||
|
||||
## Why this corpus
|
||||
|
||||
rsl-siege-manager is structurally interesting for graphify evaluation because:
|
||||
|
||||
- **Three services in one repo** — Python backend, TypeScript frontend, Python bot — exercises cross-language inference.
|
||||
- **Substantial test suite** — both Python (`backend/tests/`) and TypeScript (`frontend/src/**/__tests__/`) — surfaces how degree-centrality behaves on covered codebases.
|
||||
- **17 Alembic migrations** with revision docstrings — exercises how docstring-shaped content is or is not treated as graph entities.
|
||||
- **Clean three-tier architecture** — a developer can describe the structure in one sentence, giving a clear ground truth to evaluate community detection against.
|
||||
|
||||
## Reference
|
||||
|
||||
- graphify repo: https://github.com/safishamsi/graphify
|
||||
- graphify PyPI: https://pypi.org/project/graphifyy/
|
||||
- rsl-siege-manager: https://github.com/glitchwerks/rsl-siege-manager
|
||||
@@ -0,0 +1,305 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="en">
|
||||
<head>
|
||||
<meta charset="UTF-8">
|
||||
<title>graphify - graphify-out\graph.html</title>
|
||||
<script src="https://unpkg.com/vis-network/standalone/umd/vis-network.min.js"></script>
|
||||
<style>
|
||||
* { box-sizing: border-box; margin: 0; padding: 0; }
|
||||
body { background: #0f0f1a; color: #e0e0e0; font-family: -apple-system, BlinkMacSystemFont, "Segoe UI", sans-serif; display: flex; height: 100vh; overflow: hidden; }
|
||||
#graph { flex: 1; }
|
||||
#sidebar { width: 280px; background: #1a1a2e; border-left: 1px solid #2a2a4e; display: flex; flex-direction: column; overflow: hidden; }
|
||||
#search-wrap { padding: 12px; border-bottom: 1px solid #2a2a4e; }
|
||||
#search { width: 100%; background: #0f0f1a; border: 1px solid #3a3a5e; color: #e0e0e0; padding: 7px 10px; border-radius: 6px; font-size: 13px; outline: none; }
|
||||
#search:focus { border-color: #4E79A7; }
|
||||
#search-results { max-height: 140px; overflow-y: auto; padding: 4px 12px; border-bottom: 1px solid #2a2a4e; display: none; }
|
||||
.search-item { padding: 4px 6px; cursor: pointer; border-radius: 4px; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; }
|
||||
.search-item:hover { background: #2a2a4e; }
|
||||
#info-panel { padding: 14px; border-bottom: 1px solid #2a2a4e; min-height: 140px; }
|
||||
#info-panel h3 { font-size: 13px; color: #aaa; margin-bottom: 8px; text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
#info-content { font-size: 13px; color: #ccc; line-height: 1.6; }
|
||||
#info-content .field { margin-bottom: 5px; }
|
||||
#info-content .field b { color: #e0e0e0; }
|
||||
#info-content .empty { color: #555; font-style: italic; }
|
||||
.neighbor-link { display: block; padding: 2px 6px; margin: 2px 0; border-radius: 3px; cursor: pointer; font-size: 12px; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; border-left: 3px solid #333; }
|
||||
.neighbor-link:hover { background: #2a2a4e; }
|
||||
#neighbors-list { max-height: 160px; overflow-y: auto; margin-top: 4px; }
|
||||
#legend-wrap { flex: 1; overflow-y: auto; padding: 12px; }
|
||||
#legend-wrap h3 { font-size: 13px; color: #aaa; margin-bottom: 10px; text-transform: uppercase; letter-spacing: 0.05em; }
|
||||
.legend-item { display: flex; align-items: center; gap: 8px; padding: 4px 0; cursor: pointer; border-radius: 4px; font-size: 12px; }
|
||||
.legend-item:hover { background: #2a2a4e; padding-left: 4px; }
|
||||
.legend-item.dimmed { opacity: 0.35; }
|
||||
.legend-dot { width: 12px; height: 12px; border-radius: 50%; flex-shrink: 0; }
|
||||
.legend-label { flex: 1; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; }
|
||||
.legend-count { color: #666; font-size: 11px; }
|
||||
#stats { padding: 10px 14px; border-top: 1px solid #2a2a4e; font-size: 11px; color: #555; }
|
||||
#legend-controls { display: flex; align-items: center; gap: 8px; margin-bottom: 8px; padding: 4px 0; }
|
||||
#legend-controls label { display: flex; align-items: center; gap: 6px; cursor: pointer; font-size: 12px; color: #aaa; user-select: none; }
|
||||
#legend-controls label:hover { color: #e0e0e0; }
|
||||
.legend-cb, #select-all-cb { appearance: none; -webkit-appearance: none; width: 14px; height: 14px; border: 1.5px solid #3a3a5e; border-radius: 3px; background: #0f0f1a; cursor: pointer; position: relative; flex-shrink: 0; }
|
||||
.legend-cb:checked, #select-all-cb:checked { background: #4E79A7; border-color: #4E79A7; }
|
||||
.legend-cb:checked::after, #select-all-cb:checked::after { content: ''; position: absolute; left: 3.5px; top: 1px; width: 4px; height: 7px; border: solid #fff; border-width: 0 2px 2px 0; transform: rotate(45deg); }
|
||||
#select-all-cb:indeterminate { background: #4E79A7; border-color: #4E79A7; }
|
||||
#select-all-cb:indeterminate::after { content: ''; position: absolute; left: 2px; top: 5px; width: 8px; height: 2px; background: #fff; border: none; transform: none; }
|
||||
</style>
|
||||
</head>
|
||||
<body>
|
||||
<div id="graph"></div>
|
||||
<div id="sidebar">
|
||||
<div id="search-wrap">
|
||||
<input id="search" type="text" placeholder="Search nodes..." autocomplete="off">
|
||||
<div id="search-results"></div>
|
||||
</div>
|
||||
<div id="info-panel">
|
||||
<h3>Node Info</h3>
|
||||
<div id="info-content"><span class="empty">Click a node to inspect it</span></div>
|
||||
</div>
|
||||
<div id="legend-wrap">
|
||||
<h3>Communities</h3>
|
||||
<div id="legend-controls">
|
||||
<label><input type="checkbox" id="select-all-cb" checked onchange="toggleAllCommunities(!this.checked)">Select All</label>
|
||||
</div>
|
||||
<div id="legend"></div>
|
||||
</div>
|
||||
<div id="stats">1886 nodes · 3876 edges · 141 communities</div>
|
||||
</div>
|
||||
<script>
|
||||
const RAW_NODES = [{"id": "backend_alembic_env_py", "label": "env.py", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 11.0, "font": {"size": 0, "color": "#ffffff"}, "title": "env.py", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 4}, {"id": "alembic_env_run_migrations_offline", "label": "run_migrations_offline()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "run_migrations_offline()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 1}, {"id": "alembic_env_do_run_migrations", "label": "do_run_migrations()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "do_run_migrations()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 1}, {"id": "alembic_env_run_async_migrations", "label": "run_async_migrations()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.5, "font": {"size": 0, "color": "#ffffff"}, "title": "run_async_migrations()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 2}, {"id": "alembic_env_run_migrations_online", "label": "run_migrations_online()", "color": {"background": "#B07AA1", "border": "#B07AA1", "highlight": {"background": "#ffffff", "border": "#B07AA1"}}, "size": 10.5, "font": {"size": 0, "color": "#ffffff"}, "title": "run_migrations_online()", "community": 66, "community_name": "Community 66", "source_file": "backend/alembic/env.py", "file_type": "code", "degree": 2}, {"id": "backend_alembic_versions_0001_initial_schema_py", "label": "0001_initial_schema.py", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.7, "font": {"size": 0, "color": "#ffffff"}, "title": "0001_initial_schema.py", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 3}, {"id": "versions_0001_initial_schema_upgrade", "label": "upgrade()", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 13.1, "font": {"size": 0, "color": "#ffffff"}, "title": "upgrade()", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 13}, {"id": "versions_0001_initial_schema_downgrade", "label": "downgrade()", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 13.1, "font": {"size": 0, "color": "#ffffff"}, "title": "downgrade()", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "code", "degree": 13}, {"id": "versions_0001_initial_schema_rationale_1", "label": "initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0001_initial_schema.py", "file_type": "rationale", "degree": 1}, {"id": "backend_alembic_versions_0002_add_preview_columns_py", "label": "0002_add_preview_columns.py", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.7, "font": {"size": 0, "color": "#ffffff"}, "title": "0002_add_preview_columns.py", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0002_add_preview_columns.py", "file_type": "code", "degree": 3}, {"id": "versions_0002_add_preview_columns_rationale_1", "label": "add autofill and attack day preview columns to siege Revision ID: 0002 Revises:", "color": {"background": "#76B7B2", "border": "#76B7B2", "highlight": {"background": "#ffffff", "border": "#76B7B2"}}, "size": 10.2, "font": {"size": 0, "color": "#ffffff"}, "title": "add autofill and attack day preview columns to siege Revision ID: 0002 Revises:", "community": 23, "community_name": "Community 23", "source_file": "backend/alembic/versions/0002_add_preview_columns.py", "file_type": "rationale", "degree": 1}, {"id": "backend_alembic_versions_0003_make_siege_date_nullable_py", "label"Line truncated
|
||||
const RAW_EDGES = [{"from": "backend_alembic_env_py", "to": "alembic_env_run_migrations_offline", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_do_run_migrations", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_run_async_migrations", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_env_py", "to": "alembic_env_run_migrations_online", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "alembic_env_run_migrations_online", "to": "alembic_env_run_async_migrations", "label": "calls", "title": "calls [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0001_initial_schema_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0001_initial_schema_py", "to": "versions_0001_initial_schema_downgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0001_initial_schema_rationale_1", "to": "backend_alembic_versions_0001_initial_schema_py", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0002_add_preview_columns_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0003_make_siege_date_nullable_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0004_add_post_priority_config_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0005_add_description_to_post_priority_config_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0006_power_level_and_drop_sort_value_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0007_fix_group_number_max_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0008_add_matched_condition_id_to_position_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0009_add_discord_id_to_member_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0010_add_last_seen_changelog_at_to_member_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0010_add_last_seen_changelog_at_to_member_rationale_25", "to": "versions_0001_initial_schema_upgrade", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0011_add_post_suggest_preview_py", "to": "versions_0001_initial_schema_upgrade", "label": "contains", "title": "contains [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "versions_0011_add_post_suggest_preview_rationale_23", "to": "versions_0001_initial_schema_upgrade", "label": "rationale_for", "title": "rationale_for [EXTRACTED]", "dashes": false, "width": 2, "color": {"opacity": 0.7}, "confidence": "EXTRACTED"}, {"from": "backend_alembic_versions_0002_add_preLine truncated
|
||||
const LEGEND = [{"cid": 0, "color": "#4E79A7", "label": "Community 0", "count": 87}, {"cid": 1, "color": "#F28E2B", "label": "Community 1", "count": 66}, {"cid": 2, "color": "#E15759", "label": "Community 2", "count": 63}, {"cid": 3, "color": "#76B7B2", "label": "Community 3", "count": 62}, {"cid": 4, "color": "#59A14F", "label": "Community 4", "count": 62}, {"cid": 5, "color": "#EDC948", "label": "Community 5", "count": 60}, {"cid": 6, "color": "#B07AA1", "label": "Community 6", "count": 55}, {"cid": 7, "color": "#FF9DA7", "label": "Community 7", "count": 51}, {"cid": 8, "color": "#9C755F", "label": "Community 8", "count": 51}, {"cid": 9, "color": "#BAB0AC", "label": "Community 9", "count": 50}, {"cid": 10, "color": "#4E79A7", "label": "Community 10", "count": 49}, {"cid": 11, "color": "#F28E2B", "label": "Community 11", "count": 47}, {"cid": 12, "color": "#E15759", "label": "Community 12", "count": 45}, {"cid": 13, "color": "#76B7B2", "label": "Community 13", "count": 45}, {"cid": 14, "color": "#59A14F", "label": "Community 14", "count": 40}, {"cid": 15, "color": "#EDC948", "label": "Community 15", "count": 40}, {"cid": 16, "color": "#B07AA1", "label": "Community 16", "count": 40}, {"cid": 17, "color": "#FF9DA7", "label": "Community 17", "count": 39}, {"cid": 18, "color": "#9C755F", "label": "Community 18", "count": 38}, {"cid": 19, "color": "#BAB0AC", "label": "Community 19", "count": 37}, {"cid": 20, "color": "#4E79A7", "label": "Community 20", "count": 35}, {"cid": 21, "color": "#F28E2B", "label": "Community 21", "count": 32}, {"cid": 22, "color": "#E15759", "label": "Community 22", "count": 28}, {"cid": 23, "color": "#76B7B2", "label": "Community 23", "count": 28}, {"cid": 24, "color": "#59A14F", "label": "Community 24", "count": 26}, {"cid": 25, "color": "#EDC948", "label": "Community 25", "count": 26}, {"cid": 26, "color": "#B07AA1", "label": "Community 26", "count": 25}, {"cid": 27, "color": "#FF9DA7", "label": "Community 27", "count": 23}, {"cid": 28, "color": "#9C755F", "label": "Community 28", "count": 23}, {"cid": 29, "color": "#BAB0AC", "label": "Community 29", "count": 23}, {"cid": 30, "color": "#4E79A7", "label": "Community 30", "count": 22}, {"cid": 31, "color": "#F28E2B", "label": "Community 31", "count": 22}, {"cid": 32, "color": "#E15759", "label": "Community 32", "count": 21}, {"cid": 33, "color": "#76B7B2", "label": "Community 33", "count": 21}, {"cid": 34, "color": "#59A14F", "label": "Community 34", "count": 20}, {"cid": 35, "color": "#EDC948", "label": "Community 35", "count": 19}, {"cid": 36, "color": "#B07AA1", "label": "Community 36", "count": 18}, {"cid": 37, "color": "#FF9DA7", "label": "Community 37", "count": 17}, {"cid": 38, "color": "#9C755F", "label": "Community 38", "count": 17}, {"cid": 39, "color": "#BAB0AC", "label": "Community 39", "count": 16}, {"cid": 40, "color": "#4E79A7", "label": "Community 40", "count": 15}, {"cid": 41, "color": "#F28E2B", "label": "Community 41", "count": 15}, {"cid": 42, "color": "#E15759", "label": "Community 42", "count": 15}, {"cid": 43, "color": "#76B7B2", "label": "Community 43", "count": 15}, {"cid": 44, "color": "#59A14F", "label": "Community 44", "count": 14}, {"cid": 45, "color": "#EDC948", "label": "Community 45", "count": 14}, {"cid": 46, "color": "#B07AA1", "label": "Community 46", "count": 14}, {"cid": 47, "color": "#FF9DA7", "label": "Community 47", "count": 13}, {"cid": 48, "color": "#9C755F", "label": "Community 48", "count": 13}, {"cid": 49, "color": "#BAB0AC", "label": "Community 49", "count": 11}, {"cid": 50, "color": "#4E79A7", "label": "Community 50", "count": 11}, {"cid": 51, "color": "#F28E2B", "label": "Community 51", "count": 11}, {"cid": 52, "color": "#E15759", "label": "Community 52", "count": 11}, {"cid": 53, "color": "#76B7B2", "label": "Community 53", "count": 10}, {"cid": 54, "color": "#59A14F", "label": "Community 54", "count": 10}, {"cid": 55, "color": "#EDC948", "label": "Community 55", "count": 10}, {"cid": 56, "color": "#B07AA1", "label": "Community 56", "count": 10}, {"cid": 57, "color": "#FF9DA7", "label": "Community 57", "count": 8}, {"cid": 58, "color": "#9C755F", "label": "Community 58", "count": 8}, {"cid": 59, "color": "#BAB0AC", "label": "Community 59", "count": 8}, {"cid": 60, "color": "#4E79A7", "label": "Community 60", "count": 7}, {"cid": 61, "color": "#F28E2B", "label": "Community 61", "count": 6}, {"cid": 62, "color": "#E15759", "label": "Community 62", "count": 6}, {"cid": 63, "color": "#76B7B2", "label": "Community 63", "count": 6}, {"cid": 64, "color": "#59A14F", "label": "Community 64", "count": 6}, {"cid": 65, "color": "#EDC948", "label": "Community 65", "count": 6}, {"cid": 66, "color": "#B07AA1", "label": "Community 66", "count": 5}, {"cid": 67, "color": "#FF9DA7", "label": "Community 67", "count": 5}, {"cid": 68, "color": "#9C755F", "label": "Community 68", "count": 4}, {"cid": 69, "color": "#BAB0AC", "label": "Community 69", "count": 4}, {"cid": 70, "color": "#4E79A7", "label": "CommLine truncated
|
||||
|
||||
// HTML-escape helper — prevents XSS when injecting graph data into innerHTML
|
||||
function esc(s) {
|
||||
return String(s).replace(/&/g,'&').replace(/</g,'<').replace(/>/g,'>').replace(/"/g,'"').replace(/'/g,''');
|
||||
}
|
||||
|
||||
// Build vis datasets
|
||||
const nodesDS = new vis.DataSet(RAW_NODES.map(n => ({
|
||||
id: n.id, label: n.label, color: n.color, size: n.size,
|
||||
font: n.font, title: n.title,
|
||||
_community: n.community, _community_name: n.community_name,
|
||||
_source_file: n.source_file, _file_type: n.file_type, _degree: n.degree,
|
||||
})));
|
||||
|
||||
const edgesDS = new vis.DataSet(RAW_EDGES.map((e, i) => ({
|
||||
id: i, from: e.from, to: e.to,
|
||||
label: '',
|
||||
title: e.title,
|
||||
dashes: e.dashes,
|
||||
width: e.width,
|
||||
color: e.color,
|
||||
arrows: { to: { enabled: true, scaleFactor: 0.5 } },
|
||||
})));
|
||||
|
||||
const container = document.getElementById('graph');
|
||||
const network = new vis.Network(container, { nodes: nodesDS, edges: edgesDS }, {
|
||||
physics: {
|
||||
enabled: true,
|
||||
solver: 'forceAtlas2Based',
|
||||
forceAtlas2Based: {
|
||||
gravitationalConstant: -60,
|
||||
centralGravity: 0.005,
|
||||
springLength: 120,
|
||||
springConstant: 0.08,
|
||||
damping: 0.4,
|
||||
avoidOverlap: 0.8,
|
||||
},
|
||||
stabilization: { iterations: 200, fit: true },
|
||||
},
|
||||
interaction: {
|
||||
hover: true,
|
||||
tooltipDelay: 100,
|
||||
hideEdgesOnDrag: true,
|
||||
navigationButtons: false,
|
||||
keyboard: false,
|
||||
},
|
||||
nodes: { shape: 'dot', borderWidth: 1.5 },
|
||||
edges: { smooth: { type: 'continuous', roundness: 0.2 }, selectionWidth: 3 },
|
||||
});
|
||||
|
||||
network.once('stabilizationIterationsDone', () => {
|
||||
network.setOptions({ physics: { enabled: false } });
|
||||
});
|
||||
|
||||
function showInfo(nodeId) {
|
||||
const n = nodesDS.get(nodeId);
|
||||
if (!n) return;
|
||||
const neighborIds = network.getConnectedNodes(nodeId);
|
||||
const neighborItems = neighborIds.map(nid => {
|
||||
const nb = nodesDS.get(nid);
|
||||
const color = nb ? nb.color.background : '#555';
|
||||
return `<span class="neighbor-link" style="border-left-color:${esc(color)}" onclick="focusNode(${JSON.stringify(nid)})">${esc(nb ? nb.label : nid)}</span>`;
|
||||
}).join('');
|
||||
document.getElementById('info-content').innerHTML = `
|
||||
<div class="field"><b>${esc(n.label)}</b></div>
|
||||
<div class="field">Type: ${esc(n._file_type || 'unknown')}</div>
|
||||
<div class="field">Community: ${esc(n._community_name)}</div>
|
||||
<div class="field">Source: ${esc(n._source_file || '-')}</div>
|
||||
<div class="field">Degree: ${n._degree}</div>
|
||||
${neighborIds.length ? `<div class="field" style="margin-top:8px;color:#aaa;font-size:11px">Neighbors (${neighborIds.length})</div><div id="neighbors-list">${neighborItems}</div>` : ''}
|
||||
`;
|
||||
}
|
||||
|
||||
function focusNode(nodeId) {
|
||||
network.focus(nodeId, { scale: 1.4, animation: true });
|
||||
network.selectNodes([nodeId]);
|
||||
showInfo(nodeId);
|
||||
}
|
||||
|
||||
// Track hovered node — hover detection is more reliable than click params
|
||||
let hoveredNodeId = null;
|
||||
network.on('hoverNode', params => {
|
||||
hoveredNodeId = params.node;
|
||||
container.style.cursor = 'pointer';
|
||||
});
|
||||
network.on('blurNode', () => {
|
||||
hoveredNodeId = null;
|
||||
container.style.cursor = 'default';
|
||||
});
|
||||
container.addEventListener('click', () => {
|
||||
if (hoveredNodeId !== null) {
|
||||
showInfo(hoveredNodeId);
|
||||
network.selectNodes([hoveredNodeId]);
|
||||
}
|
||||
});
|
||||
network.on('click', params => {
|
||||
if (params.nodes.length > 0) {
|
||||
showInfo(params.nodes[0]);
|
||||
} else if (hoveredNodeId === null) {
|
||||
document.getElementById('info-content').innerHTML = '<span class="empty">Click a node to inspect it</span>';
|
||||
}
|
||||
});
|
||||
|
||||
const searchInput = document.getElementById('search');
|
||||
const searchResults = document.getElementById('search-results');
|
||||
searchInput.addEventListener('input', () => {
|
||||
const q = searchInput.value.toLowerCase().trim();
|
||||
searchResults.innerHTML = '';
|
||||
if (!q) { searchResults.style.display = 'none'; return; }
|
||||
const matches = RAW_NODES.filter(n => n.label.toLowerCase().includes(q)).slice(0, 20);
|
||||
if (!matches.length) { searchResults.style.display = 'none'; return; }
|
||||
searchResults.style.display = 'block';
|
||||
matches.forEach(n => {
|
||||
const el = document.createElement('div');
|
||||
el.className = 'search-item';
|
||||
el.textContent = n.label;
|
||||
el.style.borderLeft = `3px solid ${n.color.background}`;
|
||||
el.style.paddingLeft = '8px';
|
||||
el.onclick = () => {
|
||||
network.focus(n.id, { scale: 1.5, animation: true });
|
||||
network.selectNodes([n.id]);
|
||||
showInfo(n.id);
|
||||
searchResults.style.display = 'none';
|
||||
searchInput.value = '';
|
||||
};
|
||||
searchResults.appendChild(el);
|
||||
});
|
||||
});
|
||||
document.addEventListener('click', e => {
|
||||
if (!searchResults.contains(e.target) && e.target !== searchInput)
|
||||
searchResults.style.display = 'none';
|
||||
});
|
||||
|
||||
const hiddenCommunities = new Set();
|
||||
|
||||
const selectAllCb = document.getElementById('select-all-cb');
|
||||
|
||||
function updateSelectAllState() {
|
||||
const total = LEGEND.length;
|
||||
const hidden = hiddenCommunities.size;
|
||||
selectAllCb.checked = hidden === 0;
|
||||
selectAllCb.indeterminate = hidden > 0 && hidden < total;
|
||||
}
|
||||
|
||||
function toggleAllCommunities(hide) {
|
||||
document.querySelectorAll('.legend-item').forEach(item => {
|
||||
hide ? item.classList.add('dimmed') : item.classList.remove('dimmed');
|
||||
});
|
||||
document.querySelectorAll('.legend-cb').forEach(cb => {
|
||||
cb.checked = !hide;
|
||||
});
|
||||
LEGEND.forEach(c => {
|
||||
if (hide) hiddenCommunities.add(c.cid); else hiddenCommunities.delete(c.cid);
|
||||
});
|
||||
const updates = RAW_NODES.map(n => ({ id: n.id, hidden: hide }));
|
||||
nodesDS.update(updates);
|
||||
updateSelectAllState();
|
||||
}
|
||||
|
||||
const legendEl = document.getElementById('legend');
|
||||
LEGEND.forEach(c => {
|
||||
const item = document.createElement('div');
|
||||
item.className = 'legend-item';
|
||||
const cb = document.createElement('input');
|
||||
cb.type = 'checkbox';
|
||||
cb.className = 'legend-cb';
|
||||
cb.checked = true;
|
||||
cb.addEventListener('change', (e) => {
|
||||
e.stopPropagation();
|
||||
if (cb.checked) {
|
||||
hiddenCommunities.delete(c.cid);
|
||||
item.classList.remove('dimmed');
|
||||
} else {
|
||||
hiddenCommunities.add(c.cid);
|
||||
item.classList.add('dimmed');
|
||||
}
|
||||
const updates = RAW_NODES
|
||||
.filter(n => n.community === c.cid)
|
||||
.map(n => ({ id: n.id, hidden: !cb.checked }));
|
||||
nodesDS.update(updates);
|
||||
updateSelectAllState();
|
||||
});
|
||||
item.innerHTML = `<div class="legend-dot" style="background:${c.color}"></div>
|
||||
<span class="legend-label">${c.label}</span>
|
||||
<span class="legend-count">${c.count}</span>`;
|
||||
item.prepend(cb);
|
||||
item.onclick = (e) => {
|
||||
if (e.target === cb) return;
|
||||
cb.checked = !cb.checked;
|
||||
cb.dispatchEvent(new Event('change'));
|
||||
};
|
||||
legendEl.appendChild(item);
|
||||
});
|
||||
</script>
|
||||
<script>
|
||||
// Render hyperedges as shaded regions
|
||||
const hyperedges = [];
|
||||
// afterDrawing passes ctx already transformed to network coordinate space.
|
||||
// Draw node positions raw — no manual pan/zoom/DPR math needed.
|
||||
network.on('afterDrawing', function(ctx) {
|
||||
hyperedges.forEach(h => {
|
||||
const positions = h.nodes
|
||||
.map(nid => network.getPositions([nid])[nid])
|
||||
.filter(p => p !== undefined);
|
||||
if (positions.length < 2) return;
|
||||
ctx.save();
|
||||
ctx.globalAlpha = 0.12;
|
||||
ctx.fillStyle = '#6366f1';
|
||||
ctx.strokeStyle = '#6366f1';
|
||||
ctx.lineWidth = 2;
|
||||
ctx.beginPath();
|
||||
// Centroid and expanded hull in network coordinates
|
||||
const cx = positions.reduce((s, p) => s + p.x, 0) / positions.length;
|
||||
const cy = positions.reduce((s, p) => s + p.y, 0) / positions.length;
|
||||
const expanded = positions.map(p => ({
|
||||
x: cx + (p.x - cx) * 1.15,
|
||||
y: cy + (p.y - cy) * 1.15
|
||||
}));
|
||||
ctx.moveTo(expanded[0].x, expanded[0].y);
|
||||
expanded.slice(1).forEach(p => ctx.lineTo(p.x, p.y));
|
||||
ctx.closePath();
|
||||
ctx.fill();
|
||||
ctx.globalAlpha = 0.4;
|
||||
ctx.stroke();
|
||||
// Label
|
||||
ctx.globalAlpha = 0.8;
|
||||
ctx.fillStyle = '#4f46e5';
|
||||
ctx.font = 'bold 11px sans-serif';
|
||||
ctx.textAlign = 'center';
|
||||
ctx.fillText(h.label, cx, cy - 5);
|
||||
ctx.restore();
|
||||
});
|
||||
});
|
||||
</script>
|
||||
</body>
|
||||
</html>
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -0,0 +1,154 @@
|
||||
# Review: rsl-siege-manager
|
||||
|
||||
**Corpus:** [`glitchwerks/rsl-siege-manager`](https://github.com/glitchwerks/rsl-siege-manager) @ `6085fd66`
|
||||
**Date:** 2026-05-15
|
||||
**Run:** tests included, no `.graphifyignore`
|
||||
**Counts:** 1886 nodes · 3876 edges · 141 communities · 90% EXTRACTED / 10% INFERRED (avg INFERRED confidence 0.62)
|
||||
**Cost:** $0 (tree-sitter only; this corpus's natural file mix surfaced no non-code files in meaningful quantity)
|
||||
**Setup:** ~10 minutes of CLI time end-to-end
|
||||
|
||||
This review evaluates the **headline outputs** in `GRAPH_REPORT.md` — god nodes, surprising connections, communities, isolated nodes, suggested questions — against a single criterion: do they reflect things a developer familiar with this codebase would themselves nominate as core, surprising, or worth investigating? Each finding quotes the report directly so it is verifiable against the committed artifacts.
|
||||
|
||||
---
|
||||
|
||||
## Finding 1 — Test fixtures dominate "core abstractions" when tests are included
|
||||
|
||||
Top god nodes, verbatim from `GRAPH_REPORT.md` (lines 141–150):
|
||||
|
||||
```
|
||||
1. `_make_siege()` - 124 edges
|
||||
2. `_make_member()` - 92 edges
|
||||
3. `_make_position()` - 85 edges
|
||||
4. `SiegeMember` - 78 edges
|
||||
5. `_make_building()` - 64 edges
|
||||
6. `_make_group()` - 60 edges
|
||||
7. `BoardPage()` - 55 edges
|
||||
8. `makeSiegeMember()` - 55 edges
|
||||
9. `PostsPage()` - 37 edges
|
||||
10. `_session_with_siege_and_configs()` - 35 edges
|
||||
```
|
||||
|
||||
Six of the top ten — positions 1, 2, 3, 5, 6, and 8 — are test factory functions (`_make_siege`, `_make_member`, `_make_position`, `_make_building`, `_make_group`, `makeSiegeMember`). Position 10 is a test session fixture. These are the highest-connectivity nodes in the graph, and they are infrastructure for verifying the codebase, not the codebase itself.
|
||||
|
||||
The god-node list is labeled "your core abstractions" in the report. On this corpus, no developer would nominate `_make_siege()` as a core abstraction of a siege-assignment web app. Degree centrality on a well-tested codebase will tend to surface test factories: by design, factories create the primary domain objects that every test then exercises, so they accumulate edges from every part of the suite. The pattern is structural — the better the test coverage, the more saturated the factory's degree count.
|
||||
|
||||
For users running graphify on a codebase with substantial test coverage, the documented mitigation (a `.graphifyignore` excluding `tests/`, `__tests__/`, etc.) is effective at removing this class of false-positive. See Finding 2 for what the same corpus surfaces without tests.
|
||||
|
||||
## Finding 2 — Without tests, god nodes mix domain types with entry points and utilities
|
||||
|
||||
For comparison, an earlier run of the same corpus with `.graphifyignore` excluding `backend/tests/` and `frontend/src/**/__tests__/` produced this god-node list:
|
||||
|
||||
```
|
||||
1. `SiegeMember` - 55 edges
|
||||
2. `BoardPage()` - 53 edges
|
||||
3. `Post Suggestions Modal Handoff` - 40 edges
|
||||
4. `postsTab` - 29 edges
|
||||
5. `cn()` - 29 edges
|
||||
6. `PostsPage()` - 28 edges
|
||||
7. `BuildingType` - 27 edges
|
||||
8. `MembersPage()` - 27 edges
|
||||
9. `MemberRole` - 25 edges
|
||||
10. `Self-Host on Azure Wiki Page` - 23 edges
|
||||
```
|
||||
|
||||
(That run's artifacts are not committed here — only the tests-included artifacts are kept — but the list is reproducible by re-running with the same `.graphifyignore`.)
|
||||
|
||||
Three of ten — `SiegeMember`, `BuildingType`, `MemberRole` (positions 1, 7, 9) — are legitimate domain models a developer would identify.
|
||||
|
||||
The other seven illustrate a second pattern worth knowing about:
|
||||
|
||||
- **React top-level page components** (`BoardPage`, `PostsPage`, `MembersPage` at 2, 6, 8) — these import many things because they are entry points, not because they encode domain logic.
|
||||
- **Class-merge utilities** — `cn()` (position 5) is a one-line Tailwind class-merging utility (`src/lib/utils.ts`). It scores 29 edges because every component that conditionally combines classes imports it. The connection count reflects a structural pattern (the React+Tailwind idiom), not semantic importance.
|
||||
- **Document/wiki entities** — `Post Suggestions Modal Handoff` (position 3) is a planning document under `docs/design-refs/`; `Self-Host on Azure Wiki Page` (position 10) is a wiki article. Both are extracted as nodes alongside code entities and sort by edge count the same way.
|
||||
|
||||
This is informative for users tuning expectations: degree centrality on a React frontend with a shared `cn()` utility will surface that utility regardless of how aggressive the ignore filter is, because the connections are real even though the semantic importance is low.
|
||||
|
||||
## Finding 3 — Surprising connections cross language boundaries
|
||||
|
||||
Both runs surface INFERRED edges between Python backend types and TypeScript frontend types under "Surprising Connections (you probably didn't know these)." Examples:
|
||||
|
||||
```
|
||||
- `AuthError` --uses--> `Member` [INFERRED]
|
||||
backend/app/api/auth.py → frontend/src/api/types.ts
|
||||
```
|
||||
|
||||
```
|
||||
- `TestStartupValidation` --uses--> `MemberRole` [INFERRED]
|
||||
backend/tests/test_auth.py → frontend/src/api/types.ts
|
||||
```
|
||||
|
||||
A Python class does not "use" a TypeScript type at runtime. These are name-based similarity matches between identically-named constructs in two languages, surfaced as semantic relationships. The confidence values are flagged as INFERRED (avg 0.62 on this run), but the section header presents them as insights worth investigating.
|
||||
|
||||
The one cross-language INFERRED edge in this run that maps to a real design contract is:
|
||||
|
||||
```
|
||||
- `PostPriorityResponse` --uses--> `PostPriorityConfig` [INFERRED]
|
||||
backend/app/api/post_priority_config.py → frontend/src/api/posts.ts
|
||||
```
|
||||
|
||||
The backend Pydantic schema and the frontend TypeScript type do mirror each other intentionally — this is the API contract. That relationship is real, but a developer who wrote either side already knows about it; INFERRED detection here recovers a fact rather than discovering one.
|
||||
|
||||
For corpora that mix Python and TypeScript with overlapping type names (common in monorepos with shared domain vocabulary), users should expect a high false-positive rate in this section and read it with the INFERRED confidence in mind.
|
||||
|
||||
## Finding 4 — Community cohesion is uniformly low on this corpus
|
||||
|
||||
Most of rsl-siege-manager's 141 communities (tests-included run) score between 0.05 and 0.17 on cohesion. The report itself flags 0.05 as "weakly interconnected" in the Suggested Questions section:
|
||||
|
||||
> "Should `Community 0` be split into smaller, more focused modules? — Cohesion score 0.05 - nodes in this community are weakly interconnected."
|
||||
|
||||
Community 0 has 112 nodes on this corpus.
|
||||
|
||||
rsl-siege-manager has a clean three-service architecture (backend / frontend / bot). The community-detection pass does not recover that structure as three large cohesive communities; it produces many small communities with low internal cohesion. Possible interpretations: the underlying graph has many INFERRED cross-language edges diluting the cluster signal, the chosen algorithm parameters favor over-segmentation on graphs of this density, or this corpus genuinely lacks tight intra-cluster topology that community detection can exploit.
|
||||
|
||||
A neutral framing for users: community cohesion is informative on this corpus mainly as a signal that the graph topology does not match the obvious three-tier mental model — which itself may be useful (it surfaces that the cross-language edges are doing the work). The "split this community" prompts the report generates from low cohesion scores are less actionable as direct architectural advice on this corpus.
|
||||
|
||||
## Finding 5 — Alembic migration docstrings surface as isolated nodes
|
||||
|
||||
The tests-included run reports 752 isolated nodes; the without-tests run reports 259. The leading examples are identical in both:
|
||||
|
||||
```
|
||||
`initial schema Revision ID: 0001 Revises: Create Date: 2026-03-16`,
|
||||
`add autofill and attack day preview columns to siege Revision ID: 0002 Revises:`,
|
||||
`make siege date nullable Revision ID: 0003 Revises: 0002 Create Date: 2026-03-1`,
|
||||
`Add post_priority_config table`, ...
|
||||
```
|
||||
|
||||
These are Alembic migration revision docstrings parsed as standalone graph nodes. There are 17 migration files in this corpus. The isolated-node count growing from 259 to 752 when tests are added is dominated by test docstrings parsed the same way.
|
||||
|
||||
The report labels these as "possible documentation gaps or missing edges." For users with corpora that contain Alembic migrations, pytest docstrings, or other docstring-heavy auto-generated files, this label can be misleading — these are change annotations or test descriptions, not architectural entities with missing connections.
|
||||
|
||||
A `.graphifyignore` rule for `**/alembic/versions/*.py` reduces the isolated-node count materially on this corpus; users with similar setups may want a default recipe.
|
||||
|
||||
## Finding 6 — Suggested questions skew toward graph-property prompts
|
||||
|
||||
The Suggested Questions section consists primarily of two kinds of questions:
|
||||
|
||||
1. **Betweenness centrality prompts:** "Why does `_make_siege()` connect Community 12 to Community 0, Community 1, Community 3...?" The answer on this corpus is direct: `_make_siege()` creates the primary domain object, every test that touches a siege uses it, and the test suite spans the codebase — so the fixture is a betweenness bridge by construction.
|
||||
|
||||
2. **Inferred-edge audits:** "Are the 17 inferred relationships involving `SiegeMember` (e.g. with `Base` and `TestSeedDemoMembers`) actually correct?" These ask the developer to validate the tool's own low-confidence connections.
|
||||
|
||||
A genuinely concrete question in this section — "What is the exact relationship between `bootstrap-images.ps1` and `scripts/bootstrap-images.ps1`?" — is tagged AMBIGUOUS by the report. The answer is concrete (they are the same script referenced by two slightly different paths), but it is a file-naming observation, not an architectural insight.
|
||||
|
||||
For users hoping the Suggested Questions section will surface domain-level prompts ("how does authentication flow?", "what enforces the siege-day invariant?"), this corpus's section is dominated by graph-property meta-questions.
|
||||
|
||||
---
|
||||
|
||||
## What worked well on this corpus
|
||||
|
||||
- **Throughput:** 1886 nodes extracted in a few minutes at $0 cost. tree-sitter handles all 29 supported languages locally; LLM calls fire only for non-code files.
|
||||
- **Genuine domain extractions are present:** `SiegeMember`, `BuildingType`, and `MemberRole` in the god-node list are correct. `PostPriorityResponse --uses--> PostPriorityConfig` is a real API contract that INFERRED detection picked up across the Python/TypeScript boundary.
|
||||
- **`graph.html` visualization:** clear, navigable, easy to filter and search. Useful for browsing communities even when the labelled cohesion scores are low.
|
||||
|
||||
The underlying graph build is solid. The findings above are about how the report layer summarizes that graph into headline metrics — specifically, what those metrics surface on a well-tested cross-language full-stack web app.
|
||||
|
||||
---
|
||||
|
||||
## Suggested follow-ups
|
||||
|
||||
Patterns from this review that may be worth tracking upstream:
|
||||
|
||||
1. **Test-fixture suppression** — degree centrality on covered codebases consistently surfaces test factories; documenting the ignore-pattern recipe in a "first run on a codebase with tests" section would shorten the iteration loop for users.
|
||||
2. **Cross-language INFERRED edges in monorepos** — name-based matches between Python and TypeScript types in mixed-language repos may warrant a higher confidence threshold or a "potential contract" label rather than the current "surprising connection" framing.
|
||||
3. **Docstring-heavy files (Alembic, pytest)** — defaulting to skip migration `versions/` directories, or detecting and grouping docstring nodes that share a structural pattern, would reduce the isolated-node noise materially.
|
||||
|
||||
These are observations, not change requests — users running graphify on similar corpora may find the same patterns useful to know about.
|
||||
Reference in new issue
Block a user