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 | ||
|
|
258d2600cd | ||
|
|
c4c2205658 | ||
|
|
53da14333e | ||
|
|
822abd6e69 | ||
|
|
7bb0919c72 | ||
|
|
d0e09aa89d | ||
|
|
c0048d0a61 | ||
|
|
5f9ea2b80e | ||
|
|
ab32098063 | ||
|
|
994b17be46 | ||
|
|
2db5d966f2 | ||
|
|
28fc71eddc | ||
|
|
ef0e6ee681 | ||
|
|
8e4c803f31 | ||
|
|
094d8ba731 | ||
|
|
dd465afd2c | ||
|
|
95e2c5eb32 | ||
|
|
4cec58e072 | ||
|
|
9caaa17f7f | ||
|
|
8c4c67f3ad | ||
|
|
5ead190891 | ||
|
|
db66b8727b | ||
|
|
8c00287e84 | ||
|
|
e926079c0a |
No files matched your search
@@ -21,6 +21,7 @@ Each stage is a single function in its own module. They communicate through plai
|
||||
| `analyze.py` | `analyze(G)` | graph → analysis dict (god nodes, surprises, questions) |
|
||||
| `report.py` | `render_report(G, analysis)` | graph + analysis → GRAPH_REPORT.md string |
|
||||
| `export.py` | `export(G, out_dir, ...)` | graph → Obsidian vault, graph.json, graph.html, graph.svg |
|
||||
| `callflow_html.py` | `write_callflow_html(...)` | graphify-out files → Mermaid architecture/call-flow HTML |
|
||||
| `ingest.py` | `ingest(url, ...)` | URL → file saved to corpus dir |
|
||||
| `cache.py` | `check_semantic_cache / save_semantic_cache` | files → (cached, uncached) split |
|
||||
| `security.py` | validation helpers | URL / path / label → validated or raises |
|
||||
|
||||
@@ -2,6 +2,79 @@
|
||||
|
||||
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)
|
||||
- Fix: MCP `shortest_path` and `get_neighbors` tools had the same reversed-arrow bug; now fixed in `serve.py` alongside the CLI commands (#849, #853)
|
||||
- Fix: `graphify extract --backend bedrock` was rejected by the CLI guard even when `AWS_PROFILE`/`AWS_REGION`/`AWS_DEFAULT_REGION`/`AWS_ACCESS_KEY_ID` were set — boto3 session auth was never reached (#846)
|
||||
- Fix: BFS/DFS query traversal now skips expanding high-degree hub nodes (threshold: `max(50, p99_degree)`) as transit — hubs can still be destinations but no longer produce semantically meaningless 2-hop paths like `ClassA → View → ClassB` in Android/Spring corpora (#830)
|
||||
- Fix: `--update` manifest shrink — after an incremental run, `manifest.json` was overwritten with only the changed-file subset, causing the next `--update` to re-flag the entire unchanged corpus as new; Step 9 now persists the full corpus via `all_files` fallback (#837)
|
||||
- Fix: `file_type` enum aligned across `skill.md` and `llm.py` (both now enumerate all six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`); synonym mapper in `build.py` silently coerces known LLM-emitted synonyms (`pattern→concept`, `markdown→document`, `tool→code`, etc.) before validation (#840)
|
||||
- Fix: Fortran test fixture renamed `sample.F90` → `sample_preprocessed.F90` to avoid case-collision with `sample.f90` on macOS case-insensitive filesystems (credit: @FatahChan, #823)
|
||||
|
||||
## 0.7.16 (2026-05-12)
|
||||
|
||||
- Fix: all `read_text()`/`write_text()` calls in `skill.md` and `skill-windows.md` now specify `encoding="utf-8"` — bare calls defaulted to the system codepage on Chinese-locale Windows, silently mojibaking node labels and Markdown content on `--update` (#832)
|
||||
- Fix: `json.dumps` in skill pipeline now uses `ensure_ascii=False` so Chinese/CJK characters are stored as-is rather than `\uXXXX` escaped (#832)
|
||||
- Fix: Step 1 install fallback in skill now prefers `uv tool install --upgrade graphifyy` over `pip` when uv is on PATH — pip was installing to the wrong environment when graphify was originally installed via `uv tool` (#831)
|
||||
- Fix: `_score_nodes` in `serve.py` now uses three-tier precedence (exact 1000 / prefix 100 / substring 1) instead of flat substring scoring — `graphify path "Foo" "FooBar"` no longer returns 0 hops when both labels substring-match the same node (#828)
|
||||
- Fix: `graphify path` and MCP `_tool_shortest_path` now emit a clear error when source and target resolve to the same node, instead of silently returning 0 hops (#828)
|
||||
- Fix: `file_hash` in `cache.py` now normalises path keys via `.as_posix().lower()` — Windows junction/case variants of the same file now hash identically, fixing `save_semantic_cache` always reporting "Cached 0 files" on subsequent `--update` runs (#826)
|
||||
- Fix: `check_semantic_cache` now applies the same absolute-path normalization as `save_semantic_cache` so relative `source_file` paths resolve consistently on both sides (#826)
|
||||
- Fix: `_AGENTS_MD_SECTION` now includes the `/graphify` skill trigger instruction — all 7 AGENTS.md platforms (OpenCode, Codex, Aider, Trae, Hermes, OpenClaw, Factory Droid) now correctly invoke the skill tool when the user types `/graphify` (#827)
|
||||
|
||||
## 0.7.15 (2026-05-11)
|
||||
|
||||
- Fix: `-h`/`--help`/`-?` in any position now stops execution — previously `graphify cursor install --help` silently installed into Cursor; `graphify benchmark --help` crashed with FileNotFoundError (#821)
|
||||
- Fix: `--version`, `-v`, and `graphify version` now print the installed version and exit (#818)
|
||||
- Fix: `GRAPHIFY_OLLAMA_NUM_CTX=<invalid>` no longer falls back to hardcoded 131072 (which exhausted VRAM) — it now falls through to the auto-derived value and prints a warning (#820)
|
||||
- Fix: when `GRAPHIFY_OLLAMA_NUM_CTX` is set smaller than the estimated chunk size, graphify now warns explicitly that Ollama will silently truncate the prompt and suggests a corrected `--token-budget` (#820)
|
||||
|
||||
## 0.7.14 (2026-05-11)
|
||||
|
||||
- Fix: `_make_id` and `_normalize_id` now apply NFKC Unicode normalization before ID generation -- composed/decomposed forms of the same character (e.g. `é` typed vs pasted from a PDF) now produce the same node ID; switched from `.lower()` to `.casefold()` for correct Turkish/German/Greek case folding; both functions are now byte-for-byte equivalent (#811)
|
||||
- Fix: non-ASCII identifiers (CJK, Cyrillic, Arabic, accented Latin) are no longer collapsed to a bare file stem -- `[^\w]+` with `re.UNICODE` replaces the old `[^a-zA-Z0-9]+` so Unicode word chars are preserved as part of the ID (#811)
|
||||
- Fix: dedup edge remap uses explicit key-presence check instead of `or` so empty-string `source` is not silently swapped for `from`; stale `from`/`to` keys are now popped before the edge is emitted so they can't leak into `graph.json` edge attributes (#803)
|
||||
- Fix: `--update` merge now calls `build_merge()` directly instead of an inline NetworkX round-trip that re-introduced the direction-flip bug from #760; dict merge ordering fixed so explicit `source`/`target` always win over stale attrs; hyperedges pulled from `G.graph` (merged) rather than just the new extraction (#801)
|
||||
- Fix: subagent chunk files are now written to an absolute path (`CHUNK_PATH` injected at dispatch time from `graphify-out/.graphify_root`) so the Write tool doesn't lose chunks to an undefined working directory (#808)
|
||||
- Fix: skill version mismatch warning is now suppressed during `hook-check` (runs on every editor tool use and must be silent) and routed to stderr for all other commands
|
||||
|
||||
## 0.7.13 (2026-05-09)
|
||||
|
||||
- Fix: Ollama `num_ctx` now derived from actual chunk size instead of hardcoded 131072 -- over-allocating 128k KV-cache slots for small chunks exhausted VRAM by chunk 4 on large models; formula is `min(input_tokens + output_cap + 2000, 131072)` so `--token-budget 8192` gets ~26k instead of 131072 (#798)
|
||||
- Fix: hollow-response warning now mentions VRAM pressure and `GRAPHIFY_OLLAMA_NUM_CTX` / `GRAPHIFY_OLLAMA_KEEP_ALIVE` env vars as tuning knobs (#798)
|
||||
- Feat: `graphify export callflow-html` -- generates a self-contained Mermaid architecture/call-flow HTML page from `graphify-out/graph.json`, grouped by community with interactive zoom/pan diagrams, call detail tables, and graph report highlights (#797)
|
||||
- Feat: callflow HTML auto-regenerates on every `--watch` rebuild and post-commit hook if the file already exists -- opt-in by existence, zero config (#800)
|
||||
|
||||
## 0.7.12 (2026-05-09)
|
||||
|
||||
- Fix: `graphify explain` and `graphify path` no longer crash on `MultiGraph` inputs -- new `edge_data()`/`edge_datas()` helpers in `build.py` handle both simple and multi-graphs; all 8 production call sites and 30 skill-file inline heredocs updated (#796)
|
||||
- Fix: hollow Ollama responses (0 tokens / empty string) now trigger adaptive retry bisection instead of silently dropping the chunk -- `_response_is_hollow()` detects empty/null/whitespace content and parsed results with no nodes/edges, then rewrites `finish_reason="length"` to route into the existing bisection path (#792)
|
||||
- Fix: post-commit hook no longer spawns unbounded parallel rebuilds -- per-repo `fcntl.flock` non-blocking lock in `_rebuild_code`; `changed_paths` wired from hook through to AST extractor; stale nodes evicted on deletion; `GRAPHIFY_REBUILD_TIMEOUT` watchdog; Darwin-aware memory cap (#791)
|
||||
- Fix: Antigravity install now writes to `.agents/` (plural) -- corrected in platform config, paths, workflow body, and help text (#453)
|
||||
- Fix: Antigravity rules file now includes `trigger: always_on` YAML frontmatter so Antigravity recognises it (#785)
|
||||
- Feat: `graphify extract` gains `--max-workers`, `--token-budget`, `--max-concurrency`, `--api-timeout` flags; hard 8-worker AST cap removed; explicit HTTP timeout on OpenAI client (default 600s, `GRAPHIFY_API_TIMEOUT`); ollama API key gate skipped for loopback URLs (#792)
|
||||
- Feat: Pascal/Delphi extraction now works without `tree-sitter-pascal` -- regex fallback covers unit/program/library headers, uses clauses, class/interface inheritance, method declarations, and intra-file calls (#781)
|
||||
- Feat: `/graphify --help` now prints the Usage block and stops without running pipeline steps (all 12 skill files) (#795)
|
||||
|
||||
## 0.7.11 (2026-05-09)
|
||||
|
||||
- Fix: context-window-exceeded API errors now trigger automatic retry with bisected file chunks -- exponential bisection up to 6 levels deep; covers `"context_length_exceeded"`, `"maximum context length"`, and `"too_large"` across OpenAI-compat backends (#789)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<a href="https://safishamsi.gumroad.com/l/qetvlo"><img src="https://img.shields.io/badge/Book-The%20Memory%20Layer-2ea44f?style=flat&logo=gitbook&logoColor=white" alt="The Memory Layer"/></a>
|
||||
<a href="https://github.com/safishamsi/graphify/actions/workflows/ci.yml"><img src="https://github.com/safishamsi/graphify/actions/workflows/ci.yml/badge.svg?branch=v7" alt="CI"/></a>
|
||||
<a href="https://pypi.org/project/graphifyy/"><img src="https://img.shields.io/pypi/v/graphifyy" alt="PyPI"/></a>
|
||||
<a href="https://pepy.tech/project/graphifyy"><img src="https://static.pepy.tech/badge/graphifyy" alt="Downloads"/></a>
|
||||
<a href="https://clickpy.clickhouse.com/dashboard/graphifyy"><img src="https://img.shields.io/badge/dynamic/json?url=https%3A%2F%2Fsql-clickhouse.clickhouse.com%2F%3Fquery%3DSELECT%2520concat%2528toString%2528round%2528sum%2528count%2529%2F1000%2529%2529%2C%2520%2527k%2527%2529%2520AS%2520c%2520FROM%2520pypi.pypi_downloads%2520WHERE%2520project%253D%2527graphifyy%2527%2520FORMAT%2520JSON%26user%3Ddemo&query=%24.data%5B0%5D.c&label=downloads&color=blue" alt="Downloads"/></a>
|
||||
<a href="https://github.com/sponsors/safishamsi"><img src="https://img.shields.io/badge/sponsor-safishamsi-ea4aaa?logo=github-sponsors" alt="Sponsor"/></a>
|
||||
<a href="https://www.linkedin.com/in/safi-shamsi"><img src="https://img.shields.io/badge/LinkedIn-Safi%20Shamsi-0077B5?logo=linkedin" alt="LinkedIn"/></a>
|
||||
<a href="https://x.com/graphifyy"><img src="https://img.shields.io/badge/X-graphifyy-000000?logo=x&logoColor=white" alt="X"/></a>
|
||||
@@ -39,21 +39,65 @@ graphify-out/
|
||||
└── graph.json the full graph — query it anytime without re-reading your files
|
||||
```
|
||||
|
||||
For a readable architecture page with Mermaid call-flow diagrams, run:
|
||||
|
||||
```bash
|
||||
graphify export callflow-html
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## Prerequisites
|
||||
|
||||
| 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
|
||||
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
|
||||
|
||||
**Requires Python 3.10+**
|
||||
|
||||
```bash
|
||||
uv tool install graphifyy && graphify install
|
||||
# or: pipx install graphifyy && graphify install
|
||||
# or: pip install graphifyy && graphify 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`.
|
||||
|
||||
@@ -83,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
|
||||
@@ -129,7 +194,7 @@ To remove graphify from all platforms at once: `graphify uninstall` (add `--purg
|
||||
|
||||
| Type | Extensions |
|
||||
|------|-----------|
|
||||
| Code (28 languages) | `.py .ts .js .jsx .tsx .go .rs .java .c .cpp .rb .cs .kt .scala .php .swift .lua .luau .zig .ps1 .ex .exs .m .jl .vue .svelte .groovy .gradle .sql .f .F .f90 .F90 .f95 .F95 .f03 .F03 .f08 .F08` |
|
||||
| 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]`) |
|
||||
@@ -164,6 +229,7 @@ You can also set `GRAPHIFY_GOOGLE_WORKSPACE=1`. Graphify exports shortcuts into
|
||||
/graphify . --cluster-only # rerun clustering without re-extracting
|
||||
/graphify . --no-viz # skip the HTML, just the report + JSON
|
||||
/graphify . --wiki # build a markdown wiki from the graph
|
||||
graphify export callflow-html # architecture/call-flow HTML from graphify-out/
|
||||
|
||||
/graphify query "what connects auth to the database?"
|
||||
/graphify path "UserService" "DatabasePool"
|
||||
@@ -240,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
|
||||
|
||||
```
|
||||
@@ -300,16 +443,29 @@ 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)
|
||||
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
|
||||
|
||||
graphify export callflow-html # graphify-out/<project>-callflow.html
|
||||
graphify export callflow-html --max-sections 8 # cap generated architecture sections
|
||||
graphify export callflow-html --output docs/arch.html
|
||||
graphify export callflow-html ./some-repo/graphify-out
|
||||
|
||||
graphify global add graphify-out/graph.json myrepo # register a project graph into ~/.graphify/global.json
|
||||
graphify global remove myrepo # remove a project from the global graph
|
||||
graphify global list # show all registered repos + node/edge counts
|
||||
@@ -317,9 +473,12 @@ graphify global path # print path to the global
|
||||
|
||||
graphify clone https://github.com/karpathy/nanoGPT
|
||||
graphify merge-graphs a.json b.json --out merged.json
|
||||
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
|
||||
```
|
||||
@@ -347,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.
|
||||
|
||||
+203
-27
@@ -33,7 +33,7 @@ def _check_skill_version(skill_dst: Path) -> None:
|
||||
return
|
||||
installed = version_file.read_text(encoding="utf-8").strip()
|
||||
if installed != __version__:
|
||||
print(f" warning: skill is from graphify {installed}, package is {__version__}. Run 'graphify install' to update.")
|
||||
print(f" warning: skill is from graphify {installed}, package is {__version__}. Run 'graphify install' to update.", file=sys.stderr)
|
||||
|
||||
|
||||
def _refresh_all_version_stamps() -> None:
|
||||
@@ -254,6 +254,8 @@ _AGENTS_MD_SECTION = """\
|
||||
|
||||
This project has a knowledge graph at graphify-out/ with god nodes, community structure, and cross-file relationships.
|
||||
|
||||
When the user types `/graphify`, invoke the `skill` tool with `skill: "graphify"` before doing anything else.
|
||||
|
||||
Rules:
|
||||
- ALWAYS read graphify-out/GRAPH_REPORT.md before reading any source files, running grep/glob searches, or answering codebase questions. The graph is your primary map of the codebase.
|
||||
- IF graphify-out/wiki/index.md EXISTS, navigate it instead of reading raw files
|
||||
@@ -1115,12 +1117,18 @@ def _clone_repo(url: str, branch: str | None = None, out_dir: Path | None = None
|
||||
def main() -> None:
|
||||
# Check all known skill install locations for a stale version stamp.
|
||||
# Skip during install/uninstall (hook writes trigger a fresh check anyway).
|
||||
# Skip during hook-check — it runs on every editor tool use and must be silent.
|
||||
# Deduplicate paths so platforms sharing the same install dir don't warn twice.
|
||||
if not any(arg in ("install", "uninstall") for arg in sys.argv):
|
||||
_silent_cmds = {"install", "uninstall", "hook-check"}
|
||||
if not any(arg in _silent_cmds for arg in sys.argv):
|
||||
for skill_dst in {Path.home() / cfg["skill_dst"] for cfg in _PLATFORM_CONFIG.values()}:
|
||||
_check_skill_version(skill_dst)
|
||||
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help"):
|
||||
if len(sys.argv) >= 2 and sys.argv[1] in ("-v", "--version", "version"):
|
||||
print(f"graphify {__version__}")
|
||||
return
|
||||
|
||||
if len(sys.argv) < 2 or sys.argv[1] in ("-h", "--help", "-?"):
|
||||
print("Usage: graphify <command>")
|
||||
print()
|
||||
print("Commands:")
|
||||
@@ -1145,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)")
|
||||
@@ -1185,6 +1194,7 @@ def main() -> None:
|
||||
print(" global list list repos in the global graph")
|
||||
print(" global path print path to the global graph file")
|
||||
print(" benchmark [graph.json] measure token reduction vs naive full-corpus approach")
|
||||
print(" export callflow-html emit Mermaid-based architecture/call-flow HTML")
|
||||
print(" hook install install post-commit/post-checkout git hooks (all platforms)")
|
||||
print(" hook uninstall remove git hooks")
|
||||
print(" hook status check if git hooks are installed")
|
||||
@@ -1224,6 +1234,17 @@ def main() -> None:
|
||||
return
|
||||
|
||||
cmd = sys.argv[1]
|
||||
|
||||
# Universal help guard: -h/--help/-? anywhere after the command shows help
|
||||
# and stops — prevents flags from silently triggering destructive subcommands
|
||||
# (e.g. "cursor install --help" was silently installing into Cursor, #821).
|
||||
# Exempt: free-text commands (user string may contain these tokens), and
|
||||
# "install"/"uninstall" which have their own per-subcommand help handlers.
|
||||
_FREE_TEXT_CMDS = {"query", "explain", "path", "save-result", "install", "uninstall"}
|
||||
if cmd not in _FREE_TEXT_CMDS and any(a in {"-h", "--help", "-?"} for a in sys.argv[2:]):
|
||||
print(f"Run 'graphify --help' for full usage.")
|
||||
return
|
||||
|
||||
if cmd == "install":
|
||||
# Default to windows platform on Windows, claude elsewhere
|
||||
default_platform = "windows" if platform.system() == "Windows" else "claude"
|
||||
@@ -1494,6 +1515,8 @@ def main() -> None:
|
||||
_raw = json.loads(gp.read_text(encoding="utf-8"))
|
||||
if "links" not in _raw and "edges" in _raw:
|
||||
_raw = dict(_raw, links=_raw["edges"])
|
||||
# Force directed so the renderer can recover stored caller→callee direction.
|
||||
_raw = {**_raw, "directed": True}
|
||||
try:
|
||||
G = json_graph.node_link_graph(_raw, edges="links")
|
||||
except TypeError:
|
||||
@@ -1507,8 +1530,27 @@ def main() -> None:
|
||||
print(f"No node matching '{target_label}' found.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
|
||||
# Ambiguity guard: when both queries resolve to the same node, the
|
||||
# shortest path is trivially zero hops, which is almost never what the
|
||||
# caller wanted (see bug #828).
|
||||
if src_nid == tgt_nid:
|
||||
print(
|
||||
f"'{source_label}' and '{target_label}' both resolved to the same "
|
||||
f"node '{src_nid}'. Use a more specific label or the exact node ID.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
for _name, _scored in (("source", src_scored), ("target", tgt_scored)):
|
||||
if len(_scored) >= 2:
|
||||
_top, _runner = _scored[0][0], _scored[1][0]
|
||||
if _top > 0 and (_top - _runner) / _top < 0.10:
|
||||
print(
|
||||
f"warning: {_name} match was ambiguous "
|
||||
f"(top score {_top:g}, runner-up {_runner:g})",
|
||||
file=sys.stderr,
|
||||
)
|
||||
try:
|
||||
path_nodes = _nx.shortest_path(G, src_nid, tgt_nid)
|
||||
path_nodes = _nx.shortest_path(G.to_undirected(as_view=True), src_nid, tgt_nid)
|
||||
except (_nx.NetworkXNoPath, _nx.NodeNotFound):
|
||||
print(f"No path found between '{source_label}' and '{target_label}'.")
|
||||
sys.exit(0)
|
||||
@@ -1517,13 +1559,22 @@ def main() -> None:
|
||||
from graphify.build import edge_data
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
edata = edge_data(G, u, v)
|
||||
# Check which direction the stored edge points.
|
||||
if G.has_edge(u, v):
|
||||
edata = edge_data(G, u, v)
|
||||
forward = True
|
||||
else:
|
||||
edata = edge_data(G, v, u)
|
||||
forward = False
|
||||
rel = edata.get("relation", "")
|
||||
conf = edata.get("confidence", "")
|
||||
conf_str = f" [{conf}]" if conf else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
|
||||
if forward:
|
||||
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
|
||||
else:
|
||||
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
|
||||
print(f"Shortest path ({hops} hops):\n " + " ".join(segments))
|
||||
|
||||
elif cmd == "explain":
|
||||
@@ -1545,6 +1596,8 @@ def main() -> None:
|
||||
_raw = json.loads(gp.read_text(encoding="utf-8"))
|
||||
if "links" not in _raw and "edges" in _raw:
|
||||
_raw = dict(_raw, links=_raw["edges"])
|
||||
# Force directed so the renderer can recover stored caller→callee direction.
|
||||
_raw = {**_raw, "directed": True}
|
||||
try:
|
||||
G = json_graph.node_link_graph(_raw, edges="links")
|
||||
except TypeError:
|
||||
@@ -1561,17 +1614,22 @@ def main() -> None:
|
||||
print(f" Type: {d.get('file_type', '')}")
|
||||
print(f" Community: {d.get('community', '')}")
|
||||
print(f" Degree: {G.degree(nid)}")
|
||||
neighbors = list(G.neighbors(nid))
|
||||
if neighbors:
|
||||
from graphify.build import edge_data
|
||||
print(f"\nConnections ({len(neighbors)}):")
|
||||
for nb in sorted(neighbors, key=lambda n: G.degree(n), reverse=True)[:20]:
|
||||
edata = edge_data(G, nid, nb)
|
||||
from graphify.build import edge_data
|
||||
connections: list[tuple[str, str, dict]] = [] # (direction, neighbor_id, edge_data)
|
||||
for nb in G.successors(nid):
|
||||
connections.append(("out", nb, edge_data(G, nid, nb)))
|
||||
for nb in G.predecessors(nid):
|
||||
connections.append(("in", nb, edge_data(G, nb, nid)))
|
||||
if connections:
|
||||
print(f"\nConnections ({len(connections)}):")
|
||||
connections.sort(key=lambda c: G.degree(c[1]), reverse=True)
|
||||
for direction, nb, edata in connections[:20]:
|
||||
rel = edata.get("relation", "")
|
||||
conf = edata.get("confidence", "")
|
||||
print(f" --> {G.nodes[nb].get('label', nb)} [{rel}] [{conf}]")
|
||||
if len(neighbors) > 20:
|
||||
print(f" ... and {len(neighbors) - 20} more")
|
||||
arrow = "-->" if direction == "out" else "<--"
|
||||
print(f" {arrow} {G.nodes[nb].get('label', nb)} [{rel}] [{conf}]")
|
||||
if len(connections) > 20:
|
||||
print(f" ... and {len(connections) - 20} more")
|
||||
|
||||
elif cmd == "add":
|
||||
if len(sys.argv) < 3:
|
||||
@@ -1699,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"
|
||||
@@ -1720,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 (
|
||||
@@ -1923,9 +1995,11 @@ def main() -> None:
|
||||
|
||||
elif cmd == "export":
|
||||
subcmd = sys.argv[2] if len(sys.argv) > 2 else ""
|
||||
if subcmd not in ("html", "obsidian", "wiki", "svg", "graphml", "neo4j"):
|
||||
if subcmd not in ("html", "callflow-html", "obsidian", "wiki", "svg", "graphml", "neo4j"):
|
||||
print("Usage: graphify export <format>", file=sys.stderr)
|
||||
print(" html [--graph PATH] [--labels PATH] [--node-limit N] [--no-viz]", file=sys.stderr)
|
||||
print(" callflow-html [GRAPH|DIR] [--graph PATH] [--labels PATH] [--report PATH] [--sections PATH] [--output HTML]", file=sys.stderr)
|
||||
print(" [--lang auto|zh-CN|en] [--max-sections N] [--diagram-scale N]", file=sys.stderr)
|
||||
print(" obsidian [--graph PATH] [--labels PATH] [--dir PATH]", file=sys.stderr)
|
||||
print(" wiki [--graph PATH] [--labels PATH]", file=sys.stderr)
|
||||
print(" svg [--graph PATH] [--labels PATH]", file=sys.stderr)
|
||||
@@ -1937,7 +2011,18 @@ def main() -> None:
|
||||
# Parse shared args
|
||||
args = sys.argv[3:]
|
||||
graph_path = Path(_GRAPHIFY_OUT) / "graph.json"
|
||||
graph_path_explicit = False
|
||||
labels_path = Path(_GRAPHIFY_OUT) / ".graphify_labels.json"
|
||||
labels_path_explicit = False
|
||||
report_path = Path(_GRAPHIFY_OUT) / "GRAPH_REPORT.md"
|
||||
report_path_explicit = False
|
||||
sections_path: Path | None = None
|
||||
callflow_output: Path | None = None
|
||||
callflow_lang = "auto"
|
||||
callflow_max_sections = 15
|
||||
callflow_diagram_scale = 1.0
|
||||
callflow_max_diagram_nodes = 18
|
||||
callflow_max_diagram_edges = 24
|
||||
analysis_path = Path(_GRAPHIFY_OUT) / ".graphify_analysis.json"
|
||||
node_limit = 5000
|
||||
no_viz = False
|
||||
@@ -1952,9 +2037,45 @@ def main() -> None:
|
||||
while i < len(args):
|
||||
a = args[i]
|
||||
if a == "--graph" and i + 1 < len(args):
|
||||
graph_path = Path(args[i + 1]); i += 2
|
||||
graph_path = Path(args[i + 1])
|
||||
graph_path_explicit = True
|
||||
i += 2
|
||||
elif a == "--labels" and i + 1 < len(args):
|
||||
labels_path = Path(args[i + 1]); i += 2
|
||||
labels_path = Path(args[i + 1])
|
||||
labels_path_explicit = True
|
||||
i += 2
|
||||
elif a == "--report" and i + 1 < len(args):
|
||||
report_path = Path(args[i + 1])
|
||||
report_path_explicit = True
|
||||
i += 2
|
||||
elif a == "--sections" and i + 1 < len(args):
|
||||
sections_path = Path(args[i + 1]); i += 2
|
||||
elif a == "--output" and i + 1 < len(args):
|
||||
callflow_output = Path(args[i + 1]).expanduser()
|
||||
if not callflow_output.is_absolute():
|
||||
callflow_output = Path.cwd() / callflow_output
|
||||
i += 2
|
||||
elif a == "--lang" and i + 1 < len(args):
|
||||
callflow_lang = args[i + 1]; i += 2
|
||||
elif a == "--max-sections" and i + 1 < len(args):
|
||||
callflow_max_sections = int(args[i + 1]); i += 2
|
||||
elif a == "--diagram-scale" and i + 1 < len(args):
|
||||
callflow_diagram_scale = float(args[i + 1]); i += 2
|
||||
elif a == "--max-diagram-nodes" and i + 1 < len(args):
|
||||
callflow_max_diagram_nodes = int(args[i + 1]); i += 2
|
||||
elif a == "--max-diagram-edges" and i + 1 < len(args):
|
||||
callflow_max_diagram_edges = int(args[i + 1]); i += 2
|
||||
elif a in ("-h", "--help") and subcmd == "callflow-html":
|
||||
print("Usage: graphify export callflow-html [GRAPH|DIR] [--graph PATH] [--labels PATH]")
|
||||
print(" --report PATH path to GRAPH_REPORT.md")
|
||||
print(" --sections PATH JSON section definitions")
|
||||
print(" --output HTML output path (default graphify-out/<project>-callflow.html)")
|
||||
print(" --lang LANG auto, zh-CN, en, etc. (default auto)")
|
||||
print(" --max-sections N maximum auto-derived sections (default 15)")
|
||||
print(" --diagram-scale N Mermaid diagram scale (default 1.0)")
|
||||
print(" --max-diagram-nodes N representative nodes per section (default 18)")
|
||||
print(" --max-diagram-edges N representative edges per section (default 24)")
|
||||
sys.exit(0)
|
||||
elif a == "--node-limit" and i + 1 < len(args):
|
||||
node_limit = int(args[i + 1]); i += 2
|
||||
elif a == "--no-viz":
|
||||
@@ -1967,13 +2088,51 @@ def main() -> None:
|
||||
neo4j_user = args[i + 1]; i += 2
|
||||
elif a == "--password" and i + 1 < len(args):
|
||||
neo4j_password = args[i + 1]; i += 2
|
||||
elif subcmd == "callflow-html" and not a.startswith("-") and not graph_path_explicit:
|
||||
candidate = Path(a)
|
||||
if candidate.name == "graph.json" or candidate.suffix.lower() == ".json":
|
||||
graph_path = candidate
|
||||
elif (candidate / "graph.json").exists():
|
||||
graph_path = candidate / "graph.json"
|
||||
else:
|
||||
graph_path = candidate / _GRAPHIFY_OUT / "graph.json"
|
||||
graph_path_explicit = True
|
||||
i += 1
|
||||
else:
|
||||
i += 1
|
||||
|
||||
graph_path = graph_path.expanduser()
|
||||
if graph_path_explicit:
|
||||
graph_out_dir = graph_path.parent
|
||||
if not labels_path_explicit:
|
||||
labels_path = graph_out_dir / ".graphify_labels.json"
|
||||
if not report_path_explicit:
|
||||
report_path = graph_out_dir / "GRAPH_REPORT.md"
|
||||
labels_path = labels_path.expanduser()
|
||||
report_path = report_path.expanduser()
|
||||
|
||||
if not graph_path.exists():
|
||||
print(f"error: graph not found: {graph_path}. Run /graphify <path> first.", file=sys.stderr)
|
||||
sys.exit(1)
|
||||
|
||||
if subcmd == "callflow-html":
|
||||
from graphify.callflow_html import write_callflow_html as _write_callflow_html
|
||||
out = _write_callflow_html(
|
||||
graph=graph_path,
|
||||
report=report_path,
|
||||
labels=labels_path,
|
||||
sections=sections_path,
|
||||
output=callflow_output,
|
||||
lang=callflow_lang,
|
||||
max_sections=callflow_max_sections,
|
||||
diagram_scale=callflow_diagram_scale,
|
||||
max_diagram_nodes=callflow_max_diagram_nodes,
|
||||
max_diagram_edges=callflow_max_diagram_edges,
|
||||
verbose=True,
|
||||
)
|
||||
print(f"callflow HTML written - open in any browser: {out}")
|
||||
sys.exit(0)
|
||||
|
||||
from networkx.readwrite import json_graph as _jg
|
||||
from graphify.build import build_from_json as _bfj
|
||||
|
||||
@@ -2296,6 +2455,23 @@ def main() -> None:
|
||||
host in ("localhost", "127.0.0.1", "::1")
|
||||
or host.startswith("127.")
|
||||
)
|
||||
elif backend == "bedrock":
|
||||
allow_no_key = bool(
|
||||
os.environ.get("AWS_PROFILE")
|
||||
or os.environ.get("AWS_REGION")
|
||||
or os.environ.get("AWS_DEFAULT_REGION")
|
||||
or os.environ.get("AWS_ACCESS_KEY_ID")
|
||||
)
|
||||
elif backend == "claude-cli":
|
||||
import shutil as _shutil
|
||||
allow_no_key = _shutil.which("claude") is not None
|
||||
if not allow_no_key:
|
||||
print(
|
||||
"error: backend 'claude-cli' requires the `claude` CLI on $PATH "
|
||||
"(install Claude Code and run `claude` once to authenticate).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
sys.exit(1)
|
||||
if not allow_no_key:
|
||||
print(
|
||||
f"error: backend '{backend}' requires {_format_backend_env_keys(backend)} to be set.",
|
||||
@@ -2489,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:
|
||||
@@ -2571,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)
|
||||
|
||||
|
||||
+32
-4
@@ -24,19 +24,44 @@ from __future__ import annotations
|
||||
import json
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from pathlib import Path
|
||||
import networkx as nx
|
||||
from .validate import validate_extraction
|
||||
|
||||
|
||||
# Synonym mapper for known invalid file_type values that LLM subagents commonly
|
||||
# emit. Keeps semantic intent close (markdown→document, tool→code) and falls
|
||||
# back to "concept" for any other invalid value (see #840).
|
||||
_FILE_TYPE_SYNONYMS = {
|
||||
"markdown": "document",
|
||||
"text": "document",
|
||||
"tool": "code",
|
||||
"library": "code",
|
||||
"pattern": "concept",
|
||||
"principle": "concept",
|
||||
"constraint": "concept",
|
||||
"tech": "concept",
|
||||
"technology": "concept",
|
||||
"data-source": "concept",
|
||||
"data_source": "concept",
|
||||
"gotcha": "concept",
|
||||
"framework": "concept",
|
||||
}
|
||||
|
||||
|
||||
def _normalize_id(s: str) -> str:
|
||||
"""Normalize an ID string the same way extract._make_id does.
|
||||
r"""Normalize an ID string the same way extract._make_id does.
|
||||
|
||||
Used to reconcile edge endpoints when the LLM generates IDs with slightly
|
||||
different punctuation or casing than the AST extractor.
|
||||
different punctuation or casing than the AST extractor. Must stay in sync
|
||||
with extract._make_id — NFKC normalization, \w with re.UNICODE, underscore
|
||||
collapse, and casefold must all match (#811).
|
||||
"""
|
||||
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", s)
|
||||
return cleaned.strip("_").lower()
|
||||
s = unicodedata.normalize("NFKC", s)
|
||||
cleaned = re.sub(r"[^\w]+", "_", s, flags=re.UNICODE)
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
return cleaned.strip("_").casefold()
|
||||
|
||||
|
||||
def _norm_source_file(p: str | None) -> str | None:
|
||||
@@ -100,6 +125,9 @@ def build_from_json(extraction: dict, *, directed: bool = False) -> nx.Graph:
|
||||
# trigger spurious "invalid file_type 'None'" validator warnings (#660).
|
||||
if node.get("file_type") in (None, ""):
|
||||
node["file_type"] = "concept"
|
||||
ft = node.get("file_type", "")
|
||||
if ft and ft not in {"code", "document", "paper", "image", "rationale", "concept"}:
|
||||
node["file_type"] = _FILE_TYPE_SYNONYMS.get(ft, "concept")
|
||||
|
||||
errors = validate_extraction(extraction)
|
||||
# Dangling edges (stdlib/external imports) are expected - only warn about real schema errors.
|
||||
|
||||
+6
-3
@@ -55,9 +55,9 @@ def file_hash(path: Path, root: Path = Path(".")) -> str:
|
||||
h.update(b"\x00")
|
||||
try:
|
||||
rel = p.resolve().relative_to(Path(root).resolve())
|
||||
h.update(str(rel).encode())
|
||||
h.update(rel.as_posix().lower().encode())
|
||||
except ValueError:
|
||||
h.update(str(p.resolve()).encode())
|
||||
h.update(p.resolve().as_posix().lower().encode())
|
||||
return h.hexdigest()
|
||||
|
||||
|
||||
@@ -190,7 +190,10 @@ def check_semantic_cache(
|
||||
uncached: list[str] = []
|
||||
|
||||
for fpath in files:
|
||||
result = load_cached(Path(fpath), root, kind="semantic")
|
||||
p = Path(fpath)
|
||||
if not p.is_absolute():
|
||||
p = Path(root) / p
|
||||
result = load_cached(p, root, kind="semantic")
|
||||
if result is not None:
|
||||
cached_nodes.extend(result.get("nodes", []))
|
||||
cached_edges.extend(result.get("edges", []))
|
||||
|
||||
File diff suppressed because it is too large.
Load diff
+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]))
|
||||
+14
-2
@@ -233,8 +233,20 @@ def deduplicate_entities(
|
||||
deduped_edges = []
|
||||
for edge in edges:
|
||||
e = dict(edge)
|
||||
e["source"] = remap.get(e["source"], e["source"])
|
||||
e["target"] = remap.get(e["target"], e["target"])
|
||||
# Tolerate "from"/"to" keys from LLM backends that don't follow the
|
||||
# schema exactly — build_from_json normalises later but dedup runs
|
||||
# first so bracket access would KeyError here (#803).
|
||||
# Use explicit key presence check (not `or`) so empty-string src/tgt
|
||||
# aren't silently replaced by the fallback key.
|
||||
src = e["source"] if "source" in e else e.get("from")
|
||||
tgt = e["target"] if "target" in e else e.get("to")
|
||||
if src is None or tgt is None:
|
||||
continue
|
||||
e["source"] = remap.get(src, src)
|
||||
e["target"] = remap.get(tgt, tgt)
|
||||
# Remove legacy keys so they don't leak into edge attrs in graph.json.
|
||||
e.pop("from", None)
|
||||
e.pop("to", None)
|
||||
if e["source"] != e["target"]:
|
||||
deduped_edges.append(e)
|
||||
|
||||
|
||||
+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
|
||||
|
||||
|
||||
+150
-3
@@ -5,6 +5,7 @@ import json
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
import unicodedata
|
||||
from dataclasses import dataclass, field
|
||||
from pathlib import Path
|
||||
from typing import Callable, Any
|
||||
@@ -30,10 +31,19 @@ def _safe_extract(extractor: Callable, path: Path) -> dict:
|
||||
|
||||
|
||||
def _make_id(*parts: str) -> str:
|
||||
"""Build a stable node ID from one or more name parts."""
|
||||
r"""Build a stable node ID from one or more name parts.
|
||||
|
||||
Preserves Unicode letters/digits (CJK, Cyrillic, Arabic, accented Latin,
|
||||
etc.) so non-ASCII identifiers produce distinct IDs and don't collapse to
|
||||
a single per-file node (#811). NFKC normalization ensures composed and
|
||||
decomposed forms of the same character (e.g. é vs e+combining-acute)
|
||||
produce the same ID. Must stay in sync with build._normalize_id.
|
||||
"""
|
||||
combined = "_".join(p.strip("_.") for p in parts if p)
|
||||
cleaned = re.sub(r"[^a-zA-Z0-9]+", "_", combined)
|
||||
return cleaned.strip("_").lower()
|
||||
combined = unicodedata.normalize("NFKC", combined)
|
||||
cleaned = re.sub(r"[^\w]+", "_", combined, flags=re.UNICODE)
|
||||
cleaned = re.sub(r"_+", "_", cleaned)
|
||||
return cleaned.strip("_").casefold()
|
||||
|
||||
|
||||
def _file_stem(path: Path) -> str:
|
||||
@@ -2113,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)
|
||||
@@ -5480,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
|
||||
|
||||
|
||||
|
||||
+159
-6
@@ -94,6 +94,16 @@ BACKENDS: dict[str, dict] = {
|
||||
"temperature": 0,
|
||||
"max_tokens": 16384,
|
||||
},
|
||||
"claude-cli": {
|
||||
# Routes through the locally-installed `claude` CLI (Claude Code) using
|
||||
# `-p --output-format json`. Authenticates via the user's existing
|
||||
# Pro/Max subscription instead of a separate ANTHROPIC_API_KEY — costs
|
||||
# are billed to the plan, not pay-as-you-go API credit.
|
||||
"default_model": "claude-code-plan",
|
||||
"pricing": {"input": 0.0, "output": 0.0},
|
||||
"temperature": 0,
|
||||
"max_tokens": 16384,
|
||||
},
|
||||
}
|
||||
|
||||
|
||||
@@ -122,7 +132,7 @@ Node ID format: lowercase, only [a-z0-9_], no dots or slashes.
|
||||
Format: {stem}_{entity} where stem = filename without extension, entity = symbol name (both normalised).
|
||||
|
||||
Output exactly this schema:
|
||||
{"nodes":[{"id":"stem_entity","label":"Human Readable Name","file_type":"code|document|paper|image|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","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
|
||||
{"nodes":[{"id":"stem_entity","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","confidence":"EXTRACTED|INFERRED|AMBIGUOUS","confidence_score":1.0,"source_file":"relative/path","source_location":null,"weight":1.0}],"hyperedges":[],"input_tokens":0,"output_tokens":0}
|
||||
"""
|
||||
|
||||
|
||||
@@ -279,6 +289,50 @@ def _call_openai_compat(
|
||||
# Kimi-k2.6 is a reasoning model — disable thinking so content isn't empty
|
||||
if "moonshot" in base_url:
|
||||
kwargs["extra_body"] = {"thinking": {"type": "disabled"}}
|
||||
# Ollama defaults num_ctx to 2048 and silently truncates prompts larger
|
||||
# than that — the symptom is hollow 200 OK responses after the first few
|
||||
# chunks (#798). We derive num_ctx from the actual prompt size so we don't
|
||||
# over-allocate KV-cache VRAM. Over-allocation (e.g. 128k slots for an 8k
|
||||
# prompt on a 31B model) exhausts VRAM by chunk 4 and produces the same
|
||||
# hollow-200 symptom — just from a different direction (#798 follow-up).
|
||||
# Formula: actual input tokens + output cap + system prompt headroom.
|
||||
# Capped at 131072 (enough for the default 60k token_budget); env var wins.
|
||||
if backend == "ollama":
|
||||
num_ctx_raw = os.environ.get("GRAPHIFY_OLLAMA_NUM_CTX", "").strip()
|
||||
# Auto-derive num_ctx from actual chunk size regardless — used as the
|
||||
# fallback and for the mismatch check below.
|
||||
estimated_input = len(user_message) // _CHARS_PER_TOKEN + 400
|
||||
auto_num_ctx = min(estimated_input + max_completion_tokens + 2000, 131072)
|
||||
auto_num_ctx = max(auto_num_ctx, 8192)
|
||||
if num_ctx_raw:
|
||||
try:
|
||||
num_ctx = int(num_ctx_raw)
|
||||
except ValueError:
|
||||
# Bad env var: fall through to auto-derivation (not 131072 —
|
||||
# hardcoding the cap is what causes OOM on constrained VRAM).
|
||||
print(
|
||||
f"[graphify] GRAPHIFY_OLLAMA_NUM_CTX={num_ctx_raw!r} is not a valid integer; "
|
||||
f"using auto-derived value ({auto_num_ctx}).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
num_ctx = auto_num_ctx
|
||||
else:
|
||||
# Warn when the pinned value is smaller than the estimated input —
|
||||
# Ollama silently truncates the prompt and returns empty responses.
|
||||
if num_ctx < estimated_input:
|
||||
print(
|
||||
f"[graphify] warning: GRAPHIFY_OLLAMA_NUM_CTX={num_ctx} is smaller than "
|
||||
f"the estimated chunk input (~{estimated_input} tokens). Ollama will "
|
||||
f"silently truncate the prompt and return empty responses. "
|
||||
f"Try --token-budget {max(1024, num_ctx // 3)} or increase NUM_CTX.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
else:
|
||||
# Estimate input tokens: user_message chars / 4 (standard BPE
|
||||
# heuristic) + 400 for the system prompt, then add output headroom.
|
||||
num_ctx = auto_num_ctx
|
||||
keep_alive = os.environ.get("GRAPHIFY_OLLAMA_KEEP_ALIVE", "30m")
|
||||
kwargs["extra_body"] = {"options": {"num_ctx": num_ctx}, "keep_alive": keep_alive}
|
||||
resp = client.chat.completions.create(**kwargs)
|
||||
raw_content = resp.choices[0].message.content
|
||||
result = _parse_llm_json(raw_content or "{}")
|
||||
@@ -306,9 +360,12 @@ def _call_openai_compat(
|
||||
output_tokens = result["output_tokens"]
|
||||
if output_tokens < 50 and backend == "ollama":
|
||||
print(
|
||||
"[graphify] warning: ollama returned very few tokens — the model may be "
|
||||
"too small or not following the JSON instruction format. "
|
||||
"Try a larger model with --model (e.g. --model qwen2.5-coder:14b).",
|
||||
"[graphify] warning: ollama returned very few tokens — likely causes: "
|
||||
"(1) VRAM pressure: check `nvidia-smi` and reduce chunk size with "
|
||||
"--token-budget (e.g. --token-budget 4096) or set "
|
||||
"GRAPHIFY_OLLAMA_NUM_CTX to a smaller value; "
|
||||
"(2) model too small for JSON instruction following — "
|
||||
"try a larger model with --model (e.g. --model qwen2.5-coder:14b).",
|
||||
file=sys.stderr,
|
||||
)
|
||||
return result
|
||||
@@ -350,6 +407,71 @@ def _call_claude(api_key: str, model: str, user_message: str, max_tokens: int =
|
||||
return result
|
||||
|
||||
|
||||
def _call_claude_cli(user_message: str, max_tokens: int = 8192) -> dict:
|
||||
"""Call Claude via the locally-installed Claude Code CLI (`claude -p`).
|
||||
|
||||
Routes through the user's Claude Code subscription auth instead of a separate
|
||||
ANTHROPIC_API_KEY. Useful for Pro/Max subscribers who don't want to provision
|
||||
a pay-as-you-go API key just to run graphify's semantic pass.
|
||||
"""
|
||||
import shutil
|
||||
import subprocess
|
||||
|
||||
if shutil.which("claude") is None:
|
||||
raise RuntimeError(
|
||||
"Claude Code CLI not found on $PATH. Install from "
|
||||
"https://claude.ai/code and run `claude` once to authenticate."
|
||||
)
|
||||
|
||||
proc = subprocess.run(
|
||||
[
|
||||
"claude", "-p",
|
||||
"--output-format", "json",
|
||||
"--no-session-persistence",
|
||||
"--append-system-prompt", _EXTRACTION_SYSTEM,
|
||||
],
|
||||
input=user_message,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=600,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(
|
||||
f"claude -p exited {proc.returncode}: {proc.stderr.strip()[:500]}"
|
||||
)
|
||||
|
||||
try:
|
||||
envelope = json.loads(proc.stdout)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(
|
||||
f"claude -p produced unparseable JSON envelope: {exc}; "
|
||||
f"first 500 chars of stdout: {proc.stdout[:500]!r}"
|
||||
) from exc
|
||||
|
||||
raw_content = envelope.get("result", "")
|
||||
result = _parse_llm_json(raw_content or "{}")
|
||||
usage = envelope.get("usage") or {}
|
||||
result["input_tokens"] = (
|
||||
int(usage.get("input_tokens", 0) or 0)
|
||||
+ int(usage.get("cache_read_input_tokens", 0) or 0)
|
||||
+ int(usage.get("cache_creation_input_tokens", 0) or 0)
|
||||
)
|
||||
result["output_tokens"] = int(usage.get("output_tokens", 0) or 0)
|
||||
model_usage = envelope.get("modelUsage") or {}
|
||||
result["model"] = next(iter(model_usage), "claude-code-plan")
|
||||
stop_reason = envelope.get("stop_reason", "")
|
||||
result["finish_reason"] = "length" if stop_reason == "max_tokens" else "stop"
|
||||
if _response_is_hollow(raw_content, result) and result["finish_reason"] != "length":
|
||||
print(
|
||||
"[graphify] claude-cli returned a hollow response; treating as "
|
||||
"truncation so adaptive retry can bisect the chunk.",
|
||||
file=sys.stderr,
|
||||
)
|
||||
result["finish_reason"] = "length"
|
||||
return result
|
||||
|
||||
|
||||
def _call_bedrock(model: str, user_message: str, max_tokens: int = 8192) -> dict:
|
||||
"""Call AWS Bedrock via boto3 Converse API using the standard AWS credential chain."""
|
||||
try:
|
||||
@@ -424,7 +546,7 @@ def extract_files_direct(
|
||||
file=sys.stderr,
|
||||
)
|
||||
key = "ollama"
|
||||
if not key and backend != "bedrock":
|
||||
if not key and backend not in ("bedrock", "claude-cli"):
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. "
|
||||
f"Set {_format_backend_env_keys(backend)} or pass api_key=."
|
||||
@@ -435,6 +557,8 @@ def extract_files_direct(
|
||||
|
||||
if backend == "claude":
|
||||
return _call_claude(key, mdl, user_msg, max_tokens=max_out)
|
||||
if backend == "claude-cli":
|
||||
return _call_claude_cli(user_msg, max_tokens=max_out)
|
||||
if backend == "bedrock":
|
||||
return _call_bedrock(mdl, user_msg, max_tokens=max_out)
|
||||
return _call_openai_compat(
|
||||
@@ -742,6 +866,15 @@ def extract_corpus_parallel(
|
||||
except Exception as exc: # noqa: BLE001 — caller-facing surface, log + continue
|
||||
return idx, None, exc
|
||||
|
||||
# Ollama serves one request at a time per loaded model on a single GPU.
|
||||
# Four concurrent 60k-token requests cause VRAM pressure and hollow
|
||||
# responses after 3-4 chunks (#798). Force serial unless the user opts in.
|
||||
if backend == "ollama" and os.environ.get("GRAPHIFY_OLLAMA_PARALLEL", "").strip() != "1":
|
||||
max_concurrency = 1
|
||||
# claude-cli shells out to a Claude Code session; parallel subprocesses conflict
|
||||
# over session state. Force serial unless the user explicitly opts in.
|
||||
if backend == "claude-cli" and os.environ.get("GRAPHIFY_CLAUDE_CLI_PARALLEL", "").strip() != "1":
|
||||
max_concurrency = 1
|
||||
workers = max(1, min(max_concurrency, total))
|
||||
if workers == 1:
|
||||
# Avoid thread pool overhead for single-worker runs (and keep
|
||||
@@ -800,7 +933,7 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
|
||||
ollama_url = os.environ.get("OLLAMA_BASE_URL", cfg.get("base_url", ""))
|
||||
_validate_ollama_base_url(ollama_url)
|
||||
key = "ollama"
|
||||
if not key and backend != "bedrock":
|
||||
if not key and backend not in ("bedrock", "claude-cli"):
|
||||
raise ValueError(
|
||||
f"No API key for backend '{backend}'. Set {_format_backend_env_keys(backend)}."
|
||||
)
|
||||
@@ -819,6 +952,26 @@ def _call_llm(prompt: str, *, backend: str, max_tokens: int = 200) -> str:
|
||||
)
|
||||
return resp.content[0].text if resp.content else ""
|
||||
|
||||
if backend == "claude-cli":
|
||||
import shutil, subprocess
|
||||
if shutil.which("claude") is None:
|
||||
raise RuntimeError("Claude Code CLI not found on $PATH")
|
||||
proc = subprocess.run(
|
||||
["claude", "-p", "--output-format", "json", "--no-session-persistence"],
|
||||
input=prompt,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=600,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
raise RuntimeError(f"claude -p exited {proc.returncode}: {proc.stderr.strip()[:500]}")
|
||||
try:
|
||||
envelope = json.loads(proc.stdout)
|
||||
except json.JSONDecodeError as exc:
|
||||
raise RuntimeError(f"claude -p produced unparseable JSON envelope: {exc}") from exc
|
||||
return envelope.get("result", "")
|
||||
|
||||
if backend == "bedrock":
|
||||
try:
|
||||
import boto3
|
||||
|
||||
+104
-16
@@ -20,6 +20,7 @@ def _load_graph(graph_path: str) -> nx.Graph:
|
||||
data = json.loads(safe.read_text(encoding="utf-8"))
|
||||
if "links" not in data and "edges" in data:
|
||||
data = dict(data, links=data["edges"])
|
||||
data = {**data, "directed": True}
|
||||
try:
|
||||
return json_graph.node_link_graph(data, edges="links")
|
||||
except TypeError:
|
||||
@@ -48,7 +49,10 @@ def _strip_diacritics(text: str) -> str:
|
||||
return "".join(c for c in nfkd if not unicodedata.combining(c))
|
||||
|
||||
|
||||
_EXACT_MATCH_BONUS = 100.0
|
||||
_EXACT_MATCH_BONUS = 1000.0
|
||||
_PREFIX_MATCH_BONUS = 100.0
|
||||
_SUBSTRING_MATCH_BONUS = 1.0
|
||||
_SOURCE_MATCH_BONUS = 0.5
|
||||
|
||||
|
||||
def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
@@ -56,11 +60,20 @@ def _score_nodes(G: nx.Graph, terms: list[str]) -> list[tuple[float, str]]:
|
||||
norm_terms = [_strip_diacritics(t).lower() for t in terms]
|
||||
for nid, data in G.nodes(data=True):
|
||||
norm_label = data.get("norm_label") or _strip_diacritics(data.get("label") or "").lower()
|
||||
bare_label = norm_label.rstrip("()")
|
||||
source = (data.get("source_file") or "").lower()
|
||||
score = sum(1 for t in norm_terms if t in norm_label) + sum(0.5 for t in norm_terms if t in source)
|
||||
# Exact match: single term equals the full label (strip trailing () for functions)
|
||||
if any(t == norm_label or t == norm_label.rstrip("()") for t in norm_terms):
|
||||
score += _EXACT_MATCH_BONUS
|
||||
score = 0.0
|
||||
for t in norm_terms:
|
||||
# Three-tier precedence: exact > prefix > substring (take the
|
||||
# strongest tier per term so a single term cannot double-count).
|
||||
if t == norm_label or t == bare_label:
|
||||
score += _EXACT_MATCH_BONUS
|
||||
elif norm_label.startswith(t) or bare_label.startswith(t):
|
||||
score += _PREFIX_MATCH_BONUS
|
||||
elif t in norm_label:
|
||||
score += _SUBSTRING_MATCH_BONUS
|
||||
if t in source:
|
||||
score += _SOURCE_MATCH_BONUS
|
||||
if score > 0:
|
||||
scored.append((score, nid))
|
||||
return sorted(scored, reverse=True)
|
||||
@@ -129,12 +142,26 @@ def _filter_graph_by_context(G: nx.Graph, context_filters: list[str] | None) ->
|
||||
|
||||
|
||||
def _bfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], list[tuple]]:
|
||||
# Compute hub threshold: nodes above this degree are not expanded as transit.
|
||||
# p99 of degree distribution, floored at 50 to avoid over-blocking small graphs.
|
||||
degrees = [G.degree(n) for n in G.nodes()]
|
||||
if degrees:
|
||||
degrees_sorted = sorted(degrees)
|
||||
p99_idx = int(len(degrees_sorted) * 0.99)
|
||||
hub_threshold = max(50, degrees_sorted[p99_idx])
|
||||
else:
|
||||
hub_threshold = 50
|
||||
seed_set = set(start_nodes)
|
||||
visited: set[str] = set(start_nodes)
|
||||
frontier = set(start_nodes)
|
||||
edges_seen: list[tuple] = []
|
||||
for _ in range(depth):
|
||||
next_frontier: set[str] = set()
|
||||
for n in frontier:
|
||||
# Don't expand through high-degree hubs (except seeds - a hub that
|
||||
# is the starting node should still be explored).
|
||||
if n not in seed_set and G.degree(n) >= hub_threshold:
|
||||
continue
|
||||
for neighbor in G.neighbors(n):
|
||||
if neighbor not in visited:
|
||||
next_frontier.add(neighbor)
|
||||
@@ -145,6 +172,14 @@ def _bfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
|
||||
|
||||
def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], list[tuple]]:
|
||||
degrees = [G.degree(n) for n in G.nodes()]
|
||||
if degrees:
|
||||
degrees_sorted = sorted(degrees)
|
||||
p99_idx = int(len(degrees_sorted) * 0.99)
|
||||
hub_threshold = max(50, degrees_sorted[p99_idx])
|
||||
else:
|
||||
hub_threshold = 50
|
||||
seed_set = set(start_nodes)
|
||||
visited: set[str] = set()
|
||||
edges_seen: list[tuple] = []
|
||||
stack = [(n, 0) for n in reversed(start_nodes)]
|
||||
@@ -153,6 +188,8 @@ def _dfs(G: nx.Graph, start_nodes: list[str], depth: int) -> tuple[set[str], lis
|
||||
if node in visited or d > depth:
|
||||
continue
|
||||
visited.add(node)
|
||||
if node not in seed_set and G.degree(node) >= hub_threshold:
|
||||
continue
|
||||
for neighbor in G.neighbors(node):
|
||||
if neighbor not in visited:
|
||||
stack.append((neighbor, d + 1))
|
||||
@@ -233,11 +270,26 @@ def _query_graph_text(
|
||||
|
||||
|
||||
def _find_node(G: nx.Graph, label: str) -> list[str]:
|
||||
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive)."""
|
||||
"""Return node IDs whose label or ID matches the search term (diacritic-insensitive).
|
||||
|
||||
Results are ordered by three-tier precedence: exact match, then prefix match,
|
||||
then substring match. Node-ID exact matches are grouped with label exact matches.
|
||||
"""
|
||||
term = _strip_diacritics(label).lower()
|
||||
return [nid for nid, d in G.nodes(data=True)
|
||||
if term in (d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower())
|
||||
or term == nid.lower()]
|
||||
exact: list[str] = []
|
||||
prefix: list[str] = []
|
||||
substring: list[str] = []
|
||||
for nid, d in G.nodes(data=True):
|
||||
norm_label = d.get("norm_label") or _strip_diacritics(d.get("label") or "").lower()
|
||||
bare_label = norm_label.rstrip("()")
|
||||
nid_lower = nid.lower()
|
||||
if term == norm_label or term == bare_label or term == nid_lower:
|
||||
exact.append(nid)
|
||||
elif norm_label.startswith(term) or bare_label.startswith(term) or nid_lower.startswith(term):
|
||||
prefix.append(nid)
|
||||
elif term in norm_label:
|
||||
substring.append(nid)
|
||||
return exact + prefix + substring
|
||||
|
||||
|
||||
def _filter_blank_stdin() -> None:
|
||||
@@ -403,13 +455,22 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
return f"No node matching '{label}' found."
|
||||
nid = matches[0]
|
||||
lines = [f"Neighbors of {sanitize_label(G.nodes[nid].get('label', nid))}:"]
|
||||
for neighbor in G.neighbors(nid):
|
||||
d = edge_data(G, nid, neighbor)
|
||||
for nb in G.successors(nid):
|
||||
d = edge_data(G, nid, nb)
|
||||
rel = d.get("relation", "")
|
||||
if rel_filter and rel_filter not in rel.lower():
|
||||
continue
|
||||
lines.append(
|
||||
f" --> {sanitize_label(G.nodes[neighbor].get('label', neighbor))} "
|
||||
f" --> {sanitize_label(G.nodes[nb].get('label', nb))} "
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]"
|
||||
)
|
||||
for nb in G.predecessors(nid):
|
||||
d = edge_data(G, nb, nid)
|
||||
rel = d.get("relation", "")
|
||||
if rel_filter and rel_filter not in rel.lower():
|
||||
continue
|
||||
lines.append(
|
||||
f" <-- {sanitize_label(G.nodes[nb].get('label', nb))} "
|
||||
f"[{sanitize_label(str(rel))}] [{sanitize_label(str(d.get('confidence', '')))}]"
|
||||
)
|
||||
return "\n".join(lines)
|
||||
@@ -456,9 +517,27 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
if not tgt_scored:
|
||||
return f"No node matching target '{arguments['target']}' found."
|
||||
src_nid, tgt_nid = src_scored[0][1], tgt_scored[0][1]
|
||||
# Ambiguity guard: when both queries resolve to the same node, the
|
||||
# shortest path is trivially zero hops, which is almost never what the
|
||||
# caller wanted (see bug #828).
|
||||
if src_nid == tgt_nid:
|
||||
return (
|
||||
f"'{arguments['source']}' and '{arguments['target']}' both resolved to "
|
||||
f"the same node '{src_nid}'. Use a more specific label or the exact node ID."
|
||||
)
|
||||
warnings: list[str] = []
|
||||
for name, scored in (("source", src_scored), ("target", tgt_scored)):
|
||||
if len(scored) >= 2:
|
||||
top, runner = scored[0][0], scored[1][0]
|
||||
if top > 0 and (top - runner) / top < 0.10:
|
||||
warnings.append(
|
||||
f"warning: {name} match was ambiguous "
|
||||
f"(top score {top:g}, runner-up {runner:g})"
|
||||
)
|
||||
max_hops = int(arguments.get("max_hops", 8))
|
||||
try:
|
||||
path_nodes = nx.shortest_path(G, src_nid, tgt_nid)
|
||||
# Use undirected view for path-finding (works regardless of query src/tgt order)
|
||||
path_nodes = nx.shortest_path(G.to_undirected(as_view=True), src_nid, tgt_nid)
|
||||
except (nx.NetworkXNoPath, nx.NodeNotFound):
|
||||
return f"No path found between '{G.nodes[src_nid].get('label', src_nid)}' and '{G.nodes[tgt_nid].get('label', tgt_nid)}'."
|
||||
hops = len(path_nodes) - 1
|
||||
@@ -467,14 +546,23 @@ def serve(graph_path: str = "graphify-out/graph.json") -> None:
|
||||
segments = []
|
||||
for i in range(len(path_nodes) - 1):
|
||||
u, v = path_nodes[i], path_nodes[i + 1]
|
||||
edata = edge_data(G, u, v)
|
||||
if G.has_edge(u, v):
|
||||
edata = edge_data(G, u, v)
|
||||
forward = True
|
||||
else:
|
||||
edata = edge_data(G, v, u)
|
||||
forward = False
|
||||
rel = edata.get("relation", "")
|
||||
conf = edata.get("confidence", "")
|
||||
conf_str = f" [{conf}]" if conf else ""
|
||||
if i == 0:
|
||||
segments.append(G.nodes[u].get("label", u))
|
||||
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
|
||||
return f"Shortest path ({hops} hops):\n " + " ".join(segments)
|
||||
if forward:
|
||||
segments.append(f"--{rel}{conf_str}--> {G.nodes[v].get('label', v)}")
|
||||
else:
|
||||
segments.append(f"<--{rel}{conf_str}-- {G.nodes[v].get('label', v)}")
|
||||
prefix = ("\n".join(warnings) + "\n") if warnings else ""
|
||||
return prefix + f"Shortest path ({hops} hops):\n " + " ".join(segments)
|
||||
|
||||
_handlers = {
|
||||
"query_graph": _tool_query_graph,
|
||||
|
||||
+69
-63
@@ -69,10 +69,16 @@ import graphify
|
||||
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_1.py -Encoding utf8
|
||||
python .graphify_step_1_ensure_graphify_is_installed_1.py 2>$null
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_1.py
|
||||
if ($LASTEXITCODE -ne 0) { pip install graphifyy -q 2>&1 | Select-Object -Last 3 }
|
||||
if ($LASTEXITCODE -ne 0) {
|
||||
if (Get-Command uv -ErrorAction SilentlyContinue) {
|
||||
uv tool install --upgrade graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
} else {
|
||||
pip install graphifyy -q 2>&1 | Select-Object -Last 3
|
||||
}
|
||||
}
|
||||
# Write interpreter path for all subsequent steps
|
||||
@'
|
||||
import sys; open('.graphify_python', 'w').write(sys.executable)
|
||||
import sys; open('.graphify_python', 'w', encoding='utf-8').write(sys.executable)
|
||||
'@ | Out-File -FilePath .graphify_step_1_ensure_graphify_is_installed_2.py -Encoding utf8
|
||||
python .graphify_step_1_ensure_graphify_is_installed_2.py
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_step_1_ensure_graphify_is_installed_2.py
|
||||
@@ -88,7 +94,7 @@ import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
print(json.dumps(result))
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
'@ | Out-File -FilePath .graphify_step_2_detect_files_3.py -Encoding utf8
|
||||
python .graphify_step_2_detect_files_3.py > .graphify_detect.json
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_step_2_detect_files_3.py
|
||||
@@ -140,12 +146,12 @@ import json, os
|
||||
from pathlib import Path
|
||||
from graphify.transcribe import transcribe_all
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
video_files = detect.get('files', {}).get('video', [])
|
||||
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
|
||||
|
||||
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
|
||||
print(json.dumps(transcript_paths))
|
||||
print(json.dumps(transcript_paths, ensure_ascii=False))
|
||||
'@ | Out-File -FilePath .graphify_step_transcribe.py -Encoding utf8
|
||||
& (Get-Content graphify-out\.graphify_python) .graphify_step_transcribe.py | Out-File -FilePath graphify-out\.graphify_transcripts.json -Encoding utf8
|
||||
Remove-Item -ErrorAction SilentlyContinue .graphify_step_transcribe.py
|
||||
@@ -182,16 +188,16 @@ from pathlib import Path
|
||||
|
||||
def main():
|
||||
code_files = []
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files)
|
||||
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
Path('.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'AST: {len(result["nodes"])} nodes, {len(result["edges"])} edges')
|
||||
else:
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
Path('.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding="utf-8")
|
||||
print('No code files - skipping AST extraction')
|
||||
|
||||
|
||||
@@ -229,14 +235,14 @@ import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-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}))
|
||||
Path('.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
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
|
||||
@@ -343,7 +349,7 @@ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
@@ -352,7 +358,7 @@ for c in chunks:
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
}, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
@@ -364,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()) 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
|
||||
@@ -378,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()) if Path('.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('.graphify_semantic_new.json').read_text()) 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', [])
|
||||
@@ -398,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))
|
||||
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
|
||||
|
||||
@@ -413,8 +419,8 @@ Clean up temp files: `Remove-Item -ErrorAction SilentlyContinue .graphify_cached
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('.graphify_semantic.json').read_text())
|
||||
ast = json.loads(Path('.graphify_ast.json').read_text(encoding="utf-8"))
|
||||
sem = json.loads(Path('.graphify_semantic.json').read_text(encoding="utf-8"))
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
@@ -433,7 +439,7 @@ merged = {
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast["nodes"])} AST + {len(sem["nodes"])} semantic)')
|
||||
@@ -455,8 +461,8 @@ from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
@@ -469,7 +475,7 @@ labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
@@ -479,7 +485,7 @@ analysis = {
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
@@ -509,9 +515,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -525,8 +531,8 @@ labels = LABELS_DICT
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
Path('.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding="utf-8")
|
||||
print('Report updated with community labels')
|
||||
'@ | Out-File -FilePath .graphify_step_5_label_communities_10.py -Encoding utf8
|
||||
python .graphify_step_5_label_communities_10.py
|
||||
@@ -551,9 +557,9 @@ from graphify.build import build_from_json
|
||||
from graphify.export import to_obsidian, to_canvas
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -586,9 +592,9 @@ from graphify.build import build_from_json
|
||||
from graphify.export import to_html
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -615,7 +621,7 @@ from graphify.build import build_from_json
|
||||
from graphify.export import to_cypher
|
||||
from pathlib import Path
|
||||
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text()))
|
||||
G = build_from_json(json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8")))
|
||||
to_cypher(G, 'graphify-out/cypher.txt')
|
||||
print('cypher.txt written - import with: cypher-shell < graphify-out/cypher.txt')
|
||||
'@ | Out-File -FilePath .graphify_step_7_neo4j_export_only_if_neo4j_or__13.py -Encoding utf8
|
||||
@@ -633,8 +639,8 @@ from graphify.cluster import cluster
|
||||
from graphify.export import push_to_neo4j
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
|
||||
@@ -656,9 +662,9 @@ from graphify.build import build_from_json
|
||||
from graphify.export import to_svg
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text()) if Path('.graphify_labels.json').exists() else {}
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
labels_raw = json.loads(Path('.graphify_labels.json').read_text(encoding="utf-8")) if Path('.graphify_labels.json').exists() else {}
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -680,8 +686,8 @@ from graphify.build import build_from_json
|
||||
from graphify.export import to_graphml
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
analysis = json.loads(Path('.graphify_analysis.json').read_text(encoding="utf-8"))
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -723,7 +729,7 @@ import json
|
||||
from graphify.benchmark import run_benchmark, print_benchmark
|
||||
from pathlib import Path
|
||||
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detection = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
result = run_benchmark('graphify-out/graph.json', corpus_words=detection['total_words'])
|
||||
print_benchmark(result)
|
||||
'@ | Out-File -FilePath .graphify_step_8_token_reduction_benchmark_only_17.py -Encoding utf8
|
||||
@@ -745,17 +751,17 @@ from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('.graphify_detect.json').read_text(encoding="utf-8"))
|
||||
save_manifest(detect['files'])
|
||||
|
||||
# Update cumulative cost tracker
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
cost_path = Path('graphify-out/cost.json')
|
||||
if cost_path.exists():
|
||||
cost = json.loads(cost_path.read_text())
|
||||
cost = json.loads(cost_path.read_text(encoding="utf-8"))
|
||||
else:
|
||||
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
|
||||
|
||||
@@ -767,7 +773,7 @@ cost['runs'].append({
|
||||
})
|
||||
cost['total_input_tokens'] += input_tok
|
||||
cost['total_output_tokens'] += output_tok
|
||||
cost_path.write_text(json.dumps(cost, indent=2))
|
||||
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost["total_input_tokens"]:,} input, {cost["total_output_tokens"]:,} output ({len(cost["runs"])} runs)')
|
||||
@@ -821,8 +827,8 @@ from pathlib import Path
|
||||
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result))
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
Path('.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding="utf-8")
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -839,7 +845,7 @@ If new files exist, first check whether all changed files are code files:
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('.graphify_incremental.json').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
result = json.loads(open('.graphify_incremental.json', encoding='utf-8').read()) if Path('.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
@@ -866,15 +872,15 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load existing graph
|
||||
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
existing_data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
|
||||
# Load new extraction
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text())
|
||||
new_extraction = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Prune nodes from deleted files
|
||||
incremental = json.loads(Path('.graphify_incremental.json').read_text())
|
||||
incremental = json.loads(Path('.graphify_incremental.json').read_text(encoding="utf-8"))
|
||||
deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
@@ -914,8 +920,8 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('.graphify_old.json').read_text()) if Path('.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('.graphify_extract.json').read_text())
|
||||
old_data = json.loads(Path('.graphify_old.json').read_text(encoding="utf-8")) if Path('.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('.graphify_extract.json').read_text(encoding="utf-8"))
|
||||
G_new = build_from_json(new_extract)
|
||||
|
||||
if old_data:
|
||||
@@ -951,7 +957,7 @@ from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
detection = {'total_files': 0, 'total_words': 99999, 'needs_graph': True, 'warning': None,
|
||||
@@ -965,7 +971,7 @@ surprises = surprising_connections(G, communities)
|
||||
labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, '.')
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding="utf-8")
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
@@ -974,7 +980,7 @@ analysis = {
|
||||
'gods': gods,
|
||||
'surprises': surprises,
|
||||
}
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding="utf-8")
|
||||
print(f'Re-clustered: {len(communities)} communities')
|
||||
'@ | Out-File -FilePath .graphify_step_for_cluster_only_23.py -Encoding utf8
|
||||
python .graphify_step_for_cluster_only_23.py
|
||||
@@ -1022,7 +1028,7 @@ from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
question = 'QUESTION'
|
||||
@@ -1140,7 +1146,7 @@ import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
a_term = 'NODE_A'
|
||||
@@ -1217,7 +1223,7 @@ import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
from pathlib import Path
|
||||
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
data = json.loads(Path('graphify-out/graph.json').read_text(encoding="utf-8"))
|
||||
G = json_graph.node_link_graph(data, edges='links')
|
||||
|
||||
term = 'NODE_NAME'
|
||||
|
||||
+117
-81
@@ -99,10 +99,19 @@ if [ -z "$PYTHON" ] && [ -n "$GRAPHIFY_BIN" ]; then
|
||||
fi
|
||||
# 3. Fall back to python3
|
||||
if [ -z "$PYTHON" ]; then PYTHON="python3"; fi
|
||||
"$PYTHON" -c "import graphify" 2>/dev/null || "$PYTHON" -m pip install graphifyy -q 2>/dev/null || "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
if ! "$PYTHON" -c "import graphify" 2>/dev/null; then
|
||||
if command -v uv >/dev/null 2>&1; then
|
||||
uv tool install --upgrade graphifyy -q 2>&1 | tail -3
|
||||
_UV_PY=$(uv tool run graphifyy python -c "import sys; print(sys.executable)" 2>/dev/null)
|
||||
if [ -n "$_UV_PY" ]; then PYTHON="$_UV_PY"; fi
|
||||
else
|
||||
"$PYTHON" -m pip install graphifyy -q 2>/dev/null \
|
||||
|| "$PYTHON" -m pip install graphifyy -q --break-system-packages 2>&1 | tail -3
|
||||
fi
|
||||
fi
|
||||
# Write interpreter path for all subsequent steps (persists across invocations)
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
|
||||
# Save scan root so `graphify update` (no args) knows where to look next time
|
||||
echo "$(cd INPUT_PATH && pwd)" > graphify-out/.graphify_root
|
||||
```
|
||||
@@ -119,7 +128,7 @@ import json
|
||||
from graphify.detect import detect
|
||||
from pathlib import Path
|
||||
result = detect(Path('INPUT_PATH'))
|
||||
print(json.dumps(result))
|
||||
print(json.dumps(result, ensure_ascii=False))
|
||||
" > graphify-out/.graphify_detect.json
|
||||
```
|
||||
|
||||
@@ -170,12 +179,12 @@ import json, os
|
||||
from pathlib import Path
|
||||
from graphify.transcribe import transcribe_all
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
video_files = detect.get('files', {}).get('video', [])
|
||||
prompt = os.environ.get('GRAPHIFY_WHISPER_PROMPT', 'Use proper punctuation and paragraph breaks.')
|
||||
|
||||
transcript_paths = transcribe_all(video_files, initial_prompt=prompt)
|
||||
print(json.dumps(transcript_paths))
|
||||
print(json.dumps(transcript_paths, ensure_ascii=False))
|
||||
" > graphify-out/.graphify_transcripts.json
|
||||
```
|
||||
|
||||
@@ -198,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.
|
||||
@@ -214,16 +225,16 @@ from pathlib import Path
|
||||
import json
|
||||
|
||||
code_files = []
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
for f in detect.get('files', {}).get('code', []):
|
||||
code_files.extend(collect_files(Path(f)) if Path(f).is_dir() else [Path(f)])
|
||||
|
||||
if code_files:
|
||||
result = extract(code_files, cache_root=Path('.'))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps(result, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'AST: {len(result[\"nodes\"])} nodes, {len(result[\"edges\"])} edges')
|
||||
else:
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}))
|
||||
Path('graphify-out/.graphify_ast.json').write_text(json.dumps({'nodes':[],'edges':[],'input_tokens':0,'output_tokens':0}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print('No code files - skipping AST extraction')
|
||||
"
|
||||
```
|
||||
@@ -250,14 +261,14 @@ import json
|
||||
from graphify.cache import check_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-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-out/.graphify_cached.json').write_text(json.dumps({'nodes': cached_nodes, 'edges': cached_edges, 'hyperedges': cached_hyperedges}))
|
||||
Path('graphify-out/.graphify_uncached.txt').write_text('\n'.join(uncached))
|
||||
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')
|
||||
"
|
||||
```
|
||||
@@ -282,7 +293,15 @@ Concrete example for 3 chunks:
|
||||
```
|
||||
All three in one message. Not three separate messages.
|
||||
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, and DEEP_MODE):
|
||||
Each subagent receives this exact prompt (substitute FILE_LIST, CHUNK_NUM, TOTAL_CHUNKS, DEEP_MODE, and CHUNK_PATH).
|
||||
|
||||
CHUNK_PATH must be an **absolute** path — derive it before dispatching:
|
||||
```bash
|
||||
PROJECT_ROOT=$(cat graphify-out/.graphify_root)
|
||||
# Then for chunk N: CHUNK_PATH="${PROJECT_ROOT}/graphify-out/.graphify_chunk_0N.json"
|
||||
```
|
||||
|
||||
Subagent prompt template:
|
||||
|
||||
```
|
||||
You are a graphify extraction subagent. Read the files listed and extract a knowledge graph fragment.
|
||||
@@ -298,7 +317,7 @@ Rules:
|
||||
|
||||
Code files: focus on semantic edges AST cannot find (call relationships, shared data, arch patterns).
|
||||
Do not re-extract imports - AST already has those.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). Do NOT invent file_types like `concept` — valid values are only `code|document|paper|image|rationale`.
|
||||
Doc/paper files: extract named concepts, entities, citations. For rationale (WHY decisions were made, trade-offs, design intent): store as a `rationale` attribute on the relevant concept node — do NOT create a separate rationale node or fragment node. Only create a node for something that is itself a named entity or concept. Use `file_type:"rationale"` for concept-like nodes (ideas, principles, mechanisms, design patterns). `file_type` MUST be one of exactly these six values: `code`, `document`, `paper`, `image`, `rationale`, `concept`. Any other value is invalid and will be rejected.
|
||||
Code files: when adding `calls` edges, source MUST be the caller (the function/class doing the calling), target MUST be the callee. Never reverse this direction.
|
||||
Image files: use vision to understand what the image IS - do not just OCR.
|
||||
UI screenshot: layout patterns, design decisions, key elements, purpose.
|
||||
@@ -340,10 +359,13 @@ 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.
|
||||
|
||||
Output exactly this JSON (no other text):
|
||||
{"nodes":[{"id":"session_validatetoken","label":"Human Readable Name","file_type":"code|document|paper|image|rationale","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}
|
||||
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}
|
||||
|
||||
Then write the JSON to disk using the Write tool at this exact absolute path (no relative paths — Write resolves relative paths against an undefined cwd and the file will be silently lost):
|
||||
CHUNK_PATH
|
||||
```
|
||||
|
||||
**Step B3 - Collect, cache, and merge**
|
||||
@@ -366,7 +388,7 @@ chunks = sorted(glob.glob('graphify-out/.graphify_chunk_*.json'))
|
||||
all_nodes, all_edges, all_hyperedges = [], [], []
|
||||
total_in, total_out = 0, 0
|
||||
for c in chunks:
|
||||
d = json.loads(Path(c).read_text())
|
||||
d = json.loads(Path(c).read_text(encoding=\"utf-8\"))
|
||||
all_nodes += d.get('nodes', [])
|
||||
all_edges += d.get('edges', [])
|
||||
all_hyperedges += d.get('hyperedges', [])
|
||||
@@ -375,7 +397,7 @@ for c in chunks:
|
||||
Path('graphify-out/.graphify_semantic_new.json').write_text(json.dumps({
|
||||
'nodes': all_nodes, 'edges': all_edges, 'hyperedges': all_hyperedges,
|
||||
'input_tokens': total_in, 'output_tokens': total_out,
|
||||
}, indent=2))
|
||||
}, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'Merged {len(chunks)} chunks: {total_in:,} in / {total_out:,} out tokens')
|
||||
"
|
||||
```
|
||||
@@ -387,7 +409,7 @@ import json
|
||||
from graphify.cache import save_semantic_cache
|
||||
from pathlib import Path
|
||||
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.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')
|
||||
"
|
||||
@@ -399,8 +421,8 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
cached = json.loads(Path('graphify-out/.graphify_cached.json').read_text()) if Path('graphify-out/.graphify_cached.json').exists() else {'nodes':[],'edges':[],'hyperedges':[]}
|
||||
new = json.loads(Path('graphify-out/.graphify_semantic_new.json').read_text()) if Path('graphify-out/.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', [])
|
||||
@@ -419,7 +441,7 @@ merged = {
|
||||
'input_tokens': new.get('input_tokens', 0),
|
||||
'output_tokens': new.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_semantic.json').write_text(json.dumps(merged, indent=2))
|
||||
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)')
|
||||
"
|
||||
```
|
||||
@@ -432,8 +454,8 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from pathlib import Path
|
||||
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text())
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text())
|
||||
ast = json.loads(Path('graphify-out/.graphify_ast.json').read_text(encoding=\"utf-8\"))
|
||||
sem = json.loads(Path('graphify-out/.graphify_semantic.json').read_text(encoding=\"utf-8\"))
|
||||
|
||||
# Merge: AST nodes first, semantic nodes deduplicated by id
|
||||
seen = {n['id'] for n in ast['nodes']}
|
||||
@@ -452,7 +474,7 @@ merged = {
|
||||
'input_tokens': sem.get('input_tokens', 0),
|
||||
'output_tokens': sem.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2))
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
total = len(merged_nodes)
|
||||
edges = len(merged_edges)
|
||||
print(f'Merged: {total} nodes, {edges} edges ({len(ast[\"nodes\"])} AST + {len(sem[\"nodes\"])} semantic)')
|
||||
@@ -474,8 +496,8 @@ from graphify.report import generate
|
||||
from graphify.export import to_json
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = cluster(G)
|
||||
@@ -488,7 +510,7 @@ labels = {cid: 'Community ' + str(cid) for cid in communities}
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, gods, surprises, detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
to_json(G, communities, 'graphify-out/graph.json')
|
||||
|
||||
analysis = {
|
||||
@@ -498,7 +520,7 @@ analysis = {
|
||||
'surprises': surprises,
|
||||
'questions': questions,
|
||||
}
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2))
|
||||
Path('graphify-out/.graphify_analysis.json').write_text(json.dumps(analysis, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
if G.number_of_nodes() == 0:
|
||||
print('ERROR: Graph is empty - extraction produced no nodes.')
|
||||
print('Possible causes: all files were skipped, binary-only corpus, or extraction failed.')
|
||||
@@ -526,9 +548,9 @@ from graphify.analyze import god_nodes, surprising_connections, suggest_question
|
||||
from graphify.report import generate
|
||||
from pathlib import Path
|
||||
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text())
|
||||
extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
detection = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
analysis = json.loads(Path('graphify-out/.graphify_analysis.json').read_text(encoding=\"utf-8\"))
|
||||
|
||||
G = build_from_json(extraction)
|
||||
communities = {int(k): v for k, v in analysis['communities'].items()}
|
||||
@@ -542,8 +564,8 @@ labels = LABELS_DICT
|
||||
questions = suggest_questions(G, communities, labels)
|
||||
|
||||
report = generate(G, communities, cohesion, labels, analysis['gods'], analysis['surprises'], detection, tokens, 'INPUT_PATH', suggested_questions=questions)
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report)
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}))
|
||||
Path('graphify-out/GRAPH_REPORT.md').write_text(report, encoding=\"utf-8\")
|
||||
Path('graphify-out/.graphify_labels.json').write_text(json.dumps({str(k): v for k, v in labels.items()}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print('Report updated with community labels')
|
||||
"
|
||||
```
|
||||
@@ -651,17 +673,19 @@ from datetime import datetime, timezone
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Save manifest for --update
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text())
|
||||
save_manifest(detect['files'])
|
||||
detect = json.loads(Path('graphify-out/.graphify_detect.json').read_text(encoding=\"utf-8\"))
|
||||
# In --update mode, 'all_files' carries the full corpus; 'files' is the changed
|
||||
# subset. Full-rebuild mode populates only 'files', so the fallback handles that.
|
||||
save_manifest(detect.get('all_files') or detect['files'])
|
||||
|
||||
# Update cumulative cost tracker
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
input_tok = extract.get('input_tokens', 0)
|
||||
output_tok = extract.get('output_tokens', 0)
|
||||
|
||||
cost_path = Path('graphify-out/cost.json')
|
||||
if cost_path.exists():
|
||||
cost = json.loads(cost_path.read_text())
|
||||
cost = json.loads(cost_path.read_text(encoding=\"utf-8\"))
|
||||
else:
|
||||
cost = {'runs': [], 'total_input_tokens': 0, 'total_output_tokens': 0}
|
||||
|
||||
@@ -673,7 +697,7 @@ cost['runs'].append({
|
||||
})
|
||||
cost['total_input_tokens'] += input_tok
|
||||
cost['total_output_tokens'] += output_tok
|
||||
cost_path.write_text(json.dumps(cost, indent=2))
|
||||
cost_path.write_text(json.dumps(cost, indent=2, ensure_ascii=False), encoding=\"utf-8\")
|
||||
|
||||
print(f'This run: {input_tok:,} input tokens, {output_tok:,} output tokens')
|
||||
print(f'All time: {cost[\"total_input_tokens\"]:,} input, {cost[\"total_output_tokens\"]:,} output ({len(cost[\"runs\"])} runs)')
|
||||
@@ -727,7 +751,7 @@ if [ ! -f graphify-out/.graphify_python ]; then
|
||||
PYTHON="python3"
|
||||
fi
|
||||
mkdir -p graphify-out
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w').write(sys.executable)"
|
||||
"$PYTHON" -c "import sys; open('graphify-out/.graphify_python', 'w', encoding='utf-8').write(sys.executable)"
|
||||
fi
|
||||
```
|
||||
|
||||
@@ -743,8 +767,8 @@ from pathlib import Path
|
||||
|
||||
result = detect_incremental(Path('INPUT_PATH'))
|
||||
new_total = result.get('new_total', 0)
|
||||
print(json.dumps(result, indent=2))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result))
|
||||
print(json.dumps(result, indent=2, ensure_ascii=False))
|
||||
Path('graphify-out/.graphify_incremental.json').write_text(json.dumps(result, ensure_ascii=False), encoding=\"utf-8\")
|
||||
if new_total == 0:
|
||||
print('No files changed since last run. Nothing to update.')
|
||||
raise SystemExit(0)
|
||||
@@ -752,6 +776,24 @@ print(f'{new_total} new/changed file(s) to re-extract.')
|
||||
"
|
||||
```
|
||||
|
||||
Then populate `.graphify_detect.json` so Steps 3A–6 (which read it unconditionally) see the right state for an incremental run. `files` carries the changed subset (drives Step 3A AST + Step 3B0 cache check on only what changed); `all_files` carries the full corpus for any step that needs corpus-wide context:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
r = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
Path('graphify-out/.graphify_detect.json').write_text(json.dumps({
|
||||
'files': r.get('new_files', {}),
|
||||
'all_files': r.get('files', {}),
|
||||
'total_files': r.get('new_total', 0),
|
||||
'total_words': r.get('total_words', 0),
|
||||
'skipped_sensitive': r.get('skipped_sensitive', []),
|
||||
'needs_graph': True,
|
||||
}, ensure_ascii=False), encoding=\"utf-8\")
|
||||
"
|
||||
```
|
||||
|
||||
If new files exist, first check whether all changed files are code files:
|
||||
|
||||
```bash
|
||||
@@ -759,7 +801,7 @@ $(cat graphify-out/.graphify_python) -c "
|
||||
import json
|
||||
from pathlib import Path
|
||||
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
result = json.loads(open('graphify-out/.graphify_incremental.json', encoding='utf-8').read()) if Path('graphify-out/.graphify_incremental.json').exists() else {}
|
||||
code_exts = {'.py','.ts','.js','.go','.rs','.java','.cpp','.c','.rb','.swift','.kt','.cs','.scala','.php','.cc','.cxx','.hpp','.h','.kts','.lua','.toc','.f','.F','.f90','.F90','.f95','.F95','.f03','.F03','.f08','.F08'}
|
||||
new_files = result.get('new_files', {})
|
||||
all_changed = [f for files in new_files.values() for f in files]
|
||||
@@ -776,55 +818,49 @@ Then:
|
||||
|
||||
```bash
|
||||
$(cat graphify-out/.graphify_python) -c "
|
||||
import sys, json
|
||||
from graphify.build import build_from_json
|
||||
from graphify.export import to_json
|
||||
from networkx.readwrite import json_graph
|
||||
import networkx as nx
|
||||
import json
|
||||
from pathlib import Path
|
||||
from graphify.build import build_merge
|
||||
from graphify.detect import save_manifest
|
||||
|
||||
# Load existing graph
|
||||
existing_data = json.loads(Path('graphify-out/graph.json').read_text())
|
||||
G_existing = json_graph.node_link_graph(existing_data, edges='links')
|
||||
# Load new extraction and incremental state
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text(encoding=\"utf-8\"))
|
||||
deleted = list(incremental.get('deleted_files', []))
|
||||
|
||||
# Load new extraction
|
||||
new_extraction = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
G_new = build_from_json(new_extraction)
|
||||
|
||||
# Prune nodes from deleted files
|
||||
incremental = json.loads(Path('graphify-out/.graphify_incremental.json').read_text())
|
||||
deleted = set(incremental.get('deleted_files', []))
|
||||
if deleted:
|
||||
to_remove = [n for n, d in G_existing.nodes(data=True) if d.get('source_file') in deleted]
|
||||
G_existing.remove_nodes_from(to_remove)
|
||||
if to_remove:
|
||||
print(f'Pruned {len(to_remove)} ghost node(s) from {len(deleted)} deleted file(s) — drift detected and corrected.')
|
||||
else:
|
||||
print(f'{len(deleted)} file(s) deleted since last run, but no ghost nodes were present in the graph — no drift.')
|
||||
|
||||
# Merge: new nodes/edges into existing graph
|
||||
G_existing.update(G_new)
|
||||
print(f'Merged: {G_existing.number_of_nodes()} nodes, {G_existing.number_of_edges()} edges')
|
||||
# Use build_merge() — reads graph.json directly without NetworkX round-trip
|
||||
# so edge direction (calls, implements, imports) is always preserved (#801).
|
||||
G = build_merge(
|
||||
[new_extraction],
|
||||
graph_path='graphify-out/graph.json',
|
||||
prune_sources=deleted or None,
|
||||
)
|
||||
print(f'[graphify update] Merged: {G.number_of_nodes()} nodes, {G.number_of_edges()} edges')
|
||||
|
||||
# Write merged result back to .graphify_extract.json so Step 4 sees the full graph
|
||||
merged_out = {
|
||||
'nodes': [{'id': n, **d} for n, d in G_existing.nodes(data=True)],
|
||||
'edges': [{'source': u, 'target': v, **d} for u, v, d in G_existing.edges(data=True)],
|
||||
'hyperedges': new_extraction.get('hyperedges', []),
|
||||
'nodes': [{'id': n, **d} for n, d in G.nodes(data=True)],
|
||||
'edges': [
|
||||
# Explicit source/target last so they win over any stale attrs in d.
|
||||
{**{k: val for k, val in d.items() if k not in ('_src', '_tgt', 'source', 'target')},
|
||||
'source': d.get('_src', u), 'target': d.get('_tgt', v)}
|
||||
for u, v, d in G.edges(data=True)
|
||||
],
|
||||
# G.graph["hyperedges"] holds hyperedges from both existing graph.json
|
||||
# and new_extraction (build_merge combines them). Falling back to
|
||||
# new_extraction only would silently drop prior-run hyperedges (#801).
|
||||
'hyperedges': list(G.graph.get('hyperedges', [])),
|
||||
'input_tokens': new_extraction.get('input_tokens', 0),
|
||||
'output_tokens': new_extraction.get('output_tokens', 0),
|
||||
}
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out))
|
||||
Path('graphify-out/.graphify_extract.json').write_text(json.dumps(merged_out, ensure_ascii=False), encoding=\"utf-8\")
|
||||
print(f'[graphify update] Merged extraction written ({len(merged_out[\"nodes\"])} nodes, {len(merged_out[\"edges\"])} edges)')
|
||||
|
||||
# Save manifest with the CURRENT full file list so the next --update
|
||||
# diffs against today's filesystem state, not the prior --update's
|
||||
# baseline. Without this, deleted files get reported as ghosts again
|
||||
# on every subsequent --update until a full rebuild runs.
|
||||
from graphify.detect import save_manifest
|
||||
# Save manifest so next --update diffs against today's state, not the
|
||||
# prior run's baseline (prevents ghost-node reports on subsequent updates).
|
||||
save_manifest(incremental['files'])
|
||||
print('[graphify update] Manifest saved.')
|
||||
"
|
||||
"
|
||||
```
|
||||
|
||||
Then run Steps 4–8 on the merged graph as normal.
|
||||
@@ -841,8 +877,8 @@ import networkx as nx
|
||||
from pathlib import Path
|
||||
|
||||
# Load old graph (before update) from backup written before merge
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text()) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text())
|
||||
old_data = json.loads(Path('graphify-out/.graphify_old.json').read_text(encoding=\"utf-8\")) if Path('graphify-out/.graphify_old.json').exists() else None
|
||||
new_extract = json.loads(Path('graphify-out/.graphify_extract.json').read_text(encoding=\"utf-8\"))
|
||||
G_new = build_from_json(new_extract)
|
||||
|
||||
if old_data:
|
||||
|
||||
+303
-35
@@ -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,46 +505,89 @@ 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 and not no_change:
|
||||
try:
|
||||
from graphify.callflow_html import write_callflow_html
|
||||
for cf in callflow_files:
|
||||
write_callflow_html(
|
||||
graph=out / "graph.json",
|
||||
report=out / "GRAPH_REPORT.md",
|
||||
labels=out / ".graphify_labels.json",
|
||||
output=cf,
|
||||
verbose=False,
|
||||
)
|
||||
except Exception as cf_err:
|
||||
print(f"[graphify watch] callflow HTML update skipped: {cf_err}")
|
||||
|
||||
# clear stale needs_update flag if present
|
||||
flag = out / "needs_update"
|
||||
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"
|
||||
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.11"
|
||||
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" }
|
||||
|
||||
File renamed without changes.
@@ -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
|
||||
+23
-6
@@ -116,8 +116,9 @@ def test_missing_file_type_defaults_to_concept(capsys):
|
||||
assert G.nodes["n1"]["file_type"] == "concept"
|
||||
|
||||
|
||||
def test_real_invalid_file_type_still_warns(capsys):
|
||||
"""Truly invalid file_type values (not None, not empty) must still warn."""
|
||||
def test_real_invalid_file_type_coerced_to_concept():
|
||||
"""Unknown file_type values are coerced through the synonym mapper, falling
|
||||
back to 'concept' for anything that isn't a known LLM synonym (#840)."""
|
||||
ext = {
|
||||
"nodes": [
|
||||
{"id": "n1", "label": "Bad", "file_type": "weird_type", "source_file": "a.py"},
|
||||
@@ -126,10 +127,26 @@ def test_real_invalid_file_type_still_warns(capsys):
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}
|
||||
build_from_json(ext)
|
||||
err = capsys.readouterr().err
|
||||
assert "invalid file_type" in err
|
||||
assert "weird_type" in err
|
||||
G = build_from_json(ext)
|
||||
assert G.nodes["n1"]["file_type"] == "concept"
|
||||
|
||||
|
||||
def test_file_type_synonym_mapping():
|
||||
"""Known invalid file_type values map to their canonical equivalents."""
|
||||
ext = {
|
||||
"nodes": [
|
||||
{"id": "n1", "label": "MD", "file_type": "markdown", "source_file": "a.md"},
|
||||
{"id": "n2", "label": "Tool", "file_type": "tool", "source_file": "b.py"},
|
||||
{"id": "n3", "label": "Pat", "file_type": "pattern", "source_file": "c.md"},
|
||||
],
|
||||
"edges": [],
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}
|
||||
G = build_from_json(ext)
|
||||
assert G.nodes["n1"]["file_type"] == "document"
|
||||
assert G.nodes["n2"]["file_type"] == "code"
|
||||
assert G.nodes["n3"]["file_type"] == "concept"
|
||||
|
||||
|
||||
def test_build_merge_preserves_call_edge_direction(tmp_path):
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
from graphify.callflow_html import derive_sections_from_communities, write_callflow_html
|
||||
|
||||
|
||||
def _make_graphify_out(tmp_path: Path) -> Path:
|
||||
out = tmp_path / "graphify-out"
|
||||
out.mkdir()
|
||||
graph = {
|
||||
"directed": False,
|
||||
"multigraph": False,
|
||||
"graph": {},
|
||||
"nodes": [
|
||||
{"id": "api", "label": "ApiClient", "source_file": "src/api.py", "file_type": "code", "community": 0},
|
||||
{"id": "run", "label": "run()", "source_file": "src/main.py", "file_type": "code", "community": 0},
|
||||
{"id": "export", "label": "write_html()", "source_file": "src/export.py", "file_type": "code", "community": 1},
|
||||
{"id": "evil", "label": "<script>alert(1)</script>", "source_file": "src/evil.py", "file_type": "code", "community": 1},
|
||||
],
|
||||
"links": [
|
||||
{"source": "run", "target": "api", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
|
||||
{"source": "api", "target": "export", "relation": "uses", "confidence": "EXTRACTED", "confidence_score": 1.0},
|
||||
{"source": "export", "target": "evil", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
|
||||
],
|
||||
"hyperedges": [],
|
||||
"built_at_commit": "abcdef123456",
|
||||
}
|
||||
(out / "graph.json").write_text(json.dumps(graph), encoding="utf-8")
|
||||
(out / ".graphify_labels.json").write_text(
|
||||
json.dumps({"0": "Runtime", "1": "Export"}),
|
||||
encoding="utf-8",
|
||||
)
|
||||
(out / "GRAPH_REPORT.md").write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"# Graph Report - sample",
|
||||
"",
|
||||
"## Summary",
|
||||
"- 3 nodes · 2 edges · 1 communities detected",
|
||||
"",
|
||||
"## God Nodes (most connected - your core abstractions)",
|
||||
"1. `Transformer` - 2 edges",
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
return out
|
||||
|
||||
|
||||
def test_write_callflow_html_creates_file_and_uses_report(tmp_path):
|
||||
out = _make_graphify_out(tmp_path)
|
||||
|
||||
html_path = write_callflow_html(
|
||||
tmp_path,
|
||||
output="graphify-out/callflow.html",
|
||||
max_sections=4,
|
||||
)
|
||||
|
||||
assert html_path == out / "callflow.html"
|
||||
content = html_path.read_text(encoding="utf-8")
|
||||
assert "mermaid" in content
|
||||
assert "Graph Report Highlights" in content
|
||||
assert "Transformer" in content
|
||||
assert "ApiClient" in content
|
||||
assert "<script>alert(1)</script>" in content
|
||||
assert "<script>alert(1)</script>" not in content
|
||||
|
||||
|
||||
def test_export_callflow_html_cli_creates_file(tmp_path):
|
||||
_make_graphify_out(tmp_path)
|
||||
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"graphify",
|
||||
"export",
|
||||
"callflow-html",
|
||||
"--output",
|
||||
"graphify-out/from-cli.html",
|
||||
"--max-sections",
|
||||
"4",
|
||||
],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
html_path = tmp_path / "graphify-out" / "from-cli.html"
|
||||
assert html_path.exists()
|
||||
assert "callflow HTML written" in result.stdout
|
||||
|
||||
|
||||
def test_export_callflow_html_cli_accepts_positional_graph_path(tmp_path):
|
||||
_make_graphify_out(tmp_path)
|
||||
external_out = tmp_path / "GitNexus" / "graphify-out"
|
||||
external_out.mkdir(parents=True)
|
||||
graph = {
|
||||
"directed": False,
|
||||
"multigraph": False,
|
||||
"graph": {},
|
||||
"nodes": [
|
||||
{"id": "external", "label": "ExternalOnly", "source_file": "src/external.py", "file_type": "code", "community": 0},
|
||||
{"id": "writer", "label": "write_external()", "source_file": "src/writer.py", "file_type": "code", "community": 1},
|
||||
],
|
||||
"links": [
|
||||
{"source": "external", "target": "writer", "relation": "calls", "confidence": "EXTRACTED", "confidence_score": 1.0},
|
||||
],
|
||||
"hyperedges": [],
|
||||
}
|
||||
(external_out / "graph.json").write_text(json.dumps(graph), encoding="utf-8")
|
||||
(external_out / ".graphify_labels.json").write_text(json.dumps({"0": "External Runtime", "1": "External Export"}), encoding="utf-8")
|
||||
(external_out / "GRAPH_REPORT.md").write_text(
|
||||
"\n".join(
|
||||
[
|
||||
"# Graph Report - external",
|
||||
"",
|
||||
"## Summary",
|
||||
"- 2 nodes · 1 edges · 2 communities detected",
|
||||
"",
|
||||
"## God Nodes (most connected - your core abstractions)",
|
||||
"1. `ExternalGod` - 1 edges",
|
||||
]
|
||||
),
|
||||
encoding="utf-8",
|
||||
)
|
||||
|
||||
result = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
"-m",
|
||||
"graphify",
|
||||
"export",
|
||||
"callflow-html",
|
||||
str(external_out / "graph.json"),
|
||||
"--output",
|
||||
"positional.html",
|
||||
"--max-sections",
|
||||
"4",
|
||||
],
|
||||
cwd=tmp_path,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
assert result.returncode == 0, result.stderr
|
||||
html = (tmp_path / "positional.html").read_text(encoding="utf-8")
|
||||
assert "ExternalOnly" in html
|
||||
assert "ExternalGod" in html
|
||||
assert "ApiClient" not in html
|
||||
assert "Transformer" not in html
|
||||
|
||||
|
||||
def test_derive_sections_groups_by_architecture_keywords():
|
||||
nodes = [
|
||||
{"id": "extract_py", "label": "extract_python", "source_file": "graphify/extract.py", "community": 0},
|
||||
{"id": "extract_js", "label": "extract_js", "source_file": "graphify/extract.py", "community": 0},
|
||||
{"id": "to_html", "label": "to_html", "source_file": "graphify/export.py", "community": 1},
|
||||
{"id": "test_html", "label": "test_export_html", "source_file": "tests/test_export.py", "community": 2},
|
||||
]
|
||||
|
||||
sections = derive_sections_from_communities(nodes, {}, "en", 6)
|
||||
ids = {section["id"] for section in sections}
|
||||
|
||||
assert "extract-pipeline" in ids
|
||||
assert "outputs-docs" in ids
|
||||
assert "tests-fixtures" in ids
|
||||
@@ -0,0 +1,117 @@
|
||||
"""Tests for the `claude-cli` backend (#855/#856).
|
||||
|
||||
Mocks subprocess.run + shutil.which so the suite runs on CI without
|
||||
the `claude` binary or a live network call.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from unittest.mock import MagicMock, patch
|
||||
|
||||
import pytest
|
||||
|
||||
from graphify import llm
|
||||
|
||||
_ENVELOPE = {
|
||||
"type": "result",
|
||||
"subtype": "success",
|
||||
"is_error": False,
|
||||
"result": json.dumps({
|
||||
"nodes": [
|
||||
{"id": "foo_module", "label": "Foo", "file_type": "document", "source_file": "foo.md"},
|
||||
{"id": "foo_greet", "label": "greet", "file_type": "code", "source_file": "foo.md"},
|
||||
],
|
||||
"edges": [
|
||||
{"source": "foo_module", "target": "foo_greet",
|
||||
"relation": "references", "confidence": "EXTRACTED", "confidence_score": 1.0},
|
||||
],
|
||||
"hyperedges": [],
|
||||
"input_tokens": 0,
|
||||
"output_tokens": 0,
|
||||
}),
|
||||
"stop_reason": "end_turn",
|
||||
"usage": {
|
||||
"input_tokens": 6,
|
||||
"output_tokens": 11,
|
||||
"cache_read_input_tokens": 17837,
|
||||
"cache_creation_input_tokens": 30800,
|
||||
},
|
||||
"modelUsage": {"claude-opus-4-7[1m]": {"inputTokens": 6, "outputTokens": 11}},
|
||||
}
|
||||
|
||||
|
||||
@pytest.fixture
|
||||
def fake_claude(monkeypatch):
|
||||
completed = MagicMock(returncode=0, stdout=json.dumps(_ENVELOPE), stderr="")
|
||||
monkeypatch.setattr(llm, "_response_is_hollow", lambda raw, parsed: False)
|
||||
with patch("shutil.which", return_value="/fake/bin/claude"), \
|
||||
patch("subprocess.run", return_value=completed) as run:
|
||||
yield run
|
||||
|
||||
|
||||
def test_returns_parsed_nodes_and_edges(fake_claude):
|
||||
result = llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
assert len(result["nodes"]) == 2
|
||||
assert len(result["edges"]) == 1
|
||||
|
||||
|
||||
def test_token_accounting_includes_cache(fake_claude):
|
||||
result = llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
assert result["input_tokens"] == 6 + 17837 + 30800
|
||||
assert result["output_tokens"] == 11
|
||||
assert result["model"] == "claude-opus-4-7[1m]"
|
||||
assert result["finish_reason"] == "stop"
|
||||
|
||||
|
||||
def test_finish_reason_length_on_max_tokens(monkeypatch):
|
||||
envelope = dict(_ENVELOPE, stop_reason="max_tokens")
|
||||
completed = MagicMock(returncode=0, stdout=json.dumps(envelope), stderr="")
|
||||
monkeypatch.setattr(llm, "_response_is_hollow", lambda raw, parsed: False)
|
||||
with patch("shutil.which", return_value="/fake/bin/claude"), \
|
||||
patch("subprocess.run", return_value=completed):
|
||||
result = llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
assert result["finish_reason"] == "length"
|
||||
|
||||
|
||||
def test_raises_when_cli_missing():
|
||||
with patch("shutil.which", return_value=None):
|
||||
with pytest.raises(RuntimeError, match="Claude Code CLI not found"):
|
||||
llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
|
||||
|
||||
def test_raises_on_nonzero_exit():
|
||||
completed = MagicMock(returncode=2, stdout="", stderr="auth failed")
|
||||
with patch("shutil.which", return_value="/fake/bin/claude"), \
|
||||
patch("subprocess.run", return_value=completed):
|
||||
with pytest.raises(RuntimeError, match="exited 2"):
|
||||
llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
|
||||
|
||||
def test_raises_on_garbage_envelope():
|
||||
completed = MagicMock(returncode=0, stdout="not json", stderr="")
|
||||
with patch("shutil.which", return_value="/fake/bin/claude"), \
|
||||
patch("subprocess.run", return_value=completed):
|
||||
with pytest.raises(RuntimeError, match="unparseable JSON envelope"):
|
||||
llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
|
||||
|
||||
def test_extract_files_direct_dispatches_to_claude_cli(tmp_path, fake_claude):
|
||||
f = tmp_path / "foo.md"
|
||||
f.write_text("# Foo\n\nThe greet() helper formats a name.\n")
|
||||
result = llm.extract_files_direct(files=[f], backend="claude-cli", root=tmp_path)
|
||||
assert fake_claude.called
|
||||
assert len(result["nodes"]) == 2
|
||||
|
||||
|
||||
def test_backend_registered_with_zero_cost():
|
||||
assert "claude-cli" in llm.BACKENDS
|
||||
pricing = llm.BACKENDS["claude-cli"]["pricing"]
|
||||
assert pricing["input"] == 0.0
|
||||
assert pricing["output"] == 0.0
|
||||
assert llm.estimate_cost("claude-cli", 1_000_000, 1_000_000) == 0.0
|
||||
|
||||
|
||||
def test_no_session_persistence_flag_in_subprocess(fake_claude):
|
||||
llm._call_claude_cli("dummy", max_tokens=8192)
|
||||
call_args = fake_claude.call_args[0][0]
|
||||
assert "--no-session-persistence" in call_args
|
||||
@@ -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)
|
||||
@@ -0,0 +1,56 @@
|
||||
"""Regression tests for `graphify explain` arrow direction (#853)."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import graphify.__main__ as mainmod
|
||||
|
||||
|
||||
def _write_graph(tmp_path):
|
||||
graph_data = {
|
||||
"directed": False, "multigraph": False, "graph": {},
|
||||
"nodes": [
|
||||
{"id": "validate", "label": "validateSanitySession()",
|
||||
"source_file": "server/sanity-validate-session.ts", "community": 0},
|
||||
{"id": "create_patch", "label": "createPatchHandler()",
|
||||
"source_file": "server/create-patch-handler.ts", "community": 0},
|
||||
{"id": "create_edit", "label": "createEditHandler()",
|
||||
"source_file": "server/create-edit-handler.ts", "community": 0},
|
||||
{"id": "stable_stringify", "label": "stableStringify()",
|
||||
"source_file": "shared/stringify.ts", "community": 0},
|
||||
],
|
||||
"links": [
|
||||
{"source": "create_patch", "target": "validate",
|
||||
"relation": "calls", "confidence": "EXTRACTED"},
|
||||
{"source": "create_edit", "target": "validate",
|
||||
"relation": "calls", "confidence": "EXTRACTED"},
|
||||
{"source": "validate", "target": "stable_stringify",
|
||||
"relation": "calls", "confidence": "EXTRACTED"},
|
||||
],
|
||||
}
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(graph_data))
|
||||
return p
|
||||
|
||||
|
||||
def _run(monkeypatch, graph_path, label, capsys):
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(mainmod.sys, "argv",
|
||||
["graphify", "explain", label, "--graph", str(graph_path)])
|
||||
mainmod.main()
|
||||
return capsys.readouterr().out
|
||||
|
||||
|
||||
def test_callee_shows_callers_as_inbound(monkeypatch, tmp_path, capsys):
|
||||
p = _write_graph(tmp_path)
|
||||
out = _run(monkeypatch, p, "validateSanitySession", capsys)
|
||||
assert "<-- createPatchHandler() [calls]" in out
|
||||
assert "<-- createEditHandler() [calls]" in out
|
||||
assert "--> stableStringify() [calls]" in out
|
||||
assert "--> createPatchHandler() [calls]" not in out
|
||||
assert "--> createEditHandler() [calls]" not in out
|
||||
|
||||
|
||||
def test_caller_shows_callee_as_outbound(monkeypatch, tmp_path, capsys):
|
||||
p = _write_graph(tmp_path)
|
||||
out = _run(monkeypatch, p, "createPatchHandler", capsys)
|
||||
assert "--> validateSanitySession() [calls]" in out
|
||||
assert "<-- " not in out
|
||||
@@ -784,7 +784,7 @@ def test_fortran_no_dangling_edges():
|
||||
|
||||
|
||||
def test_fortran_capital_F_parses_preprocessed():
|
||||
r = extract_fortran(FIXTURES / "sample.F90")
|
||||
r = extract_fortran(FIXTURES / "sample_preprocessed.F90")
|
||||
assert "error" not in r
|
||||
labels = [n["label"] for n in r["nodes"]]
|
||||
assert "shapes" in labels
|
||||
|
||||
@@ -325,6 +325,159 @@ def test_call_openai_compat_preserves_real_finish_reason(monkeypatch):
|
||||
assert result["nodes"] == [{"id": "a"}]
|
||||
|
||||
|
||||
# ---------------------------------------------------------------------------
|
||||
# Ollama context-window fix (#798): num_ctx + keep_alive in extra_body,
|
||||
# serial execution by default.
|
||||
# ---------------------------------------------------------------------------
|
||||
|
||||
|
||||
def _install_capturing_openai(monkeypatch):
|
||||
"""Like _install_fake_openai but records kwargs passed to create()."""
|
||||
import sys
|
||||
import types
|
||||
|
||||
captured = {}
|
||||
|
||||
class _FakeOpenAI:
|
||||
def __init__(self, *_, **__):
|
||||
self.chat = self
|
||||
self.completions = self
|
||||
|
||||
def create(self, **kwargs):
|
||||
captured.update(kwargs)
|
||||
return _fake_openai_response(
|
||||
'{"nodes":[{"id":"x"}],"edges":[],"hyperedges":[]}',
|
||||
finish_reason="stop",
|
||||
completion_tokens=100,
|
||||
)
|
||||
|
||||
fake_module = types.ModuleType("openai")
|
||||
fake_module.OpenAI = _FakeOpenAI
|
||||
monkeypatch.setitem(sys.modules, "openai", fake_module)
|
||||
return captured
|
||||
|
||||
|
||||
def test_ollama_extra_body_sets_num_ctx_and_keep_alive(monkeypatch):
|
||||
captured = _install_capturing_openai(monkeypatch)
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
|
||||
|
||||
llm._call_openai_compat(
|
||||
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
|
||||
"user msg", temperature=0, max_completion_tokens=8192, backend="ollama",
|
||||
)
|
||||
|
||||
assert "extra_body" in captured, "extra_body must be sent to Ollama"
|
||||
eb = captured["extra_body"]
|
||||
# num_ctx is now dynamic: derived from message size, not hardcoded 131072
|
||||
assert "num_ctx" in eb.get("options", {}), "num_ctx must be present"
|
||||
assert eb["options"]["num_ctx"] >= 8192, "num_ctx must be at least the floor value"
|
||||
assert eb.get("keep_alive") == "30m", "default keep_alive must be 30m"
|
||||
|
||||
|
||||
def test_ollama_num_ctx_scales_with_small_token_budget(monkeypatch):
|
||||
# Regression for #798 follow-up: with --token-budget 8192, the old hardcoded
|
||||
# 131072 forced Ollama to allocate 128k KV-cache slots on a 31B model, causing
|
||||
# VRAM exhaustion by chunk 4. num_ctx must now reflect actual chunk size.
|
||||
captured = _install_capturing_openai(monkeypatch)
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_NUM_CTX", raising=False)
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
|
||||
|
||||
# Simulate an 8k-token chunk: ~32k chars of content
|
||||
small_chunk_msg = "x" * 32_000
|
||||
|
||||
llm._call_openai_compat(
|
||||
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
|
||||
small_chunk_msg, temperature=0, max_completion_tokens=16384, backend="ollama",
|
||||
)
|
||||
|
||||
num_ctx = captured["extra_body"]["options"]["num_ctx"]
|
||||
# Should be far less than 131072 for an 8k input — VRAM-friendly
|
||||
assert num_ctx < 131072, (
|
||||
f"num_ctx={num_ctx} is too large for a small chunk; "
|
||||
"this wastes VRAM and causes OOM on large models (#798)"
|
||||
)
|
||||
# But still large enough to fit input + output
|
||||
assert num_ctx >= 8192, "num_ctx must cover at least the output cap"
|
||||
|
||||
|
||||
def test_ollama_num_ctx_env_override(monkeypatch):
|
||||
captured = _install_capturing_openai(monkeypatch)
|
||||
monkeypatch.setenv("GRAPHIFY_OLLAMA_NUM_CTX", "65536")
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_KEEP_ALIVE", raising=False)
|
||||
|
||||
llm._call_openai_compat(
|
||||
"http://localhost:11434/v1", "ollama", "qwen2.5-coder:7b",
|
||||
"u", temperature=0, max_completion_tokens=8192, backend="ollama",
|
||||
)
|
||||
|
||||
assert captured["extra_body"]["options"]["num_ctx"] == 65536
|
||||
|
||||
|
||||
def test_non_ollama_backend_gets_no_num_ctx_extra_body(monkeypatch):
|
||||
captured = _install_capturing_openai(monkeypatch)
|
||||
|
||||
llm._call_openai_compat(
|
||||
"https://api.openai.com/v1", "sk-test", "gpt-4.1-mini",
|
||||
"u", temperature=0, max_completion_tokens=8192, backend="openai",
|
||||
)
|
||||
|
||||
eb = captured.get("extra_body")
|
||||
assert eb is None or "options" not in eb, "non-ollama backends must not get num_ctx injection"
|
||||
|
||||
|
||||
def test_extract_corpus_parallel_ollama_runs_serially(tmp_path, monkeypatch):
|
||||
# With 3 chunks and backend=ollama, ThreadPoolExecutor must NOT be used
|
||||
# (workers=1 takes the sequential path). We verify by ensuring all chunks
|
||||
# are processed and no pool is spun up.
|
||||
files = [tmp_path / f"f{i}.md" for i in range(6)]
|
||||
for f in files:
|
||||
f.write_text("hello")
|
||||
|
||||
call_order = []
|
||||
|
||||
def fake_extract(chunk, *_, **__):
|
||||
call_order.append(len(chunk))
|
||||
return _ok(nodes=[{"id": f.stem} for f in chunk])
|
||||
|
||||
monkeypatch.delenv("GRAPHIFY_OLLAMA_PARALLEL", raising=False)
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", side_effect=fake_extract):
|
||||
with patch("graphify.llm.ThreadPoolExecutor") as mock_pool:
|
||||
result = llm.extract_corpus_parallel(
|
||||
files, backend="ollama", api_key="ollama", model="qwen2.5-coder:7b",
|
||||
root=tmp_path, token_budget=None, chunk_size=2, max_concurrency=4,
|
||||
)
|
||||
|
||||
mock_pool.assert_not_called()
|
||||
assert len(result["nodes"]) == 6
|
||||
|
||||
|
||||
def test_extract_corpus_parallel_ollama_parallel_env_restores_concurrency(tmp_path, monkeypatch):
|
||||
files = [tmp_path / f"f{i}.md" for i in range(4)]
|
||||
for f in files:
|
||||
f.write_text("hello")
|
||||
|
||||
monkeypatch.setenv("GRAPHIFY_OLLAMA_PARALLEL", "1")
|
||||
|
||||
with patch("graphify.llm.extract_files_direct", return_value=_ok()):
|
||||
with patch("graphify.llm.ThreadPoolExecutor") as mock_pool:
|
||||
mock_pool.return_value.__enter__ = lambda s: s
|
||||
mock_pool.return_value.__exit__ = lambda s, *a: False
|
||||
mock_pool.return_value.submit = lambda fn, *a, **kw: type(
|
||||
"F", (), {"result": lambda self: fn(*a, **kw)}
|
||||
)()
|
||||
try:
|
||||
llm.extract_corpus_parallel(
|
||||
files, backend="ollama", api_key="ollama", model="m",
|
||||
root=tmp_path, token_budget=None, chunk_size=2, max_concurrency=4,
|
||||
)
|
||||
except Exception:
|
||||
pass # mock scaffolding may not be complete; we only care about the call
|
||||
|
||||
mock_pool.assert_called()
|
||||
|
||||
|
||||
def test_adaptive_retry_bisects_on_hollow_ollama_response(tmp_path):
|
||||
# End-to-end: an overwhelmed Ollama returns hollow on the full 4-file
|
||||
# chunk; halves succeed. The bug being fixed is that pre-fix this
|
||||
|
||||
@@ -0,0 +1,48 @@
|
||||
"""Regression tests for `graphify path` arrow direction (#849)."""
|
||||
from __future__ import annotations
|
||||
import json
|
||||
import networkx as nx
|
||||
from networkx.readwrite import json_graph
|
||||
import graphify.__main__ as mainmod
|
||||
|
||||
|
||||
def _write_graph(tmp_path):
|
||||
graph_data = {
|
||||
"directed": False, "multigraph": False, "graph": {},
|
||||
"nodes": [
|
||||
{"id": "create_patch", "label": "createPatchHandler()",
|
||||
"source_file": "server/create-patch-handler.ts", "community": 0},
|
||||
{"id": "validate", "label": "validateSanitySession()",
|
||||
"source_file": "server/sanity-validate-session.ts", "community": 0},
|
||||
],
|
||||
"links": [
|
||||
{"source": "create_patch", "target": "validate",
|
||||
"relation": "calls", "confidence": "EXTRACTED"},
|
||||
],
|
||||
}
|
||||
p = tmp_path / "graph.json"
|
||||
p.write_text(json.dumps(graph_data))
|
||||
return p
|
||||
|
||||
|
||||
def _run(monkeypatch, graph_path, src, tgt, capsys):
|
||||
monkeypatch.setattr(mainmod, "_check_skill_version", lambda _: None)
|
||||
monkeypatch.setattr(mainmod.sys, "argv",
|
||||
["graphify", "path", src, tgt, "--graph", str(graph_path)])
|
||||
mainmod.main()
|
||||
return capsys.readouterr().out
|
||||
|
||||
|
||||
def test_forward_arrow(monkeypatch, tmp_path, capsys):
|
||||
p = _write_graph(tmp_path)
|
||||
out = _run(monkeypatch, p, "createPatchHandler", "validateSanitySession", capsys)
|
||||
assert "Shortest path (1 hops):" in out
|
||||
assert "createPatchHandler() --calls [EXTRACTED]--> validateSanitySession()" in out
|
||||
|
||||
|
||||
def test_reverse_arrow(monkeypatch, tmp_path, capsys):
|
||||
p = _write_graph(tmp_path)
|
||||
out = _run(monkeypatch, p, "validateSanitySession", "createPatchHandler", capsys)
|
||||
assert "Shortest path (1 hops):" in out
|
||||
assert "validateSanitySession() <--calls [EXTRACTED]-- createPatchHandler()" in out
|
||||
assert "validateSanitySession() --calls [EXTRACTED]--> createPatchHandler()" not in out
|
||||
+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